Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/warning-inline-not-stored.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Add warning 113, on by default, for an exported `@inline` function that other modules can't inline, with the reason: it uses another value of its module, it's async or has a directive, or it calls an external with a relative path. It's still inlined in its own module. Turn it off for one binding with `@warning("-113")`.
3 changes: 2 additions & 1 deletion compiler/backend/lam_compile_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -459,14 +459,15 @@ let compile ?on_optimized_lambda (output_prefix : string)
| 0 -> Lam_module_ident.compare_same_name id1 id2
| c -> c)
in
Warnings.check_fatal ();
let effect_ =
Lam_stats_export.get_dependent_module_effect maybe_pure external_module_ids
in
let v : Js_cmj_format.t =
Lam_stats_export.export_to_cmj meta effect_ export_map
(Ext_filename.case output_prefix)
in
(* After the export, which reports warning 113. *)
Warnings.check_fatal ();
if not !((Clflags.current ()).dont_write_files) then
Js_cmj_format.to_file
~check_exists:(not !((Js_config.current ()).force_cmj))
Expand Down
97 changes: 62 additions & 35 deletions compiler/backend/lam_stats_export.ml
Original file line number Diff line number Diff line change
Expand Up @@ -73,42 +73,69 @@ let values_of_export (meta : Lam_stats.t) (export_map : Lambda.t Map_ident.t) :
| None ->
optlam
| Some lambda -> (
if calls_relative_external lambda then None
else
match lambda with
| Lfunction ({attr = {inline = Always_inline}} as fn) ->
(* An [@inline] function or functor: other modules inline its
body too, with or without -bs-cross-module-opt, when they
can. It must be closed, since the body is copied without
its environment. *)
if
Lambda.lfunction_can_be_inlined fn
&& Lam_closure.is_closed lambda
then optlam
else None
| _ when not !((Js_config.current ()).cross_module_inline) -> None
| _ when not (Lam_analysis.safe_to_inline lambda) ->
(* when inlining a non function, we have to be very careful,
match lambda with
| Lfunction
{
attr = {inline = Always_inline; async; directive; is_a_functor};
loc;
} -> (
(* An [@inline] function or functor: other modules inline its
body too, when they can. It must be closed, since the body is
copied without its environment. *)
let not_stored =
if async then Some "it is async"
else if Option.is_some directive then Some "it has a directive"
else if calls_relative_external lambda then
Some "it calls an external with a path relative to this file"
else if Lam_closure.is_closed lambda then None
else
(* The first variable that [Lam_closure.is_closed] objects
to: other modules are global and fine to name. *)
match
Map_ident.fold
(fun id _ found ->
match found with
| None when not (Ident.global id) -> Some id
| _ -> found)
(Lam_closure.free_variables Set_ident.empty Map_ident.empty
lambda)
None
with
| Some id ->
Some ("it uses " ^ Ident.name id ^ ", a value of this module")
| None -> None
in
match not_stored with
| None -> optlam
| Some reason ->
Inline_not_stored.report x (fun () ->
Loc_report.prerr_warning loc
(Warnings.Inline_not_stored
((if is_a_functor then "functor" else "function"), reason)));
None)
| _ when calls_relative_external lambda -> None
| _ when not !((Js_config.current ()).cross_module_inline) -> None
| _ when not (Lam_analysis.safe_to_inline lambda) ->
(* when inlining a non function, we have to be very careful,
only truly immutable values can be inlined *)
None
| Lfunction {attr = {is_a_functor = true}} ->
if Lam_closure.is_closed lambda then optlam else None
| _ ->
let lam_size =
Lam_analysis.size_upto ~limit:Lam_analysis.small_inline_size
lambda
in
let free_variables =
Lam_closure.free_variables Set_ident.empty Map_ident.empty
lambda
in
if
lam_size < Lam_analysis.small_inline_size
&& Map_ident.is_empty free_variables
then (
Ir_log.dwarn ~__POS__ "%s recorded for inlining @." x.name;
optlam)
else None)
None
| Lfunction {attr = {is_a_functor = true}} ->
if Lam_closure.is_closed lambda then optlam else None
| _ ->
let lam_size =
Lam_analysis.size_upto ~limit:Lam_analysis.small_inline_size
lambda
in
let free_variables =
Lam_closure.free_variables Set_ident.empty Map_ident.empty lambda
in
if
lam_size < Lam_analysis.small_inline_size
&& Map_ident.is_empty free_variables
then (
Ir_log.dwarn ~__POS__ "%s recorded for inlining @." x.name;
optlam)
else None)
in
match (arity, persistent_closed_lambda) with
| Single Arity_na, (None | Some (Lconst Const_module_alias)) -> acc
Expand Down
38 changes: 38 additions & 0 deletions compiler/typing/inline_not_stored.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
(* Warning 113 is reported where the .cmj is built, after type checking,
when the warning scopes of a binding and of [@@warning] are gone. The type
checker records here the warning state of each [@inline] binding, whose
[@inline] may be on the binding or on its expression, so the warning is
reported, or not, and made an error, or not, as it would have been there. *)
let states_key =
Request_local.new_key (fun () : (Ident.t, Warnings.state) Hashtbl.t ->
Hashtbl.create 1)

let has_inline (attributes : Parsetree.attributes) =
List.exists
(fun (({txt}, _) : Parsetree.attribute) -> txt = "inline")
attributes

let record_binding (attributes : Parsetree.attributes)
(inner_attributes : Parsetree.attributes) ids =
if has_inline attributes || has_inline inner_attributes then
(* Type checking applied these scopes already and reported what they
report, such as [@ppwarning] or a malformed [@warning]; here they are
only read. *)
let state =
Warnings.without_warnings (fun () ->
Builtin_attributes.warning_scope ~ppwarning:false attributes
(fun () ->
Builtin_attributes.warning_scope ~ppwarning:false inner_attributes
Warnings.backup))
in
List.iter
(fun id -> Hashtbl.replace (Domain.DLS.get states_key) id state)
(ids ())

let report (id : Ident.t) report =
match Hashtbl.find_opt (Domain.DLS.get states_key) id with
| None -> report ()
| Some state ->
let outside = Warnings.backup () in
Warnings.restore state;
Fun.protect ~finally:(fun () -> Warnings.restore outside) report
13 changes: 13 additions & 0 deletions compiler/typing/inline_not_stored.mli
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
(* The warning state of the bindings of [@inline] values: their [@warning]
and [@warnerror], and a [@@warning] above them. *)

(* [record_binding attributes inner_attributes ids] records, if the binding
or its expression is [@inline], the warning state inside the binding's
[attributes] and those of its expression for the identifiers [ids ()]
binds. *)
val record_binding :
Parsetree.attributes -> Parsetree.attributes -> (unit -> Ident.t list) -> unit

(* [report id f] runs [f], which reports warning 113 for [id], in the
warning state of [id]'s binding. *)
val report : Ident.t -> (unit -> unit) -> unit
29 changes: 29 additions & 0 deletions compiler/typing/typemod.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1469,6 +1469,24 @@ and type_structure funct_body anchor env sstr =
let defs, newenv =
Typecore.type_binding ~context:None env rec_flag sdefs
in
(* Warning 113 is reported after type checking, outside the warning
scopes of the binding and of a [@@warning] above it, so record the
warning state of [@inline] bindings here. *)
List.iter
(fun (vb : value_binding) ->
(* A type constraint keeps its attributes in [exp_extra], the
outermost first. [warning_scope] applies a list from its end,
so the innermost attributes go first. *)
let expression_attributes =
match vb.vb_expr.exp_extra with
| [] -> vb.vb_expr.exp_attributes
| extra ->
vb.vb_expr.exp_attributes
@ List.concat_map (fun (_, _, attrs) -> attrs) (List.rev extra)
in
Inline_not_stored.record_binding vb.vb_attributes
expression_attributes (fun () -> pat_bound_idents vb.vb_pat))
defs;
let () =
if rec_flag = Recursive then Rec_check.check_recursive_bindings defs
in
Expand Down Expand Up @@ -1582,6 +1600,17 @@ and type_structure funct_body anchor env sstr =
check_name check_module names name;
let id = Ident.create name.txt in
(* create early for PR#6752 *)
(* An [@inline] functor gets warning 113 like a function. Its [@inline]
may be below module type constraints. *)
let rec module_attributes (smod : Parsetree.module_expr) =
match smod.pmod_desc with
| Pmod_constraint (inner, _) ->
(* The innermost first, as for expressions. *)
module_attributes inner @ smod.pmod_attributes
| _ -> smod.pmod_attributes
in
Inline_not_stored.record_binding attrs (module_attributes smodl)
(fun () -> [id]);
let modl =
Builtin_attributes.warning_scope attrs (fun () ->
type_module ~alias:true true funct_body
Expand Down
9 changes: 8 additions & 1 deletion compiler/typing/warnings.ml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ type t =
| Bs_todo of string option (* 110 *)
| Bs_private_record_mutation of string (* 111 *)
| Bs_record_rest_optional_overlap of string list (* 112 *)
| Inline_not_stored of string * string (* 113 *)

(* If you remove a warning, leave a hole in the numbering. NEVER change
the numbers of existing warnings.
Expand Down Expand Up @@ -128,8 +129,9 @@ let number = function
| Bs_todo _ -> 110
| Bs_private_record_mutation _ -> 111
| Bs_record_rest_optional_overlap _ -> 112
| Inline_not_stored _ -> 113

let last_warning_number = 112
let last_warning_number = 113

let letter_all =
let rec loop i = if i = 0 then [] else i :: loop (i - 1) in
Expand Down Expand Up @@ -463,6 +465,10 @@ let message = function
^ "\n\n\
\ This code is not implemented yet and will crash at runtime. Make sure \
you implement this before running the code."
| Inline_not_stored (kind, reason) ->
"This @inline " ^ kind
^ " is inlined only in this module, not in modules that use it: " ^ reason
^ "."
| Bs_private_record_mutation field_name ->
Printf.sprintf "Mutation of private record field %S." field_name

Expand Down Expand Up @@ -563,6 +569,7 @@ let descriptions =
(110, "Todo found");
(111, "Mutation of private record field");
(112, "Record rest pattern will always be empty");
(113, "@inline function inlined only in its own module");
]

let help_warnings () =
Expand Down
1 change: 1 addition & 0 deletions compiler/typing/warnings.mli
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ type t =
| Bs_todo of string option (* 110 *)
| Bs_private_record_mutation of string (* 111 *)
| Bs_record_rest_optional_overlap of string list (* 112 *)
| Inline_not_stored of string * string (* 113 *)

val parse_options : bool -> string -> unit

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,19 @@
import * as assert from "node:assert";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { stripVTControlCharacters } from "node:util";
import { setup } from "#dev/process";

const { execBuildOrThrow, execClean } = setup(import.meta.dirname);

await execBuildOrThrow();
const { stdout, stderr } = await execBuildOrThrow();
const output = stripVTControlCharacters(stdout + stderr);

assert.match(
output,
/Warning number 113.*Hidden\.res.*calls an external with a path relative to this file/s,
"warning 113 reports that Hidden.wrapped stays in its module",
);

const app = await fs.readFile(
path.join(import.meta.dirname, "src", "app", "App.mjs"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@
},
"suffix": ".mjs",
"compiler-flags": ["-bs-cross-module-opt"],
"warnings": { "error": true }
"warnings": { "error": "A-113" }
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// A path relative to this file: the call must stay in this module.
// A path relative to this file: the call must stay in this module, which
// warning 113 reports (checked by input.js).
@module("./helper.js") external raw: int => int = "raw"
@inline let wrapped = x => raw(x) + 1

Expand Down
2 changes: 2 additions & 0 deletions tests/build_tests/projects/inline_warning_as_error/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
lib
src/**/*.mjs
34 changes: 34 additions & 0 deletions tests/build_tests/projects/inline_warning_as_error/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// @ts-check

// Warning 113 is reported while the .cmj is built, after type checking. As an
// error, it must still fail the build.

import * as assert from "node:assert";
import { stripVTControlCharacters } from "node:util";
import { setup } from "#dev/process";

const { execBuild, execClean } = setup(import.meta.dirname);

const lines = (/** @type {{stderr: string}} */ out) =>
stripVTControlCharacters(out.stderr)
.split("\n")
.map(s => s.trim());

await execClean();

const warning = await execBuild();
assert.equal(warning.status, 0, warning.stdout + warning.stderr);
assert.ok(
lines(warning).includes("Warning number 113"),
warning.stdout + warning.stderr,
);

await execClean();
const error = await execBuild(["--warn-error", "+113"]);
assert.notEqual(error.status, 0, "warning 113 as an error fails the build");
assert.ok(
lines(error).includes("Warning number 113 (configured as error)"),
error.stdout + error.stderr,
);

await execClean();
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "inline_warning_as_error",
"sources": ["src"],
"package-specs": { "module": "esmodule", "in-source": true },
"suffix": ".mjs"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
let limit = "abc"

// Other modules can't inline this: it uses `limit`.
@inline let withLimit = x => x ++ limit
Loading
Loading