From bc67a45673f5bb9ca1d646e54b615f493de62a7e Mon Sep 17 00:00:00 2001 From: mununki Date: Sun, 29 Nov 2026 04:50:14 +0900 Subject: [PATCH 1/4] Emit source map mappings for pattern-match arms, branch tests, and block boundaries Why: Pattern-match arms and `if` branches returning a constant or variable (`| Empty => "empty"`, `| None => -1`, `| _ => x`) emitted no source map mapping, because `Lambda.t` carried `Location.t` only on `Lprim`, `Lapply`, and `Lfunction`. Branch dispatch tests (`typeof s !== "object"`, `o === undefined`, `switch (s.TAG)`) and shared destructuring (`Primitive_option.valFromOption(o)`) either had no mapping or borrowed a sibling arm's location, and block/function closing braces had no end mappings, causing V8 coverage tools (`c8` / `v8-to-istanbul`) to drop unexecuted ranges and report unexecuted arms as covered (#9387). SourceMap modified (pattern-match arms and dispatch tests): Example: let opt = o => switch o { | Some(Some(x)) => x + 1 | Some(None) => 0 | None => -1 } Before (text): function opt(o) { @0 -> 1:10 o => if (o === undefined) { @6 -> 3:4 Some(Some(x)) => x + 1 return -1; (none) } (none) let x = Primitive_option.valFromOption(o); @10 -> 4:4 Some(None) => 0 if (x !== undefined) { @6 -> 3:9 Some(x)) => x + 1 return x + 1 | 0; @11 -> 3:21 x + 1 } else { (none) return 0; (none) } (none) } (none) After (text): function opt(o) { @0 -> 1:10 o => if (o === undefined) { @2 -> 2:2 switch o { return -1; @4 -> 5:13 -1 } @2 -> 5:14 (end) let x = Primitive_option.valFromOption(o); @2 -> 2:2 switch o { if (x !== undefined) { @2 -> 2:2 switch o { return x + 1 | 0; @4 -> 3:21 x + 1 } else { @2 -> 3:26 (end) @3 -> 4:18 0 return 0; @4 -> 4:18 0 } @2 -> 4:19 (end) } @0 -> 6:3 (end) Review: Does attaching locations to Lambda branch nodes change optimizations or generated JS? No. Leaf nodes (`Lconst`, `Lvar`) are untouched, and `Lambda_traverse.make_key` and `Lambda.eq_approx` ignore all branch and node locations. Generated JS is byte-identical with source maps enabled or disabled (apart from the `sourceMappingURL` comment). Review: How are non-1:1 arm optimizations (merged, split, or reordered branches) handled? Shared destructuring (`relocate_cell_args`) and dispatch tests map to the enclosing `switch`/`if` rather than a sibling arm. Fallthrough `case` labels keep each arm's `pat_loc`, inlined static exits (`Lam_pass_exits`) propagate `branch_loc` to every inlined site, and same-switch nested dispatch blocks (`if (typeof s !== "object")`) map `{` and `}` to `switch` start so interleaved executed arms are never marked uncovered. Fixes #9387 Signed-off-by: mununki --- .../sourcemap-pattern-match-branches.fix.md | 1 + compiler/backend/ext_pp.mli | 2 + compiler/backend/js_dump.ml | 239 ++++++- compiler/backend/js_exp_make.ml | 18 +- compiler/backend/js_exp_make.mli | 2 +- compiler/backend/js_pass_flatten.ml | 26 +- compiler/backend/js_source_map.ml | 31 +- compiler/backend/js_source_map.mli | 2 + compiler/backend/js_stmt_make.ml | 76 +- compiler/backend/js_stmt_make.mli | 3 + compiler/backend/lam_analysis.ml | 8 +- compiler/backend/lam_arity_analysis.ml | 19 +- compiler/backend/lam_beta_reduce.ml | 2 +- compiler/backend/lam_bounded_vars.ml | 44 +- compiler/backend/lam_check.ml | 32 +- compiler/backend/lam_closure.ml | 16 +- compiler/backend/lam_compile.ml | 433 ++++++++---- compiler/backend/lam_compile_context.ml | 17 +- compiler/backend/lam_compile_context.mli | 12 +- compiler/backend/lam_exit_count.ml | 16 +- compiler/backend/lam_hit.ml | 44 +- compiler/backend/lam_pass_collect.ml | 16 +- compiler/backend/lam_pass_count.ml | 16 +- compiler/backend/lam_pass_exits.ml | 148 +++- compiler/backend/lam_pass_guard_raises.ml | 5 +- compiler/backend/lam_pass_remove_alias.ml | 33 +- compiler/typing/lambda.ml | 98 ++- compiler/typing/lambda.mli | 44 +- compiler/typing/lambda_effects.ml | 4 +- compiler/typing/lambda_exits.ml | 4 +- compiler/typing/lambda_exits.mli | 3 +- compiler/typing/lambda_scc.ml | 21 +- compiler/typing/lambda_traverse.ml | 76 +- compiler/typing/matching.ml | 531 ++++++++------ compiler/typing/matching.mli | 11 +- compiler/typing/polyvar_pattern_match.ml | 52 +- compiler/typing/printlambda.ml | 16 +- compiler/typing/switch.ml | 152 ++-- compiler/typing/switch.mli | 5 +- compiler/typing/translcore.ml | 47 +- tests/ounit_tests/ounit_exits_tests.ml | 76 ++ .../ounit_lam_bounded_vars_tests.ml | 14 +- .../ounit_lambda_constant_tests.ml | 8 +- .../ounit_lambda_traverse_tests.ml | 81 ++- tests/project_tests/source_map/input.js | 648 +++++++++++++++++- .../project_tests/source_map/src/Branches.res | 131 ++++ 46 files changed, 2463 insertions(+), 820 deletions(-) create mode 100644 changes/sourcemap-pattern-match-branches.fix.md create mode 100644 tests/project_tests/source_map/src/Branches.res diff --git a/changes/sourcemap-pattern-match-branches.fix.md b/changes/sourcemap-pattern-match-branches.fix.md new file mode 100644 index 00000000000..93df84cd841 --- /dev/null +++ b/changes/sourcemap-pattern-match-branches.fix.md @@ -0,0 +1 @@ +- Emit accurate source map mappings for pattern-match arms, branch dispatch tests, `if`/`else` expressions, and block boundaries, fixing missing mappings for constant- and variable-returning arms and improving coverage reporting through source maps. diff --git a/compiler/backend/ext_pp.mli b/compiler/backend/ext_pp.mli index e5c94c946ce..c9b9dcb7c5a 100644 --- a/compiler/backend/ext_pp.mli +++ b/compiler/backend/ext_pp.mli @@ -75,6 +75,8 @@ val in_operator_forbidden : t -> bool val newline : t -> unit +val force_newline : t -> unit + val at_least_two_lines : t -> unit val from_channel : ?track_positions:bool -> out_channel -> t diff --git a/compiler/backend/js_dump.ml b/compiler/backend/js_dump.ml index 2c6590ff0d0..fe5eb1c0a4c 100644 --- a/compiler/backend/js_dump.ml +++ b/compiler/backend/js_dump.ml @@ -397,6 +397,155 @@ type fn_exp_state = let default_fn_exp_state = No_name {single_arg = false} +let rec stmt_first_arm_loc (s : J.statement) : Location.t option = + match s.statement_desc with + | Block b -> block_first_arm_loc b + | If (_, s1, s2) -> ( + match s.source_loc with + | Some _ as loc -> loc + | None -> ( + match block_first_arm_loc s1 with + | Some _ as loc -> loc + | None -> block_first_arm_loc s2)) + | Int_switch (_, cc, def) -> ( + match first_case_loc cc with + | Some _ as loc -> loc + | None -> ( + match def with + | Some b -> block_first_arm_loc b + | None -> s.source_loc)) + | String_switch (_, cc, def) -> ( + match first_case_loc cc with + | Some _ as loc -> loc + | None -> ( + match def with + | Some b -> block_first_arm_loc b + | None -> s.source_loc)) + | Return e | Exp e | Throw e -> ( + match s.source_loc with + | Some _ as loc -> loc + | None -> e.source_loc) + | Variable {value = Some e} -> ( + match s.source_loc with + | Some _ as loc -> loc + | None -> e.source_loc) + | _ -> s.source_loc + +and first_case_loc : 'a. ('a * J.case_clause) list -> Location.t option = + function + | [] -> None + | (_, {source_loc; switch_body}) :: rest -> ( + match source_loc with + | Some _ as loc -> loc + | None -> ( + match block_first_arm_loc switch_body with + | Some _ as loc -> loc + | None -> first_case_loc rest)) + +and block_first_arm_loc (b : J.block) : Location.t option = + match b with + | [] -> None + | s :: rest -> ( + match stmt_first_arm_loc s with + | Some _ as loc -> loc + | None -> block_first_arm_loc rest) + +let rec stmt_last_arm_loc (s : J.statement) : Location.t option = + match s.statement_desc with + | Block b -> block_last_arm_loc b + | If (_, s1, s2) -> ( + match block_last_arm_loc s2 with + | Some _ as loc -> loc + | None -> ( + match block_last_arm_loc s1 with + | Some _ as loc -> loc + | None -> s.source_loc)) + | Int_switch (_, cc, def) -> ( + match def with + | Some b -> ( + match block_last_arm_loc b with + | Some _ as loc -> loc + | None -> last_case_loc cc s.source_loc) + | None -> last_case_loc cc s.source_loc) + | String_switch (_, cc, def) -> ( + match def with + | Some b -> ( + match block_last_arm_loc b with + | Some _ as loc -> loc + | None -> last_case_loc cc s.source_loc) + | None -> last_case_loc cc s.source_loc) + | Return e | Exp e | Throw e -> ( + match s.source_loc with + | Some _ as loc -> loc + | None -> e.source_loc) + | Variable {value = Some e} -> ( + match s.source_loc with + | Some _ as loc -> loc + | None -> e.source_loc) + | _ -> s.source_loc + +and last_case_loc : + 'a. ('a * J.case_clause) list -> Location.t option -> Location.t option = + fun cc fallback -> + let rec loop = function + | [] -> fallback + | (_, ({source_loc; switch_body} : J.case_clause)) :: rest -> ( + match block_last_arm_loc switch_body with + | Some _ as loc -> loc + | None -> ( + match source_loc with + | Some _ as loc -> loc + | None -> loop rest)) + in + loop (List.rev cc) + +and block_last_arm_loc (b : J.block) : Location.t option = + let rec loop = function + | [] -> None + | s :: rest -> ( + match stmt_last_arm_loc s with + | Some _ as loc -> loc + | None -> loop rest) + in + loop (List.rev b) + +let ensure_ordered_locs start_loc end_loc = + match (start_loc, end_loc) with + | Some s, Some e + when s.Location.loc_start.pos_cnum > e.Location.loc_end.pos_cnum -> + (Some s, Some s) + | _ -> (start_loc, end_loc) + +let rec is_same_dispatch_block (outer_loc : Location.t option) (b : J.block) = + match (outer_loc, b) with + | Some _, [{statement_desc = Block b}] -> is_same_dispatch_block outer_loc b + | ( Some outer, + [ + { + statement_desc = If _ | Int_switch _ | String_switch _; + source_loc = Some inner; + }; + ] ) -> + outer = inner + | _ -> false + +let brace_vgroup_mapped f ?start_loc ?end_loc ?(end_at_start = false) n action = + Option.iter (fun loc -> Js_source_map.mark_source_loc f (Some loc)) start_loc; + P.string f "{"; + let v = + P.vgroup f n (fun _ -> + P.newline f; + action ()) + in + P.force_newline f; + Option.iter + (fun loc -> + if end_at_start then Js_source_map.mark_source_loc f (Some loc) + else Js_source_map.mark_source_loc_end f (Some loc)) + end_loc; + P.string f "}"; + v + (* TODO: refactoring Note that {!pp_function} could print both statement and expression when [No_name] is given @@ -404,7 +553,7 @@ let default_fn_exp_state = No_name {single_arg = false} name it is printed as when it only calls that name. *) let rec pp_function ~return_unit ~async ~is_method ?directive ?(paren = false) - cxt (f : P.t) ~fn_state (l : Ident.t list) (b : J.block) + ?source_loc cxt (f : P.t) ~fn_state (l : Ident.t list) (b : J.block) (env : Js_fun_env.t) : cxt = match b with | [ @@ -474,7 +623,7 @@ let rec pp_function ~return_unit ~async ~is_method ?directive ?(paren = false) formal_parameter_list inner_cxt f arguments) in P.space f; - P.brace_vgroup f 1 (fun _ -> + brace_vgroup_mapped f ?end_loc:source_loc 1 (fun _ -> (* A directive must be the first statement of the body, so it comes before [let self = this] *) print_directive f directive; @@ -498,13 +647,14 @@ let rec pp_function ~return_unit ~async ~is_method ?directive ?(paren = false) | [{statement_desc = Return {expression_desc = Undefined _}}] when arrow -> P.string f "{"; + Js_source_map.mark_source_loc_end f source_loc; P.string f "}" | ([{statement_desc = Return e}] | [{statement_desc = Exp e}]) when arrow && directive == None -> (if exp_need_paren ~arrow e then P.paren_group f 0 else P.group f 0) (fun _ -> ignore (expression ~level:0 cxt f e)) | _ -> - P.brace_vgroup f 1 (fun _ -> + brace_vgroup_mapped f ?end_loc:source_loc 1 (fun _ -> function_body ?directive ~return_unit cxt f b) in let enclose () = @@ -545,10 +695,10 @@ and pp_one_case_clause : let cxt = P.group f 1 (fun _ -> P.group f 0 (fun _ -> + Js_source_map.mark_source_loc f source_loc; P.string f L.case; P.space f; pp_comment_option f comment; - Js_source_map.mark_source_loc f source_loc; pp_cond f switch_case; (* could be integer or string *) P.space f; @@ -563,6 +713,12 @@ and pp_one_case_clause : in if should_break then ( P.newline f; + let break_loc = + match block_last_arm_loc switch_body with + | Some _ as loc -> loc + | None -> source_loc + in + Js_source_map.mark_source_loc_end f break_loc; P.string f L.break; semi f); cxt)) @@ -594,7 +750,7 @@ and vident cxt f (v : J.vident) = and expression ~level:l cxt f (exp : J.expression) : cxt = pp_comment_option f exp.comment; Js_source_map.mark_source_loc f exp.source_loc; - expression_desc cxt ~level:l f exp.expression_desc + expression_desc ?source_loc:exp.source_loc cxt ~level:l f exp.expression_desc (* The operand of a prefix operator. [**] has the same level as the prefix operators, but JavaScript rejects [-a ** b], so it needs parentheses. An @@ -629,7 +785,7 @@ and int32_operand ~level cxt f (e : J.expression) : cxt = unary_operand cxt f operand) | _ -> expression ~level cxt f e -and expression_desc cxt ~(level : int) f x : cxt = +and expression_desc ?source_loc cxt ~(level : int) f x : cxt = match x with | Null -> P.string f L.null; @@ -669,8 +825,8 @@ and expression_desc cxt ~(level : int) f x : cxt = operand and as the object of a call or member access. A [function] expression takes them there too, as it would otherwise start a declaration at the start of a statement. *) - pp_function ?directive ~is_method ~return_unit ~async ~paren:(level > 2) - ~fn_state:default_fn_exp_state cxt f params body env + pp_function ?directive ?source_loc ~is_method ~return_unit ~async + ~paren:(level > 2) ~fn_state:default_fn_exp_state cxt f params body env | Jsx {callee; tag; spread; props; children; key; multi; fragment} -> if jsx_printable ~tag ~spread ~props ~children ~key ~multi ~fragment then print_jsx cxt f ~tag ~spread ~props ~children ~key ~fragment @@ -714,9 +870,14 @@ and expression_desc cxt ~(level : int) f x : cxt = async; directive; }; + comment = fn_comment; + source_loc = fn_loc; }; ] -> - pp_function ?directive ~is_method ~return_unit ~async + pp_comment_option f fn_comment; + Js_source_map.mark_source_loc f fn_loc; + pp_function ?directive ?source_loc:fn_loc ~is_method + ~return_unit ~async ~fn_state:(No_name {single_arg = true}) cxt f params body env | _ -> @@ -1256,7 +1417,8 @@ and variable_declaration top cxt f (variable : J.variable_declaration) : cxt = | Fun {is_method; params; body; env; return_unit; async; directive} -> pp_comment_option f e.comment; Js_source_map.mark_source_loc f e.source_loc; - pp_function ?directive ~is_method ~return_unit ~async + pp_function ?directive ?source_loc:e.source_loc ~is_method ~return_unit + ~async ~fn_state:(if top then Name_top name else Name_non_top name) cxt f params body env | Record_rest (fields, source) -> @@ -1300,9 +1462,9 @@ and statement top cxt f ({statement_desc = s; comment; source_loc} : J.statement) : cxt = pp_comment_option f comment; Js_source_map.mark_source_loc f source_loc; - statement_desc top cxt f s + statement_desc ?source_loc top cxt f s -and statement_desc top cxt f (s : J.statement_desc) : cxt = +and statement_desc ?source_loc top cxt f (s : J.statement_desc) : cxt = match s with | Block [] -> ipp_comment f L.empty_block; @@ -1344,20 +1506,47 @@ and statement_desc top cxt f (s : J.statement_desc) : cxt = P.space f; let cxt = P.paren_group f 1 (fun _ -> expression ~level:0 cxt f e) in P.space f; - let cxt = brace_block cxt f s1 in + let cxt = + if is_same_dispatch_block source_loc s1 then + brace_block_mapped cxt f ?start_loc:source_loc ?end_loc:source_loc + ~end_at_start:true s1 + else + let then_start, then_end = + ensure_ordered_locs (block_first_arm_loc s1) (block_last_arm_loc s1) + in + brace_block_mapped cxt f ?start_loc:then_start ?end_loc:then_end s1 + in match s2 with | [] | [{statement_desc = Block [] | Exp {expression_desc = Var _}}] -> cxt | [({statement_desc = If _} as nest)] | [{statement_desc = Block [({statement_desc = If _; _} as nest)]; _}] -> + let else_loc = + match nest.source_loc with + | Some _ as loc -> loc + | None -> block_first_arm_loc [nest] + in + Js_source_map.mark_source_loc f else_loc; P.space f; P.string f L.else_; P.space f; statement false cxt f nest | _ :: _ as s2 -> - P.space f; - P.string f L.else_; - P.space f; - brace_block cxt f s2) + if is_same_dispatch_block source_loc s2 then ( + Js_source_map.mark_source_loc f source_loc; + P.space f; + P.string f L.else_; + P.space f; + brace_block_mapped cxt f ?start_loc:source_loc ?end_loc:source_loc + ~end_at_start:true s2) + else + let else_start, else_end = + ensure_ordered_locs (block_first_arm_loc s2) (block_last_arm_loc s2) + in + Js_source_map.mark_source_loc f else_start; + P.space f; + P.string f L.else_; + P.space f; + brace_block_mapped cxt f ?start_loc:else_start ?end_loc:else_end s2) | While (label, e, s) -> (* FIXME: print scope as well *) let cxt = @@ -1549,13 +1738,15 @@ and statement_desc top cxt f (s : J.statement_desc) : cxt = | Return e -> ( match e.expression_desc with | Fun {is_method; params; body; env; return_unit; async; directive} -> + Js_source_map.mark_source_loc f e.source_loc; let cxt = - pp_function ?directive ~return_unit ~is_method ~async - ~fn_state:Is_return cxt f params body env + pp_function ?directive ?source_loc:e.source_loc ~return_unit ~is_method + ~async ~fn_state:Is_return cxt f params body env in semi f; cxt | Undefined _ -> + Js_source_map.mark_source_loc f e.source_loc; P.string f L.return; semi f; cxt @@ -1574,7 +1765,7 @@ and statement_desc top cxt f (s : J.statement_desc) : cxt = P.space f; let cxt = P.paren_group f 1 (fun _ -> expression ~level:0 cxt f e) in P.space f; - P.brace_vgroup f 1 (fun _ -> + brace_vgroup_mapped f ?end_loc:source_loc 1 (fun _ -> let cxt = loop_case_clauses cxt f (fun f i -> P.string f (string_of_int i)) cc in @@ -1583,6 +1774,7 @@ and statement_desc top cxt f (s : J.statement_desc) : cxt = | Some def -> P.newline f; P.group f 1 (fun _ -> + Js_source_map.mark_source_loc f (block_first_arm_loc def); P.string f L.default; P.string f L.colon; P.newline f; @@ -1592,7 +1784,7 @@ and statement_desc top cxt f (s : J.statement_desc) : cxt = P.space f; let cxt = P.paren_group f 1 (fun _ -> expression ~level:0 cxt f e) in P.space f; - P.brace_vgroup f 1 (fun _ -> + brace_vgroup_mapped f ?end_loc:source_loc 1 (fun _ -> let pp_as_value f (tag_type : Variant_runtime.tag_type) = let e = E.tag_type tag_type in ignore @@ expression_desc cxt ~level:0 f e.expression_desc @@ -1603,6 +1795,7 @@ and statement_desc top cxt f (s : J.statement_desc) : cxt = | Some def -> P.newline f; P.group f 1 (fun _ -> + Js_source_map.mark_source_loc f (block_first_arm_loc def); P.string f L.default; P.string f L.colon; P.newline f; @@ -1681,6 +1874,10 @@ and brace_block cxt f b = (* This one is for '{' *) P.brace_vgroup f 1 (fun _ -> statements false cxt f b) +and brace_block_mapped cxt f ?start_loc ?end_loc ?end_at_start b = + brace_vgroup_mapped f ?start_loc ?end_loc ?end_at_start 1 (fun _ -> + statements false cxt f b) + (* main entry point *) and statements top cxt f b = iter_lst cxt f b diff --git a/compiler/backend/js_exp_make.ml b/compiler/backend/js_exp_make.ml index a7ba9b579e9..5e7c903aac3 100644 --- a/compiler/backend/js_exp_make.ml +++ b/compiler/backend/js_exp_make.ml @@ -1341,12 +1341,11 @@ let not_empty_branch (x : t) = | Number (Int {i = 0l}) | Undefined _ -> false | _ -> true -let rec econd ?comment (pred : t) (ifso : t) (ifnot : t) : t = +let rec econd ?comment ?source_loc (pred : t) (ifso : t) (ifnot : t) : t = let default () = if Js_analyzer.eq_expression ifso ifnot then if no_side_effect pred then ifso else seq ?comment pred ifso - else - {expression_desc = Cond (pred, ifso, ifnot); comment; source_loc = None} + else {expression_desc = Cond (pred, ifso, ifnot); comment; source_loc} in match (pred.expression_desc, ifso.expression_desc, ifnot.expression_desc) with | Bool false, _, _ -> ifnot @@ -1366,21 +1365,22 @@ let rec econd ?comment (pred : t) (ifso : t) (ifnot : t) : t = if b && p1 then branch_code0 else branch_code1 ]} *) - econd (and_ pred pred1) ifso1 ifnot + econd ?source_loc (and_ pred pred1) ifso1 ifnot | _, Cond (pred1, ifso1, ifnot1), _ when Js_analyzer.eq_expression ifso1 ifnot -> - econd (and_ pred (not pred1)) ifnot1 ifnot + econd ?source_loc (and_ pred (not pred1)) ifnot1 ifnot | _, _, Cond (pred1, ifso1, ifnot1) when Js_analyzer.eq_expression ifso ifso1 -> - econd (or_ pred pred1) ifso ifnot1 + econd ?source_loc (or_ pred pred1) ifso ifnot1 | _, _, Cond (pred1, ifso1, ifnot1) when Js_analyzer.eq_expression ifso ifnot1 -> - econd (or_ pred (not pred1)) ifso ifso1 - | Js_not e, _, _ when not_empty_branch ifnot -> econd ?comment e ifnot ifso + econd ?source_loc (or_ pred (not pred1)) ifso ifso1 + | Js_not e, _, _ when not_empty_branch ifnot -> + econd ?comment ?source_loc e ifnot ifso | ( _, Seq (a, {expression_desc = Undefined _}), Seq (b, {expression_desc = Undefined _}) ) -> - seq (econd ?comment pred a b) undefined + seq (econd ?comment ?source_loc pred a b) undefined | _, _, Bool false -> ( match simplify_and pred ifso with | Some e -> e diff --git a/compiler/backend/js_exp_make.mli b/compiler/backend/js_exp_make.mli index e0c891f6ddb..abd7d0d33b5 100644 --- a/compiler/backend/js_exp_make.mli +++ b/compiler/backend/js_exp_make.mli @@ -103,7 +103,7 @@ val method_ : J.block -> t -val econd : ?comment:string -> t -> t -> t -> t +val econd : ?comment:string -> ?source_loc:Location.t -> t -> t -> t -> t val int : ?comment:string -> ?c:int -> int32 -> t diff --git a/compiler/backend/js_pass_flatten.ml b/compiler/backend/js_pass_flatten.ml index 97c11333e17..5f863718dac 100644 --- a/compiler/backend/js_pass_flatten.ml +++ b/compiler/backend/js_pass_flatten.ml @@ -49,9 +49,11 @@ let flatten_map = S.block (List.map (fun arg -> self.statement self (S.exp arg)) args) | Exp {expression_desc = Cond (a, b, c); comment; source_loc} -> (* A branch whose value is pure leaves nothing to run *) - let branch e = + let branch (e : J.expression) = if Js_analyzer.no_side_effect_expression e then [] - else [self.statement self (S.exp e)] + else + let stmt = S.exp e in + [self.statement self {stmt with source_loc = e.source_loc}] in let statement_desc : J.statement_desc = match (branch b, branch c) with @@ -61,6 +63,11 @@ let flatten_map = | [], ifnot -> If (E.not a, ifnot, []) | ifso, ifnot -> If (a, ifso, ifnot) in + let source_loc = + match source_loc with + | Some _ -> source_loc + | None -> x.source_loc + in {statement_desc; comment; source_loc} | Exp { @@ -79,12 +86,17 @@ let flatten_map = (* (S.block (List.rev_append rest_rev [S.exp (E.assign a last_one)])) *) | _ -> assert false) | Return {expression_desc = Cond (a, b, c); comment; source_loc} -> + let return_with_loc (e : J.expression) = + let stmt = S.return_stmt e in + self.statement self {stmt with source_loc = e.source_loc} + in + let source_loc = + match source_loc with + | Some _ -> source_loc + | None -> x.source_loc + in { - statement_desc = - If - ( a, - [self.statement self (S.return_stmt b)], - [self.statement self (S.return_stmt c)] ); + statement_desc = If (a, [return_with_loc b], [return_with_loc c]); comment; source_loc; } diff --git a/compiler/backend/js_source_map.ml b/compiler/backend/js_source_map.ml index 3e455d95054..38463b58251 100644 --- a/compiler/backend/js_source_map.ml +++ b/compiler/backend/js_source_map.ml @@ -177,17 +177,18 @@ let original_column source (pos : Lexing.position) = | None -> max 0 (pos.pos_cnum - pos.pos_bol) | Some content -> utf16_units_in_utf8_slice content pos.pos_bol pos.pos_cnum -let add_mapping builder ~generated_line ~generated_column (loc : Location.t) = - if loc.loc_ghost || loc.loc_start.pos_cnum < 0 then () +let add_pos_mapping builder ~generated_line ~generated_column + (pos : Lexing.position) = + if pos.pos_cnum < 0 then () else match builder.last_generated with | Some (line, column) when line = generated_line && column = generated_column -> () | _ -> - let source_index, source = add_source builder loc.loc_start.pos_fname in - let original_line = max 0 (loc.loc_start.pos_lnum - 1) in - let original_column = original_column source loc.loc_start in + let source_index, source = add_source builder pos.pos_fname in + let original_line = max 0 (pos.pos_lnum - 1) in + let original_column = original_column source pos in builder.mappings <- { generated_line; @@ -199,14 +200,22 @@ let add_mapping builder ~generated_line ~generated_column (loc : Location.t) = :: builder.mappings; builder.last_generated <- Some (generated_line, generated_column) +let mark_source_pos fmt (pos : Lexing.position) = + match !(Domain.DLS.get current) with + | None -> () + | Some builder -> + let generated_line, generated_column = Ext_pp.position fmt in + add_pos_mapping builder ~generated_line ~generated_column pos + let mark_source_loc fmt = function | None -> () - | Some loc -> ( - match !(Domain.DLS.get current) with - | None -> () - | Some builder -> - let generated_line, generated_column = Ext_pp.position fmt in - add_mapping builder ~generated_line ~generated_column loc) + | Some loc -> + if not loc.Location.loc_ghost then mark_source_pos fmt loc.loc_start + +let mark_source_loc_end fmt = function + | None -> () + | Some loc -> + if not loc.Location.loc_ghost then mark_source_pos fmt loc.loc_end let base64_vlq_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" diff --git a/compiler/backend/js_source_map.mli b/compiler/backend/js_source_map.mli index 1079bff2b64..7e9f5463fc2 100644 --- a/compiler/backend/js_source_map.mli +++ b/compiler/backend/js_source_map.mli @@ -9,6 +9,8 @@ val source_loc_of_loc : Location.t -> Location.t option val mark_source_loc : Ext_pp.t -> Location.t option -> unit +val mark_source_loc_end : Ext_pp.t -> Location.t option -> unit + val json : t -> string val linked_comment : map_file:string -> string diff --git a/compiler/backend/js_stmt_make.ml b/compiler/backend/js_stmt_make.ml index 52d00f39cf2..99b8634ffa2 100644 --- a/compiler/backend/js_stmt_make.ml +++ b/compiler/backend/js_stmt_make.ml @@ -75,7 +75,12 @@ let define_variable ~kind (v : Ident.t) (exp : J.expression) : t = source_loc = None; } -let int_switch ?(declaration : (J.property * Ident.t) option) +let with_exp_source_loc source_loc (e : J.expression) = + match (source_loc, e.source_loc) with + | Some _, None -> {e with source_loc} + | _ -> e + +let int_switch ?source_loc ?(declaration : (J.property * Ident.t) option) ?(default : J.block option) (e : J.expression) (clauses : (int * J.case_clause) list) : t = match e.expression_desc with @@ -103,11 +108,15 @@ let int_switch ?(declaration : (J.property * Ident.t) option) Bin (Eq, {expression_desc = Var (Id id); _}, e0); _; }; + source_loc = stmt_loc; _; }; ] ) when Ident.same did id -> - define_variable ~kind id e0 + { + (define_variable ~kind id (with_exp_source_loc stmt_loc e0)) with + source_loc = stmt_loc; + } | Some (kind, did), _ -> block (declare_variable ~kind did :: continuation) | None, _ -> block continuation) | _ -> ( @@ -119,17 +128,17 @@ let int_switch ?(declaration : (J.property * Ident.t) option) { statement_desc = J.Int_switch (e, clauses, default); comment = None; - source_loc = None; + source_loc; }; ] | None -> { statement_desc = J.Int_switch (e, clauses, default); comment = None; - source_loc = None; + source_loc; }) -let string_switch ?(declaration : (J.property * Ident.t) option) +let string_switch ?source_loc ?(declaration : (J.property * Ident.t) option) ?(default : J.block option) (e : J.expression) (clauses : (Variant_runtime.tag_type * J.case_clause) list) : t = match e.expression_desc with @@ -163,11 +172,15 @@ let string_switch ?(declaration : (J.property * Ident.t) option) Bin (Eq, {expression_desc = Var (Id id); _}, e0); _; }; + source_loc = stmt_loc; _; }; ] ) when Ident.same did id -> - define_variable ~kind id e0 + { + (define_variable ~kind id (with_exp_source_loc stmt_loc e0)) with + source_loc = stmt_loc; + } | Some (kind, did), _ -> block @@ (declare_variable ~kind did :: continuation) | None, _ -> block continuation) @@ -180,14 +193,14 @@ let string_switch ?(declaration : (J.property * Ident.t) option) { statement_desc = String_switch (e, clauses, default); comment = None; - source_loc = None; + source_loc; }; ] | None -> { statement_desc = String_switch (e, clauses, default); comment = None; - source_loc = None; + source_loc; }) let rec block_last_is_return_throw_or_continue (x : J.block) = @@ -237,7 +250,8 @@ let rec block_last_is_return_throw_or_continue (x : J.block) = ]} Not clear the benefit *) -let if_ ?declaration ?else_ (e : J.expression) (then_ : J.block) : t = +let if_ ?source_loc ?declaration ?else_ (e : J.expression) (then_ : J.block) : t + = let declared = ref false in let rec aux (e : J.expression) (ifso : J.block) (ifnot : J.block) : t = (* An empty block, such as a dropped condition of a nested [if], leaves @@ -259,24 +273,26 @@ let if_ ?declaration ?else_ (e : J.expression) (then_ : J.block) : t = needs to be kept *) if Js_analyzer.no_side_effect_expression e then empty_stmt else exp e | [], _ -> aux (E.not e) ifnot [] (*Make sure no infinite loop*) - | ( [{statement_desc = Return ret_ifso; _}], - [{statement_desc = Return ret_ifnot; _}] ) -> - return_stmt (E.econd e ret_ifso ret_ifnot) + | ( [{statement_desc = Return ret_ifso; source_loc = s1}], + [{statement_desc = Return ret_ifnot; source_loc = s2}] ) -> + let ret_ifso = with_exp_source_loc s1 ret_ifso in + let ret_ifnot = with_exp_source_loc s2 ret_ifnot in + { + statement_desc = Return (E.econd ?source_loc e ret_ifso ret_ifnot); + comment = None; + source_loc; + } | _, [{statement_desc = Return _}] -> block ({ statement_desc = If (E.not e, ifnot, []); comment = None; - source_loc = None; + source_loc; } :: ifso) | _, _ when block_last_is_return_throw_or_continue ifso -> block - ({ - statement_desc = If (e, ifso, []); - comment = None; - source_loc = None; - } + ({statement_desc = If (e, ifso, []); comment = None; source_loc} :: ifnot) | ( [ { @@ -290,6 +306,7 @@ let if_ ?declaration ?else_ (e : J.expression) (then_ : J.block) : t = rhs_ifso ); _; }; + source_loc = s1; _; }; ], @@ -305,18 +322,24 @@ let if_ ?declaration ?else_ (e : J.expression) (then_ : J.block) : t = lhs_ifnot ); _; }; + source_loc = s2; _; }; ] ) when Ident.same var_ifso var_ifnot -> ( + let rhs_ifso = with_exp_source_loc s1 rhs_ifso in + let lhs_ifnot = with_exp_source_loc s2 lhs_ifnot in + let cond = E.econd ?source_loc e rhs_ifso lhs_ifnot in match declaration with | Some (kind, id) when Ident.same id var_ifso -> declared := true; - define_variable ~kind var_ifso (E.econd e rhs_ifso lhs_ifnot) - | _ -> exp (E.assign lhs_ifso (E.econd e rhs_ifso lhs_ifnot))) - | ( [{statement_desc = Exp exp_ifso; _}], - [{statement_desc = Exp exp_ifnot; _}] ) -> - exp (E.econd e exp_ifso exp_ifnot) + {(define_variable ~kind var_ifso cond) with source_loc} + | _ -> {(exp (E.assign lhs_ifso cond)) with source_loc}) + | ( [{statement_desc = Exp exp_ifso; source_loc = s1}], + [{statement_desc = Exp exp_ifnot; source_loc = s2}] ) -> + let exp_ifso = with_exp_source_loc s1 exp_ifso in + let exp_ifnot = with_exp_source_loc s2 exp_ifnot in + {(exp (E.econd ?source_loc e exp_ifso exp_ifnot)) with source_loc} | [{statement_desc = If (pred1, ifso1, ifnot1)}], _ when Js_analyzer.eq_block ifnot1 ifnot -> aux (E.and_ e pred1) ifso1 ifnot1 @@ -329,12 +352,7 @@ let if_ ?declaration ?else_ (e : J.expression) (then_ : J.block) : t = | _, [{statement_desc = If (pred1, ifso1, ifnot1)}] when Js_analyzer.eq_block ifso ifnot1 -> aux (E.or_ e (E.not pred1)) ifso ifso1 - | _ -> - { - statement_desc = If (e, ifso, ifnot); - comment = None; - source_loc = None; - }) + | _ -> {statement_desc = If (e, ifso, ifnot); comment = None; source_loc}) in let if_block = aux e then_ diff --git a/compiler/backend/js_stmt_make.mli b/compiler/backend/js_stmt_make.mli index 62a3b01c865..1e12b2d0305 100644 --- a/compiler/backend/js_stmt_make.mli +++ b/compiler/backend/js_stmt_make.mli @@ -29,6 +29,7 @@ type t = J.statement val throw_stmt : J.expression -> t val if_ : + ?source_loc:Location.t -> ?declaration:Lambda.let_kind * Ident.t -> (* when it's not None, we also need make a variable declaration in the begininnig, however, we can optmize such case @@ -45,6 +46,7 @@ val block : J.block -> t *) val int_switch : + ?source_loc:Location.t -> ?declaration:Lambda.let_kind * Ident.t -> ?default:J.block -> J.expression -> @@ -67,6 +69,7 @@ val int_switch : *) val string_switch : + ?source_loc:Location.t -> ?declaration:Lambda.let_kind * Ident.t -> ?default:J.block -> J.expression -> diff --git a/compiler/backend/lam_analysis.ml b/compiler/backend/lam_analysis.ml index 0812ed0fea6..7f40c74014b 100644 --- a/compiler/backend/lam_analysis.ml +++ b/compiler/backend/lam_analysis.ml @@ -32,7 +32,7 @@ let rec delay_safe ~assignable (lam : Lambda.t) : bool = match lam with | Lconst _ | Lfunction _ | Lglobal_module _ -> true | Lvar id -> not (Set_ident.mem id assignable) - | Lifthenelse (a, b, c) -> + | Lifthenelse (a, b, c, _) -> delay_safe ~assignable a && delay_safe ~assignable b && delay_safe ~assignable c | Lprim {primitive; args} -> ( @@ -159,13 +159,13 @@ let size_upto ~limit (lam : Lambda.t) = List.iter size ap_args | Lfunction {body} -> size body | Lswitch _ -> add too_big - | Lstringswitch (_, _, _) -> add too_big + | Lstringswitch (_, _, _, _) -> add too_big | Lstaticraise (_i, ls) -> add 1; List.iter size ls | Lstaticcatch _ -> add too_big | Ltrywith _ | Ltryfinally _ -> add too_big - | Lifthenelse (l1, l2, l3) -> + | Lifthenelse (l1, l2, l3, _) -> add 1; size l1; size l2; @@ -221,7 +221,7 @@ let destruct_pattern (body : Lambda.t) params args = size_upto ~limit:small_inline_size (Lambda.switch lam switch) < small_inline_size | Some _ | None -> false) - | Lifthenelse (Lvar v, then_, else_) -> ( + | Lifthenelse (Lvar v, then_, else_, _) -> ( (* -FIXME *) match aux v params args with | Some (Lconst _ as lam) -> diff --git a/compiler/backend/lam_arity_analysis.ml b/compiler/backend/lam_arity_analysis.ml index 2d23430d832..4b55c9583ec 100644 --- a/compiler/backend/lam_arity_analysis.ml +++ b/compiler/backend/lam_arity_analysis.ml @@ -108,18 +108,23 @@ let rec get_arity (meta : Lam_stats.t) (lam : Lambda.t) : Lam_arity.t = sw_consts_full = _; } ) -> all_lambdas meta - (let rest = Ext_list.map_append sw_consts (List.map snd sw_blocks) snd in + (let rest = + Ext_list.map_append sw_consts + (List.map (fun (_, e, _) -> e) sw_blocks) + (fun (_, e, _) -> e) + in match sw_failaction with | None -> rest - | Some x -> x :: rest) - | Lstringswitch (_, sw, d) -> ( + | Some (x, _) -> x :: rest) + | Lstringswitch (_, sw, d, _) -> ( + let bodies = List.map (fun (_, e, _) -> e) sw in match d with - | None -> all_lambdas meta (List.map snd sw) - | Some v -> all_lambdas meta (v :: List.map snd sw)) - | Lstaticcatch (_, _, handler) -> get_arity meta handler + | None -> all_lambdas meta bodies + | Some (v, _) -> all_lambdas meta (v :: bodies)) + | Lstaticcatch (_, _, handler, _) -> get_arity meta handler | Ltrywith (l1, _, l2) -> all_lambdas meta [l1; l2] | Ltryfinally (body, _) -> get_arity meta body - | Lifthenelse (_, l2, l3) -> all_lambdas meta [l2; l3] + | Lifthenelse (_, l2, l3, _) -> all_lambdas meta [l2; l3] | Lsequence (_, l2) -> get_arity meta l2 | Lstaticraise _ (* since it will not be in tail position *) -> Lam_arity.na | Lbreak | Lcontinue -> Lam_arity.non_function_arity_info diff --git a/compiler/backend/lam_beta_reduce.ml b/compiler/backend/lam_beta_reduce.ml index b155ad68316..9cb101343bb 100644 --- a/compiler/backend/lam_beta_reduce.ml +++ b/compiler/backend/lam_beta_reduce.ml @@ -73,7 +73,7 @@ let read_before_effects param (body : Lambda.t) = | Lsequence (a, b) -> walk a; walk b - | Lifthenelse (cond, then_, else_) -> + | Lifthenelse (cond, then_, else_, _) -> walk cond; let before = !effects in walk then_; diff --git a/compiler/backend/lam_bounded_vars.ml b/compiler/backend/lam_bounded_vars.ml index 995a2ed5f88..f17e7ba7d01 100644 --- a/compiler/backend/lam_bounded_vars.ml +++ b/compiler/backend/lam_bounded_vars.ml @@ -80,11 +80,7 @@ let rewrite (map : _ Hash_ident.t) (lam : Lambda.t) : Lambda.t = | None -> i in (* order matters, especially for let bindings *) - let rec option_map op = - match op with - | None -> None - | Some x -> Some (aux x) - and aux (lam : Lambda.t) : Lambda.t = + let rec aux (lam : Lambda.t) : Lambda.t = match lam with | Lvar v -> ( match Hash_ident.find_opt map v with @@ -105,7 +101,7 @@ let rewrite (map : _ Hash_ident.t) (lam : Lambda.t) : Lambda.t = let params = List.map rebind params in let body = aux body in Lambda.function_ ~loc ~params ~body ~attr - | Lstaticcatch (l1, (i, xs), l2) -> + | Lstaticcatch (l1, (i, xs), l2, loc) -> let i' = if i < 0 then Lambda_exits.next_negative_raise_count () else Lambda_exits.next_raise_count () @@ -116,7 +112,7 @@ let rewrite (map : _ Hash_ident.t) (lam : Lambda.t) : Lambda.t = exits := outer; let xs = List.map rebind xs in let l2 = aux l2 in - Lambda.staticcatch l1 (i', xs) l2 + Lambda.staticcatch ~loc l1 (i', xs) l2 | Lfor (ident, l1, l2, dir, l3) -> let ident = rebind ident in let l1 = aux l1 in @@ -142,29 +138,23 @@ let rewrite (map : _ Hash_ident.t) (lam : Lambda.t) : Lambda.t = let fn = aux ap_func in let args = List.map aux ap_args in Lambda.apply fn args ap_loc - | Lswitch - ( l, - { - sw_failaction; - sw_consts; - sw_blocks; - sw_blocks_full; - sw_consts_full; - sw_dispatch; - } ) -> + | Lswitch (l, sw) -> let l = aux l in Lambda.switch l { - sw_consts = Ext_list.map_snd sw_consts aux; - sw_blocks = Ext_list.map_snd sw_blocks aux; - sw_consts_full; - sw_blocks_full; - sw_failaction = option_map sw_failaction; - sw_dispatch; + sw with + sw_consts = + List.map (fun (k, arm, loc) -> (k, aux arm, loc)) sw.sw_consts; + sw_blocks = + List.map (fun (k, arm, loc) -> (k, aux arm, loc)) sw.sw_blocks; + sw_failaction = + Option.map (fun (arm, loc) -> (aux arm, loc)) sw.sw_failaction; } - | Lstringswitch (l, sw, d) -> + | Lstringswitch (l, sw, d, loc) -> let l = aux l in - Lambda.stringswitch l (Ext_list.map_snd sw aux) (option_map d) + Lambda.stringswitch ~loc l + (List.map (fun (k, arm, arm_loc) -> (k, aux arm, arm_loc)) sw) + (Option.map (fun (arm, arm_loc) -> (aux arm, arm_loc)) d) | Lstaticraise (i, ls) -> Lambda.staticraise (find_exit i) (List.map aux ls) | Ltrywith (l1, v, l2) -> let l1 = aux l1 in @@ -175,11 +165,11 @@ let rewrite (map : _ Hash_ident.t) (lam : Lambda.t) : Lambda.t = let l1 = aux l1 in let l2 = aux l2 in Lambda.try_finally l1 l2 - | Lifthenelse (l1, l2, l3) -> + | Lifthenelse (l1, l2, l3, {if_loc; then_loc; else_loc}) -> let l1 = aux l1 in let l2 = aux l2 in let l3 = aux l3 in - Lambda.if_ l1 l2 l3 + Lambda.if_ ~loc:if_loc ~then_loc ~else_loc l1 l2 l3 | Lsequence (l1, l2) -> let l1 = aux l1 in let l2 = aux l2 in diff --git a/compiler/backend/lam_check.ml b/compiler/backend/lam_check.ml index ba7ce824fec..a8b7ac13a9d 100644 --- a/compiler/backend/lam_check.ml +++ b/compiler/backend/lam_check.ml @@ -78,24 +78,24 @@ let check ~file ~pass lam = check_staticfails body cxt | Lswitch (arg, sw) -> check_staticfails arg cxt; - check_list_snd sw.sw_consts cxt; - check_list_snd sw.sw_blocks cxt; - Option.iter (fun x -> check_staticfails x cxt) sw.sw_failaction - | Lstringswitch (arg, cases, default) -> + List.iter (fun (_, x, _) -> check_staticfails x cxt) sw.sw_consts; + List.iter (fun (_, x, _) -> check_staticfails x cxt) sw.sw_blocks; + Option.iter (fun (x, _) -> check_staticfails x cxt) sw.sw_failaction + | Lstringswitch (arg, cases, default, _) -> check_staticfails arg cxt; - check_list_snd cases cxt; - Option.iter (fun x -> check_staticfails x cxt) default + List.iter (fun (_, x, _) -> check_staticfails x cxt) cases; + Option.iter (fun (x, _) -> check_staticfails x cxt) default | Lstaticraise (i, args) -> if Set_int.mem i cxt then check_list args cxt else failwith (Printf.sprintf "exit %d unbound after %s in %s" i pass file) - | Lstaticcatch (e1, (j, _vars), e2) -> + | Lstaticcatch (e1, (j, _vars), e2, _) -> check_staticfails e1 (Set_int.add j cxt); check_staticfails e2 cxt | Ltrywith (e1, _, e2) | Ltryfinally (e1, e2) -> check_staticfails e1 cxt; check_staticfails e2 cxt - | Lifthenelse (e1, e2, e3) -> check_list [e1; e2; e3] cxt + | Lifthenelse (e1, e2, e3, _) -> check_list [e1; e2; e3] cxt | Lsequence (e1, e2) -> check_list [e1; e2] cxt | Lassign (_id, e) -> check_staticfails e cxt in @@ -124,17 +124,17 @@ let check ~file ~pass lam = iter body | Lswitch (arg, sw) -> iter arg; - iter_list_snd sw.sw_consts; - iter_list_snd sw.sw_blocks; - Option.iter iter sw.sw_failaction; + List.iter (fun (_, x, _) -> iter x) sw.sw_consts; + List.iter (fun (_, x, _) -> iter x) sw.sw_blocks; + Option.iter (fun (x, _) -> iter x) sw.sw_failaction; assert ( not (sw.sw_failaction <> None && sw.sw_consts_full && sw.sw_blocks_full)) - | Lstringswitch (arg, cases, default) -> + | Lstringswitch (arg, cases, default, _) -> iter arg; - iter_list_snd cases; - Option.iter iter default + List.iter (fun (_, x, _) -> iter x) cases; + Option.iter (fun (x, _) -> iter x) default | Lstaticraise (_i, args) -> iter_list args - | Lstaticcatch (e1, (_, vars), e2) -> + | Lstaticcatch (e1, (_, vars), e2, _) -> iter e1; List.iter def vars; iter e2 @@ -145,7 +145,7 @@ let check ~file ~pass lam = | Ltryfinally (e1, e2) -> iter e1; iter e2 - | Lifthenelse (e1, e2, e3) -> + | Lifthenelse (e1, e2, e3, _) -> iter e1; iter e2; iter e3 diff --git a/compiler/backend/lam_closure.ml b/compiler/backend/lam_closure.ml index 5e51d66285e..30078b91c9a 100644 --- a/compiler/backend/lam_closure.ml +++ b/compiler/backend/lam_closure.ml @@ -98,29 +98,29 @@ let free_variables (export_idents : Set_ident.t) (params : stats Map_ident.t) ) -> ( iter top arg; let top = Lam_var_stats.new_position_after_lam arg top in - List.iter (fun (_, case) -> iter top case) sw_consts; - List.iter (fun (_, case) -> iter top case) sw_blocks; + List.iter (fun (_, case, _) -> iter top case) sw_consts; + List.iter (fun (_, case, _) -> iter top case) sw_blocks; match sw_failaction with | None -> () - | Some x -> + | Some (x, _) -> if sw_consts_full || sw_blocks_full then iter top x else iter sink_pos x ) - | Lstringswitch (arg, cases, default) -> ( + | Lstringswitch (arg, cases, default, _) -> ( iter top arg; let top = Lam_var_stats.new_position_after_lam arg top in - List.iter (fun (_, act) -> iter top act) cases; + List.iter (fun (_, act, _) -> iter top act) cases; match default with | None -> () - | Some x -> iter top x) + | Some (x, _) -> iter top x) | Lstaticraise (_, args) -> List.iter (iter sink_pos) args - | Lstaticcatch (e1, (_, vars), e2) -> + | Lstaticcatch (e1, (_, vars), e2, _) -> iter sink_pos e1; local_add_list vars; iter sink_pos e2 | Ltrywith (e1, _, e2) | Ltryfinally (e1, e2) -> iter top e1; iter sink_pos e2 - | Lifthenelse (e1, e2, e3) -> + | Lifthenelse (e1, e2, e3, _) -> iter top e1; let top = Lam_var_stats.new_position_after_lam e1 top in iter top e2; diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 6fe20f7a1dc..9e2eb2041b9 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -27,11 +27,27 @@ module S = Js_stmt_make let source_map_loc = Js_source_map.source_loc_of_loc -let with_source_loc loc (exp : J.expression) = - match (source_map_loc loc, exp.source_loc) with - | Some source_loc, None -> {exp with source_loc = Some source_loc} +let with_exp_source_loc_opt source_loc (exp : J.expression) = + match (source_loc, exp.source_loc) with + | Some _, None -> {exp with source_loc} | _ -> exp +let with_source_loc loc (exp : J.expression) = + with_exp_source_loc_opt (source_map_loc loc) exp + +let source_map_body_loc ({pat_loc; body_loc} : Lambda.branch_loc) = + match source_map_loc body_loc with + | Some _ as loc -> loc + | None -> source_map_loc pat_loc + +let source_map_case_loc ({pat_loc; body_loc} : Lambda.branch_loc) = + match source_map_loc pat_loc with + | Some _ as loc -> loc + | None -> source_map_loc body_loc + +let loc_if_valid (loc : Location.t) = + if (not loc.loc_ghost) && loc.loc_start.pos_cnum >= 0 then Some loc else None + let rec source_loc_of_lam (lam : Lambda.t) = match lam with | Lapply {ap_loc} -> Some ap_loc @@ -41,21 +57,12 @@ let rec source_loc_of_lam (lam : Lambda.t) = | Some _ as loc -> loc | None -> source_loc_of_lam body) | Lletrec (_, body) | Lsequence (_, body) -> source_loc_of_lam body - | Lifthenelse (_, then_, _) -> source_loc_of_lam then_ - | Lstaticcatch (body, _, _) | Ltrywith (body, _, _) | Ltryfinally (body, _) -> + | Lifthenelse (_, _, _, {if_loc}) -> loc_if_valid if_loc + | Lstaticcatch (body, _, _, _) | Ltrywith (body, _, _) | Ltryfinally (body, _) + -> source_loc_of_lam body - | Lstringswitch (_, cases, default) -> ( - match cases with - | (_, body) :: _ -> source_loc_of_lam body - | [] -> ( - match default with - | Some body -> source_loc_of_lam body - | None -> None)) - | Lswitch (_, sw) -> ( - match (sw.sw_consts, sw.sw_blocks, sw.sw_failaction) with - | (_, body) :: _, _, _ | _, (_, body) :: _, _ -> source_loc_of_lam body - | [], [], Some body -> source_loc_of_lam body - | [], [], None -> None) + | Lstringswitch (_, _, _, loc) -> loc_if_valid loc + | Lswitch (_, {sw_loc}) -> loc_if_valid sw_loc | Lstaticraise (_, args) -> ( match args with | arg :: _ -> source_loc_of_lam arg @@ -74,15 +81,57 @@ let source_map_loc_of_lam lam = | None -> None let with_statement_source_loc source_loc (stmt : J.statement) = - match (source_loc, stmt.source_loc) with - | Some source_loc, None -> {stmt with source_loc = Some source_loc} - | _ -> stmt - -let with_block_source_loc lam block = + match source_loc with + | None -> stmt + | Some _ -> + let inner_loc, statement_desc = + match stmt.statement_desc with + | Return e -> ( + match e.source_loc with + | Some _ as loc -> (loc, stmt.statement_desc) + | None -> (source_loc, Return (with_exp_source_loc_opt source_loc e))) + | Exp ({expression_desc = Bin (Eq, lhs, rhs)} as exp) -> ( + match rhs.source_loc with + | Some _ as loc -> (loc, stmt.statement_desc) + | None -> + ( source_loc, + Exp + { + exp with + expression_desc = + Bin (Eq, lhs, with_exp_source_loc_opt source_loc rhs); + } )) + | Exp e -> ( + match e.source_loc with + | Some _ as loc -> (loc, stmt.statement_desc) + | None -> (source_loc, Exp (with_exp_source_loc_opt source_loc e))) + | Variable ({value = Some e} as vd) -> ( + match e.source_loc with + | Some _ as loc -> (loc, stmt.statement_desc) + | None -> + ( source_loc, + Variable + {vd with value = Some (with_exp_source_loc_opt source_loc e)} )) + | _ -> (source_loc, stmt.statement_desc) + in + { + stmt with + statement_desc; + source_loc = + (match stmt.source_loc with + | Some _ -> stmt.source_loc + | None -> inner_loc); + } + +let with_branch_block_source_loc (arm_loc : Lambda.branch_loc) lam block = + let loc = + match source_map_body_loc arm_loc with + | Some _ as loc -> loc + | None -> source_map_loc_of_lam lam + in match block with | [] -> [] - | stmt :: rest -> - with_statement_source_loc (source_map_loc_of_lam lam) stmt :: rest + | stmt :: rest -> with_statement_source_loc loc stmt :: rest let args_either_function_or_const (args : Lambda.t list) = List.for_all @@ -136,7 +185,7 @@ let in_staticcatch (x : Lam_compile_context.tail_type) : let rec flat_catches (acc : Lam_compile_context.handler list) (x : Lambda.t) : Lam_compile_context.handler list * Lambda.t = match x with - | Lstaticcatch (l, (label, bindings), handler) + | Lstaticcatch (l, (label, bindings), handler, handler_loc) when acc = [] || not (Lam_exit_code.has_exit_code handler (fun exit -> @@ -144,7 +193,7 @@ let rec flat_catches (acc : Lam_compile_context.handler list) (x : Lambda.t) : (fun (x : Lam_compile_context.handler) -> x.label = exit) acc)) -> (* #1698 should not crush exit code here without checking *) - flat_catches ({label; handler; bindings} :: acc) l + flat_catches ({label; handler; handler_loc; bindings} :: acc) l | _ -> (acc, x) let flatten_nested_caches (x : Lambda.t) : @@ -160,7 +209,7 @@ let morph_declare_to_assign (cxt : Lam_compile_context.t) k = let group_apply cases callback = List.concat_map (fun group -> Ext_list.map_last group callback) - (Ext_list.stable_group cases (fun (_, lam) (_, lam1) -> + (Ext_list.stable_group cases (fun (_, lam, _) (_, lam1, _) -> Lambda.eq_approx lam lam1)) (* TODO: for expression generation, @@ -168,12 +217,15 @@ let group_apply cases callback = only jmp_table and env needed *) -type default_case = Default of Lambda.t | Complete | NonComplete +type default_case = + | Default of Lambda.t * Lambda.branch_loc + | Complete + | NonComplete let default_action ~saturated failaction = match failaction with | None -> Complete - | Some x -> if saturated then Complete else Default x + | Some (x, loc) -> if saturated then Complete else Default (x, loc) let tag_of_switch_key : _ -> Variant_runtime.tag_type option = function | Lambda.Switch_int _ -> None @@ -823,67 +875,69 @@ let compile output_prefix = ('a option -> J.expression -> 'a option -> J.expression -> J.expression) -> cxt:Lam_compile_context.t -> switch: - (?default:J.block -> + (?source_loc:Location.t -> + ?default:J.block -> ?declaration:Lambda.let_kind * Ident.t -> _ -> ('a * J.case_clause) list -> J.statement) -> switch_exp:J.expression -> + sw_loc:Location.t -> default:default_case -> - ('a * Lambda.t) list -> + ('a * Lambda.t * Lambda.branch_loc) list -> J.block = fun (type a) ~(make_exp : a -> J.expression) ~(eq_exp : a option -> J.expression -> a option -> J.expression -> J.expression) ~(cxt : Lam_compile_context.t) ~(switch : + ?source_loc:Location.t -> ?default:J.block -> ?declaration:Lambda.let_kind * Ident.t -> _ -> (a * J.case_clause) list -> - J.statement) ~(switch_exp : J.expression) ~(default : default_case) - (cases : (a * Lambda.t) list) -> - let output_block_with_source_loc cxt lam = + J.statement) ~(switch_exp : J.expression) ~(sw_loc : Location.t) + ~(default : default_case) + (cases : (a * Lambda.t * Lambda.branch_loc) list) -> + let sw_source_loc = source_map_loc sw_loc in + let output_block_with_source_loc cxt arm_loc lam = compile_lambda cxt lam |> Js_output.output_as_block - |> with_block_source_loc lam + |> with_branch_block_source_loc arm_loc lam + in + let case_source_loc arm_loc lam = + match source_map_case_loc arm_loc with + | Some _ as loc -> loc + | None -> source_map_loc_of_lam lam in let output_default cxt = function - | Default lam -> output_block_with_source_loc cxt lam + | Default (lam, arm_loc) -> output_block_with_source_loc cxt arm_loc lam | Complete | NonComplete -> [] in match (cases, default) with | [], Default _ -> output_default cxt default | [], (Complete | NonComplete) -> [] - | [(_, lam)], Complete -> + | [(_, lam, arm_loc)], Complete -> (* To take advantage of such optimizations, when we generate code using switch, we should always have a default, otherwise the compiler engine would think that it's also complete *) - output_block_with_source_loc cxt lam - | [(id, lam)], NonComplete -> + output_block_with_source_loc cxt arm_loc lam + | [(id, lam, arm_loc)], NonComplete -> morph_declare_to_assign cxt (fun cxt define -> [ - S.if_ ?declaration:define + S.if_ ?source_loc:sw_source_loc ?declaration:define (eq_exp None switch_exp (Some id) (make_exp id)) - (output_block_with_source_loc cxt lam); + (output_block_with_source_loc cxt arm_loc lam); ]) - | [(id, lam)], Default _ -> + | [(id, lam, arm_loc)], Default (x, x_loc) + | [(id, lam, arm_loc); (_, x, x_loc)], Complete -> morph_declare_to_assign cxt (fun cxt define -> - let else_block = output_default cxt default in - let then_block = output_block_with_source_loc cxt lam in + let else_block = output_block_with_source_loc cxt x_loc x in + let then_block = output_block_with_source_loc cxt arm_loc lam in [ - S.if_ ?declaration:define - (eq_exp None switch_exp (Some id) (make_exp id)) - then_block ~else_:else_block; - ]) - | [(id, lam); (_, x)], Complete -> - morph_declare_to_assign cxt (fun cxt define -> - let else_block = output_block_with_source_loc cxt x in - let then_block = output_block_with_source_loc cxt lam in - [ - S.if_ ?declaration:define + S.if_ ?source_loc:sw_source_loc ?declaration:define (eq_exp None switch_exp (Some id) (make_exp id)) then_block ~else_:else_block; ]) @@ -910,9 +964,9 @@ let compile output_prefix = (* Exclude cases that are the same as the default if the default is defined *) let cases = match default with - | Default lam -> + | Default (lam, _) -> List.filter - (fun (_, lam1) -> not (Lambda.eq_approx lam lam1)) + (fun (_, lam1, _) -> not (Lambda.eq_approx lam lam1)) cases | _ -> cases in @@ -923,13 +977,15 @@ let compile output_prefix = | statements -> Some statements in let body = - group_apply cases (fun last (switch_case, lam) -> + group_apply cases (fun last (switch_case, lam, arm_loc) -> if last then (* merge and shared *) let switch_body, should_break = Js_output.to_break_block (compile_lambda switch_cxt lam) in - let switch_body = with_block_source_loc lam switch_body in + let switch_body = + with_branch_block_source_loc arm_loc lam switch_body + in let should_break = if not @@ -944,7 +1000,7 @@ let compile output_prefix = switch_body; should_break; comment = None; - source_loc = source_map_loc_of_lam lam; + source_loc = case_source_loc arm_loc lam; } ) else ( switch_case, @@ -952,27 +1008,30 @@ let compile output_prefix = switch_body = []; should_break = false; comment = None; - source_loc = source_map_loc_of_lam lam; + source_loc = case_source_loc arm_loc lam; } )) (* TODO: we should also group default *) (* The last clause does not need [break] common break through, *) in - [switch ?default ?declaration switch_exp body]) + [ + switch ?source_loc:sw_source_loc ?default ?declaration switch_exp + body; + ]) and use_compile_literal_cases table = List.fold_right - (fun (key, lam) acc -> + (fun (key, lam, arm_loc) acc -> match (tag_of_switch_key key, acc) with | Some tag_type, Some string_table -> - Some ((tag_type, lam) :: string_table) + Some ((tag_type, lam, arm_loc) :: string_table) | _, _ -> None) table (Some []) - and compile_cases ~cxt ~(switch_exp : E.t) ?(default = NonComplete) cases : - initialization = + and compile_cases ~cxt ~(switch_exp : E.t) ?(sw_loc = Location.none) + ?(default = NonComplete) cases : initialization = match use_compile_literal_cases cases with | Some string_cases -> - compile_string_cases ~cxt ~switch_exp ~default string_cases + compile_string_cases ~cxt ~switch_exp ~sw_loc ~default string_cases | None -> cases |> compile_general_cases @@ -981,15 +1040,15 @@ let compile output_prefix = | Switch_constructor _ -> assert false) ~eq_exp:(fun _ x _ y -> E.int_equal x y) ~cxt - ~switch:(fun ?default ?declaration e clauses -> - S.int_switch ?default ?declaration e + ~switch:(fun ?source_loc ?default ?declaration e clauses -> + S.int_switch ?source_loc ?default ?declaration e (List.map (fun (key, clause) -> match key with | Lambda.Switch_int i -> (i, clause) | Switch_constructor _ -> assert false) clauses)) - ~switch_exp ~default + ~switch_exp ~sw_loc ~default and compile_switch (switch_arg : Lambda.t) (sw : Lambda.lambda_switch) (lambda_cxt : Lam_compile_context.t) = (* TODO: if default is None, we can do some optimizations @@ -1006,10 +1065,12 @@ let compile output_prefix = sw_blocks; sw_failaction; sw_dispatch; + sw_loc; } : Lambda.lambda_switch) = sw in + let sw_source_loc = source_map_loc sw_loc in let sw_num_default = default_action ~saturated:sw_consts_full sw_failaction in @@ -1037,26 +1098,27 @@ let compile output_prefix = match Lambda.untagged_plan sw with | Some plan -> let compile e = - compile_untagged_plan ~cxt ~switch_exp:e ~fallback:sw_failaction - plan + compile_untagged_plan ~cxt ~switch_exp:e ~sw_loc + ~fallback:sw_failaction plan in if payload_only then compile e else with_variable compile | None -> if payload_only then - compile_cases ~cxt ~switch_exp:(E.tag ~name:tag_name e) + compile_cases ~cxt ~switch_exp:(E.tag ~name:tag_name e) ~sw_loc ~default:sw_blocks_default sw_blocks else if sw_blocks_full && sw_blocks = [] then - compile_cases ~cxt ~switch_exp:e ~default:sw_num_default sw_consts + compile_cases ~cxt ~switch_exp:e ~sw_loc ~default:sw_num_default + sw_consts else with_variable (fun e -> [ - S.if_ + S.if_ ?source_loc:sw_source_loc (E.is_int_tag ~literal_tags:literal_cases e) - (compile_cases ~cxt ~switch_exp:e ~default:sw_num_default - sw_consts) + (compile_cases ~cxt ~switch_exp:e ~sw_loc + ~default:sw_num_default sw_consts) ~else_: (compile_cases ~cxt ~switch_exp:(E.tag ~name:tag_name e) - ~default:sw_blocks_default sw_blocks); + ~sw_loc ~default:sw_blocks_default sw_blocks); ])) in match lambda_cxt.continuation with @@ -1076,19 +1138,22 @@ let compile output_prefix = (S.declare_variable ~kind id :: compile_whole {lambda_cxt with continuation = Assign id}) | EffectCall _ | Assign _ -> Js_output.make (compile_whole lambda_cxt) - and compile_string_cases ~cxt ~switch_exp ~default cases : initialization = + and compile_string_cases ~cxt ~switch_exp ~sw_loc ~default cases : + initialization = cases |> compile_general_cases ~make_exp:E.tag_type ~eq_exp:(fun _ x _ y -> E.string_equal x y) ~cxt - ~switch:(fun ?default ?declaration e clauses -> - S.string_switch ?default ?declaration e clauses) - ~switch_exp ~default - and compile_untagged_plan ~(cxt : Lam_compile_context.t) ~switch_exp ~fallback - (plan : Lambda.t Untagged_dispatch.tree) : J.block = + ~switch:(fun ?source_loc ?default ?declaration e clauses -> + S.string_switch ?source_loc ?default ?declaration e clauses) + ~switch_exp ~sw_loc ~default + and compile_untagged_plan ~(cxt : Lam_compile_context.t) ~switch_exp ~sw_loc + ~fallback (plan : (Lambda.t * Lambda.branch_loc) Untagged_dispatch.tree) : + J.block = (* Prints the plan: each node is one statement. A body in a [switch] statement is compiled in a [switch] context, a body of an [if] is not *) + let sw_source_loc = source_map_loc sw_loc in let e = switch_exp in let rec test_exp : Untagged_dispatch.test -> J.expression = function | Equals literal -> E.string_equal e (E.tag_type (Literal literal)) @@ -1104,9 +1169,14 @@ let compile output_prefix = | And (test1, test2) -> E.and_ (test_exp test1) (test_exp test2) | Or (test1, test2) -> E.or_ (test_exp test1) (test_exp test2) in - let output_block cxt lam = + let output_block cxt (lam, arm_loc) = compile_lambda cxt lam |> Js_output.output_as_block - |> with_block_source_loc lam + |> with_branch_block_source_loc arm_loc lam + in + let case_source_loc (lam, arm_loc) = + match source_map_case_loc arm_loc with + | Some _ as loc -> loc + | None -> source_map_loc_of_lam lam in (* The default action is compiled once and shared by every path to it *) let fallback_blocks = ref [] in @@ -1117,15 +1187,17 @@ let compile output_prefix = | None -> let block = match fallback with - | Some lam -> output_block cxt lam + | Some arm -> output_block cxt arm | None -> assert false in fallback_blocks := (in_switch, block) :: !fallback_blocks; block in - let rec emit ~cxt (tree : Lambda.t Untagged_dispatch.tree) : J.block = + let rec emit ~cxt + (tree : (Lambda.t * Lambda.branch_loc) Untagged_dispatch.tree) : J.block + = match tree with - | Run lam -> output_block cxt lam + | Run arm -> output_block cxt arm | Fallback -> fallback_block cxt | Skip -> [] | If (test, then_, else_) -> @@ -1133,7 +1205,7 @@ let compile output_prefix = loop labels top to bottom *) let then_ = emit ~cxt then_ in let else_ = emit ~cxt else_ in - [S.if_ (test_exp test) then_ ~else_] + [S.if_ ?source_loc:sw_source_loc (test_exp test) then_ ~else_] | Block tree -> [S.block (emit ~cxt tree)] | Switch_value (clauses, default) -> let cxt = Lam_compile_context.enter_switch cxt in @@ -1148,12 +1220,16 @@ let compile output_prefix = (Variant_runtime.Literal literal, emit_clause ~cxt clause)) clauses in - [S.string_switch ?default e clauses] + [S.string_switch ?source_loc:sw_source_loc ?default e clauses] | Switch_typeof ([(block_type, (Body _ as clause))], default) -> (* One kind is an [if], so its bodies are not in a [switch] *) let clause = emit_clause ~cxt clause in let default = emit ~cxt default in - [S.if_ (test_exp (Typeof block_type)) clause.switch_body ~else_:default] + [ + S.if_ ?source_loc:sw_source_loc + (test_exp (Typeof block_type)) + clause.switch_body ~else_:default; + ] | Switch_typeof (clauses, default) -> let cxt = Lam_compile_context.enter_switch cxt in let default = emit ~cxt default in @@ -1163,18 +1239,21 @@ let compile output_prefix = (Variant_runtime.Payload_shape block_type, emit_clause ~cxt clause)) clauses in - [S.string_switch ~default (E.typeof e) clauses] - and emit_clause ~cxt (clause : Lambda.t Untagged_dispatch.clause) : + [ + S.string_switch ?source_loc:sw_source_loc ~default (E.typeof e) clauses; + ] + and emit_clause ~cxt + (clause : (Lambda.t * Lambda.branch_loc) Untagged_dispatch.clause) : J.case_clause = match clause with - | Falls_through lam -> + | Falls_through arm -> { switch_body = []; should_break = false; comment = None; - source_loc = Option.bind lam source_map_loc_of_lam; + source_loc = Option.bind arm case_source_loc; } - | Body (Run lam) -> + | Body (Run (lam, arm_loc)) -> let switch_body, should_break = Js_output.to_break_block (compile_lambda cxt lam) in @@ -1184,10 +1263,10 @@ let compile output_prefix = else should_break && Lam_exit_code.has_exit lam in { - switch_body = with_block_source_loc lam switch_body; + switch_body = with_branch_block_source_loc arm_loc lam switch_body; should_break; comment = None; - source_loc = source_map_loc_of_lam lam; + source_loc = case_source_loc (lam, arm_loc); } | Body Fallback -> let block = fallback_block cxt in @@ -1195,20 +1274,22 @@ let compile output_prefix = switch_body = block; should_break = not (S.block_last_is_return_throw_or_continue block); comment = None; - source_loc = None; + source_loc = Option.bind fallback case_source_loc; } | Body (Skip | If _ | Block _ | Switch_value _ | Switch_typeof _) -> assert false in emit ~cxt plan - and compile_stringswitch l cases default (lambda_cxt : Lam_compile_context.t) - = + and compile_stringswitch l cases default sw_loc + (lambda_cxt : Lam_compile_context.t) = (* TODO might better optimization according to the number of cases Be careful: we should avoid multiple evaluation of l, The [gen] can be elimiated when number of [cases] is less than 3 *) let cases = - cases |> List.map (fun (s, l) -> (Variant_runtime.Literal (String s), l)) + cases + |> List.map (fun (s, l, arm_loc) -> + (Variant_runtime.Literal (String s), l, arm_loc)) in match compile_lambda {lambda_cxt with continuation = NeedValue Not_tail} l @@ -1219,7 +1300,7 @@ let compile output_prefix = otherwise it's ok *) let default = match default with - | Some x -> Default x + | Some (x, arm_loc) -> Default (x, arm_loc) | None -> Complete in match lambda_cxt.continuation with @@ -1230,13 +1311,13 @@ let compile output_prefix = (List.append block (compile_string_cases ~cxt:{lambda_cxt with continuation = Declare (Variable, v)} - ~switch_exp:e ~default cases)) + ~switch_exp:e ~sw_loc ~default cases)) ~value:(E.var v) | _ -> Js_output.make (List.append block - (compile_string_cases ~cxt:lambda_cxt ~switch_exp:e ~default cases)) - ) + (compile_string_cases ~cxt:lambda_cxt ~switch_exp:e ~sw_loc + ~default cases))) (* This should be optimized in lambda layer (let (match/1038 = (apply g/1027 x/1028)) @@ -1306,7 +1387,7 @@ let compile output_prefix = [code_table] ) (* tail position and only one exit code *) when Lam_compile_context.no_static_raise_in_handler code_table -> - let jmp_table, handler = + let jmp_table, (handler, handler_loc) = Lam_compile_context.add_pseudo_jmp lambda_cxt.jmp_table exit_id code_table in @@ -1324,15 +1405,26 @@ let compile output_prefix = (fun x -> S.declare_variable ~kind:Variable x) code_table.bindings in + let handler_output = + let out = compile_lambda lambda_cxt handler in + let block = + with_branch_block_source_loc handler_loc handler + (Js_output.output_as_block out) + in + Js_output.make block ~output_finished:out.output_finished + in Js_output.append_output (Js_output.make declares) - (Js_output.append_output lbody (compile_lambda lambda_cxt handler)) + (Js_output.append_output lbody handler_output) | _ -> ( let exit_expr = E.var exit_id in let jmp_table, handlers = Lam_compile_context.add_jmps lambda_cxt.jmp_table exit_id code_table in let handlers = - List.map (fun (i, handler) -> (Lambda.Switch_int i, handler)) handlers + List.map + (fun (i, handler, handler_loc) -> + (Lambda.Switch_int i, handler, handler_loc)) + handlers in (* Declaration First, body and handler have the same value *) @@ -1681,7 +1773,19 @@ let compile output_prefix = (aux lambda_cxt {lambda_cxt with continuation = EffectCall new_return_type}) and compile_ifthenelse (predicate : Lambda.t) (t_branch : Lambda.t) - (f_branch : Lambda.t) (lambda_cxt : Lam_compile_context.t) = + (f_branch : Lambda.t) ({if_loc; then_loc; else_loc} : Lambda.if_locs) + (lambda_cxt : Lam_compile_context.t) = + let if_source_loc = source_map_loc if_loc in + let then_source_loc = source_map_body_loc then_loc in + let else_source_loc = source_map_body_loc else_loc in + let branch_block arm_loc lam out = + Js_output.output_as_block out |> with_branch_block_source_loc arm_loc lam + in + let econd_with_locs e out1 out2 = + E.econd ?source_loc:if_source_loc e + (with_exp_source_loc_opt then_source_loc out1) + (with_exp_source_loc_opt else_source_loc out2) + in match compile_lambda {lambda_cxt with continuation = NeedValue Not_tail} @@ -1697,7 +1801,7 @@ let compile output_prefix = with | {block = []; value = Some out1}, {block = []; value = Some out2} -> (* speical optimization *) - Js_output.make b ~value:(E.econd e out1 out2) + Js_output.make b ~value:(econd_with_locs e out1 out2) | _, _ -> ( (* we can not reuse -- here we need they have the same name, TODO: could be optimized by inspecting assigment statement *) @@ -1712,9 +1816,9 @@ let compile output_prefix = (List.append (S.declare_variable ~kind:Variable id :: b) [ - S.if_ e - (Js_output.output_as_block out1) - ~else_:(Js_output.output_as_block out2); + S.if_ ?source_loc:if_source_loc e + (branch_block then_loc t_branch out1) + ~else_:(branch_block else_loc f_branch out2); ]) ~value:(E.var id))) | Declare (kind, id) -> ( @@ -1725,30 +1829,37 @@ let compile output_prefix = with | {block = []; value = Some out1}, {block = []; value = Some out2} -> (* Invariant: should_return is false*) - Js_output.make (b @ [S.define_variable ~kind id (E.econd e out1 out2)]) + Js_output.make + (b + @ [ + with_statement_source_loc if_source_loc + (S.define_variable ~kind id (econd_with_locs e out1 out2)); + ]) | _, _ -> Js_output.make (b @ [ - S.if_ ~declaration:(kind, id) e - (Js_output.output_as_block - @@ compile_lambda - {lambda_cxt with continuation = Assign id} - t_branch) + S.if_ ?source_loc:if_source_loc ~declaration:(kind, id) e + (branch_block then_loc t_branch + (compile_lambda + {lambda_cxt with continuation = Assign id} + t_branch)) ~else_: - (Js_output.output_as_block - @@ compile_lambda - {lambda_cxt with continuation = Assign id} - f_branch); + (branch_block else_loc f_branch + (compile_lambda + {lambda_cxt with continuation = Assign id} + f_branch)); ])) | Assign _ -> let then_output = - Js_output.output_as_block (compile_lambda lambda_cxt t_branch) + branch_block then_loc t_branch (compile_lambda lambda_cxt t_branch) in let else_output = - Js_output.output_as_block (compile_lambda lambda_cxt f_branch) + branch_block else_loc f_branch (compile_lambda lambda_cxt f_branch) in - Js_output.make (b @ [S.if_ e then_output ~else_:else_output]) + Js_output.make + (b + @ [S.if_ ?source_loc:if_source_loc e then_output ~else_:else_output]) | EffectCall should_return -> ( let context1 = {lambda_cxt with continuation = NeedValue should_return} @@ -1766,13 +1877,25 @@ let compile output_prefix = ( Js_exp_make.remove_pure_sub_exp out1, Js_exp_make.remove_pure_sub_exp out2 ) with - | None, None -> Js_output.make (b @ [S.if_ e []]) + | None, None -> + Js_output.make (b @ [S.if_ ?source_loc:if_source_loc e []]) (* FIX #1762 *) | Some out1, Some out2 -> - Js_output.make b ~value:(E.econd e out1 out2) - | Some out1, None -> Js_output.make (b @ [S.if_ e [S.exp out1]]) + Js_output.make b ~value:(econd_with_locs e out1 out2) + | Some out1, None -> + Js_output.make + (b + @ [ + S.if_ ?source_loc:if_source_loc e + [with_statement_source_loc then_source_loc (S.exp out1)]; + ]) | None, Some out2 -> - Js_output.make (b @ [S.if_ (E.not e) [S.exp out2]])) + Js_output.make + (b + @ [ + S.if_ ?source_loc:if_source_loc (E.not e) + [with_statement_source_loc else_source_loc (S.exp out2)]; + ])) | Not_tail, {block = []; value = Some out1}, _ -> (* assert branch TODO: here we re-compile two branches since @@ -1782,33 +1905,34 @@ let compile output_prefix = Js_output.make (List.append b [ - S.if_ (E.not e) - (Js_output.output_as_block - @@ compile_lambda lambda_cxt f_branch); + S.if_ ?source_loc:if_source_loc (E.not e) + (branch_block else_loc f_branch + (compile_lambda lambda_cxt f_branch)); ]) else Js_output.make (List.append b [ - S.if_ e - (Js_output.output_as_block - @@ compile_lambda lambda_cxt t_branch) + S.if_ ?source_loc:if_source_loc e + (branch_block then_loc t_branch + (compile_lambda lambda_cxt t_branch)) ~else_: - (Js_output.output_as_block - @@ compile_lambda lambda_cxt f_branch); + (branch_block else_loc f_branch + (compile_lambda lambda_cxt f_branch)); ]) | Not_tail, _, {block = []; value = Some out2} -> let else_ = if Js_analyzer.no_side_effect_expression out2 then None else Some - (Js_output.output_as_block (compile_lambda lambda_cxt f_branch)) + (branch_block else_loc f_branch + (compile_lambda lambda_cxt f_branch)) in Js_output.make (b @ [ - S.if_ e - (Js_output.output_as_block + S.if_ ?source_loc:if_source_loc e + (branch_block then_loc t_branch (compile_lambda lambda_cxt t_branch)) ?else_; ]) @@ -1816,16 +1940,25 @@ let compile output_prefix = {block = []; value = Some out1}, {block = []; value = Some out2} ) -> Js_output.make - (b @ [S.return_stmt (E.econd e out1 out2)]) + (b + @ [ + { + (S.return_stmt (econd_with_locs e out1 out2)) with + source_loc = if_source_loc; + }; + ]) ~output_finished:True | _, _, _ -> let then_output = - Js_output.output_as_block (compile_lambda lambda_cxt t_branch) + branch_block then_loc t_branch (compile_lambda lambda_cxt t_branch) in let else_output = - Js_output.output_as_block (compile_lambda lambda_cxt f_branch) + branch_block else_loc f_branch (compile_lambda lambda_cxt f_branch) in - Js_output.make (b @ [S.if_ e then_output ~else_:else_output]))) + Js_output.make + (b + @ [S.if_ ?source_loc:if_source_loc e then_output ~else_:else_output] + ))) and compile_apply (appinfo : Lambda.lambda_apply) (lambda_cxt : Lam_compile_context.t) = match appinfo with @@ -2350,10 +2483,10 @@ let compile output_prefix = in let output_l2 = compile_lambda lambda_cxt l2 in Js_output.append_output output_l1 output_l2 - | Lifthenelse (predicate, t_branch, f_branch) -> - compile_ifthenelse predicate t_branch f_branch lambda_cxt - | Lstringswitch (l, cases, default) -> - compile_stringswitch l cases default lambda_cxt + | Lifthenelse (predicate, t_branch, f_branch, locs) -> + compile_ifthenelse predicate t_branch f_branch locs lambda_cxt + | Lstringswitch (l, cases, default, loc) -> + compile_stringswitch l cases default loc lambda_cxt | Lswitch (switch_arg, sw) -> compile_switch switch_arg sw lambda_cxt | Lstaticraise (i, largs) -> compile_staticraise i largs lambda_cxt | Lstaticcatch _ -> compile_staticcatch cur_lam lambda_cxt diff --git a/compiler/backend/lam_compile_context.ml b/compiler/backend/lam_compile_context.ml index 923b6fe2249..e629368ae00 100644 --- a/compiler/backend/lam_compile_context.ml +++ b/compiler/backend/lam_compile_context.ml @@ -100,7 +100,12 @@ let ensure_loop_label cxt frame = frame.label <- Some label; label -type handler = {label: jbl_label; handler: Lambda.t; bindings: Ident.t list} +type handler = { + label: jbl_label; + handler: Lambda.t; + handler_loc: Lambda.branch_loc; + bindings: Ident.t list; +} let no_static_raise_in_handler (x : handler) : bool = not (Lam_exit_code.has_exit_code x.handler (fun _code -> true)) @@ -112,22 +117,22 @@ let no_static_raise_in_handler (x : handler) : bool = [handlers] is used for compiling [staticcatch] *) let add_jmps (m : jmp_table) (exit_id : Ident.t) (code_table : handler list) : - jmp_table * (int * Lambda.t) list = + jmp_table * (int * Lambda.t * Lambda.branch_loc) list = let map, handlers = Ext_list.fold_left_with_offset code_table (m, []) (Handler_map.cardinal m + 1) - (fun {label; handler; bindings} (acc, handlers) order_id -> + (fun {label; handler; handler_loc; bindings} (acc, handlers) order_id -> ( Handler_map.add label {exit_id; bindings; order_id} acc, - (order_id, handler) :: handlers )) + (order_id, handler, handler_loc) :: handlers )) in (map, List.rev handlers) let add_pseudo_jmp (m : jmp_table) (exit_id : Ident.t) (* TODO not needed, remove it later *) - (code_table : handler) : jmp_table * Lambda.t = + (code_table : handler) : jmp_table * (Lambda.t * Lambda.branch_loc) = ( Handler_map.add code_table.label {exit_id; bindings = code_table.bindings; order_id = -1} m, - code_table.handler ) + (code_table.handler, code_table.handler_loc) ) let find_exn cxt i = Map_int.find i cxt.jmp_table diff --git a/compiler/backend/lam_compile_context.mli b/compiler/backend/lam_compile_context.mli index f19f9496f65..cfafb695c2e 100644 --- a/compiler/backend/lam_compile_context.mli +++ b/compiler/backend/lam_compile_context.mli @@ -82,7 +82,12 @@ val enter_switch : t -> t val push_loop : t -> t * loop_frame val ensure_loop_label : t -> loop_frame -> J.label -type handler = {label: jbl_label; handler: Lambda.t; bindings: Ident.t list} +type handler = { + label: jbl_label; + handler: Lambda.t; + handler_loc: Lambda.branch_loc; + bindings: Ident.t list; +} val no_static_raise_in_handler : handler -> bool @@ -90,8 +95,9 @@ val add_jmps : jmp_table -> Ident.t -> handler list -> - jmp_table * (jbl_label * Lambda.t) list + jmp_table * (jbl_label * Lambda.t * Lambda.branch_loc) list -val add_pseudo_jmp : jmp_table -> Ident.t -> handler -> jmp_table * Lambda.t +val add_pseudo_jmp : + jmp_table -> Ident.t -> handler -> jmp_table * (Lambda.t * Lambda.branch_loc) val find_exn : t -> jbl_label -> value diff --git a/compiler/backend/lam_exit_count.ml b/compiler/backend/lam_exit_count.ml index 061fdc96c71..ce38b8f114f 100644 --- a/compiler/backend/lam_exit_count.ml +++ b/compiler/backend/lam_exit_count.ml @@ -68,13 +68,13 @@ let count_helper (lam : Lambda.t) : collection option = | Lstaticraise (i, ls) -> incr_exit exits i; List.iter count ls - | Lstaticcatch (l1, (i, _), l2) -> + | Lstaticcatch (l1, (i, _), l2, _) -> count l1; if count_exit exits i > 0 then count l2 - | Lstringswitch (l, sw, d) -> + | Lstringswitch (l, sw, d, _) -> count l; - Ext_list.iter_snd sw count; - Option.iter count d + List.iter (fun (_, e, _) -> count e) sw; + Option.iter (fun (e, _) -> count e) d | Lglobal_module _ | Lvar _ | Lconst _ -> () | Lapply {ap_func; ap_args; _} -> count ap_func; @@ -90,12 +90,12 @@ let count_helper (lam : Lambda.t) : collection option = | Lswitch (l, sw) -> count_default sw; count l; - Ext_list.iter_snd sw.sw_consts count; - Ext_list.iter_snd sw.sw_blocks count + List.iter (fun (_, e, _) -> count e) sw.sw_consts; + List.iter (fun (_, e, _) -> count e) sw.sw_blocks | Ltrywith (l1, _, l2) | Ltryfinally (l1, l2) -> count l1; count l2 - | Lifthenelse (l1, l2, l3) -> + | Lifthenelse (l1, l2, l3, _) -> count l1; count l2; count l3 @@ -120,7 +120,7 @@ let count_helper (lam : Lambda.t) : collection option = and count_default sw = match sw.sw_failaction with | None -> () - | Some al -> + | Some (al, _) -> if (not sw.sw_consts_full) && not sw.sw_blocks_full then ( count al; count al) diff --git a/compiler/backend/lam_hit.ml b/compiler/backend/lam_hit.ml index e75d2a5deb5..477f106064d 100644 --- a/compiler/backend/lam_hit.ml +++ b/compiler/backend/lam_hit.ml @@ -25,11 +25,7 @@ type t = Lambda.t let hit_variables (fv : Set_ident.t) (l : t) : bool = - let rec hit_opt (x : t option) = - match x with - | None -> false - | Some a -> hit a - and hit_var (id : Ident.t) = Set_ident.mem id fv + let rec hit_var (id : Ident.t) = Set_ident.mem id fv and hit_list_snd : 'a. ('a * t) list -> bool = fun x -> Ext_list.exists_snd x hit and hit_list xs = List.exists hit xs @@ -37,7 +33,7 @@ let hit_variables (fv : Set_ident.t) (l : t) : bool = match (l : t) with | Lvar id -> hit_var id | Lassign (id, e) -> hit_var id || hit e - | Lstaticcatch (e1, (_, _vars), e2) -> hit e1 || hit e2 + | Lstaticcatch (e1, (_, _vars), e2, _) -> hit e1 || hit e2 | Ltrywith (e1, _, e2) | Ltryfinally (e1, e2) -> hit e1 || hit e2 | Lfunction {body; params = _} -> hit body | Llet (_str, _id, arg, body) -> hit arg || hit body @@ -49,12 +45,16 @@ let hit_variables (fv : Set_ident.t) (l : t) : bool = | Lglobal_module _ (* global persistent module, play safe *) -> false | Lprim {args; _} -> hit_list args | Lswitch (arg, sw) -> - hit arg || hit_list_snd sw.sw_consts || hit_list_snd sw.sw_blocks - || hit_opt sw.sw_failaction - | Lstringswitch (arg, cases, default) -> - hit arg || hit_list_snd cases || hit_opt default + hit arg + || List.exists (fun (_, e, _) -> hit e) sw.sw_consts + || List.exists (fun (_, e, _) -> hit e) sw.sw_blocks + || Option.fold ~none:false ~some:(fun (e, _) -> hit e) sw.sw_failaction + | Lstringswitch (arg, cases, default, _) -> + hit arg + || List.exists (fun (_, e, _) -> hit e) cases + || Option.fold ~none:false ~some:(fun (e, _) -> hit e) default | Lstaticraise (_, args) -> hit_list args - | Lifthenelse (e1, e2, e3) -> hit e1 || hit e2 || hit e3 + | Lifthenelse (e1, e2, e3, _) -> hit e1 || hit e2 || hit e3 | Lsequence (e1, e2) -> hit e1 || hit e2 | Lbreak | Lcontinue -> false | Lwhile (e1, e2) -> hit e1 || hit e2 @@ -62,11 +62,7 @@ let hit_variables (fv : Set_ident.t) (l : t) : bool = hit l let hit_variable (fv : Ident.t) (l : t) : bool = - let rec hit_opt (x : t option) = - match x with - | None -> false - | Some a -> hit a - and hit_var (id : Ident.t) = Ident.same id fv + let rec hit_var (id : Ident.t) = Ident.same id fv and hit_list_snd : 'a. ('a * t) list -> bool = fun x -> Ext_list.exists_snd x hit and hit_list xs = List.exists hit xs @@ -74,7 +70,7 @@ let hit_variable (fv : Ident.t) (l : t) : bool = match (l : t) with | Lvar id -> hit_var id | Lassign (id, e) -> hit_var id || hit e - | Lstaticcatch (e1, (_, _vars), e2) -> hit e1 || hit e2 + | Lstaticcatch (e1, (_, _vars), e2, _) -> hit e1 || hit e2 | Ltrywith (e1, _, e2) | Ltryfinally (e1, e2) -> hit e1 || hit e2 | Lfunction {body; params = _} -> hit body | Llet (_str, _id, arg, body) -> hit arg || hit body @@ -86,12 +82,16 @@ let hit_variable (fv : Ident.t) (l : t) : bool = | Lglobal_module _ (* global persistent module, play safe *) -> false | Lprim {args; _} -> hit_list args | Lswitch (arg, sw) -> - hit arg || hit_list_snd sw.sw_consts || hit_list_snd sw.sw_blocks - || hit_opt sw.sw_failaction - | Lstringswitch (arg, cases, default) -> - hit arg || hit_list_snd cases || hit_opt default + hit arg + || List.exists (fun (_, e, _) -> hit e) sw.sw_consts + || List.exists (fun (_, e, _) -> hit e) sw.sw_blocks + || Option.fold ~none:false ~some:(fun (e, _) -> hit e) sw.sw_failaction + | Lstringswitch (arg, cases, default, _) -> + hit arg + || List.exists (fun (_, e, _) -> hit e) cases + || Option.fold ~none:false ~some:(fun (e, _) -> hit e) default | Lstaticraise (_, args) -> hit_list args - | Lifthenelse (e1, e2, e3) -> hit e1 || hit e2 || hit e3 + | Lifthenelse (e1, e2, e3, _) -> hit e1 || hit e2 || hit e3 | Lsequence (e1, e2) -> hit e1 || hit e2 | Lbreak | Lcontinue -> false | Lwhile (e1, e2) -> hit e1 || hit e2 diff --git a/compiler/backend/lam_pass_collect.ml b/compiler/backend/lam_pass_collect.ml index d667ef7fcda..f1899d631cd 100644 --- a/compiler/backend/lam_pass_collect.ml +++ b/compiler/backend/lam_pass_collect.ml @@ -108,21 +108,21 @@ let collect_info (meta : Lam_stats.t) (lam : Lambda.t) = | Lprim {args; _} -> List.iter collect args | Lswitch (l, {sw_failaction; sw_consts; sw_blocks}) -> collect l; - Ext_list.iter_snd sw_consts collect; - Ext_list.iter_snd sw_blocks collect; - Option.iter collect sw_failaction - | Lstringswitch (l, sw, d) -> + List.iter (fun (_, e, _) -> collect e) sw_consts; + List.iter (fun (_, e, _) -> collect e) sw_blocks; + Option.iter (fun (e, _) -> collect e) sw_failaction + | Lstringswitch (l, sw, d, _) -> collect l; - Ext_list.iter_snd sw collect; - Option.iter collect d + List.iter (fun (_, e, _) -> collect e) sw; + Option.iter (fun (e, _) -> collect e) d | Lstaticraise (_code, ls) -> List.iter collect ls - | Lstaticcatch (l1, (_, _), l2) -> + | Lstaticcatch (l1, (_, _), l2, _) -> collect l1; collect l2 | Ltrywith (l1, _, l2) | Ltryfinally (l1, l2) -> collect l1; collect l2 - | Lifthenelse (l1, l2, l3) -> + | Lifthenelse (l1, l2, l3, _) -> collect l1; collect l2; collect l3 diff --git a/compiler/backend/lam_pass_count.ml b/compiler/backend/lam_pass_count.ml index 0df8167adde..a56b2efbfe7 100644 --- a/compiler/backend/lam_pass_count.ml +++ b/compiler/backend/lam_pass_count.ml @@ -147,13 +147,13 @@ let collect_occurs ~assignable lam : occ_tbl = | Lswitch (l, sw) -> count_default bv sw; count bv l; - List.iter (fun (_, l) -> count bv l) sw.sw_consts; - List.iter (fun (_, l) -> count bv l) sw.sw_blocks - | Lstringswitch (l, sw, d) -> ( + List.iter (fun (_, l, _) -> count bv l) sw.sw_consts; + List.iter (fun (_, l, _) -> count bv l) sw.sw_blocks + | Lstringswitch (l, sw, d, _) -> ( count bv l; - List.iter (fun (_, l) -> count bv l) sw; + List.iter (fun (_, l, _) -> count bv l) sw; match d with - | Some d -> count bv d + | Some (d, _) -> count bv d | None -> ()) (* x2 for native backend *) (* begin match sw with *) @@ -161,13 +161,13 @@ let collect_occurs ~assignable lam : occ_tbl = (* | _ -> count bv d ; count bv d *) (* end *) | Lstaticraise (_i, ls) -> List.iter (count bv) ls - | Lstaticcatch (l1, (_i, _), l2) -> + | Lstaticcatch (l1, (_i, _), l2, _) -> count bv l1; count bv l2 | Ltrywith (l1, _, l2) | Ltryfinally (l1, l2) -> count bv l1; count bv l2 - | Lifthenelse (l1, l2, l3) -> + | Lifthenelse (l1, l2, l3, _) -> count bv l1; count bv l2; count bv l3 @@ -178,7 +178,7 @@ let collect_occurs ~assignable lam : occ_tbl = and count_default bv sw = match sw.sw_failaction with | None -> () - | Some al -> + | Some (al, _) -> if (not sw.sw_consts_full) && not sw.sw_blocks_full then ( (* default action will occur twice in native code *) count bv al; diff --git a/compiler/backend/lam_pass_exits.ml b/compiler/backend/lam_pass_exits.ml index a2fadf34352..c9d39901c69 100644 --- a/compiler/backend/lam_pass_exits.ml +++ b/compiler/backend/lam_pass_exits.ml @@ -21,13 +21,13 @@ *) let rec no_list args = List.for_all no_bounded_variables args -and no_list_snd : 'a. ('a * Lambda.t) list -> bool = - fun args -> Ext_list.for_all_snd args no_bounded_variables +and no_list_cases : 'a. ('a * Lambda.t * Lambda.branch_loc) list -> bool = + fun args -> List.for_all (fun (_, l, _) -> no_bounded_variables l) args -and no_opt x = +and no_opt_branch x = match x with | None -> true - | Some a -> no_bounded_variables a + | Some (a, _) -> no_bounded_variables a and no_bounded_variables (l : Lambda.t) = match l with @@ -39,18 +39,19 @@ and no_bounded_variables (l : Lambda.t) = | Lglobal_module _ -> true | Lprim {args; primitive = _} -> no_list args | Lswitch (arg, sw) -> - no_bounded_variables arg && no_list_snd sw.sw_consts - && no_list_snd sw.sw_blocks && no_opt sw.sw_failaction - | Lstringswitch (arg, cases, default) -> - no_bounded_variables arg && no_list_snd cases && no_opt default + no_bounded_variables arg && no_list_cases sw.sw_consts + && no_list_cases sw.sw_blocks + && no_opt_branch sw.sw_failaction + | Lstringswitch (arg, cases, default, _) -> + no_bounded_variables arg && no_list_cases cases && no_opt_branch default | Lstaticraise (_, args) -> no_list args - | Lifthenelse (e1, e2, e3) -> + | Lifthenelse (e1, e2, e3, _) -> no_bounded_variables e1 && no_bounded_variables e2 && no_bounded_variables e3 | Lsequence (e1, e2) -> no_bounded_variables e1 && no_bounded_variables e2 | Lbreak | Lcontinue -> true | Lwhile (e1, e2) -> no_bounded_variables e1 && no_bounded_variables e2 - | Lstaticcatch (e1, (_, vars), e2) -> + | Lstaticcatch (e1, (_, vars), e2, _) -> vars = [] && no_bounded_variables e1 && no_bounded_variables e2 | Lfunction {body; params} -> params = [] && no_bounded_variables body | Lfor _ -> false @@ -78,17 +79,17 @@ and no_bounded_variables (l : Lambda.t) = ]} *) +type lam_subst = {lam: Lambda.t; loc: Lambda.branch_loc} (** The third argument is its occurrence, when do the substitution, if its occurence is > 1, we should refresh *) -type lam_subst = Id of Lambda.t [@@unboxed] type subst_tbl = (Ident.t list * lam_subst) Hash_int.t -let to_lam x = - match x with - | Id x -> x +let pick_branch_loc (existing : Lambda.branch_loc) (inlined : Lambda.branch_loc) + = + if Lambda.has_branch_loc existing then existing else inlined (** Simplify ``catch body with (i ...) handler'' @@ -152,21 +153,45 @@ let to_lam x = let subst_helper (subst : subst_tbl) (query : int -> int) (lam : Lambda.t) : Lambda.t = - let rec simplif (lam : Lambda.t) = + let rec simplif_cases : + 'a. + ('a * Lambda.t * Lambda.branch_loc) list -> + ('a * Lambda.t * Lambda.branch_loc) list = + fun cases -> + match cases with + | [] -> cases + | (k, arm, loc) :: tl -> + let arm', inlined_loc = simplif_with_loc arm in + let loc' = pick_branch_loc loc inlined_loc in + let tl' = simplif_cases tl in + if arm' == arm && loc' == loc && tl' == tl then cases + else (k, arm', loc') :: tl' + and simplif_opt_branch = function + | None -> None + | Some (arm, loc) as opt -> + let arm', inlined_loc = simplif_with_loc arm in + let loc' = pick_branch_loc loc inlined_loc in + if arm' == arm && loc' == loc then opt else Some (arm', loc') + and simplif_with_loc (lam : Lambda.t) : Lambda.t * Lambda.branch_loc = match lam with - | Lstaticcatch (l1, (i, xs), l2) -> ( + | Lstaticcatch (l1, (i, xs), l2, handler_loc) -> ( let i_occur = query i in match (i_occur, l2) with - | 0, _ -> simplif l1 + | 0, _ -> simplif_with_loc l1 | _, Lvar _ | _, Lconst _ (* when i >= 0 # 2316 *) -> - Hash_int.add subst i (xs, Id (simplif l2)); - simplif l1 (* l1 will inline *) + let l2', inlined_loc = simplif_with_loc l2 in + let loc = pick_branch_loc handler_loc inlined_loc in + Hash_int.add subst i (xs, {lam = l2'; loc}); + simplif_with_loc l1 (* l1 will inline *) | 1, _ when i >= 0 -> (* Ask: Note that we have predicate i >=0 *) - Hash_int.add subst i (xs, Id (simplif l2)); - simplif l1 (* l1 will inline *) + let l2', inlined_loc = simplif_with_loc l2 in + let loc = pick_branch_loc handler_loc inlined_loc in + Hash_int.add subst i (xs, {lam = l2'; loc}); + simplif_with_loc l1 (* l1 will inline *) | _ -> - let l2' = simplif l2 in + let l2', inlined_loc = simplif_with_loc l2 in + let handler_loc' = pick_branch_loc handler_loc inlined_loc in (* we only inline when [l2] does not contain bound variables no need to refresh *) @@ -180,34 +205,81 @@ let subst_helper (subst : subst_tbl) (query : int -> int) (lam : Lambda.t) : || lam_size < 5 in if ok_to_inline then ( - Hash_int.add subst i (xs, Id l2'); - simplif l1) + Hash_int.add subst i (xs, {lam = l2'; loc = handler_loc'}); + simplif_with_loc l1) else - let l1' = simplif l1 in - if l1' == l1 && l2' == l2 then lam - else Lambda.staticcatch l1' (i, xs) l2') + let l1', loc1 = simplif_with_loc l1 in + if l1' == l1 && l2' == l2 && handler_loc' == handler_loc then + (lam, loc1) + else (Lambda.staticcatch ~loc:handler_loc' l1' (i, xs) l2', loc1)) | Lstaticraise (i, []) -> ( match Hash_int.find_opt subst i with - | Some (_, handler) -> to_lam handler - | None -> lam) + | Some (_, {lam = handler; loc}) -> (handler, loc) + | None -> (lam, Lambda.no_branch_loc)) | Lstaticraise (i, ls) -> ( let ls' = Ext_list.map_sharing ls simplif in match Hash_int.find_opt subst i with - | Some (xs, handler) -> - let handler = to_lam handler in + | Some (xs, {lam = handler; loc}) -> let ys = List.map Ident.rename xs in let env = List.fold_right2 (fun x y t -> Ident.add x (Lambda.var y) t) xs ys Ident.empty in - List.fold_right2 - (fun y l r -> Lambda.let_ Strict y l r) - ys ls' - (Lambda_traverse.subst_lambda env handler) - | None -> if ls' == ls then lam else Lambda.staticraise i ls') - | _ -> Lambda_traverse.shallow_map_sharing simplif lam - in + ( List.fold_right2 + (fun y l r -> Lambda.let_ Strict y l r) + ys ls' + (Lambda_traverse.subst_lambda env handler), + loc ) + | None -> + ( (if ls' == ls then lam else Lambda.staticraise i ls'), + Lambda.no_branch_loc )) + | Llet (kind, id, e, body) -> + let e' = simplif e in + let body', loc = simplif_with_loc body in + if e' == e && body' == body then (lam, loc) + else (Lambda.let_ kind id e' body', loc) + | Lifthenelse (a, b, c, {if_loc; then_loc; else_loc}) -> + let a' = simplif a in + let b', inlined_then = simplif_with_loc b in + let c', inlined_else = simplif_with_loc c in + let then_loc' = pick_branch_loc then_loc inlined_then in + let else_loc' = pick_branch_loc else_loc inlined_else in + let res = + if + a' == a && b' == b && c' == c && then_loc' == then_loc + && else_loc' == else_loc + then lam + else + Lambda.if_ ~loc:if_loc ~then_loc:then_loc' ~else_loc:else_loc' a' b' + c' + in + (res, Lambda.no_branch_loc) + | Lswitch (arg, sw) -> + let arg' = simplif arg in + let sw_consts = simplif_cases sw.sw_consts in + let sw_blocks = simplif_cases sw.sw_blocks in + let sw_failaction = simplif_opt_branch sw.sw_failaction in + let res = + if + arg' == arg && sw_consts == sw.sw_consts && sw_blocks == sw.sw_blocks + && sw_failaction == sw.sw_failaction + then lam + else Lambda.switch arg' {sw with sw_consts; sw_blocks; sw_failaction} + in + (res, Lambda.no_branch_loc) + | Lstringswitch (arg, cases, default, loc) -> + let arg' = simplif arg in + let cases' = simplif_cases cases in + let default' = simplif_opt_branch default in + let res = + if arg' == arg && cases' == cases && default' == default then lam + else Lambda.stringswitch ~loc arg' cases' default' + in + (res, Lambda.no_branch_loc) + | _ -> + (Lambda_traverse.shallow_map_sharing simplif lam, Lambda.no_branch_loc) + and simplif (lam : Lambda.t) = fst (simplif_with_loc lam) in simplif lam let simplify_exits (lam : Lambda.t) = diff --git a/compiler/backend/lam_pass_guard_raises.ml b/compiler/backend/lam_pass_guard_raises.ml index fe3e2f2c1bb..c932f66abfd 100644 --- a/compiler/backend/lam_pass_guard_raises.ml +++ b/compiler/backend/lam_pass_guard_raises.ml @@ -1,11 +1,12 @@ let rec guard_raises (lam : Lambda.t) : Lambda.t = match lam with - | Lifthenelse (a, (Lprim {primitive = Praise} as b), c) -> ( + | Lifthenelse (a, (Lprim {primitive = Praise} as b), c, {if_loc; then_loc}) + -> ( match c with (* A constant alternative is already as flat as it gets. *) | Lconst _ -> Lambda_traverse.shallow_map_sharing guard_raises lam | _ -> Lambda.seq - (Lambda.if_ (guard_raises a) b Lambda.lambda_unit) + (Lambda.if_ ~loc:if_loc ~then_loc (guard_raises a) b Lambda.lambda_unit) (guard_raises c)) | _ -> Lambda_traverse.shallow_map_sharing guard_raises lam diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index 0c12d7c657a..c46fe9edbc2 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -109,20 +109,27 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = when not (Lambda.const_is_allocating c) -> l | _ -> if p = Pval_from_option_not_nest then lvar else x) - | Lifthenelse (Lprim {primitive = Pis_not_none; args = [Lvar id]}, l2, l3) - -> ( + | Lifthenelse + ( Lprim {primitive = Pis_not_none; args = [Lvar id]; loc = prim_loc}, + l2, + l3, + {if_loc; then_loc; else_loc} ) -> ( + let cond_loc = + if (not if_loc.loc_ghost) && if_loc.loc_start.pos_cnum >= 0 then if_loc + else prim_loc + in match Hash_ident.find_opt meta.ident_tbl id with | Some (Constant c) when is_const_some c -> simpl l2 | Some (ImmutableBlock _ | Normal_optional _) -> simpl l2 | Some (OptionalBlock (l, Null)) -> - Lambda.if_ - (Lambda.not_ Location.none - (Lambda.prim ~primitive:Pis_null ~args:[l] Location.none)) + Lambda.if_ ~loc:if_loc ~then_loc ~else_loc + (Lambda.not_ cond_loc + (Lambda.prim ~primitive:Pis_null ~args:[l] cond_loc)) (simpl l2) (simpl l3) | Some (OptionalBlock (l, Null_undefined)) -> - Lambda.if_ - (Lambda.not_ Location.none - (Lambda.prim ~primitive:Pis_null_undefined ~args:[l] Location.none)) + Lambda.if_ ~loc:if_loc ~then_loc ~else_loc + (Lambda.not_ cond_loc + (Lambda.prim ~primitive:Pis_null_undefined ~args:[l] cond_loc)) (simpl l2) (simpl l3) | Some _ | None -> Lambda_traverse.shallow_map_sharing simpl lam) (* could be the code path @@ -130,7 +137,7 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = | h::hs -> ]} *) - | Lifthenelse (l1, l2, l3) -> ( + | Lifthenelse (l1, l2, l3, _) -> ( match l1 with | Lvar id -> ( match id_is_for_sure_true_in_boolean meta.ident_tbl id with @@ -263,7 +270,7 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = (record_assigned (Lam_beta_reduce.propagate_beta_reduce (current_meta ()) params body args)) - | Lstringswitch (l, sw, d) -> ( + | Lstringswitch (l, sw, d, loc) -> ( let known_constant = match l with | Lvar s -> ( @@ -275,9 +282,9 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = match known_constant with | Some c -> (* Switch on the constant the scrutinee is bound to. *) - Lambda.stringswitch (Lambda.const c) - (Ext_list.map_snd sw simpl) - (Option.map simpl d) + Lambda.stringswitch ~loc (Lambda.const c) + (List.map (fun (k, arm, arm_loc) -> (k, simpl arm, arm_loc)) sw) + (Option.map (fun (arm, arm_loc) -> (simpl arm, arm_loc)) d) | None -> Lambda_traverse.shallow_map_sharing simpl lam) | _ -> Lambda_traverse.shallow_map_sharing simpl lam in diff --git a/compiler/typing/lambda.ml b/compiler/typing/lambda.ml index 5c289e56dfc..256416ce215 100644 --- a/compiler/typing/lambda.ml +++ b/compiler/typing/lambda.ml @@ -359,12 +359,13 @@ type t = | Lletrec of (Ident.t * t) list * t | Lprim of prim_info | Lswitch of t * lambda_switch - | Lstringswitch of t * (string * t) list * t option + | Lstringswitch of + t * (string * t * branch_loc) list * (t * branch_loc) option * Location.t | Lstaticraise of int * t list - | Lstaticcatch of t * (int * Ident.t list) * t + | Lstaticcatch of t * (int * Ident.t list) * t * branch_loc | Ltrywith of t * Ident.t * t | Ltryfinally of t * t - | Lifthenelse of t * t * t + | Lifthenelse of t * t * t * if_locs | Lsequence of t * t | Lbreak | Lcontinue @@ -385,6 +386,10 @@ and prim_info = {primitive: primitive; args: t list; loc: Location.t} and lambda_apply = {ap_func: t; ap_args: t list; ap_loc: Location.t} +and branch_loc = {pat_loc: Location.t; body_loc: Location.t} + +and if_locs = {if_loc: Location.t; then_loc: branch_loc; else_loc: branch_loc} + and switch_key = | Switch_int of int | Switch_constructor of Variant_runtime.constructor_case @@ -395,15 +400,29 @@ and switch_dispatch = and 'a switch = { sw_consts_full: bool; - sw_consts: (switch_key * 'a) list; + sw_consts: (switch_key * 'a * branch_loc) list; sw_blocks_full: bool; - sw_blocks: (switch_key * 'a) list; - sw_failaction: 'a option; + sw_blocks: (switch_key * 'a * branch_loc) list; + sw_failaction: ('a * branch_loc) option; sw_dispatch: switch_dispatch; + sw_loc: Location.t; } and lambda_switch = t switch +let has_loc (loc : Location.t) = + (not loc.loc_ghost) && loc.loc_start.pos_cnum >= 0 + +let no_branch_loc = {pat_loc = Location.none; body_loc = Location.none} + +let branch_loc ?(pat_loc = Location.none) body_loc = {pat_loc; body_loc} + +let has_branch_loc ({pat_loc; body_loc} : branch_loc) = + has_loc pat_loc || has_loc body_loc + +let no_if_locs = + {if_loc = Location.none; then_loc = no_branch_loc; else_loc = no_branch_loc} + (* This is actually a dummy value not necessary "()", it can be used as a place holder for module alias etc. @@ -680,7 +699,9 @@ let let_ kind id e body : t = Llet (kind, id, e, body) let letrec bindings body : t = Lletrec (bindings, body) let staticraise i args : t = Lstaticraise (i, args) -let staticcatch body catch handler : t = Lstaticcatch (body, catch, handler) + +let staticcatch ?(loc = no_branch_loc) body catch handler : t = + Lstaticcatch (body, catch, handler, loc) let try_ body id handler : t = Ltrywith (body, id, handler) let try_finally body finally : t = Ltryfinally (body, finally) let break : t = Lbreak @@ -780,9 +801,9 @@ let rec eq_approx (l1 : t) (l2 : t) = eq_approx app1.ap_func app2.ap_func && eq_approx_list app1.ap_args app2.ap_args | _ -> false) - | Lifthenelse (a, b, c) -> ( + | Lifthenelse (a, b, c, _) -> ( match l2 with - | Lifthenelse (a0, b0, c0) -> + | Lifthenelse (a0, b0, c0, _) -> eq_approx a a0 && eq_approx b b0 && eq_approx c c0 | _ -> false) | Lsequence (a, b) -> ( @@ -809,12 +830,13 @@ let rec eq_approx (l1 : t) (l2 : t) = eq_primitive_approx info1.primitive info2.primitive && eq_approx_list info1.args info2.args | _ -> false) - | Lstringswitch (arg, patterns, default) -> ( + | Lstringswitch (arg, patterns, default, _) -> ( match l2 with - | Lstringswitch (arg2, patterns2, default2) -> - eq_approx arg arg2 && eq_option default default2 + | Lstringswitch (arg2, patterns2, default2, _) -> + eq_approx arg arg2 + && eq_option (Option.map fst default) (Option.map fst default2) && Ext_list.for_all2_no_exn patterns patterns2 - (fun ((k : string), v) (k2, v2) -> k = k2 && eq_approx v v2) + (fun ((k : string), v, _) (k2, v2, _) -> k = k2 && eq_approx v v2) | _ -> false) | Lfunction _ | Llet (_, _, _, _) @@ -877,16 +899,17 @@ let untagged_plan (sw : lambda_switch) = let exception Not_untagged in match ( List.map - (fun (key, action) -> + (fun (key, action, arm_loc) -> match key with - | Switch_constructor (Constant {literal}) -> (literal, action) + | Switch_constructor (Constant {literal}) -> + (literal, (action, arm_loc)) | Switch_constructor (Block _) | Switch_int _ -> raise Not_untagged) sw.sw_consts, List.map - (fun (key, action) -> + (fun (key, action, arm_loc) -> match key with | Switch_constructor (Block (Untagged {block_type})) -> - (block_type, action) + (block_type, (action, arm_loc)) | Switch_constructor (Constant _ | Block (Tagged _)) | Switch_int _ -> raise Not_untagged) @@ -894,7 +917,8 @@ let untagged_plan (sw : lambda_switch) = with | literal_arms, payload_arms -> Some - (Untagged_dispatch.plan ~same:eq_approx + (Untagged_dispatch.plan + ~same:(fun (a, _) (b, _) -> eq_approx a b) { facts; literal_arms; @@ -911,7 +935,7 @@ let switch lam (lam_switch : lambda_switch) : t = | Some action -> action | None -> ( match lam_switch.sw_failaction with - | Some action -> action + | Some (action, _) -> action | None -> Lswitch (lam, lam_switch)) in match (lam, lam_switch.sw_dispatch) with @@ -922,7 +946,7 @@ let switch lam (lam_switch : lambda_switch) : t = match (untagged_plan lam_switch, untagged_value cst) with | Some plan, Some value -> ( match Untagged_dispatch.select plan value with - | Arm action -> action + | Arm (action, _) -> action | Default -> action_or_switch None | Nothing -> Lswitch (lam, lam_switch)) | (Some _ | None), _ -> Lswitch (lam, lam_switch)) @@ -930,7 +954,7 @@ let switch lam (lam_switch : lambda_switch) : t = (* By runtime value: a coercion accepts [@as(1.)] for [@as(1.0)] *) let action = lam_switch.sw_consts - |> List.find_map (fun (key, action) -> + |> List.find_map (fun (key, action, _) -> match key with | Switch_constructor (Constant tag) when literal_denotes_same constant.literal tag.literal -> @@ -944,7 +968,7 @@ let switch lam (lam_switch : lambda_switch) : t = let i = Int32.to_int i in let action = lam_switch.sw_consts - |> List.find_map (fun (key, action) -> + |> List.find_map (fun (key, action, _) -> match key with | Switch_int ordinal when ordinal = i -> Some action | Switch_constructor (Constant {literal}) @@ -973,7 +997,7 @@ let switch lam (lam_switch : lambda_switch) : t = in let action = lam_switch.sw_blocks - |> List.find_map (fun (key, action) -> + |> List.find_map (fun (key, action, _) -> match (key, runtime) with | Switch_constructor (Block case_runtime), Some runtime when same_runtime runtime case_runtime -> @@ -983,10 +1007,20 @@ let switch lam (lam_switch : lambda_switch) : t = action_or_switch action | _ -> Lswitch (lam, lam_switch) -let stringswitch (lam : t) cases default : t = +let stringswitch ?(loc = Location.none) (lam : t) cases default : t = match lam with - | Lconst (Const_string s) -> Ext_list.assoc_by_string cases s default - | _ -> Lstringswitch (lam, cases, default) + | Lconst (Const_string s) -> ( + match + List.find_map + (fun (k, action, _) -> if k = s then Some action else None) + cases + with + | Some action -> action + | None -> ( + match default with + | Some (action, _) -> action + | None -> assert false)) + | _ -> Lstringswitch (lam, cases, default, loc) let rec seq (a : t) b : t = match a with @@ -1211,29 +1245,31 @@ let rec eval_const_as_bool (v : structured_constant) : bool option = | Null | Undefined -> Some false | Float _ | BigInt _ -> None) -let if_ (a : t) (b : t) (c : t) : t = +let if_ ?(loc = Location.none) ?(then_loc = no_branch_loc) + ?(else_loc = no_branch_loc) (a : t) (b : t) (c : t) : t = + let locs = {if_loc = loc; then_loc; else_loc} in match a with | Lconst v -> ( match eval_const_as_bool v with | Some v -> if v then b else c - | None -> Lifthenelse (a, b, c)) + | None -> Lifthenelse (a, b, c, locs)) | _ -> ( match (b, c) with | _, Lconst Const_assertfalse -> seq a b (* TODO: we could customize more cases *) | Lconst Const_assertfalse, _ -> seq a c | Lconst Const_js_true, Lconst Const_js_false -> - if has_boolean_type a != None then a else Lifthenelse (a, b, c) + if has_boolean_type a != None then a else Lifthenelse (a, b, c, locs) | Lconst Const_js_false, Lconst Const_js_true -> ( match has_boolean_type a with | Some loc -> not_ loc a - | None -> Lifthenelse (a, b, c)) + | None -> Lifthenelse (a, b, c, locs)) (* [if a then raise e else c] could become [(if a then raise e else ()); c], but that is code motion, not normalization: it changes the shape that matching's own exit bookkeeping inspects after the term is assembled, and doing it here leaves static raises without their catch. It is {!Lam_pass_guard_raises} instead. *) - | _ -> Lifthenelse (a, b, c)) + | _ -> Lifthenelse (a, b, c, locs)) let sequor l r = if_ l lambda_true r diff --git a/compiler/typing/lambda.mli b/compiler/typing/lambda.mli index 4b5e70dd05f..714ceca5e05 100644 --- a/compiler/typing/lambda.mli +++ b/compiler/typing/lambda.mli @@ -373,16 +373,17 @@ type t = private | Lswitch of t * lambda_switch (* switch on strings, clauses are sorted by string order, strings are pairwise distinct *) - | Lstringswitch of t * (string * t) list * t option + | Lstringswitch of + t * (string * t * branch_loc) list * (t * branch_loc) option * Location.t | Lstaticraise of int * t list - | Lstaticcatch of t * (int * Ident.t list) * t + | Lstaticcatch of t * (int * Ident.t list) * t * branch_loc | Ltrywith of t * Ident.t * t | Ltryfinally of t * t (** [Ltryfinally (body, finally)] evaluates [body], then [finally] however [body] is left (normally, by an exception, or by break/continue/return), and has the value of [body]. A try with both catch and finally is an [Ltryfinally] around an [Ltrywith]. *) - | Lifthenelse of t * t * t + | Lifthenelse of t * t * t * if_locs | Lsequence of t * t | Lbreak | Lcontinue @@ -403,6 +404,10 @@ and prim_info = private {primitive: primitive; args: t list; loc: Location.t} and lambda_apply = private {ap_func: t; ap_args: t list; ap_loc: Location.t} +and branch_loc = {pat_loc: Location.t; body_loc: Location.t} + +and if_locs = {if_loc: Location.t; then_loc: branch_loc; else_loc: branch_loc} + and switch_key = | Switch_int of int | Switch_constructor of Variant_runtime.constructor_case @@ -413,15 +418,21 @@ and switch_dispatch = and 'a switch = { sw_consts_full: bool; - sw_consts: (switch_key * 'a) list; + sw_consts: (switch_key * 'a * branch_loc) list; sw_blocks_full: bool; - sw_blocks: (switch_key * 'a) list; - sw_failaction: 'a option; (* Action to take if failure *) + sw_blocks: (switch_key * 'a * branch_loc) list; + sw_failaction: ('a * branch_loc) option; (* Action to take if failure *) sw_dispatch: switch_dispatch; + sw_loc: Location.t; } and lambda_switch = t switch +val no_branch_loc : branch_loc +val branch_loc : ?pat_loc:Location.t -> Location.t -> branch_loc +val has_branch_loc : branch_loc -> bool +val no_if_locs : if_locs + (* Sharing key *) val const_int : int -> structured_constant @@ -501,23 +512,36 @@ val letrec : (Ident.t * t) list -> t -> t val prim : primitive:primitive -> args:t list -> Location.t -> t -val untagged_plan : lambda_switch -> t Untagged_dispatch.tree option +val untagged_plan : + lambda_switch -> (t * branch_loc) Untagged_dispatch.tree option (** The dispatch of a switch on an untagged variant, which the code generator prints and constant folding evaluates *) val switch : t -> lambda_switch -> t -val stringswitch : t -> (string * t) list -> t option -> t +val stringswitch : + ?loc:Location.t -> + t -> + (string * t * branch_loc) list -> + (t * branch_loc) option -> + t val staticraise : int -> t list -> t -val staticcatch : t -> int * Ident.t list -> t -> t +val staticcatch : ?loc:branch_loc -> t -> int * Ident.t list -> t -> t val try_ : t -> Ident.t -> t -> t val try_finally : t -> t -> t -val if_ : t -> t -> t -> t +val if_ : + ?loc:Location.t -> + ?then_loc:branch_loc -> + ?else_loc:branch_loc -> + t -> + t -> + t -> + t val seq : t -> t -> t diff --git a/compiler/typing/lambda_effects.ml b/compiler/typing/lambda_effects.ml index e8e60c9eb54..030c0a393da 100644 --- a/compiler/typing/lambda_effects.ml +++ b/compiler/typing/lambda_effects.ml @@ -114,7 +114,7 @@ let rec no_side_effects (lam : Lambda.t) : bool = false) | Llet (_, _, arg, body) -> no_side_effects arg && no_side_effects body | Lswitch (_, _) -> false - | Lstringswitch (_, _, _) -> false + | Lstringswitch (_, _, _, _) -> false | Lstaticraise _ -> false | Lstaticcatch _ -> false (* It would be nice that we can also analysis some small functions @@ -124,7 +124,7 @@ let rec no_side_effects (lam : Lambda.t) : bool = no_side_effects body && no_side_effects handler | Ltryfinally (body, finally) -> no_side_effects body && no_side_effects finally - | Lifthenelse (a, b, c) -> + | Lifthenelse (a, b, c, _) -> no_side_effects a && no_side_effects b && no_side_effects c | Lsequence (a, b) -> no_side_effects a && no_side_effects b | Lbreak | Lcontinue -> false diff --git a/compiler/typing/lambda_exits.ml b/compiler/typing/lambda_exits.ml index 0265886e18b..be844585a1c 100644 --- a/compiler/typing/lambda_exits.ml +++ b/compiler/typing/lambda_exits.ml @@ -47,7 +47,7 @@ let rec as_simple_exit = function (* Introduce a catch around [handler], if worth it. Returns the exit number to raise to, and a function wrapping a body in the catch - a body that turns out to be exactly that raise gets the handler itself instead. *) -let make_catch_delayed handler = +let make_catch_delayed ?(loc = no_branch_loc) handler = match as_simple_exit handler with | Some i -> (i, fun act -> act) | None -> ( @@ -56,4 +56,4 @@ let make_catch_delayed handler = fun body -> match body with | Lstaticraise (j, _) -> if i = j then handler else body - | _ -> staticcatch body (i, []) handler )) + | _ -> staticcatch ~loc body (i, []) handler )) diff --git a/compiler/typing/lambda_exits.mli b/compiler/typing/lambda_exits.mli index eb7e0f9ac3e..e3a2845f80d 100644 --- a/compiler/typing/lambda_exits.mli +++ b/compiler/typing/lambda_exits.mli @@ -31,6 +31,7 @@ val make_exit : int -> Lambda.t val as_simple_exit : Lambda.t -> int option (** The exit a term jumps to, when it is nothing but that jump. *) -val make_catch_delayed : Lambda.t -> int * (Lambda.t -> Lambda.t) +val make_catch_delayed : + ?loc:Lambda.branch_loc -> Lambda.t -> int * (Lambda.t -> Lambda.t) (** Exit number to raise to, and a wrapper that puts the catch around a body. A body that turns out to be exactly that raise gets the handler itself. *) diff --git a/compiler/typing/lambda_scc.ml b/compiler/typing/lambda_scc.ml index ff1c6f7aca2..96065a9817b 100644 --- a/compiler/typing/lambda_scc.ml +++ b/compiler/typing/lambda_scc.ml @@ -28,17 +28,14 @@ type bindings = (Ident.t * Lambda.t) list (* [p] may have side effects (masking). Returning true stops the walk. *) let exists_var (p : Ident.t -> bool) (l : Lambda.t) : bool = - let rec hit_opt = function - | None -> false - | Some a -> hit a - and hit_list_snd : 'a. ('a * Lambda.t) list -> bool = + let rec hit_list_snd : 'a. ('a * Lambda.t) list -> bool = fun x -> Ext_list.exists_snd x hit and hit_list xs = List.exists hit xs and hit (l : Lambda.t) = match l with | Lvar id -> p id | Lassign (id, e) -> p id || hit e - | Lstaticcatch (e1, _, e2) + | Lstaticcatch (e1, _, e2, _) | Ltrywith (e1, _, e2) | Ltryfinally (e1, e2) | Lsequence (e1, e2) @@ -49,17 +46,21 @@ let exists_var (p : Ident.t -> bool) (l : Lambda.t) : bool = | Lfunction {body} -> hit body | Llet (_, _, arg, body) -> hit arg || hit body | Lletrec (decl, body) -> hit body || hit_list_snd decl - | Lfor (_, e1, e2, _, e3) | Lifthenelse (e1, e2, e3) -> + | Lfor (_, e1, e2, _, e3) | Lifthenelse (e1, e2, e3, _) -> hit e1 || hit e2 || hit e3 | Lconst _ | Lbreak | Lcontinue -> false | Lapply {ap_func; ap_args} -> hit ap_func || hit_list ap_args | Lprim {primitive = _; args; loc = _} | Lstaticraise (_, args) -> hit_list args | Lswitch (arg, sw) -> - hit arg || hit_list_snd sw.sw_consts || hit_list_snd sw.sw_blocks - || hit_opt sw.sw_failaction - | Lstringswitch (arg, cases, default) -> - hit arg || hit_list_snd cases || hit_opt default + hit arg + || List.exists (fun (_, e, _) -> hit e) sw.sw_consts + || List.exists (fun (_, e, _) -> hit e) sw.sw_blocks + || Option.fold ~none:false ~some:(fun (e, _) -> hit e) sw.sw_failaction + | Lstringswitch (arg, cases, default, _) -> + hit arg + || List.exists (fun (_, e, _) -> hit e) cases + || Option.fold ~none:false ~some:(fun (e, _) -> hit e) default | Lglobal_module _ -> false in hit l diff --git a/compiler/typing/lambda_traverse.ml b/compiler/typing/lambda_traverse.ml index 5a5635c4193..8f514b8b620 100644 --- a/compiler/typing/lambda_traverse.ml +++ b/compiler/typing/lambda_traverse.ml @@ -22,12 +22,20 @@ open Lambda (* Preserve the option wrapper so unchanged switch defaults do not rebuild their parent node. *) -let option_map_sharing option f = +let option_branch_map_sharing option f = match option with | None -> option - | Some value -> + | Some (value, loc) -> let mapped = f value in - if mapped == value then option else Some mapped + if mapped == value then option else Some (mapped, loc) + +let rec map_cases_sharing cases f = + match cases with + | [] -> cases + | (key, value, loc) :: tl -> + let mapped = f value in + let tl' = map_cases_sharing tl f in + if mapped == value && tl' == tl then cases else (key, mapped, loc) :: tl' (** [shallow_map_sharing f lam] rewrites [lam]'s immediate children with [f] and rebuilds the node through its smart constructor, so the result is @@ -55,9 +63,9 @@ let shallow_map_sharing (f : t -> t) (lam : t) : t = if args' == args then lam else prim ~primitive ~args:args' loc | Lswitch (e, sw) -> let e' = f e in - let consts = Ext_list.map_snd_sharing sw.sw_consts f in - let blocks = Ext_list.map_snd_sharing sw.sw_blocks f in - let fail = option_map_sharing sw.sw_failaction f in + let consts = map_cases_sharing sw.sw_consts f in + let blocks = map_cases_sharing sw.sw_blocks f in + let fail = option_branch_map_sharing sw.sw_failaction f in if e' == e && consts == sw.sw_consts && blocks == sw.sw_blocks && fail == sw.sw_failaction @@ -65,27 +73,28 @@ let shallow_map_sharing (f : t -> t) (lam : t) : t = else switch e' {sw with sw_consts = consts; sw_blocks = blocks; sw_failaction = fail} - | Lstringswitch (e, cases, d) -> + | Lstringswitch (e, cases, d, loc) -> let e' = f e in - let cases' = Ext_list.map_snd_sharing cases f in - let d' = option_map_sharing d f in + let cases' = map_cases_sharing cases f in + let d' = option_branch_map_sharing d f in if e' == e && cases' == cases && d' == d then lam - else stringswitch e' cases' d' + else stringswitch ~loc e' cases' d' | Lstaticraise (i, args) -> let args' = Ext_list.map_sharing args f in if args' == args then lam else staticraise i args' - | Lstaticcatch (b, h, hd) -> + | Lstaticcatch (b, h, hd, loc) -> let b' = f b and hd' = f hd in - if b' == b && hd' == hd then lam else staticcatch b' h hd' + if b' == b && hd' == hd then lam else staticcatch ~loc b' h hd' | Ltrywith (b, id, h) -> let b' = f b and h' = f h in if b' == b && h' == h then lam else try_ b' id h' | Ltryfinally (b, fin) -> let b' = f b and fin' = f fin in if b' == b && fin' == fin then lam else try_finally b' fin' - | Lifthenelse (a, b, c) -> + | Lifthenelse (a, b, c, {if_loc; then_loc; else_loc}) -> let a' = f a and b' = f b and c' = f c in - if a' == a && b' == b && c' == c then lam else if_ a' b' c' + if a' == a && b' == b && c' == c then lam + else if_ ~loc:if_loc ~then_loc ~else_loc a' b' c' | Lsequence (a, b) -> let a' = f a and b' = f b in if a' == a && b' == b then lam else seq a' b' @@ -141,16 +150,16 @@ let make_key e = | Lprim {primitive = p; args = es; loc = _} -> prim ~primitive:p ~args:(tr_recs env es) Location.none | Lswitch (e, sw) -> switch (tr_rec env e) (tr_sw env sw) - | Lstringswitch (e, sw, d) -> + | Lstringswitch (e, sw, d, _) -> stringswitch (tr_rec env e) - (List.map (fun (s, e) -> (s, tr_rec env e)) sw) + (List.map (fun (s, e, _) -> (s, tr_rec env e, no_branch_loc)) sw) (tr_opt env d) | Lstaticraise (i, es) -> staticraise i (tr_recs env es) - | Lstaticcatch (e1, xs, e2) -> + | Lstaticcatch (e1, xs, e2, _) -> staticcatch (tr_rec env e1) xs (tr_rec env e2) | Ltrywith (e1, x, e2) -> try_ (tr_rec env e1) x (tr_rec env e2) | Ltryfinally (e1, e2) -> try_finally (tr_rec env e1) (tr_rec env e2) - | Lifthenelse (cond, ifso, ifnot) -> + | Lifthenelse (cond, ifso, ifnot, _) -> if_ (tr_rec env cond) (tr_rec env ifso) (tr_rec env ifnot) | Lsequence (e1, e2) -> seq (tr_rec env e1) (tr_rec env e2) | Lbreak -> break @@ -163,13 +172,20 @@ let make_key e = and tr_sw env sw = { sw with - sw_consts = List.map (fun (i, e) -> (i, tr_rec env e)) sw.sw_consts; - sw_blocks = List.map (fun (i, e) -> (i, tr_rec env e)) sw.sw_blocks; + sw_consts = + List.map + (fun (i, e, _) -> (i, tr_rec env e, no_branch_loc)) + sw.sw_consts; + sw_blocks = + List.map + (fun (i, e, _) -> (i, tr_rec env e, no_branch_loc)) + sw.sw_blocks; sw_failaction = tr_opt env sw.sw_failaction; + sw_loc = Location.none; } and tr_opt env = function | None -> None - | Some e -> Some (tr_rec env e) + | Some (e, _) -> Some (tr_rec env e, no_branch_loc) in try Some (tr_rec Ident.empty e) with Not_simple -> None @@ -185,17 +201,17 @@ let shallow_exists (f : t -> bool) (lam : t) : bool = | Lprim {args} -> List.exists f args | Lswitch (arg, {sw_consts; sw_blocks; sw_failaction}) -> f arg - || Ext_list.exists_snd sw_consts f - || Ext_list.exists_snd sw_blocks f - || Option.fold ~none:false ~some:f sw_failaction - | Lstringswitch (arg, cases, default) -> + || List.exists (fun (_, e, _) -> f e) sw_consts + || List.exists (fun (_, e, _) -> f e) sw_blocks + || Option.fold ~none:false ~some:(fun (e, _) -> f e) sw_failaction + | Lstringswitch (arg, cases, default, _) -> f arg - || Ext_list.exists_snd cases f - || Option.fold ~none:false ~some:f default + || List.exists (fun (_, e, _) -> f e) cases + || Option.fold ~none:false ~some:(fun (e, _) -> f e) default | Lstaticraise (_, args) -> List.exists f args - | Lstaticcatch (e1, _, e2) -> f e1 || f e2 + | Lstaticcatch (e1, _, e2, _) -> f e1 || f e2 | Ltrywith (e1, _, e2) | Ltryfinally (e1, e2) -> f e1 || f e2 - | Lifthenelse (e1, e2, e3) -> f e1 || f e2 || f e3 + | Lifthenelse (e1, e2, e3, _) -> f e1 || f e2 || f e3 | Lsequence (e1, e2) -> f e1 || f e2 | Lwhile (e1, e2) -> f e1 || f e2 | Lfor (_, e1, e2, _, e3) -> f e1 || f e2 || f e3 @@ -221,7 +237,7 @@ let free_ids get l = | Llet (_str, id, _arg, _body) -> fv := Set_ident.remove id !fv | Lletrec (decl, _body) -> List.iter (fun (id, _exp) -> fv := Set_ident.remove id !fv) decl - | Lstaticcatch (_e1, (_, vars), _e2) -> + | Lstaticcatch (_e1, (_, vars), _e2, _) -> List.iter (fun id -> fv := Set_ident.remove id !fv) vars | Ltrywith (_e1, exn, _e2) -> fv := Set_ident.remove exn !fv | Lfor (v, _e1, _e2, _dir, _e3) -> fv := Set_ident.remove v !fv diff --git a/compiler/typing/matching.ml b/compiler/typing/matching.ml index 6f6232b2c37..8c32af2f98c 100644 --- a/compiler/typing/matching.ml +++ b/compiler/typing/matching.ml @@ -373,12 +373,16 @@ let jumps_map f env = List.map (fun (i, pss) -> (i, f pss)) env accumulate here too, outermost first. *) type action = { binds: (let_kind * Ident.t * Lambda.t) list; - guard: Lambda.t option; + guard: (Lambda.t * Location.t) option; body: Lambda.t; + loc: Lambda.branch_loc; } -let unguarded body = {binds = []; guard = None; body} -let guarded ~guard body = {binds = []; guard = Some guard; body} +let unguarded ?(loc = no_branch_loc) body = + {binds = []; guard = None; body; loc} + +let guarded ?(loc = no_branch_loc) ~guard ?(guard_loc = Location.none) body = + {binds = []; guard = Some (guard, guard_loc); body; loc} (* Bring [id = e] into scope over the whole right-hand side. Like [Lambda.bind], an alias of a variable to itself is dropped. *) @@ -387,11 +391,13 @@ let bind_action kind id e (a : action) = | Lvar v when Ident.same v id -> a | _ -> {a with binds = (kind, id, e) :: a.binds} -let action_body_with ~fail {binds; guard; body} = +let action_body_with ~fail ?(fail_loc = no_branch_loc) {binds; guard; body; loc} + = let core = match guard with | None -> body - | Some g -> if_ g body fail + | Some (g, g_loc) -> + if_ ~loc:g_loc ~then_loc:loc ~else_loc:fail_loc g body fail in List.fold_right (fun (k, id, e) acc -> let_ k id e acc) binds core @@ -402,11 +408,11 @@ let action_body_with ~fail {binds; guard; body} = merging those loses one evaluation of [g]. *) let action_key_term ~fail a = action_body_with ~fail a -let action_free_variables {binds; guard; body} = +let action_free_variables {binds; guard; body; _} = let inner = match guard with | None -> Lambda_traverse.free_variables body - | Some g -> + | Some (g, _) -> Set_ident.union (Lambda_traverse.free_variables body) (Lambda_traverse.free_variables g) @@ -512,10 +518,10 @@ let pretty_precompiled_res first nexts = *) module Store_exp = Switch.Store (struct - type t = Lambda.t + type t = Lambda.t * Lambda.branch_loc type key = Lambda.t let compare_key = compare - let make_key = Lambda_traverse.make_key + let make_key (lam, _) = Lambda_traverse.make_key lam end) let tr_raw act = @@ -526,12 +532,13 @@ let tr_raw act = let same_actions = function | [] -> None | [(_, act)] -> Some act - | (_, act0) :: rem -> ( + | (_, ((act0, _) as res0)) :: rem -> ( try let raw_act0 = tr_raw act0 in let rec s_rec = function - | [] -> Some act0 - | (_, act) :: rem -> if raw_act0 = tr_raw act then s_rec rem else None + | [] -> Some res0 + | (_, (act, _)) :: rem -> + if raw_act0 = tr_raw act then s_rec rem else None in s_rec rem with Exit -> None) @@ -1454,9 +1461,40 @@ let make_constr_matching p def ctx = function pat = normalize_pat p; } -let divide_constructor ctx pm = +let single_arm_loc cases fallback = + match cases with + | [] -> fallback + | (_, act) :: rest -> + let loc = act.loc.pat_loc in + if + loc <> Location.none + && List.for_all (fun (_, act') -> act'.loc.pat_loc = loc) rest + then loc + else fallback + +let relocate_cell_args ~switch_loc ~orig_args (cell : cell) = + let loc = single_arm_loc cell.pm.cases switch_loc in + let rec relocate args = + if args == orig_args then args + else + match args with + | [] -> [] + | (Lprim {primitive; args = pargs; loc = _}, str) :: rest -> + (prim ~primitive ~args:pargs loc, str) :: relocate rest + | hd :: rest -> hd :: relocate rest + in + {cell with pm = {cell.pm with args = relocate cell.pm.args}} + +let divide_constructor ~switch_loc ctx pm = + let orig_args = + match pm.args with + | _ :: argl -> argl + | [] -> [] + in divide make_constr_matching Types.same_constructor get_key_constr get_args_constr ctx pm + |> List.map (fun (cstr, cell) -> + (cstr, relocate_cell_args ~switch_loc ~orig_args cell)) (* Matching against a variant *) @@ -1504,7 +1542,12 @@ let make_variant_matching_nonconst p lab def ctx = function pat = normalize_pat p; } -let divide_variant row ctx {cases = cl; args = al; default = def} = +let divide_variant ~switch_loc row ctx {cases = cl; args = al; default = def} = + let orig_args = + match al with + | _ :: argl -> argl + | [] -> [] + in let row = Btype.row_repr row in let rec divide = function | (({pat_desc = Tpat_variant (lab, pato, _)} as p) :: patl, action) :: rem @@ -1531,6 +1574,8 @@ let divide_variant row ctx {cases = cl; args = al; default = def} = | _ -> [] in divide cl + |> List.map (fun (key, cell) -> + (key, relocate_cell_args ~switch_loc ~orig_args cell)) (* Three ``no-test'' cases @@ -1578,9 +1623,10 @@ let make_tuple_matching loc arity def = function default = make_default (matcher_tuple arity) def; } -let divide_tuple arity p ctx pm = +let divide_tuple ~switch_loc arity p ctx pm = + let loc = single_arm_loc pm.cases switch_loc in divide_line (filter_ctx p) - (make_tuple_matching p.pat_loc arity) + (make_tuple_matching loc arity) (get_args_tuple arity) p ctx pm (* Matching against a record pattern *) @@ -1722,7 +1768,8 @@ let bind_record_fields_and_rest arg ((patl, action) as case) = action ) | _ -> case -let divide_record all_labels p ctx pm = +let divide_record ~switch_loc all_labels p ctx pm = + let loc = single_arm_loc pm.cases switch_loc in let cases = match pm.args with | (arg, _) :: _ -> List.map (bind_record_fields_and_rest arg) pm.cases @@ -1730,7 +1777,7 @@ let divide_record all_labels p ctx pm = in let get_args = get_args_record (Array.length all_labels) in divide_line (filter_ctx p) - (make_record_matching p.pat_loc all_labels + (make_record_matching loc all_labels ~bound_next_to_rest:(fields_bound_next_to_rest cases)) get_args p ctx {pm with cases} @@ -1770,20 +1817,27 @@ let make_array_matching p def ctx = function pat = normalize_pat p; } -let divide_array ctx pm = +let divide_array ~switch_loc ctx pm = + let orig_args = + match pm.args with + | _ :: argl -> argl + | [] -> [] + in divide make_array_matching ( = ) get_key_array get_args_array ctx pm + |> List.map (fun (key, cell) -> + (key, relocate_cell_args ~switch_loc ~orig_args cell)) (* Entry point *) let handle_shared () = let hs = ref (fun x -> x) in let handle_shared act = match act with - | Switch.Single act -> act - | Switch.Shared act -> - let i, h = Lambda_exits.make_catch_delayed act in + | Switch.Single (act, loc) -> (act, loc) + | Switch.Shared (act, loc) -> + let i, h = Lambda_exits.make_catch_delayed ~loc act in let ohs = !hs in (hs := fun act -> h (ohs act)); - Lambda_exits.make_exit i + (Lambda_exits.make_exit i, loc) in (hs, handle_shared) @@ -1795,8 +1849,13 @@ let share_actions_tree sw d = | None -> None | Some d -> Some (store.Switch.act_store_shared d) in - (* Store all other actions *) - let sw = List.map (fun (cst, act) -> (cst, store.Switch.act_store act)) sw in + (* Store all other actions, preserving each arm's own location *) + let sw = + List.map + (fun (cst, ((_, arm_loc) as act)) -> + (cst, store.Switch.act_store act, arm_loc)) + sw + in (* Retrieve all actions, including potential default *) let acts = store.Switch.act_get_shared () in @@ -1811,7 +1870,14 @@ let share_actions_tree sw d = | None -> None | Some d -> Some acts.(d) in - let sw = List.map (fun (cst, j) -> (cst, acts.(j))) sw in + let sw = + List.map + (fun (cst, j, arm_loc) -> + let act, shared_loc = acts.(j) in + let loc = if has_branch_loc arm_loc then arm_loc else shared_loc in + (cst, (act, loc))) + sw + in (!hs, sw, d) (* Note: dichotomic search requires sorted input with no duplicates *) @@ -1835,22 +1901,24 @@ let rec cut n l = let l1, l2 = cut (n - 1) l in (a :: l1, l2) -let rec do_tests_fail loc fail tst arg = function - | [] -> fail - | (c, act) :: rem -> - if_ - (prim ~primitive:tst ~args:[arg; const (const_of_typed c)] loc) - (do_tests_fail loc fail tst arg rem) - act +let rec do_tests_fail loc (fail, fail_loc) tst arg = function + | [] -> (fail, fail_loc) + | (c, (act, act_loc)) :: rem -> + let next, next_loc = do_tests_fail loc (fail, fail_loc) tst arg rem in + ( if_ ~loc ~then_loc:next_loc ~else_loc:act_loc + (prim ~primitive:tst ~args:[arg; const (const_of_typed c)] loc) + next act, + no_branch_loc ) let rec do_tests_nofail loc tst arg = function | [] -> fatal_error "Matching.do_tests_nofail" | [(_, act)] -> act - | (c, act) :: rem -> - if_ - (prim ~primitive:tst ~args:[arg; const (const_of_typed c)] loc) - (do_tests_nofail loc tst arg rem) - act + | (c, (act, act_loc)) :: rem -> + let next, next_loc = do_tests_nofail loc tst arg rem in + ( if_ ~loc ~then_loc:next_loc ~else_loc:act_loc + (prim ~primitive:tst ~args:[arg; const (const_of_typed c)] loc) + next act, + no_branch_loc ) let make_test_sequence loc fail tst lt_tst arg const_lambda_list = let const_lambda_list = sort_lambda_list const_lambda_list in @@ -1866,13 +1934,17 @@ let make_test_sequence loc fail tst lt_tst arg const_lambda_list = let list1, list2 = cut (List.length const_lambda_list / 2) const_lambda_list in - if_ - (prim ~primitive:lt_tst - ~args:[arg; const (const_of_typed (fst (List.hd list2)))] - loc) - (make_test_sequence list1) (make_test_sequence list2) + let lam1, loc1 = make_test_sequence list1 in + let lam2, loc2 = make_test_sequence list2 in + ( if_ ~loc ~then_loc:loc1 ~else_loc:loc2 + (prim ~primitive:lt_tst + ~args:[arg; const (const_of_typed (fst (List.hd list2)))] + loc) + lam1 lam2, + no_branch_loc ) in - hs (make_test_sequence const_lambda_list) + let lam, arm_loc = make_test_sequence const_lambda_list in + (hs lam, arm_loc) (* Action sharing for Lswitch argument *) let share_actions_sw sw = @@ -1886,9 +1958,13 @@ let share_actions_sw sw = Some (store.Switch.act_store_shared fail) in let consts = - List.map (fun (i, e) -> (i, store.Switch.act_store e)) sw.sw_consts + List.map + (fun (i, e, loc) -> (i, store.Switch.act_store (e, loc), loc)) + sw.sw_consts and blocks = - List.map (fun (i, e) -> (i, store.Switch.act_store e)) sw.sw_blocks + List.map + (fun (i, e, loc) -> (i, store.Switch.act_store (e, loc), loc)) + sw.sw_blocks in let acts = store.Switch.act_get_shared () in let hs, handle_shared = handle_shared () in @@ -1898,11 +1974,16 @@ let share_actions_sw sw = | None -> None | Some fail -> Some acts.(fail) in + let restore (i, j, arm_loc) = + let act, shared_loc = acts.(j) in + let loc = if has_branch_loc arm_loc then arm_loc else shared_loc in + (i, act, loc) + in ( !hs, { sw with - sw_consts = List.map (fun (i, j) -> (i, acts.(j))) consts; - sw_blocks = List.map (fun (i, j) -> (i, acts.(j))) blocks; + sw_consts = List.map restore consts; + sw_blocks = List.map restore blocks; sw_failaction = fail; } ) @@ -1913,7 +1994,7 @@ let reintroduce_fail sw = match sw.sw_failaction with | None -> let t = Hashtbl.create 17 in - let seen (_, l) = + let seen (_, l, _) = match Lambda_exits.as_simple_exit l with | Some i -> let old = try Hashtbl.find t i with Not_found -> 0 in @@ -1936,7 +2017,7 @@ let reintroduce_fail sw = let default = !i_max in let remove ls = List.filter - (fun (_, lam) -> + (fun (_, lam, _) -> match Lambda_exits.as_simple_exit lam with | Some j -> j <> default | None -> true) @@ -1952,7 +2033,7 @@ let reintroduce_fail sw = sw_blocks_full = sw.sw_blocks_full && List.length sw_blocks = List.length sw.sw_blocks; sw_blocks; - sw_failaction = Some (Lambda_exits.make_exit default); + sw_failaction = Some (Lambda_exits.make_exit default, no_branch_loc); } else sw | Some _ -> sw @@ -2070,14 +2151,14 @@ let as_interval_ranges fail low high l = | None -> as_interval_nofail l | Some act -> as_interval_canfail act low high l ) -let call_switcher_ranges fail arg low high range_lambda_list = +let call_switcher_ranges ~loc fail arg low high range_lambda_list = let edges, (cases, actions) = as_interval_ranges fail low high range_lambda_list in - Switch.zyva edges arg cases actions + Switch.zyva ~loc edges arg cases actions -let call_switcher fail arg low high int_lambda_list = - call_switcher_ranges fail arg low high +let call_switcher ~loc fail arg low high int_lambda_list = + call_switcher_ranges ~loc fail arg low high (List.map (fun (i, act) -> (i, i, act)) int_lambda_list) let rec list_as_pat = function @@ -2100,7 +2181,8 @@ let mk_failaction_neg partial ctx def = match partial with | Partial -> ( match def with - | (_, idef) :: _ -> (Some (staticraise idef []), jumps_singleton idef ctx) + | (_, idef) :: _ -> + (Some (staticraise idef [], no_branch_loc), jumps_singleton idef ctx) | [] -> (* Act as Total, this means If no appropriate default matrix exists, @@ -2119,7 +2201,7 @@ let mk_failaction_pos partial seen ctx defs = | [], _ | _, [] -> List.fold_left (fun (klist, jumps) (pats, i) -> - let action = staticraise i [] in + let action = (staticraise i [], no_branch_loc) in let klist = List.fold_right (fun pat r -> (get_key_constr pat, action) :: r) @@ -2153,13 +2235,13 @@ let mk_failaction_pos partial seen ctx defs = eprintf "FAIL: %s\n" (match fail with | None -> "" - | Some lam -> string_of_lam lam); + | Some (lam, _) -> string_of_lam lam); (fail, [], jumps)) let combine_constant loc arg cst partial ctx def (const_lambda_list, total, _pats) = let fail, local_jumps = mk_failaction_neg partial ctx def in - let lambda1 = + let lambda1, arm_loc = match (cst : Asttypes.constant) with | Const_int _ | Const_char _ -> (* [char] is an alias of [int], so a column can mix both. Its keys are @@ -2175,7 +2257,7 @@ let combine_constant loc arg cst partial ctx def (* Match intervals must use ReScript's int32 bounds, not the host's. Otherwise the upper fail interval starts at 2147483648, which wraps when converted to a Lambda integer constant. *) - call_switcher_ranges fail arg int32_low int32_high range_lambda_list + call_switcher_ranges ~loc fail arg int32_low int32_high range_lambda_list | Const_string _ -> (* Note as the bytecode compiler may resort to dichotomic search, the clauses of stringswitch are sorted with duplicates removed. @@ -2194,7 +2276,8 @@ let combine_constant loc arg cst partial ctx def const_lambda_list in let hs, sw, fail = share_actions_tree sw fail in - hs (stringswitch arg sw fail) + let sw = List.map (fun (s, (act, arm_loc)) -> (s, act, arm_loc)) sw in + (hs (stringswitch ~loc arg sw fail), no_branch_loc) | Const_float _ -> make_test_sequence loc fail (Pfloatcomp Cneq) (Pfloatcomp Clt) arg (List.map (fun ((c, _), l) -> (c, l)) const_lambda_list) @@ -2202,7 +2285,7 @@ let combine_constant loc arg cst partial ctx def make_test_sequence loc fail (Pbigintcomp Cneq) (Pbigintcomp Clt) arg (List.map (fun ((c, _), l) -> (c, l)) const_lambda_list) in - (lambda1, jumps_union local_jumps total) + (lambda1, arm_loc, jumps_union local_jumps total) let split_cases tag_lambda_list = let rec split_rec = function @@ -2259,17 +2342,19 @@ let constructor_switch_key (cstr : Types.constructor_description) = type payload_presence_test = Is_present_option | Is_nonempty_list type constructor_matching_plan = - | Use_constructor_action of Lambda.t + | Use_constructor_action of Lambda.t * branch_loc (** Every possible constructor reaches the same action. *) | Test_payload_presence of { test: payload_presence_test; - absent: Lambda.t; - present: Lambda.t; + absent: Lambda.t * branch_loc; + present: Lambda.t * branch_loc; } (** A two-constructor representation whose runtime value directly reveals whether the payload constructor is present. *) - | Test_boolean_value of {if_false: Lambda.t; if_true: Lambda.t} - (** The predefined boolean constructors are JavaScript booleans. *) + | Test_boolean_value of { + if_false: Lambda.t * branch_loc; + if_true: Lambda.t * branch_loc; + } (** The predefined boolean constructors are JavaScript booleans. *) | Switch_on_constructors of Lambda.lambda_switch (** General nominal and untagged variant matching. *) @@ -2316,14 +2401,14 @@ let rec value_test_defaults_on_undefined ~arg ~absent present = (* The value bound to a name *) value_test_defaults_on_undefined ~arg:(Lambda.var id) ~absent body || value_test_defaults_on_undefined ~arg:def ~absent body - | Lswitch (scrutinee, ({sw_failaction = Some fail} as sw)) -> + | Lswitch (scrutinee, ({sw_failaction = Some (fail, _)} as sw)) -> is_value scrutinee && Lambda.eq_approx fail absent && switch_defaults_on_undefined sw - | Lstringswitch (scrutinee, _, Some fail) -> + | Lstringswitch (scrutinee, _, Some (fail, _), _) -> is_value scrutinee && Lambda.eq_approx fail absent (* undefined is unequal to every constant *) - | Lifthenelse (Lprim {primitive; args}, if_true, if_false) + | Lifthenelse (Lprim {primitive; args}, if_true, if_false, _) when compares_value args -> ( match is_equality primitive with | Some Cneq -> Lambda.eq_approx if_true absent @@ -2343,35 +2428,44 @@ and switch_defaults_on_undefined (sw : lambda_switch) = && (not (sw.sw_consts_full && sw.sw_consts <> [])) && List.for_all (function - | Switch_constructor (Constant {literal}), _ -> + | Switch_constructor (Constant {literal}), _, _ -> literal <> Variant_runtime.Undefined | _ -> true) sw.sw_consts | Switch_direct -> false let lower_constructor_matching_plan ~loc ~arg = function - | Use_constructor_action action -> action - | Test_payload_presence {test = Is_present_option; absent; present} + | Use_constructor_action (action, action_loc) -> (action, action_loc) + | Test_payload_presence + { + test = Is_present_option; + absent = absent, _; + present = present, present_loc; + } when value_test_defaults_on_undefined ~arg ~absent present -> - present - | Test_payload_presence {test; absent; present} -> + (present, present_loc) + | Test_payload_presence + {test; absent = absent, else_loc; present = present, then_loc} -> let condition = match test with | Is_present_option -> prim ~primitive:Pis_not_none ~args:[arg] loc | Is_nonempty_list -> prim ~primitive:(Pjscomp Cneq) ~args:[arg; const (const_int 0)] loc in - if_ condition present absent - | Test_boolean_value {if_false; if_true} -> if_ arg if_true if_false + (if_ ~loc ~then_loc ~else_loc condition present absent, no_branch_loc) + | Test_boolean_value + {if_false = if_false, else_loc; if_true = if_true, then_loc} -> + (if_ ~loc ~then_loc ~else_loc arg if_true if_false, no_branch_loc) | Switch_on_constructors sw -> let hs, sw = share_actions_sw sw in let sw = reintroduce_fail sw in - hs (switch arg sw) + (hs (switch arg sw), no_branch_loc) -let make_constructor_matching_plan ~cstr ~(layout : Variant_runtime.layout) +let make_constructor_matching_plan ~loc ~cstr ~(layout : Variant_runtime.layout) ~fail_opt ~num_consts ~num_nonconsts ~tag_lambda_list ~consts ~nonconsts = match (fail_opt, same_actions tag_lambda_list) with - | None, Some action -> Use_constructor_action action + | None, Some (action, action_loc) -> + Use_constructor_action (action, action_loc) | _ -> ( match (num_consts, num_nonconsts, consts, nonconsts) with | 1, 1, [(_, absent)], [(_, present)] @@ -2401,7 +2495,8 @@ let make_constructor_matching_plan ~cstr ~(layout : Variant_runtime.layout) | _, _, _, _ -> let switch_cases cases = List.map - (fun (cstr, action) -> (constructor_switch_key cstr, action)) + (fun (cstr, (action, arm_loc)) -> + (constructor_switch_key cstr, action, arm_loc)) cases in Switch_on_constructors @@ -2412,6 +2507,7 @@ let make_constructor_matching_plan ~cstr ~(layout : Variant_runtime.layout) sw_blocks = switch_cases nonconsts; sw_failaction = fail_opt; sw_dispatch = Switch_variant (Variant_runtime.matching_facts layout); + sw_loc = loc; }) let combine_constructor loc arg ex_pat cstr partial ctx def @@ -2424,7 +2520,7 @@ let combine_constructor loc arg ex_pat cstr partial ctx def if is_extension then (* Special cases for extensions *) let fail, local_jumps = mk_failaction_neg partial ctx def in - let lambda1 = + let lambda1, arm_loc = let extension_cases = get_extension_cases tag_lambda_list in let default, extension_cases = match fail with @@ -2438,28 +2534,30 @@ let combine_constructor loc arg ex_pat cstr partial ctx def | [] -> default | _ -> let tag = Ident.create "tag" in - let tests = + let tests, _ = List.fold_right - (fun (path, act) rem -> + (fun (path, (act, then_loc)) (rem, else_loc) -> let ext = Transl_path.transl_extension_path ex_pat.pat_env path in - if_ - (prim ~primitive:(Pstringcomp Ceq) - ~args: - [ - prim - ~primitive: - (Pfield (0, Fld_record {name = Literals.exception_id})) - ~args:[var tag] - loc; - ext; - ] - loc) - act rem) + ( if_ ~loc ~then_loc ~else_loc + (prim ~primitive:(Pstringcomp Ceq) + ~args: + [ + prim + ~primitive: + (Pfield + (0, Fld_record {name = Literals.exception_id})) + ~args:[var tag] + loc; + ext; + ] + loc) + act rem, + no_branch_loc )) extension_cases default in - let_ Alias tag arg tests + (let_ Alias tag arg tests, no_branch_loc) in - (lambda1, jumps_union local_jumps total1) + (lambda1, arm_loc, jumps_union local_jumps total1) else (* Regular concrete type *) let layout = Datarepr.constructor_variant cstr in @@ -2477,11 +2575,11 @@ let combine_constructor loc arg ex_pat cstr partial ctx def let consts = sort_constructor_cases consts and nonconsts = sort_constructor_cases nonconsts in let plan = - make_constructor_matching_plan ~cstr ~layout ~fail_opt ~num_consts + make_constructor_matching_plan ~loc ~cstr ~layout ~fail_opt ~num_consts ~num_nonconsts ~tag_lambda_list ~consts ~nonconsts in - let lambda1 = lower_constructor_matching_plan ~loc ~arg plan in - (lambda1, jumps_union local_jumps total1) + let lambda1, arm_loc = lower_constructor_matching_plan ~loc ~arg plan in + (lambda1, arm_loc, jumps_union local_jumps total1) let combine_variant loc row arg partial ctx def (tag_lambda_list, total1, _pats) = @@ -2495,8 +2593,11 @@ let combine_variant loc row arg partial ctx def (tag_lambda_list, total1, _pats) | _ -> incr num_constr) row.row_fields else num_constr := max_int; - let test_int_or_block arg if_int if_block = - if_ (prim ~primitive:Pis_poly_var_block ~args:[arg] loc) if_block if_int + let test_int_or_block arg (if_int, else_loc) (if_block, then_loc) = + ( if_ ~loc ~then_loc ~else_loc + (prim ~primitive:Pis_poly_var_block ~args:[arg] loc) + if_block if_int, + no_branch_loc ) in let sig_complete = List.length tag_lambda_list = !num_constr and one_action = same_actions tag_lambda_list in @@ -2512,7 +2613,7 @@ let combine_variant loc row arg partial ctx def (tag_lambda_list, total1, _pats) else mk_failaction_neg partial ctx def in let consts, nonconsts = split_variant_cases tag_lambda_list in - let lambda1 = + let lambda1, arm_loc = match (fail, one_action) with | None, Some act -> act | _, _ -> ( @@ -2521,7 +2622,7 @@ let combine_variant loc row arg partial ctx def (tag_lambda_list, total1, _pats) test_int_or_block arg act1 act2 | _, [] -> (* One can compare integers and pointers *) - Polyvar_pattern_match.make_test_sequence_variant_constant fail arg + Polyvar_pattern_match.make_test_sequence_variant_constant loc fail arg consts | [], _ -> ( let lam = @@ -2534,23 +2635,27 @@ let combine_variant loc row arg partial ctx def (tag_lambda_list, total1, _pats) | Some fail -> test_int_or_block arg fail lam) | _, _ -> let lam_const = - Polyvar_pattern_match.call_switcher_variant_constant fail arg consts + Polyvar_pattern_match.call_switcher_variant_constant loc fail arg + consts and lam_nonconst = Polyvar_pattern_match.call_switcher_variant_constr loc fail arg nonconsts in test_int_or_block arg lam_const lam_nonconst) in - (lambda1, jumps_union local_jumps total1) + (lambda1, arm_loc, jumps_union local_jumps total1) let combine_array loc arg partial ctx def (len_lambda_list, total1, _pats) = let fail, local_jumps = mk_failaction_neg partial ctx def in - let lambda1 = + let lambda1, arm_loc = let newvar = Ident.create "len" in - let switch = call_switcher fail (var newvar) 0 max_int len_lambda_list in - bind Alias newvar (prim ~primitive:Parraylength ~args:[arg] loc) switch + let switch, arm_loc = + call_switcher ~loc fail (var newvar) 0 max_int len_lambda_list + in + ( bind Alias newvar (prim ~primitive:Parraylength ~args:[arg] loc) switch, + arm_loc ) in - (lambda1, jumps_union local_jumps total1) + (lambda1, arm_loc, jumps_union local_jumps total1) (* Insertion of debugging events *) @@ -2580,11 +2685,11 @@ let compile_list compile_fun division = | [] -> c_rec totals rem | _ -> ( try - let lambda1, total1 = compile_fun cell.ctx cell.pm in + let lambda1, arm_loc1, total1 = compile_fun cell.ctx cell.pm in let c_rem, total, new_pats = c_rec (jumps_map ctx_combine total1 :: totals) rem in - ((key, lambda1) :: c_rem, total, cell.pat :: new_pats) + ((key, (lambda1, arm_loc1)) :: c_rem, total, cell.pat :: new_pats) with Unused -> c_rec totals rem)) in c_rec [] division @@ -2617,36 +2722,39 @@ let rec add_raised_exits raised lam = Lambda_traverse.iter (add_raised_exits raised) lam | _ -> Lambda_traverse.iter (add_raised_exits raised) lam -let compile_orhandlers compile_fun lambda1 total1 ctx to_catch = +let compile_orhandlers compile_fun lambda1 arm_loc1 total1 ctx to_catch = (* The exits of the match and of the handlers compiled so far *) let raised = Hashtbl.create 16 in add_raised_exits raised lambda1; - let rec do_rec r total_r = function - | [] -> (r, total_r) + let rec do_rec r arm_loc_r total_r = function + | [] -> (r, arm_loc_r, total_r) | (_, i, _, _) :: rem when not (Hashtbl.mem raised i) -> (* The or-pattern is unreachable, e.g. after a wildcard. Its handler is not compiled: with a guard and no default, its failure has no exit. *) - do_rec r total_r rem + do_rec r arm_loc_r total_r rem | (mat, i, vars, pm) :: rem -> ( try let ctx = select_columns mat ctx in - let handler_i, total_i = compile_fun ctx pm in + let handler_i, handler_loc, total_i = compile_fun ctx pm in add_raised_exits raised handler_i; match as_exit_call r with | Some (j, args) -> if i = j then ( List.fold_right2 (bind Alias) vars args handler_i, + handler_loc, jumps_map (ctx_rshift_num (ncols mat)) total_i ) - else do_rec r total_r rem + else do_rec r arm_loc_r total_r rem | None -> do_rec - (staticcatch r (i, vars) handler_i) + (staticcatch ~loc:handler_loc r (i, vars) handler_i) + arm_loc_r (jumps_union (jumps_remove i total_r) (jumps_map (ctx_rshift_num (ncols mat)) total_i)) rem - with Unused -> do_rec (staticcatch r (i, vars) lambda_unit) total_r rem) + with Unused -> + do_rec (staticcatch r (i, vars) lambda_unit) arm_loc_r total_r rem) in - do_rec lambda1 total1 to_catch + do_rec lambda1 arm_loc1 total1 to_catch let compile_test compile_fun partial divide combine ctx to_match = let division = divide ctx to_match in @@ -2655,7 +2763,7 @@ let compile_test compile_fun partial divide combine ctx to_match = | [], _, _ -> ( match mk_failaction_neg partial ctx to_match.default with | None, _ -> raise Unused - | Some l, total -> (l, total)) + | Some (l, loc), total -> (l, loc, total)) | _ -> combine ctx to_match.default c_div (* Attempt to avoid some useless bindings by lowering them *) @@ -2672,21 +2780,23 @@ let rec approx_present v = function let rec lower_bind v arg lam = match lam with - | Lifthenelse (cond, ifso, ifnot) -> ( + | Lifthenelse (cond, ifso, ifnot, {if_loc; then_loc; else_loc}) -> ( let pcond = approx_present v cond and pso = approx_present v ifso and pnot = approx_present v ifnot in match (pcond, pso, pnot) with | false, false, false -> lam - | false, true, false -> if_ cond (lower_bind v arg ifso) ifnot - | false, false, true -> if_ cond ifso (lower_bind v arg ifnot) + | false, true, false -> + if_ ~loc:if_loc ~then_loc ~else_loc cond (lower_bind v arg ifso) ifnot + | false, false, true -> + if_ ~loc:if_loc ~then_loc ~else_loc cond ifso (lower_bind v arg ifnot) | _, _, _ -> bind Alias v arg lam) - | Lswitch (ls, ({sw_consts = [(i, act)]; sw_blocks = []} as sw)) + | Lswitch (ls, ({sw_consts = [(i, act, loc)]; sw_blocks = []} as sw)) when not (approx_present v ls) -> - switch ls {sw with sw_consts = [(i, lower_bind v arg act)]} - | Lswitch (ls, ({sw_consts = []; sw_blocks = [(i, act)]} as sw)) + switch ls {sw with sw_consts = [(i, lower_bind v arg act, loc)]} + | Lswitch (ls, ({sw_consts = []; sw_blocks = [(i, act, loc)]} as sw)) when not (approx_present v ls) -> - switch ls {sw with sw_blocks = [(i, lower_bind v arg act)]} + switch ls {sw with sw_blocks = [(i, lower_bind v arg act, loc)]} | Llet (Alias, vv, lv, l) -> if approx_present v lv then bind Alias v arg lam else let_ Alias vv lv (lower_bind v arg l) @@ -2704,24 +2814,24 @@ let bind_check str v arg lam = let comp_exit ctx m = match m.default with - | (_, i) :: _ -> (staticraise i [], jumps_singleton i ctx) + | (_, i) :: _ -> (staticraise i [], no_branch_loc, jumps_singleton i ctx) | _ -> fatal_error "Matching.comp_exit" let rec comp_match_handlers comp_fun partial ctx arg first_match next_matchs = match next_matchs with | [] -> comp_fun partial ctx arg first_match | rem -> ( - let rec c_rec body total_body = function - | [] -> (body, total_body) + let rec c_rec body arm_loc total_body = function + | [] -> (body, arm_loc, total_body) (* Hum, -1 means never taken | (-1,pm)::rem -> c_rec body total_body rem *) | (i, pm) :: rem -> ( let ctx_i, total_rem = jumps_extract i total_body in match ctx_i with - | [] -> c_rec body total_body rem + | [] -> c_rec body arm_loc total_body rem | _ -> ( try - let li, total_i = + let li, li_loc, total_i = comp_fun (match rem with | [] -> partial @@ -2729,15 +2839,16 @@ let rec comp_match_handlers comp_fun partial ctx arg first_match next_matchs = ctx_i arg pm in c_rec - (staticcatch body (i, []) li) + (staticcatch ~loc:li_loc body (i, []) li) + arm_loc (jumps_union total_i total_rem) rem with Unused -> - c_rec (staticcatch body (i, []) lambda_unit) total_rem rem)) + c_rec (staticcatch body (i, []) lambda_unit) arm_loc total_rem rem)) in try - let first_lam, total = comp_fun Partial ctx arg first_match in - c_rec first_lam total rem + let first_lam, first_loc, total = comp_fun Partial ctx arg first_match in + c_rec first_lam first_loc total rem with Unused -> ( match next_matchs with | [] -> raise Unused @@ -2773,15 +2884,17 @@ let arg_to_var arg cls = (* The main compilation function. Input: + switch_loc=location of the enclosing match/try expression repr=used for inserting debug events partial=exhaustiveness information from Parmatch ctx=a context m=a pattern matching - Output: a lambda term, a jump summary {..., exit number -> context, .. } + Output: a lambda term, its arm location when it represents one arm, and a + jump summary {..., exit number -> context, .. } *) -let rec compile_match repr partial ctx m = +let rec compile_match ~switch_loc repr partial ctx m = match m with | {cases = []; args = []} -> comp_exit ctx m | {cases = ([], action) :: rem} -> ( @@ -2789,18 +2902,24 @@ let rec compile_match repr partial ctx m = falls through to the remaining rows when the guard fails, so those are compiled first and become the alternative. *) match action.guard with - | None -> (action_body_with ~fail:lambda_unit action, jumps_empty) + | None -> + (action_body_with ~fail:lambda_unit action, action.loc, jumps_empty) | Some _ -> - let fail, total = compile_match None partial ctx {m with cases = rem} in - (action_body_with ~fail action, total)) + let fail, fail_loc, total = + compile_match ~switch_loc None partial ctx {m with cases = rem} + in + ( action_body_with ~fail ~fail_loc action, + {pat_loc = action.loc.pat_loc; body_loc = Location.none}, + total )) | {args = (arg, str) :: argl} -> let v, newarg = arg_to_var arg m.cases in let first_match, rem = split_precompile (Some v) {m with args = (newarg, Alias) :: argl} in - let lam, total = + let lam, arm_loc, total = comp_match_handlers - ((if dbg then do_compile_matching_pr else do_compile_matching) repr) + ((if dbg then do_compile_matching_pr else do_compile_matching) + ~switch_loc repr) partial ctx newarg first_match rem in (* A mutable field or array element is read once into [v] here. The code @@ -2812,12 +2931,12 @@ let rec compile_match repr partial ctx m = | StrictOpt -> jumps_map ctx_erase_first_col total | Strict | Alias | Variable -> total in - (bind_check str v arg lam, total) + (bind_check str v arg lam, arm_loc, total) | _ -> assert false (* verbose version of do_compile_matching, for debug *) -and do_compile_matching_pr repr partial ctx arg x = +and do_compile_matching_pr ~switch_loc repr partial ctx arg x = prerr_string "COMPILE: "; prerr_endline (match partial with @@ -2827,63 +2946,72 @@ and do_compile_matching_pr repr partial ctx arg x = pretty_precompiled x; prerr_endline "CTX"; pretty_ctx ctx; - let ((_, jumps) as r) = do_compile_matching repr partial ctx arg x in + let ((_, _, jumps) as r) = + do_compile_matching ~switch_loc repr partial ctx arg x + in prerr_endline "JUMPS"; pretty_jumps jumps; r -and do_compile_matching repr partial ctx arg pmh = +and do_compile_matching ~switch_loc repr partial ctx arg pmh = match pmh with | Pm pm -> ( let pat = what_is_cases pm.cases in match pat.pat_desc with - | Tpat_any -> compile_no_test divide_var ctx_rshift repr partial ctx pm + | Tpat_any -> + compile_no_test ~switch_loc divide_var ctx_rshift repr partial ctx pm | Tpat_tuple patl -> - compile_no_test - (divide_tuple (List.length patl) (normalize_pat pat)) + compile_no_test ~switch_loc + (divide_tuple ~switch_loc (List.length patl) (normalize_pat pat)) ctx_combine repr partial ctx pm | Tpat_record ((_, lbl, _, _) :: _, _, _rest) -> - compile_no_test - (divide_record lbl.lbl_all (normalize_pat pat)) + compile_no_test ~switch_loc + (divide_record ~switch_loc lbl.lbl_all (normalize_pat pat)) ctx_combine repr partial ctx pm | Tpat_constant cst | Tpat_interval (cst, _) -> compile_test - (compile_match repr partial) + (compile_match ~switch_loc repr partial) partial divide_constant - (combine_constant pat.pat_loc arg cst partial) + (combine_constant switch_loc arg cst partial) ctx pm | Tpat_construct (_, cstr, _) -> compile_test - (compile_match repr partial) - partial divide_constructor - (combine_constructor pat.pat_loc arg pat cstr partial) + (compile_match ~switch_loc repr partial) + partial + (divide_constructor ~switch_loc) + (combine_constructor switch_loc arg pat cstr partial) ctx pm | Tpat_array _ -> compile_test - (compile_match repr partial) - partial divide_array - (combine_array pat.pat_loc arg partial) + (compile_match ~switch_loc repr partial) + partial (divide_array ~switch_loc) + (combine_array switch_loc arg partial) ctx pm | Tpat_variant (_, _, row) -> compile_test - (compile_match repr partial) - partial (divide_variant !row) - (combine_variant pat.pat_loc !row arg partial) + (compile_match ~switch_loc repr partial) + partial + (divide_variant ~switch_loc !row) + (combine_variant switch_loc !row arg partial) ctx pm | _ -> assert false) | PmVar {inside = pmh; var_arg = arg} -> - let lam, total = - do_compile_matching repr partial (ctx_lshift ctx) arg pmh + let lam, arm_loc, total = + do_compile_matching ~switch_loc repr partial (ctx_lshift ctx) arg pmh in - (lam, jumps_map ctx_rshift total) + (lam, arm_loc, jumps_map ctx_rshift total) | PmOr {body; handlers} -> - let lam, total = compile_match repr partial ctx body in - compile_orhandlers (compile_match repr partial) lam total ctx handlers + let lam, arm_loc, total = compile_match ~switch_loc repr partial ctx body in + compile_orhandlers + (compile_match ~switch_loc repr partial) + lam arm_loc total ctx handlers -and compile_no_test divide up_ctx repr partial ctx to_match = +and compile_no_test ~switch_loc divide up_ctx repr partial ctx to_match = let {pm = this_match; ctx = this_ctx} = divide ctx to_match in - let lambda, total = compile_match repr partial this_ctx this_match in - (lambda, jumps_map up_ctx total) + let lambda, arm_loc, total = + compile_match ~switch_loc repr partial this_ctx this_match + in + (lambda, arm_loc, jumps_map up_ctx total) (* The entry points *) @@ -2965,11 +3093,11 @@ let check_partial = check_partial is_mutable let start_ctx n = [{left = []; right = omegas n}] -let check_total total lambda i handler_fun = +let check_total ~loc total lambda i handler_fun = if jumps_is_empty total then lambda - else staticcatch lambda (i, []) (handler_fun ()) + else staticcatch ~loc:(branch_loc loc) lambda (i, []) (handler_fun ()) -let compile_matching repr handler_fun arg pat_act_list partial = +let compile_matching ~switch_loc repr handler_fun arg pat_act_list partial = let partial = check_partial pat_act_list partial in match partial with | Partial -> ( @@ -2982,8 +3110,10 @@ let compile_matching repr handler_fun arg pat_act_list partial = } in try - let lambda, total = compile_match repr partial (start_ctx 1) pm in - check_total total lambda raise_num handler_fun + let lambda, _, total = + compile_match ~switch_loc repr partial (start_ctx 1) pm + in + check_total ~loc:switch_loc total lambda raise_num handler_fun with Unused -> assert false (* ; handler_fun() *)) | Total -> let pm = @@ -2993,7 +3123,9 @@ let compile_matching repr handler_fun arg pat_act_list partial = default = []; } in - let lambda, total = compile_match repr partial (start_ctx 1) pm in + let lambda, _, total = + compile_match ~switch_loc repr partial (start_ctx 1) pm + in assert (jumps_is_empty total); lambda @@ -3023,17 +3155,18 @@ let lower_dict_patterns pat_act_list = let for_function loc repr param pat_act_list partial = let pat_act_list = lower_dict_patterns pat_act_list in - compile_matching repr (partial_function loc) param pat_act_list partial + compile_matching ~switch_loc:loc repr (partial_function loc) param + pat_act_list partial (* In the following two cases, exhaustiveness info is not available! *) -let for_trywith param pat_act_list = +let for_trywith loc param pat_act_list = let pat_act_list = lower_dict_patterns pat_act_list in - compile_matching None - (fun () -> prim ~primitive:Praise ~args:[param] Location.none) + compile_matching ~switch_loc:loc None + (fun () -> prim ~primitive:Praise ~args:[param] loc) param pat_act_list Partial let simple_for_let loc param pat body = - compile_matching None (partial_function loc) param + compile_matching ~switch_loc:loc None (partial_function loc) param (lower_dict_patterns [(pat, unguarded body)]) Partial @@ -3162,12 +3295,14 @@ let flatten_precompiled size args pmh = Hence it needs a fourth argument, which it ignores *) -let compile_flattened repr partial ctx _ pmh = +let compile_flattened ~switch_loc repr partial ctx _ pmh = match pmh with - | Pm pm -> compile_match repr partial ctx pm + | Pm pm -> compile_match ~switch_loc repr partial ctx pm | PmOr {body = b; handlers = hs} -> - let lam, total = compile_match repr partial ctx b in - compile_orhandlers (compile_match repr partial) lam total ctx hs + let lam, arm_loc, total = compile_match ~switch_loc repr partial ctx b in + compile_orhandlers + (compile_match ~switch_loc repr partial) + lam arm_loc total ctx hs | PmVar _ -> assert false let do_for_multiple_match loc paraml pat_act_list partial = @@ -3208,20 +3343,24 @@ let do_for_multiple_match loc paraml pat_act_list partial = List.map (fun (e, pm) -> (e, flatten_precompiled size args pm)) nexts in - let lam, total = - comp_match_handlers (compile_flattened repr) partial (start_ctx size) () - flat_next flat_nexts + let lam, _, total = + comp_match_handlers + (compile_flattened ~switch_loc:loc repr) + partial (start_ctx size) () flat_next flat_nexts in List.fold_right2 (bind Strict) idl paraml (match partial with - | Partial -> check_total total lam raise_num (partial_function loc) + | Partial -> check_total ~loc total lam raise_num (partial_function loc) | Total -> assert (jumps_is_empty total); lam) with Cannot_flatten -> ( - let lambda, total = compile_match None partial (start_ctx 1) pm1 in + let lambda, _, total = + compile_match ~switch_loc:loc None partial (start_ctx 1) pm1 + in match partial with - | Partial -> check_total total lambda raise_num (partial_function loc) + | Partial -> + check_total ~loc total lambda raise_num (partial_function loc) | Total -> assert (jumps_is_empty total); lambda) diff --git a/compiler/typing/matching.mli b/compiler/typing/matching.mli index b7dfecf700b..fbb4dcde163 100644 --- a/compiler/typing/matching.mli +++ b/compiler/typing/matching.mli @@ -22,9 +22,14 @@ open Typedtree to be recognized by shape later. *) type action -val unguarded : Lambda.t -> action +val unguarded : ?loc:Lambda.branch_loc -> Lambda.t -> action -val guarded : guard:Lambda.t -> Lambda.t -> action +val guarded : + ?loc:Lambda.branch_loc -> + guard:Lambda.t -> + ?guard_loc:Location.t -> + Lambda.t -> + action (* Entry points to match compiler *) val for_function : @@ -34,7 +39,7 @@ val for_function : (pattern * action) list -> partial -> Lambda.t -val for_trywith : Lambda.t -> (pattern * action) list -> Lambda.t +val for_trywith : Location.t -> Lambda.t -> (pattern * action) list -> Lambda.t val for_let : Location.t -> Lambda.t -> pattern -> Lambda.t -> Lambda.t val for_multiple_match : Location.t -> Lambda.t list -> (pattern * action) list -> partial -> Lambda.t diff --git a/compiler/typing/polyvar_pattern_match.ml b/compiler/typing/polyvar_pattern_match.ml index 5bd14c3c082..a97943e186a 100644 --- a/compiler/typing/polyvar_pattern_match.ml +++ b/compiler/typing/polyvar_pattern_match.ml @@ -24,11 +24,13 @@ type lam = Lambda.t +type located_lam = Lambda.t * Lambda.branch_loc + type names = string list -type input = (int * (string * lam)) list +type input = (int * (string * located_lam)) list -type output = (names * lam) list +type output = (names * located_lam) list module Coll = Hashtbl.Make (struct type t = lam @@ -38,32 +40,32 @@ module Coll = Hashtbl.Make (struct let hash = Hashtbl.hash end) -type value = {stamp: int; names_act: names * lam} +type value = {stamp: int; names_act: names * located_lam} let convert (xs : input) : output = let coll = Coll.create 63 in let os : value list ref = ref [] in xs - |> List.iteri (fun i (_hash, (name, act)) -> + |> List.iteri (fun i (_hash, (name, ((act, _) as located))) -> match Lambda_traverse.make_key act with - | None -> os := {stamp = i; names_act = ([name], act)} :: !os + | None -> os := {stamp = i; names_act = ([name], located)} :: !os | Some key -> ( match Coll.find_opt coll key with - | Some ({names_act = names, act} as acc) -> - Coll.replace coll key {acc with names_act = (name :: names, act)} - | None -> Coll.add coll key {names_act = ([name], act); stamp = i})); + | Some ({names_act = names, located} as acc) -> + Coll.replace coll key {acc with names_act = (name :: names, located)} + | None -> Coll.add coll key {names_act = ([name], located); stamp = i})); let result = Coll.fold (fun _ value acc -> value :: acc) coll !os in Ext_list.sort_via_arrayf result (fun x y -> compare x.stamp y.stamp) (fun x -> x.names_act) -let or_list (arg : lam) (names : names) = +let or_list ~loc (arg : lam) (names : names) = match names with | name :: rest -> let init : lam = Lambda.prim ~primitive:(Pintcomp Ceq) ~args:[arg; Lambda.const (Lambda.const_polyvar name)] - Location.none + loc in List.fold_left (fun acc name -> @@ -73,21 +75,23 @@ let or_list (arg : lam) (names : names) = acc; Lambda.prim ~primitive:(Pintcomp Ceq) ~args:[arg; Lambda.const (Lambda.const_polyvar name)] - Location.none; + loc; ] - Location.none) + loc) init rest | _ -> assert false -let make_test_sequence_variant_constant (fail : lam option) (arg : lam) - (int_lambda_list : (int * (string * lam)) list) : lam = +let make_test_sequence_variant_constant (loc : Location.t) + (fail : located_lam option) (arg : lam) (int_lambda_list : input) : + located_lam = let names_lambda_list : output = convert int_lambda_list in match (names_lambda_list, fail) with | (_, act) :: rest, None | rest, Some act -> List.fold_right - (fun (names, act1) acc -> - let predicate : lam = or_list arg names in - Lambda.if_ predicate act1 acc) + (fun (names, (act1, then_loc)) (acc, else_loc) -> + let predicate : lam = or_list ~loc arg names in + ( Lambda.if_ ~loc ~then_loc ~else_loc predicate act1 acc, + Lambda.no_branch_loc )) rest act | [], None -> assert false @@ -95,9 +99,13 @@ let make_test_sequence_variant_constant (fail : lam option) (arg : lam) same chain of tag tests. *) let call_switcher_variant_constant = make_test_sequence_variant_constant -let call_switcher_variant_constr (loc : Location.t) (fail : lam option) - (arg : lam) int_lambda_list : lam = +let call_switcher_variant_constr (loc : Location.t) (fail : located_lam option) + (arg : lam) (int_lambda_list : input) : located_lam = let v = Ident.create "variant" in - Lambda.let_ Alias v - (Lambda.prim ~primitive:(Pfield (0, Fld_poly_var_tag)) ~args:[arg] loc) - (call_switcher_variant_constant fail (Lambda.var v) int_lambda_list) + let sw, arm_loc = + call_switcher_variant_constant loc fail (Lambda.var v) int_lambda_list + in + ( Lambda.let_ Alias v + (Lambda.prim ~primitive:(Pfield (0, Fld_poly_var_tag)) ~args:[arg] loc) + sw, + arm_loc ) diff --git a/compiler/typing/printlambda.ml b/compiler/typing/printlambda.ml index 12f340fc9ba..186bcdea1c1 100644 --- a/compiler/typing/printlambda.ml +++ b/compiler/typing/printlambda.ml @@ -293,7 +293,7 @@ let rec lam ppf = function let switch ppf sw = let spc = ref false in List.iter - (fun (key, l) -> + (fun (key, l, _) -> if !spc then fprintf ppf "@ " else spc := true; match key with | Switch_int ordinal -> @@ -303,7 +303,7 @@ let rec lam ppf = function | Switch_constructor (Block _) -> assert false) sw.sw_consts; List.iter - (fun (key, l) -> + (fun (key, l, _) -> if !spc then fprintf ppf "@ " else spc := true; match key with | Switch_int ordinal -> @@ -315,7 +315,7 @@ let rec lam ppf = function sw.sw_blocks; match sw.sw_failaction with | None -> () - | Some l -> + | Some (l, _) -> if !spc then fprintf ppf "@ " else spc := true; fprintf ppf "@[default:@ %a@]" lam l in @@ -324,16 +324,16 @@ let rec lam ppf = function | None -> "switch*" | _ -> "switch") lam larg switch sw - | Lstringswitch (arg, cases, default) -> + | Lstringswitch (arg, cases, default, _) -> let switch ppf cases = let spc = ref false in List.iter - (fun (s, l) -> + (fun (s, l, _) -> if !spc then fprintf ppf "@ " else spc := true; fprintf ppf "@[case \"%s\":@ %a@]" (String.escaped s) lam l) cases; match default with - | Some default -> + | Some (default, _) -> if !spc then fprintf ppf "@ " else spc := true; fprintf ppf "@[default:@ %a@]" lam default | None -> () @@ -342,7 +342,7 @@ let rec lam ppf = function | Lstaticraise (i, ls) -> let lams ppf largs = List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in fprintf ppf "@[<2>(exit@ %d%a)@]" i lams ls - | Lstaticcatch (lbody, (i, vars), lhandler) -> + | Lstaticcatch (lbody, (i, vars), lhandler, _) -> fprintf ppf "@[<2>(catch@ %a@;<1 -1>with (%d%a)@ %a)@]" lam lbody i (fun ppf vars -> match vars with @@ -354,7 +354,7 @@ let rec lam ppf = function param lam lhandler | Ltryfinally (lbody, lfinally) -> fprintf ppf "@[<2>(try@ %a@;<1 -1>finally@ %a)@]" lam lbody lam lfinally - | Lifthenelse (lcond, lif, lelse) -> + | Lifthenelse (lcond, lif, lelse, _) -> fprintf ppf "@[<2>(if@ %a@ %a@ %a)@]" lam lcond lam lif lam lelse | Lsequence (l1, l2) -> fprintf ppf "@[<2>(seq@ %a@ %a)@]" lam l1 sequence l2 | Lbreak -> fprintf ppf "break" diff --git a/compiler/typing/switch.ml b/compiler/typing/switch.ml index 7b783a2eca2..40f881c4e62 100644 --- a/compiler/typing/switch.ml +++ b/compiler/typing/switch.ml @@ -99,25 +99,27 @@ let ltint = Pintcomp Clt let geint = Pintcomp Cge let gtint = Pintcomp Cgt -let prim p args : Lambda.t = prim ~primitive:p ~args Location.none +let prim ~loc p args : Lambda.t = prim ~primitive:p ~args loc (* [covers_range cases ~start ~finish] holds when [cases] is exactly the contiguous integer keys [start .. finish], in order. *) -let rec covers_range (cases : (switch_key * Lambda.t) list) ~start ~finish = +let rec covers_range (cases : (switch_key * Lambda.t * branch_loc) list) ~start + ~finish = match cases with | [] -> finish < start - | (Switch_int i, _) :: rest -> + | (Switch_int i, _, _) :: rest -> start <= finish && i = start && covers_range rest ~start:(start + 1) ~finish - | (Switch_constructor _, _) :: _ -> false + | (Switch_constructor _, _, _) :: _ -> false (* [arg] is outside [lo .. hi]. A two-value range reads better as a pair of equality tests than as a pair of comparisons. *) -let out_of_range arg ~lo ~hi = - let test cmp k = prim (Pintcomp cmp) [arg; const (const_int k)] in - if hi = lo + 1 then prim Pnot [prim Psequor [test Ceq lo; test Ceq hi]] - else prim Psequor [test Cgt hi; test Clt lo] +let out_of_range ~loc arg ~lo ~hi = + let test cmp k = prim ~loc (Pintcomp cmp) [arg; const (const_int k)] in + if hi = lo + 1 then + prim ~loc Pnot [prim ~loc Psequor [test Ceq lo; test Ceq hi]] + else prim ~loc Psequor [test Cgt hi; test Clt lo] -let emit_if_out ~offset ~range arg ifso ifno = +let emit_if_out ~loc ~offset ~range arg (ifso, then_loc) (ifno, else_loc) = let lo = -offset and hi = range - offset in match (arg, ifno) with (* The switcher guards a jump table with a range test, because on a machine @@ -134,27 +136,37 @@ let emit_if_out ~offset ~range arg ifso ifno = sw_failaction = None; } as sw) ) ) when Ident.same x y && covers_range sw_consts ~start:lo ~finish:hi -> - switch sarg {sw with sw_failaction = Some ifso; sw_consts_full = false} - | _ -> if_ (out_of_range arg ~lo ~hi) ifso ifno - -let emit_if_in ~offset ~range arg ifso ifno = + ( switch sarg + {sw with sw_failaction = Some (ifso, then_loc); sw_consts_full = false}, + no_branch_loc ) + | _ -> + ( if_ ~loc ~then_loc ~else_loc (out_of_range ~loc arg ~lo ~hi) ifso ifno, + no_branch_loc ) + +let emit_if_in ~loc ~offset ~range arg (ifso, then_loc) (ifno, else_loc) = let lo = -offset and hi = range - offset in - if_ (prim Pnot [out_of_range arg ~lo ~hi]) ifso ifno + ( if_ ~loc ~then_loc ~else_loc + (prim ~loc Pnot [out_of_range ~loc arg ~lo ~hi]) + ifso ifno, + no_branch_loc ) -let emit_switch arg cases acts ~offset : Lambda.t = +let emit_switch ~loc arg cases acts ~offset : Lambda.t * branch_loc = let l = ref [] in for i = Array.length cases - 1 downto 0 do - l := (Switch_int (offset + i), acts.(cases.(i))) :: !l + let act, arm_loc = acts.(cases.(i)) in + l := (Switch_int (offset + i), act, arm_loc) :: !l done; - switch arg - { - sw_consts_full = true; - sw_consts = !l; - sw_blocks_full = true; - sw_blocks = []; - sw_failaction = None; - sw_dispatch = Switch_direct; - } + ( switch arg + { + sw_consts_full = true; + sw_consts = !l; + sw_blocks_full = true; + sw_blocks = []; + sw_failaction = None; + sw_dispatch = Switch_direct; + sw_loc = loc; + }, + no_branch_loc ) (* The module will ``produce good code for the case statement'' *) (* @@ -472,30 +484,33 @@ and enum top cases = rc := with_sep); (!r, !rc) -let make_if_test test arg i ifso ifnot = - if_ (prim test [arg; const (const_int i)]) ifso ifnot +let make_if_test ~loc test arg i (ifso, then_loc) (ifnot, else_loc) = + ( if_ ~loc ~then_loc ~else_loc + (prim ~loc test [arg; const (const_int i)]) + ifso ifnot, + no_branch_loc ) -let make_if_lt arg i ifso ifnot = +let make_if_lt ~loc arg i ifso ifnot = match i with - | 1 -> make_if_test leint arg 0 ifso ifnot - | _ -> make_if_test ltint arg i ifso ifnot + | 1 -> make_if_test ~loc leint arg 0 ifso ifnot + | _ -> make_if_test ~loc ltint arg i ifso ifnot -and make_if_ge arg i ifso ifnot = +and make_if_ge ~loc arg i ifso ifnot = match i with - | 1 -> make_if_test gtint arg 0 ifso ifnot - | _ -> make_if_test geint arg i ifso ifnot + | 1 -> make_if_test ~loc gtint arg 0 ifso ifnot + | _ -> make_if_test ~loc geint arg i ifso ifnot -and make_if_eq arg i ifso ifnot = make_if_test eqint arg i ifso ifnot +and make_if_eq ~loc arg i ifso ifnot = make_if_test ~loc eqint arg i ifso ifnot -and make_if_ne arg i ifso ifnot = make_if_test neint arg i ifso ifnot +and make_if_ne ~loc arg i ifso ifnot = make_if_test ~loc neint arg i ifso ifnot -let make_if_out ctx l d mk_ifso mk_ifno = - emit_if_out ~offset:(-l) ~range:d ctx.arg (mk_ifso ctx) (mk_ifno ctx) +let make_if_out ~loc ctx l d mk_ifso mk_ifno = + emit_if_out ~loc ~offset:(-l) ~range:d ctx.arg (mk_ifso ctx) (mk_ifno ctx) -let make_if_in ctx l d mk_ifso mk_ifno = - emit_if_in ~offset:(-l) ~range:d ctx.arg (mk_ifso ctx) (mk_ifno ctx) +let make_if_in ~loc ctx l d mk_ifso mk_ifno = + emit_if_in ~loc ~offset:(-l) ~range:d ctx.arg (mk_ifso ctx) (mk_ifno ctx) -let rec c_test ctx ({cases; actions} as s) = +let rec c_test ~loc ctx ({cases; actions} as s) = let lcases = Array.length cases in assert (lcases > 0); if lcases = 1 then actions.(get_act cases 0) ctx @@ -516,21 +531,21 @@ let rec c_test ctx ({cases; actions} as s) = in the privileged (positive) branch of ``if'' *) if low = high then if less_tests coutside cinside then - make_if_eq ctx.arg (low + ctx.off) - (c_test ctx {s with cases = inside}) - (c_test ctx {s with cases = outside}) + make_if_eq ~loc ctx.arg (low + ctx.off) + (c_test ~loc ctx {s with cases = inside}) + (c_test ~loc ctx {s with cases = outside}) else - make_if_ne ctx.arg (low + ctx.off) - (c_test ctx {s with cases = outside}) - (c_test ctx {s with cases = inside}) + make_if_ne ~loc ctx.arg (low + ctx.off) + (c_test ~loc ctx {s with cases = outside}) + (c_test ~loc ctx {s with cases = inside}) else if less_tests coutside cinside then - make_if_in ctx (low + ctx.off) (high - low) - (fun ctx -> c_test ctx {s with cases = inside}) - (fun ctx -> c_test ctx {s with cases = outside}) + make_if_in ~loc ctx (low + ctx.off) (high - low) + (fun ctx -> c_test ~loc ctx {s with cases = inside}) + (fun ctx -> c_test ~loc ctx {s with cases = outside}) else - make_if_out ctx (low + ctx.off) (high - low) - (fun ctx -> c_test ctx {s with cases = outside}) - (fun ctx -> c_test ctx {s with cases = inside}) + make_if_out ~loc ctx (low + ctx.off) (high - low) + (fun ctx -> c_test ~loc ctx {s with cases = outside}) + (fun ctx -> c_test ~loc ctx {s with cases = inside}) | Sep i -> let lim, left, right = coupe cases i in let _, (cleft, _) = opt_count false left @@ -538,11 +553,13 @@ let rec c_test ctx ({cases; actions} as s) = let left = {s with cases = left} and right = {s with cases = right} in if i = 1 && lim + ctx.off = 1 && get_low cases 0 + ctx.off = 0 then - make_if_ne ctx.arg 0 (c_test ctx right) (c_test ctx left) + make_if_ne ~loc ctx.arg 0 (c_test ~loc ctx right) (c_test ~loc ctx left) else if less_tests cright cleft then - make_if_lt ctx.arg (lim + ctx.off) (c_test ctx left) (c_test ctx right) + make_if_lt ~loc ctx.arg (lim + ctx.off) (c_test ~loc ctx left) + (c_test ~loc ctx right) else - make_if_ge ctx.arg (lim + ctx.off) (c_test ctx right) (c_test ctx left) + make_if_ge ~loc ctx.arg (lim + ctx.off) (c_test ~loc ctx right) + (c_test ~loc ctx left) (* Minimal density of switches *) let theta = ref 0.33333 @@ -603,7 +620,7 @@ let comp_clusters s = (min_clusters.(len - 1), k) (* Assume j > i *) -let make_switch {cases; actions} i j = +let make_switch ~loc {cases; actions} i j = let ll, _, _ = cases.(i) and _, hh, _ = cases.(j) in let tbl = Array.make (hh - ll + 1) 0 and t = Hashtbl.create 17 @@ -626,9 +643,9 @@ let make_switch {cases; actions} i j = done; let acts = Array.make !index actions.(0) in Hashtbl.iter (fun act i -> acts.(i) <- actions.(act)) t; - fun ctx -> emit_switch ~offset:(ll + ctx.off) ctx.arg tbl acts + fun ctx -> emit_switch ~loc ~offset:(ll + ctx.off) ctx.arg tbl acts -let make_clusters ({cases; actions} as s) n_clusters k = +let make_clusters ~loc ({cases; actions} as s) n_clusters k = let len = Array.length cases in let r = Array.make n_clusters (0, 0, 0) and t = Hashtbl.create 17 @@ -659,7 +676,7 @@ let make_clusters ({cases; actions} as s) n_clusters k = else (* assert i < j *) let l, _, _ = cases.(i) and _, h, _ = cases.(j) in - r.(ir) <- (l, h, add_index (make_switch s i j))); + r.(ir) <- (l, h, add_index (make_switch ~loc s i j))); if i > 0 then zyva (i - 1) (ir - 1) in @@ -668,7 +685,7 @@ let make_clusters ({cases; actions} as s) n_clusters k = Hashtbl.iter (fun _ (i, act) -> acts.(i) <- act) t; {cases = r; actions = acts} -let do_zyva (low, high) arg cases actions = +let do_zyva ~loc (low, high) arg cases actions = let old_ok = !(ok_inter ()) in ok_inter () := abs low <= inter_limit && abs high <= inter_limit; if !(ok_inter ()) <> old_ok then Hashtbl.clear (cache ()); @@ -681,8 +698,8 @@ let do_zyva (low, high) arg cases actions = prerr_endline "" ; *) let n_clusters, k = comp_clusters s in - let clusters = make_clusters s n_clusters k in - c_test {arg; off = 0} clusters + let clusters = make_clusters ~loc s n_clusters k in + c_test ~loc {arg; off = 0} clusters let abstract_shared actions = let handlers = ref (fun x -> x) in @@ -691,17 +708,18 @@ let abstract_shared actions = (fun act -> match act with | Single act -> act - | Shared act -> - let i, h = Lambda_exits.make_catch_delayed act in + | Shared (act, arm_loc) -> + let i, h = Lambda_exits.make_catch_delayed ~loc:arm_loc act in let oh = !handlers in (handlers := fun act -> h (oh act)); - Lambda_exits.make_exit i) + (Lambda_exits.make_exit i, arm_loc)) actions in (!handlers, actions) -let zyva lh arg cases actions = +let zyva ~loc lh arg cases actions = assert (Array.length cases > 0); let actions = actions.act_get_shared () in let hs, actions = abstract_shared actions in - hs (do_zyva lh arg cases actions) + let lam, arm_loc = do_zyva ~loc lh arg cases actions in + (hs lam, arm_loc) diff --git a/compiler/typing/switch.mli b/compiler/typing/switch.mli index 27208488196..b58b08c0e1d 100644 --- a/compiler/typing/switch.mli +++ b/compiler/typing/switch.mli @@ -59,8 +59,9 @@ end returns an action that performs the switch. *) val zyva : + loc:Location.t -> int * int -> Lambda.t -> (int * int * int) array -> - Lambda.t t_store -> - Lambda.t + (Lambda.t * Lambda.branch_loc) t_store -> + Lambda.t * Lambda.branch_loc diff --git a/compiler/typing/translcore.ml b/compiler/typing/translcore.ml index f4741f028f8..0478206be03 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -917,10 +917,7 @@ let wrap_exn loc arg = loc) [arg] loc let exception_id_destructed (l : Lambda.t) (fv : Ident.t) : bool = - let rec hit_opt = function - | None -> false - | Some a -> hit a - and hit_list_snd : 'a. ('a * _) list -> bool = + let rec hit_list_snd : 'a. ('a * _) list -> bool = fun x -> Ext_list.exists_snd x hit and hit_list xs = List.exists hit xs and hit (l : Lambda.t) = @@ -929,7 +926,7 @@ let exception_id_destructed (l : Lambda.t) (fv : Ident.t) : bool = | Lprim {primitive = _; args; loc = _} -> hit_list args | Lvar id -> Ident.same id fv | Lassign (id, e) -> Ident.same id fv || hit e - | Lstaticcatch (e1, _, e2) -> hit e1 || hit e2 + | Lstaticcatch (e1, _, e2, _) -> hit e1 || hit e2 | Ltrywith (e1, _, e2) -> hit e1 || hit e2 | Ltryfinally (e1, e2) -> hit e1 || hit e2 | Lfunction {body} -> hit body @@ -940,12 +937,16 @@ let exception_id_destructed (l : Lambda.t) (fv : Ident.t) : bool = | Lglobal_module _ | Lconst _ -> false | Lapply {ap_func; ap_args} -> hit ap_func || hit_list ap_args | Lswitch (arg, sw) -> - hit arg || hit_list_snd sw.sw_consts || hit_list_snd sw.sw_blocks - || hit_opt sw.sw_failaction - | Lstringswitch (arg, cases, default) -> - hit arg || hit_list_snd cases || hit_opt default + hit arg + || List.exists (fun (_, e, _) -> hit e) sw.sw_consts + || List.exists (fun (_, e, _) -> hit e) sw.sw_blocks + || Option.fold ~none:false ~some:(fun (e, _) -> hit e) sw.sw_failaction + | Lstringswitch (arg, cases, default, _) -> + hit arg + || List.exists (fun (_, e, _) -> hit e) cases + || Option.fold ~none:false ~some:(fun (e, _) -> hit e) default | Lstaticraise (_, args) -> hit_list args - | Lifthenelse (e1, e2, e3) -> hit e1 || hit e2 || hit e3 + | Lifthenelse (e1, e2, e3, _) -> hit e1 || hit e2 || hit e3 | Lsequence (e1, e2) -> hit e1 || hit e2 | Lbreak | Lcontinue -> false | Lwhile (e1, e2) -> hit e1 || hit e2 @@ -1387,7 +1388,7 @@ and transl_exp0 (e : Typedtree.expression) : Lambda.t = | _ :: _ -> let id = Typecore.name_pattern "exn" pat_expr_list in let handler = - Matching.for_trywith (var id) (transl_cases pat_expr_list) + Matching.for_trywith e.exp_loc (var id) (transl_cases pat_expr_list) in let id, handler = pack_trywith_exn id handler in try_ body id handler @@ -1563,9 +1564,12 @@ and transl_exp0 (e : Typedtree.expression) : Lambda.t = sources) e.exp_loc) | Texp_ifthenelse (cond, ifso, Some ifnot) -> - if_ (transl_exp cond) (transl_exp ifso) (transl_exp ifnot) + if_ ~loc:e.exp_loc ~then_loc:(branch_loc ifso.exp_loc) + ~else_loc:(branch_loc ifnot.exp_loc) (transl_exp cond) (transl_exp ifso) + (transl_exp ifnot) | Texp_ifthenelse (cond, ifso, None) -> - if_ (transl_exp cond) (transl_exp ifso) lambda_unit + if_ ~loc:e.exp_loc ~then_loc:(branch_loc ifso.exp_loc) (transl_exp cond) + (transl_exp ifso) lambda_unit | Texp_sequence (expr1, expr2) -> seq (transl_exp expr1) (transl_exp expr2) | Texp_break -> break | Texp_continue -> continue @@ -1608,17 +1612,22 @@ and transl_exp0 (e : Typedtree.expression) : Lambda.t = else assert_failed e | Texp_assert cond -> if !((Clflags.current ()).noassert) then lambda_unit - else if_ (transl_exp cond) lambda_unit (assert_failed e) + else + if_ ~loc:e.exp_loc ~else_loc:(branch_loc e.exp_loc) (transl_exp cond) + lambda_unit (assert_failed e) and transl_list expr_list = List.map transl_exp expr_list -and transl_guard guard rhs = +and transl_guard ~pat_loc guard rhs = + let loc = branch_loc ~pat_loc rhs.exp_loc in let body = transl_exp rhs in match guard with - | None -> Matching.unguarded body - | Some cond -> Matching.guarded ~guard:(transl_exp cond) body + | None -> Matching.unguarded ~loc body + | Some cond -> + Matching.guarded ~loc ~guard:(transl_exp cond) ~guard_loc:cond.exp_loc body -and transl_case {c_lhs; c_guard; c_rhs} = (c_lhs, transl_guard c_guard c_rhs) +and transl_case {c_lhs; c_guard; c_rhs} = + (c_lhs, transl_guard ~pat_loc:c_lhs.pat_loc c_guard c_rhs) and transl_cases cases = List.map transl_case cases @@ -2008,7 +2017,7 @@ and transl_match e arg pat_expr_list exn_pat_expr_list partial = and exn_cases = transl_cases exn_pat_expr_list in let static_catch body val_ids handler = let static_exception_id = Lambda_exits.next_negative_raise_count () in - let exn_handler = Matching.for_trywith (var id) exn_cases in + let exn_handler = Matching.for_trywith e.exp_loc (var id) exn_cases in let id, exn_handler = pack_trywith_exn id exn_handler in staticcatch (try_ (staticraise static_exception_id body) id exn_handler) diff --git a/tests/ounit_tests/ounit_exits_tests.ml b/tests/ounit_tests/ounit_exits_tests.ml index 79099d94b38..da2eaa389d3 100644 --- a/tests/ounit_tests/ounit_exits_tests.ml +++ b/tests/ounit_tests/ounit_exits_tests.ml @@ -2,6 +2,12 @@ open OUnit let loc = Location.none +let make_loc line col_start col_end = + let pos c = + {Lexing.pos_fname = "Test.res"; pos_lnum = line; pos_bol = 0; pos_cnum = c} + in + {Location.loc_start = pos col_start; loc_end = pos col_end; loc_ghost = false} + let debugger = Lambda.prim ~primitive:Pdebugger ~args:[] loc let suites = @@ -28,4 +34,74 @@ let suites = let lam = Lambda.staticcatch body (1, []) debugger in assert_bool "the unused handler is removed" (Lam_pass_exits.simplify_exits lam == body) ); + ( "propagates handler branch_loc when inlining staticcatch into if" + >:: fun _ -> + let if_loc = make_loc 1 0 20 in + let then_loc = + Lambda.branch_loc ~pat_loc:(make_loc 2 2 6) (make_loc 2 10 15) + in + let handler_loc = + Lambda.branch_loc ~pat_loc:(make_loc 3 2 6) (make_loc 3 10 15) + in + let x = Ident.create "x" in + let lam = + Lambda.staticcatch ~loc:handler_loc + (Lambda.if_ ~loc:if_loc ~then_loc (Lambda.var x) + (Lambda.const (Lambda.const_int 1)) + (Lambda.staticraise 7 [])) + (7, []) + (Lambda.const (Lambda.const_int 2)) + in + match Lam_pass_exits.simplify_exits lam with + | Lifthenelse (_, _, _, locs) -> + assert_equal locs.if_loc if_loc; + assert_equal locs.then_loc then_loc; + assert_equal locs.else_loc handler_loc + | _ -> assert_failure "expected Lifthenelse" ); + ( "propagates handler branch_loc when inlining staticcatch into switch" + >:: fun _ -> + let sw_loc = make_loc 10 0 30 in + let arm0_loc = + Lambda.branch_loc ~pat_loc:(make_loc 11 2 5) (make_loc 11 9 12) + in + let handler_loc = + Lambda.branch_loc ~pat_loc:(make_loc 12 2 5) (make_loc 12 9 14) + in + let x = Ident.create "x" in + let lam = + Lambda.staticcatch ~loc:handler_loc + (Lambda.switch (Lambda.var x) + { + sw_consts_full = false; + sw_consts = + [ + ( Switch_int 0, + Lambda.const (Lambda.const_int 0), + arm0_loc ); + ( Switch_int 1, + Lambda.staticraise 9 [], + Lambda.no_branch_loc ); + ]; + sw_blocks_full = true; + sw_blocks = []; + sw_failaction = + Some (Lambda.staticraise 9 [], Lambda.no_branch_loc); + sw_dispatch = Switch_direct; + sw_loc; + }) + (9, []) + (Lambda.const (Lambda.const_int 99)) + in + match Lam_pass_exits.simplify_exits lam with + | Lswitch (_, sw) -> ( + assert_equal sw.sw_loc sw_loc; + (match sw.sw_consts with + | [(_, _, loc0); (_, _, loc1)] -> + assert_equal loc0 arm0_loc; + assert_equal loc1 handler_loc + | _ -> assert_failure "expected 2 const cases"); + match sw.sw_failaction with + | Some (_, fail_loc) -> assert_equal fail_loc handler_loc + | None -> assert_failure "expected failaction") + | _ -> assert_failure "expected Lswitch" ); ] diff --git a/tests/ounit_tests/ounit_lam_bounded_vars_tests.ml b/tests/ounit_tests/ounit_lam_bounded_vars_tests.ml index 974698f7c37..b783d3ecb0e 100644 --- a/tests/ounit_tests/ounit_lam_bounded_vars_tests.ml +++ b/tests/ounit_tests/ounit_lam_bounded_vars_tests.ml @@ -82,7 +82,8 @@ let test_exit_is_renamed_per_copy _ = in let check_copy lam = match (lam : Lambda.t) with - | Lstaticcatch (Lstaticraise (raised, [_]), (caught, [x']), Lvar x_use) -> + | Lstaticcatch (Lstaticraise (raised, [_]), (caught, [x']), Lvar x_use, _) + -> assert_fresh_exit "the exit is renamed" exit caught; assert_exit "its raise follows" caught raised; OUnit.assert_bool "the handler's variable is renamed" @@ -109,7 +110,8 @@ let test_outer_exit_is_kept _ = | Lstaticcatch ( Lsequence (Lstaticraise (in_body, []), Lstaticraise (raised, [])), (caught, []), - Lstaticraise (in_handler, []) ) -> + Lstaticraise (in_handler, []), + _ ) -> assert_fresh_exit "the caught exit is renamed" exit caught; assert_exit "its raise follows" caught raised; assert_exit "the outer exit is kept in the body" outer in_body; @@ -128,9 +130,11 @@ let test_exit_scopes_over_the_body_only _ = ( Lstaticcatch ( Lstaticraise (in_inner_body, []), (inner_caught, []), - Lstaticraise (in_inner_handler, []) ), + Lstaticraise (in_inner_handler, []), + _ ), (outer_caught, []), - Lstaticraise (in_outer_handler, []) ) -> + Lstaticraise (in_outer_handler, []), + _ ) -> assert_fresh_exit "the inner exit is renamed" exit inner_caught; assert_fresh_exit "the outer exit is renamed" exit outer_caught; assert_fresh_exit "the two catches have different exits" inner_caught @@ -150,7 +154,7 @@ let test_negative_exit_stays_negative _ = Lambda.staticcatch (Lambda.staticraise exit []) (exit, []) (int 1) in match rewrite lam with - | Lstaticcatch (Lstaticraise (raised, []), (caught, []), Lconst _) -> + | Lstaticcatch (Lstaticraise (raised, []), (caught, []), Lconst _, _) -> assert_fresh_exit "the exit is renamed" exit caught; assert_exit "its raise follows" caught raised; OUnit.assert_bool "the new id is negative" (caught < 0) diff --git a/tests/ounit_tests/ounit_lambda_constant_tests.ml b/tests/ounit_tests/ounit_lambda_constant_tests.ml index 949a5d8ee49..423c8f1a37f 100644 --- a/tests/ounit_tests/ounit_lambda_constant_tests.ml +++ b/tests/ounit_tests/ounit_lambda_constant_tests.ml @@ -32,15 +32,17 @@ let variant_switch ~constructors ~cases ~default : Lambda.lambda_switch = in let keys = List.map (fun (case, result) -> - (Lambda.Switch_constructor case, action result)) + (Lambda.Switch_constructor case, action result, Lambda.no_branch_loc)) in { sw_consts_full = List.length consts = Variant_runtime.num_constants layout; sw_consts = keys consts; sw_blocks_full = List.length blocks = Variant_runtime.num_blocks layout; sw_blocks = keys blocks; - sw_failaction = Option.map action default; + sw_failaction = + Option.map (fun d -> (action d, Lambda.no_branch_loc)) default; sw_dispatch = Switch_variant (Variant_runtime.matching_facts layout); + sw_loc = Location.none; } let assert_fold sw value expected = @@ -198,7 +200,7 @@ let switch_tests = sw with sw_blocks = []; sw_blocks_full = false; - sw_failaction = Some (action "default"); + sw_failaction = Some (action "default", Lambda.no_branch_loc); } in assert_fold sw diff --git a/tests/ounit_tests/ounit_lambda_traverse_tests.ml b/tests/ounit_tests/ounit_lambda_traverse_tests.ml index 67d3f39a185..ca28522111e 100644 --- a/tests/ounit_tests/ounit_lambda_traverse_tests.ml +++ b/tests/ounit_tests/ounit_lambda_traverse_tests.ml @@ -21,13 +21,17 @@ let nodes : (string * Lambda.t) list = Lambda.switch var { sw_consts_full = false; - sw_consts = [(Switch_int 0, debugger)]; + sw_consts = [(Switch_int 0, debugger, Lambda.no_branch_loc)]; sw_blocks_full = false; sw_blocks = []; - sw_failaction = Some debugger; + sw_failaction = Some (debugger, Lambda.no_branch_loc); sw_dispatch = Switch_direct; + sw_loc = loc; } ); - ("stringswitch", Lambda.stringswitch var [("a", debugger)] (Some debugger)); + ( "stringswitch", + Lambda.stringswitch var + [("a", debugger, Lambda.no_branch_loc)] + (Some (debugger, Lambda.no_branch_loc)) ); ("staticraise", Lambda.staticraise 1 [var]); ( "staticcatch", Lambda.staticcatch (Lambda.staticraise 1 []) (1, []) debugger ); @@ -69,4 +73,75 @@ let suites = node != node)) nodes ); + ( "branch locations do not affect make_key or eq_approx" >:: fun _ -> + let mk_loc line = + let pos c = + { + Lexing.pos_fname = "Loc.res"; + pos_lnum = line; + pos_bol = 0; + pos_cnum = c; + } + in + {Location.loc_start = pos 0; loc_end = pos 10; loc_ghost = false} + in + let bl1 = Lambda.branch_loc ~pat_loc:(mk_loc 1) (mk_loc 2) in + let bl2 = Lambda.branch_loc ~pat_loc:(mk_loc 10) (mk_loc 20) in + let pairs = + [ + ( "ifthenelse", + true, + Lambda.if_ ~loc:(mk_loc 1) ~then_loc:bl1 ~else_loc:bl2 var + debugger var, + Lambda.if_ var debugger var ); + ( "switch", + false, + Lambda.switch var + { + sw_consts_full = false; + sw_consts = [(Switch_int 0, debugger, bl1)]; + sw_blocks_full = false; + sw_blocks = []; + sw_failaction = Some (var, bl2); + sw_dispatch = Switch_direct; + sw_loc = mk_loc 3; + }, + Lambda.switch var + { + sw_consts_full = false; + sw_consts = + [(Switch_int 0, debugger, Lambda.no_branch_loc)]; + sw_blocks_full = false; + sw_blocks = []; + sw_failaction = Some (var, Lambda.no_branch_loc); + sw_dispatch = Switch_direct; + sw_loc = Location.none; + } ); + ( "stringswitch", + true, + Lambda.stringswitch ~loc:(mk_loc 4) var + [("a", debugger, bl1)] + (Some (var, bl2)), + Lambda.stringswitch var + [("a", debugger, Lambda.no_branch_loc)] + (Some (var, Lambda.no_branch_loc)) ); + ( "staticcatch", + false, + Lambda.staticcatch ~loc:bl1 (Lambda.staticraise 1 []) (1, []) + debugger, + Lambda.staticcatch (Lambda.staticraise 1 []) (1, []) debugger + ); + ] + in + List.iter + (fun (name, check_eq_approx, a, b) -> + assert_equal + ~msg:(name ^ " make_key should ignore locations") + (Lambda_traverse.make_key a) + (Lambda_traverse.make_key b); + if check_eq_approx then + assert_bool + (name ^ " eq_approx should ignore locations") + (Lambda.eq_approx a b)) + pairs ); ] diff --git a/tests/project_tests/source_map/input.js b/tests/project_tests/source_map/input.js index f1906ca45cc..3e367b4f802 100644 --- a/tests/project_tests/source_map/input.js +++ b/tests/project_tests/source_map/input.js @@ -2,6 +2,7 @@ import * as assert from "node:assert"; import { Buffer } from "node:buffer"; +import { execFileSync } from "node:child_process"; import * as fs from "node:fs/promises"; import * as path from "node:path"; import { setup } from "#dev/process"; @@ -145,7 +146,7 @@ function mapFromInlineComment(js, filename) { return JSON.parse(Buffer.from(match[1], "base64").toString("utf8")); } -const moduleNames = ["Demo", "Helper"]; +const moduleNames = ["Demo", "Helper", "Branches"]; const outputFilenames = moduleNames.flatMap(moduleName => [ `${moduleName}.cjs`, `${moduleName}.mjs`, @@ -155,6 +156,12 @@ const demoSourcePath = path.join(import.meta.dirname, "src", "Demo.res"); const demoSource = await fs.readFile(demoSourcePath, "utf8"); const helperSourcePath = path.join(import.meta.dirname, "src", "Helper.res"); const helperSource = await fs.readFile(helperSourcePath, "utf8"); +const branchesSourcePath = path.join( + import.meta.dirname, + "src", + "Branches.res", +); +const branchesSource = await fs.readFile(branchesSourcePath, "utf8"); const configPath = path.join(import.meta.dirname, "rescript.json"); const originalConfig = await fs.readFile(configPath, "utf8"); const originalDebuggerPositions = findTokenPositions(demoSource, "debugger()"); @@ -255,6 +262,16 @@ function sourceMapFixture(filename) { debuggerPositions: [], fieldAssignmentPositions: [], }; + case "Branches": + return { + sourceName: "Branches.res", + sourceContentMarker: "let area = s =>", + raiseErrorPositions: [], + pipeCallPositions: [], + patternBranchPositions: [], + debuggerPositions: [], + fieldAssignmentPositions: [], + }; default: throw new Error(`Unknown source map fixture for ${filename}`); } @@ -399,9 +416,353 @@ function assertSourceMap(filename, js, map, options = {}) { ), `${filename}.map debugger mappings should point to ${fixture.sourceName}`, ); + + if (moduleNameFromFilename(filename) === "Branches") { + assertBranchesSourceMap(filename, js, map, decodedMappings); + } +} + +/** + * Look up the original position for a generated (0-based) line/column using + * greatest-lower-bound or least-upper-bound bias, matching source-map consumers. + * @param {Mapping[]} decodedMappings + * @param {number} generatedLine + * @param {number} generatedColumn + * @param {"glb" | "lub"} bias + * @returns {Mapping | undefined} + */ +function lookupOriginal(decodedMappings, generatedLine, generatedColumn, bias) { + const onLine = decodedMappings + .filter(m => m.generatedLine === generatedLine) + .sort((a, b) => a.generatedColumn - b.generatedColumn); + if (onLine.length === 0) { + return undefined; + } + if (bias === "glb") { + /** @type {Mapping | undefined} */ + let best; + for (const m of onLine) { + if (m.generatedColumn <= generatedColumn) { + best = m; + } else { + break; + } + } + return best; + } + return onLine.find(m => m.generatedColumn >= generatedColumn); +} + +/** + * @param {Mapping[]} decodedMappings + * @param {number} generatedLine + * @param {number} generatedColumn + * @returns {Mapping | undefined} + */ +function lookupOriginalTryBoth( + decodedMappings, + generatedLine, + generatedColumn, +) { + let result = lookupOriginal( + decodedMappings, + generatedLine, + generatedColumn, + "glb", + ); + if (!result) { + result = lookupOriginal( + decodedMappings, + generatedLine, + generatedColumn, + "lub", + ); + } + const atZero = lookupOriginal(decodedMappings, generatedLine, 0, "glb"); + if (atZero && result && atZero.originalLine > result.originalLine) { + result = atZero; + } + return result; } -async function assertLinkedOutput() { +/** + * @param {string} filename + * @param {string} js + * @param {SourceMap} map + * @param {Mapping[]} decodedMappings + */ +function assertBranchesSourceMap(filename, js, map, decodedMappings) { + // 1. Round-trip markers: every constant/string arm marker resolves to its + // exact original line & column and reverse lookup includes the generated pos. + const armMarkers = [ + '"arm_label_empty"', + '"arm_label_unknown"', + '"arm_label_circle"', + '"arm_label_polygon"', + '"arm_inter_empty"', + '"arm_inter_circle"', + '"arm_inter_rect"', + '"arm_inter_square"', + '"arm_inter_unknown"', + '"arm_classify_zero"', + '"arm_classify_neg"', + '"arm_classify_big"', + '"arm_classify_small"', + '"arm_lst_nil"', + '"arm_lst_one"', + '"arm_lst_pair"', + '"arm_lst_many"', + '"arm_str_a"', + '"arm_str_b"', + '"arm_str_default"', + '"arm_tup_tt"', + '"arm_tup_tf"', + '"arm_tup_f"', + '"arm_if_a"', + '"arm_if_b"', + '"arm_if_c"', + '"arm_ternary_t"', + '"arm_ternary_f"', + '"arm_or_none"', + '"arm_or_circle"', + '"arm_or_box"', + ]; + + // Folded multi-line let arms map to the arm body start (`let msg = ...`). + for (const marker of ['"arm_ml_empty"', '"arm_ml_unknown"']) { + const origLine = findSingleTokenPosition(branchesSource, marker).line; + const genPos = findSingleTokenPosition(js, marker); + const mapping = lookupOriginal( + decodedMappings, + genPos.line, + genPos.column, + "glb", + ); + assert.ok(mapping, `${filename}.map should map ${marker}`); + assert.equal( + mapping.originalLine, + origLine, + `${filename}.map ${marker} should map to arm body line ${origLine}`, + ); + } + + for (const marker of armMarkers) { + const origPos = findSingleTokenPosition(branchesSource, marker); + const genPositions = findTokenPositions(js, marker); + assert.ok( + genPositions.length >= 1, + `${filename} should contain marker ${marker}`, + ); + for (const genPos of genPositions) { + const mapping = lookupOriginal( + decodedMappings, + genPos.line, + genPos.column, + "glb", + ); + assert.ok( + mapping, + `${filename}.map should map ${marker} at ${genPos.line}:${genPos.column}`, + ); + assert.ok( + map.sources[mapping.sourceIndex].endsWith("Branches.res"), + `${filename}.map ${marker} should point to Branches.res`, + ); + assert.equal( + mapping.originalLine, + origPos.line, + `${filename}.map ${marker} should map to original line ${origPos.line}, got ${mapping.originalLine}`, + ); + assert.equal( + mapping.originalColumn, + origPos.column, + `${filename}.map ${marker} should map to original column ${origPos.column}, got ${mapping.originalColumn}`, + ); + + // Reverse lookup: original position must include this generated position. + const reverseMatches = decodedMappings.filter( + m => + m.originalLine === origPos.line && + m.originalColumn === origPos.column && + map.sources[m.sourceIndex].endsWith("Branches.res"), + ); + assert.ok( + reverseMatches.some( + m => + m.generatedLine === genPos.line && + m.generatedColumn === genPos.column, + ), + `${filename}.map reverse lookup for ${marker} (${origPos.line}:${origPos.column}) should include ${genPos.line}:${genPos.column}`, + ); + } + } + + // 2. Containment: dispatch tests & shared destructuring must point to the + // enclosing switch/if or guard, never into a sibling arm. + const optSwitchLine = findSingleTokenPosition( + branchesSource, + "switch o {", + ).line; + const optNoneLine = findSingleTokenPosition( + branchesSource, + "| None => -1", + ).line; + const optSomeNoneLine = findSingleTokenPosition( + branchesSource, + "| Some(None) => 0", + ).line; + + const optUndefinedPos = findSingleTokenPosition(js, "if (o === undefined)"); + const optUndefinedMapping = lookupOriginal( + decodedMappings, + optUndefinedPos.line, + optUndefinedPos.column, + "glb", + ); + assert.ok(optUndefinedMapping); + assert.equal( + optUndefinedMapping.originalLine, + optSwitchLine, + `${filename}: opt dispatch "o === undefined" should map to switch o (line ${optSwitchLine}), not a sibling arm`, + ); + + const valFromOptionPos = findTokenPositions( + js, + "Primitive_option.valFromOption(o)", + ); + assert.ok(valFromOptionPos.length >= 1); + for (const pos of valFromOptionPos) { + const m = lookupOriginal(decodedMappings, pos.line, pos.column, "glb"); + assert.ok(m); + assert.equal( + m.originalLine, + optSwitchLine, + `${filename}: shared Primitive_option.valFromOption(o) should map to switch o (line ${optSwitchLine})`, + ); + } + + const optReturnNeg1 = findSingleTokenPosition(js, "return -1;"); + const optReturnNeg1Map = lookupOriginal( + decodedMappings, + optReturnNeg1.line, + optReturnNeg1.column, + "glb", + ); + assert.ok(optReturnNeg1Map); + assert.equal( + optReturnNeg1Map.originalLine, + optNoneLine, + `${filename}: "return -1;" should map to "| None => -1"`, + ); + + const optReturn0 = findSingleTokenPosition(js, "return 0;"); + const optReturn0Map = lookupOriginal( + decodedMappings, + optReturn0.line, + optReturn0.column, + "glb", + ); + assert.ok(optReturn0Map); + assert.equal( + optReturn0Map.originalLine, + optSomeNoneLine, + `${filename}: "return 0;" should map to "| Some(None) => 0"`, + ); + + // Variable-returning arm: `| None => fallback` + const fallbackArmLine = findSingleTokenPosition( + branchesSource, + "| None => fallback", + ).line; + const returnFallbackPos = findSingleTokenPosition(js, "return fallback;"); + const returnFallbackMap = lookupOriginal( + decodedMappings, + returnFallbackPos.line, + returnFallbackPos.column, + "glb", + ); + assert.ok(returnFallbackMap); + assert.equal( + returnFallbackMap.originalLine, + fallbackArmLine, + `${filename}: "return fallback;" should map to "| None => fallback"`, + ); + + // Guard expressions map to their own guard line, not sibling arms. + const guardNegLine = findSingleTokenPosition( + branchesSource, + "| n if n < 0 =>", + ).line; + const guardNegPos = findSingleTokenPosition(js, "if (n < 0)"); + const guardNegMap = lookupOriginal( + decodedMappings, + guardNegPos.line, + guardNegPos.column, + "glb", + ); + assert.ok(guardNegMap); + assert.equal( + guardNegMap.originalLine, + guardNegLine, + `${filename}: "if (n < 0)" should map to guard line ${guardNegLine}`, + ); + + const guardBigLine = findSingleTokenPosition( + branchesSource, + "| n if n > 100 =>", + ).line; + const guardBigPos = findSingleTokenPosition(js, "if (n > 100)"); + const guardBigMap = lookupOriginal( + decodedMappings, + guardBigPos.line, + guardBigPos.column, + "glb", + ); + assert.ok(guardBigMap); + assert.equal( + guardBigMap.originalLine, + guardBigLine, + `${filename}: "if (n > 100)" should map to guard line ${guardBigLine}`, + ); + + // 3. Completeness: every line inside branch functions (including dispatch, + // arms, returns, cases, default, break, and closing braces) is mapped. + const jsLines = js.split(/\r?\n/); + const mappedLines = new Set(decodedMappings.map(m => m.generatedLine)); + let currentFn = ""; + for (let lineIdx = 0; lineIdx < jsLines.length; lineIdx++) { + const line = jsLines[lineIdx]; + const fnMatch = line.match(/^function (\w+)\(/); + if (fnMatch) { + currentFn = fnMatch[1]; + } + if (currentFn !== "" && line.trim() !== "") { + // Outside branches, unboxed `let acc = 0.0;` / `return acc;` in + // `imperativeSwitch` are bare Llet/Lvar leaves; every line of its switch + // (and every line of every other function) must be mapped. + const isBareRefLeaf = + currentFn === "imperativeSwitch" && + (line.trim() === "let acc = 0.0;" || line.trim() === "return acc;"); + if (!isBareRefLeaf) { + assert.ok( + mappedLines.has(lineIdx), + `${filename}:${lineIdx + 1} (${currentFn}) should have at least one source map mapping: ${line}`, + ); + } + } + if (currentFn !== "" && line === "}") { + currentFn = ""; + } + } +} + +/** @param {string} js */ +function stripSourceMappingUrl(js) { + return js.replace(/\/\/# sourceMappingURL=[^\n]*\n?$/, ""); +} + +/** @param {Map} defaultOutput */ +async function assertLinkedOutput(defaultOutput) { await fs.writeFile(configPath, configWithMode("linked")); await execBuildOrThrow(); @@ -421,6 +782,11 @@ async function assertLinkedOutput() { js, new RegExp(`//# sourceMappingURL=${filename.replace(".", "\\.")}\\.map`), ); + assert.equal( + stripSourceMappingUrl(js), + defaultOutput.get(filename), + `${filename} JS output should be byte-identical to source maps disabled`, + ); assertSourceMap( filename, @@ -430,6 +796,262 @@ async function assertLinkedOutput() { } await assertNodeStackTraceUsesSourceMap(); + await assertNodeV8CoverageUsesSourceMap(); +} + +async function assertNodeV8CoverageUsesSourceMap() { + const covDir = path.join(import.meta.dirname, ".v8-coverage-tmp"); + const driverPath = path.join(import.meta.dirname, ".v8-coverage-driver.mjs"); + const branchesJsPath = path.join(import.meta.dirname, "src", "Branches.mjs"); + const branchesMapPath = `${branchesJsPath}.map`; + + await fs.rm(covDir, { recursive: true, force: true }); + await fs.mkdir(covDir, { recursive: true }); + await fs.writeFile( + driverPath, + ` + import * as Branches from "./src/Branches.mjs"; + Branches.area({ TAG: "Circle", _0: 2.0 }); + Branches.label({ TAG: "Circle", _0: 2.0 }); + Branches.interleaved({ TAG: "Circle", _0: 2.0 }); + Branches.opt(5); + Branches.str("a"); + Branches.ifChain(true, false); + Branches.imperativeSwitch({ TAG: "Circle", _0: 2.0 }); + Branches.multilineSwitch({ TAG: "Circle", _0: 2.0 }); + `, + ); + + try { + execFileSync(process.execPath, [driverPath], { + cwd: import.meta.dirname, + env: { ...process.env, NODE_V8_COVERAGE: covDir }, + stdio: "pipe", + }); + + const covFiles = await fs.readdir(covDir); + assert.ok( + covFiles.length > 0, + "NODE_V8_COVERAGE should emit coverage JSON", + ); + const covJson = JSON.parse( + await fs.readFile(path.join(covDir, covFiles[0]), "utf8"), + ); + /** @type {{ url: string, functions: { functionName: string, ranges: { startOffset: number, endOffset: number, count: number }[] }[] } | undefined} */ + const scriptCov = covJson.result.find( + /** @param {{ url: string }} entry */ + entry => entry.url.endsWith("/Branches.mjs"), + ); + assert.ok(scriptCov, "V8 coverage should include Branches.mjs"); + + const jsText = await fs.readFile(branchesJsPath, "utf8"); + /** @type {SourceMap} */ + const map = JSON.parse(await fs.readFile(branchesMapPath, "utf8")); + const decoded = decodeMappings(map.mappings); + + /** @type {{ line: number, startCol: number, endCol: number }[]} */ + const jsLineInfos = []; + let offset = 0; + for (const [idx, lineStr] of jsText.split(/(?<=\r?\n)/u).entries()) { + const nlMatch = lineStr.match(/\r?\n$/u); + const nlLen = nlMatch ? nlMatch[0].length : 0; + jsLineInfos.push({ + line: idx, + startCol: offset, + endCol: offset + lineStr.length - nlLen, + }); + offset += lineStr.length; + } + + /** @param {number} off */ + function offsetToGenLineCol(off) { + for (const info of jsLineInfos) { + if (off >= info.startCol && off <= info.endCol) { + return { line: info.line, column: off - info.startCol }; + } + } + const last = jsLineInfos[jsLineInfos.length - 1]; + return { line: last.line, column: last.endCol - last.startCol }; + } + + /** @type {{ line: number, startCol: number, endCol: number, count: number }[]} */ + const resLineInfos = []; + let resOffset = 0; + for (const [idx, lineStr] of branchesSource + .split(/(?<=\r?\n)/u) + .entries()) { + const nlMatch = lineStr.match(/\r?\n$/u); + const nlLen = nlMatch ? nlMatch[0].length : 0; + resLineInfos.push({ + line: idx, + startCol: resOffset, + endCol: resOffset + lineStr.length - nlLen, + count: 1, + }); + resOffset += lineStr.length; + } + + /** @type {Map} */ + const remappedByFn = new Map(); + const exercisedFns = new Set([ + "area", + "label", + "interleaved", + "opt", + "str", + "ifChain", + "imperativeSwitch", + "multilineSwitch", + ]); + + for (const fn of scriptCov.functions) { + if (!exercisedFns.has(fn.functionName)) { + continue; + } + const fnRanges = []; + for (const range of fn.ranges) { + const startGen = offsetToGenLineCol(range.startOffset); + const endGen = offsetToGenLineCol( + Math.max(range.startOffset, range.endOffset - 1), + ); + const origStart = lookupOriginalTryBoth( + decoded, + startGen.line, + startGen.column, + ); + const origEnd = lookupOriginalTryBoth( + decoded, + endGen.line, + endGen.column, + ); + assert.ok( + origStart && origEnd, + `V8 range in ${fn.functionName} (${startGen.line}:${startGen.column}..${endGen.line}:${endGen.column}) should not be dropped`, + ); + assert.ok( + origStart.originalLine <= origEnd.originalLine, + `V8 range in ${fn.functionName} should not invert original lines (${origStart.originalLine} > ${origEnd.originalLine})`, + ); + fnRanges.push({ + startLine: origStart.originalLine, + endLine: origEnd.originalLine, + count: range.count, + }); + + // Apply v8-to-istanbul line-span rule to check multi-line arms & interleaved arms. + const startInfo = resLineInfos[origStart.originalLine]; + const endInfo = resLineInfos[origEnd.originalLine]; + const origStartOff = Math.min( + startInfo.startCol + origStart.originalColumn, + startInfo.endCol, + ); + const origEndOff = endInfo.endCol; + for (const resLine of resLineInfos) { + if ( + origStartOff <= resLine.startCol && + origEndOff >= resLine.endCol + ) { + resLine.count = range.count; + } + } + } + remappedByFn.set(fn.functionName, fnRanges); + } + + // Verify unexecuted branches were detected and mapped to their arms. + const optUncovered = (remappedByFn.get("opt") ?? []).filter( + r => r.count === 0, + ); + const optSomeNoneLine = findSingleTokenPosition( + branchesSource, + "| Some(None) => 0", + ).line; + const optNoneLine = findSingleTokenPosition( + branchesSource, + "| None => -1", + ).line; + assert.ok( + optUncovered.some(r => r.startLine === optSomeNoneLine), + "V8 coverage should detect uncovered Some(None) branch in opt", + ); + assert.ok( + optUncovered.some(r => r.startLine === optNoneLine), + "V8 coverage should detect uncovered None branch in opt", + ); + + const strUncovered = (remappedByFn.get("str") ?? []).filter( + r => r.count === 0, + ); + const strBLine = findSingleTokenPosition( + branchesSource, + '"arm_str_b"', + ).line; + const strDefaultLine = findSingleTokenPosition( + branchesSource, + '"arm_str_default"', + ).line; + assert.ok( + strUncovered.some(r => r.startLine === strBLine), + 'V8 coverage should detect uncovered "b" branch in str', + ); + assert.ok( + strUncovered.some(r => r.startLine === strDefaultLine), + "V8 coverage should detect uncovered default branch in str", + ); + + const ifUncovered = (remappedByFn.get("ifChain") ?? []).filter( + r => r.count === 0, + ); + assert.ok( + ifUncovered.length >= 1, + "V8 coverage should detect uncovered else branch in ifChain", + ); + + // Interleaved switch: executed Circle arm must NOT be marked uncovered by + // an unexecuted Empty/Unknown constant-tag dispatch block. + const interCircleLine = findSingleTokenPosition( + branchesSource, + '"arm_inter_circle"', + ).line; + assert.equal( + resLineInfos[interCircleLine].count, + 1, + "Executed Circle arm in interleaved switch must stay covered", + ); + + // Multi-line switch: executed Circle body stays covered; unexecuted Rect & + // Square body lines are marked uncovered (count = 0). + const mlCircleLine = findSingleTokenPosition( + branchesSource, + '"arm_ml_circle:" ++ v', + ).line; + const mlRectLine = findSingleTokenPosition( + branchesSource, + "let a = w *. h", + ).line; + const mlSquareLine = findSingleTokenPosition( + branchesSource, + "let a = x *. x", + ).line; + assert.equal( + resLineInfos[mlCircleLine].count, + 1, + "Executed multiline Circle body line must stay covered", + ); + assert.equal( + resLineInfos[mlRectLine].count, + 0, + "Unexecuted multiline Rect body line must be uncovered", + ); + assert.equal( + resLineInfos[mlSquareLine].count, + 0, + "Unexecuted multiline Square body line must be uncovered", + ); + } finally { + await fs.rm(driverPath, { force: true }); + await fs.rm(covDir, { recursive: true, force: true }); + } } async function assertNodeStackTraceUsesSourceMap() { @@ -461,7 +1083,8 @@ async function assertNodeStackTraceUsesSourceMap() { } } -async function assertHiddenOutput() { +/** @param {Map} defaultOutput */ +async function assertHiddenOutput(defaultOutput) { const sourceRoot = "rescript://source-map-test/"; await removeGeneratedMapFiles(); await fs.writeFile( @@ -480,6 +1103,11 @@ async function assertHiddenOutput() { /\/\/# sourceMappingURL=/, `${filename} should not include a sourceMappingURL comment in hidden mode`, ); + assert.equal( + js, + defaultOutput.get(filename), + `${filename} JS output in hidden mode should be byte-identical to source maps disabled`, + ); assert.ok(await fileExists(mapPath), `${filename}.map should exist`); assertSourceMap( filename, @@ -544,7 +1172,8 @@ async function assertDisabledOutput(defaultOutput) { } } -async function assertInlineOutput() { +/** @param {Map} defaultOutput */ +async function assertInlineOutput(defaultOutput) { await fs.writeFile( configPath, configWithSourceMap({ mode: "inline", sourcesContent: false }), @@ -561,6 +1190,11 @@ async function assertInlineOutput() { /\/\/# sourceMappingURL=data:application\/json;base64,/, `${filename} should include an inline source map`, ); + assert.equal( + stripSourceMappingUrl(js), + defaultOutput.get(filename), + `${filename} JS output in inline mode should be byte-identical to source maps disabled`, + ); assert.equal( await fileExists(mapPath), false, @@ -575,10 +1209,10 @@ async function assertInlineOutput() { await execClean(); try { const defaultOutput = await assertDefaultOutput(); - await assertLinkedOutput(); + await assertLinkedOutput(defaultOutput); await assertDisabledOutput(defaultOutput); - await assertHiddenOutput(); - await assertInlineOutput(); + await assertHiddenOutput(defaultOutput); + await assertInlineOutput(defaultOutput); } finally { await fs.writeFile(configPath, originalConfig); await execClean(); diff --git a/tests/project_tests/source_map/src/Branches.res b/tests/project_tests/source_map/src/Branches.res new file mode 100644 index 00000000000..6773d74d21e --- /dev/null +++ b/tests/project_tests/source_map/src/Branches.res @@ -0,0 +1,131 @@ +type shape = + | Circle(float) + | Rect(float, float) + | Square(float) + | Empty + | Unknown + +let area = s => + switch s { + | Circle(r) => 3.14 * r * r + | Rect(w, h) => w * h + | Square(x) => x * x + | Empty => 0.0 + | Unknown => -1.0 + } + +let label = s => + switch s { + | Empty => "arm_label_empty" + | Unknown => "arm_label_unknown" + | Circle(_) => "arm_label_circle" + | _ => "arm_label_polygon" + } + +let interleaved = s => + switch s { + | Empty => "arm_inter_empty" + | Circle(_) => "arm_inter_circle" + | Rect(_, _) => "arm_inter_rect" + | Square(_) => "arm_inter_square" + | Unknown => "arm_inter_unknown" + } + +let classify = n => + switch n { + | 0 => "arm_classify_zero" + | n if n < 0 => "arm_classify_neg" + | n if n > 100 => "arm_classify_big" + | _ => "arm_classify_small" + } + +let opt = o => + switch o { + | Some(Some(x)) => x + 1 + | Some(None) => 0 + | None => -1 + } + +let lst = l => + switch l { + | list{} => "arm_lst_nil" + | list{_} => "arm_lst_one" + | list{a, b, ..._} if a == b => "arm_lst_pair" + | _ => "arm_lst_many" + } + +let str = s => + switch s { + | "a" => "arm_str_a" + | "b" => "arm_str_b" + | _ => "arm_str_default" + } + +let tup = (a, b) => + switch (a, b) { + | (true, true) => "arm_tup_tt" + | (true, false) => "arm_tup_tf" + | (false, _) => "arm_tup_f" + } + +let ifChain = (a, b) => + if a { + "arm_if_a" + } else if b { + "arm_if_b" + } else { + "arm_if_c" + } + +let ifTernary = flag => { + let chosen = if flag { + "arm_ternary_t" + } else { + "arm_ternary_f" + } + chosen +} + +let varReturn = (v, fallback) => + switch v { + | Some(x) => x + | None => fallback + } + +let orPattern = s => + switch s { + | Empty | Unknown => "arm_or_none" + | Circle(_) => "arm_or_circle" + | Rect(_, _) | Square(_) => "arm_or_box" + } + +let imperativeSwitch = s => { + let acc = ref(0.0) + switch s { + | Circle(r) => acc := acc.contents +. r + | Rect(w, h) => acc := acc.contents +. w *. h + | Square(x) => acc := acc.contents +. x *. x + | Empty => acc := 0.0 + | Unknown => acc := -1.0 + } + acc.contents +} + +let multilineSwitch = s => + switch s { + | Empty => + let msg = "arm_ml_empty" + msg + | Circle(r) => + let v = Float.toString(r) + "arm_ml_circle:" ++ v + | Rect(w, h) => + let a = w *. h + Float.toString(a) + | Square(x) => + let a = x *. x + Float.toString(a) + | Unknown => + let msg = "arm_ml_unknown" + msg + } From 2abd577e8f63001a93f0e72495e0be213d97ceb9 Mon Sep 17 00:00:00 2001 From: mununki Date: Sun, 29 Nov 2026 14:24:08 +0900 Subject: [PATCH 2/4] Avoid branch-location overhead in .cmj exports and non-sourcemap builds Why: 1. Lambda.no_if_locs was exported in lambda.mli without external callers, triggering reanalyze's dead-code check; keep it internal and share both no_if_locs and no_branch_loc when locations are absent. 2. Marshaling branch, switch, and handler locations inside persistent_closed_lambda inflated runtime .cmj files (+1.42%); strip branch locations before exporting Lambda terms to .cmj. 3. Printing chained else-if trees scanned remaining else branches quadratically when nested If statements carried no source_loc, and divide_variant / Lam_compile repeated location work when source maps were disabled (+1.34% instructions on PolyVariantSwitch.res); guard source-map boundary lookups behind active source-map state and share unchanged pattern-match cells. Signed-off-by: mununki --- compiler/backend/js_dump.ml | 81 +++++++++++-------- compiler/backend/js_pass_flatten.ml | 14 +++- compiler/backend/js_source_map.ml | 14 +++- compiler/backend/js_source_map.mli | 4 + compiler/backend/lam_compile.ml | 76 ++++++++++------- compiler/backend/lam_pass_exits.ml | 4 +- compiler/backend/lam_stats_export.ml | 3 + compiler/typing/lambda.ml | 27 +++++-- compiler/typing/lambda.mli | 1 - compiler/typing/lambda_traverse.ml | 57 +++++++++++++ compiler/typing/lambda_traverse.mli | 4 + compiler/typing/matching.ml | 48 ++++++----- .../ounit_lambda_traverse_tests.ml | 7 ++ 13 files changed, 244 insertions(+), 96 deletions(-) diff --git a/compiler/backend/js_dump.ml b/compiler/backend/js_dump.ml index fe5eb1c0a4c..cd246f8640a 100644 --- a/compiler/backend/js_dump.ml +++ b/compiler/backend/js_dump.ml @@ -487,27 +487,28 @@ let rec stmt_last_arm_loc (s : J.statement) : Location.t option = and last_case_loc : 'a. ('a * J.case_clause) list -> Location.t option -> Location.t option = fun cc fallback -> - let rec loop = function - | [] -> fallback + let rec find_last = function + | [] -> None | (_, ({source_loc; switch_body} : J.case_clause)) :: rest -> ( - match block_last_arm_loc switch_body with + match find_last rest with | Some _ as loc -> loc | None -> ( - match source_loc with + match block_last_arm_loc switch_body with | Some _ as loc -> loc - | None -> loop rest)) + | None -> source_loc)) in - loop (List.rev cc) + match find_last cc with + | Some _ as loc -> loc + | None -> fallback and block_last_arm_loc (b : J.block) : Location.t option = - let rec loop = function - | [] -> None - | s :: rest -> ( - match stmt_last_arm_loc s with - | Some _ as loc -> loc - | None -> loop rest) - in - loop (List.rev b) + match b with + | [] -> None + | [s] -> stmt_last_arm_loc s + | s :: rest -> ( + match block_last_arm_loc rest with + | Some _ as loc -> loc + | None -> stmt_last_arm_loc s) let ensure_ordered_locs start_loc end_loc = match (start_loc, end_loc) with @@ -713,12 +714,13 @@ and pp_one_case_clause : in if should_break then ( P.newline f; - let break_loc = - match block_last_arm_loc switch_body with - | Some _ as loc -> loc - | None -> source_loc - in - Js_source_map.mark_source_loc_end f break_loc; + (if Js_source_map.is_active () then + let break_loc = + match block_last_arm_loc switch_body with + | Some _ as loc -> loc + | None -> source_loc + in + Js_source_map.mark_source_loc_end f break_loc); P.string f L.break; semi f); cxt)) @@ -1502,12 +1504,14 @@ and statement_desc ?source_loc top cxt f (s : J.statement_desc) : cxt = | Variable l -> variable_declaration top cxt f l | If (e, s1, s2) -> ( (* TODO: always brace those statements *) + let source_map_active = Js_source_map.is_active () in P.string f L.if_; P.space f; let cxt = P.paren_group f 1 (fun _ -> expression ~level:0 cxt f e) in P.space f; let cxt = - if is_same_dispatch_block source_loc s1 then + if not source_map_active then brace_block cxt f s1 + else if is_same_dispatch_block source_loc s1 then brace_block_mapped cxt f ?start_loc:source_loc ?end_loc:source_loc ~end_at_start:true s1 else @@ -1518,20 +1522,31 @@ and statement_desc ?source_loc top cxt f (s : J.statement_desc) : cxt = in match s2 with | [] | [{statement_desc = Block [] | Exp {expression_desc = Var _}}] -> cxt - | [({statement_desc = If _} as nest)] - | [{statement_desc = Block [({statement_desc = If _; _} as nest)]; _}] -> - let else_loc = - match nest.source_loc with - | Some _ as loc -> loc - | None -> block_first_arm_loc [nest] - in - Js_source_map.mark_source_loc f else_loc; + | [({statement_desc = If (_, n1, _)} as nest)] + | [ + { + statement_desc = Block [({statement_desc = If (_, n1, _); _} as nest)]; + _; + }; + ] -> + (if source_map_active then + let else_loc = + match nest.source_loc with + | Some _ as loc -> loc + | None -> block_first_arm_loc n1 + in + Js_source_map.mark_source_loc f else_loc); P.space f; P.string f L.else_; P.space f; statement false cxt f nest | _ :: _ as s2 -> - if is_same_dispatch_block source_loc s2 then ( + if not source_map_active then ( + P.space f; + P.string f L.else_; + P.space f; + brace_block cxt f s2) + else if is_same_dispatch_block source_loc s2 then ( Js_source_map.mark_source_loc f source_loc; P.space f; P.string f L.else_; @@ -1774,7 +1789,8 @@ and statement_desc ?source_loc top cxt f (s : J.statement_desc) : cxt = | Some def -> P.newline f; P.group f 1 (fun _ -> - Js_source_map.mark_source_loc f (block_first_arm_loc def); + if Js_source_map.is_active () then + Js_source_map.mark_source_loc f (block_first_arm_loc def); P.string f L.default; P.string f L.colon; P.newline f; @@ -1795,7 +1811,8 @@ and statement_desc ?source_loc top cxt f (s : J.statement_desc) : cxt = | Some def -> P.newline f; P.group f 1 (fun _ -> - Js_source_map.mark_source_loc f (block_first_arm_loc def); + if Js_source_map.is_active () then + Js_source_map.mark_source_loc f (block_first_arm_loc def); P.string f L.default; P.string f L.colon; P.newline f; diff --git a/compiler/backend/js_pass_flatten.ml b/compiler/backend/js_pass_flatten.ml index 5f863718dac..dac7e788fbd 100644 --- a/compiler/backend/js_pass_flatten.ml +++ b/compiler/backend/js_pass_flatten.ml @@ -53,7 +53,12 @@ let flatten_map = if Js_analyzer.no_side_effect_expression e then [] else let stmt = S.exp e in - [self.statement self {stmt with source_loc = e.source_loc}] + let stmt = + match e.source_loc with + | None -> stmt + | Some _ -> {stmt with source_loc = e.source_loc} + in + [self.statement self stmt] in let statement_desc : J.statement_desc = match (branch b, branch c) with @@ -88,7 +93,12 @@ let flatten_map = | Return {expression_desc = Cond (a, b, c); comment; source_loc} -> let return_with_loc (e : J.expression) = let stmt = S.return_stmt e in - self.statement self {stmt with source_loc = e.source_loc} + let stmt = + match e.source_loc with + | None -> stmt + | Some _ -> {stmt with source_loc = e.source_loc} + in + self.statement self stmt in let source_loc = match source_loc with diff --git a/compiler/backend/js_source_map.ml b/compiler/backend/js_source_map.ml index 38463b58251..522805ecfc1 100644 --- a/compiler/backend/js_source_map.ml +++ b/compiler/backend/js_source_map.ml @@ -52,11 +52,17 @@ type t = { before reading this state. *) let current = Request_local.new_key (fun () -> ref None) -let source_loc_of_loc (loc : Location.t) = +let enabled () = match !((Js_config.current ()).source_map) with - | No_source_map -> None - | Linked | Inline | Hidden -> - if loc.loc_ghost || loc.loc_start.pos_cnum < 0 then None else Some loc + | No_source_map -> false + | Linked | Inline | Hidden -> true + +let is_active () = !(Domain.DLS.get current) <> None + +let source_loc_of_loc (loc : Location.t) = + if not (enabled ()) then None + else if loc.loc_ghost || loc.loc_start.pos_cnum < 0 then None + else Some loc let with_builder builder f = let current = Domain.DLS.get current in diff --git a/compiler/backend/js_source_map.mli b/compiler/backend/js_source_map.mli index 7e9f5463fc2..a74ce91faec 100644 --- a/compiler/backend/js_source_map.mli +++ b/compiler/backend/js_source_map.mli @@ -5,6 +5,10 @@ val make : val with_builder : t -> (unit -> 'a) -> 'a +val enabled : unit -> bool + +val is_active : unit -> bool + val source_loc_of_loc : Location.t -> Location.t option val mark_source_loc : Ext_pp.t -> Location.t option -> unit diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 9e2eb2041b9..76b10c870b5 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -25,26 +25,11 @@ module E = Js_exp_make module S = Js_stmt_make -let source_map_loc = Js_source_map.source_loc_of_loc - let with_exp_source_loc_opt source_loc (exp : J.expression) = match (source_loc, exp.source_loc) with | Some _, None -> {exp with source_loc} | _ -> exp -let with_source_loc loc (exp : J.expression) = - with_exp_source_loc_opt (source_map_loc loc) exp - -let source_map_body_loc ({pat_loc; body_loc} : Lambda.branch_loc) = - match source_map_loc body_loc with - | Some _ as loc -> loc - | None -> source_map_loc pat_loc - -let source_map_case_loc ({pat_loc; body_loc} : Lambda.branch_loc) = - match source_map_loc pat_loc with - | Some _ as loc -> loc - | None -> source_map_loc body_loc - let loc_if_valid (loc : Location.t) = if (not loc.loc_ghost) && loc.loc_start.pos_cnum >= 0 then Some loc else None @@ -75,11 +60,6 @@ let rec source_loc_of_lam (lam : Lambda.t) = | Lassign (_, body) -> source_loc_of_lam body | Lvar _ | Lglobal_module _ | Lconst _ | Lbreak | Lcontinue -> None -let source_map_loc_of_lam lam = - match source_loc_of_lam lam with - | Some loc -> source_map_loc loc - | None -> None - let with_statement_source_loc source_loc (stmt : J.statement) = match source_loc with | None -> stmt @@ -123,16 +103,6 @@ let with_statement_source_loc source_loc (stmt : J.statement) = | None -> inner_loc); } -let with_branch_block_source_loc (arm_loc : Lambda.branch_loc) lam block = - let loc = - match source_map_body_loc arm_loc with - | Some _ as loc -> loc - | None -> source_map_loc_of_lam lam - in - match block with - | [] -> [] - | stmt :: rest -> with_statement_source_loc loc stmt :: rest - let args_either_function_or_const (args : Lambda.t list) = List.for_all (fun (x : Lambda.t) -> @@ -560,6 +530,52 @@ let spreads_in_place (parts : J.expression list) = in_place let compile output_prefix = + let has_source_map = Js_source_map.enabled () in + let source_map_loc loc = + if has_source_map then Js_source_map.source_loc_of_loc loc else None + in + let with_source_loc loc (exp : J.expression) = + if has_source_map then with_exp_source_loc_opt (loc_if_valid loc) exp + else exp + in + let source_map_body_loc ({pat_loc; body_loc} : Lambda.branch_loc) = + if not has_source_map then None + else + match loc_if_valid body_loc with + | Some _ as loc -> loc + | None -> loc_if_valid pat_loc + in + let source_map_case_loc ({pat_loc; body_loc} : Lambda.branch_loc) = + if not has_source_map then None + else + match loc_if_valid pat_loc with + | Some _ as loc -> loc + | None -> loc_if_valid body_loc + in + let source_map_loc_of_lam lam = + if not has_source_map then None + else + match source_loc_of_lam lam with + | Some loc -> loc_if_valid loc + | None -> None + in + let with_branch_block_source_loc (arm_loc : Lambda.branch_loc) lam block = + if not has_source_map then block + else + match block with + | [] -> [] + | stmt :: rest -> ( + let loc = + match source_map_body_loc arm_loc with + | Some _ as loc -> loc + | None -> source_map_loc_of_lam lam + in + match loc with + | None -> block + | Some _ -> + let stmt' = with_statement_source_loc loc stmt in + if stmt' == stmt then block else stmt' :: rest) + in (* When compiling a read from another module, a nested source path like Other.A.B.make reaches this point as nested module-field reads: diff --git a/compiler/backend/lam_pass_exits.ml b/compiler/backend/lam_pass_exits.ml index c9d39901c69..42007bfcae1 100644 --- a/compiler/backend/lam_pass_exits.ml +++ b/compiler/backend/lam_pass_exits.ml @@ -89,7 +89,9 @@ type subst_tbl = (Ident.t list * lam_subst) Hash_int.t let pick_branch_loc (existing : Lambda.branch_loc) (inlined : Lambda.branch_loc) = - if Lambda.has_branch_loc existing then existing else inlined + if inlined == Lambda.no_branch_loc || Lambda.has_branch_loc existing then + existing + else inlined (** Simplify ``catch body with (i ...) handler'' diff --git a/compiler/backend/lam_stats_export.ml b/compiler/backend/lam_stats_export.ml index a744ed5a739..563a561e162 100644 --- a/compiler/backend/lam_stats_export.ml +++ b/compiler/backend/lam_stats_export.ml @@ -103,6 +103,9 @@ let values_of_export (meta : Lam_stats.t) (export_map : Lambda.t Map_ident.t) : | Single Arity_na, (None | Some (Lconst Const_module_alias)) -> acc | Submodule [||], None -> acc | _ -> + let persistent_closed_lambda = + Option.map Lambda_traverse.strip_branch_locs persistent_closed_lambda + in let cmj_value : Js_cmj_format.cmj_value = {arity; persistent_closed_lambda} in diff --git a/compiler/typing/lambda.ml b/compiler/typing/lambda.ml index 256416ce215..224978f4c57 100644 --- a/compiler/typing/lambda.ml +++ b/compiler/typing/lambda.ml @@ -415,10 +415,12 @@ let has_loc (loc : Location.t) = let no_branch_loc = {pat_loc = Location.none; body_loc = Location.none} -let branch_loc ?(pat_loc = Location.none) body_loc = {pat_loc; body_loc} +let branch_loc ?(pat_loc = Location.none) body_loc = + if pat_loc == Location.none && body_loc == Location.none then no_branch_loc + else {pat_loc; body_loc} -let has_branch_loc ({pat_loc; body_loc} : branch_loc) = - has_loc pat_loc || has_loc body_loc +let has_branch_loc ({pat_loc; body_loc} as loc : branch_loc) = + loc != no_branch_loc && (has_loc pat_loc || has_loc body_loc) let no_if_locs = {if_loc = Location.none; then_loc = no_branch_loc; else_loc = no_branch_loc} @@ -1247,29 +1249,38 @@ let rec eval_const_as_bool (v : structured_constant) : bool option = let if_ ?(loc = Location.none) ?(then_loc = no_branch_loc) ?(else_loc = no_branch_loc) (a : t) (b : t) (c : t) : t = - let locs = {if_loc = loc; then_loc; else_loc} in + let make_if a b c = + let locs = + if + loc == Location.none && then_loc == no_branch_loc + && else_loc == no_branch_loc + then no_if_locs + else {if_loc = loc; then_loc; else_loc} + in + Lifthenelse (a, b, c, locs) + in match a with | Lconst v -> ( match eval_const_as_bool v with | Some v -> if v then b else c - | None -> Lifthenelse (a, b, c, locs)) + | None -> make_if a b c) | _ -> ( match (b, c) with | _, Lconst Const_assertfalse -> seq a b (* TODO: we could customize more cases *) | Lconst Const_assertfalse, _ -> seq a c | Lconst Const_js_true, Lconst Const_js_false -> - if has_boolean_type a != None then a else Lifthenelse (a, b, c, locs) + if has_boolean_type a != None then a else make_if a b c | Lconst Const_js_false, Lconst Const_js_true -> ( match has_boolean_type a with | Some loc -> not_ loc a - | None -> Lifthenelse (a, b, c, locs)) + | None -> make_if a b c) (* [if a then raise e else c] could become [(if a then raise e else ()); c], but that is code motion, not normalization: it changes the shape that matching's own exit bookkeeping inspects after the term is assembled, and doing it here leaves static raises without their catch. It is {!Lam_pass_guard_raises} instead. *) - | _ -> Lifthenelse (a, b, c, locs)) + | _ -> make_if a b c) let sequor l r = if_ l lambda_true r diff --git a/compiler/typing/lambda.mli b/compiler/typing/lambda.mli index 714ceca5e05..24386f22596 100644 --- a/compiler/typing/lambda.mli +++ b/compiler/typing/lambda.mli @@ -431,7 +431,6 @@ and lambda_switch = t switch val no_branch_loc : branch_loc val branch_loc : ?pat_loc:Location.t -> Location.t -> branch_loc val has_branch_loc : branch_loc -> bool -val no_if_locs : if_locs (* Sharing key *) diff --git a/compiler/typing/lambda_traverse.ml b/compiler/typing/lambda_traverse.ml index 8f514b8b620..026c76ba2ce 100644 --- a/compiler/typing/lambda_traverse.ml +++ b/compiler/typing/lambda_traverse.ml @@ -284,3 +284,60 @@ let subst_lambda s lam = | _ -> shallow_map_sharing subst l in subst lam + +let rec strip_cases_sharing : + 'a. ('a * t * branch_loc) list -> ('a * t * branch_loc) list = function + | [] as cases -> cases + | (key, value, loc) :: tl as cases -> + let value' = strip_branch_locs value in + let tl' = strip_cases_sharing tl in + if value' == value && loc == no_branch_loc && tl' == tl then cases + else (key, value', no_branch_loc) :: tl' + +and strip_opt_branch_sharing = function + | None as opt -> opt + | Some (value, loc) as opt -> + let value' = strip_branch_locs value in + if value' == value && loc == no_branch_loc then opt + else Some (value', no_branch_loc) + +and strip_branch_locs (lam : t) : t = + match lam with + | Lifthenelse (a, b, c, {if_loc; then_loc; else_loc}) -> + let a' = strip_branch_locs a + and b' = strip_branch_locs b + and c' = strip_branch_locs c in + if + a' == a && b' == b && c' == c && if_loc == Location.none + && then_loc == no_branch_loc && else_loc == no_branch_loc + then lam + else if_ a' b' c' + | Lswitch (e, sw) -> + let e' = strip_branch_locs e in + let consts = strip_cases_sharing sw.sw_consts in + let blocks = strip_cases_sharing sw.sw_blocks in + let fail = strip_opt_branch_sharing sw.sw_failaction in + if + e' == e && consts == sw.sw_consts && blocks == sw.sw_blocks + && fail == sw.sw_failaction && sw.sw_loc == Location.none + then lam + else + switch e' + { + sw with + sw_consts = consts; + sw_blocks = blocks; + sw_failaction = fail; + sw_loc = Location.none; + } + | Lstringswitch (e, cases, d, loc) -> + let e' = strip_branch_locs e in + let cases' = strip_cases_sharing cases in + let d' = strip_opt_branch_sharing d in + if e' == e && cases' == cases && d' == d && loc == Location.none then lam + else stringswitch e' cases' d' + | Lstaticcatch (b, h, hd, loc) -> + let b' = strip_branch_locs b and hd' = strip_branch_locs hd in + if b' == b && hd' == hd && loc == no_branch_loc then lam + else staticcatch b' h hd' + | _ -> shallow_map_sharing strip_branch_locs lam diff --git a/compiler/typing/lambda_traverse.mli b/compiler/typing/lambda_traverse.mli index 9c342c2daad..fd1f64aac3f 100644 --- a/compiler/typing/lambda_traverse.mli +++ b/compiler/typing/lambda_traverse.mli @@ -36,6 +36,10 @@ val subst_lambda : Lambda.t Ident.tbl -> Lambda.t -> Lambda.t Assumes the substitution's image is out of reach of the term's bound variables, so no capture can occur. *) +val strip_branch_locs : Lambda.t -> Lambda.t +(** Drop branch, switch, and handler source locations while preserving term + structure and sharing subterms that already carry none. *) + val make_key : Lambda.t -> Lambda.t option (** A canonical form for comparing two terms: locations are dropped, alias bindings are substituted away, and remaining binders are renumbered. Only diff --git a/compiler/typing/matching.ml b/compiler/typing/matching.ml index 8c32af2f98c..e4ae1594629 100644 --- a/compiler/typing/matching.ml +++ b/compiler/typing/matching.ml @@ -1473,17 +1473,25 @@ let single_arm_loc cases fallback = else fallback let relocate_cell_args ~switch_loc ~orig_args (cell : cell) = - let loc = single_arm_loc cell.pm.cases switch_loc in - let rec relocate args = - if args == orig_args then args - else - match args with - | [] -> [] - | (Lprim {primitive; args = pargs; loc = _}, str) :: rest -> - (prim ~primitive ~args:pargs loc, str) :: relocate rest - | hd :: rest -> hd :: relocate rest - in - {cell with pm = {cell.pm with args = relocate cell.pm.args}} + if cell.pm.args == orig_args then cell + else + let loc = single_arm_loc cell.pm.cases switch_loc in + let rec relocate args = + if args == orig_args then args + else + match args with + | [] -> [] + | (Lprim {primitive; args = pargs; loc = pr_loc}, str) :: rest -> + let rest' = relocate rest in + if pr_loc == loc && rest' == rest then args + else (prim ~primitive ~args:pargs loc, str) :: rest' + | hd :: rest -> + let rest' = relocate rest in + if rest' == rest then args else hd :: rest' + in + let args' = relocate cell.pm.args in + if args' == cell.pm.args then cell + else {cell with pm = {cell.pm with args = args'}} let divide_constructor ~switch_loc ctx pm = let orig_args = @@ -1491,10 +1499,13 @@ let divide_constructor ~switch_loc ctx pm = | _ :: argl -> argl | [] -> [] in - divide make_constr_matching Types.same_constructor get_key_constr - get_args_constr ctx pm - |> List.map (fun (cstr, cell) -> - (cstr, relocate_cell_args ~switch_loc ~orig_args cell)) + let cells = + divide make_constr_matching Types.same_constructor get_key_constr + get_args_constr ctx pm + in + Ext_list.map_sharing cells (fun ((cstr, cell) as pair) -> + let cell' = relocate_cell_args ~switch_loc ~orig_args cell in + if cell' == cell then pair else (cstr, cell')) (* Matching against a variant *) @@ -1573,9 +1584,10 @@ let divide_variant ~switch_loc row ctx {cases = cl; args = al; default = def} = al) | _ -> [] in - divide cl - |> List.map (fun (key, cell) -> - (key, relocate_cell_args ~switch_loc ~orig_args cell)) + let variants = divide cl in + Ext_list.map_sharing variants (fun ((key, cell) as pair) -> + let cell' = relocate_cell_args ~switch_loc ~orig_args cell in + if cell' == cell then pair else (key, cell')) (* Three ``no-test'' cases diff --git a/tests/ounit_tests/ounit_lambda_traverse_tests.ml b/tests/ounit_tests/ounit_lambda_traverse_tests.ml index ca28522111e..a4b6e117d23 100644 --- a/tests/ounit_tests/ounit_lambda_traverse_tests.ml +++ b/tests/ounit_tests/ounit_lambda_traverse_tests.ml @@ -139,6 +139,13 @@ let suites = ~msg:(name ^ " make_key should ignore locations") (Lambda_traverse.make_key a) (Lambda_traverse.make_key b); + assert_equal + ~msg:(name ^ " strip_branch_locs should drop locations") + (Lambda_traverse.strip_branch_locs a) + b; + assert_bool + (name ^ " strip_branch_locs should share clean terms") + (Lambda_traverse.strip_branch_locs b == b); if check_eq_approx then assert_bool (name ^ " eq_approx should ignore locations") From 74f49b01e13b72538767e9b28a4ccc25d90496d8 Mon Sep 17 00:00:00 2001 From: mununki Date: Sun, 29 Nov 2026 15:00:14 +0900 Subject: [PATCH 3/4] Handle dispatch prologues, preserve Seq source_loc, and cut pass allocations Why: 1. Non-tail pattern matches with shared destructuring prologues (such as `let match = l.tl; let x = l.hd; if (match !== 0) ...`) were rejected by the singleton-only `is_same_dispatch_block` check, mapping the dispatch block's opening brace to the enclosing `switch` and its closing brace to a descendant arm end so executing only the empty-list arm marked that executed arm uncovered in V8 coverage. Step through same-switch variable prologues and nested blocks in `is_same_dispatch_block`. 2. `Js_exp_make.econd`, `remove_pure_sub_exp`, `Js_stmt_make.exp`, and `Js_analyzer.rev_flatten_seq` dropped `source_loc` when unwrapping `Seq (_, Undefined)` wrappers around unit/ref-assignment arms. Preserve the outer `source_loc` when the unwrapped child has none. 3. `Lam_pass_exits.simplif_with_loc` allocated a `(lam, loc)` pair on every visited node, and `Lswitch`/`Lstringswitch` traversals across backend/typing passes allocated closures per switch, causing >1% allocation regressions on Result, Primitive_object, and no-op/leaf-edit benchmarks. Track inlined handler locations via a single ref and eliminate per-node/per-switch closure allocations. Signed-off-by: mununki --- compiler/backend/js_analyzer.ml | 8 +- compiler/backend/js_dump.ml | 53 ++++-- compiler/backend/js_exp_make.ml | 15 +- compiler/backend/js_stmt_make.ml | 5 + compiler/backend/lam_check.ml | 47 +++-- compiler/backend/lam_closure.ml | 16 +- compiler/backend/lam_compile.ml | 95 +++++----- compiler/backend/lam_exit_count.ml | 20 ++- compiler/backend/lam_hit.ml | 32 ++-- compiler/backend/lam_pass_collect.ml | 24 ++- compiler/backend/lam_pass_count.ml | 16 +- compiler/backend/lam_pass_exits.ml | 162 +++++++++--------- compiler/typing/lambda.ml | 42 ++--- compiler/typing/lambda_traverse.ml | 20 ++- compiler/typing/matching.ml | 26 +-- compiler/typing/translcore.ml | 17 +- tests/project_tests/source_map/input.js | 54 ++++++ .../project_tests/source_map/src/Branches.res | 20 +++ 18 files changed, 435 insertions(+), 237 deletions(-) diff --git a/compiler/backend/js_analyzer.ml b/compiler/backend/js_analyzer.ml index 3bbcd8de7eb..189123e66af 100644 --- a/compiler/backend/js_analyzer.ml +++ b/compiler/backend/js_analyzer.ml @@ -333,7 +333,13 @@ and eq_statement ({statement_desc = x0} : J.statement) let rev_flatten_seq (x : J.expression) = let rec aux acc (x : J.expression) : J.block = match x.expression_desc with - | Seq (a, b) -> aux (aux acc a) b + | Seq (a, b) -> + let a = + match (x.source_loc, a.source_loc) with + | Some _, None -> {a with source_loc = x.source_loc} + | _ -> a + in + aux (aux acc a) b | _ -> {statement_desc = Exp x; comment = None; source_loc = None} :: acc in aux [] x diff --git a/compiler/backend/js_dump.ml b/compiler/backend/js_dump.ml index cd246f8640a..22351fa3fd0 100644 --- a/compiler/backend/js_dump.ml +++ b/compiler/backend/js_dump.ml @@ -517,21 +517,42 @@ let ensure_ordered_locs start_loc end_loc = (Some s, Some s) | _ -> (start_loc, end_loc) -let rec is_same_dispatch_block (outer_loc : Location.t option) (b : J.block) = - match (outer_loc, b) with - | Some _, [{statement_desc = Block b}] -> is_same_dispatch_block outer_loc b - | ( Some outer, - [ - { +let is_same_dispatch_block (outer_loc : Location.t option) (b : J.block) = + match outer_loc with + | None -> false + | Some outer -> + let rec check (b : J.block) = + match b with + | {statement_desc = Block bs} :: rest -> check (bs @ rest) + | { statement_desc = If _ | Int_switch _ | String_switch _; source_loc = Some inner; - }; - ] ) -> - outer = inner - | _ -> false + } + :: _ -> + outer = inner + | {statement_desc = Variable {value = None}; source_loc} :: rest -> ( + match source_loc with + | None -> check rest + | Some loc when loc = outer -> check rest + | Some _ -> false) + | {statement_desc = Variable {value = Some e}; source_loc} :: rest -> ( + let loc = + match source_loc with + | Some _ as loc -> loc + | None -> e.source_loc + in + match loc with + | None -> check rest + | Some loc when loc = outer -> check rest + | Some _ -> false) + | _ -> false + in + check b let brace_vgroup_mapped f ?start_loc ?end_loc ?(end_at_start = false) n action = - Option.iter (fun loc -> Js_source_map.mark_source_loc f (Some loc)) start_loc; + (match start_loc with + | None -> () + | Some _ -> Js_source_map.mark_source_loc f start_loc); P.string f "{"; let v = P.vgroup f n (fun _ -> @@ -539,11 +560,11 @@ let brace_vgroup_mapped f ?start_loc ?end_loc ?(end_at_start = false) n action = action ()) in P.force_newline f; - Option.iter - (fun loc -> - if end_at_start then Js_source_map.mark_source_loc f (Some loc) - else Js_source_map.mark_source_loc_end f (Some loc)) - end_loc; + (match end_loc with + | None -> () + | Some _ -> + if end_at_start then Js_source_map.mark_source_loc f end_loc + else Js_source_map.mark_source_loc_end f end_loc); P.string f "}"; v diff --git a/compiler/backend/js_exp_make.ml b/compiler/backend/js_exp_make.ml index 5e7c903aac3..a867db33d0f 100644 --- a/compiler/backend/js_exp_make.ml +++ b/compiler/backend/js_exp_make.ml @@ -33,6 +33,11 @@ type t = J.expression (modulo return value) It will return None if [x] is pure *) +let preserve_source_loc (parent : t) (child : t) = + match (parent.source_loc, child.source_loc) with + | Some _, None -> {child with source_loc = parent.source_loc} + | _ -> child + let rec remove_pure_sub_exp (x : t) : t option = match x.expression_desc with | Var _ | Str _ | Template_literal _ | Json_literal _ | Number _ -> @@ -45,8 +50,8 @@ let rec remove_pure_sub_exp (x : t) : t option = | None, None -> None | Some u, Some v -> Some {x with expression_desc = Seq (u, v)} (* may still have some simplification*) - | None, (Some _ as v) -> v - | (Some _ as u), None -> u) + | None, Some v -> Some (preserve_source_loc x v) + | Some u, None -> Some (preserve_source_loc x u)) | _ -> Some x and is_pure_sub_exp (x : t) = remove_pure_sub_exp x = None @@ -1380,7 +1385,11 @@ let rec econd ?comment ?source_loc (pred : t) (ifso : t) (ifnot : t) : t = | ( _, Seq (a, {expression_desc = Undefined _}), Seq (b, {expression_desc = Undefined _}) ) -> - seq (econd ?comment ?source_loc pred a b) undefined + seq + (econd ?comment ?source_loc pred + (preserve_source_loc ifso a) + (preserve_source_loc ifnot b)) + undefined | _, _, Bool false -> ( match simplify_and pred ifso with | Some e -> e diff --git a/compiler/backend/js_stmt_make.ml b/compiler/backend/js_stmt_make.ml index 99b8634ffa2..287227816bd 100644 --- a/compiler/backend/js_stmt_make.ml +++ b/compiler/backend/js_stmt_make.ml @@ -48,6 +48,11 @@ let rec exp ?comment (e : E.t) : t = match e.expression_desc with | Seq ({expression_desc = Number _ | Undefined _}, b) | Seq (b, {expression_desc = Number _ | Undefined _}) -> + let b = + match (e.source_loc, b.source_loc) with + | Some _, None -> {b with source_loc = e.source_loc} + | _ -> b + in exp ?comment b | Number _ | Undefined _ -> block [] (* TODO: we can do more *) diff --git a/compiler/backend/lam_check.ml b/compiler/backend/lam_check.ml index a8b7ac13a9d..bf17759d623 100644 --- a/compiler/backend/lam_check.ml +++ b/compiler/backend/lam_check.ml @@ -51,6 +51,13 @@ let check ~file ~pass lam = List.iter (fun x -> check_staticfails x cxt) xs and check_list_snd : 'a. ('a * Lambda.t) list -> _ -> unit = fun xs cxt -> Ext_list.iter_snd xs (fun x -> check_staticfails x cxt) + and check_cases : 'a. ('a * Lambda.t * Lambda.branch_loc) list -> _ -> unit = + fun xs cxt -> + match xs with + | [] -> () + | (_, x, _) :: tl -> + check_staticfails x cxt; + check_cases tl cxt and check_staticfails (l : Lambda.t) (cxt : Set_int.t) = match l with | Lvar _ | Lconst _ | Lglobal_module _ -> () @@ -76,15 +83,19 @@ let check ~file ~pass lam = | Lletrec (decl, body) -> check_list_snd decl cxt; check_staticfails body cxt - | Lswitch (arg, sw) -> + | Lswitch (arg, sw) -> ( check_staticfails arg cxt; - List.iter (fun (_, x, _) -> check_staticfails x cxt) sw.sw_consts; - List.iter (fun (_, x, _) -> check_staticfails x cxt) sw.sw_blocks; - Option.iter (fun (x, _) -> check_staticfails x cxt) sw.sw_failaction - | Lstringswitch (arg, cases, default, _) -> + check_cases sw.sw_consts cxt; + check_cases sw.sw_blocks cxt; + match sw.sw_failaction with + | None -> () + | Some (x, _) -> check_staticfails x cxt) + | Lstringswitch (arg, cases, default, _) -> ( check_staticfails arg cxt; - List.iter (fun (_, x, _) -> check_staticfails x cxt) cases; - Option.iter (fun (x, _) -> check_staticfails x cxt) default + check_cases cases cxt; + match default with + | None -> () + | Some (x, _) -> check_staticfails x cxt) | Lstaticraise (i, args) -> if Set_int.mem i cxt then check_list args cxt else @@ -102,6 +113,12 @@ let check ~file ~pass lam = let rec iter_list xs = List.iter iter xs and iter_list_snd : 'a. ('a * Lambda.t) list -> unit = fun xs -> Ext_list.iter_snd xs iter + and iter_cases : 'a. ('a * Lambda.t * Lambda.branch_loc) list -> unit = + function + | [] -> () + | (_, x, _) :: tl -> + iter x; + iter_cases tl and iter (l : Lambda.t) = match l with | Lvar id -> use id @@ -124,15 +141,19 @@ let check ~file ~pass lam = iter body | Lswitch (arg, sw) -> iter arg; - List.iter (fun (_, x, _) -> iter x) sw.sw_consts; - List.iter (fun (_, x, _) -> iter x) sw.sw_blocks; - Option.iter (fun (x, _) -> iter x) sw.sw_failaction; + iter_cases sw.sw_consts; + iter_cases sw.sw_blocks; + (match sw.sw_failaction with + | None -> () + | Some (x, _) -> iter x); assert ( not (sw.sw_failaction <> None && sw.sw_consts_full && sw.sw_blocks_full)) - | Lstringswitch (arg, cases, default, _) -> + | Lstringswitch (arg, cases, default, _) -> ( iter arg; - List.iter (fun (_, x, _) -> iter x) cases; - Option.iter (fun (x, _) -> iter x) default + iter_cases cases; + match default with + | None -> () + | Some (x, _) -> iter x) | Lstaticraise (_i, args) -> iter_list args | Lstaticcatch (e1, (_, vars), e2, _) -> iter e1; diff --git a/compiler/backend/lam_closure.ml b/compiler/backend/lam_closure.ml index 30078b91c9a..78018172c30 100644 --- a/compiler/backend/lam_closure.ml +++ b/compiler/backend/lam_closure.ml @@ -68,7 +68,15 @@ let free_variables (export_idents : Set_ident.t) (params : stats Map_ident.t) if not (Set_ident.mem v !local_set) then fv := adjust !fv cur_pos v in - let rec iter (top : position) (lam : Lambda.t) = + let rec iter_cases : + 'a. position -> ('a * Lambda.t * Lambda.branch_loc) list -> unit = + fun top cases -> + match cases with + | [] -> () + | (_, case, _) :: tl -> + iter top case; + iter_cases top tl + and iter (top : position) (lam : Lambda.t) = match lam with | Lvar v -> used top v | Lconst _ -> () @@ -98,8 +106,8 @@ let free_variables (export_idents : Set_ident.t) (params : stats Map_ident.t) ) -> ( iter top arg; let top = Lam_var_stats.new_position_after_lam arg top in - List.iter (fun (_, case, _) -> iter top case) sw_consts; - List.iter (fun (_, case, _) -> iter top case) sw_blocks; + iter_cases top sw_consts; + iter_cases top sw_blocks; match sw_failaction with | None -> () | Some (x, _) -> @@ -108,7 +116,7 @@ let free_variables (export_idents : Set_ident.t) (params : stats Map_ident.t) | Lstringswitch (arg, cases, default, _) -> ( iter top arg; let top = Lam_var_stats.new_position_after_lam arg top in - List.iter (fun (_, act, _) -> iter top act) cases; + iter_cases top cases; match default with | None -> () | Some (x, _) -> iter top x) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 76b10c870b5..0e13260424c 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -576,6 +576,24 @@ let compile output_prefix = let stmt' = with_statement_source_loc loc stmt in if stmt' == stmt then block else stmt' :: rest) in + let branch_block arm_loc lam out = + Js_output.output_as_block out |> with_branch_block_source_loc arm_loc lam + in + let case_source_loc arm_loc lam = + if not has_source_map then None + else + match source_map_case_loc arm_loc with + | Some _ as loc -> loc + | None -> source_map_loc_of_lam lam + in + let econd_with_locs if_source_loc then_source_loc else_source_loc e out1 out2 + = + if not has_source_map then E.econd e out1 out2 + else + E.econd ?source_loc:if_source_loc e + (with_exp_source_loc_opt then_source_loc out1) + (with_exp_source_loc_opt else_source_loc out2) + in (* When compiling a read from another module, a nested source path like Other.A.B.make reaches this point as nested module-field reads: @@ -916,17 +934,9 @@ let compile output_prefix = ~(default : default_case) (cases : (a * Lambda.t * Lambda.branch_loc) list) -> let sw_source_loc = source_map_loc sw_loc in - let output_block_with_source_loc cxt arm_loc lam = - compile_lambda cxt lam |> Js_output.output_as_block - |> with_branch_block_source_loc arm_loc lam - in - let case_source_loc arm_loc lam = - match source_map_case_loc arm_loc with - | Some _ as loc -> loc - | None -> source_map_loc_of_lam lam - in let output_default cxt = function - | Default (lam, arm_loc) -> output_block_with_source_loc cxt arm_loc lam + | Default (lam, arm_loc) -> + branch_block arm_loc lam (compile_lambda cxt lam) | Complete | NonComplete -> [] in match (cases, default) with @@ -939,19 +949,19 @@ let compile output_prefix = otherwise the compiler engine would think that it's also complete *) - output_block_with_source_loc cxt arm_loc lam + branch_block arm_loc lam (compile_lambda cxt lam) | [(id, lam, arm_loc)], NonComplete -> morph_declare_to_assign cxt (fun cxt define -> [ S.if_ ?source_loc:sw_source_loc ?declaration:define (eq_exp None switch_exp (Some id) (make_exp id)) - (output_block_with_source_loc cxt arm_loc lam); + (branch_block arm_loc lam (compile_lambda cxt lam)); ]) | [(id, lam, arm_loc)], Default (x, x_loc) | [(id, lam, arm_loc); (_, x, x_loc)], Complete -> morph_declare_to_assign cxt (fun cxt define -> - let else_block = output_block_with_source_loc cxt x_loc x in - let then_block = output_block_with_source_loc cxt arm_loc lam in + let else_block = branch_block x_loc x (compile_lambda cxt x) in + let then_block = branch_block arm_loc lam (compile_lambda cxt lam) in [ S.if_ ?source_loc:sw_source_loc ?declaration:define (eq_exp None switch_exp (Some id) (make_exp id)) @@ -1186,14 +1196,9 @@ let compile output_prefix = | Or (test1, test2) -> E.or_ (test_exp test1) (test_exp test2) in let output_block cxt (lam, arm_loc) = - compile_lambda cxt lam |> Js_output.output_as_block - |> with_branch_block_source_loc arm_loc lam - in - let case_source_loc (lam, arm_loc) = - match source_map_case_loc arm_loc with - | Some _ as loc -> loc - | None -> source_map_loc_of_lam lam + branch_block arm_loc lam (compile_lambda cxt lam) in + let plan_case_source_loc (lam, arm_loc) = case_source_loc arm_loc lam in (* The default action is compiled once and shared by every path to it *) let fallback_blocks = ref [] in let fallback_block (cxt : Lam_compile_context.t) = @@ -1267,7 +1272,7 @@ let compile output_prefix = switch_body = []; should_break = false; comment = None; - source_loc = Option.bind arm case_source_loc; + source_loc = Option.bind arm plan_case_source_loc; } | Body (Run (lam, arm_loc)) -> let switch_body, should_break = @@ -1282,7 +1287,7 @@ let compile output_prefix = switch_body = with_branch_block_source_loc arm_loc lam switch_body; should_break; comment = None; - source_loc = case_source_loc (lam, arm_loc); + source_loc = case_source_loc arm_loc lam; } | Body Fallback -> let block = fallback_block cxt in @@ -1290,7 +1295,7 @@ let compile output_prefix = switch_body = block; should_break = not (S.block_last_is_return_throw_or_continue block); comment = None; - source_loc = Option.bind fallback case_source_loc; + source_loc = Option.bind fallback plan_case_source_loc; } | Body (Skip | If _ | Block _ | Switch_value _ | Switch_typeof _) -> assert false @@ -1794,14 +1799,6 @@ let compile output_prefix = let if_source_loc = source_map_loc if_loc in let then_source_loc = source_map_body_loc then_loc in let else_source_loc = source_map_body_loc else_loc in - let branch_block arm_loc lam out = - Js_output.output_as_block out |> with_branch_block_source_loc arm_loc lam - in - let econd_with_locs e out1 out2 = - E.econd ?source_loc:if_source_loc e - (with_exp_source_loc_opt then_source_loc out1) - (with_exp_source_loc_opt else_source_loc out2) - in match compile_lambda {lambda_cxt with continuation = NeedValue Not_tail} @@ -1817,7 +1814,10 @@ let compile output_prefix = with | {block = []; value = Some out1}, {block = []; value = Some out2} -> (* speical optimization *) - Js_output.make b ~value:(econd_with_locs e out1 out2) + Js_output.make b + ~value: + (econd_with_locs if_source_loc then_source_loc else_source_loc e + out1 out2) | _, _ -> ( (* we can not reuse -- here we need they have the same name, TODO: could be optimized by inspecting assigment statement *) @@ -1849,7 +1849,9 @@ let compile output_prefix = (b @ [ with_statement_source_loc if_source_loc - (S.define_variable ~kind id (econd_with_locs e out1 out2)); + (S.define_variable ~kind id + (econd_with_locs if_source_loc then_source_loc + else_source_loc e out1 out2)); ]) | _, _ -> Js_output.make @@ -1897,7 +1899,10 @@ let compile output_prefix = Js_output.make (b @ [S.if_ ?source_loc:if_source_loc e []]) (* FIX #1762 *) | Some out1, Some out2 -> - Js_output.make b ~value:(econd_with_locs e out1 out2) + Js_output.make b + ~value: + (econd_with_locs if_source_loc then_source_loc else_source_loc e + out1 out2) | Some out1, None -> Js_output.make (b @@ -1955,15 +1960,17 @@ let compile output_prefix = | ( Maybe_tail_is_return _, {block = []; value = Some out1}, {block = []; value = Some out2} ) -> - Js_output.make - (b - @ [ - { - (S.return_stmt (econd_with_locs e out1 out2)) with - source_loc = if_source_loc; - }; - ]) - ~output_finished:True + let stmt = + S.return_stmt + (econd_with_locs if_source_loc then_source_loc else_source_loc e + out1 out2) + in + let stmt = + match if_source_loc with + | None -> stmt + | Some _ -> {stmt with source_loc = if_source_loc} + in + Js_output.make (b @ [stmt]) ~output_finished:True | _, _, _ -> let then_output = branch_block then_loc t_branch (compile_lambda lambda_cxt t_branch) diff --git a/compiler/backend/lam_exit_count.ml b/compiler/backend/lam_exit_count.ml index ce38b8f114f..35af292b8e3 100644 --- a/compiler/backend/lam_exit_count.ml +++ b/compiler/backend/lam_exit_count.ml @@ -63,7 +63,13 @@ let count_helper (lam : Lambda.t) : collection option = if not (has_static_exit lam) then None else let exits : collection = Hash_int.create 17 in - let rec count (lam : Lambda.t) = + let rec count_cases : 'a. ('a * Lambda.t * Lambda.branch_loc) list -> unit = + function + | [] -> () + | (_, e, _) :: tl -> + count e; + count_cases tl + and count (lam : Lambda.t) = match lam with | Lstaticraise (i, ls) -> incr_exit exits i; @@ -71,10 +77,12 @@ let count_helper (lam : Lambda.t) : collection option = | Lstaticcatch (l1, (i, _), l2, _) -> count l1; if count_exit exits i > 0 then count l2 - | Lstringswitch (l, sw, d, _) -> + | Lstringswitch (l, sw, d, _) -> ( count l; - List.iter (fun (_, e, _) -> count e) sw; - Option.iter (fun (e, _) -> count e) d + count_cases sw; + match d with + | None -> () + | Some (e, _) -> count e) | Lglobal_module _ | Lvar _ | Lconst _ -> () | Lapply {ap_func; ap_args; _} -> count ap_func; @@ -90,8 +98,8 @@ let count_helper (lam : Lambda.t) : collection option = | Lswitch (l, sw) -> count_default sw; count l; - List.iter (fun (_, e, _) -> count e) sw.sw_consts; - List.iter (fun (_, e, _) -> count e) sw.sw_blocks + count_cases sw.sw_consts; + count_cases sw.sw_blocks | Ltrywith (l1, _, l2) | Ltryfinally (l1, l2) -> count l1; count l2 diff --git a/compiler/backend/lam_hit.ml b/compiler/backend/lam_hit.ml index 477f106064d..910fba486c4 100644 --- a/compiler/backend/lam_hit.ml +++ b/compiler/backend/lam_hit.ml @@ -28,6 +28,12 @@ let hit_variables (fv : Set_ident.t) (l : t) : bool = let rec hit_var (id : Ident.t) = Set_ident.mem id fv and hit_list_snd : 'a. ('a * t) list -> bool = fun x -> Ext_list.exists_snd x hit + and hit_cases : 'a. ('a * t * Lambda.branch_loc) list -> bool = function + | [] -> false + | (_, e, _) :: tl -> hit e || hit_cases tl + and hit_opt = function + | None -> false + | Some (e, _) -> hit e and hit_list xs = List.exists hit xs and hit (l : t) = match (l : t) with @@ -45,14 +51,10 @@ let hit_variables (fv : Set_ident.t) (l : t) : bool = | Lglobal_module _ (* global persistent module, play safe *) -> false | Lprim {args; _} -> hit_list args | Lswitch (arg, sw) -> - hit arg - || List.exists (fun (_, e, _) -> hit e) sw.sw_consts - || List.exists (fun (_, e, _) -> hit e) sw.sw_blocks - || Option.fold ~none:false ~some:(fun (e, _) -> hit e) sw.sw_failaction + hit arg || hit_cases sw.sw_consts || hit_cases sw.sw_blocks + || hit_opt sw.sw_failaction | Lstringswitch (arg, cases, default, _) -> - hit arg - || List.exists (fun (_, e, _) -> hit e) cases - || Option.fold ~none:false ~some:(fun (e, _) -> hit e) default + hit arg || hit_cases cases || hit_opt default | Lstaticraise (_, args) -> hit_list args | Lifthenelse (e1, e2, e3, _) -> hit e1 || hit e2 || hit e3 | Lsequence (e1, e2) -> hit e1 || hit e2 @@ -65,6 +67,12 @@ let hit_variable (fv : Ident.t) (l : t) : bool = let rec hit_var (id : Ident.t) = Ident.same id fv and hit_list_snd : 'a. ('a * t) list -> bool = fun x -> Ext_list.exists_snd x hit + and hit_cases : 'a. ('a * t * Lambda.branch_loc) list -> bool = function + | [] -> false + | (_, e, _) :: tl -> hit e || hit_cases tl + and hit_opt = function + | None -> false + | Some (e, _) -> hit e and hit_list xs = List.exists hit xs and hit (l : t) = match (l : t) with @@ -82,14 +90,10 @@ let hit_variable (fv : Ident.t) (l : t) : bool = | Lglobal_module _ (* global persistent module, play safe *) -> false | Lprim {args; _} -> hit_list args | Lswitch (arg, sw) -> - hit arg - || List.exists (fun (_, e, _) -> hit e) sw.sw_consts - || List.exists (fun (_, e, _) -> hit e) sw.sw_blocks - || Option.fold ~none:false ~some:(fun (e, _) -> hit e) sw.sw_failaction + hit arg || hit_cases sw.sw_consts || hit_cases sw.sw_blocks + || hit_opt sw.sw_failaction | Lstringswitch (arg, cases, default, _) -> - hit arg - || List.exists (fun (_, e, _) -> hit e) cases - || Option.fold ~none:false ~some:(fun (e, _) -> hit e) default + hit arg || hit_cases cases || hit_opt default | Lstaticraise (_, args) -> hit_list args | Lifthenelse (e1, e2, e3, _) -> hit e1 || hit e2 || hit e3 | Lsequence (e1, e2) -> hit e1 || hit e2 diff --git a/compiler/backend/lam_pass_collect.ml b/compiler/backend/lam_pass_collect.ml index f1899d631cd..99a93a81e82 100644 --- a/compiler/backend/lam_pass_collect.ml +++ b/compiler/backend/lam_pass_collect.ml @@ -79,6 +79,12 @@ let collect_info (meta : Lam_stats.t) (lam : Lambda.t) = collect x; if Set_ident.mem ident meta.export_idents then annotate meta rec_flag ident (Lam_arity_analysis.get_arity meta x) lam + and collect_cases : 'a. ('a * Lambda.t * Lambda.branch_loc) list -> unit = + function + | [] -> () + | (_, e, _) :: tl -> + collect e; + collect_cases tl and collect (lam : Lambda.t) = match lam with | Lconst _ -> () @@ -106,15 +112,19 @@ let collect_info (meta : Lam_stats.t) (lam : Lambda.t) = collect body | Lglobal_module _ -> () | Lprim {args; _} -> List.iter collect args - | Lswitch (l, {sw_failaction; sw_consts; sw_blocks}) -> + | Lswitch (l, {sw_failaction; sw_consts; sw_blocks}) -> ( collect l; - List.iter (fun (_, e, _) -> collect e) sw_consts; - List.iter (fun (_, e, _) -> collect e) sw_blocks; - Option.iter (fun (e, _) -> collect e) sw_failaction - | Lstringswitch (l, sw, d, _) -> + collect_cases sw_consts; + collect_cases sw_blocks; + match sw_failaction with + | None -> () + | Some (e, _) -> collect e) + | Lstringswitch (l, sw, d, _) -> ( collect l; - List.iter (fun (_, e, _) -> collect e) sw; - Option.iter (fun (e, _) -> collect e) d + collect_cases sw; + match d with + | None -> () + | Some (e, _) -> collect e) | Lstaticraise (_code, ls) -> List.iter collect ls | Lstaticcatch (l1, (_, _), l2, _) -> collect l1; diff --git a/compiler/backend/lam_pass_count.ml b/compiler/backend/lam_pass_count.ml index a56b2efbfe7..25f3adb088a 100644 --- a/compiler/backend/lam_pass_count.ml +++ b/compiler/backend/lam_pass_count.ml @@ -92,7 +92,15 @@ let collect_occurs ~assignable lam : occ_tbl = ()) in - let rec count (bv : local_tbl) (lam : Lambda.t) = + let rec count_cases : + 'a. local_tbl -> ('a * Lambda.t * Lambda.branch_loc) list -> unit = + fun bv cases -> + match cases with + | [] -> () + | (_, l, _) :: tl -> + count bv l; + count_cases bv tl + and count (bv : local_tbl) (lam : Lambda.t) = match lam with | Lfunction {body = l} -> count Map_ident.empty l (* when entering a function local [bv] @@ -147,11 +155,11 @@ let collect_occurs ~assignable lam : occ_tbl = | Lswitch (l, sw) -> count_default bv sw; count bv l; - List.iter (fun (_, l, _) -> count bv l) sw.sw_consts; - List.iter (fun (_, l, _) -> count bv l) sw.sw_blocks + count_cases bv sw.sw_consts; + count_cases bv sw.sw_blocks | Lstringswitch (l, sw, d, _) -> ( count bv l; - List.iter (fun (_, l, _) -> count bv l) sw; + count_cases bv sw; match d with | Some (d, _) -> count bv d | None -> ()) diff --git a/compiler/backend/lam_pass_exits.ml b/compiler/backend/lam_pass_exits.ml index 42007bfcae1..4e00a65ceea 100644 --- a/compiler/backend/lam_pass_exits.ml +++ b/compiler/backend/lam_pass_exits.ml @@ -79,13 +79,7 @@ and no_bounded_variables (l : Lambda.t) = ]} *) -type lam_subst = {lam: Lambda.t; loc: Lambda.branch_loc} -(** The third argument is its occurrence, - when do the substitution, if its occurence is > 1, - we should refresh -*) - -type subst_tbl = (Ident.t list * lam_subst) Hash_int.t +type subst_tbl = (Ident.t list * Lambda.t * Lambda.branch_loc) Hash_int.t let pick_branch_loc (existing : Lambda.branch_loc) (inlined : Lambda.branch_loc) = @@ -155,6 +149,7 @@ let pick_branch_loc (existing : Lambda.branch_loc) (inlined : Lambda.branch_loc) let subst_helper (subst : subst_tbl) (query : int -> int) (lam : Lambda.t) : Lambda.t = + let inlined_loc = ref Lambda.no_branch_loc in let rec simplif_cases : 'a. ('a * Lambda.t * Lambda.branch_loc) list -> @@ -163,37 +158,44 @@ let subst_helper (subst : subst_tbl) (query : int -> int) (lam : Lambda.t) : match cases with | [] -> cases | (k, arm, loc) :: tl -> - let arm', inlined_loc = simplif_with_loc arm in - let loc' = pick_branch_loc loc inlined_loc in + inlined_loc := Lambda.no_branch_loc; + let arm' = simplif arm in + let loc' = pick_branch_loc loc !inlined_loc in let tl' = simplif_cases tl in if arm' == arm && loc' == loc && tl' == tl then cases else (k, arm', loc') :: tl' and simplif_opt_branch = function | None -> None | Some (arm, loc) as opt -> - let arm', inlined_loc = simplif_with_loc arm in - let loc' = pick_branch_loc loc inlined_loc in + inlined_loc := Lambda.no_branch_loc; + let arm' = simplif arm in + let loc' = pick_branch_loc loc !inlined_loc in if arm' == arm && loc' == loc then opt else Some (arm', loc') - and simplif_with_loc (lam : Lambda.t) : Lambda.t * Lambda.branch_loc = + and simplif (lam : Lambda.t) : Lambda.t = match lam with | Lstaticcatch (l1, (i, xs), l2, handler_loc) -> ( let i_occur = query i in match (i_occur, l2) with - | 0, _ -> simplif_with_loc l1 + | 0, _ -> simplif l1 | _, Lvar _ | _, Lconst _ (* when i >= 0 # 2316 *) -> - let l2', inlined_loc = simplif_with_loc l2 in - let loc = pick_branch_loc handler_loc inlined_loc in - Hash_int.add subst i (xs, {lam = l2'; loc}); - simplif_with_loc l1 (* l1 will inline *) + inlined_loc := Lambda.no_branch_loc; + let l2' = simplif l2 in + let loc = pick_branch_loc handler_loc !inlined_loc in + Hash_int.add subst i (xs, l2', loc); + inlined_loc := Lambda.no_branch_loc; + simplif l1 (* l1 will inline *) | 1, _ when i >= 0 -> (* Ask: Note that we have predicate i >=0 *) - let l2', inlined_loc = simplif_with_loc l2 in - let loc = pick_branch_loc handler_loc inlined_loc in - Hash_int.add subst i (xs, {lam = l2'; loc}); - simplif_with_loc l1 (* l1 will inline *) + inlined_loc := Lambda.no_branch_loc; + let l2' = simplif l2 in + let loc = pick_branch_loc handler_loc !inlined_loc in + Hash_int.add subst i (xs, l2', loc); + inlined_loc := Lambda.no_branch_loc; + simplif l1 (* l1 will inline *) | _ -> - let l2', inlined_loc = simplif_with_loc l2 in - let handler_loc' = pick_branch_loc handler_loc inlined_loc in + inlined_loc := Lambda.no_branch_loc; + let l2' = simplif l2 in + let handler_loc' = pick_branch_loc handler_loc !inlined_loc in (* we only inline when [l2] does not contain bound variables no need to refresh *) @@ -207,81 +209,87 @@ let subst_helper (subst : subst_tbl) (query : int -> int) (lam : Lambda.t) : || lam_size < 5 in if ok_to_inline then ( - Hash_int.add subst i (xs, {lam = l2'; loc = handler_loc'}); - simplif_with_loc l1) - else - let l1', loc1 = simplif_with_loc l1 in - if l1' == l1 && l2' == l2 && handler_loc' == handler_loc then - (lam, loc1) - else (Lambda.staticcatch ~loc:handler_loc' l1' (i, xs) l2', loc1)) + Hash_int.add subst i (xs, l2', handler_loc'); + inlined_loc := Lambda.no_branch_loc; + simplif l1) + else ( + inlined_loc := Lambda.no_branch_loc; + let l1' = simplif l1 in + if l1' == l1 && l2' == l2 && handler_loc' == handler_loc then lam + else Lambda.staticcatch ~loc:handler_loc' l1' (i, xs) l2')) | Lstaticraise (i, []) -> ( match Hash_int.find_opt subst i with - | Some (_, {lam = handler; loc}) -> (handler, loc) - | None -> (lam, Lambda.no_branch_loc)) + | Some (_, handler, loc) -> + inlined_loc := loc; + handler + | None -> + inlined_loc := Lambda.no_branch_loc; + lam) | Lstaticraise (i, ls) -> ( - let ls' = Ext_list.map_sharing ls simplif in + let ls' = Ext_list.map_sharing ls simplif_sub in match Hash_int.find_opt subst i with - | Some (xs, {lam = handler; loc}) -> + | Some (xs, handler, loc) -> let ys = List.map Ident.rename xs in let env = List.fold_right2 (fun x y t -> Ident.add x (Lambda.var y) t) xs ys Ident.empty in - ( List.fold_right2 - (fun y l r -> Lambda.let_ Strict y l r) - ys ls' - (Lambda_traverse.subst_lambda env handler), - loc ) + inlined_loc := loc; + List.fold_right2 + (fun y l r -> Lambda.let_ Strict y l r) + ys ls' + (Lambda_traverse.subst_lambda env handler) | None -> - ( (if ls' == ls then lam else Lambda.staticraise i ls'), - Lambda.no_branch_loc )) + inlined_loc := Lambda.no_branch_loc; + if ls' == ls then lam else Lambda.staticraise i ls') | Llet (kind, id, e, body) -> - let e' = simplif e in - let body', loc = simplif_with_loc body in - if e' == e && body' == body then (lam, loc) - else (Lambda.let_ kind id e' body', loc) + let e' = simplif_sub e in + inlined_loc := Lambda.no_branch_loc; + let body' = simplif body in + if e' == e && body' == body then lam else Lambda.let_ kind id e' body' | Lifthenelse (a, b, c, {if_loc; then_loc; else_loc}) -> - let a' = simplif a in - let b', inlined_then = simplif_with_loc b in - let c', inlined_else = simplif_with_loc c in - let then_loc' = pick_branch_loc then_loc inlined_then in - let else_loc' = pick_branch_loc else_loc inlined_else in - let res = - if - a' == a && b' == b && c' == c && then_loc' == then_loc - && else_loc' == else_loc - then lam - else - Lambda.if_ ~loc:if_loc ~then_loc:then_loc' ~else_loc:else_loc' a' b' - c' - in - (res, Lambda.no_branch_loc) + let a' = simplif_sub a in + inlined_loc := Lambda.no_branch_loc; + let b' = simplif b in + let then_loc' = pick_branch_loc then_loc !inlined_loc in + inlined_loc := Lambda.no_branch_loc; + let c' = simplif c in + let else_loc' = pick_branch_loc else_loc !inlined_loc in + inlined_loc := Lambda.no_branch_loc; + if + a' == a && b' == b && c' == c && then_loc' == then_loc + && else_loc' == else_loc + then lam + else + Lambda.if_ ~loc:if_loc ~then_loc:then_loc' ~else_loc:else_loc' a' b' c' | Lswitch (arg, sw) -> - let arg' = simplif arg in + let arg' = simplif_sub arg in let sw_consts = simplif_cases sw.sw_consts in let sw_blocks = simplif_cases sw.sw_blocks in let sw_failaction = simplif_opt_branch sw.sw_failaction in - let res = - if - arg' == arg && sw_consts == sw.sw_consts && sw_blocks == sw.sw_blocks - && sw_failaction == sw.sw_failaction - then lam - else Lambda.switch arg' {sw with sw_consts; sw_blocks; sw_failaction} - in - (res, Lambda.no_branch_loc) + inlined_loc := Lambda.no_branch_loc; + if + arg' == arg && sw_consts == sw.sw_consts && sw_blocks == sw.sw_blocks + && sw_failaction == sw.sw_failaction + then lam + else Lambda.switch arg' {sw with sw_consts; sw_blocks; sw_failaction} | Lstringswitch (arg, cases, default, loc) -> - let arg' = simplif arg in + let arg' = simplif_sub arg in let cases' = simplif_cases cases in let default' = simplif_opt_branch default in - let res = - if arg' == arg && cases' == cases && default' == default then lam - else Lambda.stringswitch ~loc arg' cases' default' - in - (res, Lambda.no_branch_loc) + inlined_loc := Lambda.no_branch_loc; + if arg' == arg && cases' == cases && default' == default then lam + else Lambda.stringswitch ~loc arg' cases' default' | _ -> - (Lambda_traverse.shallow_map_sharing simplif lam, Lambda.no_branch_loc) - and simplif (lam : Lambda.t) = fst (simplif_with_loc lam) in + let res = Lambda_traverse.shallow_map_sharing simplif_sub lam in + inlined_loc := Lambda.no_branch_loc; + res + and simplif_sub (lam : Lambda.t) : Lambda.t = + let res = simplif lam in + inlined_loc := Lambda.no_branch_loc; + res + in simplif lam let simplify_exits (lam : Lambda.t) = diff --git a/compiler/typing/lambda.ml b/compiler/typing/lambda.ml index 224978f4c57..1920db5492f 100644 --- a/compiler/typing/lambda.ml +++ b/compiler/typing/lambda.ml @@ -836,7 +836,10 @@ let rec eq_approx (l1 : t) (l2 : t) = match l2 with | Lstringswitch (arg2, patterns2, default2, _) -> eq_approx arg arg2 - && eq_option (Option.map fst default) (Option.map fst default2) + && (match (default, default2) with + | None, None -> true + | Some (a, _), Some (b, _) -> eq_approx a b + | _ -> false) && Ext_list.for_all2_no_exn patterns patterns2 (fun ((k : string), v, _) (k2, v2, _) -> k = k2 && eq_approx v v2) | _ -> false) @@ -848,14 +851,6 @@ let rec eq_approx (l1 : t) (l2 : t) = | Lfor_await_of (_, _, _) -> false -and eq_option l1 l2 = - match l1 with - | None -> l2 = None - | Some l1 -> ( - match l2 with - | Some l2 -> eq_approx l1 l2 - | None -> false) - and eq_approx_list ls ls1 = Ext_list.for_all2_no_exn ls ls1 eq_approx (* The JavaScript value a constant is emitted as by [Lam_compile_const] and @@ -1247,40 +1242,41 @@ let rec eval_const_as_bool (v : structured_constant) : bool option = | Null | Undefined -> Some false | Float _ | BigInt _ -> None) +let make_if ~loc ~then_loc ~else_loc (a : t) (b : t) (c : t) : t = + let locs = + if + loc == Location.none && then_loc == no_branch_loc + && else_loc == no_branch_loc + then no_if_locs + else {if_loc = loc; then_loc; else_loc} + in + Lifthenelse (a, b, c, locs) + let if_ ?(loc = Location.none) ?(then_loc = no_branch_loc) ?(else_loc = no_branch_loc) (a : t) (b : t) (c : t) : t = - let make_if a b c = - let locs = - if - loc == Location.none && then_loc == no_branch_loc - && else_loc == no_branch_loc - then no_if_locs - else {if_loc = loc; then_loc; else_loc} - in - Lifthenelse (a, b, c, locs) - in match a with | Lconst v -> ( match eval_const_as_bool v with | Some v -> if v then b else c - | None -> make_if a b c) + | None -> make_if ~loc ~then_loc ~else_loc a b c) | _ -> ( match (b, c) with | _, Lconst Const_assertfalse -> seq a b (* TODO: we could customize more cases *) | Lconst Const_assertfalse, _ -> seq a c | Lconst Const_js_true, Lconst Const_js_false -> - if has_boolean_type a != None then a else make_if a b c + if has_boolean_type a != None then a + else make_if ~loc ~then_loc ~else_loc a b c | Lconst Const_js_false, Lconst Const_js_true -> ( match has_boolean_type a with | Some loc -> not_ loc a - | None -> make_if a b c) + | None -> make_if ~loc ~then_loc ~else_loc a b c) (* [if a then raise e else c] could become [(if a then raise e else ()); c], but that is code motion, not normalization: it changes the shape that matching's own exit bookkeeping inspects after the term is assembled, and doing it here leaves static raises without their catch. It is {!Lam_pass_guard_raises} instead. *) - | _ -> make_if a b c) + | _ -> make_if ~loc ~then_loc ~else_loc a b c) let sequor l r = if_ l lambda_true r diff --git a/compiler/typing/lambda_traverse.ml b/compiler/typing/lambda_traverse.ml index 026c76ba2ce..9b3fbd343fc 100644 --- a/compiler/typing/lambda_traverse.ml +++ b/compiler/typing/lambda_traverse.ml @@ -190,6 +190,16 @@ let make_key e = try Some (tr_rec Ident.empty e) with Not_simple -> None +let rec exists_cases cases f = + match cases with + | [] -> false + | (_, e, _) :: tl -> f e || exists_cases tl f + +let exists_opt_branch opt f = + match opt with + | None -> false + | Some (e, _) -> f e + (* Does any immediate child satisfy [f]? Short-circuits. *) let shallow_exists (f : t -> bool) (lam : t) : bool = match lam with @@ -200,14 +210,10 @@ let shallow_exists (f : t -> bool) (lam : t) : bool = | Lletrec (decl, body) -> f body || Ext_list.exists_snd decl f | Lprim {args} -> List.exists f args | Lswitch (arg, {sw_consts; sw_blocks; sw_failaction}) -> - f arg - || List.exists (fun (_, e, _) -> f e) sw_consts - || List.exists (fun (_, e, _) -> f e) sw_blocks - || Option.fold ~none:false ~some:(fun (e, _) -> f e) sw_failaction + f arg || exists_cases sw_consts f || exists_cases sw_blocks f + || exists_opt_branch sw_failaction f | Lstringswitch (arg, cases, default, _) -> - f arg - || List.exists (fun (_, e, _) -> f e) cases - || Option.fold ~none:false ~some:(fun (e, _) -> f e) default + f arg || exists_cases cases f || exists_opt_branch default f | Lstaticraise (_, args) -> List.exists f args | Lstaticcatch (e1, _, e2, _) -> f e1 || f e2 | Ltrywith (e1, _, e2) | Ltryfinally (e1, e2) -> f e1 || f e2 diff --git a/compiler/typing/matching.ml b/compiler/typing/matching.ml index e4ae1594629..099378e6951 100644 --- a/compiler/typing/matching.ml +++ b/compiler/typing/matching.ml @@ -1461,16 +1461,16 @@ let make_constr_matching p def ctx = function pat = normalize_pat p; } +let rec all_same_pat_loc loc = function + | [] -> true + | (_, act') :: rest -> act'.loc.pat_loc = loc && all_same_pat_loc loc rest + let single_arm_loc cases fallback = match cases with | [] -> fallback | (_, act) :: rest -> let loc = act.loc.pat_loc in - if - loc <> Location.none - && List.for_all (fun (_, act') -> act'.loc.pat_loc = loc) rest - then loc - else fallback + if loc <> Location.none && all_same_pat_loc loc rest then loc else fallback let relocate_cell_args ~switch_loc ~orig_args (cell : cell) = if cell.pm.args == orig_args then cell @@ -1493,6 +1493,14 @@ let relocate_cell_args ~switch_loc ~orig_args (cell : cell) = if args' == cell.pm.args then cell else {cell with pm = {cell.pm with args = args'}} +let rec relocate_cells ~switch_loc ~orig_args = function + | [] as xs -> xs + | ((key, cell) as pair) :: rest as xs -> + let cell' = relocate_cell_args ~switch_loc ~orig_args cell in + let rest' = relocate_cells ~switch_loc ~orig_args rest in + if cell' == cell && rest' == rest then xs + else (if cell' == cell then pair else (key, cell')) :: rest' + let divide_constructor ~switch_loc ctx pm = let orig_args = match pm.args with @@ -1503,9 +1511,7 @@ let divide_constructor ~switch_loc ctx pm = divide make_constr_matching Types.same_constructor get_key_constr get_args_constr ctx pm in - Ext_list.map_sharing cells (fun ((cstr, cell) as pair) -> - let cell' = relocate_cell_args ~switch_loc ~orig_args cell in - if cell' == cell then pair else (cstr, cell')) + relocate_cells ~switch_loc ~orig_args cells (* Matching against a variant *) @@ -1585,9 +1591,7 @@ let divide_variant ~switch_loc row ctx {cases = cl; args = al; default = def} = | _ -> [] in let variants = divide cl in - Ext_list.map_sharing variants (fun ((key, cell) as pair) -> - let cell' = relocate_cell_args ~switch_loc ~orig_args cell in - if cell' == cell then pair else (key, cell')) + relocate_cells ~switch_loc ~orig_args variants (* Three ``no-test'' cases diff --git a/compiler/typing/translcore.ml b/compiler/typing/translcore.ml index 0478206be03..5640f863730 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -919,6 +919,13 @@ let wrap_exn loc arg = let exception_id_destructed (l : Lambda.t) (fv : Ident.t) : bool = let rec hit_list_snd : 'a. ('a * _) list -> bool = fun x -> Ext_list.exists_snd x hit + and hit_cases : 'a. ('a * Lambda.t * Lambda.branch_loc) list -> bool = + function + | [] -> false + | (_, e, _) :: tl -> hit e || hit_cases tl + and hit_opt = function + | None -> false + | Some (e, _) -> hit e and hit_list xs = List.exists hit xs and hit (l : Lambda.t) = match l with @@ -937,14 +944,10 @@ let exception_id_destructed (l : Lambda.t) (fv : Ident.t) : bool = | Lglobal_module _ | Lconst _ -> false | Lapply {ap_func; ap_args} -> hit ap_func || hit_list ap_args | Lswitch (arg, sw) -> - hit arg - || List.exists (fun (_, e, _) -> hit e) sw.sw_consts - || List.exists (fun (_, e, _) -> hit e) sw.sw_blocks - || Option.fold ~none:false ~some:(fun (e, _) -> hit e) sw.sw_failaction + hit arg || hit_cases sw.sw_consts || hit_cases sw.sw_blocks + || hit_opt sw.sw_failaction | Lstringswitch (arg, cases, default, _) -> - hit arg - || List.exists (fun (_, e, _) -> hit e) cases - || Option.fold ~none:false ~some:(fun (e, _) -> hit e) default + hit arg || hit_cases cases || hit_opt default | Lstaticraise (_, args) -> hit_list args | Lifthenelse (e1, e2, e3, _) -> hit e1 || hit e2 || hit e3 | Lsequence (e1, e2) -> hit e1 || hit e2 diff --git a/tests/project_tests/source_map/input.js b/tests/project_tests/source_map/input.js index 3e367b4f802..e46673dce8a 100644 --- a/tests/project_tests/source_map/input.js +++ b/tests/project_tests/source_map/input.js @@ -819,6 +819,8 @@ async function assertNodeV8CoverageUsesSourceMap() { Branches.ifChain(true, false); Branches.imperativeSwitch({ TAG: "Circle", _0: 2.0 }); Branches.multilineSwitch({ TAG: "Circle", _0: 2.0 }); + Branches.lstRef(0, { contents: -1 }); + Branches.lstRefPair({ hd: 1, tl: { hd: 2, tl: 0 } }, { contents: -1 }); `, ); @@ -902,6 +904,8 @@ async function assertNodeV8CoverageUsesSourceMap() { "ifChain", "imperativeSwitch", "multilineSwitch", + "lstRef", + "lstRefPair", ]); for (const fn of scriptCov.functions) { @@ -1048,6 +1052,56 @@ async function assertNodeV8CoverageUsesSourceMap() { 0, "Unexecuted multiline Square body line must be uncovered", ); + + // Non-tail list match with shared destructuring prologue (`let match = l.tl`): + // executing only `list{}` must NOT mark the executed `list{}` arm uncovered. + const lstRefNilLine = findSingleTokenPosition( + branchesSource, + "| list{} => out := 0", + ).line; + assert.equal( + resLineInfos[lstRefNilLine].count, + 1, + "Executed empty-list arm in non-tail lstRef must stay covered", + ); + + // Executing only the `list{x, y}` arm in `lstRefPair` must keep that arm + // covered while reporting the unexecuted `list{}`, `list{x}`, and fallback + // ref-assignment arms as uncovered (preserving Seq(_, Undefined) source_loc). + const lstRefPairNilLine = findSingleTokenPosition( + branchesSource, + "| list{} => out := 100", + ).line; + const lstRefPairOneLine = findSingleTokenPosition( + branchesSource, + "| list{x} => out := x + 100", + ).line; + const lstRefPairTwoLine = findSingleTokenPosition( + branchesSource, + "| list{x, y} => out := x + y + 100", + ).line; + const lstRefPairManyLine = findSingleTokenPosition( + branchesSource, + "| list{_, _, ..._} => out := 199", + ).line; + assert.equal( + resLineInfos[lstRefPairTwoLine].count, + 1, + "Executed pair arm in lstRefPair must stay covered", + ); + const lstRefPairUncovered = (remappedByFn.get("lstRefPair") ?? []).filter( + r => r.count === 0, + ); + for (const [label, line] of [ + ["list{}", lstRefPairNilLine], + ["list{x}", lstRefPairOneLine], + ["list{_, _, ..._}", lstRefPairManyLine], + ]) { + assert.ok( + lstRefPairUncovered.some(r => r.startLine === line), + `V8 coverage should detect uncovered ${label} ref-assignment arm in lstRefPair`, + ); + } } finally { await fs.rm(driverPath, { force: true }); await fs.rm(covDir, { recursive: true, force: true }); diff --git a/tests/project_tests/source_map/src/Branches.res b/tests/project_tests/source_map/src/Branches.res index 6773d74d21e..bee46ca50bc 100644 --- a/tests/project_tests/source_map/src/Branches.res +++ b/tests/project_tests/source_map/src/Branches.res @@ -129,3 +129,23 @@ let multilineSwitch = s => let msg = "arm_ml_unknown" msg } + +let lstRef = (l: list, out: ref) => { + switch l { + | list{} => out := 0 + | list{x} => out := x + | list{x, y} => out := x + y + | list{_, _, ..._} => out := 99 + } + out.contents +} + +let lstRefPair = (l: list, out: ref) => { + switch l { + | list{} => out := 100 + | list{x} => out := x + 100 + | list{x, y} => out := x + y + 100 + | list{_, _, ..._} => out := 199 + } + out.contents +} From c7e1138f9241c86805ae226824238eb092f04ca8 Mon Sep 17 00:00:00 2001 From: mununki Date: Sun, 29 Nov 2026 16:14:31 +0900 Subject: [PATCH 4/4] Hoist source-map helpers out of Lam_compile.compile Why: `Lam_compile_main.compile` calls `Lam_compile.compile_lambda ~output_prefix` once per top-level `Lam_group.t`, which re-enters `Lam_compile.compile`. Keeping the nine source-map helper functions nested inside `compile` capturing `has_source_map` allocated fresh closures for every top-level group, regressing allocations by +1.32% on `build/Namespace/edit` (1,000 top-level namespace alias groups) and +0.71% on `stress/InlineChain.res`. Hoist the source-map helpers to module top-level so `Lam_compile.compile` allocates no per-group closures, checking `Js_source_map.enabled ()` inside each helper and caching it locally in `compile_ifthenelse`. Signed-off-by: mununki --- compiler/backend/lam_compile.ml | 139 ++++++++++++++++---------------- 1 file changed, 71 insertions(+), 68 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 0e13260424c..ab5574c9f54 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -25,14 +25,33 @@ module E = Js_exp_make module S = Js_stmt_make +let source_map_loc = Js_source_map.source_loc_of_loc + let with_exp_source_loc_opt source_loc (exp : J.expression) = match (source_loc, exp.source_loc) with | Some _, None -> {exp with source_loc} | _ -> exp +let with_source_loc loc (exp : J.expression) = + with_exp_source_loc_opt (source_map_loc loc) exp + let loc_if_valid (loc : Location.t) = if (not loc.loc_ghost) && loc.loc_start.pos_cnum >= 0 then Some loc else None +let source_map_body_loc ({pat_loc; body_loc} : Lambda.branch_loc) = + if not (Js_source_map.enabled ()) then None + else + match loc_if_valid body_loc with + | Some _ as loc -> loc + | None -> loc_if_valid pat_loc + +let source_map_case_loc ({pat_loc; body_loc} : Lambda.branch_loc) = + if not (Js_source_map.enabled ()) then None + else + match loc_if_valid pat_loc with + | Some _ as loc -> loc + | None -> loc_if_valid body_loc + let rec source_loc_of_lam (lam : Lambda.t) = match lam with | Lapply {ap_loc} -> Some ap_loc @@ -103,6 +122,50 @@ let with_statement_source_loc source_loc (stmt : J.statement) = | None -> inner_loc); } +let source_map_loc_of_lam lam = + if not (Js_source_map.enabled ()) then None + else + match source_loc_of_lam lam with + | Some loc -> loc_if_valid loc + | None -> None + +let with_branch_block_source_loc (arm_loc : Lambda.branch_loc) lam block = + if not (Js_source_map.enabled ()) then block + else + match block with + | [] -> [] + | stmt :: rest -> ( + let loc = + match source_map_body_loc arm_loc with + | Some _ as loc -> loc + | None -> source_map_loc_of_lam lam + in + match loc with + | None -> block + | Some _ -> + let stmt' = with_statement_source_loc loc stmt in + if stmt' == stmt then block else stmt' :: rest) + +let branch_block arm_loc lam out = + Js_output.output_as_block out |> with_branch_block_source_loc arm_loc lam + +let case_source_loc arm_loc lam = + if not (Js_source_map.enabled ()) then None + else + match source_map_case_loc arm_loc with + | Some _ as loc -> loc + | None -> source_map_loc_of_lam lam + +let plan_case_source_loc (lam, arm_loc) = case_source_loc arm_loc lam + +let econd_with_locs if_source_loc then_source_loc else_source_loc e out1 out2 = + match (if_source_loc, then_source_loc, else_source_loc) with + | None, None, None -> E.econd e out1 out2 + | _ -> + E.econd ?source_loc:if_source_loc e + (with_exp_source_loc_opt then_source_loc out1) + (with_exp_source_loc_opt else_source_loc out2) + let args_either_function_or_const (args : Lambda.t list) = List.for_all (fun (x : Lambda.t) -> @@ -530,70 +593,6 @@ let spreads_in_place (parts : J.expression list) = in_place let compile output_prefix = - let has_source_map = Js_source_map.enabled () in - let source_map_loc loc = - if has_source_map then Js_source_map.source_loc_of_loc loc else None - in - let with_source_loc loc (exp : J.expression) = - if has_source_map then with_exp_source_loc_opt (loc_if_valid loc) exp - else exp - in - let source_map_body_loc ({pat_loc; body_loc} : Lambda.branch_loc) = - if not has_source_map then None - else - match loc_if_valid body_loc with - | Some _ as loc -> loc - | None -> loc_if_valid pat_loc - in - let source_map_case_loc ({pat_loc; body_loc} : Lambda.branch_loc) = - if not has_source_map then None - else - match loc_if_valid pat_loc with - | Some _ as loc -> loc - | None -> loc_if_valid body_loc - in - let source_map_loc_of_lam lam = - if not has_source_map then None - else - match source_loc_of_lam lam with - | Some loc -> loc_if_valid loc - | None -> None - in - let with_branch_block_source_loc (arm_loc : Lambda.branch_loc) lam block = - if not has_source_map then block - else - match block with - | [] -> [] - | stmt :: rest -> ( - let loc = - match source_map_body_loc arm_loc with - | Some _ as loc -> loc - | None -> source_map_loc_of_lam lam - in - match loc with - | None -> block - | Some _ -> - let stmt' = with_statement_source_loc loc stmt in - if stmt' == stmt then block else stmt' :: rest) - in - let branch_block arm_loc lam out = - Js_output.output_as_block out |> with_branch_block_source_loc arm_loc lam - in - let case_source_loc arm_loc lam = - if not has_source_map then None - else - match source_map_case_loc arm_loc with - | Some _ as loc -> loc - | None -> source_map_loc_of_lam lam - in - let econd_with_locs if_source_loc then_source_loc else_source_loc e out1 out2 - = - if not has_source_map then E.econd e out1 out2 - else - E.econd ?source_loc:if_source_loc e - (with_exp_source_loc_opt then_source_loc out1) - (with_exp_source_loc_opt else_source_loc out2) - in (* When compiling a read from another module, a nested source path like Other.A.B.make reaches this point as nested module-field reads: @@ -1198,7 +1197,6 @@ let compile output_prefix = let output_block cxt (lam, arm_loc) = branch_block arm_loc lam (compile_lambda cxt lam) in - let plan_case_source_loc (lam, arm_loc) = case_source_loc arm_loc lam in (* The default action is compiled once and shared by every path to it *) let fallback_blocks = ref [] in let fallback_block (cxt : Lam_compile_context.t) = @@ -1796,9 +1794,14 @@ let compile output_prefix = and compile_ifthenelse (predicate : Lambda.t) (t_branch : Lambda.t) (f_branch : Lambda.t) ({if_loc; then_loc; else_loc} : Lambda.if_locs) (lambda_cxt : Lam_compile_context.t) = - let if_source_loc = source_map_loc if_loc in - let then_source_loc = source_map_body_loc then_loc in - let else_source_loc = source_map_body_loc else_loc in + let has_source_map = Js_source_map.enabled () in + let if_source_loc = if has_source_map then loc_if_valid if_loc else None in + let then_source_loc = + if has_source_map then source_map_body_loc then_loc else None + in + let else_source_loc = + if has_source_map then source_map_body_loc else_loc else None + in match compile_lambda {lambda_cxt with continuation = NeedValue Not_tail}