From 7d9ed1bb40822c62f589f47dd7bbe232c7d57774 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 19:33:05 +0000 Subject: [PATCH 01/14] Derive a package's namespace in one place Ext_namespace, rewatch-ocaml's Config_decode and genType each had a copy of the package-name-to-namespace rule. genType's dropped `_`, unlike the build system, so it didn't recognize the namespace module of a scoped dependency like `@my_org/lib` (My_orgLib). All three now use Ext_namespace.namespace_of_package_name; a gentype ounit test covers the underscore case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- ...gentype-scoped-namespace-underscore.fix.md | 1 + compiler/core/js_packages_state.ml | 2 -- compiler/gentype/gentype_common.ml | 26 ++----------------- rewatch-ocaml/config.ml | 4 +-- rewatch-ocaml/config_decode.ml | 15 ----------- rewatch-ocaml/config_decode.mli | 1 - tests/ounit_tests/ounit_gentype_tests.ml | 8 ++++++ 7 files changed, 13 insertions(+), 44 deletions(-) create mode 100644 changes/gentype-scoped-namespace-underscore.fix.md diff --git a/changes/gentype-scoped-namespace-underscore.fix.md b/changes/gentype-scoped-namespace-underscore.fix.md new file mode 100644 index 00000000000..7dd9e769704 --- /dev/null +++ b/changes/gentype-scoped-namespace-underscore.fix.md @@ -0,0 +1 @@ +- genType now recognizes the namespace module of a scoped dependency whose name contains `_` (such as `@my_org/lib`), which it derived differently from the build system. diff --git a/compiler/core/js_packages_state.ml b/compiler/core/js_packages_state.ml index 01c849c39b1..3e6b3b7b8e1 100644 --- a/compiler/core/js_packages_state.ml +++ b/compiler/core/js_packages_state.ml @@ -47,8 +47,6 @@ let make_runtime () : unit = state.packages_info <- Js_packages_info.runtime_package_specs let set_package_map module_name = - (* set_package_name name ; - let module_name = Ext_namespace.namespace_of_package_name name in *) (Clflags.current ()).dont_record_crc_unit := Some module_name; (Clflags.current ()).open_modules := module_name :: !((Clflags.current ()).open_modules) diff --git a/compiler/gentype/gentype_common.ml b/compiler/gentype/gentype_common.ml index ff69b6c3543..6c037e159ee 100644 --- a/compiler/gentype/gentype_common.ml +++ b/compiler/gentype/gentype_common.ml @@ -115,33 +115,11 @@ type dep = | Internal of Resolved_name.t | Dot of dep * string -module Scoped_package = -(* Taken from ext_namespace.ml in bukclescript *) -struct - let namespace_of_package_name (s : string) : string = - let len = String.length s in - let buf = Buffer.create len in - let add capital ch = - Buffer.add_char buf (if capital then Char.uppercase_ascii ch else ch) - in - let rec aux capital off len = - if off >= len then () - else - let ch = String.unsafe_get s off in - match ch with - | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' -> - add capital ch; - aux false (off + 1) len - | '/' | '-' -> aux true (off + 1) len - | _ -> aux capital (off + 1) len - in - aux true 0 len; - Buffer.contents buf - +module Scoped_package = struct (** @demo/some-library -> DemoSomelibrary *) let package_name_to_generated_module_name package_name = if String.contains package_name '/' then - Some (package_name |> namespace_of_package_name) + Some (Ext_namespace.namespace_of_package_name package_name) else None let is_generated_module id ~(config : Config.t) = diff --git a/rewatch-ocaml/config.ml b/rewatch-ocaml/config.ml index 7ae9da8df74..6ec6f833598 100644 --- a/rewatch-ocaml/config.ml +++ b/rewatch-ocaml/config.ml @@ -120,7 +120,7 @@ let decode_namespace path ~name fields = namespace source fix) in let from_package_name () = - namespace_from_package_name name + Ext_namespace.namespace_of_package_name name |> module_name ~source:(Printf.sprintf "package name \"%s\"" name) ~fix:" or rename the package" @@ -140,7 +140,7 @@ let decode_namespace path ~name fields = | Some (`String value) when Option.is_some namespace_entry -> Some (from_value value (pascal_case value)) | Some (`String value) -> - Some (from_value value (namespace_from_package_name value)) + Some (from_value value (Ext_namespace.namespace_of_package_name value)) | Some _ -> fail path "field \"namespace\" must be a boolean or string" in match (namespace_entry, namespace_name) with diff --git a/rewatch-ocaml/config_decode.ml b/rewatch-ocaml/config_decode.ml index 56fdabe29cf..61a61cd1a9f 100644 --- a/rewatch-ocaml/config_decode.ml +++ b/rewatch-ocaml/config_decode.ml @@ -133,21 +133,6 @@ let strings path field = function | `List values -> List.map (string path field) values | _ -> fail path (Printf.sprintf "field %S must be an array of strings" field) -let namespace_from_package_name name = - let buffer = Buffer.create (String.length name) in - let capitalize = ref true in - String.iter - (fun character -> - match character with - | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' -> - Buffer.add_char buffer - (if !capitalize then Char.uppercase_ascii character else character); - capitalize := false - | '/' | '-' -> capitalize := true - | _ -> ()) - name; - Buffer.contents buffer - (* A string namespace combined with a namespace-entry is converted with the Pascal case of the convert_case Rust crate (0.6) that the original build system used, which rescript.json files already depend on: "my_lib" names diff --git a/rewatch-ocaml/config_decode.mli b/rewatch-ocaml/config_decode.mli index d99df917e3b..8c8f28e76f9 100644 --- a/rewatch-ocaml/config_decode.mli +++ b/rewatch-ocaml/config_decode.mli @@ -24,7 +24,6 @@ val reject_duplicates : string -> string -> (string * 'a) list -> unit val string : string -> string -> Yojson.Safe.t -> string val strings : string -> string -> Yojson.Safe.t -> string list -val namespace_from_package_name : string -> string val pascal_case : string -> string val is_upper_flat_case : string -> bool val is_module_name : string -> bool diff --git a/tests/ounit_tests/ounit_gentype_tests.ml b/tests/ounit_tests/ounit_gentype_tests.ml index eed2cb147e3..28d84dfd6f9 100644 --- a/tests/ounit_tests/ounit_gentype_tests.ml +++ b/tests/ounit_tests/ounit_gentype_tests.ml @@ -3,6 +3,14 @@ open OUnit let suites = "gentype" >::: [ + ( "name a scoped package's module as the build system does" >:: fun _ -> + let name = + Gentype_common.Scoped_package.package_name_to_generated_module_name + in + assert_equal (Some "DemoSomeLibrary") (name "@demo/some-library"); + (* the build system keeps underscores in namespace names *) + assert_equal (Some "My_orgLib") (name "@my_org/lib"); + assert_equal None (name "unscoped") ); ( "split relative module paths" >:: fun _ -> assert_equal ["."] (Module_resolver.path_to_list "."); assert_equal ["src"] (Module_resolver.path_to_list "src"); From aca40196dd9d40a9ea2585a7ab447beb505bc7e8 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:03:07 +0000 Subject: [PATCH 02/14] Print type declarations with one function print_type_declaration, used for `with type` constraints, was a copy of print_type_declaration2 that took the name and the `=`/`:=` sign as parameters and lacked the empty-record case. The copy is now the only implementation, and print_type_declaration2 computes the name and passes `=`. Output is unchanged: `with type t = {}` parses as an object type. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- compiler/syntax/src/res_printer.ml | 89 ++++-------------------------- 1 file changed, 11 insertions(+), 78 deletions(-) diff --git a/compiler/syntax/src/res_printer.ml b/compiler/syntax/src/res_printer.ml index b4fb2019364..861e8c7bd44 100644 --- a/compiler/syntax/src/res_printer.ml +++ b/compiler/syntax/src/res_printer.ml @@ -1451,84 +1451,8 @@ and print_type_declarations ~state ~rec_flag type_declarations cmt_tbl = * (* Invariant: non-empty list *) * | Ptype_open *) -and print_type_declaration ~state ~name ~equal_sign ~rec_flag i - (td : Parsetree.type_declaration) cmt_tbl = - let attrs = - print_attributes ~state ~loc:td.ptype_loc td.ptype_attributes cmt_tbl - in - let prefix = - if i > 0 then Doc.text "and " else Doc.concat [Doc.text "type "; rec_flag] - in - let type_name = name in - let type_params = print_type_params ~state td.ptype_params cmt_tbl in - let manifest_and_kind = - match td.ptype_kind with - | Ptype_abstract -> ( - match td.ptype_manifest with - | None -> Doc.nil - | Some typ -> - Doc.concat - [ - Doc.concat [Doc.space; Doc.text equal_sign; Doc.space]; - print_private_flag td.ptype_private; - print_typ_expr ~state typ cmt_tbl; - ]) - | Ptype_open -> - Doc.concat - [ - Doc.concat [Doc.space; Doc.text equal_sign; Doc.space]; - print_private_flag td.ptype_private; - Doc.text ".."; - ] - | Ptype_record lds -> - let manifest = - match td.ptype_manifest with - | None -> Doc.nil - | Some typ -> - Doc.concat - [ - Doc.concat [Doc.space; Doc.text equal_sign; Doc.space]; - print_typ_expr ~state typ cmt_tbl; - ] - in - Doc.concat - [ - manifest; - Doc.concat [Doc.space; Doc.text equal_sign; Doc.space]; - print_private_flag td.ptype_private; - print_record_declaration ~record_loc:td.ptype_loc ~state lds cmt_tbl; - ] - | Ptype_variant cds -> - let manifest = - match td.ptype_manifest with - | None -> Doc.nil - | Some typ -> - Doc.concat - [ - Doc.concat [Doc.space; Doc.text equal_sign; Doc.space]; - print_typ_expr ~state typ cmt_tbl; - ] - in - Doc.concat - [ - manifest; - Doc.concat [Doc.space; Doc.text equal_sign]; - print_constructor_declarations ~state ~private_flag:td.ptype_private - cds cmt_tbl; - ] - in - let constraints = print_type_definition_constraints ~state td.ptype_cstrs in - Doc.group - (Doc.concat - [attrs; prefix; type_name; type_params; manifest_and_kind; constraints]) - -and print_type_declaration2 ?inline_record_definitions ~state ~rec_flag - (td : Parsetree.type_declaration) cmt_tbl i = - let name = - let doc = print_ident_like td.Parsetree.ptype_name.txt in - print_comments doc cmt_tbl td.ptype_name.loc - in - let equal_sign = "=" in +and print_type_declaration ?inline_record_definitions ~state ~name ~equal_sign + ~rec_flag i (td : Parsetree.type_declaration) cmt_tbl = let attrs = print_attributes ~state ~loc:td.ptype_loc td.ptype_attributes cmt_tbl in @@ -1611,6 +1535,15 @@ and print_type_declaration2 ?inline_record_definitions ~state ~rec_flag (Doc.concat [attrs; prefix; type_name; type_params; manifest_and_kind; constraints]) +and print_type_declaration2 ?inline_record_definitions ~state ~rec_flag + (td : Parsetree.type_declaration) cmt_tbl i = + let name = + let doc = print_ident_like td.Parsetree.ptype_name.txt in + print_comments doc cmt_tbl td.ptype_name.loc + in + print_type_declaration ?inline_record_definitions ~state ~name ~equal_sign:"=" + ~rec_flag i td cmt_tbl + and print_type_definition_constraints ~state cstrs = match cstrs with | [] -> Doc.nil From 12a61fe8010267e61f211ed0890162412bbd7e20 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:03:49 +0000 Subject: [PATCH 03/14] Instantiate types in analysis with one type walker instantiate_type and instantiate_type2 were 55-line copies of the same type walker that differed only in how a variable is substituted (by identity or by name). Both now use map_type_vars with their own substitution. The by-name one returned the whole type being instantiated for a variable that isn't a parameter; it now keeps the variable. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- analysis/src/type_utils.ml | 169 ++++++++++++++----------------------- 1 file changed, 64 insertions(+), 105 deletions(-) diff --git a/analysis/src/type_utils.ml b/analysis/src/type_utils.ml index 6e66d82c72d..ee88af8c3b9 100644 --- a/analysis/src/type_utils.ml +++ b/analysis/src/type_utils.ml @@ -130,124 +130,83 @@ let get_extracted_type maybe_res = | None -> None | Some (extracted_type, _) -> Some extracted_type +(* Rebuild [t] with each type variable [v] replaced by [sub v]. *) +let map_type_vars ~sub (t : Types.type_expr) = + let rec loop (t : Types.type_expr) = + match t.desc with + | Tlink t -> loop t + | Tvar _ -> sub t + | Tunivar _ -> t + | Tconstr (path, args, memo) -> + {t with desc = Tconstr (path, args |> List.map loop, memo)} + | Tsubst t -> loop t + | Tvariant rd -> {t with desc = Tvariant (row_desc rd)} + | Tnil -> t + | Tarrow (params, ret) -> + { + t with + desc = + Tarrow + ( List.map + (fun (arg : Types.arg) -> {arg with typ = loop arg.typ}) + params, + loop ret ); + } + | Ttuple tl -> {t with desc = Ttuple (tl |> List.map loop)} + | Tobject t -> {t with desc = Tobject (loop t)} + | Tfield f -> + {t with desc = Tfield {f with typ = loop f.typ; rest = loop f.rest}} + | Tpoly (t, []) -> loop t + | Tpoly (t, tl) -> {t with desc = Tpoly (loop t, tl |> List.map loop)} + | Tpackage (p, l, tl) -> + {t with desc = Tpackage (p, l, tl |> List.map loop)} + and row_desc (rd : Types.row_desc) = + let row_fields = + rd.row_fields |> List.map (fun (l, rf) -> (l, row_field rf)) + in + let row_more = loop rd.row_more in + let row_name = + match rd.row_name with + | None -> None + | Some (p, tl) -> Some (p, tl |> List.map loop) + in + {rd with row_fields; row_more; row_name} + and row_field (rf : Types.row_field) = + match rf with + | Rpresent None -> rf + | Rpresent (Some t) -> Rpresent (Some (loop t)) + | Reither (b1, tl, b2, r) -> Reither (b1, tl |> List.map loop, b2, r) + | Rabsent -> Rabsent + in + loop t + let instantiate_type ~type_params ~type_args (t : Types.type_expr) = if type_params = [] || type_args = [] then t else - let rec apply_sub tp ta t = + let rec apply_sub tp ta v = match (tp, ta) with | t1 :: t_rest1, t2 :: t_rest2 -> - if t1 = t then t2 else apply_sub t_rest1 t_rest2 t - | [], _ | _, [] -> t - in - let rec loop (t : Types.type_expr) = - match t.desc with - | Tlink t -> loop t - | Tvar _ -> apply_sub type_params type_args t - | Tunivar _ -> t - | Tconstr (path, args, memo) -> - {t with desc = Tconstr (path, args |> List.map loop, memo)} - | Tsubst t -> loop t - | Tvariant rd -> {t with desc = Tvariant (row_desc rd)} - | Tnil -> t - | Tarrow (params, ret) -> - { - t with - desc = - Tarrow - ( List.map - (fun (arg : Types.arg) -> {arg with typ = loop arg.typ}) - params, - loop ret ); - } - | Ttuple tl -> {t with desc = Ttuple (tl |> List.map loop)} - | Tobject t -> {t with desc = Tobject (loop t)} - | Tfield f -> - {t with desc = Tfield {f with typ = loop f.typ; rest = loop f.rest}} - | Tpoly (t, []) -> loop t - | Tpoly (t, tl) -> {t with desc = Tpoly (loop t, tl |> List.map loop)} - | Tpackage (p, l, tl) -> - {t with desc = Tpackage (p, l, tl |> List.map loop)} - and row_desc (rd : Types.row_desc) = - let row_fields = - rd.row_fields |> List.map (fun (l, rf) -> (l, row_field rf)) - in - let row_more = loop rd.row_more in - let row_name = - match rd.row_name with - | None -> None - | Some (p, tl) -> Some (p, tl |> List.map loop) - in - {rd with row_fields; row_more; row_name} - and row_field (rf : Types.row_field) = - match rf with - | Rpresent None -> rf - | Rpresent (Some t) -> Rpresent (Some (loop t)) - | Reither (b1, tl, b2, r) -> Reither (b1, tl |> List.map loop, b2, r) - | Rabsent -> Rabsent + if t1 = v then t2 else apply_sub t_rest1 t_rest2 v + | [], _ | _, [] -> v in - loop t + map_type_vars ~sub:(apply_sub type_params type_args) t +(* Like [instantiate_type], but matches type variables by name. *) let instantiate_type2 ?(type_arg_context : type_arg_context option) (t : Types.type_expr) = match type_arg_context with | None | Some {type_args = []} | Some {type_params = []} -> t | Some {type_args; type_params} -> - let rec apply_sub tp ta name = - match (tp, ta) with - | {Types.desc = Tvar (Some var_name)} :: t_rest1, t2 :: t_rest2 -> - if var_name = name then t2 else apply_sub t_rest1 t_rest2 name - | _ :: t_rest1, _ :: t_rest2 -> apply_sub t_rest1 t_rest2 name - | [], _ | _, [] -> t - in - - let rec loop (t : Types.type_expr) = - match t.desc with - | Tlink t -> loop t - | Tvar (Some name) -> apply_sub type_params type_args name - | Tvar _ -> t - | Tunivar _ -> t - | Tconstr (path, args, memo) -> - {t with desc = Tconstr (path, args |> List.map loop, memo)} - | Tsubst t -> loop t - | Tvariant rd -> {t with desc = Tvariant (row_desc rd)} - | Tnil -> t - | Tarrow (params, ret) -> - { - t with - desc = - Tarrow - ( List.map - (fun (arg : Types.arg) -> {arg with typ = loop arg.typ}) - params, - loop ret ); - } - | Ttuple tl -> {t with desc = Ttuple (tl |> List.map loop)} - | Tobject t -> {t with desc = Tobject (loop t)} - | Tfield f -> - {t with desc = Tfield {f with typ = loop f.typ; rest = loop f.rest}} - | Tpoly (t, []) -> loop t - | Tpoly (t, tl) -> {t with desc = Tpoly (loop t, tl |> List.map loop)} - | Tpackage (p, l, tl) -> - {t with desc = Tpackage (p, l, tl |> List.map loop)} - and row_desc (rd : Types.row_desc) = - let row_fields = - rd.row_fields |> List.map (fun (l, rf) -> (l, row_field rf)) - in - let row_more = loop rd.row_more in - let row_name = - match rd.row_name with - | None -> None - | Some (p, tl) -> Some (p, tl |> List.map loop) - in - {rd with row_fields; row_more; row_name} - and row_field (rf : Types.row_field) = - match rf with - | Rpresent None -> rf - | Rpresent (Some t) -> Rpresent (Some (loop t)) - | Reither (b1, tl, b2, r) -> Reither (b1, tl |> List.map loop, b2, r) - | Rabsent -> Rabsent + let rec apply_sub tp ta (v : Types.type_expr) = + match (v.desc, tp, ta) with + | ( Tvar (Some name), + {Types.desc = Tvar (Some param)} :: t_rest1, + t2 :: t_rest2 ) -> + if param = name then t2 else apply_sub t_rest1 t_rest2 v + | Tvar (Some _), _ :: t_rest1, _ :: t_rest2 -> apply_sub t_rest1 t_rest2 v + | _ -> v in - loop t + map_type_vars ~sub:(apply_sub type_params type_args) t let rec extract_record_type ~state ~env ~package (t : Types.type_expr) = match t.desc with From 7af08bd09c47cd6e03ee86c88f61a630849b8060 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:05:00 +0000 Subject: [PATCH 04/14] Attach comments around a node with one helper The comments table spelled out "attach the comments before a node, walk it with those inside, attach those after" 50 times; walk_around now does it. walk_mod_expr_parameter and walk_mod_type_parameter were identical and are now walk_functor_parameter. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- compiler/syntax/src/res_comments_table.ml | 330 +++++----------------- 1 file changed, 65 insertions(+), 265 deletions(-) diff --git a/compiler/syntax/src/res_comments_table.ml b/compiler/syntax/src/res_comments_table.ml index 7c61b2652ac..82bcb520ad2 100644 --- a/compiler/syntax/src/res_comments_table.ml +++ b/compiler/syntax/src/res_comments_table.ml @@ -456,6 +456,14 @@ let get_loc node = | ValueBinding vb -> vb.pvb_loc | JsxProp prop -> Parsetree_viewer.get_jsx_prop_loc prop +(* Attach the comments before and after [loc] to it, and walk [node], which + spans [loc], with the comments inside. *) +let walk_around ~loc walk node t comments = + let before, inside, after = partition_by_loc comments loc in + attach t.leading loc before; + walk node t inside; + attach t.trailing loc after + let rec walk_structure s t comments = match s with | _ when comments = [] -> () @@ -502,10 +510,7 @@ and walk_value_description vd t comments = partition_adjacent_trailing vd.pval_name.loc trailing in attach t.trailing vd.pval_name.loc after_name; - let before, inside, after = partition_by_loc rest vd.pval_type.ptyp_loc in - attach t.leading vd.pval_type.ptyp_loc before; - walk_core_type vd.pval_type t inside; - attach t.trailing vd.pval_type.ptyp_loc after + walk_around ~loc:vd.pval_type.ptyp_loc walk_core_type vd.pval_type t rest and walk_type_extension te t comments = let leading, trailing = @@ -531,12 +536,8 @@ and walk_type_extension te t comments = t rest and walk_include_declaration incl_decl t comments = - let before, inside, after = - partition_by_loc comments incl_decl.pincl_mod.pmod_loc - in - attach t.leading incl_decl.pincl_mod.pmod_loc before; - walk_module_expr incl_decl.pincl_mod t inside; - attach t.trailing incl_decl.pincl_mod.pmod_loc after + walk_around ~loc:incl_decl.pincl_mod.pmod_loc walk_module_expr + incl_decl.pincl_mod t comments and walk_module_type_declaration mtd t comments = let leading, trailing = @@ -550,10 +551,7 @@ and walk_module_type_declaration mtd t comments = partition_adjacent_trailing mtd.pmtd_name.loc trailing in attach t.trailing mtd.pmtd_name.loc after_name; - let before, inside, after = partition_by_loc rest mod_type.pmty_loc in - attach t.leading mod_type.pmty_loc before; - walk_mod_type mod_type t inside; - attach t.trailing mod_type.pmty_loc after + walk_around ~loc:mod_type.pmty_loc walk_mod_type mod_type t rest and walk_module_binding mb t comments = let leading, trailing = partition_leading_trailing comments mb.pmb_name.loc in @@ -602,20 +600,14 @@ and walk_signature_item (si : Parsetree.signature_item) t comments = | Psig_extension (extension, _) -> walk_extension extension t comments and walk_include_description id t comments = - let before, inside, after = partition_by_loc comments id.pincl_mod.pmty_loc in - attach t.leading id.pincl_mod.pmty_loc before; - walk_mod_type id.pincl_mod t inside; - attach t.trailing id.pincl_mod.pmty_loc after + walk_around ~loc:id.pincl_mod.pmty_loc walk_mod_type id.pincl_mod t comments and walk_module_declaration md t comments = let leading, trailing = partition_leading_trailing comments md.pmd_name.loc in attach t.leading md.pmd_name.loc leading; let after_name, rest = partition_adjacent_trailing md.pmd_name.loc trailing in attach t.trailing md.pmd_name.loc after_name; - let leading, inside, trailing = partition_by_loc rest md.pmd_type.pmty_loc in - attach t.leading md.pmd_type.pmty_loc leading; - walk_mod_type md.pmd_type t inside; - attach t.trailing md.pmd_type.pmty_loc trailing + walk_around ~loc:md.pmd_type.pmty_loc walk_mod_type md.pmd_type t rest and walk_node node tbl comments = match node with @@ -843,12 +835,7 @@ and walk_label_declaration ld t comments = attach t.leading ld.pld_name.loc before_name; let after_name, rest = partition_adjacent_trailing ld.pld_name.loc rest in attach t.trailing ld.pld_name.loc after_name; - let before_typ, inside_typ, after_typ = - partition_by_loc rest ld.pld_type.ptyp_loc - in - attach t.leading ld.pld_type.ptyp_loc before_typ; - walk_core_type ld.pld_type t inside_typ; - attach t.trailing ld.pld_type.ptyp_loc after_typ + walk_around ~loc:ld.pld_type.ptyp_loc walk_core_type ld.pld_type t rest and walk_constructor_declarations cds t comments = visit_list_but_continue_with_remaining_comments @@ -1023,10 +1010,7 @@ and walk_expression expr t comments = | Pexp_braces {expr = inner} when is_block_expr inner -> walk_expression inner t comments | Pexp_braces {expr = inner} -> - let before, inside, after = partition_by_loc comments inner.pexp_loc in - attach t.leading inner.pexp_loc before; - walk_expression inner t inside; - attach t.trailing inner.pexp_loc after + walk_around ~loc:inner.pexp_loc walk_expression inner t comments | Pexp_regexp _ | Pexp_constant _ -> let leading, trailing = partition_leading_trailing comments expr.pexp_loc in attach t.leading expr.pexp_loc leading; @@ -1051,13 +1035,7 @@ and walk_expression expr t comments = comments in if is_block_expr expr2 then walk_expression expr2 t comments - else - let leading, inside, trailing = - partition_by_loc comments expr2.pexp_loc - in - attach t.leading expr2.pexp_loc leading; - walk_expression expr2 t inside; - attach t.trailing expr2.pexp_loc trailing + else walk_around ~loc:expr2.pexp_loc walk_expression expr2 t comments | Pexp_sequence (expr1, expr2) -> let leading, inside, trailing = partition_by_loc comments expr1.pexp_loc in let comments = @@ -1077,13 +1055,7 @@ and walk_expression expr t comments = comments) in if is_block_expr expr2 then walk_expression expr2 t comments - else - let leading, inside, trailing = - partition_by_loc comments expr2.pexp_loc - in - attach t.leading expr2.pexp_loc leading; - walk_expression expr2 t inside; - attach t.trailing expr2.pexp_loc trailing + else walk_around ~loc:expr2.pexp_loc walk_expression expr2 t comments | Pexp_open (_override, longident, expr2) -> let leading, comments = partition_leading_trailing comments expr.pexp_loc in attach t.leading @@ -1096,11 +1068,7 @@ and walk_expression expr t comments = in attach t.trailing longident.loc after_longident; if is_block_expr expr2 then walk_expression expr2 t rest - else - let leading, inside, trailing = partition_by_loc rest expr2.pexp_loc in - attach t.leading expr2.pexp_loc leading; - walk_expression expr2 t inside; - attach t.trailing expr2.pexp_loc trailing + else walk_around ~loc:expr2.pexp_loc walk_expression expr2 t rest | Pexp_object_literal fields -> walk_list (Ext_list.map fields (fun ((s : string Asttypes.loc), e) -> @@ -1130,11 +1098,7 @@ and walk_expression expr t comments = in attach t.trailing extension_constructor.pext_loc after_ext_constr; if is_block_expr expr2 then walk_expression expr2 t rest - else - let leading, inside, trailing = partition_by_loc rest expr2.pexp_loc in - attach t.leading expr2.pexp_loc leading; - walk_expression expr2 t inside; - attach t.trailing expr2.pexp_loc trailing + else walk_around ~loc:expr2.pexp_loc walk_expression expr2 t rest | Pexp_letmodule (string_loc, mod_expr, expr2) -> let leading, comments = partition_leading_trailing comments expr.pexp_loc in attach t.leading @@ -1158,38 +1122,24 @@ and walk_expression expr t comments = in attach t.trailing mod_expr.pmod_loc after_mod_expr; if is_block_expr expr2 then walk_expression expr2 t rest - else - let leading, inside, trailing = partition_by_loc rest expr2.pexp_loc in - attach t.leading expr2.pexp_loc leading; - walk_expression expr2 t inside; - attach t.trailing expr2.pexp_loc trailing + else walk_around ~loc:expr2.pexp_loc walk_expression expr2 t rest | Pexp_assert expr -> if is_block_expr expr then walk_expression expr t comments - else - let leading, inside, trailing = partition_by_loc comments expr.pexp_loc in - attach t.leading expr.pexp_loc leading; - walk_expression expr t inside; - attach t.trailing expr.pexp_loc trailing + else walk_around ~loc:expr.pexp_loc walk_expression expr t comments | Pexp_coerce (expr, typexpr) -> let leading, inside, trailing = partition_by_loc comments expr.pexp_loc in attach t.leading expr.pexp_loc leading; walk_expression expr t inside; let after_expr, rest = partition_adjacent_trailing expr.pexp_loc trailing in attach t.trailing expr.pexp_loc after_expr; - let leading, inside, trailing = partition_by_loc rest typexpr.ptyp_loc in - attach t.leading typexpr.ptyp_loc leading; - walk_core_type typexpr t inside; - attach t.trailing typexpr.ptyp_loc trailing + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t rest | Pexp_constraint (expr, typexpr) -> let leading, inside, trailing = partition_by_loc comments expr.pexp_loc in attach t.leading expr.pexp_loc leading; walk_expression expr t inside; let after_expr, rest = partition_adjacent_trailing expr.pexp_loc trailing in attach t.trailing expr.pexp_loc after_expr; - let leading, inside, trailing = partition_by_loc rest typexpr.ptyp_loc in - attach t.leading typexpr.ptyp_loc leading; - walk_core_type typexpr t inside; - attach t.trailing typexpr.ptyp_loc trailing + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t rest | Pexp_tuple [] | Pexp_array [] | Pexp_break | Pexp_continue @@ -1281,11 +1231,7 @@ and walk_expression expr t comments = in attach t.trailing longident.loc after_longident; if is_block_expr expr2 then walk_expression expr2 t rest - else - let leading, inside, trailing = partition_by_loc rest expr2.pexp_loc in - attach t.leading expr2.pexp_loc leading; - walk_expression expr2 t inside; - attach t.trailing expr2.pexp_loc trailing + else walk_around ~loc:expr2.pexp_loc walk_expression expr2 t rest | (Pexp_ifthenelse _ | Pexp_ternary _) as conditional -> ( let if_expr, then_expr, else_expr = match conditional with @@ -1338,13 +1284,7 @@ and walk_expression expr t comments = | Some expr -> if is_block_expr expr || is_conditional_expr expr then walk_expression expr t comments - else - let leading, inside, trailing = - partition_by_loc comments expr.pexp_loc - in - attach t.leading expr.pexp_loc leading; - walk_expression expr t inside; - attach t.trailing expr.pexp_loc trailing) + else walk_around ~loc:expr.pexp_loc walk_expression expr t comments) | Pexp_while (expr1, expr2) -> let leading, inside, trailing = partition_by_loc comments expr1.pexp_loc in let rest = @@ -1364,11 +1304,7 @@ and walk_expression expr t comments = rest) in if is_block_expr expr2 then walk_expression expr2 t rest - else - let leading, inside, trailing = partition_by_loc rest expr2.pexp_loc in - attach t.leading expr2.pexp_loc leading; - walk_expression expr2 t inside; - attach t.trailing expr2.pexp_loc trailing + else walk_around ~loc:expr2.pexp_loc walk_expression expr2 t rest | Pexp_for (pat, expr1, expr2, _, expr3) -> let leading, inside, trailing = partition_by_loc comments pat.ppat_loc in attach t.leading pat.ppat_loc leading; @@ -1390,16 +1326,9 @@ and walk_expression expr t comments = in attach t.trailing expr2.pexp_loc after_expr; if is_block_expr expr3 then walk_expression expr3 t rest - else - let leading, inside, trailing = partition_by_loc rest expr3.pexp_loc in - attach t.leading expr3.pexp_loc leading; - walk_expression expr3 t inside; - attach t.trailing expr3.pexp_loc trailing + else walk_around ~loc:expr3.pexp_loc walk_expression expr3 t rest | Pexp_pack mod_expr -> - let before, inside, after = partition_by_loc comments mod_expr.pmod_loc in - attach t.leading mod_expr.pmod_loc before; - walk_module_expr mod_expr t inside; - attach t.trailing mod_expr.pmod_loc after + walk_around ~loc:mod_expr.pmod_loc walk_module_expr mod_expr t comments | Pexp_match (expr, cases) | Pexp_try (expr, cases, None) -> let rest = walk_switch_or_try_head expr t comments in walk_list (cases |> List.map (fun case -> Case case)) t rest @@ -1475,10 +1404,7 @@ and walk_expression expr t comments = }; args = [(Nolabel, arg_expr)]; } -> - let before, inside, after = partition_by_loc comments arg_expr.pexp_loc in - attach t.leading arg_expr.pexp_loc before; - walk_expression arg_expr t inside; - attach t.trailing arg_expr.pexp_loc after + walk_around ~loc:arg_expr.pexp_loc walk_expression arg_expr t comments (* binary expression *) | Pexp_apply { @@ -1573,22 +1499,12 @@ and walk_expression expr t comments = in attach t.trailing typ.ptyp_loc after_typ; if is_block_expr expr then walk_expression expr t comments - else - let leading, inside, trailing = - partition_by_loc comments expr.pexp_loc - in - attach t.leading expr.pexp_loc leading; - walk_expression expr t inside; - attach t.trailing expr.pexp_loc trailing + else walk_around ~loc:expr.pexp_loc walk_expression expr t comments | _ -> if is_block_expr return_expr then walk_expression return_expr t comments else - let leading, inside, trailing = - partition_by_loc comments return_expr.pexp_loc - in - attach t.leading return_expr.pexp_loc leading; - walk_expression return_expr t inside; - attach t.trailing return_expr.pexp_loc trailing) + walk_around ~loc:return_expr.pexp_loc walk_expression return_expr t + comments) | Pexp_jsx_element (Jsx_fragment { @@ -1728,11 +1644,7 @@ and walk_expression expr t comments = in attach t.trailing expr1.pexp_loc after_expr; if is_block_expr expr2 then walk_expression expr2 t rest - else - let leading, inside, trailing = partition_by_loc rest expr2.pexp_loc in - attach t.leading expr2.pexp_loc leading; - walk_expression expr2 t inside; - attach t.trailing expr2.pexp_loc trailing + else walk_around ~loc:expr2.pexp_loc walk_expression expr2 t rest | Pexp_object_get (e1, _) -> walk_expression e1 t comments | Pexp_object_set (e1, _, e2) -> let leading, inside, trailing = partition_by_loc comments e1.pexp_loc in @@ -1740,10 +1652,7 @@ and walk_expression expr t comments = walk_expression e1 t inside; let after_lhs, rest = partition_adjacent_trailing e1.pexp_loc trailing in attach t.trailing e1.pexp_loc after_lhs; - let before, inside, after = partition_by_loc rest e2.pexp_loc in - attach t.leading e2.pexp_loc before; - walk_expression e2 t inside; - attach t.trailing e2.pexp_loc after + walk_around ~loc:e2.pexp_loc walk_expression e2 t rest and walk_expr_parameter (_attrs, _argLbl, expr_opt, pattern) t comments = let leading, inside, trailing = partition_by_loc comments pattern.ppat_loc in @@ -1756,11 +1665,7 @@ and walk_expr_parameter (_attrs, _argLbl, expr_opt, pattern) t comments = in attach t.trailing pattern.ppat_loc after_pat; if is_block_expr expr then walk_expression expr t rest - else - let leading, inside, trailing = partition_by_loc rest expr.pexp_loc in - attach t.leading expr.pexp_loc leading; - walk_expression expr t inside; - attach t.trailing expr.pexp_loc trailing + else walk_around ~loc:expr.pexp_loc walk_expression expr t rest | None -> attach t.trailing pattern.ppat_loc trailing and walk_expr_argument expr loc t comments = @@ -1768,10 +1673,7 @@ and walk_expr_argument expr loc t comments = attach t.leading loc leading; let after_label, rest = partition_adjacent_trailing loc trailing in attach t.trailing loc after_label; - let before, inside, after = partition_by_loc rest expr.pexp_loc in - attach t.leading expr.pexp_loc before; - walk_expression expr t inside; - attach t.trailing expr.pexp_loc after + walk_around ~loc:expr.pexp_loc walk_expression expr t rest and walk_case (case : Parsetree.case) t comments = let before, inside, after = partition_by_loc comments case.pc_lhs.ppat_loc in @@ -1798,12 +1700,7 @@ and walk_case (case : Parsetree.case) t comments = in if is_block_expr case.pc_rhs then walk_expression case.pc_rhs t comments else - let before, inside, after = - partition_by_loc comments case.pc_rhs.pexp_loc - in - attach t.leading case.pc_rhs.pexp_loc before; - walk_expression case.pc_rhs t inside; - attach t.trailing case.pc_rhs.pexp_loc after + walk_around ~loc:case.pc_rhs.pexp_loc walk_expression case.pc_rhs t comments and walk_expr_record_row (longident, expr) t comments = let before_longident, after_longident = @@ -1814,10 +1711,7 @@ and walk_expr_record_row (longident, expr) t comments = partition_adjacent_trailing longident.loc after_longident in attach t.trailing longident.loc after_longident; - let leading, inside, trailing = partition_by_loc rest expr.pexp_loc in - attach t.leading expr.pexp_loc leading; - walk_expression expr t inside; - attach t.trailing expr.pexp_loc trailing + walk_around ~loc:expr.pexp_loc walk_expression expr t rest and walk_extension_constructor ext_constr t comments = let leading, trailing = @@ -1841,10 +1735,7 @@ and walk_extension_constructor_kind kind t comments = match maybe_typ_expr with | None -> () | Some typexpr -> - let before, inside, after = partition_by_loc rest typexpr.ptyp_loc in - attach t.leading typexpr.ptyp_loc before; - walk_core_type typexpr t inside; - attach t.trailing typexpr.ptyp_loc after) + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t rest) and walk_module_expr mod_expr t comments = match mod_expr.pmod_desc with @@ -1857,10 +1748,7 @@ and walk_module_expr mod_expr t comments = | Pmod_extension extension -> walk_extension extension t comments | Pmod_await mod_expr -> walk_module_expr mod_expr t comments | Pmod_unpack expr -> - let before, inside, after = partition_by_loc comments expr.pexp_loc in - attach t.leading expr.pexp_loc before; - walk_expression expr t inside; - attach t.trailing expr.pexp_loc after + walk_around ~loc:expr.pexp_loc walk_expression expr t comments | Pmod_constraint (modexpr, modtype) -> if modtype.pmty_loc.loc_start >= modexpr.pmod_loc.loc_end then ( let before, inside, after = partition_by_loc comments modexpr.pmod_loc in @@ -1868,20 +1756,14 @@ and walk_module_expr mod_expr t comments = walk_module_expr modexpr t inside; let after, rest = partition_adjacent_trailing modexpr.pmod_loc after in attach t.trailing modexpr.pmod_loc after; - let before, inside, after = partition_by_loc rest modtype.pmty_loc in - attach t.leading modtype.pmty_loc before; - walk_mod_type modtype t inside; - attach t.trailing modtype.pmty_loc after) + walk_around ~loc:modtype.pmty_loc walk_mod_type modtype t rest) else let before, inside, after = partition_by_loc comments modtype.pmty_loc in attach t.leading modtype.pmty_loc before; walk_mod_type modtype t inside; let after, rest = partition_adjacent_trailing modtype.pmty_loc after in attach t.trailing modtype.pmty_loc after; - let before, inside, after = partition_by_loc rest modexpr.pmod_loc in - attach t.leading modexpr.pmod_loc before; - walk_module_expr modexpr t inside; - attach t.trailing modexpr.pmod_loc after + walk_around ~loc:modexpr.pmod_loc walk_module_expr modexpr t rest | Pmod_apply (_callModExpr, _argModExpr) -> let mod_exprs = mod_expr_apply mod_expr in walk_list (mod_exprs |> List.map (fun me -> ModuleExpr me)) t comments @@ -1894,7 +1776,7 @@ and walk_module_expr mod_expr t comments = | None -> lbl.Asttypes.loc | Some mod_type -> {lbl.loc with loc_end = mod_type.Parsetree.pmty_loc.loc_end}) - ~walk_node:walk_mod_expr_parameter ~newline_delimited:false parameters t + ~walk_node:walk_functor_parameter ~newline_delimited:false parameters t comments in match return_mod_expr.pmod_desc with @@ -1906,19 +1788,12 @@ and walk_module_expr mod_expr t comments = walk_mod_type mod_type t inside; let after, rest = partition_adjacent_trailing mod_type.pmty_loc after in attach t.trailing mod_type.pmty_loc after; - let before, inside, after = partition_by_loc rest mod_expr.pmod_loc in - attach t.leading mod_expr.pmod_loc before; - walk_module_expr mod_expr t inside; - attach t.trailing mod_expr.pmod_loc after + walk_around ~loc:mod_expr.pmod_loc walk_module_expr mod_expr t rest | _ -> - let before, inside, after = - partition_by_loc comments return_mod_expr.pmod_loc - in - attach t.leading return_mod_expr.pmod_loc before; - walk_module_expr return_mod_expr t inside; - attach t.trailing return_mod_expr.pmod_loc after) + walk_around ~loc:return_mod_expr.pmod_loc walk_module_expr return_mod_expr + t comments) -and walk_mod_expr_parameter parameter t comments = +and walk_functor_parameter parameter t comments = let _attrs, lbl, mod_type_option = parameter in let leading, trailing = partition_leading_trailing comments lbl.loc in attach t.leading lbl.loc leading; @@ -1927,10 +1802,7 @@ and walk_mod_expr_parameter parameter t comments = | Some mod_type -> let after_lbl, rest = partition_adjacent_trailing lbl.loc trailing in attach t.trailing lbl.loc after_lbl; - let before, inside, after = partition_by_loc rest mod_type.pmty_loc in - attach t.leading mod_type.pmty_loc before; - walk_mod_type mod_type t inside; - attach t.trailing mod_type.pmty_loc after + walk_around ~loc:mod_type.pmty_loc walk_mod_type mod_type t rest and walk_mod_type mod_type t comments = match mod_type.pmty_desc with @@ -1942,15 +1814,9 @@ and walk_mod_type mod_type t comments = | Pmty_signature signature -> walk_signature signature t comments | Pmty_extension extension -> walk_extension extension t comments | Pmty_typeof mod_expr -> - let before, inside, after = partition_by_loc comments mod_expr.pmod_loc in - attach t.leading mod_expr.pmod_loc before; - walk_module_expr mod_expr t inside; - attach t.trailing mod_expr.pmod_loc after + walk_around ~loc:mod_expr.pmod_loc walk_module_expr mod_expr t comments | Pmty_with (mod_type, _withConstraints) -> - let before, inside, after = partition_by_loc comments mod_type.pmty_loc in - attach t.leading mod_type.pmty_loc before; - walk_mod_type mod_type t inside; - attach t.trailing mod_type.pmty_loc after + walk_around ~loc:mod_type.pmty_loc walk_mod_type mod_type t comments (* TODO: withConstraints*) | Pmty_functor _ -> let parameters, return_mod_type = functor_type mod_type in @@ -1962,28 +1828,11 @@ and walk_mod_type mod_type t comments = | Some mod_type -> if lbl.txt = "_" then mod_type.Parsetree.pmty_loc else {lbl.loc with loc_end = mod_type.Parsetree.pmty_loc.loc_end}) - ~walk_node:walk_mod_type_parameter ~newline_delimited:false parameters t + ~walk_node:walk_functor_parameter ~newline_delimited:false parameters t comments in - let before, inside, after = - partition_by_loc comments return_mod_type.pmty_loc - in - attach t.leading return_mod_type.pmty_loc before; - walk_mod_type return_mod_type t inside; - attach t.trailing return_mod_type.pmty_loc after - -and walk_mod_type_parameter (_, lbl, mod_type_option) t comments = - let leading, trailing = partition_leading_trailing comments lbl.loc in - attach t.leading lbl.loc leading; - match mod_type_option with - | None -> attach t.trailing lbl.loc trailing - | Some mod_type -> - let after_lbl, rest = partition_adjacent_trailing lbl.loc trailing in - attach t.trailing lbl.loc after_lbl; - let before, inside, after = partition_by_loc rest mod_type.pmty_loc in - attach t.leading mod_type.pmty_loc before; - walk_mod_type mod_type t inside; - attach t.trailing mod_type.pmty_loc after + walk_around ~loc:return_mod_type.pmty_loc walk_mod_type return_mod_type t + comments and walk_pattern pat t comments = let open Location in @@ -2025,10 +1874,7 @@ and walk_pattern pat t comments = partition_adjacent_trailing constr.loc trailing in attach t.trailing constr.loc after_constructor; - let leading, inside, trailing = partition_by_loc rest pat.ppat_loc in - attach t.leading pat.ppat_loc leading; - walk_pattern pat t inside; - attach t.trailing pat.ppat_loc trailing + walk_around ~loc:pat.ppat_loc walk_pattern pat t rest | Ppat_construct (constr, {txt = pats}) -> let leading, trailing = partition_leading_trailing comments constr.loc in attach t.leading constr.loc leading; @@ -2071,19 +1917,9 @@ and walk_pattern pat t comments = partition_adjacent_trailing pattern.ppat_loc after_pattern in attach t.trailing pattern.ppat_loc after_pattern; - let before_typ, inside_typ, after_typ = - partition_by_loc rest typ.ptyp_loc - in - attach t.leading typ.ptyp_loc before_typ; - walk_core_type typ t inside_typ; - attach t.trailing typ.ptyp_loc after_typ + walk_around ~loc:typ.ptyp_loc walk_core_type typ t rest | Ppat_exception pattern -> - let leading, inside, trailing = - partition_by_loc comments pattern.ppat_loc - in - attach t.leading pattern.ppat_loc leading; - walk_pattern pattern t inside; - attach t.trailing pattern.ppat_loc trailing + walk_around ~loc:pattern.ppat_loc walk_pattern pattern t comments | Ppat_unpack string_loc -> let leading, trailing = partition_leading_trailing comments string_loc.loc @@ -2131,10 +1967,7 @@ and walk_pattern_record_row row t comments = attach t.leading longident.loc before_lbl; let after_lbl, rest = partition_adjacent_trailing longident.loc after_lbl in attach t.trailing longident.loc after_lbl; - let leading, inside, trailing = partition_by_loc rest pattern.ppat_loc in - attach t.leading pattern.ppat_loc leading; - walk_pattern pattern t inside; - attach t.trailing pattern.ppat_loc trailing + walk_around ~loc:pattern.ppat_loc walk_pattern pattern t rest (* Unlike a record row, a dict row is never punned: [dict{"a": a}] keeps its key, so comments around the key stay on the key *) @@ -2143,10 +1976,7 @@ and walk_pattern_dict_row {pdp_key = key; pdp_pattern = pattern} t comments = attach t.leading key.loc before_key; let after_key, rest = partition_adjacent_trailing key.loc after_key in attach t.trailing key.loc after_key; - let leading, inside, trailing = partition_by_loc rest pattern.ppat_loc in - attach t.leading pattern.ppat_loc leading; - walk_pattern pattern t inside; - attach t.trailing pattern.ppat_loc trailing + walk_around ~loc:pattern.ppat_loc walk_pattern pattern t rest and walk_row_field (row_field : Parsetree.row_field) t comments = match row_field with @@ -2164,12 +1994,7 @@ and walk_core_type typ t comments = | Ptyp_extension extension -> walk_extension extension t comments | Ptyp_package package_type -> walk_package_type package_type t comments | Ptyp_alias (typexpr, _alias) -> - let before_typ, inside_typ, after_typ = - partition_by_loc comments typexpr.ptyp_loc - in - attach t.leading typexpr.ptyp_loc before_typ; - walk_core_type typexpr t inside_typ; - attach t.trailing typexpr.ptyp_loc after_typ + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t comments | Ptyp_poly (strings, typexpr) -> let comments = visit_list_but_continue_with_remaining_comments @@ -2182,12 +2007,7 @@ and walk_core_type typ t comments = attach t.trailing longident.loc after_longident) ~newline_delimited:false strings t comments in - let before_typ, inside_typ, after_typ = - partition_by_loc comments typexpr.ptyp_loc - in - attach t.leading typexpr.ptyp_loc before_typ; - walk_core_type typexpr t inside_typ; - attach t.trailing typexpr.ptyp_loc after_typ + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t comments | Ptyp_variant (row_fields, _, _) -> walk_list (row_fields |> List.map (fun rf -> RowField rf)) t comments | Ptyp_constr (longident, typexprs) -> @@ -2203,12 +2023,7 @@ and walk_core_type typ t comments = | Ptyp_arrow _ -> let _, parameters, typexpr = arrow_type typ in let comments = walk_type_parameters parameters t comments in - let before_typ, inside_typ, after_typ = - partition_by_loc comments typexpr.ptyp_loc - in - attach t.leading typexpr.ptyp_loc before_typ; - walk_core_type typexpr t inside_typ; - attach t.trailing typexpr.ptyp_loc after_typ + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t comments | Ptyp_object (fields, _) -> walk_typ_object_fields fields t comments | _ -> () @@ -2222,12 +2037,7 @@ and walk_object_field field t comments = attach t.leading lbl.loc before_lbl; let after_lbl, rest = partition_adjacent_trailing lbl.loc after_lbl in attach t.trailing lbl.loc after_lbl; - let before_typ, inside_typ, after_typ = - partition_by_loc rest typexpr.ptyp_loc - in - attach t.leading typexpr.ptyp_loc before_typ; - walk_core_type typexpr t inside_typ; - attach t.trailing typexpr.ptyp_loc after_typ + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t rest | _ -> () and walk_type_parameters type_parameters t comments = @@ -2248,12 +2058,7 @@ and walk_type_parameters type_parameters t comments = and walk_type_parameter parameter t comments = match parameter with | Parsetree.Parg_type {typ = typexpr} -> - let before_typ, inside_typ, after_typ = - partition_by_loc comments typexpr.ptyp_loc - in - attach t.leading typexpr.ptyp_loc before_typ; - walk_core_type typexpr t inside_typ; - attach t.trailing typexpr.ptyp_loc after_typ + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t comments | Parsetree.Parg_fixed {loc} -> (* Like the [_] it is written with, which is where its comments go. *) let loc = Ast_fixed_arg.underscore_loc loc in @@ -2289,12 +2094,7 @@ and walk_package_constraint package_constraint t comments = partition_adjacent_trailing longident.loc after_longident in attach t.trailing longident.loc after_longident; - let before_typ, inside_typ, after_typ = - partition_by_loc rest typexpr.ptyp_loc - in - attach t.leading typexpr.ptyp_loc before_typ; - walk_core_type typexpr t inside_typ; - attach t.trailing typexpr.ptyp_loc after_typ + walk_around ~loc:typexpr.ptyp_loc walk_core_type typexpr t rest and walk_extension extension t comments = let id, payload = extension in From d764697cc07d430765760a62c5ed6fde2ae63057 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:25:37 +0000 Subject: [PATCH 05/14] Use the standard library for int, bytes and ref helpers Ext_pervasives.min_int/max_int, Ext_int.compare/equal, Ext_bytes.unsafe_blit_string and Ext_ref.protect copied Int.min/max, Int.compare/equal, Bytes.unsafe_blit_string and Fun.protect. Their callers use the standard library now; Ext_bytes and Ext_ref are gone. Ext_pervasives.finally stays: unlike Fun.protect it re-raises an exception from the cleanup unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- compiler/depends/ast_extract.ml | 7 ++++++- compiler/ext/ext_buffer.ml | 6 +++--- compiler/ext/ext_bytes.ml | 27 -------------------------- compiler/ext/ext_bytes.mli | 27 -------------------------- compiler/ext/ext_int.ml | 6 ------ compiler/ext/ext_int.mli | 6 ------ compiler/ext/ext_pervasives.ml | 4 ---- compiler/ext/ext_pervasives.mli | 4 ---- compiler/ext/ext_ref.ml | 34 --------------------------------- compiler/ext/ext_ref.mli | 25 ------------------------ compiler/ext/hash_int.ml | 2 +- compiler/ext/map_int.ml | 2 +- compiler/ext/set_int.ml | 2 +- compiler/ext/warnings.ml | 2 +- compiler/ml/ctype.ml | 12 ++++-------- compiler/ml/path.ml | 3 +-- 16 files changed, 18 insertions(+), 151 deletions(-) delete mode 100644 compiler/ext/ext_bytes.ml delete mode 100644 compiler/ext/ext_bytes.mli delete mode 100644 compiler/ext/ext_ref.ml delete mode 100644 compiler/ext/ext_ref.mli diff --git a/compiler/depends/ast_extract.ml b/compiler/depends/ast_extract.ml index ed64e85dc78..2d79257fb90 100644 --- a/compiler/depends/ast_extract.ml +++ b/compiler/depends/ast_extract.ml @@ -35,7 +35,12 @@ type 'a kind = 'a Ml_binary.kind let read_parse_and_extract (type t) (k : t kind) (ast : t) : Set_string.t = Depend.free_structure_names () := Set_string.empty; - Ext_ref.protect (Clflags.current ()).transparent_modules false (fun _ -> + let transparent_modules = (Clflags.current ()).transparent_modules in + let old = !transparent_modules in + transparent_modules := false; + Fun.protect + ~finally:(fun () -> transparent_modules := old) + (fun () -> List.iter (* check *) (fun modname -> ignore @@ Depend.open_module bound_vars (Longident.Lident modname)) diff --git a/compiler/ext/ext_buffer.ml b/compiler/ext/ext_buffer.ml index 6ee30dbdec2..8af2a8c99fc 100644 --- a/compiler/ext/ext_buffer.ml +++ b/compiler/ext/ext_buffer.ml @@ -70,7 +70,7 @@ let[@inline] add_char b c = then invalid_arg "Ext_buffer.add_substring/add_subbytes"; let new_position = b.position + len in if new_position > b.length then resize b len; - Ext_bytes.unsafe_blit_string s offset b.buffer b.position len; + Bytes.unsafe_blit_string s offset b.buffer b.position len; b.position <- new_position *) (* let add_subbytes b s offset len = @@ -80,7 +80,7 @@ let add_string b s = let len = String.length s in let new_position = b.position + len in if new_position > b.length then resize b len; - Ext_bytes.unsafe_blit_string s 0 b.buffer b.position len; + Bytes.unsafe_blit_string s 0 b.buffer b.position len; b.position <- new_position (* TODO: micro-optimzie *) @@ -90,7 +90,7 @@ let add_string_char b s c = let new_position = b.position + len in if new_position > b.length then resize b len; let b_buffer = b.buffer in - Ext_bytes.unsafe_blit_string s 0 b_buffer b.position s_len; + Bytes.unsafe_blit_string s 0 b_buffer b.position s_len; Bytes.unsafe_set b_buffer (new_position - 1) c; b.position <- new_position diff --git a/compiler/ext/ext_bytes.ml b/compiler/ext/ext_bytes.ml deleted file mode 100644 index 68808ab422f..00000000000 --- a/compiler/ext/ext_bytes.ml +++ /dev/null @@ -1,27 +0,0 @@ -(* Copyright (C) 2015-2016 Bloomberg Finance L.P. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * In addition to the permissions granted to you by the LGPL, you may combine - * or link a "work that uses the Library" with a publicly distributed version - * of this file to produce a combined library or application, then distribute - * that combined work under the terms of your choosing, with no requirement - * to comply with the obligations normally placed on you by section 4 of the - * LGPL version 3 (or the corresponding section of a later version of the LGPL - * should you choose to use a later version). - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) - -external unsafe_blit_string : string -> int -> bytes -> int -> int -> unit - = "caml_blit_string" -[@@noalloc] diff --git a/compiler/ext/ext_bytes.mli b/compiler/ext/ext_bytes.mli deleted file mode 100644 index 68808ab422f..00000000000 --- a/compiler/ext/ext_bytes.mli +++ /dev/null @@ -1,27 +0,0 @@ -(* Copyright (C) 2015-2016 Bloomberg Finance L.P. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * In addition to the permissions granted to you by the LGPL, you may combine - * or link a "work that uses the Library" with a publicly distributed version - * of this file to produce a combined library or application, then distribute - * that combined work under the terms of your choosing, with no requirement - * to comply with the obligations normally placed on you by section 4 of the - * LGPL version 3 (or the corresponding section of a later version of the LGPL - * should you choose to use a later version). - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) - -external unsafe_blit_string : string -> int -> bytes -> int -> int -> unit - = "caml_blit_string" -[@@noalloc] diff --git a/compiler/ext/ext_int.ml b/compiler/ext/ext_int.ml index 3c71537cab2..e40200581ca 100644 --- a/compiler/ext/ext_int.ml +++ b/compiler/ext/ext_int.ml @@ -22,12 +22,6 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) -type t = int - -let compare (x : t) (y : t) = Stdlib.compare x y - -let equal (x : t) (y : t) = x = y - let move = 0x1_0000_0000 (* works only on 64 bit platform *) diff --git a/compiler/ext/ext_int.mli b/compiler/ext/ext_int.mli index 0c618100097..0cfc2f0ba80 100644 --- a/compiler/ext/ext_int.mli +++ b/compiler/ext/ext_int.mli @@ -22,12 +22,6 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) -type t = int - -val compare : t -> t -> int - -val equal : t -> t -> bool - val int32_unsigned_to_int : int32 -> int (** works on 64 bit platform only diff --git a/compiler/ext/ext_pervasives.ml b/compiler/ext/ext_pervasives.ml index 42e1d1ee5ea..956015b6d4c 100644 --- a/compiler/ext/ext_pervasives.ml +++ b/compiler/ext/ext_pervasives.ml @@ -39,10 +39,6 @@ let finally v ~clean:action f = let with_file_as_chan filename f = finally (open_out_bin filename) ~clean:close_out f -let max_int (x : int) y = if x >= y then x else y - -let min_int (x : int) y = if x < y then x else y - let max_int_option (x : int option) y = match (x, y) with | None, _ -> y diff --git a/compiler/ext/ext_pervasives.mli b/compiler/ext/ext_pervasives.mli index e8bcc0eefc4..20470f5729a 100644 --- a/compiler/ext/ext_pervasives.mli +++ b/compiler/ext/ext_pervasives.mli @@ -31,10 +31,6 @@ val finally : 'a -> clean:('a -> unit) -> ('a -> 'b) -> 'b val with_file_as_chan : string -> (out_channel -> 'a) -> 'a -val max_int : int -> int -> int - -val min_int : int -> int -> int - val max_int_option : int option -> int option -> int option (* external id : 'a -> 'a = "%identity" *) diff --git a/compiler/ext/ext_ref.ml b/compiler/ext/ext_ref.ml deleted file mode 100644 index 3550d4fc67d..00000000000 --- a/compiler/ext/ext_ref.ml +++ /dev/null @@ -1,34 +0,0 @@ -(* Copyright (C) 2015-2016 Bloomberg Finance L.P. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * In addition to the permissions granted to you by the LGPL, you may combine - * or link a "work that uses the Library" with a publicly distributed version - * of this file to produce a combined library or application, then distribute - * that combined work under the terms of your choosing, with no requirement - * to comply with the obligations normally placed on you by section 4 of the - * LGPL version 3 (or the corresponding section of a later version of the LGPL - * should you choose to use a later version). - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) - -let protect r v body = - let old = !r in - try - r := v; - let res = body () in - r := old; - res - with x -> - r := old; - raise x diff --git a/compiler/ext/ext_ref.mli b/compiler/ext/ext_ref.mli deleted file mode 100644 index 8ca93af1e91..00000000000 --- a/compiler/ext/ext_ref.mli +++ /dev/null @@ -1,25 +0,0 @@ -(* Copyright (C) 2015-2016 Bloomberg Finance L.P. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * In addition to the permissions granted to you by the LGPL, you may combine - * or link a "work that uses the Library" with a publicly distributed version - * of this file to produce a combined library or application, then distribute - * that combined work under the terms of your choosing, with no requirement - * to comply with the obligations normally placed on you by section 4 of the - * LGPL version 3 (or the corresponding section of a later version of the LGPL - * should you choose to use a later version). - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) - -val protect : 'a ref -> 'a -> (unit -> 'b) -> 'b diff --git a/compiler/ext/hash_int.ml b/compiler/ext/hash_int.ml index 6d92a657e8b..a439d196b82 100644 --- a/compiler/ext/hash_int.ml +++ b/compiler/ext/hash_int.ml @@ -25,6 +25,6 @@ include Hashtbl.Make (struct type t = int - let equal = Ext_int.equal + let equal = Int.equal let hash = Ext_platform_primitives.hash_int end) diff --git a/compiler/ext/map_int.ml b/compiler/ext/map_int.ml index 1e50c6faf00..d64a3d15003 100644 --- a/compiler/ext/map_int.ml +++ b/compiler/ext/map_int.ml @@ -25,5 +25,5 @@ include Map.Make (struct type t = int - let compare = Ext_int.compare + let compare = Int.compare end) diff --git a/compiler/ext/set_int.ml b/compiler/ext/set_int.ml index 170b951cf7f..4a40ee11d74 100644 --- a/compiler/ext/set_int.ml +++ b/compiler/ext/set_int.ml @@ -25,5 +25,5 @@ include Set.Make (struct type t = int - let compare = Ext_int.compare + let compare = Int.compare end) diff --git a/compiler/ext/warnings.ml b/compiler/ext/warnings.ml index 83e5b65426e..72cd0e9ec5f 100644 --- a/compiler/ext/warnings.ml +++ b/compiler/ext/warnings.ml @@ -212,7 +212,7 @@ let parse_opt error active flags s = match s.[i] with | '0' .. '9' -> let i, n1, n2 = get_range i in - for n = n1 to Ext_pervasives.min_int n2 last_warning_number do + for n = n1 to Int.min n2 last_warning_number do myset n done; loop i diff --git a/compiler/ml/ctype.ml b/compiler/ml/ctype.ml index 0e0eaef1e4b..c582d9e8b6b 100644 --- a/compiler/ml/ctype.ml +++ b/compiler/ml/ctype.ml @@ -2280,7 +2280,7 @@ and unify2 env t1 t2 = ignore (expand_head_unif !env t2); let t1' = expand_head_unif !env t1 in let t2' = expand_head_unif !env t2 in - let lv = Ext_pervasives.min_int t1'.level t2'.level in + let lv = Int.min t1'.level t2'.level in update_level !env lv t2; update_level !env lv t1; if unify_eq t1' t2' then () @@ -2474,11 +2474,7 @@ and unify_fields env (ty1 : Types.type_expr) (ty2 : Types.type_expr) = requires this pre-unification state because tail unification can close an open row before the matching fields are processed. *) let open1 = is_Tvar (repr rest1) and open2 = is_Tvar (repr rest2) in - let va = - make_rowvar - (Ext_pervasives.min_int l1 l2) - (miss2 = []) rest1 (miss1 = []) rest2 - in + let va = make_rowvar (Int.min l1 l2) (miss2 = []) rest1 (miss1 = []) rest2 in let d1 = rest1.desc and d2 = rest2.desc in try unify env (build_fields l1 miss1 va) rest2; @@ -2548,7 +2544,7 @@ and unify_row env row1 row2 = let more = if fixed1 then rm1 else if fixed2 then rm2 - else newty2 (Ext_pervasives.min_int rm1.level rm2.level) (Tvar None) + else newty2 (Int.min rm1.level rm2.level) (Tvar None) in let fixed = fixed1 || fixed2 and closed = row1.row_closed || row2.row_closed in @@ -3402,7 +3398,7 @@ let pred_enlarge n = if n mod 2 = 1 then pred n else n type change = Unchanged | Equiv | Changed [@@immediate] let[@inline] max (c1 : change) (c2 : change) : change = - Obj.magic (Ext_pervasives.max_int (Obj.magic c1 : int) (Obj.magic c2 : int)) + Obj.magic (Int.max (Obj.magic c1 : int) (Obj.magic c2 : int)) let collect l = List.fold_left (fun c1 (_, c2) -> max c1 c2) Unchanged l let rec filter_visited = function diff --git a/compiler/ml/path.ml b/compiler/ml/path.ml index d3c78a3b135..31dced57f75 100644 --- a/compiler/ml/path.ml +++ b/compiler/ml/path.ml @@ -44,8 +44,7 @@ let rec isfree id = function let rec binding_time = function | Pident id -> Ident.binding_time id | Pdot (p, _s, _pos) -> binding_time p - | Papply (p1, p2) -> - Ext_pervasives.max_int (binding_time p1) (binding_time p2) + | Papply (p1, p2) -> Int.max (binding_time p1) (binding_time p2) let kfalse _ = false From 192746c411b47861b359b816d88d59af153b8687 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:29:07 +0000 Subject: [PATCH 06/14] Use the standard library for string and list helpers Ext_string.starts_with, for_all, equal, is_empty, single_colon and uncapitalize_ascii, and Ext_list.has_string, init and find_opt (a find_map) copied String and List functions; callers use those now. Three ounit cases only tested the removed copies. Ext_list.nth_opt (no raise on a negative index), assoc_by_string (default or assert) and is_empty (List.is_empty needs OCaml 5.1) stay. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- compiler/core/js_dump.ml | 4 +- compiler/core/js_dump_import_export.ml | 2 +- compiler/core/js_dump_lit.ml | 2 +- compiler/core/js_exp_make.ml | 2 +- compiler/core/js_implementation.ml | 3 +- compiler/core/js_stmt_make.ml | 16 ++++--- compiler/core/lam_compile_main.ml | 6 ++- compiler/ext/bsc_args.ml | 2 +- compiler/ext/ext_list.ml | 46 -------------------- compiler/ext/ext_list.mli | 10 ----- compiler/ext/ext_namespace.ml | 2 +- compiler/ext/ext_string.ml | 39 ----------------- compiler/ext/ext_string.mli | 12 ----- compiler/frontend/ast_derive_projector.ml | 6 +-- compiler/frontend/ast_exp_apply.ml | 2 +- compiler/frontend/ast_exp_handle_external.ml | 2 +- compiler/ml/external_ffi_types.ml | 2 +- compiler/ml/lambda.ml | 9 ++-- compiler/ml/matching.ml | 3 +- compiler/ml/record_runtime.ml | 4 +- tests/ounit_tests/ounit_scc_tests.ml | 2 +- tests/ounit_tests/ounit_string_tests.ml | 18 -------- 22 files changed, 41 insertions(+), 153 deletions(-) diff --git a/compiler/core/js_dump.ml b/compiler/core/js_dump.ml index d2d27cb1c5d..4efe26074c7 100644 --- a/compiler/core/js_dump.ml +++ b/compiler/core/js_dump.ml @@ -197,10 +197,12 @@ let rec is_printable_jsx (e : J.expression) = | _ -> false let raw_snippet_exp_simple_enough (s : string) = - Ext_string.for_all s (fun c -> + String.for_all + (fun c -> match c with | 'a' .. 'z' | 'A' .. 'Z' | '_' | '.' -> true | _ -> false) + s (* Parentheses are required when the expression starts syntactically with "{" or "function" TODO: be more conservative, since Google Closure will handle diff --git a/compiler/core/js_dump_import_export.ml b/compiler/core/js_dump_import_export.ml index 1038b8be63c..f1e07447230 100644 --- a/compiler/core/js_dump_import_export.ml +++ b/compiler/core/js_dump_import_export.ml @@ -96,7 +96,7 @@ let esmodule_export cxt f (idents : Ident.t list) = (fun (s, export) -> P.group f 0 (fun _ -> P.string f export; - if not @@ Ext_string.equal export s then ( + if not @@ String.equal export s then ( P.space f; P.string f L.as_; P.space f; diff --git a/compiler/core/js_dump_lit.ml b/compiler/core/js_dump_lit.ml index 52869920cc2..ee04aa63d98 100644 --- a/compiler/core/js_dump_lit.ml +++ b/compiler/core/js_dump_lit.ml @@ -60,7 +60,7 @@ let dot = "." let comma = "," -let colon = Ext_string.single_colon +let colon = ":" let colon_space = ": " diff --git a/compiler/core/js_exp_make.ml b/compiler/core/js_exp_make.ml index ae1a4273aed..29851cfb686 100644 --- a/compiler/core/js_exp_make.ml +++ b/compiler/core/js_exp_make.ml @@ -1510,7 +1510,7 @@ let to_int32 (e : J.expression) : J.expression = int32_bor e zero_int_literal let string_comp (cmp : Lambda.comparison) (e0 : t) (e1 : t) = match (string_literal_semantic e0, string_literal_semantic e1) with | Some a0, Some a1 -> ( - let equal = Ext_string.equal a0 a1 in + let equal = String.equal a0 a1 in match cmp with | Ceq -> bool equal | Cneq -> bool (Stdlib.not equal) diff --git a/compiler/core/js_implementation.ml b/compiler/core/js_implementation.ml index 14505c46cf6..73f1e4a8a64 100644 --- a/compiler/core/js_implementation.ml +++ b/compiler/core/js_implementation.ml @@ -188,8 +188,7 @@ let implementation_map ppf sourcefile = let ns = Ext_filename.module_name (Filename.remove_extension sourcefile) in let ml_ast = Ext_list.fold_left list_of_modules [] (fun acc line -> - if Ext_string.is_empty line then acc - else make_structure_item ~ns line :: acc) + if line = "" then acc else make_structure_item ~ns line :: acc) in Res_compmisc.init_path (); ml_ast diff --git a/compiler/core/js_stmt_make.ml b/compiler/core/js_stmt_make.ml index 2647d09499b..52d00f39cf2 100644 --- a/compiler/core/js_stmt_make.ml +++ b/compiler/core/js_stmt_make.ml @@ -82,7 +82,8 @@ let int_switch ?(declaration : (J.property * Ident.t) option) | Number (Int {i; _}) -> ( let continuation = match - Ext_list.find_opt clauses (fun (switch_case, x) -> + clauses + |> List.find_map (fun (switch_case, (x : J.case_clause)) -> if switch_case = Int32.to_int i then Some x.switch_body else None) with | Some case -> case @@ -135,10 +136,15 @@ let string_switch ?(declaration : (J.property * Ident.t) option) | Str txt -> ( let continuation = match - Ext_list.find_opt clauses (fun (switch_case, x) -> - match switch_case with - | Literal (String s) -> if s = txt then Some x.switch_body else None - | Literal _ | Payload_shape _ -> None) + clauses + |> List.find_map + (fun + ((switch_case : Variant_runtime.tag_type), (x : J.case_clause)) + -> + match switch_case with + | Literal (String s) -> + if s = txt then Some x.switch_body else None + | Literal _ | Payload_shape _ -> None) with | Some case -> case | None -> ( diff --git a/compiler/core/lam_compile_main.ml b/compiler/core/lam_compile_main.ml index e5f925a0030..3b4a01de472 100644 --- a/compiler/core/lam_compile_main.ml +++ b/compiler/core/lam_compile_main.ml @@ -83,7 +83,8 @@ let declare_undeclared_exports (exports : Ident.t list) (block : J.block) : (** Also need analyze its depenency is pure or not *) let no_side_effects (rest : Lam_group.t list) : string option = - Ext_list.find_opt rest (fun x -> + rest + |> List.find_map (fun (x : Lam_group.t) -> match x with | Single (kind, id, body) -> ( match kind with @@ -93,7 +94,8 @@ let no_side_effects (rest : Lam_group.t list) : string option = else None | _ -> None) | Recursive bindings -> - Ext_list.find_opt bindings (fun (id, lam) -> + bindings + |> List.find_map (fun (id, lam) -> if not @@ Lam_analysis.no_side_effects lam then Some (Printf.sprintf "%s" id.Ident.name) else None) diff --git a/compiler/ext/bsc_args.ml b/compiler/ext/bsc_args.ml index cc98e790397..314e9e35f32 100644 --- a/compiler/ext/bsc_args.ml +++ b/compiler/ext/bsc_args.ml @@ -54,7 +54,7 @@ let usage_b (buf : Ext_buffer.t) ~usage (speclist : t) = if String.length key > !max_col then max_col := String.length key); speclist |> Array.iter (fun (key, _, doc) -> - if not (Ext_string.starts_with doc "*internal*") then ( + if not (String.starts_with ~prefix:"*internal*" doc) then ( buf +> " "; buf +> key; buf +> String.make (!max_col - String.length key + 2) ' '; diff --git a/compiler/ext/ext_list.ml b/compiler/ext/ext_list.ml index 55ef202fad4..1a5d394fd66 100644 --- a/compiler/ext/ext_list.ml +++ b/compiler/ext/ext_list.ml @@ -101,14 +101,6 @@ let rec map l f = let y5 = f x5 in y1 :: y2 :: y3 :: y4 :: y5 :: map tail f -let rec has_string l f = - match l with - | [] -> false - | [x1] -> x1 = f - | [x1; x2] -> x1 = f || x2 = f - | [x1; x2; x3] -> x1 = f || x2 = f || x3 = f - | x1 :: x2 :: x3 :: x4 -> x1 = f || x2 = f || x3 = f || has_string x4 f - let rec map_combine l1 l2 f = match (l1, l2) with | [], [] -> [] @@ -384,36 +376,6 @@ let rec same_length xs ys = | _ :: xs, _ :: ys -> same_length xs ys | _, _ -> false -let init n f = - match n with - | 0 -> [] - | 1 -> - let a0 = f 0 in - [a0] - | 2 -> - let a0 = f 0 in - let a1 = f 1 in - [a0; a1] - | 3 -> - let a0 = f 0 in - let a1 = f 1 in - let a2 = f 2 in - [a0; a1; a2] - | 4 -> - let a0 = f 0 in - let a1 = f 1 in - let a2 = f 2 in - let a3 = f 3 in - [a0; a1; a2; a3] - | 5 -> - let a0 = f 0 in - let a1 = f 1 in - let a2 = f 2 in - let a3 = f 3 in - let a4 = f 4 in - [a0; a1; a2; a3; a4] - | _ -> Array.to_list (Array.init n f) - let rec rev_append l1 l2 = match l1 with | [] -> l2 @@ -577,14 +539,6 @@ let rec for_all2_no_exn l1 l2 p = | a1 :: l1, a2 :: l2 -> p a1 a2 && for_all2_no_exn l1 l2 p | _, _ -> false -let rec find_opt xs p = - match xs with - | [] -> None - | x :: l -> ( - match p x with - | Some _ as v -> v - | None -> find_opt l p) - let rec split_map l f = match l with | [] -> ([], []) diff --git a/compiler/ext/ext_list.mli b/compiler/ext/ext_list.mli index 5a36db2e160..fb63327b59c 100644 --- a/compiler/ext/ext_list.mli +++ b/compiler/ext/ext_list.mli @@ -32,8 +32,6 @@ val map_combine : 'a list -> 'b list -> ('a -> 'c) -> ('c * 'b) list val combine_array : 'a array -> 'b list -> ('a -> 'c) -> ('c * 'b) list -val has_string : string list -> string -> bool - val mapi : 'a list -> (int -> 'a -> 'b) -> 'b list val mapi_append : 'a list -> (int -> 'a -> 'b) -> 'b list -> 'b list @@ -90,8 +88,6 @@ val filter_map : 'a list -> ('a -> 'b option) -> 'b list val same_length : 'a list -> 'b list -> bool -val init : int -> (int -> 'a) -> 'a list - val split_at : 'a list -> int -> 'a list * 'a list (** [split_at n l] will split [l] into two lists [a,b], [a] will be of length [n], @@ -147,12 +143,6 @@ val find_first_not : 'a list -> ('a -> bool) -> 'a option fails the predicate *) -(** [find_opt f l] returns [None] if all return [None], - otherwise returns the first one. -*) - -val find_opt : 'a list -> ('a -> 'b option) -> 'b option - val rev_iter : 'a list -> ('a -> unit) -> unit val iter : 'a list -> ('a -> unit) -> unit diff --git a/compiler/ext/ext_namespace.ml b/compiler/ext/ext_namespace.ml index 52253d3a094..f7213f80983 100644 --- a/compiler/ext/ext_namespace.ml +++ b/compiler/ext/ext_namespace.ml @@ -37,7 +37,7 @@ let change_ext_ns_suffix name ext = let js_name_of_modulename s (case : Ext_js_file_kind.case) suffix : string = let s = match case with - | Little -> Ext_string.uncapitalize_ascii s + | Little -> String.uncapitalize_ascii s | Upper -> s in change_ext_ns_suffix s suffix diff --git a/compiler/ext/ext_string.ml b/compiler/ext/ext_string.ml index 5635f0ff420..5a45d729d42 100644 --- a/compiler/ext/ext_string.ml +++ b/compiler/ext/ext_string.ml @@ -44,34 +44,6 @@ let split_by ?(keep_empty = false) is_delim str = let split ?keep_empty str on = if str = "" then [] else split_by ?keep_empty (fun x -> (x : char) = on) str -let starts_with s beg = - let beg_len = String.length beg in - let s_len = String.length s in - beg_len <= s_len - && - let i = ref 0 in - while !i < beg_len && String.unsafe_get s !i = String.unsafe_get beg !i do - incr i - done; - !i = beg_len - -(* let check_suffix_case = ends_with *) -(* let check_suffix_case_then_chop = ends_with_then_chop *) - -(* let check_any_suffix_case_then_chop s suffixes = - let rec aux suffixes = - match suffixes with - | [] -> None - | x::xs -> - let id = ends_with_index s x in - if id >= 0 then Some (String.sub s 0 id) - else aux xs in - aux suffixes *) - -(* it is unsafe to expose such API as unsafe since - user can provide bad input range - -*) let rec unsafe_for_all_range s ~start ~finish p = start > finish || p (String.unsafe_get s start) @@ -82,19 +54,12 @@ let for_all_from s start p = if start < 0 then invalid_arg "Ext_string.for_all_from" else unsafe_for_all_range s ~start ~finish:(len - 1) p -let for_all s (p : char -> bool) = - unsafe_for_all_range s ~start:0 ~finish:(String.length s - 1) p - -let is_empty s = String.length s = 0 - let tail_from s x = let len = String.length s in if x > len then invalid_arg ("Ext_string.tail_from " ^ s ^ " : " ^ string_of_int x) else String.sub s x (len - x) -let equal (x : string) y = x = y - (* let rec index_rec s lim i c = if i >= lim then -1 else if String.unsafe_get s i = c then i @@ -126,10 +91,6 @@ let replace_backward_slash (x : string) = x let compare = Ext_platform_primitives.string_length_based_compare -let single_colon = ":" - -let uncapitalize_ascii = String.uncapitalize_ascii - external ( .![] ) : string -> int -> int = "%string_unsafe_get" let is_valid_hash_number (x : string) = diff --git a/compiler/ext/ext_string.mli b/compiler/ext/ext_string.mli index c5b39916752..500296641dc 100644 --- a/compiler/ext/ext_string.mli +++ b/compiler/ext/ext_string.mli @@ -33,8 +33,6 @@ val split_by : ?keep_empty:bool -> (char -> bool) -> string -> string list val split : ?keep_empty:bool -> string -> char -> string list (** default is false *) -val starts_with : string -> string -> bool - (** [ends_with_then_chop name ext] @example: @@ -52,12 +50,6 @@ val for_all_from : string -> int -> (char -> bool) -> bool if [start] is too large, it returns true *) -val for_all : string -> (char -> bool) -> bool - -val is_empty : string -> bool - -val equal : string -> string -> bool - (* val index_next : string -> int -> @@ -86,10 +78,6 @@ val replace_backward_slash : string -> string val compare : string -> string -> int -val single_colon : string - -val uncapitalize_ascii : string -> string - val is_valid_hash_number : string -> bool val hash_number_as_i32_exn : string -> int32 diff --git a/compiler/frontend/ast_derive_projector.ml b/compiler/frontend/ast_derive_projector.ml index b56ade66ce5..b95bb9643e1 100644 --- a/compiler/frontend/ast_derive_projector.ml +++ b/compiler/frontend/ast_derive_projector.ml @@ -54,7 +54,7 @@ let structure_gen (tdcls : tdcls) _explict_nonrec = | Pcstr_tuple pcd_args -> pcd_args | Pcstr_record _ -> raise_unsupported_vaiant_record_arg pcd_loc in - let little_con_name = Ext_string.uncapitalize_ascii con_name in + let little_con_name = String.uncapitalize_ascii con_name in let arity = List.length pcd_args in let annotate_type = match pcd_res with @@ -72,7 +72,7 @@ let structure_gen (tdcls : tdcls) _explict_nonrec = annotate_type else let vars = - Ext_list.init arity (fun x -> "param_" ^ string_of_int x) + List.init arity (fun x -> "param_" ^ string_of_int x) in let exp = Exp.constraint_ @@ -130,7 +130,7 @@ let signature_gen (tdcls : Parsetree.type_declaration list) _explict_nonrec = | None -> core_type in Ast_comb.single_non_rec_val ?attrs:gentype_attrs - {loc; txt = Ext_string.uncapitalize_ascii con_name} + {loc; txt = String.uncapitalize_ascii con_name} (match Ext_list.map pcd_args (fun x -> Parsetree.Parg_type {attrs = []; lbl = Nolabel; typ = x}) diff --git a/compiler/frontend/ast_exp_apply.ml b/compiler/frontend/ast_exp_apply.ml index 4a991ebcced..dc42336ceb8 100644 --- a/compiler/frontend/ast_exp_apply.ml +++ b/compiler/frontend/ast_exp_apply.ml @@ -92,7 +92,7 @@ type app_pattern = { let view_as_app (fn : exp) (s : string list) : app_pattern option = match fn.pexp_desc with | Pexp_apply {funct = {pexp_desc = Pexp_ident {txt = Lident op; _}}; args} - when Ext_list.has_string s op -> + when List.mem op s -> Some {op; loc = fn.pexp_loc; args = check_and_discard args} | _ -> None diff --git a/compiler/frontend/ast_exp_handle_external.ml b/compiler/frontend/ast_exp_handle_external.ml index 33c65d6c584..b392a6248f7 100644 --- a/compiler/frontend/ast_exp_handle_external.ml +++ b/compiler/frontend/ast_exp_handle_external.ml @@ -54,7 +54,7 @@ let ffi_expression loc ~is_function (exp : Parsetree.expression) = let arrow ~arity = let effective_arity = if arity = 0 then 1 else arity in let args = - Ext_list.init effective_arity (fun _ -> + List.init effective_arity (fun _ -> Parsetree.Parg_type {attrs = []; lbl = Nolabel; typ = any}) in Ast_helper.Typ.arrow ~loc args any diff --git a/compiler/ml/external_ffi_types.ml b/compiler/ml/external_ffi_types.ml index b32f27ede0e..523db57b2ca 100644 --- a/compiler/ml/external_ffi_types.ml +++ b/compiler/ml/external_ffi_types.ml @@ -124,7 +124,7 @@ let valid_ident (s : string) = with E -> false let is_package_relative_path (x : string) = - Ext_string.starts_with x "./" || Ext_string.starts_with x "../" + String.starts_with ~prefix:"./" x || String.starts_with ~prefix:"../" x let valid_global_name ?loc txt = if not (valid_ident txt) then diff --git a/compiler/ml/lambda.ml b/compiler/ml/lambda.ml index afe4b1464ee..4fc4b4ae486 100644 --- a/compiler/ml/lambda.ml +++ b/compiler/ml/lambda.ml @@ -930,7 +930,8 @@ let switch lam (lam_switch : lambda_switch) : t = | Lconst (Const_constructor constant), _ -> (* By runtime value: a coercion accepts [@as(1.)] for [@as(1.0)] *) let action = - Ext_list.find_opt lam_switch.sw_consts (fun (key, action) -> + lam_switch.sw_consts + |> List.find_map (fun (key, action) -> match key with | Switch_constructor (Constant tag) when literal_denotes_same constant.literal tag.literal -> @@ -943,7 +944,8 @@ let switch lam (lam_switch : lambda_switch) : t = e.g. an integer, so the const case might not be found *) let i = Int32.to_int i in let action = - Ext_list.find_opt lam_switch.sw_consts (fun (key, action) -> + lam_switch.sw_consts + |> List.find_map (fun (key, action) -> match key with | Switch_int ordinal when ordinal = i -> Some action | Switch_constructor (Constant {literal}) @@ -971,7 +973,8 @@ let switch lam (lam_switch : lambda_switch) : t = | _ -> block = case in let action = - Ext_list.find_opt lam_switch.sw_blocks (fun (key, action) -> + lam_switch.sw_blocks + |> List.find_map (fun (key, action) -> match (key, runtime) with | Switch_constructor (Block case_runtime), Some runtime when same_runtime runtime case_runtime -> diff --git a/compiler/ml/matching.ml b/compiler/ml/matching.ml index c42b9991bfc..9d544203da7 100644 --- a/compiler/ml/matching.ml +++ b/compiler/ml/matching.ml @@ -2309,7 +2309,8 @@ let make_constructor_matching_plan ~cstr ~(layout : Variant_runtime.layout) | 2, 0, _, [] when cstr.cstr_name = "true" || cstr.cstr_name = "false" -> let find_action name = match - Ext_list.find_opt consts (fun (cstr, action) -> + consts + |> List.find_map (fun (cstr, action) -> if cstr.cstr_name = name then Some action else None) with | Some action -> action diff --git a/compiler/ml/record_runtime.ml b/compiler/ml/record_runtime.ml index 57bd1ed34ec..c3abad3953e 100644 --- a/compiler/ml/record_runtime.ml +++ b/compiler/ml/record_runtime.ml @@ -55,8 +55,8 @@ let rec check_duplicated_labels_aux (lbls : Parsetree.label_declaration list) (* A field has one runtime name, so only the first [@as] naming it is taken out; a second one is left behind and reported here. *) let extra_as_attribute (lbl : Parsetree.label_declaration) = - Ext_list.find_opt lbl.pld_attributes - (fun (({txt; loc}, payload) : Parsetree.attribute) -> + lbl.pld_attributes + |> List.find_map (fun (({txt; loc}, payload) : Parsetree.attribute) -> if txt = "as" && Ast_payload.string_literal_of_payload payload <> None then Some loc else None) diff --git a/tests/ounit_tests/ounit_scc_tests.ml b/tests/ounit_tests/ounit_scc_tests.ml index cc2b0c1f22c..e8639326a05 100644 --- a/tests/ounit_tests/ounit_scc_tests.ml +++ b/tests/ounit_tests/ounit_scc_tests.ml @@ -3,7 +3,7 @@ let ( >:: ), ( >::: ) = OUnit.(( >:: ), ( >::: )) module String_hash = Hashtbl.Make (struct type t = string - let equal = Ext_string.equal + let equal = String.equal let hash = Ext_platform_primitives.hash_string end) diff --git a/tests/ounit_tests/ounit_string_tests.ml b/tests/ounit_tests/ounit_string_tests.ml index 59db1d4f5f3..cf19c5900f5 100644 --- a/tests/ounit_tests/ounit_string_tests.ml +++ b/tests/ounit_tests/ounit_string_tests.ml @@ -33,24 +33,6 @@ let suites = (Ext_string.for_all_from "xABC" 1_000 (function | 'A' .. 'Z' -> true | _ -> false)) ); - ( __LOC__ >:: fun _ -> - Ext_string.starts_with "ab" "a" =~ true; - Ext_string.starts_with "ab" "" =~ true; - Ext_string.starts_with "abb" "abb" =~ true; - Ext_string.starts_with "abb" "abbc" =~ false ); - ( __LOC__ >:: fun _ -> - Ext_string.for_all "____" (function - | '_' -> true - | _ -> false) - =~ true; - Ext_string.for_all "___-" (function - | '_' -> true - | _ -> false) - =~ false; - Ext_string.for_all "" (function - | '_' -> true - | _ -> false) - =~ true ); ( __LOC__ >:: fun _ -> Ext_string.tail_from "ghsogh" 1 =~ "hsogh"; Ext_string.tail_from "ghsogh" 0 =~ "ghsogh" ); From 7bdef7a3c3deb07254e3d6b8103d4546c8c416ac Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:29:54 +0000 Subject: [PATCH 07/14] Use the standard library for analysis's string and list helpers Utils.starts_with, ends_with, find and filter_map copied String.starts_with, String.ends_with, List.find_map and List.filter_map; their 37 callers use the standard library now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- analysis/src/commands.ml | 4 +-- analysis/src/completion_back_end.ml | 43 +++++++++++++++------------- analysis/src/dot_completion_utils.ml | 4 +-- analysis/src/find_files.ml | 6 ++-- analysis/src/process_cmt.ml | 6 ++-- analysis/src/process_extra.ml | 4 +-- analysis/src/references.ml | 7 +++-- analysis/src/scope.ml | 2 +- analysis/src/shared_types.ml | 2 +- analysis/src/utils.ml | 38 +----------------------- 10 files changed, 42 insertions(+), 74 deletions(-) diff --git a/analysis/src/commands.ml b/analysis/src/commands.ml index 902b6a1051c..1d85e6a11f3 100644 --- a/analysis/src/commands.ml +++ b/analysis/src/commands.ml @@ -194,12 +194,12 @@ let rename ~state ~full ~pos ~new_name ~debug = in let references_to_toplevel_modules = all_references - |> Utils.filter_map (fun {References.uri = uri2; loc_opt} -> + |> List.filter_map (fun {References.uri = uri2; loc_opt} -> if loc_opt = None then Some uri2 else None) in let references_to_items = all_references - |> Utils.filter_map (function + |> List.filter_map (function | {References.uri = uri2; loc_opt = Some loc} -> Some (uri2, loc) | {loc_opt = None} -> None) in diff --git a/analysis/src/completion_back_end.ml b/analysis/src/completion_back_end.ml index b5b42d21cf0..828e49f6c94 100644 --- a/analysis/src/completion_back_end.ml +++ b/analysis/src/completion_back_end.ml @@ -116,7 +116,7 @@ let completions_for_exported_constructors ~(env : Query_env.t) ~prefix ~exact (constructors |> List.filter (fun c -> Utils.check_name c.Constructor.cname.txt ~prefix ~exact) - |> Utils.filter_map (fun c -> + |> List.filter_map (fun c -> let name = c.Constructor.cname.txt in if not (Hashtbl.mem names_used name) then let () = Hashtbl.add names_used name () in @@ -140,7 +140,7 @@ let completion_for_exported_fields ~(env : Query_env.t) ~prefix ~exact res := (fields |> List.filter (fun f -> Utils.check_name f.fname.txt ~prefix ~exact) - |> Utils.filter_map (fun f -> + |> List.filter_map (fun f -> let name = f.fname.txt in if not (Hashtbl.mem names_used name) then let () = Hashtbl.add names_used name () in @@ -324,7 +324,7 @@ let kind_to_documentation ~state ~env ~full ~current_docstring name docstring @ [ Markdown.code_block - (if optional && Utils.starts_with name "?" = false then + (if optional && String.starts_with ~prefix:"?" name = false then name ^ "?: " ^ (typ |> Utils.unwrap_if_option |> Shared.type_to_string) else name ^ ": " ^ (typ |> Shared.type_to_string)); @@ -366,7 +366,7 @@ let kind_to_detail name (kind : Completion.kind) = (* Handle optional fields. Checking for "?" is because sometimes optional fields are prefixed with "?" when completing, and at that point we don't need to _also_ add a "?" after the field name, as that looks weird. *) - if optional && Utils.starts_with name "?" = false then + if optional && String.starts_with ~prefix:"?" name = false then typ |> Utils.unwrap_if_option |> Shared.type_to_string else typ |> Shared.type_to_string | Constructor (c, _) -> show_constructor c @@ -687,7 +687,7 @@ let get_complementary_completions_for_typed_value ~opens ~all_files ~scope ~env in let file_modules = all_files |> File_set.elements - |> Utils.filter_map (fun name -> + |> List.filter_map (fun name -> if Utils.check_name name ~prefix ~exact && not @@ -714,7 +714,7 @@ let get_completions_for_path ~state ~debug ~opens ~full ~pos ~exact ~scope in let file_modules = all_files |> File_set.elements - |> Utils.filter_map (fun name -> + |> List.filter_map (fun name -> if Utils.check_name name ~prefix ~exact && not @@ -1251,7 +1251,7 @@ and get_completions_for_context_path ~state ~debug ~full ~opens ~raw_opens ~pos match typ |> Type_utils.extract_object_type ~state ~env ~package with | Some (env, t_obj) -> t_obj |> Type_utils.get_obj_fields - |> Utils.filter_map (fun (field, typ) -> + |> List.filter_map (fun (field, typ) -> if Utils.check_name field ~prefix:label ~exact then Some (Completion.create field ~env ~kind:(Completion.ObjLabel typ)) @@ -1599,7 +1599,7 @@ let filter_items items ~prefix = else items |> List.filter (fun (item : Completion.t) -> - Utils.starts_with item.name prefix) + String.starts_with ~prefix item.name) type completion_mode = Pattern of Completable.pattern_mode | Expression @@ -1812,7 +1812,7 @@ let rec complete_typed_value ~raw_opens ~full ~state ~prefix ~completion_context ~as_snippet:false) ~includes_snippets:true ~insert_text: - ((if Utils.starts_with prefix "#" then "" else "#") + ((if String.starts_with ~prefix:"#" prefix then "" else "#") ^ constructor.display_name ^ print_constructor_args (List.length constructor.args) @@ -1822,7 +1822,9 @@ let rec complete_typed_value ~raw_opens ~full ~state ~prefix ~completion_context (constructor, type_expr |> Shared.type_to_string)) ~env) |> filter_items - ~prefix:(if Utils.starts_with prefix "#" then prefix else "#" ^ prefix) + ~prefix: + (if String.starts_with ~prefix:"#" prefix then prefix + else "#" ^ prefix) | Toption (env, t) -> if Debug.verbose () then print_endline "[complete_typed_value]--> Toption"; let inner_type = @@ -2116,7 +2118,7 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover Completion.create name ~kind:(Label typ_string) ~env in let key_labels = - if Utils.starts_with "key" prefix then [mk_label ("key", "string")] + if String.starts_with ~prefix "key" then [mk_label ("key", "string")] else [] in let path_to_element_props = Type_utils.path_to_element_props package in @@ -2136,7 +2138,7 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover (fields |> List.filter_map (fun (f : field) -> if - Utils.starts_with f.fname.txt prefix + String.starts_with ~prefix f.fname.txt && (for_hover || not (List.mem f.fname.txt idents_seen)) then Some @@ -2165,13 +2167,13 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover mkLabel_ name (typ |> Shared.type_to_string) in let key_labels = - if Utils.starts_with "key" prefix then [mkLabel_ "key" "string"] else [] + if String.starts_with ~prefix "key" then [mkLabel_ "key" "string"] else [] in if labels = [] then [] else (labels |> List.filter (fun (name, _t, _env) -> - Utils.starts_with name prefix + String.starts_with ~prefix name && name <> "key" && (for_hover || not (List.mem name idents_seen))) |> List.map mk_label) @@ -2326,9 +2328,9 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover in let items = items_from_package_json @ local_items in items - |> List.filter (fun name -> Utils.starts_with name prefix) + |> List.filter (fun name -> String.starts_with ~prefix name) |> List.map (fun name -> - let is_local = Utils.starts_with name "./" in + let is_local = String.starts_with ~prefix:"./" name in Completion.create name ~kind:(Label (if is_local then "Local file" else "Package")) ~env) @@ -2351,7 +2353,8 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover else Completion_decorators.local in decorators - |> List.filter (fun (decorator, _, _) -> Utils.starts_with decorator prefix) + |> List.filter (fun (decorator, _, _) -> + String.starts_with ~prefix decorator) |> List.map (fun (decorator, maybe_insert_text, doc) -> let parts = String.split_on_char '.' prefix in let len = String.length prefix in @@ -2389,7 +2392,7 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover in labels |> List.filter (fun (name, _t) -> - Utils.starts_with name prefix + String.starts_with ~prefix name && (for_hover || not (List.mem name idents_seen))) |> List.map mk_label | Cpattern {context_path; prefix; nested; fallback; pattern_mode} -> ( @@ -2597,7 +2600,7 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover | ChtmlElement {prefix} -> Completion_jsx.html_elements |> List.filter_map (fun (element_name, description, deprecated) -> - if Utils.starts_with element_name prefix then + if String.starts_with ~prefix element_name then let name = "<" ^ element_name ^ ">" in Some (Completion.create name ~synthetic:true ~kind:(Label name) @@ -2609,7 +2612,7 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover | false -> None)) else None) | CextensionNode prefix -> - if Utils.starts_with "todo" prefix then + if String.starts_with ~prefix "todo" then let detail = "`%todo` is used to tell the compiler that some code still needs to be \ implemented." diff --git a/analysis/src/dot_completion_utils.ml b/analysis/src/dot_completion_utils.ml index 6cd0f4e7123..b7ab9d8b82a 100644 --- a/analysis/src/dot_completion_utils.ml +++ b/analysis/src/dot_completion_utils.ml @@ -1,6 +1,6 @@ let filter_record_fields ~env ~record_as_string ~prefix ~exact fields = fields - |> Utils.filter_map (fun (field : Shared_types.field) -> + |> List.filter_map (fun (field : Shared_types.field) -> if Utils.check_name field.fname.txt ~prefix ~exact then Some (Shared_types.Completion.create field.fname.txt ~env @@ -17,7 +17,7 @@ let field_completions_for_dot_completion ?pos_of_dot typ ~env ~state ~package if Debug.verbose () then Printf.printf "[dot_completion]--> Obj type found:\n"; obj |> Type_utils.get_obj_fields - |> Utils.filter_map (fun (field, _typ) -> + |> List.filter_map (fun (field, _typ) -> if Utils.check_name field ~prefix ~exact then let full_obj_field_name = Printf.sprintf "[\"%s\"]" field in Some diff --git a/analysis/src/find_files.ml b/analysis/src/find_files.ml index 07eeb282ff9..8ca0fa0eabf 100644 --- a/analysis/src/find_files.ml +++ b/analysis/src/find_files.ml @@ -144,11 +144,11 @@ let collect_files ~compiled_directory ~source_directory = |> List.filter is_source_file |> filter_duplicates in compileds - |> Utils.filter_map (fun path -> + |> List.filter_map (fun path -> let mod_name = get_name path in let cmt = compiled_directory /+ path in let res_opt = - Utils.find + List.find_map (fun name -> if get_name name = mod_name then Some (source_directory /+ name) else None) @@ -213,7 +213,7 @@ let find_project_files ~public ~namespace ~path ~source_directories let normals = files |> String_set.elements - |> Utils.filter_map (fun file -> + |> List.filter_map (fun file -> if is_implementation file then ( let module_name = get_name file in let resi = Hashtbl.find_opt interfaces module_name in diff --git a/analysis/src/process_cmt.ml b/analysis/src/process_cmt.ml index 18d854a5244..f5caa8c9f61 100644 --- a/analysis/src/process_cmt.ml +++ b/analysis/src/process_cmt.ml @@ -441,7 +441,7 @@ let rec for_structure_item ~(env : Shared_types.Env.t) ~(exported : Exported.t) let unpack_loc_opt = match pat.pat_extra - |> Utils.filter_map (function + |> List.filter_map (function | Typedtree.Tpat_unpack, loc, _ -> Some loc | _ -> None) with @@ -729,7 +729,7 @@ let file_for_cmt_infos ~module_name ~uri | Partial_implementation parts -> let items = parts |> Array.to_list - |> Utils.filter_map (fun p -> + |> List.filter_map (fun p -> match (p : Cmt_format.binary_part) with | Partial_structure str -> Some str.str_items | Partial_structure_item str -> Some [str] @@ -741,7 +741,7 @@ let file_for_cmt_infos ~module_name ~uri | Partial_interface parts -> let items = parts |> Array.to_list - |> Utils.filter_map (fun (p : Cmt_format.binary_part) -> + |> List.filter_map (fun (p : Cmt_format.binary_part) -> match p with | Partial_signature str -> Some str.sig_items | Partial_signature_item str -> Some [str] diff --git a/analysis/src/process_extra.ml b/analysis/src/process_extra.ml index af339909f9d..f8e7ffc3fe0 100644 --- a/analysis/src/process_extra.ml +++ b/analysis/src/process_extra.ml @@ -110,7 +110,7 @@ let extra_for_cmt ~(iterator : Tast_iterator.iterator) | Partial_implementation parts -> let items = parts |> Array.to_list - |> Utils.filter_map (fun (p : Cmt_format.binary_part) -> + |> List.filter_map (fun (p : Cmt_format.binary_part) -> match p with | Partial_structure str -> Some str.str_items | Partial_structure_item str -> Some [str] @@ -125,7 +125,7 @@ let extra_for_cmt ~(iterator : Tast_iterator.iterator) | Partial_interface parts -> let items = parts |> Array.to_list - |> Utils.filter_map (fun (p : Cmt_format.binary_part) -> + |> List.filter_map (fun (p : Cmt_format.binary_part) -> match p with | Partial_signature s -> Some s.sig_items | Partial_signature_item str -> Some [str] diff --git a/analysis/src/references.ml b/analysis/src/references.ml index b5b143ebf52..35446df1363 100644 --- a/analysis/src/references.ml +++ b/analysis/src/references.ml @@ -25,7 +25,8 @@ let line_col_to_cmt_loc ~pos:(line, col) = (line + 1, col) *) let normalize_external_reference_key ~namespace ~module_name ~path = match namespace with - | Some namespace when Utils.ends_with module_name ("-" ^ namespace) -> + | Some namespace when String.ends_with ~suffix:("-" ^ namespace) module_name + -> let suffix_len = String.length namespace + 1 in let source_module_len = String.length module_name - suffix_len in let source_module = String.sub module_name 0 source_module_len in @@ -505,7 +506,7 @@ let for_local_stamp ~state ~full:{file; extra; package} stamp (tip : Tip.t) = | Some refs -> let locs = refs - |> Utils.filter_map (fun (p, t, locs) -> + |> List.filter_map (fun (p, t, locs) -> if p = normalized_path && t = tip then Some locs else None) in @@ -529,7 +530,7 @@ let all_references_for_loc_item ~state ~full:({file; package} as full) loc_item | TopLevelModule module_name -> let other_modules_references = package.project_files |> File_set.elements - |> Utils.filter_map (fun module_name -> + |> List.filter_map (fun module_name -> Cmt.full_from_module ~package ~module_name) |> List.map (fun full -> match Hashtbl.find_opt full.extra.file_references module_name with diff --git a/analysis/src/scope.ml b/analysis/src/scope.ml index 2fafbcc7884..70d376560a3 100644 --- a/analysis/src/scope.ml +++ b/analysis/src/scope.ml @@ -124,6 +124,6 @@ let iter_includes f x = let get_raw_opens x = x - |> Utils.filter_map (function + |> List.filter_map (function | Open path -> Some path | _ -> None) diff --git a/analysis/src/shared_types.ml b/analysis/src/shared_types.ml index ef6082bdd5a..78435e5548a 100644 --- a/analysis/src/shared_types.ml +++ b/analysis/src/shared_types.ml @@ -430,7 +430,7 @@ let get_cmt_path ~uri p = | Impl {cmt} -> cmt | Namespace {cmt} -> cmt | IntfAndImpl {cmti; cmt} -> - let interface = Utils.ends_with (Uri.to_path uri) "i" in + let interface = String.ends_with ~suffix:"i" (Uri.to_path uri) in if interface then cmti else cmt module Tip = struct diff --git a/analysis/src/utils.ml b/analysis/src/utils.ml index d5888c29bf1..4f55e18d0b4 100644 --- a/analysis/src/utils.ml +++ b/analysis/src/utils.ml @@ -1,20 +1,3 @@ -(** - * `starts_with s prefix` - * true if the string starts with the prefix - *) -let starts_with s prefix = - if prefix = "" then true - else - let p = String.length prefix in - p <= String.length s && String.sub s 0 p = prefix - -let ends_with s suffix = - if suffix = "" then true - else - let p = String.length suffix in - let l = String.length s in - p <= String.length s && String.sub s (l - p) p = suffix - let is_first_char_uppercase s = String.length s > 0 && Char.equal s.[0] (Char.uppercase_ascii s.[0]) @@ -40,25 +23,6 @@ let chop_location_end loc length = loc_end = {loc.loc_end with pos_cnum = loc.loc_end.pos_cnum - length}; } -(** An optional List.find *) -let rec find fn items = - match items with - | [] -> None - | one :: rest -> ( - match fn one with - | None -> find fn rest - | Some x -> Some x) - -let filter_map f = - let rec aux accu = function - | [] -> List.rev accu - | x :: l -> ( - match f x with - | None -> aux accu l - | Some v -> aux (v :: accu) l) - in - aux [] - let dump_path path = Str.global_replace (Str.regexp_string "\\") "/" path let flatten_long_ident ?(jsx = false) ?(cut_at_offset = None) lid = @@ -168,7 +132,7 @@ let is_jsx_component (vb : Parsetree.value_binding) = | Some {pjc_kind = Pjc_with_props} | None -> false let check_name name ~prefix ~exact = - if exact then name = prefix else starts_with name prefix + if exact then name = prefix else String.starts_with ~prefix name let indent n text = let spaces = String.make n ' ' in From b2f9dadd51baf621f716bb8ce91b80869f1c1c76 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:30:55 +0000 Subject: [PATCH 08/14] Read @deprecated in analysis as the compiler does Process_attributes.find_deprecated_attribute parsed the attribute itself and disagreed with the compiler on malformed payloads: a record without `reason` showed as deprecated with an empty message although the compiler doesn't warn. It now takes the message from Builtin_attributes.deprecated_of_attrs_with_migrate, which the interface exports for this. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- analysis/src/process_attributes.ml | 30 ++++--------------- .../editor-deprecated-like-compiler.polish.md | 1 + compiler/ml/builtin_attributes.mli | 5 ++++ 3 files changed, 11 insertions(+), 25 deletions(-) create mode 100644 changes/editor-deprecated-like-compiler.polish.md diff --git a/analysis/src/process_attributes.ml b/analysis/src/process_attributes.ml index 3bd228285ba..74112d215fa 100644 --- a/analysis/src/process_attributes.ml +++ b/analysis/src/process_attributes.ml @@ -10,31 +10,11 @@ let rec find_doc_attribute attributes = | None -> find_doc_attribute rest) | _ :: rest -> find_doc_attribute rest -let rec find_deprecated_attribute attributes = - let open Parsetree in - match attributes with - | [] -> None - | ({Asttypes.txt = "deprecated"}, PStr [{pstr_desc = Pstr_eval (expr, _)}]) - :: _ -> ( - match Ast_payload.semantic_string_of_expression expr with - | Some msg -> Some msg - | None -> ( - match (Ast_payload.unwrap_braces expr).pexp_desc with - (* deprecated attr with record *) - | Pexp_record (fields, _) -> - let reason = ref "" in - fields - |> List.iter (fun {lid = {txt}; x} -> - match txt with - | Lident "reason" -> ( - match Ast_payload.semantic_string_of_expression x with - | Some msg -> reason := msg - | None -> ()) - | _ -> ()); - Some !reason - | _ -> None)) - | ({Asttypes.txt = "deprecated"}, _) :: _ -> Some "" - | _ :: rest -> find_deprecated_attribute rest +(* The message of a [@deprecated] attribute, read as the compiler reads it + for its warning *) +let find_deprecated_attribute attributes = + Builtin_attributes.deprecated_of_attrs_with_migrate attributes + |> Option.map (fun (reason, _, _) -> reason) let new_declared ~item ~extent ~name ~stamp ~module_path is_exported attributes = diff --git a/changes/editor-deprecated-like-compiler.polish.md b/changes/editor-deprecated-like-compiler.polish.md new file mode 100644 index 00000000000..03b127ca3e5 --- /dev/null +++ b/changes/editor-deprecated-like-compiler.polish.md @@ -0,0 +1 @@ +- The editor now shows a value as deprecated exactly when the compiler warns about it, also for `@deprecated` payloads it read differently before (such as a record without `reason`). diff --git a/compiler/ml/builtin_attributes.mli b/compiler/ml/builtin_attributes.mli index d7bb9dc79e2..11585127d83 100644 --- a/compiler/ml/builtin_attributes.mli +++ b/compiler/ml/builtin_attributes.mli @@ -41,6 +41,11 @@ val check_deprecated_inclusion : unit val deprecated_of_attrs : Parsetree.attributes -> string option +val deprecated_of_attrs_with_migrate : + Parsetree.attributes -> + (string * Parsetree.expression option * Parsetree.expression option) option +(** The message and migration templates of a [@deprecated] attribute *) + val deprecated_attributes : Parsetree.attributes -> Parsetree.attributes (** The [deprecated] attributes in a list *) From abc97550552b6b4c31bd056eb338af197e9315f4 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:31:27 +0000 Subject: [PATCH 09/14] Look up local value completions with one function find_local_completions_for_values_and_constructors and find_local_completions_for_values differed only in the constructor steps; find_local_completions_for_values now takes ~constructors. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- analysis/src/completion_back_end.ml | 55 ++++++++--------------------- 1 file changed, 14 insertions(+), 41 deletions(-) diff --git a/analysis/src/completion_back_end.ml b/analysis/src/completion_back_end.ml index 828e49f6c94..7cd29d6ada1 100644 --- a/analysis/src/completion_back_end.ml +++ b/analysis/src/completion_back_end.ml @@ -547,52 +547,21 @@ let get_items_from_opens ~opens ~local_tables ~prefix ~exact ~completion_context completions_from_this_open @ results) [] -let find_local_completions_for_values_and_constructors +(* Local values and modules, and constructors when [constructors] is set *) +let find_local_completions_for_values ~constructors ~(local_tables : Local_tables.t) ~env ~prefix ~exact ~opens ~scope = local_tables |> Local_tables.populate_values ~env; local_tables |> Local_tables.populate_included_values ~env; - local_tables |> Local_tables.populate_constructors ~env; + if constructors then local_tables |> Local_tables.populate_constructors ~env; local_tables |> Local_tables.populate_modules ~env; scope |> Scope.iter_values_before_first_open (process_local_value ~prefix ~exact ~env ~local_tables); - scope - |> Scope.iter_constructors_before_first_open - (process_local_constructor ~prefix ~exact ~env ~local_tables); - scope - |> Scope.iter_modules_before_first_open - (process_local_module ~prefix ~exact ~env ~local_tables); - - let values_from_opens = - get_items_from_opens ~opens ~local_tables ~prefix ~exact - ~completion_context:Value - in - - scope - |> Scope.iter_values_after_first_open - (process_local_value ~prefix ~exact ~env ~local_tables); - scope - |> Scope.iter_constructors_after_first_open - (process_local_constructor ~prefix ~exact ~env ~local_tables); - scope - |> Scope.iter_modules_after_first_open - (process_local_module ~prefix ~exact ~env ~local_tables); - - scope - |> Scope.iter_includes - (process_local_include ~prefix ~exact ~env ~local_tables); - - List.rev_append local_tables.result_rev values_from_opens - -let find_local_completions_for_values ~(local_tables : Local_tables.t) ~env - ~prefix ~exact ~opens ~scope = - local_tables |> Local_tables.populate_values ~env; - local_tables |> Local_tables.populate_included_values ~env; - local_tables |> Local_tables.populate_modules ~env; - scope - |> Scope.iter_values_before_first_open - (process_local_value ~prefix ~exact ~env ~local_tables); + if constructors then + scope + |> Scope.iter_constructors_before_first_open + (process_local_constructor ~prefix ~exact ~env ~local_tables); scope |> Scope.iter_modules_before_first_open (process_local_module ~prefix ~exact ~env ~local_tables); @@ -605,6 +574,10 @@ let find_local_completions_for_values ~(local_tables : Local_tables.t) ~env scope |> Scope.iter_values_after_first_open (process_local_value ~prefix ~exact ~env ~local_tables); + if constructors then + scope + |> Scope.iter_constructors_after_first_open + (process_local_constructor ~prefix ~exact ~env ~local_tables); scope |> Scope.iter_modules_after_first_open (process_local_module ~prefix ~exact ~env ~local_tables); @@ -665,7 +638,7 @@ let find_local_completions_with_opens ~pos ~(env : Query_env.t) ~prefix ~exact let local_tables = Local_tables.create () in match completion_context with | Value | ValueOrField -> - find_local_completions_for_values_and_constructors ~local_tables ~env + find_local_completions_for_values ~constructors:true ~local_tables ~env ~prefix ~exact ~opens ~scope | Type -> find_local_completions_for_types ~local_tables ~env ~prefix ~exact ~opens @@ -682,8 +655,8 @@ let get_complementary_completions_for_typed_value ~opens ~all_files ~scope ~env let exact = false in let local_completions_with_opens = let local_tables = Local_tables.create () in - find_local_completions_for_values ~local_tables ~env ~prefix ~exact ~opens - ~scope + find_local_completions_for_values ~constructors:false ~local_tables ~env + ~prefix ~exact ~opens ~scope in let file_modules = all_files |> File_set.elements From 2d205781aed57744fd6f61030d87ffa77c65f050 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 20:32:27 +0000 Subject: [PATCH 10/14] Print module paths with Printtyp in analysis and tools createInterface and rescript-tools each printed an out_ident with their own copy of Printtyp.string_of_out_ident; they use Printtyp's now, which the interface exports for this. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- analysis/src/create_interface.ml | 9 +-------- compiler/ml/printtyp.mli | 1 + tools/src/tools.ml | 8 +------- 3 files changed, 3 insertions(+), 15 deletions(-) diff --git a/analysis/src/create_interface.ml b/analysis/src/create_interface.ml index cffc424c065..e174aed3d8f 100644 --- a/analysis/src/create_interface.ml +++ b/analysis/src/create_interface.ml @@ -427,14 +427,7 @@ let print_signature ~path ~source ~extractor ~signature = Buffer.add_string buf (") =>\n" ^ indent); process_module_type ~scope ~indent ret_mt | Mty_ident path | Mty_alias (_, path) -> - let rec out_ident_to_string (ident : Outcometree.out_ident) = - match ident with - | Oide_ident s -> s - | Oide_dot (ident, s) -> out_ident_to_string ident ^ "." ^ s - | Oide_apply (call, arg) -> - out_ident_to_string call ^ "(" ^ out_ident_to_string arg ^ ")" - in - Buffer.add_string buf (out_ident_to_string (Printtyp.tree_of_path path)) + Buffer.add_string buf (Printtyp.string_of_path path) in process_signature ~scope:None ~indent:"" signature; diff --git a/compiler/ml/printtyp.mli b/compiler/ml/printtyp.mli index 51ef87d0b67..8b284602563 100644 --- a/compiler/ml/printtyp.mli +++ b/compiler/ml/printtyp.mli @@ -28,6 +28,7 @@ val ident : formatter -> Ident.t -> unit val tree_of_path : Path.t -> out_ident val path : formatter -> Path.t -> unit val string_of_path : Path.t -> string +val string_of_out_ident : Outcometree.out_ident -> string val raw_type_expr : formatter -> type_expr -> unit val string_of_label : Asttypes.arg_label -> string diff --git a/tools/src/tools.ml b/tools/src/tools.ml index b8bd83d2abe..052e36e2d8a 100644 --- a/tools/src/tools.ml +++ b/tools/src/tools.ml @@ -341,12 +341,6 @@ let type_detail typ ~env ~full ~state = }) | _ -> None -let rec string_of_out_ident = function - | Outcometree.Oide_ident name -> name - | Oide_dot (path, name) -> string_of_out_ident path ^ "." ^ name - | Oide_apply (functor_, argument) -> - string_of_out_ident functor_ ^ "(" ^ string_of_out_ident argument ^ ")" - let render_out_type typ = Res_doc.to_string ~width:80 (Res_outcome_printer.print_out_type_doc typ) @@ -355,7 +349,7 @@ let rec type_doc_of_out_type (typ : Outcometree.out_type) = | Otyp_constr (path, generic_parameters) -> Constructor { - path = string_of_out_ident path; + path = Printtyp.string_of_out_ident path; generic_parameters = List.map type_doc_of_out_type generic_parameters; } | Otyp_var (weak, name) -> Variable {name; weak} From d37461f7f98d622abd3ccfe83adb009da1408c9f Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 21:04:03 +0000 Subject: [PATCH 11/14] Keep Ext_string.starts_with, which doesn't allocate String.starts_with allocates a closure for its local loop on every call, and is_package_relative_path calls it twice for every external: the benchmarks showed +163 words on Stdlib_Symbol. Ext_string.starts_with loops without allocating; it is back, with a comment saying why, for the compiler's two callers and its ounit case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- compiler/ext/bsc_args.ml | 2 +- compiler/ext/ext_string.ml | 13 +++++++++++++ compiler/ext/ext_string.mli | 4 ++++ compiler/ml/external_ffi_types.ml | 2 +- tests/ounit_tests/ounit_string_tests.ml | 5 +++++ 5 files changed, 24 insertions(+), 2 deletions(-) diff --git a/compiler/ext/bsc_args.ml b/compiler/ext/bsc_args.ml index 314e9e35f32..cc98e790397 100644 --- a/compiler/ext/bsc_args.ml +++ b/compiler/ext/bsc_args.ml @@ -54,7 +54,7 @@ let usage_b (buf : Ext_buffer.t) ~usage (speclist : t) = if String.length key > !max_col then max_col := String.length key); speclist |> Array.iter (fun (key, _, doc) -> - if not (String.starts_with ~prefix:"*internal*" doc) then ( + if not (Ext_string.starts_with doc "*internal*") then ( buf +> " "; buf +> key; buf +> String.make (!max_col - String.length key + 2) ' '; diff --git a/compiler/ext/ext_string.ml b/compiler/ext/ext_string.ml index 5a45d729d42..7cbc5338a8a 100644 --- a/compiler/ext/ext_string.ml +++ b/compiler/ext/ext_string.ml @@ -44,6 +44,19 @@ let split_by ?(keep_empty = false) is_delim str = let split ?keep_empty str on = if str = "" then [] else split_by ?keep_empty (fun x -> (x : char) = on) str +(* Unlike String.starts_with, this allocates no closure for its loop, which + matters on paths that run for every external or identifier. *) +let starts_with s beg = + let beg_len = String.length beg in + let s_len = String.length s in + beg_len <= s_len + && + let i = ref 0 in + while !i < beg_len && String.unsafe_get s !i = String.unsafe_get beg !i do + incr i + done; + !i = beg_len + let rec unsafe_for_all_range s ~start ~finish p = start > finish || p (String.unsafe_get s start) diff --git a/compiler/ext/ext_string.mli b/compiler/ext/ext_string.mli index 500296641dc..7eeb47a4140 100644 --- a/compiler/ext/ext_string.mli +++ b/compiler/ext/ext_string.mli @@ -33,6 +33,10 @@ val split_by : ?keep_empty:bool -> (char -> bool) -> string -> string list val split : ?keep_empty:bool -> string -> char -> string list (** default is false *) +val starts_with : string -> string -> bool +(** [starts_with s prefix]. Unlike [String.starts_with], it allocates + nothing. *) + (** [ends_with_then_chop name ext] @example: diff --git a/compiler/ml/external_ffi_types.ml b/compiler/ml/external_ffi_types.ml index 523db57b2ca..b32f27ede0e 100644 --- a/compiler/ml/external_ffi_types.ml +++ b/compiler/ml/external_ffi_types.ml @@ -124,7 +124,7 @@ let valid_ident (s : string) = with E -> false let is_package_relative_path (x : string) = - String.starts_with ~prefix:"./" x || String.starts_with ~prefix:"../" x + Ext_string.starts_with x "./" || Ext_string.starts_with x "../" let valid_global_name ?loc txt = if not (valid_ident txt) then diff --git a/tests/ounit_tests/ounit_string_tests.ml b/tests/ounit_tests/ounit_string_tests.ml index cf19c5900f5..b8a68e6899a 100644 --- a/tests/ounit_tests/ounit_string_tests.ml +++ b/tests/ounit_tests/ounit_string_tests.ml @@ -33,6 +33,11 @@ let suites = (Ext_string.for_all_from "xABC" 1_000 (function | 'A' .. 'Z' -> true | _ -> false)) ); + ( __LOC__ >:: fun _ -> + Ext_string.starts_with "ab" "a" =~ true; + Ext_string.starts_with "ab" "" =~ true; + Ext_string.starts_with "abb" "abb" =~ true; + Ext_string.starts_with "abb" "abbc" =~ false ); ( __LOC__ >:: fun _ -> Ext_string.tail_from "ghsogh" 1 =~ "hsogh"; Ext_string.tail_from "ghsogh" 0 =~ "ghsogh" ); From 21c0a90489feea0a9382b76854485d9c4ee4586f Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 21:04:26 +0000 Subject: [PATCH 12/14] Match the pipe operator by its name in the built-in PPX view_as_app checked every applied identifier against a one-element list with List.mem, which compares through the generic structural compare; its only caller passed ["->"]. view_as_pipe matches the constant "->" in the pattern, a direct string comparison. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- compiler/frontend/ast_exp_apply.ml | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/compiler/frontend/ast_exp_apply.ml b/compiler/frontend/ast_exp_apply.ml index dc42336ceb8..77d4bcb3b68 100644 --- a/compiler/frontend/ast_exp_apply.ml +++ b/compiler/frontend/ast_exp_apply.ml @@ -88,16 +88,15 @@ type app_pattern = { args: Parsetree.expression list; } -(* match fn as *) -let view_as_app (fn : exp) (s : string list) : app_pattern option = +(* An application of the pipe operator [->]. Matching the constant compiles + to a direct string comparison, run for every application. *) +let view_as_pipe (fn : exp) : app_pattern option = match fn.pexp_desc with - | Pexp_apply {funct = {pexp_desc = Pexp_ident {txt = Lident op; _}}; args} - when List.mem op s -> + | Pexp_apply + {funct = {pexp_desc = Pexp_ident {txt = Lident ("->" as op)}}; args} -> Some {op; loc = fn.pexp_loc; args = check_and_discard args} | _ -> None -let infix_ops = ["->"] - let rec rewrite_pipe_rhs ~loc ~attrs a (f : exp) = match f.pexp_desc with | Pexp_braces {expr; braces_loc} -> @@ -183,7 +182,7 @@ let rec rewrite_pipe_rhs ~loc ~attrs a (f : exp) = | _ -> Exp.apply ~loc ~attrs f [(Nolabel, a)] let app_exp_mapper (e : exp) (self : Ast_mapper.mapper) : exp = - match view_as_app e infix_ops with + match view_as_pipe e with | Some {op = "->"; args = [a_; f_]; loc} -> ( (* A braced pipeline RHS may contain local bindings or opens before its final call. Bind the left-hand expression before entering that context. *) From 3aa41e0f533a28ff12d9d55abbce4177a5da504b Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Wed, 11 Nov 2026 14:54:25 +0000 Subject: [PATCH 13/14] Stop exporting Printtyp.tree_of_path createInterface was its last user outside Printtyp and prints the path with Printtyp.string_of_path now, so the dead-code check reported the export. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- compiler/ml/printtyp.mli | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler/ml/printtyp.mli b/compiler/ml/printtyp.mli index 8b284602563..39f707a1c3e 100644 --- a/compiler/ml/printtyp.mli +++ b/compiler/ml/printtyp.mli @@ -25,7 +25,6 @@ type printing_context = {inlined_types: type_inlined_type list} val print_res_poly_identifier : (string -> string) ref val longident : formatter -> Longident.t -> unit val ident : formatter -> Ident.t -> unit -val tree_of_path : Path.t -> out_ident val path : formatter -> Path.t -> unit val string_of_path : Path.t -> string val string_of_out_ident : Outcometree.out_ident -> string From 2a7d515d8196606c651553b8b473f77ff3ea9398 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Thu, 12 Nov 2026 20:45:14 +0000 Subject: [PATCH 14/14] Test analysis's by-name instantiation and @deprecated reading Codex review: the two analysis behavior fixes had no tests. ounit_analysis_types_tests checks that instantiate_type2 substitutes a parameter and keeps a variable that isn't one, and that find_deprecated_attribute reads a string, a record with a reason, and a record without one (not deprecated) as the compiler does. Both fail against the previous behavior. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gKyiYMf54wPRxFdUWe Signed-off-by: Christoph Knittel --- .../ounit_tests/ounit_analysis_types_tests.ml | 84 +++++++++++++++++++ tests/ounit_tests/ounit_tests_main.ml | 1 + 2 files changed, 85 insertions(+) create mode 100644 tests/ounit_tests/ounit_analysis_types_tests.ml diff --git a/tests/ounit_tests/ounit_analysis_types_tests.ml b/tests/ounit_tests/ounit_analysis_types_tests.ml new file mode 100644 index 00000000000..ac254b2a310 --- /dev/null +++ b/tests/ounit_tests/ounit_analysis_types_tests.ml @@ -0,0 +1,84 @@ +open OUnit +open Analysis + +let var name = Btype.newgenty (Types.Tvar (Some name)) + +(* instantiate_type2 doesn't read the environment *) +let env = + Shared_types.Query_env.from_file + { + Shared_types.File.uri = Uri.from_path "/Test.res"; + stamps = Shared_types.Stamps.init (); + module_name = "Test"; + structure = + { + name = "Test"; + docstring = []; + exported = Shared_types.Exported.init (); + items = []; + deprecated = None; + }; + } + +let is_int (t : Types.type_expr) = + match (Btype.repr t).desc with + | Tconstr (path, [], _) -> Path.same path Predef.path_int + | _ -> false + +let var_name (t : Types.type_expr) = + match (Btype.repr t).desc with + | Tvar name -> name + | _ -> None + +let deprecated payload = + Process_attributes.find_deprecated_attribute + [ + ( {Location.txt = "deprecated"; loc = Location.none}, + Parsetree.PStr [Ast_helper.Str.eval payload] ); + ] + +let string_exp s = Ast_helper.Exp.constant (Ast_helper.Const.string s) + +let record fields = + Ast_helper.Exp.record + (List.map + (fun (name, x) -> + { + Parsetree.lid = {txt = Longident.Lident name; loc = Location.none}; + x; + opt = false; + }) + fields) + None + +let show = function + | Some s -> "Some " ^ s + | None -> "None" + +let suites = + __FILE__ + >::: [ + ( "instantiating by name keeps a variable that isn't a parameter" + >:: fun _ -> + let type_arg_context = + { + Shared_types.env; + type_params = [var "a"]; + type_args = [Predef.type_int ()]; + } + in + let t = Btype.newgenty (Ttuple [var "a"; var "b"]) in + match (Type_utils.instantiate_type2 ~type_arg_context t).desc with + | Ttuple [a; b] -> + assert_bool "the parameter is substituted" (is_int a); + assert_equal ~printer:show (Some "b") (var_name b) + | _ -> assert_failure "not a tuple" ); + ( "@deprecated reads as the compiler reads it" >:: fun _ -> + assert_equal ~printer:show (Some "use b") + (deprecated (string_exp "use b")); + assert_equal ~printer:show (Some "use b") + (deprecated (record [("reason", string_exp "use b")])); + (* the compiler doesn't warn for a record without a reason *) + assert_equal ~printer:show None + (deprecated (record [("migrate", string_exp "b")])) ); + ] diff --git a/tests/ounit_tests/ounit_tests_main.ml b/tests/ounit_tests/ounit_tests_main.ml index d53bffff6cd..fc923e5ef3b 100644 --- a/tests/ounit_tests/ounit_tests_main.ml +++ b/tests/ounit_tests/ounit_tests_main.ml @@ -32,6 +32,7 @@ let suites = Ounit_parser_recovery_tests.suites; Ounit_analysis_config_tests.suites; Ounit_analysis_references_tests.suites; + Ounit_analysis_types_tests.suites; Ounit_ffi_inclusion_tests.suites; Ounit_typeopt_tests.suites; Ounit_gentype_tests.suites;