id
int64 0
886
| original_context
stringlengths 648
56.6k
| modified_context
stringlengths 587
47.6k
| omitted_context
sequencelengths 0
19
| omitted_index
sequencelengths 0
19
| metadata
dict |
---|---|---|---|---|---|
100 | diff --git a/compiler/rustc_mir_transform/src/check_unnecessary_transmutes.rs b/compiler/rustc_mir_transform/src/check_unnecessary_transmutes.rs
index 8be782dcbf0ad..4aff127908eec 100644
--- a/compiler/rustc_mir_transform/src/check_unnecessary_transmutes.rs
+++ b/compiler/rustc_mir_transform/src/check_unnecessary_transmutes.rs
@@ -87,11 +87,8 @@ impl<'tcx> Visitor<'tcx> for UnnecessaryTransmuteChecker<'_, 'tcx> {
&& let Some((func_def_id, _)) = func.const_fn_def()
&& self.tcx.is_intrinsic(func_def_id, sym::transmute)
&& let span = self.body.source_info(location).span
- && let Some(lint) = self.is_unnecessary_transmute(
- func,
- self.tcx.sess.source_map().span_to_snippet(arg).expect("ok"),
- span,
- )
+ && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(arg)
+ && let Some(lint) = self.is_unnecessary_transmute(func, snippet, span)
&& let Some(hir_id) = terminator.source_info.scope.lint_root(&self.body.source_scopes)
{
self.tcx.emit_node_span_lint(UNNECESSARY_TRANSMUTES, hir_id, span, lint);
diff --git a/tests/ui/transmute/auxiliary/unnecessary-transmute-path-remap-ice-140277-trans.rs b/tests/ui/transmute/auxiliary/unnecessary-transmute-path-remap-ice-140277-trans.rs
new file mode 100644
index 0000000000000..0f273a6f536e0
--- /dev/null
+++ b/tests/ui/transmute/auxiliary/unnecessary-transmute-path-remap-ice-140277-trans.rs
@@ -0,0 +1,10 @@
+//@ compile-flags: --remap-path-prefix=/=/non-existent
+// helper for ../unnecessary-transmute-path-remap-ice-140277.rs
+
+#[macro_export]
+macro_rules! transmute {
+ ($e:expr) => {{
+ let e = $e;
+ std::mem::transmute(e)
+ }};
+}
diff --git a/tests/ui/transmute/unnecessary-transmute-path-remap-ice-140277.rs b/tests/ui/transmute/unnecessary-transmute-path-remap-ice-140277.rs
new file mode 100644
index 0000000000000..756ce7b3d5074
--- /dev/null
+++ b/tests/ui/transmute/unnecessary-transmute-path-remap-ice-140277.rs
@@ -0,0 +1,10 @@
+//@ aux-crate: zerocopy=unnecessary-transmute-path-remap-ice-140277-trans.rs
+//@ check-pass
+// tests for a regression in linting for unnecessary transmutes
+// where a span was inacessible for snippet procuring,
+// when remap-path-prefix was set, causing a panic.
+
+fn bytes_at_home(x: [u8; 4]) -> u32 {
+ unsafe { zerocopy::transmute!(x) }
+}
+fn main() {}
| diff --git a/compiler/rustc_mir_transform/src/check_unnecessary_transmutes.rs b/compiler/rustc_mir_transform/src/check_unnecessary_transmutes.rs
index 8be782dcbf0ad..4aff127908eec 100644
--- a/compiler/rustc_mir_transform/src/check_unnecessary_transmutes.rs
+++ b/compiler/rustc_mir_transform/src/check_unnecessary_transmutes.rs
@@ -87,11 +87,8 @@ impl<'tcx> Visitor<'tcx> for UnnecessaryTransmuteChecker<'_, 'tcx> {
&& let Some((func_def_id, _)) = func.const_fn_def()
&& self.tcx.is_intrinsic(func_def_id, sym::transmute)
&& let span = self.body.source_info(location).span
- && let Some(lint) = self.is_unnecessary_transmute(
- func,
- self.tcx.sess.source_map().span_to_snippet(arg).expect("ok"),
- span,
- )
+ && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(arg)
+ && let Some(lint) = self.is_unnecessary_transmute(func, snippet, span)
&& let Some(hir_id) = terminator.source_info.scope.lint_root(&self.body.source_scopes)
{
self.tcx.emit_node_span_lint(UNNECESSARY_TRANSMUTES, hir_id, span, lint);
diff --git a/tests/ui/transmute/auxiliary/unnecessary-transmute-path-remap-ice-140277-trans.rs b/tests/ui/transmute/auxiliary/unnecessary-transmute-path-remap-ice-140277-trans.rs
index 0000000000000..0f273a6f536e0
+++ b/tests/ui/transmute/auxiliary/unnecessary-transmute-path-remap-ice-140277-trans.rs
+// helper for ../unnecessary-transmute-path-remap-ice-140277.rs
+#[macro_export]
+macro_rules! transmute {
+ ($e:expr) => {{
+ }};
diff --git a/tests/ui/transmute/unnecessary-transmute-path-remap-ice-140277.rs b/tests/ui/transmute/unnecessary-transmute-path-remap-ice-140277.rs
index 0000000000000..756ce7b3d5074
+++ b/tests/ui/transmute/unnecessary-transmute-path-remap-ice-140277.rs
+//@ aux-crate: zerocopy=unnecessary-transmute-path-remap-ice-140277-trans.rs
+//@ check-pass
+// tests for a regression in linting for unnecessary transmutes
+// where a span was inacessible for snippet procuring,
+// when remap-path-prefix was set, causing a panic.
+fn bytes_at_home(x: [u8; 4]) -> u32 {
+ unsafe { zerocopy::transmute!(x) }
+fn main() {} | [
"+//@ compile-flags: --remap-path-prefix=/=/non-existent",
"+ let e = $e;",
"+ std::mem::transmute(e)"
] | [
24,
30,
31
] | {
"additions": 22,
"author": "bend-n",
"deletions": 5,
"html_url": "https://github.com/rust-lang/rust/pull/140284",
"issue_id": 140284,
"merged_at": "2025-04-25T21:57:13Z",
"omission_probability": 0.1,
"pr_number": 140284,
"repo": "rust-lang/rust",
"title": "remove expect() in `unnecessary_transmutes`",
"total_changes": 27
} |
101 | diff --git a/tests/ui/copy-a-resource.rs b/tests/ui/copy-a-resource.rs
deleted file mode 100644
index 55f2dd4ee6dde..0000000000000
--- a/tests/ui/copy-a-resource.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-#[derive(Debug)]
-struct Foo {
- i: isize,
-}
-
-impl Drop for Foo {
- fn drop(&mut self) {}
-}
-
-fn foo(i:isize) -> Foo {
- Foo {
- i: i
- }
-}
-
-fn main() {
- let x = foo(10);
- let _y = x.clone();
- //~^ ERROR no method named `clone` found
- println!("{:?}", x);
-}
diff --git a/tests/ui/fail-simple.rs b/tests/ui/macros/no-matching-rule.rs
similarity index 100%
rename from tests/ui/fail-simple.rs
rename to tests/ui/macros/no-matching-rule.rs
diff --git a/tests/ui/fail-simple.stderr b/tests/ui/macros/no-matching-rule.stderr
similarity index 85%
rename from tests/ui/fail-simple.stderr
rename to tests/ui/macros/no-matching-rule.stderr
index 50c350b3ef55e..a6312a843f398 100644
--- a/tests/ui/fail-simple.stderr
+++ b/tests/ui/macros/no-matching-rule.stderr
@@ -1,5 +1,5 @@
error: no rules expected `@`
- --> $DIR/fail-simple.rs:2:12
+ --> $DIR/no-matching-rule.rs:2:12
|
LL | panic!(@);
| ^ no rules expected this token in macro call
diff --git a/tests/ui/methods/clone-missing.rs b/tests/ui/methods/clone-missing.rs
new file mode 100644
index 0000000000000..f2e4ad268c63a
--- /dev/null
+++ b/tests/ui/methods/clone-missing.rs
@@ -0,0 +1,19 @@
+// This test checks that calling `.clone()` on a type that does not implement the `Clone` trait
+// results in a compilation error. The `Foo` struct does not derive or implement `Clone`,
+// so attempting to clone it should fail.
+
+struct Foo {
+ i: isize,
+}
+
+fn foo(i:isize) -> Foo {
+ Foo {
+ i: i
+ }
+}
+
+fn main() {
+ let x = foo(10);
+ let _y = x.clone();
+ //~^ ERROR no method named `clone` found
+}
diff --git a/tests/ui/copy-a-resource.stderr b/tests/ui/methods/clone-missing.stderr
similarity index 94%
rename from tests/ui/copy-a-resource.stderr
rename to tests/ui/methods/clone-missing.stderr
index ff1e28bf9611d..4ab1aae4934bf 100644
--- a/tests/ui/copy-a-resource.stderr
+++ b/tests/ui/methods/clone-missing.stderr
@@ -1,5 +1,5 @@
error[E0599]: no method named `clone` found for struct `Foo` in the current scope
- --> $DIR/copy-a-resource.rs:18:16
+ --> $DIR/clone-missing.rs:17:16
|
LL | struct Foo {
| ---------- method `clone` not found for this struct
diff --git a/tests/ui/modules/mod-pub-access.rs b/tests/ui/modules/mod-pub-access.rs
new file mode 100644
index 0000000000000..c07e7a2ff3062
--- /dev/null
+++ b/tests/ui/modules/mod-pub-access.rs
@@ -0,0 +1,11 @@
+//@ run-pass
+// This is a name resolution smoke test that ensures paths with more than one
+// segment (e.g., `foo::bar`) resolve correctly.
+// It also serves as a basic visibility test — confirming that a `pub` item
+// inside a private module can still be accessed from outside that module.
+
+mod foo {
+ pub fn bar(_offset: usize) {}
+}
+
+fn main() { foo::bar(0); }
diff --git a/tests/ui/path.rs b/tests/ui/path.rs
deleted file mode 100644
index bd7b99ac01ad5..0000000000000
--- a/tests/ui/path.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-//@ run-pass
-
-mod foo {
- pub fn bar(_offset: usize) { }
-}
-
-pub fn main() { foo::bar(0); }
diff --git a/tests/ui/capture1.rs b/tests/ui/resolve/fn-item-cant-capture-dynamic-env.rs
similarity index 100%
rename from tests/ui/capture1.rs
rename to tests/ui/resolve/fn-item-cant-capture-dynamic-env.rs
diff --git a/tests/ui/capture1.stderr b/tests/ui/resolve/fn-item-cant-capture-dynamic-env.stderr
similarity index 85%
rename from tests/ui/capture1.stderr
rename to tests/ui/resolve/fn-item-cant-capture-dynamic-env.stderr
index 8027430de522b..6b3e879201158 100644
--- a/tests/ui/capture1.stderr
+++ b/tests/ui/resolve/fn-item-cant-capture-dynamic-env.stderr
@@ -1,5 +1,5 @@
error[E0434]: can't capture dynamic environment in a fn item
- --> $DIR/capture1.rs:3:32
+ --> $DIR/fn-item-cant-capture-dynamic-env.rs:3:32
|
LL | fn foo() -> isize { return bar; }
| ^^^
diff --git a/tests/ui/type-alias/type-param.rs b/tests/ui/type-alias/type-param.rs
new file mode 100644
index 0000000000000..f8e73518bad6a
--- /dev/null
+++ b/tests/ui/type-alias/type-param.rs
@@ -0,0 +1,11 @@
+//@ run-pass
+// This is a smoke test to ensure that type aliases with type parameters
+// are accepted by the compiler and that the parameters are correctly
+// resolved in the aliased item type.
+
+#![allow(dead_code)]
+
+type Foo<T> = extern "C" fn(T) -> bool;
+type Bar<T> = fn(T) -> bool;
+
+fn main() {}
diff --git a/tests/ui/type-param.rs b/tests/ui/type-param.rs
deleted file mode 100644
index e7cf0e5446bcf..0000000000000
--- a/tests/ui/type-param.rs
+++ /dev/null
@@ -1,10 +0,0 @@
-//@ run-pass
-
-#![allow(non_camel_case_types)]
-#![allow(dead_code)]
-
-
-
-type lteq<T> = extern "C" fn(T) -> bool;
-
-pub fn main() { }
| diff --git a/tests/ui/copy-a-resource.rs b/tests/ui/copy-a-resource.rs
index 55f2dd4ee6dde..0000000000000
--- a/tests/ui/copy-a-resource.rs
@@ -1,21 +0,0 @@
-#[derive(Debug)]
-struct Foo {
- i: isize,
-impl Drop for Foo {
- fn drop(&mut self) {}
-fn foo(i:isize) -> Foo {
- Foo {
- i: i
- }
-fn main() {
- let x = foo(10);
- let _y = x.clone();
- //~^ ERROR no method named `clone` found
- println!("{:?}", x);
diff --git a/tests/ui/fail-simple.rs b/tests/ui/macros/no-matching-rule.rs
rename from tests/ui/fail-simple.rs
rename to tests/ui/macros/no-matching-rule.rs
diff --git a/tests/ui/fail-simple.stderr b/tests/ui/macros/no-matching-rule.stderr
rename from tests/ui/fail-simple.stderr
rename to tests/ui/macros/no-matching-rule.stderr
index 50c350b3ef55e..a6312a843f398 100644
--- a/tests/ui/fail-simple.stderr
+++ b/tests/ui/macros/no-matching-rule.stderr
error: no rules expected `@`
- --> $DIR/fail-simple.rs:2:12
+ --> $DIR/no-matching-rule.rs:2:12
LL | panic!(@);
| ^ no rules expected this token in macro call
diff --git a/tests/ui/methods/clone-missing.rs b/tests/ui/methods/clone-missing.rs
index 0000000000000..f2e4ad268c63a
+++ b/tests/ui/methods/clone-missing.rs
@@ -0,0 +1,19 @@
+// This test checks that calling `.clone()` on a type that does not implement the `Clone` trait
+// results in a compilation error. The `Foo` struct does not derive or implement `Clone`,
+// so attempting to clone it should fail.
+struct Foo {
+ i: isize,
+fn foo(i:isize) -> Foo {
+ Foo {
+ i: i
+ }
+fn main() {
+ let x = foo(10);
+ let _y = x.clone();
+ //~^ ERROR no method named `clone` found
diff --git a/tests/ui/copy-a-resource.stderr b/tests/ui/methods/clone-missing.stderr
similarity index 94%
rename from tests/ui/copy-a-resource.stderr
rename to tests/ui/methods/clone-missing.stderr
index ff1e28bf9611d..4ab1aae4934bf 100644
--- a/tests/ui/copy-a-resource.stderr
+++ b/tests/ui/methods/clone-missing.stderr
error[E0599]: no method named `clone` found for struct `Foo` in the current scope
- --> $DIR/copy-a-resource.rs:18:16
+ --> $DIR/clone-missing.rs:17:16
LL | struct Foo {
| ---------- method `clone` not found for this struct
diff --git a/tests/ui/modules/mod-pub-access.rs b/tests/ui/modules/mod-pub-access.rs
index 0000000000000..c07e7a2ff3062
+++ b/tests/ui/modules/mod-pub-access.rs
+// This is a name resolution smoke test that ensures paths with more than one
+// segment (e.g., `foo::bar`) resolve correctly.
+// inside a private module can still be accessed from outside that module.
+mod foo {
+ pub fn bar(_offset: usize) {}
+fn main() { foo::bar(0); }
diff --git a/tests/ui/path.rs b/tests/ui/path.rs
index bd7b99ac01ad5..0000000000000
--- a/tests/ui/path.rs
@@ -1,7 +0,0 @@
-mod foo {
- pub fn bar(_offset: usize) { }
-pub fn main() { foo::bar(0); }
diff --git a/tests/ui/capture1.rs b/tests/ui/resolve/fn-item-cant-capture-dynamic-env.rs
rename from tests/ui/capture1.rs
rename to tests/ui/resolve/fn-item-cant-capture-dynamic-env.rs
diff --git a/tests/ui/capture1.stderr b/tests/ui/resolve/fn-item-cant-capture-dynamic-env.stderr
rename from tests/ui/capture1.stderr
rename to tests/ui/resolve/fn-item-cant-capture-dynamic-env.stderr
index 8027430de522b..6b3e879201158 100644
--- a/tests/ui/capture1.stderr
+++ b/tests/ui/resolve/fn-item-cant-capture-dynamic-env.stderr
error[E0434]: can't capture dynamic environment in a fn item
- --> $DIR/capture1.rs:3:32
+ --> $DIR/fn-item-cant-capture-dynamic-env.rs:3:32
LL | fn foo() -> isize { return bar; }
| ^^^
diff --git a/tests/ui/type-alias/type-param.rs b/tests/ui/type-alias/type-param.rs
index 0000000000000..f8e73518bad6a
+++ b/tests/ui/type-alias/type-param.rs
+// This is a smoke test to ensure that type aliases with type parameters
+// are accepted by the compiler and that the parameters are correctly
+// resolved in the aliased item type.
+#![allow(dead_code)]
+type Foo<T> = extern "C" fn(T) -> bool;
+type Bar<T> = fn(T) -> bool;
+fn main() {}
diff --git a/tests/ui/type-param.rs b/tests/ui/type-param.rs
index e7cf0e5446bcf..0000000000000
--- a/tests/ui/type-param.rs
@@ -1,10 +0,0 @@
-#![allow(non_camel_case_types)]
-#![allow(dead_code)]
-pub fn main() { } | [
"+// It also serves as a basic visibility test — confirming that a `pub` item",
"-type lteq<T> = extern \"C\" fn(T) -> bool;"
] | [
93,
162
] | {
"additions": 44,
"author": "reddevilmidzy",
"deletions": 41,
"html_url": "https://github.com/rust-lang/rust/pull/140205",
"issue_id": 140205,
"merged_at": "2025-04-25T21:57:13Z",
"omission_probability": 0.1,
"pr_number": 140205,
"repo": "rust-lang/rust",
"title": "Tidying up UI tests [2/N]",
"total_changes": 85
} |
102 | diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs
index cfc71a412bea2..7a27bc5c38738 100644
--- a/compiler/rustc_passes/src/check_attr.rs
+++ b/compiler/rustc_passes/src/check_attr.rs
@@ -680,10 +680,14 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
}
if !other_attr.has_any_name(ALLOW_LIST) {
+ let path = other_attr.path();
+ let path: Vec<_> = path.iter().map(|s| s.as_str()).collect();
+ let other_attr_name = path.join("::");
+
self.dcx().emit_err(errors::NakedFunctionIncompatibleAttribute {
span: other_attr.span(),
naked_span: attr.span(),
- attr: other_attr.name().unwrap(),
+ attr: other_attr_name,
});
return;
diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs
index 4052264b05174..b1b4b9ee92765 100644
--- a/compiler/rustc_passes/src/errors.rs
+++ b/compiler/rustc_passes/src/errors.rs
@@ -1249,7 +1249,7 @@ pub(crate) struct NakedFunctionIncompatibleAttribute {
pub span: Span,
#[label(passes_naked_attribute)]
pub naked_span: Span,
- pub attr: Symbol,
+ pub attr: String,
}
#[derive(Diagnostic)]
diff --git a/tests/ui/asm/naked-invalid-attr.rs b/tests/ui/asm/naked-invalid-attr.rs
index c3a3131ee463c..6ac9cb9e3a9c5 100644
--- a/tests/ui/asm/naked-invalid-attr.rs
+++ b/tests/ui/asm/naked-invalid-attr.rs
@@ -51,3 +51,12 @@ fn main() {
#[unsafe(naked)] //~ ERROR should be applied to a function definition
|| {};
}
+
+// Check that the path of an attribute without a name is printed correctly (issue #140082)
+#[::a]
+//~^ ERROR attribute incompatible with `#[unsafe(naked)]`
+//~| ERROR failed to resolve: use of unresolved module or unlinked crate `a`
+#[unsafe(naked)]
+extern "C" fn issue_140082() {
+ naked_asm!("")
+}
diff --git a/tests/ui/asm/naked-invalid-attr.stderr b/tests/ui/asm/naked-invalid-attr.stderr
index 81d30e6475d95..ef389e7d921b9 100644
--- a/tests/ui/asm/naked-invalid-attr.stderr
+++ b/tests/ui/asm/naked-invalid-attr.stderr
@@ -1,3 +1,9 @@
+error[E0433]: failed to resolve: use of unresolved module or unlinked crate `a`
+ --> $DIR/naked-invalid-attr.rs:56:5
+ |
+LL | #[::a]
+ | ^ use of unresolved module or unlinked crate `a`
+
error: attribute should be applied to a function definition
--> $DIR/naked-invalid-attr.rs:13:1
|
@@ -27,6 +33,15 @@ LL | #[unsafe(naked)]
LL | || {};
| ----- not a function definition
+error[E0736]: attribute incompatible with `#[unsafe(naked)]`
+ --> $DIR/naked-invalid-attr.rs:56:1
+ |
+LL | #[::a]
+ | ^^^^^^ the `{{root}}::a` attribute is incompatible with `#[unsafe(naked)]`
+...
+LL | #[unsafe(naked)]
+ | ---------------- function marked with `#[unsafe(naked)]` here
+
error: attribute should be applied to a function definition
--> $DIR/naked-invalid-attr.rs:22:5
|
@@ -49,5 +64,7 @@ error: attribute should be applied to a function definition
LL | #![unsafe(naked)]
| ^^^^^^^^^^^^^^^^^ cannot be applied to crates
-error: aborting due to 6 previous errors
+error: aborting due to 8 previous errors
+Some errors have detailed explanations: E0433, E0736.
+For more information about an error, try `rustc --explain E0433`.
| diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs
index cfc71a412bea2..7a27bc5c38738 100644
--- a/compiler/rustc_passes/src/check_attr.rs
+++ b/compiler/rustc_passes/src/check_attr.rs
@@ -680,10 +680,14 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
}
if !other_attr.has_any_name(ALLOW_LIST) {
+ let path = other_attr.path();
+ let path: Vec<_> = path.iter().map(|s| s.as_str()).collect();
+ let other_attr_name = path.join("::");
self.dcx().emit_err(errors::NakedFunctionIncompatibleAttribute {
span: other_attr.span(),
naked_span: attr.span(),
- attr: other_attr.name().unwrap(),
+ attr: other_attr_name,
});
return;
diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs
index 4052264b05174..b1b4b9ee92765 100644
--- a/compiler/rustc_passes/src/errors.rs
+++ b/compiler/rustc_passes/src/errors.rs
@@ -1249,7 +1249,7 @@ pub(crate) struct NakedFunctionIncompatibleAttribute {
pub span: Span,
#[label(passes_naked_attribute)]
pub naked_span: Span,
- pub attr: Symbol,
+ pub attr: String,
#[derive(Diagnostic)]
diff --git a/tests/ui/asm/naked-invalid-attr.rs b/tests/ui/asm/naked-invalid-attr.rs
index c3a3131ee463c..6ac9cb9e3a9c5 100644
--- a/tests/ui/asm/naked-invalid-attr.rs
+++ b/tests/ui/asm/naked-invalid-attr.rs
@@ -51,3 +51,12 @@ fn main() {
#[unsafe(naked)] //~ ERROR should be applied to a function definition
|| {};
+// Check that the path of an attribute without a name is printed correctly (issue #140082)
+#[::a]
+//~^ ERROR attribute incompatible with `#[unsafe(naked)]`
+//~| ERROR failed to resolve: use of unresolved module or unlinked crate `a`
+extern "C" fn issue_140082() {
+ naked_asm!("")
+}
diff --git a/tests/ui/asm/naked-invalid-attr.stderr b/tests/ui/asm/naked-invalid-attr.stderr
index 81d30e6475d95..ef389e7d921b9 100644
--- a/tests/ui/asm/naked-invalid-attr.stderr
+++ b/tests/ui/asm/naked-invalid-attr.stderr
@@ -1,3 +1,9 @@
+error[E0433]: failed to resolve: use of unresolved module or unlinked crate `a`
+ --> $DIR/naked-invalid-attr.rs:56:5
+ | ^ use of unresolved module or unlinked crate `a`
--> $DIR/naked-invalid-attr.rs:13:1
@@ -27,6 +33,15 @@ LL | #[unsafe(naked)]
LL | || {};
| ----- not a function definition
+ --> $DIR/naked-invalid-attr.rs:56:1
+ | ^^^^^^ the `{{root}}::a` attribute is incompatible with `#[unsafe(naked)]`
+...
+LL | #[unsafe(naked)]
+ | ---------------- function marked with `#[unsafe(naked)]` here
--> $DIR/naked-invalid-attr.rs:22:5
@@ -49,5 +64,7 @@ error: attribute should be applied to a function definition
LL | #![unsafe(naked)]
| ^^^^^^^^^^^^^^^^^ cannot be applied to crates
-error: aborting due to 6 previous errors
+error: aborting due to 8 previous errors
+Some errors have detailed explanations: E0433, E0736.
+For more information about an error, try `rustc --explain E0433`. | [
"+#[unsafe(naked)]",
"+error[E0736]: attribute incompatible with `#[unsafe(naked)]`"
] | [
46,
68
] | {
"additions": 33,
"author": "folkertdev",
"deletions": 3,
"html_url": "https://github.com/rust-lang/rust/pull/140193",
"issue_id": 140193,
"merged_at": "2025-04-25T21:57:13Z",
"omission_probability": 0.1,
"pr_number": 140193,
"repo": "rust-lang/rust",
"title": "fix ICE in `#[naked]` attribute validation",
"total_changes": 36
} |
103 | diff --git a/library/core/src/result.rs b/library/core/src/result.rs
index 48ab9267f216c..736ffb7d0caf3 100644
--- a/library/core/src/result.rs
+++ b/library/core/src/result.rs
@@ -259,8 +259,14 @@
//! The [`is_ok`] and [`is_err`] methods return [`true`] if the [`Result`]
//! is [`Ok`] or [`Err`], respectively.
//!
+//! The [`is_ok_and`] and [`is_err_and`] methods apply the provided function
+//! to the contents of the [`Result`] to produce a boolean value. If the [`Result`] does not have the expected variant
+//! then [`false`] is returned instead without executing the function.
+//!
//! [`is_err`]: Result::is_err
//! [`is_ok`]: Result::is_ok
+//! [`is_ok_and`]: Result::is_ok_and
+//! [`is_err_and`]: Result::is_err_and
//!
//! ## Adapters for working with references
//!
@@ -287,6 +293,7 @@
//! (which must implement the [`Default`] trait)
//! * [`unwrap_or_else`] returns the result of evaluating the provided
//! function
+//! * [`unwrap_unchecked`] produces *[undefined behavior]*
//!
//! The panicking methods [`expect`] and [`unwrap`] require `E` to
//! implement the [`Debug`] trait.
@@ -297,6 +304,8 @@
//! [`unwrap_or`]: Result::unwrap_or
//! [`unwrap_or_default`]: Result::unwrap_or_default
//! [`unwrap_or_else`]: Result::unwrap_or_else
+//! [`unwrap_unchecked`]: Result::unwrap_unchecked
+//! [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
//!
//! These methods extract the contained value in a [`Result<T, E>`] when it
//! is the [`Err`] variant. They require `T` to implement the [`Debug`]
@@ -304,10 +313,13 @@
//!
//! * [`expect_err`] panics with a provided custom message
//! * [`unwrap_err`] panics with a generic message
+//! * [`unwrap_err_unchecked`] produces *[undefined behavior]*
//!
//! [`Debug`]: crate::fmt::Debug
//! [`expect_err`]: Result::expect_err
//! [`unwrap_err`]: Result::unwrap_err
+//! [`unwrap_err_unchecked`]: Result::unwrap_err_unchecked
+//! [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
//!
//! ## Transforming contained values
//!
@@ -330,21 +342,29 @@
//! [`Some(v)`]: Option::Some
//! [`transpose`]: Result::transpose
//!
-//! This method transforms the contained value of the [`Ok`] variant:
+//! These methods transform the contained value of the [`Ok`] variant:
//!
//! * [`map`] transforms [`Result<T, E>`] into [`Result<U, E>`] by applying
//! the provided function to the contained value of [`Ok`] and leaving
//! [`Err`] values unchanged
+//! * [`inspect`] takes ownership of the [`Result`], applies the
+//! provided function to the contained value by reference,
+//! and then returns the [`Result`]
//!
//! [`map`]: Result::map
+//! [`inspect`]: Result::inspect
//!
-//! This method transforms the contained value of the [`Err`] variant:
+//! These methods transform the contained value of the [`Err`] variant:
//!
//! * [`map_err`] transforms [`Result<T, E>`] into [`Result<T, F>`] by
//! applying the provided function to the contained value of [`Err`] and
//! leaving [`Ok`] values unchanged
+//! * [`inspect_err`] takes ownership of the [`Result`], applies the
+//! provided function to the contained value of [`Err`] by reference,
+//! and then returns the [`Result`]
//!
//! [`map_err`]: Result::map_err
+//! [`inspect_err`]: Result::inspect_err
//!
//! These methods transform a [`Result<T, E>`] into a value of a possibly
//! different type `U`:
@@ -578,6 +598,10 @@ impl<T, E> Result<T, E> {
///
/// let x: Result<u32, &str> = Err("hey");
/// assert_eq!(x.is_ok_and(|x| x > 1), false);
+ ///
+ /// let x: Result<String, &str> = Ok("ownership".to_string());
+ /// assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true);
+ /// println!("still alive {:?}", x);
/// ```
#[must_use]
#[inline]
@@ -623,6 +647,10 @@ impl<T, E> Result<T, E> {
///
/// let x: Result<u32, Error> = Ok(123);
/// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
+ ///
+ /// let x: Result<u32, String> = Err("ownership".to_string());
+ /// assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true);
+ /// println!("still alive {:?}", x);
/// ```
#[must_use]
#[inline]
| diff --git a/library/core/src/result.rs b/library/core/src/result.rs
index 48ab9267f216c..736ffb7d0caf3 100644
--- a/library/core/src/result.rs
+++ b/library/core/src/result.rs
@@ -259,8 +259,14 @@
//! The [`is_ok`] and [`is_err`] methods return [`true`] if the [`Result`]
//! is [`Ok`] or [`Err`], respectively.
+//! The [`is_ok_and`] and [`is_err_and`] methods apply the provided function
+//! to the contents of the [`Result`] to produce a boolean value. If the [`Result`] does not have the expected variant
+//! then [`false`] is returned instead without executing the function.
+//!
//! [`is_err`]: Result::is_err
//! [`is_ok`]: Result::is_ok
+//! [`is_ok_and`]: Result::is_ok_and
+//! [`is_err_and`]: Result::is_err_and
//! ## Adapters for working with references
@@ -287,6 +293,7 @@
//! (which must implement the [`Default`] trait)
//! * [`unwrap_or_else`] returns the result of evaluating the provided
//! function
+//! * [`unwrap_unchecked`] produces *[undefined behavior]*
//! The panicking methods [`expect`] and [`unwrap`] require `E` to
//! implement the [`Debug`] trait.
@@ -297,6 +304,8 @@
//! [`unwrap_or`]: Result::unwrap_or
//! [`unwrap_or_default`]: Result::unwrap_or_default
//! [`unwrap_or_else`]: Result::unwrap_or_else
+//! [`unwrap_unchecked`]: Result::unwrap_unchecked
//! These methods extract the contained value in a [`Result<T, E>`] when it
//! is the [`Err`] variant. They require `T` to implement the [`Debug`]
@@ -304,10 +313,13 @@
//! * [`expect_err`] panics with a provided custom message
//! * [`unwrap_err`] panics with a generic message
+//! * [`unwrap_err_unchecked`] produces *[undefined behavior]*
//! [`Debug`]: crate::fmt::Debug
//! [`expect_err`]: Result::expect_err
//! [`unwrap_err`]: Result::unwrap_err
+//! [`unwrap_err_unchecked`]: Result::unwrap_err_unchecked
//! ## Transforming contained values
@@ -330,21 +342,29 @@
//! [`Some(v)`]: Option::Some
//! [`transpose`]: Result::transpose
-//! This method transforms the contained value of the [`Ok`] variant:
+//! These methods transform the contained value of the [`Ok`] variant:
//! * [`map`] transforms [`Result<T, E>`] into [`Result<U, E>`] by applying
//! the provided function to the contained value of [`Ok`] and leaving
//! [`Err`] values unchanged
+//! * [`inspect`] takes ownership of the [`Result`], applies the
+//! provided function to the contained value by reference,
//! [`map`]: Result::map
+//! [`inspect`]: Result::inspect
+//! These methods transform the contained value of the [`Err`] variant:
//! * [`map_err`] transforms [`Result<T, E>`] into [`Result<T, F>`] by
//! applying the provided function to the contained value of [`Err`] and
//! leaving [`Ok`] values unchanged
+//! * [`inspect_err`] takes ownership of the [`Result`], applies the
+//! provided function to the contained value of [`Err`] by reference,
//! [`map_err`]: Result::map_err
+//! [`inspect_err`]: Result::inspect_err
//! These methods transform a [`Result<T, E>`] into a value of a possibly
//! different type `U`:
@@ -578,6 +598,10 @@ impl<T, E> Result<T, E> {
/// let x: Result<u32, &str> = Err("hey");
/// assert_eq!(x.is_ok_and(|x| x > 1), false);
+ /// let x: Result<String, &str> = Ok("ownership".to_string());
@@ -623,6 +647,10 @@ impl<T, E> Result<T, E> {
/// let x: Result<u32, Error> = Ok(123);
/// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
+ /// assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); | [
"-//! This method transforms the contained value of the [`Err`] variant:",
"+ /// assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true);",
"+ /// let x: Result<u32, String> = Err(\"ownership\".to_string());"
] | [
67,
88,
98
] | {
"additions": 30,
"author": "Natural-selection1",
"deletions": 2,
"html_url": "https://github.com/rust-lang/rust/pull/138968",
"issue_id": 138968,
"merged_at": "2025-04-25T21:57:13Z",
"omission_probability": 0.1,
"pr_number": 138968,
"repo": "rust-lang/rust",
"title": "Update the index of Result to make the summary more comprehensive",
"total_changes": 32
} |
104 | diff --git a/src/gcc b/src/gcc
index 13cc8243226a9..0ea98a1365b81 160000
--- a/src/gcc
+++ b/src/gcc
@@ -1 +1 @@
-Subproject commit 13cc8243226a9028bb08ab6c5e1c5fe6d533bcdf
+Subproject commit 0ea98a1365b81f7488073512c850e8ee951a4afd
diff --git a/src/tools/tidy/src/gcc_submodule.rs b/src/tools/tidy/src/gcc_submodule.rs
new file mode 100644
index 0000000000000..952ebe9e0cffe
--- /dev/null
+++ b/src/tools/tidy/src/gcc_submodule.rs
@@ -0,0 +1,47 @@
+//! Tidy check to ensure that the commit SHA of the `src/gcc` submodule is the same as the
+//! required GCC version of the GCC codegen backend.
+
+use std::path::Path;
+use std::process::Command;
+
+pub fn check(root_path: &Path, compiler_path: &Path, bad: &mut bool) {
+ let cg_gcc_version_path = compiler_path.join("rustc_codegen_gcc/libgccjit.version");
+ let cg_gcc_version = std::fs::read_to_string(&cg_gcc_version_path)
+ .expect(&format!("Cannot read GCC version from {}", cg_gcc_version_path.display()))
+ .trim()
+ .to_string();
+
+ let git_output = Command::new("git")
+ .current_dir(root_path)
+ .arg("submodule")
+ .arg("status")
+ // --cached asks for the version that is actually committed in the repository, not the one
+ // that is currently checked out.
+ .arg("--cached")
+ .arg("src/gcc")
+ .output()
+ .expect("Cannot determine git SHA of the src/gcc checkout");
+
+ // This can return e.g.
+ // -e607be166673a8de9fc07f6f02c60426e556c5f2 src/gcc
+ // e607be166673a8de9fc07f6f02c60426e556c5f2 src/gcc (master-e607be166673a8de9fc07f6f02c60426e556c5f2.e607be)
+ // +e607be166673a8de9fc07f6f02c60426e556c5f2 src/gcc (master-e607be166673a8de9fc07f6f02c60426e556c5f2.e607be)
+ let git_output = String::from_utf8_lossy(&git_output.stdout)
+ .trim()
+ .split_whitespace()
+ .next()
+ .unwrap_or_default()
+ .to_string();
+
+ // The SHA can start with + if the submodule is modified or - if it is not checked out.
+ let gcc_submodule_sha = git_output.trim_start_matches(&['+', '-']);
+ if gcc_submodule_sha != cg_gcc_version {
+ *bad = true;
+ eprintln!(
+ r#"Commit SHA of the src/gcc submodule (`{gcc_submodule_sha}`) does not match the required GCC version of the GCC codegen backend (`{cg_gcc_version}`).
+Make sure to set the src/gcc submodule to commit {cg_gcc_version}.
+The GCC codegen backend commit is configured at {}."#,
+ cg_gcc_version_path.display(),
+ );
+ }
+}
diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs
index 66856f5247bfd..ca45f8bb84ba9 100644
--- a/src/tools/tidy/src/lib.rs
+++ b/src/tools/tidy/src/lib.rs
@@ -75,6 +75,7 @@ pub mod features;
pub mod fluent_alphabetical;
pub mod fluent_period;
mod fluent_used;
+pub mod gcc_submodule;
pub(crate) mod iter_header;
pub mod known_bug;
pub mod mir_opt_tests;
diff --git a/src/tools/tidy/src/main.rs b/src/tools/tidy/src/main.rs
index 4078d462f5584..48122129b0174 100644
--- a/src/tools/tidy/src/main.rs
+++ b/src/tools/tidy/src/main.rs
@@ -116,6 +116,7 @@ fn main() {
check!(fluent_alphabetical, &compiler_path, bless);
check!(fluent_period, &compiler_path);
check!(target_policy, &root_path);
+ check!(gcc_submodule, &root_path, &compiler_path);
// Checks that only make sense for the std libs.
check!(pal, &library_path);
| diff --git a/src/gcc b/src/gcc
index 13cc8243226a9..0ea98a1365b81 160000
--- a/src/gcc
+++ b/src/gcc
@@ -1 +1 @@
-Subproject commit 13cc8243226a9028bb08ab6c5e1c5fe6d533bcdf
+Subproject commit 0ea98a1365b81f7488073512c850e8ee951a4afd
diff --git a/src/tools/tidy/src/gcc_submodule.rs b/src/tools/tidy/src/gcc_submodule.rs
new file mode 100644
index 0000000000000..952ebe9e0cffe
--- /dev/null
+++ b/src/tools/tidy/src/gcc_submodule.rs
@@ -0,0 +1,47 @@
+//! required GCC version of the GCC codegen backend.
+use std::path::Path;
+use std::process::Command;
+pub fn check(root_path: &Path, compiler_path: &Path, bad: &mut bool) {
+ let cg_gcc_version_path = compiler_path.join("rustc_codegen_gcc/libgccjit.version");
+ let cg_gcc_version = std::fs::read_to_string(&cg_gcc_version_path)
+ .expect(&format!("Cannot read GCC version from {}", cg_gcc_version_path.display()))
+ let git_output = Command::new("git")
+ .current_dir(root_path)
+ .arg("submodule")
+ .arg("status")
+ // --cached asks for the version that is actually committed in the repository, not the one
+ // that is currently checked out.
+ .arg("src/gcc")
+ .output()
+ .expect("Cannot determine git SHA of the src/gcc checkout");
+ // This can return e.g.
+ // -e607be166673a8de9fc07f6f02c60426e556c5f2 src/gcc
+ // e607be166673a8de9fc07f6f02c60426e556c5f2 src/gcc (master-e607be166673a8de9fc07f6f02c60426e556c5f2.e607be)
+ // +e607be166673a8de9fc07f6f02c60426e556c5f2 src/gcc (master-e607be166673a8de9fc07f6f02c60426e556c5f2.e607be)
+ let git_output = String::from_utf8_lossy(&git_output.stdout)
+ .split_whitespace()
+ .next()
+ .unwrap_or_default()
+ let gcc_submodule_sha = git_output.trim_start_matches(&['+', '-']);
+ if gcc_submodule_sha != cg_gcc_version {
+ *bad = true;
+ eprintln!(
+ r#"Commit SHA of the src/gcc submodule (`{gcc_submodule_sha}`) does not match the required GCC version of the GCC codegen backend (`{cg_gcc_version}`).
+Make sure to set the src/gcc submodule to commit {cg_gcc_version}.
+The GCC codegen backend commit is configured at {}."#,
+ );
+}
diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs
index 66856f5247bfd..ca45f8bb84ba9 100644
--- a/src/tools/tidy/src/lib.rs
+++ b/src/tools/tidy/src/lib.rs
@@ -75,6 +75,7 @@ pub mod features;
pub mod fluent_alphabetical;
pub mod fluent_period;
mod fluent_used;
+pub mod gcc_submodule;
pub(crate) mod iter_header;
pub mod known_bug;
pub mod mir_opt_tests;
diff --git a/src/tools/tidy/src/main.rs b/src/tools/tidy/src/main.rs
index 4078d462f5584..48122129b0174 100644
--- a/src/tools/tidy/src/main.rs
+++ b/src/tools/tidy/src/main.rs
@@ -116,6 +116,7 @@ fn main() {
check!(fluent_alphabetical, &compiler_path, bless);
check!(fluent_period, &compiler_path);
check!(target_policy, &root_path);
+ check!(gcc_submodule, &root_path, &compiler_path);
// Checks that only make sense for the std libs.
check!(pal, &library_path); | [
"+//! Tidy check to ensure that the commit SHA of the `src/gcc` submodule is the same as the",
"+ .arg(\"--cached\")",
"+ // The SHA can start with + if the submodule is modified or - if it is not checked out.",
"+ cg_gcc_version_path.display(),",
"+ }"
] | [
13,
32,
48,
56,
58
] | {
"additions": 50,
"author": "Kobzol",
"deletions": 1,
"html_url": "https://github.com/rust-lang/rust/pull/137683",
"issue_id": 137683,
"merged_at": "2025-04-25T21:57:13Z",
"omission_probability": 0.1,
"pr_number": 137683,
"repo": "rust-lang/rust",
"title": "Add a tidy check for GCC submodule version",
"total_changes": 51
} |
105 | diff --git a/library/core/src/iter/adapters/enumerate.rs b/library/core/src/iter/adapters/enumerate.rs
index bd093e279c38e..f7b9f0b7a5e9d 100644
--- a/library/core/src/iter/adapters/enumerate.rs
+++ b/library/core/src/iter/adapters/enumerate.rs
@@ -23,6 +23,39 @@ impl<I> Enumerate<I> {
pub(in crate::iter) fn new(iter: I) -> Enumerate<I> {
Enumerate { iter, count: 0 }
}
+
+ /// Retrieve the current position of the iterator.
+ ///
+ /// If the iterator has not advanced, the position returned will be 0.
+ ///
+ /// The position may also exceed the bounds of the iterator to allow for calculating
+ /// the displacement of the iterator from following calls to [`Iterator::next`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(next_index)]
+ ///
+ /// let arr = ['a', 'b'];
+ ///
+ /// let mut iter = arr.iter().enumerate();
+ ///
+ /// assert_eq!(iter.next_index(), 0);
+ /// assert_eq!(iter.next(), Some((0, &'a')));
+ ///
+ /// assert_eq!(iter.next_index(), 1);
+ /// assert_eq!(iter.next_index(), 1);
+ /// assert_eq!(iter.next(), Some((1, &'b')));
+ ///
+ /// assert_eq!(iter.next_index(), 2);
+ /// assert_eq!(iter.next(), None);
+ /// assert_eq!(iter.next_index(), 2);
+ /// ```
+ #[inline]
+ #[unstable(feature = "next_index", issue = "130711")]
+ pub fn next_index(&self) -> usize {
+ self.count
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
diff --git a/library/coretests/tests/iter/adapters/enumerate.rs b/library/coretests/tests/iter/adapters/enumerate.rs
index b57d51c077e9b..2294f856b58d6 100644
--- a/library/coretests/tests/iter/adapters/enumerate.rs
+++ b/library/coretests/tests/iter/adapters/enumerate.rs
@@ -120,3 +120,13 @@ fn test_double_ended_enumerate() {
assert_eq!(it.next_back(), Some((2, 3)));
assert_eq!(it.next(), None);
}
+
+#[test]
+fn test_empty_iterator_enumerate_next_index() {
+ let mut it = empty::<i32>().enumerate();
+ assert_eq!(it.next_index(), 0);
+ assert_eq!(it.next_index(), 0);
+ assert_eq!(it.next(), None);
+ assert_eq!(it.next_index(), 0);
+ assert_eq!(it.next_index(), 0);
+}
diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs
index 1c43bfe0ed4a9..ac11157593832 100644
--- a/library/coretests/tests/lib.rs
+++ b/library/coretests/tests/lib.rs
@@ -63,6 +63,7 @@
#![feature(maybe_uninit_write_slice)]
#![feature(min_specialization)]
#![feature(never_type)]
+#![feature(next_index)]
#![feature(numfmt)]
#![feature(pattern)]
#![feature(pointer_is_aligned_to)]
| diff --git a/library/core/src/iter/adapters/enumerate.rs b/library/core/src/iter/adapters/enumerate.rs
index bd093e279c38e..f7b9f0b7a5e9d 100644
--- a/library/core/src/iter/adapters/enumerate.rs
+++ b/library/core/src/iter/adapters/enumerate.rs
@@ -23,6 +23,39 @@ impl<I> Enumerate<I> {
pub(in crate::iter) fn new(iter: I) -> Enumerate<I> {
Enumerate { iter, count: 0 }
}
+ /// Retrieve the current position of the iterator.
+ /// If the iterator has not advanced, the position returned will be 0.
+ /// the displacement of the iterator from following calls to [`Iterator::next`].
+ /// # Examples
+ /// #![feature(next_index)]
+ /// let arr = ['a', 'b'];
+ /// let mut iter = arr.iter().enumerate();
+ /// assert_eq!(iter.next_index(), 0);
+ /// assert_eq!(iter.next(), Some((0, &'a')));
+ /// assert_eq!(iter.next(), None);
+ #[inline]
+ #[unstable(feature = "next_index", issue = "130711")]
+ pub fn next_index(&self) -> usize {
+ }
#[stable(feature = "rust1", since = "1.0.0")]
diff --git a/library/coretests/tests/iter/adapters/enumerate.rs b/library/coretests/tests/iter/adapters/enumerate.rs
index b57d51c077e9b..2294f856b58d6 100644
--- a/library/coretests/tests/iter/adapters/enumerate.rs
+++ b/library/coretests/tests/iter/adapters/enumerate.rs
@@ -120,3 +120,13 @@ fn test_double_ended_enumerate() {
assert_eq!(it.next_back(), Some((2, 3)));
assert_eq!(it.next(), None);
+ let mut it = empty::<i32>().enumerate();
+ assert_eq!(it.next(), None);
+}
diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs
index 1c43bfe0ed4a9..ac11157593832 100644
--- a/library/coretests/tests/lib.rs
+++ b/library/coretests/tests/lib.rs
@@ -63,6 +63,7 @@
#![feature(maybe_uninit_write_slice)]
#![feature(min_specialization)]
#![feature(never_type)]
+#![feature(next_index)]
#![feature(numfmt)]
#![feature(pattern)]
#![feature(pointer_is_aligned_to)] | [
"+ /// The position may also exceed the bounds of the iterator to allow for calculating",
"+ /// assert_eq!(iter.next(), Some((1, &'b')));",
"+ self.count",
"+#[test]",
"+fn test_empty_iterator_enumerate_next_index() {"
] | [
13,
30,
39,
53,
54
] | {
"additions": 44,
"author": "jogru0",
"deletions": 0,
"html_url": "https://github.com/rust-lang/rust/pull/139533",
"issue_id": 139533,
"merged_at": "2025-04-20T00:08:55Z",
"omission_probability": 0.1,
"pr_number": 139533,
"repo": "rust-lang/rust",
"title": "add next_index to Enumerate",
"total_changes": 44
} |
106 | diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs
index 1532ca77f713e..8986430141be4 100644
--- a/compiler/rustc_ast/src/ast.rs
+++ b/compiler/rustc_ast/src/ast.rs
@@ -1927,7 +1927,7 @@ impl AttrArgs {
}
/// Delimited arguments, as used in `#[attr()/[]/{}]` or `mac!()/[]/{}`.
-#[derive(Clone, Encodable, Decodable, Debug)]
+#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
pub struct DelimArgs {
pub dspan: DelimSpan,
pub delim: Delimiter, // Note: `Delimiter::Invisible` never occurs
@@ -1942,18 +1942,6 @@ impl DelimArgs {
}
}
-impl<CTX> HashStable<CTX> for DelimArgs
-where
- CTX: crate::HashStableContext,
-{
- fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
- let DelimArgs { dspan, delim, tokens } = self;
- dspan.hash_stable(ctx, hasher);
- delim.hash_stable(ctx, hasher);
- tokens.hash_stable(ctx, hasher);
- }
-}
-
/// Represents a macro definition.
#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
pub struct MacroDef {
diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index c40987541f4a5..d23cf6cb2f1de 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -916,7 +916,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
}
fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
- DelimArgs { dspan: args.dspan, delim: args.delim, tokens: args.tokens.clone() }
+ args.clone()
}
/// Lower an associated item constraint.
diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs
index 63597b37cb5ee..55c3df003fe16 100644
--- a/compiler/rustc_attr_parsing/src/context.rs
+++ b/compiler/rustc_attr_parsing/src/context.rs
@@ -3,7 +3,7 @@ use std::collections::BTreeMap;
use std::ops::Deref;
use std::sync::LazyLock;
-use rustc_ast::{self as ast, DelimArgs};
+use rustc_ast as ast;
use rustc_attr_data_structures::AttributeKind;
use rustc_errors::{DiagCtxtHandle, Diagnostic};
use rustc_feature::Features;
@@ -315,11 +315,7 @@ impl<'sess> AttributeParser<'sess> {
fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs {
match args {
ast::AttrArgs::Empty => AttrArgs::Empty,
- ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(DelimArgs {
- dspan: args.dspan,
- delim: args.delim,
- tokens: args.tokens.clone(),
- }),
+ ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(args.clone()),
// This is an inert key-value attribute - it will never be visible to macros
// after it gets lowered to HIR. Therefore, we can extract literals to handle
// nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
| diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs
index 1532ca77f713e..8986430141be4 100644
--- a/compiler/rustc_ast/src/ast.rs
+++ b/compiler/rustc_ast/src/ast.rs
@@ -1927,7 +1927,7 @@ impl AttrArgs {
/// Delimited arguments, as used in `#[attr()/[]/{}]` or `mac!()/[]/{}`.
-#[derive(Clone, Encodable, Decodable, Debug)]
+#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
pub struct DelimArgs {
pub dspan: DelimSpan,
pub delim: Delimiter, // Note: `Delimiter::Invisible` never occurs
@@ -1942,18 +1942,6 @@ impl DelimArgs {
-impl<CTX> HashStable<CTX> for DelimArgs
-where
- CTX: crate::HashStableContext,
-{
- fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
- let DelimArgs { dspan, delim, tokens } = self;
- dspan.hash_stable(ctx, hasher);
- delim.hash_stable(ctx, hasher);
- tokens.hash_stable(ctx, hasher);
- }
/// Represents a macro definition.
#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
pub struct MacroDef {
diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index c40987541f4a5..d23cf6cb2f1de 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -916,7 +916,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
- DelimArgs { dspan: args.dspan, delim: args.delim, tokens: args.tokens.clone() }
+ args.clone()
/// Lower an associated item constraint.
diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs
index 63597b37cb5ee..55c3df003fe16 100644
--- a/compiler/rustc_attr_parsing/src/context.rs
+++ b/compiler/rustc_attr_parsing/src/context.rs
@@ -3,7 +3,7 @@ use std::collections::BTreeMap;
use std::ops::Deref;
use std::sync::LazyLock;
-use rustc_ast::{self as ast, DelimArgs};
+use rustc_ast as ast;
use rustc_attr_data_structures::AttributeKind;
use rustc_errors::{DiagCtxtHandle, Diagnostic};
use rustc_feature::Features;
@@ -315,11 +315,7 @@ impl<'sess> AttributeParser<'sess> {
fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs {
match args {
ast::AttrArgs::Empty => AttrArgs::Empty,
- ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(DelimArgs {
- delim: args.delim,
- tokens: args.tokens.clone(),
- }),
+ ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(args.clone()),
// This is an inert key-value attribute - it will never be visible to macros
// after it gets lowered to HIR. Therefore, we can extract literals to handle
// nonterminals in `#[doc]` (e.g. `#[doc = $e]`). | [
"-}",
"-",
"- dspan: args.dspan,"
] | [
27,
28,
63
] | {
"additions": 4,
"author": "nnethercote",
"deletions": 20,
"html_url": "https://github.com/rust-lang/rust/pull/140229",
"issue_id": 140229,
"merged_at": "2025-04-25T12:26:12Z",
"omission_probability": 0.1,
"pr_number": 140229,
"repo": "rust-lang/rust",
"title": "`DelimArgs` tweaks",
"total_changes": 24
} |
107 | diff --git a/compiler/rustc_target/src/spec/base/cygwin.rs b/compiler/rustc_target/src/spec/base/cygwin.rs
new file mode 100644
index 0000000000000..fe3efb3f46ba0
--- /dev/null
+++ b/compiler/rustc_target/src/spec/base/cygwin.rs
@@ -0,0 +1,46 @@
+use std::borrow::Cow;
+
+use crate::spec::{Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions, cvs};
+
+pub(crate) fn opts() -> TargetOptions {
+ let mut pre_link_args = TargetOptions::link_args(
+ LinkerFlavor::Gnu(Cc::No, Lld::No),
+ &["--disable-dynamicbase", "--enable-auto-image-base"],
+ );
+ crate::spec::add_link_args(
+ &mut pre_link_args,
+ LinkerFlavor::Gnu(Cc::Yes, Lld::No),
+ &["-Wl,--disable-dynamicbase", "-Wl,--enable-auto-image-base"],
+ );
+ let cygwin_libs = &["-lcygwin", "-lgcc", "-lcygwin", "-luser32", "-lkernel32", "-lgcc_s"];
+ let mut late_link_args =
+ TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), cygwin_libs);
+ crate::spec::add_link_args(
+ &mut late_link_args,
+ LinkerFlavor::Gnu(Cc::Yes, Lld::No),
+ cygwin_libs,
+ );
+ TargetOptions {
+ os: "cygwin".into(),
+ vendor: "pc".into(),
+ // FIXME(#13846) this should be enabled for cygwin
+ function_sections: false,
+ linker: Some("gcc".into()),
+ dynamic_linking: true,
+ dll_prefix: "".into(),
+ dll_suffix: ".dll".into(),
+ exe_suffix: ".exe".into(),
+ families: cvs!["unix"],
+ is_like_windows: true,
+ allows_weak_linkage: false,
+ pre_link_args,
+ late_link_args,
+ abi_return_struct_as_int: true,
+ emit_debug_gdb_scripts: false,
+ requires_uwtable: true,
+ eh_frame_header: false,
+ debuginfo_kind: DebuginfoKind::Dwarf,
+ supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
+ ..Default::default()
+ }
+}
diff --git a/compiler/rustc_target/src/spec/base/mod.rs b/compiler/rustc_target/src/spec/base/mod.rs
index 28d10dcf2ff3a..b9139c8452c5f 100644
--- a/compiler/rustc_target/src/spec/base/mod.rs
+++ b/compiler/rustc_target/src/spec/base/mod.rs
@@ -3,6 +3,7 @@ pub(crate) mod android;
pub(crate) mod apple;
pub(crate) mod avr_gnu;
pub(crate) mod bpf;
+pub(crate) mod cygwin;
pub(crate) mod dragonfly;
pub(crate) mod freebsd;
pub(crate) mod fuchsia;
diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs
index df1862ec27eee..91154edbd0092 100644
--- a/compiler/rustc_target/src/spec/mod.rs
+++ b/compiler/rustc_target/src/spec/mod.rs
@@ -2020,6 +2020,7 @@ supported_targets! {
("riscv64imac-unknown-nuttx-elf", riscv64imac_unknown_nuttx_elf),
("riscv64gc-unknown-nuttx-elf", riscv64gc_unknown_nuttx_elf),
+ ("x86_64-pc-cygwin", x86_64_pc_cygwin),
}
/// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
@@ -3001,8 +3002,8 @@ impl Target {
);
check_eq!(
self.is_like_windows,
- self.os == "windows" || self.os == "uefi",
- "`is_like_windows` must be set if and only if `os` is `windows` or `uefi`"
+ self.os == "windows" || self.os == "uefi" || self.os == "cygwin",
+ "`is_like_windows` must be set if and only if `os` is `windows`, `uefi` or `cygwin`"
);
check_eq!(
self.is_like_wasm,
diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs
new file mode 100644
index 0000000000000..8da4fe6b8b152
--- /dev/null
+++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs
@@ -0,0 +1,24 @@
+use crate::spec::{Cc, LinkerFlavor, Lld, Target, base};
+
+pub(crate) fn target() -> Target {
+ let mut base = base::cygwin::opts();
+ base.cpu = "x86-64".into();
+ base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &["-m", "i386pep"]);
+ base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64"]);
+ base.max_atomic_width = Some(64);
+ base.linker = Some("x86_64-pc-cygwin-gcc".into());
+ Target {
+ llvm_target: "x86_64-pc-cygwin".into(),
+ pointer_width: 64,
+ data_layout:
+ "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128".into(),
+ arch: "x86_64".into(),
+ options: base,
+ metadata: crate::spec::TargetMetadata {
+ description: Some("64-bit x86 Cygwin".into()),
+ tier: Some(3),
+ host_tools: Some(false),
+ std: None,
+ },
+ }
+}
diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs
index 2ecab262413fa..dc1ef7ce245cf 100644
--- a/src/bootstrap/src/core/builder/cargo.rs
+++ b/src/bootstrap/src/core/builder/cargo.rs
@@ -245,7 +245,11 @@ impl Cargo {
// flesh out rpath support more fully in the future.
self.rustflags.arg("-Zosx-rpath-install-name");
Some(format!("-Wl,-rpath,@loader_path/../{libdir}"))
- } else if !target.is_windows() && !target.contains("aix") && !target.contains("xous") {
+ } else if !target.is_windows()
+ && !target.contains("cygwin")
+ && !target.contains("aix")
+ && !target.contains("xous")
+ {
self.rustflags.arg("-Clink-args=-Wl,-z,origin");
Some(format!("-Wl,-rpath,$ORIGIN/../{libdir}"))
} else {
diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md
index f78d3d4aee830..6c7cdec348024 100644
--- a/src/doc/rustc/src/SUMMARY.md
+++ b/src/doc/rustc/src/SUMMARY.md
@@ -102,6 +102,7 @@
- [\*-win7-windows-gnu](platform-support/win7-windows-gnu.md)
- [\*-win7-windows-msvc](platform-support/win7-windows-msvc.md)
- [x86_64-fortanix-unknown-sgx](platform-support/x86_64-fortanix-unknown-sgx.md)
+ - [x86_64-pc-cygwin](platform-support/x86_64-pc-cygwin.md)
- [x86_64-pc-solaris](platform-support/solaris.md)
- [x86_64-unknown-linux-none.md](platform-support/x86_64-unknown-linux-none.md)
- [x86_64-unknown-none](platform-support/x86_64-unknown-none.md)
diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md
index bb89d97a7984d..8b0f9f8b22968 100644
--- a/src/doc/rustc/src/platform-support.md
+++ b/src/doc/rustc/src/platform-support.md
@@ -407,6 +407,7 @@ target | std | host | notes
[`wasm64-unknown-unknown`](platform-support/wasm64-unknown-unknown.md) | ? | | WebAssembly
[`x86_64-apple-tvos`](platform-support/apple-tvos.md) | ✓ | | x86 64-bit tvOS
[`x86_64-apple-watchos-sim`](platform-support/apple-watchos.md) | ✓ | | x86 64-bit Apple WatchOS simulator
+[`x86_64-pc-cygwin`](platform-support/x86_64-pc-cygwin.md) | ? | | 64-bit x86 Cygwin |
[`x86_64-pc-nto-qnx710`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS with default network stack (io-pkt) |
[`x86_64-pc-nto-qnx710_iosock`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS with new network stack (io-sock) |
[`x86_64-pc-nto-qnx800`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 8.0 RTOS |
diff --git a/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md b/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md
new file mode 100644
index 0000000000000..a8fc4f181d8ad
--- /dev/null
+++ b/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md
@@ -0,0 +1,39 @@
+# `x86_64-pc-cygwin`
+
+**Tier: 3**
+
+Windows targets supporting Cygwin.
+The `*-cygwin` targets are **not** intended as native target for applications,
+a developer writing Windows applications should use the `*-pc-windows-*` targets instead, which are *native* Windows.
+
+Cygwin is only intended as an emulation layer for Unix-only programs which do not support the native Windows targets.
+
+## Target maintainers
+
+- [Berrysoft](https://github.com/Berrysoft)
+
+## Requirements
+
+This target is cross compiled. It needs `x86_64-pc-cygwin-gcc` as linker.
+
+The `target_os` of the target is `cygwin`, and it is `unix`.
+
+## Building the target
+
+For cross-compilation you want LLVM with [llvm/llvm-project#121439 (merged)](https://github.com/llvm/llvm-project/pull/121439) applied to fix the LLVM codegen on importing external global variables from DLLs.
+No native builds on Cygwin now. It should be possible theoretically though, but might need a lot of patches.
+
+## Building Rust programs
+
+Rust does not yet ship pre-compiled artifacts for this target. To compile for
+this target, you will either need to build Rust with the target enabled (see
+"Building the target" above), or build your own copy of `core` by using
+`build-std` or similar.
+
+## Testing
+
+Created binaries work fine on Windows with Cygwin.
+
+## Cross-compilation toolchains and C code
+
+Compatible C code can be built with GCC shipped with Cygwin. Clang is untested.
diff --git a/tests/assembly/targets/targets-pe.rs b/tests/assembly/targets/targets-pe.rs
index ab74de5c8ec42..1fa4dc821dd37 100644
--- a/tests/assembly/targets/targets-pe.rs
+++ b/tests/assembly/targets/targets-pe.rs
@@ -84,6 +84,9 @@
//@ revisions: x86_64_win7_windows_msvc
//@ [x86_64_win7_windows_msvc] compile-flags: --target x86_64-win7-windows-msvc
//@ [x86_64_win7_windows_msvc] needs-llvm-components: x86
+//@ revisions: x86_64_pc_cygwin
+//@ [x86_64_pc_cygwin] compile-flags: --target x86_64-pc-cygwin
+//@ [x86_64_pc_cygwin] needs-llvm-components: x86
// Sanity-check that each target can produce assembly code.
diff --git a/tests/ui/check-cfg/well-known-values.stderr b/tests/ui/check-cfg/well-known-values.stderr
index 6421cb8f2c2e7..ba1900fcddb2d 100644
--- a/tests/ui/check-cfg/well-known-values.stderr
+++ b/tests/ui/check-cfg/well-known-values.stderr
@@ -201,7 +201,7 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE`
LL | target_os = "_UNEXPECTED_VALUE",
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
- = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm`
+ = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm`
= note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration
warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE`
@@ -274,7 +274,7 @@ LL | #[cfg(target_os = "linuz")] // testing that we suggest `linux`
| |
| help: there is a expected value with a similar name: `"linux"`
|
- = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm`
+ = note: expected values for `target_os` are: `aix`, `amdhsa`, `android`, `cuda`, `cygwin`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `psx`, `redox`, `rtems`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm`
= note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration
warning: 28 warnings emitted
| diff --git a/compiler/rustc_target/src/spec/base/cygwin.rs b/compiler/rustc_target/src/spec/base/cygwin.rs
index 0000000000000..fe3efb3f46ba0
+++ b/compiler/rustc_target/src/spec/base/cygwin.rs
@@ -0,0 +1,46 @@
+use crate::spec::{Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions, cvs};
+pub(crate) fn opts() -> TargetOptions {
+ let mut pre_link_args = TargetOptions::link_args(
+ LinkerFlavor::Gnu(Cc::No, Lld::No),
+ &["--disable-dynamicbase", "--enable-auto-image-base"],
+ &["-Wl,--disable-dynamicbase", "-Wl,--enable-auto-image-base"],
+ let cygwin_libs = &["-lcygwin", "-lgcc", "-lcygwin", "-luser32", "-lkernel32", "-lgcc_s"];
+ let mut late_link_args =
+ TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), cygwin_libs);
+ &mut late_link_args,
+ TargetOptions {
+ os: "cygwin".into(),
+ vendor: "pc".into(),
+ // FIXME(#13846) this should be enabled for cygwin
+ function_sections: false,
+ linker: Some("gcc".into()),
+ dynamic_linking: true,
+ dll_prefix: "".into(),
+ dll_suffix: ".dll".into(),
+ exe_suffix: ".exe".into(),
+ families: cvs!["unix"],
+ is_like_windows: true,
+ allows_weak_linkage: false,
+ pre_link_args,
+ late_link_args,
+ abi_return_struct_as_int: true,
+ emit_debug_gdb_scripts: false,
+ requires_uwtable: true,
+ eh_frame_header: false,
+ debuginfo_kind: DebuginfoKind::Dwarf,
+ supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
+ ..Default::default()
diff --git a/compiler/rustc_target/src/spec/base/mod.rs b/compiler/rustc_target/src/spec/base/mod.rs
index 28d10dcf2ff3a..b9139c8452c5f 100644
--- a/compiler/rustc_target/src/spec/base/mod.rs
+++ b/compiler/rustc_target/src/spec/base/mod.rs
@@ -3,6 +3,7 @@ pub(crate) mod android;
pub(crate) mod apple;
pub(crate) mod avr_gnu;
pub(crate) mod bpf;
+pub(crate) mod cygwin;
pub(crate) mod dragonfly;
pub(crate) mod freebsd;
pub(crate) mod fuchsia;
diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs
index df1862ec27eee..91154edbd0092 100644
--- a/compiler/rustc_target/src/spec/mod.rs
+++ b/compiler/rustc_target/src/spec/mod.rs
@@ -2020,6 +2020,7 @@ supported_targets! {
("riscv64imac-unknown-nuttx-elf", riscv64imac_unknown_nuttx_elf),
("riscv64gc-unknown-nuttx-elf", riscv64gc_unknown_nuttx_elf),
+ ("x86_64-pc-cygwin", x86_64_pc_cygwin),
}
/// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
@@ -3001,8 +3002,8 @@ impl Target {
self.is_like_windows,
- "`is_like_windows` must be set if and only if `os` is `windows` or `uefi`"
+ self.os == "windows" || self.os == "uefi" || self.os == "cygwin",
+ "`is_like_windows` must be set if and only if `os` is `windows`, `uefi` or `cygwin`"
self.is_like_wasm,
diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs
index 0000000000000..8da4fe6b8b152
+++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_cygwin.rs
@@ -0,0 +1,24 @@
+use crate::spec::{Cc, LinkerFlavor, Lld, Target, base};
+pub(crate) fn target() -> Target {
+ let mut base = base::cygwin::opts();
+ base.cpu = "x86-64".into();
+ base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &["-m", "i386pep"]);
+ base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64"]);
+ base.max_atomic_width = Some(64);
+ base.linker = Some("x86_64-pc-cygwin-gcc".into());
+ Target {
+ llvm_target: "x86_64-pc-cygwin".into(),
+ pointer_width: 64,
+ "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128".into(),
+ arch: "x86_64".into(),
+ options: base,
+ metadata: crate::spec::TargetMetadata {
+ tier: Some(3),
+ host_tools: Some(false),
+ std: None,
+ },
diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs
index 2ecab262413fa..dc1ef7ce245cf 100644
--- a/src/bootstrap/src/core/builder/cargo.rs
+++ b/src/bootstrap/src/core/builder/cargo.rs
@@ -245,7 +245,11 @@ impl Cargo {
// flesh out rpath support more fully in the future.
self.rustflags.arg("-Zosx-rpath-install-name");
Some(format!("-Wl,-rpath,@loader_path/../{libdir}"))
- } else if !target.is_windows() && !target.contains("aix") && !target.contains("xous") {
+ } else if !target.is_windows()
+ && !target.contains("aix")
+ && !target.contains("xous")
+ {
self.rustflags.arg("-Clink-args=-Wl,-z,origin");
Some(format!("-Wl,-rpath,$ORIGIN/../{libdir}"))
} else {
diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md
index f78d3d4aee830..6c7cdec348024 100644
--- a/src/doc/rustc/src/SUMMARY.md
+++ b/src/doc/rustc/src/SUMMARY.md
@@ -102,6 +102,7 @@
- [\*-win7-windows-gnu](platform-support/win7-windows-gnu.md)
- [\*-win7-windows-msvc](platform-support/win7-windows-msvc.md)
- [x86_64-fortanix-unknown-sgx](platform-support/x86_64-fortanix-unknown-sgx.md)
+ - [x86_64-pc-cygwin](platform-support/x86_64-pc-cygwin.md)
- [x86_64-pc-solaris](platform-support/solaris.md)
- [x86_64-unknown-linux-none.md](platform-support/x86_64-unknown-linux-none.md)
- [x86_64-unknown-none](platform-support/x86_64-unknown-none.md)
diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md
index bb89d97a7984d..8b0f9f8b22968 100644
--- a/src/doc/rustc/src/platform-support.md
+++ b/src/doc/rustc/src/platform-support.md
@@ -407,6 +407,7 @@ target | std | host | notes
[`wasm64-unknown-unknown`](platform-support/wasm64-unknown-unknown.md) | ? | | WebAssembly
[`x86_64-apple-tvos`](platform-support/apple-tvos.md) | ✓ | | x86 64-bit tvOS
[`x86_64-apple-watchos-sim`](platform-support/apple-watchos.md) | ✓ | | x86 64-bit Apple WatchOS simulator
+[`x86_64-pc-cygwin`](platform-support/x86_64-pc-cygwin.md) | ? | | 64-bit x86 Cygwin |
[`x86_64-pc-nto-qnx710`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS with default network stack (io-pkt) |
[`x86_64-pc-nto-qnx710_iosock`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS with new network stack (io-sock) |
[`x86_64-pc-nto-qnx800`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 8.0 RTOS |
diff --git a/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md b/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md
index 0000000000000..a8fc4f181d8ad
+++ b/src/doc/rustc/src/platform-support/x86_64-pc-cygwin.md
@@ -0,0 +1,39 @@
+**Tier: 3**
+Windows targets supporting Cygwin.
+The `*-cygwin` targets are **not** intended as native target for applications,
+a developer writing Windows applications should use the `*-pc-windows-*` targets instead, which are *native* Windows.
+Cygwin is only intended as an emulation layer for Unix-only programs which do not support the native Windows targets.
+- [Berrysoft](https://github.com/Berrysoft)
+## Requirements
+This target is cross compiled. It needs `x86_64-pc-cygwin-gcc` as linker.
+The `target_os` of the target is `cygwin`, and it is `unix`.
+For cross-compilation you want LLVM with [llvm/llvm-project#121439 (merged)](https://github.com/llvm/llvm-project/pull/121439) applied to fix the LLVM codegen on importing external global variables from DLLs.
+No native builds on Cygwin now. It should be possible theoretically though, but might need a lot of patches.
+## Building Rust programs
+Rust does not yet ship pre-compiled artifacts for this target. To compile for
+this target, you will either need to build Rust with the target enabled (see
+"Building the target" above), or build your own copy of `core` by using
+`build-std` or similar.
+Created binaries work fine on Windows with Cygwin.
+## Cross-compilation toolchains and C code
+Compatible C code can be built with GCC shipped with Cygwin. Clang is untested.
diff --git a/tests/assembly/targets/targets-pe.rs b/tests/assembly/targets/targets-pe.rs
index ab74de5c8ec42..1fa4dc821dd37 100644
--- a/tests/assembly/targets/targets-pe.rs
+++ b/tests/assembly/targets/targets-pe.rs
@@ -84,6 +84,9 @@
//@ revisions: x86_64_win7_windows_msvc
//@ [x86_64_win7_windows_msvc] compile-flags: --target x86_64-win7-windows-msvc
//@ [x86_64_win7_windows_msvc] needs-llvm-components: x86
+//@ revisions: x86_64_pc_cygwin
+//@ [x86_64_pc_cygwin] compile-flags: --target x86_64-pc-cygwin
+//@ [x86_64_pc_cygwin] needs-llvm-components: x86
// Sanity-check that each target can produce assembly code.
diff --git a/tests/ui/check-cfg/well-known-values.stderr b/tests/ui/check-cfg/well-known-values.stderr
index 6421cb8f2c2e7..ba1900fcddb2d 100644
--- a/tests/ui/check-cfg/well-known-values.stderr
+++ b/tests/ui/check-cfg/well-known-values.stderr
@@ -201,7 +201,7 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE`
LL | target_os = "_UNEXPECTED_VALUE",
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE`
@@ -274,7 +274,7 @@ LL | #[cfg(target_os = "linuz")] // testing that we suggest `linux`
| |
| help: there is a expected value with a similar name: `"linux"`
warning: 28 warnings emitted | [
"+use std::borrow::Cow;",
"+ &mut pre_link_args,",
"+ cygwin_libs,",
"- self.os == \"windows\" || self.os == \"uefi\",",
"+ data_layout:",
"+ description: Some(\"64-bit x86 Cygwin\".into()),",
"+ && !target.contains(\"cygwin\")",
"+# `x86_64-pc-cygwin`",
"+## Target maintainers",
"+## Building the target",
"+## Testing"
] | [
6,
16,
26,
80,
105,
110,
127,
164,
174,
184,
196
] | {
"additions": 125,
"author": "Berrysoft",
"deletions": 5,
"html_url": "https://github.com/rust-lang/rust/pull/134999",
"issue_id": 134999,
"merged_at": "2025-02-13T14:38:35Z",
"omission_probability": 0.1,
"pr_number": 134999,
"repo": "rust-lang/rust",
"title": "Add cygwin target.",
"total_changes": 130
} |
108 | diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs
index 83f71aeed7204..97afcb6867cff 100644
--- a/src/bootstrap/src/core/build_steps/dist.rs
+++ b/src/bootstrap/src/core/build_steps/dist.rs
@@ -421,13 +421,13 @@ impl Step for Rustc {
builder.install(&rustdoc, &image.join("bin"), FileType::Executable);
}
+ let ra_proc_macro_srv_compiler =
+ builder.compiler_for(compiler.stage, builder.config.build, compiler.host);
+ builder.ensure(compile::Rustc::new(ra_proc_macro_srv_compiler, compiler.host));
+
if let Some(ra_proc_macro_srv) = builder.ensure_if_default(
tool::RustAnalyzerProcMacroSrv {
- compiler: builder.compiler_for(
- compiler.stage,
- builder.config.build,
- compiler.host,
- ),
+ compiler: ra_proc_macro_srv_compiler,
target: compiler.host,
},
builder.kind,
@@ -1177,6 +1177,8 @@ impl Step for Cargo {
let compiler = self.compiler;
let target = self.target;
+ builder.ensure(compile::Rustc::new(compiler, target));
+
let cargo = builder.ensure(tool::Cargo { compiler, target });
let src = builder.src.join("src/tools/cargo");
let etc = src.join("src/etc");
@@ -1231,6 +1233,8 @@ impl Step for RustAnalyzer {
let compiler = self.compiler;
let target = self.target;
+ builder.ensure(compile::Rustc::new(compiler, target));
+
let rust_analyzer = builder.ensure(tool::RustAnalyzer { compiler, target });
let mut tarball = Tarball::new(builder, "rust-analyzer", &target.triple);
@@ -1273,6 +1277,8 @@ impl Step for Clippy {
let compiler = self.compiler;
let target = self.target;
+ builder.ensure(compile::Rustc::new(compiler, target));
+
// Prepare the image directory
// We expect clippy to build, because we've exited this step above if tool
// state for clippy isn't testing.
@@ -1323,9 +1329,12 @@ impl Step for Miri {
if !builder.build.unstable_features() {
return None;
}
+
let compiler = self.compiler;
let target = self.target;
+ builder.ensure(compile::Rustc::new(compiler, target));
+
let miri = builder.ensure(tool::Miri { compiler, target });
let cargomiri = builder.ensure(tool::CargoMiri { compiler, target });
@@ -1462,6 +1471,8 @@ impl Step for Rustfmt {
let compiler = self.compiler;
let target = self.target;
+ builder.ensure(compile::Rustc::new(compiler, target));
+
let rustfmt = builder.ensure(tool::Rustfmt { compiler, target });
let cargofmt = builder.ensure(tool::Cargofmt { compiler, target });
let mut tarball = Tarball::new(builder, "rustfmt", &target.triple);
@@ -2327,6 +2338,8 @@ impl Step for LlvmBitcodeLinker {
let compiler = self.compiler;
let target = self.target;
+ builder.ensure(compile::Rustc::new(compiler, target));
+
let llbc_linker =
builder.ensure(tool::LlvmBitcodeLinker { compiler, target, extra_features: vec![] });
diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs
index fd3b28e4e6ab2..9a724ec34899c 100644
--- a/src/bootstrap/src/core/builder/tests.rs
+++ b/src/bootstrap/src/core/builder/tests.rs
@@ -408,6 +408,7 @@ mod dist {
use pretty_assertions::assert_eq;
use super::{Config, TEST_TRIPLE_1, TEST_TRIPLE_2, TEST_TRIPLE_3, first, run_build};
+ use crate::Flags;
use crate::core::builder::*;
fn configure(host: &[&str], target: &[&str]) -> Config {
@@ -646,6 +647,37 @@ mod dist {
);
}
+ /// This also serves as an important regression test for <https://github.com/rust-lang/rust/issues/138123>
+ /// and <https://github.com/rust-lang/rust/issues/138004>.
+ #[test]
+ fn dist_all_cross() {
+ let cmd_args =
+ &["dist", "--stage", "2", "--dry-run", "--config=/does/not/exist"].map(str::to_owned);
+ let config_str = r#"
+ [rust]
+ channel = "nightly"
+
+ [build]
+ extended = true
+
+ build = "i686-unknown-haiku"
+ host = ["i686-unknown-netbsd"]
+ target = ["i686-unknown-netbsd"]
+ "#;
+ let config = Config::parse_inner(Flags::parse(cmd_args), |&_| toml::from_str(config_str));
+ let mut cache = run_build(&[], config);
+
+ // Stage 2 `compile::Rustc` should **NEVER** be cached here.
+ assert_eq!(
+ first(cache.all::<compile::Rustc>()),
+ &[
+ rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0),
+ rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1),
+ rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_3, stage = 1),
+ ]
+ );
+ }
+
#[test]
fn build_all() {
let build = Build::new(configure(
| diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs
index 83f71aeed7204..97afcb6867cff 100644
--- a/src/bootstrap/src/core/build_steps/dist.rs
+++ b/src/bootstrap/src/core/build_steps/dist.rs
@@ -421,13 +421,13 @@ impl Step for Rustc {
builder.install(&rustdoc, &image.join("bin"), FileType::Executable);
}
+ let ra_proc_macro_srv_compiler =
+ builder.compiler_for(compiler.stage, builder.config.build, compiler.host);
+ builder.ensure(compile::Rustc::new(ra_proc_macro_srv_compiler, compiler.host));
if let Some(ra_proc_macro_srv) = builder.ensure_if_default(
tool::RustAnalyzerProcMacroSrv {
- compiler: builder.compiler_for(
- builder.config.build,
- compiler.host,
+ compiler: ra_proc_macro_srv_compiler,
target: compiler.host,
},
builder.kind,
@@ -1177,6 +1177,8 @@ impl Step for Cargo {
let cargo = builder.ensure(tool::Cargo { compiler, target });
let src = builder.src.join("src/tools/cargo");
let etc = src.join("src/etc");
@@ -1231,6 +1233,8 @@ impl Step for RustAnalyzer {
let rust_analyzer = builder.ensure(tool::RustAnalyzer { compiler, target });
let mut tarball = Tarball::new(builder, "rust-analyzer", &target.triple);
@@ -1273,6 +1277,8 @@ impl Step for Clippy {
// Prepare the image directory
// We expect clippy to build, because we've exited this step above if tool
// state for clippy isn't testing.
@@ -1323,9 +1329,12 @@ impl Step for Miri {
if !builder.build.unstable_features() {
return None;
}
let miri = builder.ensure(tool::Miri { compiler, target });
let cargomiri = builder.ensure(tool::CargoMiri { compiler, target });
@@ -1462,6 +1471,8 @@ impl Step for Rustfmt {
let rustfmt = builder.ensure(tool::Rustfmt { compiler, target });
let cargofmt = builder.ensure(tool::Cargofmt { compiler, target });
let mut tarball = Tarball::new(builder, "rustfmt", &target.triple);
@@ -2327,6 +2338,8 @@ impl Step for LlvmBitcodeLinker {
let llbc_linker =
builder.ensure(tool::LlvmBitcodeLinker { compiler, target, extra_features: vec![] });
diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs
index fd3b28e4e6ab2..9a724ec34899c 100644
--- a/src/bootstrap/src/core/builder/tests.rs
+++ b/src/bootstrap/src/core/builder/tests.rs
@@ -408,6 +408,7 @@ mod dist {
use pretty_assertions::assert_eq;
use super::{Config, TEST_TRIPLE_1, TEST_TRIPLE_2, TEST_TRIPLE_3, first, run_build};
+ use crate::Flags;
use crate::core::builder::*;
fn configure(host: &[&str], target: &[&str]) -> Config {
@@ -646,6 +647,37 @@ mod dist {
);
}
+ /// This also serves as an important regression test for <https://github.com/rust-lang/rust/issues/138123>
+ /// and <https://github.com/rust-lang/rust/issues/138004>.
+ #[test]
+ fn dist_all_cross() {
+ let cmd_args =
+ &["dist", "--stage", "2", "--dry-run", "--config=/does/not/exist"].map(str::to_owned);
+ let config_str = r#"
+ [rust]
+ channel = "nightly"
+ [build]
+ extended = true
+ build = "i686-unknown-haiku"
+ host = ["i686-unknown-netbsd"]
+ target = ["i686-unknown-netbsd"]
+ "#;
+ let config = Config::parse_inner(Flags::parse(cmd_args), |&_| toml::from_str(config_str));
+ let mut cache = run_build(&[], config);
+ // Stage 2 `compile::Rustc` should **NEVER** be cached here.
+ assert_eq!(
+ first(cache.all::<compile::Rustc>()),
+ rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0),
+ rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1),
+ rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_3, stage = 1),
+ ]
+ );
+ }
#[test]
fn build_all() {
let build = Build::new(configure( | [
"- compiler.stage,",
"- ),",
"+ &["
] | [
15,
18,
120
] | {
"additions": 50,
"author": "onur-ozkan",
"deletions": 5,
"html_url": "https://github.com/rust-lang/rust/pull/140006",
"issue_id": 140006,
"merged_at": "2025-04-25T15:37:57Z",
"omission_probability": 0.1,
"pr_number": 140006,
"repo": "rust-lang/rust",
"title": "ensure compiler existance of tools on the dist step",
"total_changes": 55
} |
109 | diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs
index 330b409876453..16c0c11804049 100644
--- a/library/core/src/macros/mod.rs
+++ b/library/core/src/macros/mod.rs
@@ -1138,6 +1138,10 @@ pub(crate) mod builtin {
issue = "29599",
reason = "`concat_idents` is not stable enough for use and is subject to change"
)]
+ #[deprecated(
+ since = "1.88.0",
+ note = "use `${concat(...)}` with the `macro_metavar_expr_concat` feature instead"
+ )]
#[rustc_builtin_macro]
#[macro_export]
macro_rules! concat_idents {
diff --git a/library/core/src/prelude/v1.rs b/library/core/src/prelude/v1.rs
index 8f1b5275871e6..9737d0baec7ca 100644
--- a/library/core/src/prelude/v1.rs
+++ b/library/core/src/prelude/v1.rs
@@ -59,6 +59,7 @@ pub use crate::hash::macros::Hash;
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow(deprecated)]
+#[cfg_attr(bootstrap, allow(deprecated_in_future))]
#[doc(no_inline)]
pub use crate::{
assert, cfg, column, compile_error, concat, concat_idents, env, file, format_args,
diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs
index 3a52b7790376c..f77bf92a806e3 100644
--- a/library/std/src/lib.rs
+++ b/library/std/src/lib.rs
@@ -709,6 +709,7 @@ pub use core::primitive;
// Re-export built-in macros defined through core.
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow(deprecated)]
+#[cfg_attr(bootstrap, allow(deprecated_in_future))]
pub use core::{
assert, assert_matches, cfg, column, compile_error, concat, concat_idents, const_format_args,
env, file, format_args, format_args_nl, include, include_bytes, include_str, line, log_syntax,
diff --git a/library/std/src/prelude/v1.rs b/library/std/src/prelude/v1.rs
index c15d8c40085a5..68c9ac1e41463 100644
--- a/library/std/src/prelude/v1.rs
+++ b/library/std/src/prelude/v1.rs
@@ -46,6 +46,7 @@ pub use crate::result::Result::{self, Err, Ok};
// Re-exported built-in macros
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow(deprecated)]
+#[cfg_attr(bootstrap, allow(deprecated_in_future))]
#[doc(no_inline)]
pub use core::prelude::v1::{
assert, cfg, column, compile_error, concat, concat_idents, env, file, format_args,
diff --git a/src/doc/unstable-book/src/library-features/concat-idents.md b/src/doc/unstable-book/src/library-features/concat-idents.md
index 4366172fb9965..8a38d155e3dbc 100644
--- a/src/doc/unstable-book/src/library-features/concat-idents.md
+++ b/src/doc/unstable-book/src/library-features/concat-idents.md
@@ -2,7 +2,10 @@
The tracking issue for this feature is: [#29599]
+This feature is deprecated, to be replaced by [`macro_metavar_expr_concat`].
+
[#29599]: https://github.com/rust-lang/rust/issues/29599
+[`macro_metavar_expr_concat`]: https://github.com/rust-lang/rust/issues/124225
------------------------
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents.rs b/tests/ui/feature-gates/feature-gate-concat_idents.rs
index 68caf3d71e907..4fc3b69159733 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents.rs
+++ b/tests/ui/feature-gates/feature-gate-concat_idents.rs
@@ -1,3 +1,5 @@
+#![expect(deprecated)] // concat_idents is deprecated
+
const XY_1: i32 = 10;
fn main() {
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents.stderr b/tests/ui/feature-gates/feature-gate-concat_idents.stderr
index d0f4fe62d048f..6399424eecd8b 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents.stderr
+++ b/tests/ui/feature-gates/feature-gate-concat_idents.stderr
@@ -1,5 +1,5 @@
error[E0658]: use of unstable library feature `concat_idents`: `concat_idents` is not stable enough for use and is subject to change
- --> $DIR/feature-gate-concat_idents.rs:5:13
+ --> $DIR/feature-gate-concat_idents.rs:7:13
|
LL | let a = concat_idents!(X, Y_1);
| ^^^^^^^^^^^^^
@@ -9,7 +9,7 @@ LL | let a = concat_idents!(X, Y_1);
= note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
error[E0658]: use of unstable library feature `concat_idents`: `concat_idents` is not stable enough for use and is subject to change
- --> $DIR/feature-gate-concat_idents.rs:6:13
+ --> $DIR/feature-gate-concat_idents.rs:8:13
|
LL | let b = concat_idents!(X, Y_2);
| ^^^^^^^^^^^^^
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents2.rs b/tests/ui/feature-gates/feature-gate-concat_idents2.rs
index 9660ffeafa518..bc2b4f7cddf99 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents2.rs
+++ b/tests/ui/feature-gates/feature-gate-concat_idents2.rs
@@ -1,3 +1,5 @@
+#![expect(deprecated)] // concat_idents is deprecated
+
fn main() {
concat_idents!(a, b); //~ ERROR `concat_idents` is not stable enough
//~| ERROR cannot find value `ab` in this scope
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents2.stderr b/tests/ui/feature-gates/feature-gate-concat_idents2.stderr
index b42a1d999e4d9..a770c1a348b5d 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents2.stderr
+++ b/tests/ui/feature-gates/feature-gate-concat_idents2.stderr
@@ -1,5 +1,5 @@
error[E0658]: use of unstable library feature `concat_idents`: `concat_idents` is not stable enough for use and is subject to change
- --> $DIR/feature-gate-concat_idents2.rs:2:5
+ --> $DIR/feature-gate-concat_idents2.rs:4:5
|
LL | concat_idents!(a, b);
| ^^^^^^^^^^^^^
@@ -9,7 +9,7 @@ LL | concat_idents!(a, b);
= note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
error[E0425]: cannot find value `ab` in this scope
- --> $DIR/feature-gate-concat_idents2.rs:2:5
+ --> $DIR/feature-gate-concat_idents2.rs:4:5
|
LL | concat_idents!(a, b);
| ^^^^^^^^^^^^^^^^^^^^ not found in this scope
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents3.rs b/tests/ui/feature-gates/feature-gate-concat_idents3.rs
index 81710fd9fb041..d4a0d2e6bb0e4 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents3.rs
+++ b/tests/ui/feature-gates/feature-gate-concat_idents3.rs
@@ -1,3 +1,5 @@
+#![expect(deprecated)] // concat_idents is deprecated
+
const XY_1: i32 = 10;
fn main() {
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents3.stderr b/tests/ui/feature-gates/feature-gate-concat_idents3.stderr
index b186601d0ed68..7d929322bc06e 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents3.stderr
+++ b/tests/ui/feature-gates/feature-gate-concat_idents3.stderr
@@ -1,5 +1,5 @@
error[E0658]: use of unstable library feature `concat_idents`: `concat_idents` is not stable enough for use and is subject to change
- --> $DIR/feature-gate-concat_idents3.rs:5:20
+ --> $DIR/feature-gate-concat_idents3.rs:7:20
|
LL | assert_eq!(10, concat_idents!(X, Y_1));
| ^^^^^^^^^^^^^
@@ -9,7 +9,7 @@ LL | assert_eq!(10, concat_idents!(X, Y_1));
= note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
error[E0658]: use of unstable library feature `concat_idents`: `concat_idents` is not stable enough for use and is subject to change
- --> $DIR/feature-gate-concat_idents3.rs:6:20
+ --> $DIR/feature-gate-concat_idents3.rs:8:20
|
LL | assert_eq!(20, concat_idents!(X, Y_2));
| ^^^^^^^^^^^^^
diff --git a/tests/ui/issues/issue-32950.rs b/tests/ui/issues/issue-32950.rs
index 27d68a11c1f16..b51ac2967768a 100644
--- a/tests/ui/issues/issue-32950.rs
+++ b/tests/ui/issues/issue-32950.rs
@@ -1,4 +1,5 @@
#![feature(concat_idents)]
+#![expect(deprecated)] // concat_idents is deprecated
#[derive(Debug)]
struct Baz<T>(
diff --git a/tests/ui/issues/issue-32950.stderr b/tests/ui/issues/issue-32950.stderr
index 3cdf35af1d866..38a82542f8964 100644
--- a/tests/ui/issues/issue-32950.stderr
+++ b/tests/ui/issues/issue-32950.stderr
@@ -1,11 +1,11 @@
error: `derive` cannot be used on items with type macros
- --> $DIR/issue-32950.rs:5:5
+ --> $DIR/issue-32950.rs:6:5
|
LL | concat_idents!(Foo, Bar)
| ^^^^^^^^^^^^^^^^^^^^^^^^
error[E0412]: cannot find type `FooBar` in this scope
- --> $DIR/issue-32950.rs:5:5
+ --> $DIR/issue-32950.rs:6:5
|
LL | concat_idents!(Foo, Bar)
| ^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope
diff --git a/tests/ui/issues/issue-50403.rs b/tests/ui/issues/issue-50403.rs
index ab22aff26d99c..f14958afc34dc 100644
--- a/tests/ui/issues/issue-50403.rs
+++ b/tests/ui/issues/issue-50403.rs
@@ -1,4 +1,5 @@
#![feature(concat_idents)]
+#![expect(deprecated)] // concat_idents is deprecated
fn main() {
let x = concat_idents!(); //~ ERROR `concat_idents!()` takes 1 or more arguments
diff --git a/tests/ui/issues/issue-50403.stderr b/tests/ui/issues/issue-50403.stderr
index 193d815d5195f..e7dd05bb0183d 100644
--- a/tests/ui/issues/issue-50403.stderr
+++ b/tests/ui/issues/issue-50403.stderr
@@ -1,5 +1,5 @@
error: `concat_idents!()` takes 1 or more arguments
- --> $DIR/issue-50403.rs:4:13
+ --> $DIR/issue-50403.rs:5:13
|
LL | let x = concat_idents!();
| ^^^^^^^^^^^^^^^^
diff --git a/tests/ui/macros/macros-nonfatal-errors.rs b/tests/ui/macros/macros-nonfatal-errors.rs
index 79beffbe986e3..091d64ea5d9eb 100644
--- a/tests/ui/macros/macros-nonfatal-errors.rs
+++ b/tests/ui/macros/macros-nonfatal-errors.rs
@@ -5,6 +5,7 @@
#![feature(trace_macros, concat_idents)]
#![feature(stmt_expr_attributes)]
+#![expect(deprecated)] // concat_idents is deprecated
use std::arch::asm;
diff --git a/tests/ui/macros/macros-nonfatal-errors.stderr b/tests/ui/macros/macros-nonfatal-errors.stderr
index 44194b506a43a..2f990cb24e2bf 100644
--- a/tests/ui/macros/macros-nonfatal-errors.stderr
+++ b/tests/ui/macros/macros-nonfatal-errors.stderr
@@ -1,5 +1,5 @@
error: the `#[default]` attribute may only be used on unit enum variants
- --> $DIR/macros-nonfatal-errors.rs:13:5
+ --> $DIR/macros-nonfatal-errors.rs:14:5
|
LL | #[default]
| ^^^^^^^^^^
@@ -7,7 +7,7 @@ LL | #[default]
= help: consider a manual implementation of `Default`
error: the `#[default]` attribute may only be used on unit enum variants
- --> $DIR/macros-nonfatal-errors.rs:18:36
+ --> $DIR/macros-nonfatal-errors.rs:19:36
|
LL | struct DefaultInnerAttrTupleStruct(#[default] ());
| ^^^^^^^^^^
@@ -15,7 +15,7 @@ LL | struct DefaultInnerAttrTupleStruct(#[default] ());
= help: consider a manual implementation of `Default`
error: the `#[default]` attribute may only be used on unit enum variants
- --> $DIR/macros-nonfatal-errors.rs:22:1
+ --> $DIR/macros-nonfatal-errors.rs:23:1
|
LL | #[default]
| ^^^^^^^^^^
@@ -23,7 +23,7 @@ LL | #[default]
= help: consider a manual implementation of `Default`
error: the `#[default]` attribute may only be used on unit enum variants
- --> $DIR/macros-nonfatal-errors.rs:26:1
+ --> $DIR/macros-nonfatal-errors.rs:27:1
|
LL | #[default]
| ^^^^^^^^^^
@@ -31,7 +31,7 @@ LL | #[default]
= help: consider a manual implementation of `Default`
error: the `#[default]` attribute may only be used on unit enum variants
- --> $DIR/macros-nonfatal-errors.rs:36:11
+ --> $DIR/macros-nonfatal-errors.rs:37:11
|
LL | Foo = #[default] 0,
| ^^^^^^^^^^
@@ -39,7 +39,7 @@ LL | Foo = #[default] 0,
= help: consider a manual implementation of `Default`
error: the `#[default]` attribute may only be used on unit enum variants
- --> $DIR/macros-nonfatal-errors.rs:37:14
+ --> $DIR/macros-nonfatal-errors.rs:38:14
|
LL | Bar([u8; #[default] 1]),
| ^^^^^^^^^^
@@ -47,7 +47,7 @@ LL | Bar([u8; #[default] 1]),
= help: consider a manual implementation of `Default`
error[E0665]: `#[derive(Default)]` on enum with no `#[default]`
- --> $DIR/macros-nonfatal-errors.rs:42:10
+ --> $DIR/macros-nonfatal-errors.rs:43:10
|
LL | #[derive(Default)]
| ^^^^^^^
@@ -67,7 +67,7 @@ LL | #[default] Bar,
| ++++++++++
error[E0665]: `#[derive(Default)]` on enum with no `#[default]`
- --> $DIR/macros-nonfatal-errors.rs:48:10
+ --> $DIR/macros-nonfatal-errors.rs:49:10
|
LL | #[derive(Default)]
| ^^^^^^^
@@ -78,7 +78,7 @@ LL | | }
| |_- this enum needs a unit variant marked with `#[default]`
error: multiple declared defaults
- --> $DIR/macros-nonfatal-errors.rs:54:10
+ --> $DIR/macros-nonfatal-errors.rs:55:10
|
LL | #[derive(Default)]
| ^^^^^^^
@@ -95,7 +95,7 @@ LL | Baz,
= note: only one variant can be default
error: `#[default]` attribute does not accept a value
- --> $DIR/macros-nonfatal-errors.rs:66:5
+ --> $DIR/macros-nonfatal-errors.rs:67:5
|
LL | #[default = 1]
| ^^^^^^^^^^^^^^
@@ -103,7 +103,7 @@ LL | #[default = 1]
= help: try using `#[default]`
error: multiple `#[default]` attributes
- --> $DIR/macros-nonfatal-errors.rs:74:5
+ --> $DIR/macros-nonfatal-errors.rs:75:5
|
LL | #[default]
| ---------- `#[default]` used here
@@ -114,13 +114,13 @@ LL | Foo,
|
= note: only one `#[default]` attribute is needed
help: try removing this
- --> $DIR/macros-nonfatal-errors.rs:73:5
+ --> $DIR/macros-nonfatal-errors.rs:74:5
|
LL | #[default]
| ^^^^^^^^^^
error: multiple `#[default]` attributes
- --> $DIR/macros-nonfatal-errors.rs:84:5
+ --> $DIR/macros-nonfatal-errors.rs:85:5
|
LL | #[default]
| ---------- `#[default]` used here
@@ -132,7 +132,7 @@ LL | Foo,
|
= note: only one `#[default]` attribute is needed
help: try removing these
- --> $DIR/macros-nonfatal-errors.rs:81:5
+ --> $DIR/macros-nonfatal-errors.rs:82:5
|
LL | #[default]
| ^^^^^^^^^^
@@ -142,7 +142,7 @@ LL | #[default]
| ^^^^^^^^^^
error: the `#[default]` attribute may only be used on unit enum variants
- --> $DIR/macros-nonfatal-errors.rs:91:5
+ --> $DIR/macros-nonfatal-errors.rs:92:5
|
LL | Foo {},
| ^^^
@@ -150,7 +150,7 @@ LL | Foo {},
= help: consider a manual implementation of `Default`
error: default variant must be exhaustive
- --> $DIR/macros-nonfatal-errors.rs:99:5
+ --> $DIR/macros-nonfatal-errors.rs:100:5
|
LL | #[non_exhaustive]
| ----------------- declared `#[non_exhaustive]` here
@@ -160,37 +160,37 @@ LL | Foo,
= help: consider a manual implementation of `Default`
error: asm template must be a string literal
- --> $DIR/macros-nonfatal-errors.rs:104:10
+ --> $DIR/macros-nonfatal-errors.rs:105:10
|
LL | asm!(invalid);
| ^^^^^^^
error: `concat_idents!()` requires ident args
- --> $DIR/macros-nonfatal-errors.rs:107:5
+ --> $DIR/macros-nonfatal-errors.rs:108:5
|
LL | concat_idents!("not", "idents");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: argument must be a string literal
- --> $DIR/macros-nonfatal-errors.rs:109:17
+ --> $DIR/macros-nonfatal-errors.rs:110:17
|
LL | option_env!(invalid);
| ^^^^^^^
error: expected string literal
- --> $DIR/macros-nonfatal-errors.rs:110:10
+ --> $DIR/macros-nonfatal-errors.rs:111:10
|
LL | env!(invalid);
| ^^^^^^^
error: `env!()` takes 1 or 2 arguments
- --> $DIR/macros-nonfatal-errors.rs:111:5
+ --> $DIR/macros-nonfatal-errors.rs:112:5
|
LL | env!(foo, abr, baz);
| ^^^^^^^^^^^^^^^^^^^
error: environment variable `RUST_HOPEFULLY_THIS_DOESNT_EXIST` not defined at compile time
- --> $DIR/macros-nonfatal-errors.rs:112:5
+ --> $DIR/macros-nonfatal-errors.rs:113:5
|
LL | env!("RUST_HOPEFULLY_THIS_DOESNT_EXIST");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -198,7 +198,7 @@ LL | env!("RUST_HOPEFULLY_THIS_DOESNT_EXIST");
= help: use `std::env::var("RUST_HOPEFULLY_THIS_DOESNT_EXIST")` to read the variable at run time
error: format argument must be a string literal
- --> $DIR/macros-nonfatal-errors.rs:114:13
+ --> $DIR/macros-nonfatal-errors.rs:115:13
|
LL | format!(invalid);
| ^^^^^^^
@@ -209,43 +209,43 @@ LL | format!("{}", invalid);
| +++++
error: argument must be a string literal
- --> $DIR/macros-nonfatal-errors.rs:116:14
+ --> $DIR/macros-nonfatal-errors.rs:117:14
|
LL | include!(invalid);
| ^^^^^^^
error: argument must be a string literal
- --> $DIR/macros-nonfatal-errors.rs:118:18
+ --> $DIR/macros-nonfatal-errors.rs:119:18
|
LL | include_str!(invalid);
| ^^^^^^^
error: couldn't read `$DIR/i'd be quite surprised if a file with this name existed`: $FILE_NOT_FOUND_MSG
- --> $DIR/macros-nonfatal-errors.rs:119:5
+ --> $DIR/macros-nonfatal-errors.rs:120:5
|
LL | include_str!("i'd be quite surprised if a file with this name existed");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: argument must be a string literal
- --> $DIR/macros-nonfatal-errors.rs:120:20
+ --> $DIR/macros-nonfatal-errors.rs:121:20
|
LL | include_bytes!(invalid);
| ^^^^^^^
error: couldn't read `$DIR/i'd be quite surprised if a file with this name existed`: $FILE_NOT_FOUND_MSG
- --> $DIR/macros-nonfatal-errors.rs:121:5
+ --> $DIR/macros-nonfatal-errors.rs:122:5
|
LL | include_bytes!("i'd be quite surprised if a file with this name existed");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: trace_macros! accepts only `true` or `false`
- --> $DIR/macros-nonfatal-errors.rs:123:5
+ --> $DIR/macros-nonfatal-errors.rs:124:5
|
LL | trace_macros!(invalid);
| ^^^^^^^^^^^^^^^^^^^^^^
error: default variant must be exhaustive
- --> $DIR/macros-nonfatal-errors.rs:133:9
+ --> $DIR/macros-nonfatal-errors.rs:134:9
|
LL | #[non_exhaustive]
| ----------------- declared `#[non_exhaustive]` here
@@ -255,7 +255,7 @@ LL | Foo,
= help: consider a manual implementation of `Default`
error: cannot find macro `llvm_asm` in this scope
- --> $DIR/macros-nonfatal-errors.rs:105:5
+ --> $DIR/macros-nonfatal-errors.rs:106:5
|
LL | llvm_asm!(invalid);
| ^^^^^^^^
diff --git a/tests/ui/simd/intrinsic/generic-comparison-pass.rs b/tests/ui/simd/intrinsic/generic-comparison-pass.rs
index 2ee164cdfd800..50a05eecb03b3 100644
--- a/tests/ui/simd/intrinsic/generic-comparison-pass.rs
+++ b/tests/ui/simd/intrinsic/generic-comparison-pass.rs
@@ -1,6 +1,6 @@
//@ run-pass
-#![feature(repr_simd, core_intrinsics, concat_idents)]
+#![feature(repr_simd, core_intrinsics, macro_metavar_expr_concat)]
#![allow(non_camel_case_types)]
use std::intrinsics::simd::{simd_eq, simd_ge, simd_gt, simd_le, simd_lt, simd_ne};
@@ -19,7 +19,7 @@ macro_rules! cmp {
($method: ident($lhs: expr, $rhs: expr)) => {{
let lhs = $lhs;
let rhs = $rhs;
- let e: u32x4 = concat_idents!(simd_, $method)($lhs, $rhs);
+ let e: u32x4 = ${concat(simd_, $method)}($lhs, $rhs);
// assume the scalar version is correct/the behaviour we want.
assert!((e.0[0] != 0) == lhs.0[0].$method(&rhs.0[0]));
assert!((e.0[1] != 0) == lhs.0[1].$method(&rhs.0[1]));
diff --git a/tests/ui/syntax-extension-minor.rs b/tests/ui/syntax-extension-minor.rs
index cdd572b50fcce..826990a89a533 100644
--- a/tests/ui/syntax-extension-minor.rs
+++ b/tests/ui/syntax-extension-minor.rs
@@ -1,6 +1,7 @@
//@ run-pass
#![feature(concat_idents)]
+#![expect(deprecated)] // concat_idents is deprecated
pub fn main() {
struct Foo;
diff --git a/tests/ui/unpretty/expanded-exhaustive.rs b/tests/ui/unpretty/expanded-exhaustive.rs
index 0fb5a26c5aae9..5697f615b9791 100644
--- a/tests/ui/unpretty/expanded-exhaustive.rs
+++ b/tests/ui/unpretty/expanded-exhaustive.rs
@@ -839,6 +839,7 @@ mod types {
}
/// TyKind::MacCall
+ #[expect(deprecated)] // concat_idents is deprecated
fn ty_mac_call() {
let _: concat_idents!(T);
let _: concat_idents![T];
diff --git a/tests/ui/unpretty/expanded-exhaustive.stdout b/tests/ui/unpretty/expanded-exhaustive.stdout
index 8febd2d6d4925..841edf63c9191 100644
--- a/tests/ui/unpretty/expanded-exhaustive.stdout
+++ b/tests/ui/unpretty/expanded-exhaustive.stdout
@@ -359,6 +359,7 @@ mod expressions {
+ // concat_idents is deprecated
@@ -674,6 +675,7 @@ mod types {
/*! there is no syntax for this */
}
/// TyKind::MacCall
+ #[expect(deprecated)]
fn ty_mac_call() { let _: T; let _: T; let _: T; }
/// TyKind::CVarArgs
fn ty_c_var_args() {
| diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs
index 330b409876453..16c0c11804049 100644
--- a/library/core/src/macros/mod.rs
+++ b/library/core/src/macros/mod.rs
@@ -1138,6 +1138,10 @@ pub(crate) mod builtin {
issue = "29599",
reason = "`concat_idents` is not stable enough for use and is subject to change"
)]
+ #[deprecated(
+ note = "use `${concat(...)}` with the `macro_metavar_expr_concat` feature instead"
+ )]
#[rustc_builtin_macro]
#[macro_export]
macro_rules! concat_idents {
diff --git a/library/core/src/prelude/v1.rs b/library/core/src/prelude/v1.rs
index 8f1b5275871e6..9737d0baec7ca 100644
--- a/library/core/src/prelude/v1.rs
+++ b/library/core/src/prelude/v1.rs
@@ -59,6 +59,7 @@ pub use crate::hash::macros::Hash;
pub use crate::{
diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs
index 3a52b7790376c..f77bf92a806e3 100644
--- a/library/std/src/lib.rs
+++ b/library/std/src/lib.rs
@@ -709,6 +709,7 @@ pub use core::primitive;
// Re-export built-in macros defined through core.
pub use core::{
assert, assert_matches, cfg, column, compile_error, concat, concat_idents, const_format_args,
env, file, format_args, format_args_nl, include, include_bytes, include_str, line, log_syntax,
diff --git a/library/std/src/prelude/v1.rs b/library/std/src/prelude/v1.rs
index c15d8c40085a5..68c9ac1e41463 100644
--- a/library/std/src/prelude/v1.rs
+++ b/library/std/src/prelude/v1.rs
@@ -46,6 +46,7 @@ pub use crate::result::Result::{self, Err, Ok};
// Re-exported built-in macros
pub use core::prelude::v1::{
diff --git a/src/doc/unstable-book/src/library-features/concat-idents.md b/src/doc/unstable-book/src/library-features/concat-idents.md
index 4366172fb9965..8a38d155e3dbc 100644
--- a/src/doc/unstable-book/src/library-features/concat-idents.md
+++ b/src/doc/unstable-book/src/library-features/concat-idents.md
@@ -2,7 +2,10 @@
The tracking issue for this feature is: [#29599]
+This feature is deprecated, to be replaced by [`macro_metavar_expr_concat`].
[#29599]: https://github.com/rust-lang/rust/issues/29599
+[`macro_metavar_expr_concat`]: https://github.com/rust-lang/rust/issues/124225
------------------------
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents.rs b/tests/ui/feature-gates/feature-gate-concat_idents.rs
index 68caf3d71e907..4fc3b69159733 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents.rs
+++ b/tests/ui/feature-gates/feature-gate-concat_idents.rs
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents.stderr b/tests/ui/feature-gates/feature-gate-concat_idents.stderr
index d0f4fe62d048f..6399424eecd8b 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents.stderr
+++ b/tests/ui/feature-gates/feature-gate-concat_idents.stderr
- --> $DIR/feature-gate-concat_idents.rs:5:13
+ --> $DIR/feature-gate-concat_idents.rs:7:13
LL | let a = concat_idents!(X, Y_1);
@@ -9,7 +9,7 @@ LL | let a = concat_idents!(X, Y_1);
- --> $DIR/feature-gate-concat_idents.rs:6:13
+ --> $DIR/feature-gate-concat_idents.rs:8:13
LL | let b = concat_idents!(X, Y_2);
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents2.rs b/tests/ui/feature-gates/feature-gate-concat_idents2.rs
index 9660ffeafa518..bc2b4f7cddf99 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents2.rs
+++ b/tests/ui/feature-gates/feature-gate-concat_idents2.rs
concat_idents!(a, b); //~ ERROR `concat_idents` is not stable enough
//~| ERROR cannot find value `ab` in this scope
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents2.stderr b/tests/ui/feature-gates/feature-gate-concat_idents2.stderr
index b42a1d999e4d9..a770c1a348b5d 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents2.stderr
+++ b/tests/ui/feature-gates/feature-gate-concat_idents2.stderr
| ^^^^^^^^^^^^^
@@ -9,7 +9,7 @@ LL | concat_idents!(a, b);
error[E0425]: cannot find value `ab` in this scope
| ^^^^^^^^^^^^^^^^^^^^ not found in this scope
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents3.rs b/tests/ui/feature-gates/feature-gate-concat_idents3.rs
index 81710fd9fb041..d4a0d2e6bb0e4 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents3.rs
+++ b/tests/ui/feature-gates/feature-gate-concat_idents3.rs
diff --git a/tests/ui/feature-gates/feature-gate-concat_idents3.stderr b/tests/ui/feature-gates/feature-gate-concat_idents3.stderr
index b186601d0ed68..7d929322bc06e 100644
--- a/tests/ui/feature-gates/feature-gate-concat_idents3.stderr
+++ b/tests/ui/feature-gates/feature-gate-concat_idents3.stderr
- --> $DIR/feature-gate-concat_idents3.rs:5:20
+ --> $DIR/feature-gate-concat_idents3.rs:7:20
LL | assert_eq!(10, concat_idents!(X, Y_1));
@@ -9,7 +9,7 @@ LL | assert_eq!(10, concat_idents!(X, Y_1));
- --> $DIR/feature-gate-concat_idents3.rs:6:20
+ --> $DIR/feature-gate-concat_idents3.rs:8:20
LL | assert_eq!(20, concat_idents!(X, Y_2));
diff --git a/tests/ui/issues/issue-32950.rs b/tests/ui/issues/issue-32950.rs
index 27d68a11c1f16..b51ac2967768a 100644
--- a/tests/ui/issues/issue-32950.rs
+++ b/tests/ui/issues/issue-32950.rs
#[derive(Debug)]
struct Baz<T>(
diff --git a/tests/ui/issues/issue-32950.stderr b/tests/ui/issues/issue-32950.stderr
index 3cdf35af1d866..38a82542f8964 100644
--- a/tests/ui/issues/issue-32950.stderr
+++ b/tests/ui/issues/issue-32950.stderr
@@ -1,11 +1,11 @@
error: `derive` cannot be used on items with type macros
| ^^^^^^^^^^^^^^^^^^^^^^^^
error[E0412]: cannot find type `FooBar` in this scope
| ^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope
diff --git a/tests/ui/issues/issue-50403.rs b/tests/ui/issues/issue-50403.rs
index ab22aff26d99c..f14958afc34dc 100644
--- a/tests/ui/issues/issue-50403.rs
+++ b/tests/ui/issues/issue-50403.rs
let x = concat_idents!(); //~ ERROR `concat_idents!()` takes 1 or more arguments
diff --git a/tests/ui/issues/issue-50403.stderr b/tests/ui/issues/issue-50403.stderr
index 193d815d5195f..e7dd05bb0183d 100644
--- a/tests/ui/issues/issue-50403.stderr
+++ b/tests/ui/issues/issue-50403.stderr
error: `concat_idents!()` takes 1 or more arguments
- --> $DIR/issue-50403.rs:4:13
+ --> $DIR/issue-50403.rs:5:13
LL | let x = concat_idents!();
| ^^^^^^^^^^^^^^^^
diff --git a/tests/ui/macros/macros-nonfatal-errors.rs b/tests/ui/macros/macros-nonfatal-errors.rs
index 79beffbe986e3..091d64ea5d9eb 100644
--- a/tests/ui/macros/macros-nonfatal-errors.rs
+++ b/tests/ui/macros/macros-nonfatal-errors.rs
@@ -5,6 +5,7 @@
#![feature(trace_macros, concat_idents)]
#![feature(stmt_expr_attributes)]
use std::arch::asm;
diff --git a/tests/ui/macros/macros-nonfatal-errors.stderr b/tests/ui/macros/macros-nonfatal-errors.stderr
index 44194b506a43a..2f990cb24e2bf 100644
--- a/tests/ui/macros/macros-nonfatal-errors.stderr
+++ b/tests/ui/macros/macros-nonfatal-errors.stderr
- --> $DIR/macros-nonfatal-errors.rs:13:5
+ --> $DIR/macros-nonfatal-errors.rs:14:5
@@ -7,7 +7,7 @@ LL | #[default]
- --> $DIR/macros-nonfatal-errors.rs:18:36
+ --> $DIR/macros-nonfatal-errors.rs:19:36
LL | struct DefaultInnerAttrTupleStruct(#[default] ());
| ^^^^^^^^^^
@@ -15,7 +15,7 @@ LL | struct DefaultInnerAttrTupleStruct(#[default] ());
- --> $DIR/macros-nonfatal-errors.rs:22:1
+ --> $DIR/macros-nonfatal-errors.rs:23:1
@@ -23,7 +23,7 @@ LL | #[default]
- --> $DIR/macros-nonfatal-errors.rs:26:1
+ --> $DIR/macros-nonfatal-errors.rs:27:1
@@ -31,7 +31,7 @@ LL | #[default]
+ --> $DIR/macros-nonfatal-errors.rs:37:11
LL | Foo = #[default] 0,
| ^^^^^^^^^^
@@ -39,7 +39,7 @@ LL | Foo = #[default] 0,
- --> $DIR/macros-nonfatal-errors.rs:37:14
+ --> $DIR/macros-nonfatal-errors.rs:38:14
LL | Bar([u8; #[default] 1]),
| ^^^^^^^^^^
@@ -47,7 +47,7 @@ LL | Bar([u8; #[default] 1]),
- --> $DIR/macros-nonfatal-errors.rs:42:10
+ --> $DIR/macros-nonfatal-errors.rs:43:10
@@ -67,7 +67,7 @@ LL | #[default] Bar,
| ++++++++++
- --> $DIR/macros-nonfatal-errors.rs:48:10
+ --> $DIR/macros-nonfatal-errors.rs:49:10
@@ -78,7 +78,7 @@ LL | | }
| |_- this enum needs a unit variant marked with `#[default]`
error: multiple declared defaults
- --> $DIR/macros-nonfatal-errors.rs:54:10
+ --> $DIR/macros-nonfatal-errors.rs:55:10
LL | #[derive(Default)]
@@ -95,7 +95,7 @@ LL | Baz,
= note: only one variant can be default
error: `#[default]` attribute does not accept a value
- --> $DIR/macros-nonfatal-errors.rs:66:5
+ --> $DIR/macros-nonfatal-errors.rs:67:5
LL | #[default = 1]
| ^^^^^^^^^^^^^^
@@ -103,7 +103,7 @@ LL | #[default = 1]
= help: try using `#[default]`
- --> $DIR/macros-nonfatal-errors.rs:74:5
+ --> $DIR/macros-nonfatal-errors.rs:75:5
@@ -114,13 +114,13 @@ LL | Foo,
help: try removing this
- --> $DIR/macros-nonfatal-errors.rs:73:5
+ --> $DIR/macros-nonfatal-errors.rs:74:5
- --> $DIR/macros-nonfatal-errors.rs:84:5
+ --> $DIR/macros-nonfatal-errors.rs:85:5
@@ -132,7 +132,7 @@ LL | Foo,
help: try removing these
- --> $DIR/macros-nonfatal-errors.rs:81:5
+ --> $DIR/macros-nonfatal-errors.rs:82:5
@@ -142,7 +142,7 @@ LL | #[default]
+ --> $DIR/macros-nonfatal-errors.rs:92:5
LL | Foo {},
| ^^^
@@ -150,7 +150,7 @@ LL | Foo {},
- --> $DIR/macros-nonfatal-errors.rs:99:5
+ --> $DIR/macros-nonfatal-errors.rs:100:5
LL | #[non_exhaustive]
| ----------------- declared `#[non_exhaustive]` here
@@ -160,37 +160,37 @@ LL | Foo,
error: asm template must be a string literal
- --> $DIR/macros-nonfatal-errors.rs:104:10
+ --> $DIR/macros-nonfatal-errors.rs:105:10
LL | asm!(invalid);
error: `concat_idents!()` requires ident args
- --> $DIR/macros-nonfatal-errors.rs:107:5
+ --> $DIR/macros-nonfatal-errors.rs:108:5
LL | concat_idents!("not", "idents");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ --> $DIR/macros-nonfatal-errors.rs:110:17
LL | option_env!(invalid);
| ^^^^^^^
error: expected string literal
+ --> $DIR/macros-nonfatal-errors.rs:111:10
LL | env!(invalid);
error: `env!()` takes 1 or 2 arguments
- --> $DIR/macros-nonfatal-errors.rs:111:5
+ --> $DIR/macros-nonfatal-errors.rs:112:5
LL | env!(foo, abr, baz);
| ^^^^^^^^^^^^^^^^^^^
error: environment variable `RUST_HOPEFULLY_THIS_DOESNT_EXIST` not defined at compile time
- --> $DIR/macros-nonfatal-errors.rs:112:5
+ --> $DIR/macros-nonfatal-errors.rs:113:5
LL | env!("RUST_HOPEFULLY_THIS_DOESNT_EXIST");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -198,7 +198,7 @@ LL | env!("RUST_HOPEFULLY_THIS_DOESNT_EXIST");
= help: use `std::env::var("RUST_HOPEFULLY_THIS_DOESNT_EXIST")` to read the variable at run time
error: format argument must be a string literal
- --> $DIR/macros-nonfatal-errors.rs:114:13
+ --> $DIR/macros-nonfatal-errors.rs:115:13
LL | format!(invalid);
| ^^^^^^^
@@ -209,43 +209,43 @@ LL | format!("{}", invalid);
| +++++
- --> $DIR/macros-nonfatal-errors.rs:116:14
+ --> $DIR/macros-nonfatal-errors.rs:117:14
LL | include!(invalid);
| ^^^^^^^
- --> $DIR/macros-nonfatal-errors.rs:118:18
+ --> $DIR/macros-nonfatal-errors.rs:119:18
LL | include_str!(invalid);
| ^^^^^^^
+ --> $DIR/macros-nonfatal-errors.rs:120:5
LL | include_str!("i'd be quite surprised if a file with this name existed");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- --> $DIR/macros-nonfatal-errors.rs:120:20
+ --> $DIR/macros-nonfatal-errors.rs:121:20
LL | include_bytes!(invalid);
| ^^^^^^^
- --> $DIR/macros-nonfatal-errors.rs:121:5
+ --> $DIR/macros-nonfatal-errors.rs:122:5
LL | include_bytes!("i'd be quite surprised if a file with this name existed");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: trace_macros! accepts only `true` or `false`
- --> $DIR/macros-nonfatal-errors.rs:123:5
+ --> $DIR/macros-nonfatal-errors.rs:124:5
LL | trace_macros!(invalid);
| ^^^^^^^^^^^^^^^^^^^^^^
- --> $DIR/macros-nonfatal-errors.rs:133:9
LL | #[non_exhaustive]
| ----------------- declared `#[non_exhaustive]` here
@@ -255,7 +255,7 @@ LL | Foo,
error: cannot find macro `llvm_asm` in this scope
- --> $DIR/macros-nonfatal-errors.rs:105:5
+ --> $DIR/macros-nonfatal-errors.rs:106:5
LL | llvm_asm!(invalid);
| ^^^^^^^^
diff --git a/tests/ui/simd/intrinsic/generic-comparison-pass.rs b/tests/ui/simd/intrinsic/generic-comparison-pass.rs
index 2ee164cdfd800..50a05eecb03b3 100644
--- a/tests/ui/simd/intrinsic/generic-comparison-pass.rs
+++ b/tests/ui/simd/intrinsic/generic-comparison-pass.rs
@@ -1,6 +1,6 @@
-#![feature(repr_simd, core_intrinsics, concat_idents)]
+#![feature(repr_simd, core_intrinsics, macro_metavar_expr_concat)]
#![allow(non_camel_case_types)]
use std::intrinsics::simd::{simd_eq, simd_ge, simd_gt, simd_le, simd_lt, simd_ne};
@@ -19,7 +19,7 @@ macro_rules! cmp {
($method: ident($lhs: expr, $rhs: expr)) => {{
let lhs = $lhs;
let rhs = $rhs;
- let e: u32x4 = concat_idents!(simd_, $method)($lhs, $rhs);
// assume the scalar version is correct/the behaviour we want.
assert!((e.0[0] != 0) == lhs.0[0].$method(&rhs.0[0]));
assert!((e.0[1] != 0) == lhs.0[1].$method(&rhs.0[1]));
diff --git a/tests/ui/syntax-extension-minor.rs b/tests/ui/syntax-extension-minor.rs
index cdd572b50fcce..826990a89a533 100644
--- a/tests/ui/syntax-extension-minor.rs
+++ b/tests/ui/syntax-extension-minor.rs
@@ -1,6 +1,7 @@
pub fn main() {
struct Foo;
diff --git a/tests/ui/unpretty/expanded-exhaustive.rs b/tests/ui/unpretty/expanded-exhaustive.rs
index 0fb5a26c5aae9..5697f615b9791 100644
--- a/tests/ui/unpretty/expanded-exhaustive.rs
+++ b/tests/ui/unpretty/expanded-exhaustive.rs
@@ -839,6 +839,7 @@ mod types {
+ #[expect(deprecated)] // concat_idents is deprecated
fn ty_mac_call() {
let _: concat_idents!(T);
let _: concat_idents![T];
diff --git a/tests/ui/unpretty/expanded-exhaustive.stdout b/tests/ui/unpretty/expanded-exhaustive.stdout
index 8febd2d6d4925..841edf63c9191 100644
--- a/tests/ui/unpretty/expanded-exhaustive.stdout
+++ b/tests/ui/unpretty/expanded-exhaustive.stdout
@@ -359,6 +359,7 @@ mod expressions {
+ // concat_idents is deprecated
@@ -674,6 +675,7 @@ mod types {
/*! there is no syntax for this */
+ #[expect(deprecated)]
fn ty_mac_call() { let _: T; let _: T; let _: T; }
/// TyKind::CVarArgs
fn ty_c_var_args() { | [
"+ since = \"1.88.0\",",
"- --> $DIR/macros-nonfatal-errors.rs:36:11",
"- --> $DIR/macros-nonfatal-errors.rs:91:5",
"- --> $DIR/macros-nonfatal-errors.rs:109:17",
"- --> $DIR/macros-nonfatal-errors.rs:110:10",
"- --> $DIR/macros-nonfatal-errors.rs:119:5",
"+ --> $DIR/macros-nonfatal-errors.rs:134:9",
"+ let e: u32x4 = ${concat(simd_, $method)}($lhs, $rhs);"
] | [
9,
259,
347,
379,
386,
432,
461,
491
] | {
"additions": 65,
"author": "tgross35",
"deletions": 42,
"html_url": "https://github.com/rust-lang/rust/pull/137653",
"issue_id": 137653,
"merged_at": "2025-04-25T15:37:51Z",
"omission_probability": 0.1,
"pr_number": 137653,
"repo": "rust-lang/rust",
"title": "Deprecate the unstable `concat_idents!`",
"total_changes": 107
} |
110 | diff --git a/library/core/src/option.rs b/library/core/src/option.rs
index 7ec0ac7127142..aed5a043c11a3 100644
--- a/library/core/src/option.rs
+++ b/library/core/src/option.rs
@@ -162,8 +162,14 @@
//! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
//! is [`Some`] or [`None`], respectively.
//!
+//! The [`is_some_and`] and [`is_none_or`] methods apply the provided function
+//! to the contents of the [`Option`] to produce a boolean value.
+//! If this is [`None`] then a default result is returned instead without executing the function.
+//!
//! [`is_none`]: Option::is_none
//! [`is_some`]: Option::is_some
+//! [`is_some_and`]: Option::is_some_and
+//! [`is_none_or`]: Option::is_none_or
//!
//! ## Adapters for working with references
//!
@@ -177,6 +183,10 @@
//! <code>[Option]<[Pin]<[&]T>></code>
//! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to
//! <code>[Option]<[Pin]<[&mut] T>></code>
+//! * [`as_slice`] returns a one-element slice of the contained value, if any.
+//! If this is [`None`], an empty slice is returned.
+//! * [`as_mut_slice`] returns a mutable one-element slice of the contained value, if any.
+//! If this is [`None`], an empty slice is returned.
//!
//! [&]: reference "shared reference"
//! [&mut]: reference "mutable reference"
@@ -187,6 +197,8 @@
//! [`as_pin_mut`]: Option::as_pin_mut
//! [`as_pin_ref`]: Option::as_pin_ref
//! [`as_ref`]: Option::as_ref
+//! [`as_slice`]: Option::as_slice
+//! [`as_mut_slice`]: Option::as_mut_slice
//!
//! ## Extracting the contained value
//!
@@ -200,12 +212,15 @@
//! (which must implement the [`Default`] trait)
//! * [`unwrap_or_else`] returns the result of evaluating the provided
//! function
+//! * [`unwrap_unchecked`] produces *[undefined behavior]*
//!
//! [`expect`]: Option::expect
//! [`unwrap`]: Option::unwrap
//! [`unwrap_or`]: Option::unwrap_or
//! [`unwrap_or_default`]: Option::unwrap_or_default
//! [`unwrap_or_else`]: Option::unwrap_or_else
+//! [`unwrap_unchecked`]: Option::unwrap_unchecked
+//! [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
//!
//! ## Transforming contained values
//!
@@ -230,8 +245,9 @@
//! * [`filter`] calls the provided predicate function on the contained
//! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
//! if the function returns `true`; otherwise, returns [`None`]
-//! * [`flatten`] removes one level of nesting from an
-//! [`Option<Option<T>>`]
+//! * [`flatten`] removes one level of nesting from an [`Option<Option<T>>`]
+//! * [`inspect`] method takes ownership of the [`Option`] and applies
+//! the provided function to the contained value by reference if [`Some`]
//! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
//! provided function to the contained value of [`Some`] and leaving
//! [`None`] values unchanged
@@ -239,6 +255,7 @@
//! [`Some(t)`]: Some
//! [`filter`]: Option::filter
//! [`flatten`]: Option::flatten
+//! [`inspect`]: Option::inspect
//! [`map`]: Option::map
//!
//! These methods transform [`Option<T>`] to a value of a possibly
@@ -621,6 +638,10 @@ impl<T> Option<T> {
///
/// let x: Option<u32> = None;
/// assert_eq!(x.is_some_and(|x| x > 1), false);
+ ///
+ /// let x: Option<String> = Some("ownership".to_string());
+ /// assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true);
+ /// println!("still alive {:?}", x);
/// ```
#[must_use]
#[inline]
@@ -665,6 +686,10 @@ impl<T> Option<T> {
///
/// let x: Option<u32> = None;
/// assert_eq!(x.is_none_or(|x| x > 1), true);
+ ///
+ /// let x: Option<String> = Some("ownership".to_string());
+ /// assert_eq!(x.as_ref().is_none_or(|x| x.len() > 1), true);
+ /// println!("still alive {:?}", x);
/// ```
#[must_use]
#[inline]
| diff --git a/library/core/src/option.rs b/library/core/src/option.rs
index 7ec0ac7127142..aed5a043c11a3 100644
--- a/library/core/src/option.rs
+++ b/library/core/src/option.rs
@@ -162,8 +162,14 @@
//! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
//! is [`Some`] or [`None`], respectively.
+//! The [`is_some_and`] and [`is_none_or`] methods apply the provided function
+//! to the contents of the [`Option`] to produce a boolean value.
+//! If this is [`None`] then a default result is returned instead without executing the function.
+//!
//! [`is_none`]: Option::is_none
//! [`is_some`]: Option::is_some
+//! [`is_some_and`]: Option::is_some_and
+//! [`is_none_or`]: Option::is_none_or
//! ## Adapters for working with references
@@ -177,6 +183,10 @@
//! <code>[Option]<[Pin]<[&]T>></code>
//! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to
//! <code>[Option]<[Pin]<[&mut] T>></code>
+//! * [`as_slice`] returns a one-element slice of the contained value, if any.
//! [&]: reference "shared reference"
//! [&mut]: reference "mutable reference"
@@ -187,6 +197,8 @@
//! [`as_pin_mut`]: Option::as_pin_mut
//! [`as_pin_ref`]: Option::as_pin_ref
//! [`as_ref`]: Option::as_ref
+//! [`as_slice`]: Option::as_slice
+//! [`as_mut_slice`]: Option::as_mut_slice
//! ## Extracting the contained value
@@ -200,12 +212,15 @@
//! (which must implement the [`Default`] trait)
//! * [`unwrap_or_else`] returns the result of evaluating the provided
//! function
+//! * [`unwrap_unchecked`] produces *[undefined behavior]*
//! [`expect`]: Option::expect
//! [`unwrap`]: Option::unwrap
//! [`unwrap_or`]: Option::unwrap_or
//! [`unwrap_or_default`]: Option::unwrap_or_default
//! [`unwrap_or_else`]: Option::unwrap_or_else
+//! [`unwrap_unchecked`]: Option::unwrap_unchecked
+//! [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
//! ## Transforming contained values
@@ -230,8 +245,9 @@
//! * [`filter`] calls the provided predicate function on the contained
//! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
//! if the function returns `true`; otherwise, returns [`None`]
-//! * [`flatten`] removes one level of nesting from an
-//! [`Option<Option<T>>`]
+//! * [`flatten`] removes one level of nesting from an [`Option<Option<T>>`]
+//! * [`inspect`] method takes ownership of the [`Option`] and applies
+//! the provided function to the contained value by reference if [`Some`]
//! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
//! provided function to the contained value of [`Some`] and leaving
//! [`None`] values unchanged
@@ -239,6 +255,7 @@
//! [`Some(t)`]: Some
//! [`filter`]: Option::filter
//! [`flatten`]: Option::flatten
//! [`map`]: Option::map
//! These methods transform [`Option<T>`] to a value of a possibly
@@ -621,6 +638,10 @@ impl<T> Option<T> {
/// assert_eq!(x.is_some_and(|x| x > 1), false);
+ /// assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true);
@@ -665,6 +686,10 @@ impl<T> Option<T> {
/// assert_eq!(x.is_none_or(|x| x > 1), true);
+ /// assert_eq!(x.as_ref().is_none_or(|x| x.len() > 1), true); | [
"+//! * [`as_mut_slice`] returns a mutable one-element slice of the contained value, if any.",
"+//! [`inspect`]: Option::inspect"
] | [
25,
71
] | {
"additions": 27,
"author": "Natural-selection1",
"deletions": 2,
"html_url": "https://github.com/rust-lang/rust/pull/138957",
"issue_id": 138957,
"merged_at": "2025-04-25T15:37:59Z",
"omission_probability": 0.1,
"pr_number": 138957,
"repo": "rust-lang/rust",
"title": "Update the index of Option to make the summary more comprehensive",
"total_changes": 29
} |
111 | diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs
index df6e8fc4503f1..4330f1f22925d 100644
--- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs
+++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs
@@ -1523,19 +1523,17 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
return None;
};
- let trait_assoc_item = self.tcx.opt_associated_item(proj.projection_term.def_id)?;
- let trait_assoc_ident = trait_assoc_item.ident(self.tcx);
-
let mut associated_items = vec![];
self.tcx.for_each_relevant_impl(
self.tcx.trait_of_item(proj.projection_term.def_id)?,
proj.projection_term.self_ty(),
|impl_def_id| {
associated_items.extend(
- self.tcx
- .associated_items(impl_def_id)
- .in_definition_order()
- .find(|assoc| assoc.ident(self.tcx) == trait_assoc_ident),
+ self.tcx.associated_items(impl_def_id).in_definition_order().find(
+ |assoc| {
+ assoc.trait_item_def_id == Some(proj.projection_term.def_id)
+ },
+ ),
);
},
);
diff --git a/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.rs b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.rs
new file mode 100644
index 0000000000000..1ee3bfd123397
--- /dev/null
+++ b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.rs
@@ -0,0 +1,23 @@
+trait ServerFn {
+ type Output;
+ fn run_body() -> impl Sized;
+}
+struct MyServerFn {}
+
+macro_rules! f {
+ () => {
+ impl ServerFn for MyServerFn {
+ type Output = ();
+ fn run_body() -> impl Sized {}
+ }
+ };
+}
+
+f! {}
+
+fn problem<T: ServerFn<Output = i64>>(_: T) {}
+
+fn main() {
+ problem(MyServerFn {});
+ //~^ ERROR type mismatch resolving `<MyServerFn as ServerFn>::Output == i64`
+}
diff --git a/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.stderr b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.stderr
new file mode 100644
index 0000000000000..b4c022d352193
--- /dev/null
+++ b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.stderr
@@ -0,0 +1,26 @@
+error[E0271]: type mismatch resolving `<MyServerFn as ServerFn>::Output == i64`
+ --> $DIR/dont-probe-missing-item-name-4.rs:21:13
+ |
+LL | problem(MyServerFn {});
+ | ------- ^^^^^^^^^^^^^ type mismatch resolving `<MyServerFn as ServerFn>::Output == i64`
+ | |
+ | required by a bound introduced by this call
+ |
+note: expected this to be `i64`
+ --> $DIR/dont-probe-missing-item-name-4.rs:10:27
+ |
+LL | type Output = ();
+ | ^^
+...
+LL | f! {}
+ | ----- in this macro invocation
+note: required by a bound in `problem`
+ --> $DIR/dont-probe-missing-item-name-4.rs:18:24
+ |
+LL | fn problem<T: ServerFn<Output = i64>>(_: T) {}
+ | ^^^^^^^^^^^^ required by this bound in `problem`
+ = note: this error originates in the macro `f` (in Nightly builds, run with -Z macro-backtrace for more info)
+
+error: aborting due to 1 previous error
+
+For more information about this error, try `rustc --explain E0271`.
| diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs
index df6e8fc4503f1..4330f1f22925d 100644
--- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs
+++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs
@@ -1523,19 +1523,17 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
return None;
};
- let trait_assoc_item = self.tcx.opt_associated_item(proj.projection_term.def_id)?;
- let trait_assoc_ident = trait_assoc_item.ident(self.tcx);
-
let mut associated_items = vec![];
self.tcx.for_each_relevant_impl(
self.tcx.trait_of_item(proj.projection_term.def_id)?,
proj.projection_term.self_ty(),
|impl_def_id| {
associated_items.extend(
- self.tcx
- .associated_items(impl_def_id)
- .in_definition_order()
- .find(|assoc| assoc.ident(self.tcx) == trait_assoc_ident),
+ self.tcx.associated_items(impl_def_id).in_definition_order().find(
+ |assoc| {
+ assoc.trait_item_def_id == Some(proj.projection_term.def_id)
+ },
+ ),
);
},
);
diff --git a/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.rs b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.rs
index 0000000000000..1ee3bfd123397
+++ b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.rs
@@ -0,0 +1,23 @@
+trait ServerFn {
+ type Output;
+ fn run_body() -> impl Sized;
+struct MyServerFn {}
+macro_rules! f {
+ () => {
+ impl ServerFn for MyServerFn {
+ type Output = ();
+ fn run_body() -> impl Sized {}
+ }
+f! {}
+fn problem<T: ServerFn<Output = i64>>(_: T) {}
+fn main() {
+ problem(MyServerFn {});
+ //~^ ERROR type mismatch resolving `<MyServerFn as ServerFn>::Output == i64`
diff --git a/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.stderr b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.stderr
index 0000000000000..b4c022d352193
+++ b/tests/ui/impl-trait/in-trait/dont-probe-missing-item-name-4.stderr
@@ -0,0 +1,26 @@
+error[E0271]: type mismatch resolving `<MyServerFn as ServerFn>::Output == i64`
+ --> $DIR/dont-probe-missing-item-name-4.rs:21:13
+LL | problem(MyServerFn {});
+ | ------- ^^^^^^^^^^^^^ type mismatch resolving `<MyServerFn as ServerFn>::Output == i64`
+ | |
+ | required by a bound introduced by this call
+note: expected this to be `i64`
+ --> $DIR/dont-probe-missing-item-name-4.rs:10:27
+ | ^^
+...
+LL | f! {}
+ | ----- in this macro invocation
+note: required by a bound in `problem`
+ --> $DIR/dont-probe-missing-item-name-4.rs:18:24
+LL | fn problem<T: ServerFn<Output = i64>>(_: T) {}
+ | ^^^^^^^^^^^^ required by this bound in `problem`
+ = note: this error originates in the macro `f` (in Nightly builds, run with -Z macro-backtrace for more info)
+error: aborting due to 1 previous error
+For more information about this error, try `rustc --explain E0271`. | [
"+ };",
"+LL | type Output = ();"
] | [
47,
75
] | {
"additions": 54,
"author": "compiler-errors",
"deletions": 7,
"html_url": "https://github.com/rust-lang/rust/pull/140278",
"issue_id": 140278,
"merged_at": "2025-04-25T15:37:51Z",
"omission_probability": 0.1,
"pr_number": 140278,
"repo": "rust-lang/rust",
"title": "Don't use item name to look up associated item from trait item",
"total_changes": 61
} |
112 | diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs
index 294c6c9ba7a50..1471262d2d676 100644
--- a/compiler/rustc_ast/src/lib.rs
+++ b/compiler/rustc_ast/src/lib.rs
@@ -6,6 +6,7 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(
html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
test(attr(deny(warnings)))
@@ -14,7 +15,6 @@
#![feature(associated_type_defaults)]
#![feature(box_patterns)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(negative_impls)]
#![feature(never_type)]
#![feature(rustdoc_internals)]
diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index c40987541f4a5..3ec00bfce73f5 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -32,12 +32,12 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(exact_size_is_empty)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(rustdoc_internals)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_ast_passes/src/lib.rs b/compiler/rustc_ast_passes/src/lib.rs
index 093199cf34212..7956057f88ee7 100644
--- a/compiler/rustc_ast_passes/src/lib.rs
+++ b/compiler/rustc_ast_passes/src/lib.rs
@@ -4,11 +4,11 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(rust_logo)]
#![feature(box_patterns)]
#![feature(if_let_guard)]
#![feature(iter_is_partitioned)]
-#![feature(let_chains)]
#![feature(rustdoc_internals)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_attr_data_structures/src/lib.rs b/compiler/rustc_attr_data_structures/src/lib.rs
index c61b44b273de5..679fe935484e8 100644
--- a/compiler/rustc_attr_data_structures/src/lib.rs
+++ b/compiler/rustc_attr_data_structures/src/lib.rs
@@ -1,7 +1,7 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(rust_logo)]
-#![feature(let_chains)]
#![feature(rustdoc_internals)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_attr_parsing/src/lib.rs b/compiler/rustc_attr_parsing/src/lib.rs
index 249e71ef70dcf..b9692c01e2c42 100644
--- a/compiler/rustc_attr_parsing/src/lib.rs
+++ b/compiler/rustc_attr_parsing/src/lib.rs
@@ -77,8 +77,8 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(rust_logo)]
-#![feature(let_chains)]
#![feature(rustdoc_internals)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs
index 3b66142eb2cec..dbf943ffdb62a 100644
--- a/compiler/rustc_borrowck/src/lib.rs
+++ b/compiler/rustc_borrowck/src/lib.rs
@@ -2,12 +2,12 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(file_buffered)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(negative_impls)]
#![feature(never_type)]
#![feature(rustc_attrs)]
diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs
index bcd40f980e649..70e817db2a630 100644
--- a/compiler/rustc_builtin_macros/src/lib.rs
+++ b/compiler/rustc_builtin_macros/src/lib.rs
@@ -5,6 +5,7 @@
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
@@ -12,7 +13,6 @@
#![feature(box_patterns)]
#![feature(decl_macro)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(proc_macro_internals)]
#![feature(proc_macro_quote)]
#![feature(rustdoc_internals)]
diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs
index 425381b0ffab7..b2feeacdb4664 100644
--- a/compiler/rustc_codegen_llvm/src/lib.rs
+++ b/compiler/rustc_codegen_llvm/src/lib.rs
@@ -6,6 +6,7 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
@@ -15,7 +16,6 @@
#![feature(if_let_guard)]
#![feature(impl_trait_in_assoc_type)]
#![feature(iter_intersperse)]
-#![feature(let_chains)]
#![feature(rustdoc_internals)]
#![feature(slice_as_array)]
#![feature(try_blocks)]
diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs
index 5b2ed69535b9f..c927aae2c4c2b 100644
--- a/compiler/rustc_codegen_ssa/src/lib.rs
+++ b/compiler/rustc_codegen_ssa/src/lib.rs
@@ -2,13 +2,13 @@
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(file_buffered)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(negative_impls)]
#![feature(rustdoc_internals)]
#![feature(string_from_utf8_lossy_owned)]
diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs
index da52d60ae59fd..7a0c2543c3002 100644
--- a/compiler/rustc_const_eval/src/lib.rs
+++ b/compiler/rustc_const_eval/src/lib.rs
@@ -1,12 +1,12 @@
// tidy-alphabetical-start
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(decl_macro)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(never_type)]
#![feature(rustdoc_internals)]
#![feature(slice_ptr_get)]
diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs
index 40cc82727a556..d18fa89281404 100644
--- a/compiler/rustc_driver_impl/src/lib.rs
+++ b/compiler/rustc_driver_impl/src/lib.rs
@@ -7,10 +7,10 @@
// tidy-alphabetical-start
#![allow(internal_features)]
#![allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(decl_macro)]
-#![feature(let_chains)]
#![feature(panic_backtrace_config)]
#![feature(panic_update_hook)]
#![feature(result_flattening)]
diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs
index c0c5dba46772a..6f37bad9bb462 100644
--- a/compiler/rustc_errors/src/lib.rs
+++ b/compiler/rustc_errors/src/lib.rs
@@ -7,6 +7,7 @@
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(array_windows)]
@@ -17,7 +18,6 @@
#![feature(default_field_values)]
#![feature(error_reporter)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(negative_impls)]
#![feature(never_type)]
#![feature(rustc_attrs)]
diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs
index 4222c9fe90616..79f838e2e33f2 100644
--- a/compiler/rustc_expand/src/lib.rs
+++ b/compiler/rustc_expand/src/lib.rs
@@ -1,11 +1,11 @@
// tidy-alphabetical-start
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(rust_logo)]
#![feature(array_windows)]
#![feature(associated_type_defaults)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(macro_metavar_expr)]
#![feature(map_try_insert)]
#![feature(proc_macro_diagnostic)]
diff --git a/compiler/rustc_hir/src/lib.rs b/compiler/rustc_hir/src/lib.rs
index a84857e3597b0..32064f96dd6c2 100644
--- a/compiler/rustc_hir/src/lib.rs
+++ b/compiler/rustc_hir/src/lib.rs
@@ -4,12 +4,12 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(associated_type_defaults)]
#![feature(box_patterns)]
#![feature(closure_track_caller)]
#![feature(debug_closure_helpers)]
#![feature(exhaustive_patterns)]
-#![feature(let_chains)]
#![feature(negative_impls)]
#![feature(never_type)]
#![feature(rustc_attrs)]
diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs
index e1ad8124aea76..309b8f2c76138 100644
--- a/compiler/rustc_hir_analysis/src/lib.rs
+++ b/compiler/rustc_hir_analysis/src/lib.rs
@@ -59,6 +59,7 @@ This API is completely unstable and subject to change.
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
@@ -67,7 +68,6 @@ This API is completely unstable and subject to change.
#![feature(if_let_guard)]
#![feature(iter_from_coroutine)]
#![feature(iter_intersperse)]
-#![feature(let_chains)]
#![feature(never_type)]
#![feature(rustdoc_internals)]
#![feature(slice_partition_dedup)]
diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs
index ff4385c3bccec..779fae80f19cd 100644
--- a/compiler/rustc_hir_pretty/src/lib.rs
+++ b/compiler/rustc_hir_pretty/src/lib.rs
@@ -2,7 +2,7 @@
//! the definitions in this file have equivalents in `rustc_ast_pretty`.
// tidy-alphabetical-start
-#![feature(let_chains)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![recursion_limit = "256"]
// tidy-alphabetical-end
diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs
index af8ec37393472..c3717b4efa47f 100644
--- a/compiler/rustc_hir_typeck/src/lib.rs
+++ b/compiler/rustc_hir_typeck/src/lib.rs
@@ -1,11 +1,11 @@
// tidy-alphabetical-start
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(array_windows)]
#![feature(box_patterns)]
#![feature(if_let_guard)]
#![feature(iter_intersperse)]
-#![feature(let_chains)]
#![feature(never_type)]
#![feature(try_blocks)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_infer/src/lib.rs b/compiler/rustc_infer/src/lib.rs
index ece18f4ea64ee..8b2aab4204228 100644
--- a/compiler/rustc_infer/src/lib.rs
+++ b/compiler/rustc_infer/src/lib.rs
@@ -16,12 +16,12 @@
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(extend_one)]
#![feature(iterator_try_collect)]
-#![feature(let_chains)]
#![feature(rustdoc_internals)]
#![recursion_limit = "512"] // For rustdoc
// tidy-alphabetical-end
diff --git a/compiler/rustc_interface/src/lib.rs b/compiler/rustc_interface/src/lib.rs
index 67e0be93523d9..4128070718308 100644
--- a/compiler/rustc_interface/src/lib.rs
+++ b/compiler/rustc_interface/src/lib.rs
@@ -1,8 +1,8 @@
// tidy-alphabetical-start
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(decl_macro)]
#![feature(file_buffered)]
#![feature(iter_intersperse)]
-#![feature(let_chains)]
#![feature(try_blocks)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs
index 212368bea8266..b4bc648c9d814 100644
--- a/compiler/rustc_lint/src/lib.rs
+++ b/compiler/rustc_lint/src/lib.rs
@@ -21,6 +21,7 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(array_windows)]
@@ -28,7 +29,6 @@
#![feature(box_patterns)]
#![feature(if_let_guard)]
#![feature(iter_order_by)]
-#![feature(let_chains)]
#![feature(rustc_attrs)]
#![feature(rustdoc_internals)]
#![feature(try_blocks)]
diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs
index edb25e799045a..62ca7ce3ca995 100644
--- a/compiler/rustc_macros/src/lib.rs
+++ b/compiler/rustc_macros/src/lib.rs
@@ -1,7 +1,7 @@
// tidy-alphabetical-start
#![allow(rustc::default_hash_types)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(never_type)]
#![feature(proc_macro_diagnostic)]
#![feature(proc_macro_span)]
diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs
index 3b44c44fcb94e..3931be1654a35 100644
--- a/compiler/rustc_metadata/src/lib.rs
+++ b/compiler/rustc_metadata/src/lib.rs
@@ -1,5 +1,6 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(coroutines)]
@@ -8,7 +9,6 @@
#![feature(file_buffered)]
#![feature(if_let_guard)]
#![feature(iter_from_coroutine)]
-#![feature(let_chains)]
#![feature(macro_metavar_expr)]
#![feature(min_specialization)]
#![feature(never_type)]
diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs
index 8fe2cc7101ba3..df025aeebf048 100644
--- a/compiler/rustc_middle/src/lib.rs
+++ b/compiler/rustc_middle/src/lib.rs
@@ -29,6 +29,7 @@
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::potential_query_instability)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(allocator_api)]
@@ -48,7 +49,6 @@
#![feature(if_let_guard)]
#![feature(intra_doc_pointers)]
#![feature(iter_from_coroutine)]
-#![feature(let_chains)]
#![feature(min_specialization)]
#![feature(negative_impls)]
#![feature(never_type)]
diff --git a/compiler/rustc_mir_build/src/lib.rs b/compiler/rustc_mir_build/src/lib.rs
index 8e96d46dac272..a051cf570b7d1 100644
--- a/compiler/rustc_mir_build/src/lib.rs
+++ b/compiler/rustc_mir_build/src/lib.rs
@@ -3,10 +3,10 @@
// tidy-alphabetical-start
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(try_blocks)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_mir_dataflow/src/lib.rs b/compiler/rustc_mir_dataflow/src/lib.rs
index a0efc623b8e7e..38f82b1274658 100644
--- a/compiler/rustc_mir_dataflow/src/lib.rs
+++ b/compiler/rustc_mir_dataflow/src/lib.rs
@@ -1,10 +1,10 @@
// tidy-alphabetical-start
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(assert_matches)]
#![feature(associated_type_defaults)]
#![feature(box_patterns)]
#![feature(exact_size_is_empty)]
#![feature(file_buffered)]
-#![feature(let_chains)]
#![feature(never_type)]
#![feature(try_blocks)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs
index 4d74ecddfb057..a0e2619d09739 100644
--- a/compiler/rustc_mir_transform/src/lib.rs
+++ b/compiler/rustc_mir_transform/src/lib.rs
@@ -1,4 +1,5 @@
// tidy-alphabetical-start
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(array_windows)]
#![feature(assert_matches)]
#![feature(box_patterns)]
@@ -7,7 +8,6 @@
#![feature(file_buffered)]
#![feature(if_let_guard)]
#![feature(impl_trait_in_assoc_type)]
-#![feature(let_chains)]
#![feature(map_try_insert)]
#![feature(never_type)]
#![feature(try_blocks)]
diff --git a/compiler/rustc_monomorphize/src/lib.rs b/compiler/rustc_monomorphize/src/lib.rs
index 8f6914f3d7242..8469e0f17a69d 100644
--- a/compiler/rustc_monomorphize/src/lib.rs
+++ b/compiler/rustc_monomorphize/src/lib.rs
@@ -1,9 +1,9 @@
// tidy-alphabetical-start
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(array_windows)]
#![feature(file_buffered)]
#![feature(if_let_guard)]
#![feature(impl_trait_in_assoc_type)]
-#![feature(let_chains)]
// tidy-alphabetical-end
use rustc_hir::lang_items::LangItem;
diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs
index 2edc8c83017d8..14a12a8318941 100644
--- a/compiler/rustc_parse/src/lib.rs
+++ b/compiler/rustc_parse/src/lib.rs
@@ -4,13 +4,13 @@
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(array_windows)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(debug_closure_helpers)]
#![feature(if_let_guard)]
#![feature(iter_intersperse)]
-#![feature(let_chains)]
#![feature(string_from_utf8_lossy_owned)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_passes/src/lib.rs b/compiler/rustc_passes/src/lib.rs
index 93ff0f66d695b..c7bb00df796a7 100644
--- a/compiler/rustc_passes/src/lib.rs
+++ b/compiler/rustc_passes/src/lib.rs
@@ -6,9 +6,9 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
-#![feature(let_chains)]
#![feature(map_try_insert)]
#![feature(rustdoc_internals)]
#![feature(try_blocks)]
diff --git a/compiler/rustc_pattern_analysis/src/lib.rs b/compiler/rustc_pattern_analysis/src/lib.rs
index 176dcbf6da427..f63d8b2d79f61 100644
--- a/compiler/rustc_pattern_analysis/src/lib.rs
+++ b/compiler/rustc_pattern_analysis/src/lib.rs
@@ -6,7 +6,7 @@
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
#![allow(unused_crate_dependencies)]
-#![cfg_attr(feature = "rustc", feature(let_chains))]
+#![cfg_attr(all(feature = "rustc", bootstrap), feature(let_chains))]
// tidy-alphabetical-end
pub mod constructor;
diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs
index c7bab828659ae..0bde289c85fc0 100644
--- a/compiler/rustc_privacy/src/lib.rs
+++ b/compiler/rustc_privacy/src/lib.rs
@@ -1,9 +1,9 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(associated_type_defaults)]
-#![feature(let_chains)]
#![feature(rustdoc_internals)]
#![feature(try_blocks)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs
index 2aedd365adc89..b159b876c7e63 100644
--- a/compiler/rustc_query_system/src/lib.rs
+++ b/compiler/rustc_query_system/src/lib.rs
@@ -1,9 +1,9 @@
// tidy-alphabetical-start
#![allow(rustc::potential_query_instability, internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(assert_matches)]
#![feature(core_intrinsics)]
#![feature(dropck_eyepatch)]
-#![feature(let_chains)]
#![feature(min_specialization)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs
index b121755acd9c3..4a252a7b5281f 100644
--- a/compiler/rustc_resolve/src/lib.rs
+++ b/compiler/rustc_resolve/src/lib.rs
@@ -10,13 +10,13 @@
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(if_let_guard)]
#![feature(iter_intersperse)]
-#![feature(let_chains)]
#![feature(rustc_attrs)]
#![feature(rustdoc_internals)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_sanitizers/src/lib.rs b/compiler/rustc_sanitizers/src/lib.rs
index e4792563e71ea..729c921450ea0 100644
--- a/compiler/rustc_sanitizers/src/lib.rs
+++ b/compiler/rustc_sanitizers/src/lib.rs
@@ -4,7 +4,7 @@
//! compiler.
// tidy-alphabetical-start
-#![feature(let_chains)]
+#![cfg_attr(bootstrap, feature(let_chains))]
// tidy-alphabetical-end
pub mod cfi;
diff --git a/compiler/rustc_session/src/lib.rs b/compiler/rustc_session/src/lib.rs
index 0e19b982a133e..ec8e9898dc71e 100644
--- a/compiler/rustc_session/src/lib.rs
+++ b/compiler/rustc_session/src/lib.rs
@@ -1,8 +1,8 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![feature(default_field_values)]
#![feature(iter_intersperse)]
-#![feature(let_chains)]
#![feature(rustc_attrs)]
// To generate CodegenOptionsTargetModifiers and UnstableOptionsTargetModifiers enums
// with macro_rules, it is necessary to use recursive mechanic ("Incremental TT Munchers").
diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs
index f788fd48037a0..fccdaed21a20b 100644
--- a/compiler/rustc_span/src/lib.rs
+++ b/compiler/rustc_span/src/lib.rs
@@ -17,6 +17,7 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(array_windows)]
@@ -24,7 +25,6 @@
#![feature(core_io_borrowed_buf)]
#![feature(hash_set_entry)]
#![feature(if_let_guard)]
-#![feature(let_chains)]
#![feature(map_try_insert)]
#![feature(negative_impls)]
#![feature(read_buf)]
diff --git a/compiler/rustc_symbol_mangling/src/lib.rs b/compiler/rustc_symbol_mangling/src/lib.rs
index cc33974cc6275..ca8918e06aaf3 100644
--- a/compiler/rustc_symbol_mangling/src/lib.rs
+++ b/compiler/rustc_symbol_mangling/src/lib.rs
@@ -89,9 +89,9 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
-#![feature(let_chains)]
#![feature(rustdoc_internals)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_target/src/lib.rs b/compiler/rustc_target/src/lib.rs
index df99280f5712e..922c18448d51a 100644
--- a/compiler/rustc_target/src/lib.rs
+++ b/compiler/rustc_target/src/lib.rs
@@ -9,12 +9,12 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(debug_closure_helpers)]
#![feature(iter_intersperse)]
-#![feature(let_chains)]
#![feature(rustc_attrs)]
#![feature(rustdoc_internals)]
// tidy-alphabetical-end
diff --git a/compiler/rustc_trait_selection/src/lib.rs b/compiler/rustc_trait_selection/src/lib.rs
index 93c1180530452..7613a0cef52a7 100644
--- a/compiler/rustc_trait_selection/src/lib.rs
+++ b/compiler/rustc_trait_selection/src/lib.rs
@@ -14,6 +14,7 @@
#![allow(internal_features)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
@@ -23,7 +24,6 @@
#![feature(if_let_guard)]
#![feature(iter_intersperse)]
#![feature(iterator_try_reduce)]
-#![feature(let_chains)]
#![feature(never_type)]
#![feature(rustdoc_internals)]
#![feature(try_blocks)]
diff --git a/compiler/rustc_ty_utils/src/lib.rs b/compiler/rustc_ty_utils/src/lib.rs
index 35cc6f3985652..99252c28b4005 100644
--- a/compiler/rustc_ty_utils/src/lib.rs
+++ b/compiler/rustc_ty_utils/src/lib.rs
@@ -6,6 +6,7 @@
// tidy-alphabetical-start
#![allow(internal_features)]
+#![cfg_attr(bootstrap, feature(let_chains))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
@@ -13,7 +14,6 @@
#![feature(box_patterns)]
#![feature(if_let_guard)]
#![feature(iterator_try_collect)]
-#![feature(let_chains)]
#![feature(never_type)]
#![feature(rustdoc_internals)]
// tidy-alphabetical-end
| diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs
index 294c6c9ba7a50..1471262d2d676 100644
--- a/compiler/rustc_ast/src/lib.rs
+++ b/compiler/rustc_ast/src/lib.rs
#![doc(
html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
test(attr(deny(warnings)))
@@ -14,7 +15,6 @@
diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index c40987541f4a5..3ec00bfce73f5 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -32,12 +32,12 @@
diff --git a/compiler/rustc_ast_passes/src/lib.rs b/compiler/rustc_ast_passes/src/lib.rs
index 093199cf34212..7956057f88ee7 100644
--- a/compiler/rustc_ast_passes/src/lib.rs
+++ b/compiler/rustc_ast_passes/src/lib.rs
@@ -4,11 +4,11 @@
#![feature(iter_is_partitioned)]
diff --git a/compiler/rustc_attr_data_structures/src/lib.rs b/compiler/rustc_attr_data_structures/src/lib.rs
index c61b44b273de5..679fe935484e8 100644
--- a/compiler/rustc_attr_data_structures/src/lib.rs
+++ b/compiler/rustc_attr_data_structures/src/lib.rs
diff --git a/compiler/rustc_attr_parsing/src/lib.rs b/compiler/rustc_attr_parsing/src/lib.rs
index 249e71ef70dcf..b9692c01e2c42 100644
--- a/compiler/rustc_attr_parsing/src/lib.rs
+++ b/compiler/rustc_attr_parsing/src/lib.rs
@@ -77,8 +77,8 @@
diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs
index 3b66142eb2cec..dbf943ffdb62a 100644
--- a/compiler/rustc_borrowck/src/lib.rs
+++ b/compiler/rustc_borrowck/src/lib.rs
@@ -2,12 +2,12 @@
diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs
index bcd40f980e649..70e817db2a630 100644
--- a/compiler/rustc_builtin_macros/src/lib.rs
+++ b/compiler/rustc_builtin_macros/src/lib.rs
@@ -5,6 +5,7 @@
@@ -12,7 +13,6 @@
#![feature(proc_macro_internals)]
#![feature(proc_macro_quote)]
diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs
index 425381b0ffab7..b2feeacdb4664 100644
--- a/compiler/rustc_codegen_llvm/src/lib.rs
+++ b/compiler/rustc_codegen_llvm/src/lib.rs
@@ -15,7 +16,6 @@
#![feature(slice_as_array)]
diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs
index 5b2ed69535b9f..c927aae2c4c2b 100644
--- a/compiler/rustc_codegen_ssa/src/lib.rs
+++ b/compiler/rustc_codegen_ssa/src/lib.rs
@@ -2,13 +2,13 @@
diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs
index da52d60ae59fd..7a0c2543c3002 100644
--- a/compiler/rustc_const_eval/src/lib.rs
+++ b/compiler/rustc_const_eval/src/lib.rs
@@ -1,12 +1,12 @@
#![feature(slice_ptr_get)]
diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs
index 40cc82727a556..d18fa89281404 100644
--- a/compiler/rustc_driver_impl/src/lib.rs
+++ b/compiler/rustc_driver_impl/src/lib.rs
@@ -7,10 +7,10 @@
#![allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
#![feature(panic_backtrace_config)]
#![feature(panic_update_hook)]
#![feature(result_flattening)]
diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs
index c0c5dba46772a..6f37bad9bb462 100644
--- a/compiler/rustc_errors/src/lib.rs
+++ b/compiler/rustc_errors/src/lib.rs
@@ -7,6 +7,7 @@
@@ -17,7 +18,6 @@
#![feature(error_reporter)]
diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs
index 4222c9fe90616..79f838e2e33f2 100644
--- a/compiler/rustc_expand/src/lib.rs
+++ b/compiler/rustc_expand/src/lib.rs
diff --git a/compiler/rustc_hir/src/lib.rs b/compiler/rustc_hir/src/lib.rs
index a84857e3597b0..32064f96dd6c2 100644
--- a/compiler/rustc_hir/src/lib.rs
+++ b/compiler/rustc_hir/src/lib.rs
@@ -4,12 +4,12 @@
#![feature(closure_track_caller)]
#![feature(exhaustive_patterns)]
diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs
index e1ad8124aea76..309b8f2c76138 100644
--- a/compiler/rustc_hir_analysis/src/lib.rs
+++ b/compiler/rustc_hir_analysis/src/lib.rs
@@ -59,6 +59,7 @@ This API is completely unstable and subject to change.
@@ -67,7 +68,6 @@ This API is completely unstable and subject to change.
#![feature(slice_partition_dedup)]
diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs
index ff4385c3bccec..779fae80f19cd 100644
--- a/compiler/rustc_hir_pretty/src/lib.rs
+++ b/compiler/rustc_hir_pretty/src/lib.rs
@@ -2,7 +2,7 @@
//! the definitions in this file have equivalents in `rustc_ast_pretty`.
#![recursion_limit = "256"]
diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs
index af8ec37393472..c3717b4efa47f 100644
--- a/compiler/rustc_hir_typeck/src/lib.rs
+++ b/compiler/rustc_hir_typeck/src/lib.rs
diff --git a/compiler/rustc_infer/src/lib.rs b/compiler/rustc_infer/src/lib.rs
index ece18f4ea64ee..8b2aab4204228 100644
--- a/compiler/rustc_infer/src/lib.rs
+++ b/compiler/rustc_infer/src/lib.rs
@@ -16,12 +16,12 @@
#![feature(extend_one)]
#![recursion_limit = "512"] // For rustdoc
diff --git a/compiler/rustc_interface/src/lib.rs b/compiler/rustc_interface/src/lib.rs
index 67e0be93523d9..4128070718308 100644
--- a/compiler/rustc_interface/src/lib.rs
+++ b/compiler/rustc_interface/src/lib.rs
diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs
index 212368bea8266..b4bc648c9d814 100644
--- a/compiler/rustc_lint/src/lib.rs
+++ b/compiler/rustc_lint/src/lib.rs
@@ -21,6 +21,7 @@
@@ -28,7 +29,6 @@
#![feature(iter_order_by)]
diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs
index edb25e799045a..62ca7ce3ca995 100644
--- a/compiler/rustc_macros/src/lib.rs
+++ b/compiler/rustc_macros/src/lib.rs
#![allow(rustc::default_hash_types)]
#![feature(proc_macro_span)]
diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs
index 3b44c44fcb94e..3931be1654a35 100644
--- a/compiler/rustc_metadata/src/lib.rs
+++ b/compiler/rustc_metadata/src/lib.rs
@@ -1,5 +1,6 @@
#![feature(coroutines)]
@@ -8,7 +9,6 @@
diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs
index 8fe2cc7101ba3..df025aeebf048 100644
--- a/compiler/rustc_middle/src/lib.rs
+++ b/compiler/rustc_middle/src/lib.rs
@@ -29,6 +29,7 @@
#![allow(rustc::potential_query_instability)]
#![feature(allocator_api)]
@@ -48,7 +49,6 @@
#![feature(intra_doc_pointers)]
diff --git a/compiler/rustc_mir_build/src/lib.rs b/compiler/rustc_mir_build/src/lib.rs
index 8e96d46dac272..a051cf570b7d1 100644
--- a/compiler/rustc_mir_build/src/lib.rs
+++ b/compiler/rustc_mir_build/src/lib.rs
@@ -3,10 +3,10 @@
diff --git a/compiler/rustc_mir_dataflow/src/lib.rs b/compiler/rustc_mir_dataflow/src/lib.rs
index a0efc623b8e7e..38f82b1274658 100644
--- a/compiler/rustc_mir_dataflow/src/lib.rs
+++ b/compiler/rustc_mir_dataflow/src/lib.rs
@@ -1,10 +1,10 @@
diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs
index 4d74ecddfb057..a0e2619d09739 100644
--- a/compiler/rustc_mir_transform/src/lib.rs
+++ b/compiler/rustc_mir_transform/src/lib.rs
@@ -1,4 +1,5 @@
@@ -7,7 +8,6 @@
diff --git a/compiler/rustc_monomorphize/src/lib.rs b/compiler/rustc_monomorphize/src/lib.rs
index 8f6914f3d7242..8469e0f17a69d 100644
--- a/compiler/rustc_monomorphize/src/lib.rs
+++ b/compiler/rustc_monomorphize/src/lib.rs
use rustc_hir::lang_items::LangItem;
diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs
index 2edc8c83017d8..14a12a8318941 100644
--- a/compiler/rustc_parse/src/lib.rs
+++ b/compiler/rustc_parse/src/lib.rs
@@ -4,13 +4,13 @@
diff --git a/compiler/rustc_passes/src/lib.rs b/compiler/rustc_passes/src/lib.rs
index 93ff0f66d695b..c7bb00df796a7 100644
--- a/compiler/rustc_passes/src/lib.rs
+++ b/compiler/rustc_passes/src/lib.rs
@@ -6,9 +6,9 @@
diff --git a/compiler/rustc_pattern_analysis/src/lib.rs b/compiler/rustc_pattern_analysis/src/lib.rs
index 176dcbf6da427..f63d8b2d79f61 100644
--- a/compiler/rustc_pattern_analysis/src/lib.rs
+++ b/compiler/rustc_pattern_analysis/src/lib.rs
@@ -6,7 +6,7 @@
#![allow(unused_crate_dependencies)]
-#![cfg_attr(feature = "rustc", feature(let_chains))]
+#![cfg_attr(all(feature = "rustc", bootstrap), feature(let_chains))]
pub mod constructor;
diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs
index c7bab828659ae..0bde289c85fc0 100644
--- a/compiler/rustc_privacy/src/lib.rs
+++ b/compiler/rustc_privacy/src/lib.rs
diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs
index 2aedd365adc89..b159b876c7e63 100644
--- a/compiler/rustc_query_system/src/lib.rs
+++ b/compiler/rustc_query_system/src/lib.rs
#![allow(rustc::potential_query_instability, internal_features)]
#![feature(core_intrinsics)]
#![feature(dropck_eyepatch)]
diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs
index b121755acd9c3..4a252a7b5281f 100644
--- a/compiler/rustc_resolve/src/lib.rs
+++ b/compiler/rustc_resolve/src/lib.rs
@@ -10,13 +10,13 @@
diff --git a/compiler/rustc_sanitizers/src/lib.rs b/compiler/rustc_sanitizers/src/lib.rs
index e4792563e71ea..729c921450ea0 100644
--- a/compiler/rustc_sanitizers/src/lib.rs
+++ b/compiler/rustc_sanitizers/src/lib.rs
@@ -4,7 +4,7 @@
//! compiler.
pub mod cfi;
diff --git a/compiler/rustc_session/src/lib.rs b/compiler/rustc_session/src/lib.rs
index 0e19b982a133e..ec8e9898dc71e 100644
--- a/compiler/rustc_session/src/lib.rs
+++ b/compiler/rustc_session/src/lib.rs
// To generate CodegenOptionsTargetModifiers and UnstableOptionsTargetModifiers enums
// with macro_rules, it is necessary to use recursive mechanic ("Incremental TT Munchers").
diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs
index f788fd48037a0..fccdaed21a20b 100644
--- a/compiler/rustc_span/src/lib.rs
+++ b/compiler/rustc_span/src/lib.rs
@@ -17,6 +17,7 @@
@@ -24,7 +25,6 @@
#![feature(core_io_borrowed_buf)]
#![feature(hash_set_entry)]
#![feature(read_buf)]
diff --git a/compiler/rustc_symbol_mangling/src/lib.rs b/compiler/rustc_symbol_mangling/src/lib.rs
index cc33974cc6275..ca8918e06aaf3 100644
--- a/compiler/rustc_symbol_mangling/src/lib.rs
+++ b/compiler/rustc_symbol_mangling/src/lib.rs
@@ -89,9 +89,9 @@
diff --git a/compiler/rustc_target/src/lib.rs b/compiler/rustc_target/src/lib.rs
index df99280f5712e..922c18448d51a 100644
--- a/compiler/rustc_target/src/lib.rs
+++ b/compiler/rustc_target/src/lib.rs
@@ -9,12 +9,12 @@
diff --git a/compiler/rustc_trait_selection/src/lib.rs b/compiler/rustc_trait_selection/src/lib.rs
index 93c1180530452..7613a0cef52a7 100644
--- a/compiler/rustc_trait_selection/src/lib.rs
+++ b/compiler/rustc_trait_selection/src/lib.rs
@@ -14,6 +14,7 @@
@@ -23,7 +24,6 @@
#![feature(iterator_try_reduce)]
diff --git a/compiler/rustc_ty_utils/src/lib.rs b/compiler/rustc_ty_utils/src/lib.rs
index 35cc6f3985652..99252c28b4005 100644
--- a/compiler/rustc_ty_utils/src/lib.rs
+++ b/compiler/rustc_ty_utils/src/lib.rs
@@ -13,7 +14,6 @@ | [] | [] | {
"additions": 40,
"author": "est31",
"deletions": 40,
"html_url": "https://github.com/rust-lang/rust/pull/140202",
"issue_id": 140202,
"merged_at": "2025-04-25T15:37:51Z",
"omission_probability": 0.1,
"pr_number": 140202,
"repo": "rust-lang/rust",
"title": "Make #![feature(let_chains)] bootstrap conditional in compiler/",
"total_changes": 80
} |
113 | diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs
index 7e17f09aecdcb..beaa6497b8caa 100644
--- a/src/librustdoc/html/render/mod.rs
+++ b/src/librustdoc/html/render/mod.rs
@@ -2086,6 +2086,7 @@ fn render_impl(
.split_summary_and_content()
})
.unwrap_or((None, None));
+
write!(
w,
"{}",
@@ -2097,24 +2098,19 @@ fn render_impl(
use_absolute,
aliases,
before_dox.as_deref(),
+ trait_.is_none() && impl_.items.is_empty(),
)
)?;
if toggled {
w.write_str("</summary>")?;
}
- if before_dox.is_some() {
- if trait_.is_none() && impl_.items.is_empty() {
- w.write_str(
- "<div class=\"item-info\">\
- <div class=\"stab empty-impl\">This impl block contains no items.</div>\
- </div>",
- )?;
- }
- if let Some(after_dox) = after_dox {
- write!(w, "<div class=\"docblock\">{after_dox}</div>")?;
- }
+ if before_dox.is_some()
+ && let Some(after_dox) = after_dox
+ {
+ write!(w, "<div class=\"docblock\">{after_dox}</div>")?;
}
+
if !default_impl_items.is_empty() || !impl_items.is_empty() {
w.write_str("<div class=\"impl-items\">")?;
close_tags.push("</div>");
@@ -2182,6 +2178,7 @@ fn render_impl_summary(
// in documentation pages for trait with automatic implementations like "Send" and "Sync".
aliases: &[String],
doc: Option<&str>,
+ impl_is_empty: bool,
) -> impl fmt::Display {
fmt::from_fn(move |w| {
let inner_impl = i.inner_impl();
@@ -2237,6 +2234,13 @@ fn render_impl_summary(
}
if let Some(doc) = doc {
+ if impl_is_empty {
+ w.write_str(
+ "<div class=\"item-info\">\
+ <div class=\"stab empty-impl\">This impl block contains no items.</div>\
+ </div>",
+ )?;
+ }
write!(w, "<div class=\"docblock\">{doc}</div>")?;
}
diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css
index a6dd06b76ea97..19ac24a5d6e3d 100644
--- a/src/librustdoc/html/static/css/rustdoc.css
+++ b/src/librustdoc/html/static/css/rustdoc.css
@@ -2319,7 +2319,10 @@ details.toggle > summary:not(.hideme)::before {
doc block while aligning it with the impl block items. */
.implementors-toggle > .docblock,
/* We indent trait items as well. */
-#main-content > .methods > :not(.item-info) {
+#main-content > .methods > :not(.item-info),
+.impl > .item-info,
+.impl > .docblock,
+.impl + .docblock {
margin-left: var(--impl-items-indent);
}
diff --git a/tests/rustdoc-gui/docblock-table-overflow.goml b/tests/rustdoc-gui/docblock-table-overflow.goml
index 18e5b4d7f3590..e603c3a4d22e0 100644
--- a/tests/rustdoc-gui/docblock-table-overflow.goml
+++ b/tests/rustdoc-gui/docblock-table-overflow.goml
@@ -11,7 +11,7 @@ assert-property: (".top-doc .docblock table", {"scrollWidth": "1572"})
// Checking it works on other doc blocks as well...
// Logically, the ".docblock" and the "<p>" should have the same scroll width (if we exclude the margin).
-assert-property: ("#implementations-list > details .docblock", {"scrollWidth": 816})
+assert-property: ("#implementations-list > details .docblock", {"scrollWidth": 835})
assert-property: ("#implementations-list > details .docblock > p", {"scrollWidth": 835})
// However, since there is overflow in the <table>, its scroll width is bigger.
assert-property: ("#implementations-list > details .docblock table", {"scrollWidth": "1572"})
diff --git a/tests/rustdoc-gui/impl-doc-indent.goml b/tests/rustdoc-gui/impl-doc-indent.goml
new file mode 100644
index 0000000000000..d647fec6d732d
--- /dev/null
+++ b/tests/rustdoc-gui/impl-doc-indent.goml
@@ -0,0 +1,16 @@
+// Checks the impl block docs have the correct indent.
+go-to: "file://" + |DOC_PATH| + "/test_docs/impls_indent/struct.Context.html"
+
+// First we ensure that the impl items are indent (more on the right of the screen) than the
+// impl itself.
+store-position: ("#impl-Context", {"x": impl_x})
+store-position: ("#impl-Context > .item-info", {"x": impl_item_x})
+assert: |impl_x| < |impl_item_x|
+
+// And we ensure that all impl items have the same indent.
+assert-position: ("#impl-Context > .docblock", {"x": |impl_item_x|})
+assert-position: ("#impl-Context + .docblock", {"x": |impl_item_x|})
+
+// Same with the collapsible impl block.
+assert-position: ("#impl-Context-1 > .docblock", {"x": |impl_item_x|})
+assert-position: (".implementors-toggle > summary + .docblock", {"x": |impl_item_x|})
diff --git a/tests/rustdoc-gui/item-info-overflow.goml b/tests/rustdoc-gui/item-info-overflow.goml
index c325beb6d0669..2c4e06e297c7d 100644
--- a/tests/rustdoc-gui/item-info-overflow.goml
+++ b/tests/rustdoc-gui/item-info-overflow.goml
@@ -21,7 +21,7 @@ compare-elements-property: (
)
assert-property: (
"#impl-SimpleTrait-for-LongItemInfo2 .item-info",
- {"scrollWidth": "916"},
+ {"scrollWidth": "935"},
)
// Just to be sure we're comparing the correct "item-info":
assert-text: (
diff --git a/tests/rustdoc-gui/src/test_docs/lib.rs b/tests/rustdoc-gui/src/test_docs/lib.rs
index 31f6b7f09b7d0..bb0015b8f9c43 100644
--- a/tests/rustdoc-gui/src/test_docs/lib.rs
+++ b/tests/rustdoc-gui/src/test_docs/lib.rs
@@ -740,3 +740,29 @@ pub mod SidebarSort {
impl Sort for Cell<u8> {}
impl<'a> Sort for &'a str {}
}
+
+pub mod impls_indent {
+ pub struct Context;
+
+ /// Working with objects.
+ ///
+ /// # Safety
+ ///
+ /// Functions that take indices of locals do not check bounds on these indices;
+ /// the caller must ensure that the indices are less than the number of locals
+ /// in the current stack frame.
+ impl Context {
+ }
+
+ /// Working with objects.
+ ///
+ /// # Safety
+ ///
+ /// Functions that take indices of locals do not check bounds on these indices;
+ /// the caller must ensure that the indices are less than the number of locals
+ /// in the current stack frame.
+ impl Context {
+ /// bla
+ pub fn bar() {}
+ }
+}
| diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs
index 7e17f09aecdcb..beaa6497b8caa 100644
--- a/src/librustdoc/html/render/mod.rs
+++ b/src/librustdoc/html/render/mod.rs
@@ -2086,6 +2086,7 @@ fn render_impl(
.split_summary_and_content()
})
.unwrap_or((None, None));
write!(
w,
"{}",
@@ -2097,24 +2098,19 @@ fn render_impl(
use_absolute,
aliases,
before_dox.as_deref(),
+ trait_.is_none() && impl_.items.is_empty(),
)
)?;
if toggled {
w.write_str("</summary>")?;
- if before_dox.is_some() {
- if trait_.is_none() && impl_.items.is_empty() {
- w.write_str(
- "<div class=\"item-info\">\
- <div class=\"stab empty-impl\">This impl block contains no items.</div>\
- </div>",
- )?;
- if let Some(after_dox) = after_dox {
- write!(w, "<div class=\"docblock\">{after_dox}</div>")?;
+ && let Some(after_dox) = after_dox
+ {
+ write!(w, "<div class=\"docblock\">{after_dox}</div>")?;
if !default_impl_items.is_empty() || !impl_items.is_empty() {
w.write_str("<div class=\"impl-items\">")?;
close_tags.push("</div>");
@@ -2182,6 +2178,7 @@ fn render_impl_summary(
// in documentation pages for trait with automatic implementations like "Send" and "Sync".
aliases: &[String],
doc: Option<&str>,
+ impl_is_empty: bool,
) -> impl fmt::Display {
fmt::from_fn(move |w| {
let inner_impl = i.inner_impl();
@@ -2237,6 +2234,13 @@ fn render_impl_summary(
if let Some(doc) = doc {
+ if impl_is_empty {
+ w.write_str(
+ "<div class=\"item-info\">\
+ <div class=\"stab empty-impl\">This impl block contains no items.</div>\
+ </div>",
+ )?;
+ }
write!(w, "<div class=\"docblock\">{doc}</div>")?;
diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css
index a6dd06b76ea97..19ac24a5d6e3d 100644
--- a/src/librustdoc/html/static/css/rustdoc.css
+++ b/src/librustdoc/html/static/css/rustdoc.css
@@ -2319,7 +2319,10 @@ details.toggle > summary:not(.hideme)::before {
doc block while aligning it with the impl block items. */
.implementors-toggle > .docblock,
/* We indent trait items as well. */
-#main-content > .methods > :not(.item-info) {
+#main-content > .methods > :not(.item-info),
+.impl > .item-info,
+.impl > .docblock,
+.impl + .docblock {
margin-left: var(--impl-items-indent);
diff --git a/tests/rustdoc-gui/docblock-table-overflow.goml b/tests/rustdoc-gui/docblock-table-overflow.goml
index 18e5b4d7f3590..e603c3a4d22e0 100644
--- a/tests/rustdoc-gui/docblock-table-overflow.goml
+++ b/tests/rustdoc-gui/docblock-table-overflow.goml
@@ -11,7 +11,7 @@ assert-property: (".top-doc .docblock table", {"scrollWidth": "1572"})
// Checking it works on other doc blocks as well...
// Logically, the ".docblock" and the "<p>" should have the same scroll width (if we exclude the margin).
-assert-property: ("#implementations-list > details .docblock", {"scrollWidth": 816})
assert-property: ("#implementations-list > details .docblock > p", {"scrollWidth": 835})
// However, since there is overflow in the <table>, its scroll width is bigger.
assert-property: ("#implementations-list > details .docblock table", {"scrollWidth": "1572"})
diff --git a/tests/rustdoc-gui/impl-doc-indent.goml b/tests/rustdoc-gui/impl-doc-indent.goml
new file mode 100644
index 0000000000000..d647fec6d732d
--- /dev/null
+++ b/tests/rustdoc-gui/impl-doc-indent.goml
@@ -0,0 +1,16 @@
+// Checks the impl block docs have the correct indent.
+go-to: "file://" + |DOC_PATH| + "/test_docs/impls_indent/struct.Context.html"
+// First we ensure that the impl items are indent (more on the right of the screen) than the
+// impl itself.
+store-position: ("#impl-Context", {"x": impl_x})
+store-position: ("#impl-Context > .item-info", {"x": impl_item_x})
+assert: |impl_x| < |impl_item_x|
+// And we ensure that all impl items have the same indent.
+assert-position: ("#impl-Context > .docblock", {"x": |impl_item_x|})
+assert-position: ("#impl-Context + .docblock", {"x": |impl_item_x|})
+// Same with the collapsible impl block.
+assert-position: ("#impl-Context-1 > .docblock", {"x": |impl_item_x|})
+assert-position: (".implementors-toggle > summary + .docblock", {"x": |impl_item_x|})
diff --git a/tests/rustdoc-gui/item-info-overflow.goml b/tests/rustdoc-gui/item-info-overflow.goml
index c325beb6d0669..2c4e06e297c7d 100644
--- a/tests/rustdoc-gui/item-info-overflow.goml
+++ b/tests/rustdoc-gui/item-info-overflow.goml
@@ -21,7 +21,7 @@ compare-elements-property: (
assert-property: (
"#impl-SimpleTrait-for-LongItemInfo2 .item-info",
- {"scrollWidth": "916"},
+ {"scrollWidth": "935"},
// Just to be sure we're comparing the correct "item-info":
assert-text: (
diff --git a/tests/rustdoc-gui/src/test_docs/lib.rs b/tests/rustdoc-gui/src/test_docs/lib.rs
index 31f6b7f09b7d0..bb0015b8f9c43 100644
--- a/tests/rustdoc-gui/src/test_docs/lib.rs
+++ b/tests/rustdoc-gui/src/test_docs/lib.rs
@@ -740,3 +740,29 @@ pub mod SidebarSort {
impl Sort for Cell<u8> {}
impl<'a> Sort for &'a str {}
+ pub struct Context;
+ /// bla
+ pub fn bar() {}
+} | [
"+ if before_dox.is_some()",
"+assert-property: (\"#implementations-list > details .docblock\", {\"scrollWidth\": 835})",
"+pub mod impls_indent {"
] | [
34,
90,
138
] | {
"additions": 63,
"author": "GuillaumeGomez",
"deletions": 14,
"html_url": "https://github.com/rust-lang/rust/pull/140248",
"issue_id": 140248,
"merged_at": "2025-04-25T12:26:12Z",
"omission_probability": 0.1,
"pr_number": 140248,
"repo": "rust-lang/rust",
"title": "Fix impl block items indent",
"total_changes": 77
} |
114 | diff --git a/INSTALL.md b/INSTALL.md
index 30e08201d6dfb..98eb825cd10f6 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -75,8 +75,31 @@ See [the rustc-dev-guide for more info][sysllvm].
2. Configure the build settings:
+ If you're unsure which build configurations to use and need a good default, you
+ can run the interactive `x.py setup` command. This will guide you through selecting
+ a config profile, setting up the LSP, configuring a Git hook, etc.
+
+ With `configure` script, you can handle multiple configurations in a single
+ command which is useful to create complex/advanced config files. For example:
+
```sh
- ./configure
+ ./configure --build=aarch64-unknown-linux-gnu \
+ --enable-full-tools \
+ --enable-profiler \
+ --enable-sanitizers \
+ --enable-compiler-docs \
+ --set target.aarch64-unknown-linux-gnu.linker=clang \
+ --set target.aarch64-unknown-linux-gnu.ar=/rustroot/bin/llvm-ar \
+ --set target.aarch64-unknown-linux-gnu.ranlib=/rustroot/bin/llvm-ranlib \
+ --set llvm.link-shared=true \
+ --set llvm.thin-lto=true \
+ --set llvm.libzstd=true \
+ --set llvm.ninja=false \
+ --set rust.debug-assertions=false \
+ --set rust.jemalloc \
+ --set rust.use-lld=true \
+ --set rust.lto=thin \
+ --set rust.codegen-units=1
```
If you plan to use `x.py install` to create an installation, you can either
| diff --git a/INSTALL.md b/INSTALL.md
index 30e08201d6dfb..98eb825cd10f6 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -75,8 +75,31 @@ See [the rustc-dev-guide for more info][sysllvm].
2. Configure the build settings:
+ If you're unsure which build configurations to use and need a good default, you
+ can run the interactive `x.py setup` command. This will guide you through selecting
+ a config profile, setting up the LSP, configuring a Git hook, etc.
+ With `configure` script, you can handle multiple configurations in a single
+ command which is useful to create complex/advanced config files. For example:
```sh
- ./configure
+ ./configure --build=aarch64-unknown-linux-gnu \
+ --enable-full-tools \
+ --enable-profiler \
+ --enable-sanitizers \
+ --enable-compiler-docs \
+ --set target.aarch64-unknown-linux-gnu.linker=clang \
+ --set target.aarch64-unknown-linux-gnu.ar=/rustroot/bin/llvm-ar \
+ --set target.aarch64-unknown-linux-gnu.ranlib=/rustroot/bin/llvm-ranlib \
+ --set llvm.link-shared=true \
+ --set llvm.thin-lto=true \
+ --set llvm.libzstd=true \
+ --set llvm.ninja=false \
+ --set rust.jemalloc \
+ --set rust.use-lld=true \
+ --set rust.lto=thin \
+ --set rust.codegen-units=1
```
If you plan to use `x.py install` to create an installation, you can either | [
"+ --set rust.debug-assertions=false \\"
] | [
29
] | {
"additions": 24,
"author": "onur-ozkan",
"deletions": 1,
"html_url": "https://github.com/rust-lang/rust/pull/140213",
"issue_id": 140213,
"merged_at": "2025-04-25T12:26:12Z",
"omission_probability": 0.1,
"pr_number": 140213,
"repo": "rust-lang/rust",
"title": "mention about `x.py setup` in `INSTALL.md`",
"total_changes": 25
} |
115 | diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs
index b19d9efe2c6f5..caf36ba47bd75 100644
--- a/compiler/rustc_hir_typeck/src/cast.rs
+++ b/compiler/rustc_hir_typeck/src/cast.rs
@@ -501,12 +501,25 @@ impl<'a, 'tcx> CastCheck<'tcx> {
.must_apply_modulo_regions()
{
label = false;
- err.span_suggestion(
- self.span,
- "consider using the `From` trait instead",
- format!("{}::from({})", self.cast_ty, snippet),
- Applicability::MaybeIncorrect,
- );
+ if let ty::Adt(def, args) = self.cast_ty.kind() {
+ err.span_suggestion_verbose(
+ self.span,
+ "consider using the `From` trait instead",
+ format!(
+ "{}::from({})",
+ fcx.tcx.value_path_str_with_args(def.did(), args),
+ snippet
+ ),
+ Applicability::MaybeIncorrect,
+ );
+ } else {
+ err.span_suggestion(
+ self.span,
+ "consider using the `From` trait instead",
+ format!("{}::from({})", self.cast_ty, snippet),
+ Applicability::MaybeIncorrect,
+ );
+ };
}
}
diff --git a/tests/ui/coercion/issue-73886.stderr b/tests/ui/coercion/issue-73886.stderr
index a6f8ba65ab51a..0d4c90017cf11 100644
--- a/tests/ui/coercion/issue-73886.stderr
+++ b/tests/ui/coercion/issue-73886.stderr
@@ -8,9 +8,14 @@ error[E0605]: non-primitive cast: `u32` as `Option<_>`
--> $DIR/issue-73886.rs:4:13
|
LL | let _ = 7u32 as Option<_>;
- | ^^^^^^^^^^^^^^^^^ help: consider using the `From` trait instead: `Option<_>::from(7u32)`
+ | ^^^^^^^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
+help: consider using the `From` trait instead
+ |
+LL - let _ = 7u32 as Option<_>;
+LL + let _ = Option::<_>::from(7u32);
+ |
error: aborting due to 2 previous errors
diff --git a/tests/ui/coercion/non-primitive-cast-135412.fixed b/tests/ui/coercion/non-primitive-cast-135412.fixed
new file mode 100644
index 0000000000000..5cadc9368d52e
--- /dev/null
+++ b/tests/ui/coercion/non-primitive-cast-135412.fixed
@@ -0,0 +1,10 @@
+//@ run-rustfix
+
+use std::sync::Arc;
+
+fn main() {
+ let _ = Option::<_>::from(7u32);
+ //~^ ERROR non-primitive cast: `u32` as `Option<_>`
+ let _ = Arc::<str>::from("String");
+ //~^ ERROR non-primitive cast: `&'static str` as `Arc<str>`
+}
diff --git a/tests/ui/coercion/non-primitive-cast-135412.rs b/tests/ui/coercion/non-primitive-cast-135412.rs
new file mode 100644
index 0000000000000..67a3ef340d2f1
--- /dev/null
+++ b/tests/ui/coercion/non-primitive-cast-135412.rs
@@ -0,0 +1,10 @@
+//@ run-rustfix
+
+use std::sync::Arc;
+
+fn main() {
+ let _ = 7u32 as Option<_>;
+ //~^ ERROR non-primitive cast: `u32` as `Option<_>`
+ let _ = "String" as Arc<str>;
+ //~^ ERROR non-primitive cast: `&'static str` as `Arc<str>`
+}
diff --git a/tests/ui/coercion/non-primitive-cast-135412.stderr b/tests/ui/coercion/non-primitive-cast-135412.stderr
new file mode 100644
index 0000000000000..7e5861f83e9c1
--- /dev/null
+++ b/tests/ui/coercion/non-primitive-cast-135412.stderr
@@ -0,0 +1,29 @@
+error[E0605]: non-primitive cast: `u32` as `Option<_>`
+ --> $DIR/non-primitive-cast-135412.rs:6:13
+ |
+LL | let _ = 7u32 as Option<_>;
+ | ^^^^^^^^^^^^^^^^^
+ |
+ = note: an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
+help: consider using the `From` trait instead
+ |
+LL - let _ = 7u32 as Option<_>;
+LL + let _ = Option::<_>::from(7u32);
+ |
+
+error[E0605]: non-primitive cast: `&'static str` as `Arc<str>`
+ --> $DIR/non-primitive-cast-135412.rs:8:13
+ |
+LL | let _ = "String" as Arc<str>;
+ | ^^^^^^^^^^^^^^^^^^^^
+ |
+ = note: an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
+help: consider using the `From` trait instead
+ |
+LL - let _ = "String" as Arc<str>;
+LL + let _ = Arc::<str>::from("String");
+ |
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0605`.
| diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs
index b19d9efe2c6f5..caf36ba47bd75 100644
--- a/compiler/rustc_hir_typeck/src/cast.rs
+++ b/compiler/rustc_hir_typeck/src/cast.rs
@@ -501,12 +501,25 @@ impl<'a, 'tcx> CastCheck<'tcx> {
.must_apply_modulo_regions()
{
label = false;
- err.span_suggestion(
- self.span,
- "consider using the `From` trait instead",
- format!("{}::from({})", self.cast_ty, snippet),
- Applicability::MaybeIncorrect,
- );
+ if let ty::Adt(def, args) = self.cast_ty.kind() {
+ err.span_suggestion_verbose(
+ format!(
+ "{}::from({})",
+ fcx.tcx.value_path_str_with_args(def.did(), args),
+ snippet
+ ),
+ } else {
+ err.span_suggestion(
+ format!("{}::from({})", self.cast_ty, snippet),
}
}
diff --git a/tests/ui/coercion/issue-73886.stderr b/tests/ui/coercion/issue-73886.stderr
index a6f8ba65ab51a..0d4c90017cf11 100644
--- a/tests/ui/coercion/issue-73886.stderr
+++ b/tests/ui/coercion/issue-73886.stderr
@@ -8,9 +8,14 @@ error[E0605]: non-primitive cast: `u32` as `Option<_>`
--> $DIR/issue-73886.rs:4:13
LL | let _ = 7u32 as Option<_>;
- | ^^^^^^^^^^^^^^^^^ help: consider using the `From` trait instead: `Option<_>::from(7u32)`
= note: an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
error: aborting due to 2 previous errors
diff --git a/tests/ui/coercion/non-primitive-cast-135412.fixed b/tests/ui/coercion/non-primitive-cast-135412.fixed
index 0000000000000..5cadc9368d52e
+++ b/tests/ui/coercion/non-primitive-cast-135412.fixed
+ let _ = Option::<_>::from(7u32);
+ let _ = Arc::<str>::from("String");
diff --git a/tests/ui/coercion/non-primitive-cast-135412.rs b/tests/ui/coercion/non-primitive-cast-135412.rs
index 0000000000000..67a3ef340d2f1
+++ b/tests/ui/coercion/non-primitive-cast-135412.rs
+ let _ = 7u32 as Option<_>;
+ let _ = "String" as Arc<str>;
diff --git a/tests/ui/coercion/non-primitive-cast-135412.stderr b/tests/ui/coercion/non-primitive-cast-135412.stderr
index 0000000000000..7e5861f83e9c1
+++ b/tests/ui/coercion/non-primitive-cast-135412.stderr
@@ -0,0 +1,29 @@
+error[E0605]: non-primitive cast: `u32` as `Option<_>`
+ --> $DIR/non-primitive-cast-135412.rs:6:13
+LL | let _ = 7u32 as Option<_>;
+error[E0605]: non-primitive cast: `&'static str` as `Arc<str>`
+ --> $DIR/non-primitive-cast-135412.rs:8:13
+LL | let _ = "String" as Arc<str>;
+ | ^^^^^^^^^^^^^^^^^^^^
+LL + let _ = Arc::<str>::from("String");
+error: aborting due to 2 previous errors
+For more information about this error, try `rustc --explain E0605`. | [
"+ };",
"+LL - let _ = \"String\" as Arc<str>;"
] | [
32,
116
] | {
"additions": 74,
"author": "Kivooeo",
"deletions": 7,
"html_url": "https://github.com/rust-lang/rust/pull/140196",
"issue_id": 140196,
"merged_at": "2025-04-25T12:26:12Z",
"omission_probability": 0.1,
"pr_number": 140196,
"repo": "rust-lang/rust",
"title": "Improved diagnostics for non-primitive cast on non-primitive types (`Arc`, `Option`)",
"total_changes": 81
} |
116 | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2e83bbf643fee..7c46871569646 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -91,6 +91,17 @@ jobs:
# Check the `calculate_matrix` job to see how is the matrix defined.
include: ${{ fromJSON(needs.calculate_matrix.outputs.jobs) }}
steps:
+ - name: Install cargo in AWS CodeBuild
+ if: matrix.codebuild
+ run: |
+ # Check if cargo is installed
+ if ! command -v cargo &> /dev/null; then
+ echo "Cargo not found, installing Rust..."
+ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal
+ # Make cargo available in PATH
+ echo "$HOME/.cargo/bin" >> $GITHUB_PATH
+ fi
+
- name: disable git crlf conversion
run: git config --global core.autocrlf false
@@ -168,6 +179,8 @@ jobs:
run: src/ci/scripts/install-ninja.sh
- name: enable ipv6 on Docker
+ # Don't run on codebuild because systemctl is not available
+ if: ${{ !matrix.codebuild }}
run: src/ci/scripts/enable-docker-ipv6.sh
# Disable automatic line ending conversion (again). On Windows, when we're
diff --git a/src/ci/citool/src/jobs.rs b/src/ci/citool/src/jobs.rs
index 13880ad466a6b..5600d7b4db59b 100644
--- a/src/ci/citool/src/jobs.rs
+++ b/src/ci/citool/src/jobs.rs
@@ -3,12 +3,15 @@ mod tests;
use std::collections::BTreeMap;
+use anyhow::Context as _;
use serde_yaml::Value;
use crate::GitHubContext;
+use crate::utils::load_env_var;
/// Representation of a job loaded from the `src/ci/github-actions/jobs.yml` file.
#[derive(serde::Deserialize, Debug, Clone)]
+#[serde(deny_unknown_fields)]
pub struct Job {
/// Name of the job, e.g. mingw-check
pub name: String,
@@ -26,6 +29,8 @@ pub struct Job {
pub free_disk: Option<bool>,
/// Documentation link to a resource that could help people debug this CI job.
pub doc_url: Option<String>,
+ /// Whether the job is executed on AWS CodeBuild.
+ pub codebuild: Option<bool>,
}
impl Job {
@@ -80,7 +85,7 @@ impl JobDatabase {
}
pub fn load_job_db(db: &str) -> anyhow::Result<JobDatabase> {
- let mut db: Value = serde_yaml::from_str(&db)?;
+ let mut db: Value = serde_yaml::from_str(db)?;
// We need to expand merge keys (<<), because serde_yaml can't deal with them
// `apply_merge` only applies the merge once, so do it a few times to unwrap nested merges.
@@ -107,6 +112,29 @@ struct GithubActionsJob {
free_disk: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
doc_url: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ codebuild: Option<bool>,
+}
+
+/// Replace GitHub context variables with environment variables in job configs.
+/// Used for codebuild jobs like
+/// `codebuild-ubuntu-22-8c-$github.run_id-$github.run_attempt`
+fn substitute_github_vars(jobs: Vec<Job>) -> anyhow::Result<Vec<Job>> {
+ let run_id = load_env_var("GITHUB_RUN_ID")?;
+ let run_attempt = load_env_var("GITHUB_RUN_ATTEMPT")?;
+
+ let jobs = jobs
+ .into_iter()
+ .map(|mut job| {
+ job.os = job
+ .os
+ .replace("$github.run_id", &run_id)
+ .replace("$github.run_attempt", &run_attempt);
+ job
+ })
+ .collect();
+
+ Ok(jobs)
}
/// Skip CI jobs that are not supposed to be executed on the given `channel`.
@@ -177,6 +205,8 @@ fn calculate_jobs(
}
RunType::AutoJob => (db.auto_jobs.clone(), "auto", &db.envs.auto_env),
};
+ let jobs = substitute_github_vars(jobs.clone())
+ .context("Failed to substitute GitHub context variables in jobs")?;
let jobs = skip_jobs(jobs, channel);
let jobs = jobs
.into_iter()
@@ -207,6 +237,7 @@ fn calculate_jobs(
continue_on_error: job.continue_on_error,
free_disk: job.free_disk,
doc_url: job.doc_url,
+ codebuild: job.codebuild,
}
})
.collect();
diff --git a/src/ci/docker/host-x86_64/dist-arm-linux/Dockerfile b/src/ci/docker/host-x86_64/dist-arm-linux/Dockerfile
index 420c42bc9d807..3795859f308e6 100644
--- a/src/ci/docker/host-x86_64/dist-arm-linux/Dockerfile
+++ b/src/ci/docker/host-x86_64/dist-arm-linux/Dockerfile
@@ -1,4 +1,4 @@
-FROM ubuntu:22.04
+FROM ghcr.io/rust-lang/ubuntu:22.04
COPY scripts/cross-apt-packages.sh /scripts/
RUN sh /scripts/cross-apt-packages.sh
diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh
index 00d791eeb6b38..36f7df2b06907 100755
--- a/src/ci/docker/run.sh
+++ b/src/ci/docker/run.sh
@@ -288,7 +288,7 @@ args="$args --privileged"
# `LOCAL_USER_ID` (recognized in `src/ci/run.sh`) to ensure that files are all
# read/written as the same user as the bare-metal user.
if [ -f /.dockerenv ]; then
- docker create -v /checkout --name checkout alpine:3.4 /bin/true
+ docker create -v /checkout --name checkout ghcr.io/rust-lang/alpine:3.4 /bin/true
docker cp . checkout:/checkout
args="$args --volumes-from checkout"
else
diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml
index cb2bec5a9dfa6..367e45ebe2006 100644
--- a/src/ci/github-actions/jobs.yml
+++ b/src/ci/github-actions/jobs.yml
@@ -56,6 +56,15 @@ runners:
- &job-aarch64-linux-8c
os: ubuntu-24.04-arm64-8core-32gb
<<: *base-job
+
+ # Codebuild runners are provisioned in
+ # https://github.com/rust-lang/simpleinfra/blob/b7ddd5e6bec8a93ec30510cdddec02c5666fefe9/terragrunt/accounts/ci-prod/ci-runners/terragrunt.hcl#L2
+ - &job-linux-36c-codebuild
+ free_disk: true
+ codebuild: true
+ os: codebuild-ubuntu-22-36c-$github.run_id-$github.run_attempt
+ <<: *base-job
+
envs:
env-x86_64-apple-tests: &env-x86_64-apple-tests
SCRIPT: ./x.py check compiletest --set build.compiletest-use-stage0-libtest=true && ./x.py --stage 2 test --skip tests/ui --skip tests/rustdoc -- --exact
@@ -153,7 +162,7 @@ auto:
<<: *job-linux-4c
- name: dist-arm-linux
- <<: *job-linux-8c
+ <<: *job-linux-36c-codebuild
- name: dist-armhf-linux
<<: *job-linux-4c
diff --git a/src/ci/scripts/free-disk-space.sh b/src/ci/scripts/free-disk-space.sh
index 055a6ac2211e3..ad7ee136e9c27 100755
--- a/src/ci/scripts/free-disk-space.sh
+++ b/src/ci/scripts/free-disk-space.sh
@@ -14,6 +14,17 @@ isX86() {
fi
}
+# Check if we're on a GitHub hosted runner.
+# In aws codebuild, the variable RUNNER_ENVIRONMENT is "self-hosted".
+isGitHubRunner() {
+ # `:-` means "use the value of RUNNER_ENVIRONMENT if it exists, otherwise use an empty string".
+ if [[ "${RUNNER_ENVIRONMENT:-}" == "github-hosted" ]]; then
+ return 0
+ else
+ return 1
+ fi
+}
+
# print a line of the specified character
printSeparationLine() {
for ((i = 0; i < 80; i++)); do
@@ -32,7 +43,7 @@ getAvailableSpace() {
# make Kb human readable (assume the input is Kb)
# REF: https://unix.stackexchange.com/a/44087/60849
formatByteCount() {
- numfmt --to=iec-i --suffix=B --padding=7 "$1"'000'
+ numfmt --to=iec-i --suffix=B --padding=7 "${1}000"
}
# macro to output saved space
@@ -45,6 +56,11 @@ printSavedSpace() {
after=$(getAvailableSpace)
local saved=$((after - before))
+ if [ "$saved" -lt 0 ]; then
+ echo "::warning::Saved space is negative: $saved. Using '0' as saved space."
+ saved=0
+ fi
+
echo ""
printSeparationLine "*"
if [ -n "${title}" ]; then
@@ -118,10 +134,14 @@ removeUnusedFilesAndDirs() {
# Azure
"/opt/az"
"/usr/share/az_"*
+ )
+ if [ -n "${AGENT_TOOLSDIRECTORY:-}" ]; then
# Environment variable set by GitHub Actions
- "$AGENT_TOOLSDIRECTORY"
- )
+ to_remove+=(
+ "${AGENT_TOOLSDIRECTORY}"
+ )
+ fi
for element in "${to_remove[@]}"; do
if [ ! -e "$element" ]; then
@@ -155,20 +175,25 @@ cleanPackages() {
'^dotnet-.*'
'^llvm-.*'
'^mongodb-.*'
- 'azure-cli'
'firefox'
'libgl1-mesa-dri'
'mono-devel'
'php.*'
)
- if isX86; then
+ if isGitHubRunner; then
packages+=(
- 'google-chrome-stable'
- 'google-cloud-cli'
- 'google-cloud-sdk'
- 'powershell'
+ azure-cli
)
+
+ if isX86; then
+ packages+=(
+ 'google-chrome-stable'
+ 'google-cloud-cli'
+ 'google-cloud-sdk'
+ 'powershell'
+ )
+ fi
fi
sudo apt-get -qq remove -y --fix-missing "${packages[@]}"
| diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2e83bbf643fee..7c46871569646 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -91,6 +91,17 @@ jobs:
# Check the `calculate_matrix` job to see how is the matrix defined.
include: ${{ fromJSON(needs.calculate_matrix.outputs.jobs) }}
steps:
+ - name: Install cargo in AWS CodeBuild
+ if: matrix.codebuild
+ run: |
+ # Check if cargo is installed
+ if ! command -v cargo &> /dev/null; then
+ echo "Cargo not found, installing Rust..."
+ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal
+ # Make cargo available in PATH
+ echo "$HOME/.cargo/bin" >> $GITHUB_PATH
+ fi
- name: disable git crlf conversion
run: git config --global core.autocrlf false
@@ -168,6 +179,8 @@ jobs:
run: src/ci/scripts/install-ninja.sh
- name: enable ipv6 on Docker
+ # Don't run on codebuild because systemctl is not available
run: src/ci/scripts/enable-docker-ipv6.sh
# Disable automatic line ending conversion (again). On Windows, when we're
diff --git a/src/ci/citool/src/jobs.rs b/src/ci/citool/src/jobs.rs
index 13880ad466a6b..5600d7b4db59b 100644
--- a/src/ci/citool/src/jobs.rs
+++ b/src/ci/citool/src/jobs.rs
@@ -3,12 +3,15 @@ mod tests;
use std::collections::BTreeMap;
+use anyhow::Context as _;
use serde_yaml::Value;
use crate::GitHubContext;
+use crate::utils::load_env_var;
/// Representation of a job loaded from the `src/ci/github-actions/jobs.yml` file.
#[derive(serde::Deserialize, Debug, Clone)]
pub struct Job {
/// Name of the job, e.g. mingw-check
pub name: String,
@@ -26,6 +29,8 @@ pub struct Job {
pub free_disk: Option<bool>,
/// Documentation link to a resource that could help people debug this CI job.
pub doc_url: Option<String>,
+ /// Whether the job is executed on AWS CodeBuild.
+ pub codebuild: Option<bool>,
impl Job {
@@ -80,7 +85,7 @@ impl JobDatabase {
pub fn load_job_db(db: &str) -> anyhow::Result<JobDatabase> {
- let mut db: Value = serde_yaml::from_str(&db)?;
+ let mut db: Value = serde_yaml::from_str(db)?;
// We need to expand merge keys (<<), because serde_yaml can't deal with them
// `apply_merge` only applies the merge once, so do it a few times to unwrap nested merges.
@@ -107,6 +112,29 @@ struct GithubActionsJob {
free_disk: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
doc_url: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ codebuild: Option<bool>,
+/// Used for codebuild jobs like
+/// `codebuild-ubuntu-22-8c-$github.run_id-$github.run_attempt`
+fn substitute_github_vars(jobs: Vec<Job>) -> anyhow::Result<Vec<Job>> {
+ let run_id = load_env_var("GITHUB_RUN_ID")?;
+ let run_attempt = load_env_var("GITHUB_RUN_ATTEMPT")?;
+ let jobs = jobs
+ .map(|mut job| {
+ job.os = job
+ .os
+ .replace("$github.run_attempt", &run_attempt);
+ job
+ .collect();
+ Ok(jobs)
/// Skip CI jobs that are not supposed to be executed on the given `channel`.
@@ -177,6 +205,8 @@ fn calculate_jobs(
}
RunType::AutoJob => (db.auto_jobs.clone(), "auto", &db.envs.auto_env),
};
+ let jobs = substitute_github_vars(jobs.clone())
+ .context("Failed to substitute GitHub context variables in jobs")?;
let jobs = skip_jobs(jobs, channel);
let jobs = jobs
.into_iter()
@@ -207,6 +237,7 @@ fn calculate_jobs(
continue_on_error: job.continue_on_error,
free_disk: job.free_disk,
doc_url: job.doc_url,
}
})
.collect();
diff --git a/src/ci/docker/host-x86_64/dist-arm-linux/Dockerfile b/src/ci/docker/host-x86_64/dist-arm-linux/Dockerfile
index 420c42bc9d807..3795859f308e6 100644
--- a/src/ci/docker/host-x86_64/dist-arm-linux/Dockerfile
+++ b/src/ci/docker/host-x86_64/dist-arm-linux/Dockerfile
@@ -1,4 +1,4 @@
-FROM ubuntu:22.04
+FROM ghcr.io/rust-lang/ubuntu:22.04
COPY scripts/cross-apt-packages.sh /scripts/
RUN sh /scripts/cross-apt-packages.sh
diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh
index 00d791eeb6b38..36f7df2b06907 100755
--- a/src/ci/docker/run.sh
+++ b/src/ci/docker/run.sh
@@ -288,7 +288,7 @@ args="$args --privileged"
# `LOCAL_USER_ID` (recognized in `src/ci/run.sh`) to ensure that files are all
# read/written as the same user as the bare-metal user.
if [ -f /.dockerenv ]; then
- docker create -v /checkout --name checkout alpine:3.4 /bin/true
+ docker create -v /checkout --name checkout ghcr.io/rust-lang/alpine:3.4 /bin/true
docker cp . checkout:/checkout
args="$args --volumes-from checkout"
else
diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml
index cb2bec5a9dfa6..367e45ebe2006 100644
--- a/src/ci/github-actions/jobs.yml
+++ b/src/ci/github-actions/jobs.yml
@@ -56,6 +56,15 @@ runners:
- &job-aarch64-linux-8c
os: ubuntu-24.04-arm64-8core-32gb
<<: *base-job
+ # Codebuild runners are provisioned in
+ # https://github.com/rust-lang/simpleinfra/blob/b7ddd5e6bec8a93ec30510cdddec02c5666fefe9/terragrunt/accounts/ci-prod/ci-runners/terragrunt.hcl#L2
+ - &job-linux-36c-codebuild
+ free_disk: true
+ codebuild: true
+ os: codebuild-ubuntu-22-36c-$github.run_id-$github.run_attempt
envs:
env-x86_64-apple-tests: &env-x86_64-apple-tests
SCRIPT: ./x.py check compiletest --set build.compiletest-use-stage0-libtest=true && ./x.py --stage 2 test --skip tests/ui --skip tests/rustdoc -- --exact
@@ -153,7 +162,7 @@ auto:
- name: dist-arm-linux
+ <<: *job-linux-36c-codebuild
- name: dist-armhf-linux
diff --git a/src/ci/scripts/free-disk-space.sh b/src/ci/scripts/free-disk-space.sh
index 055a6ac2211e3..ad7ee136e9c27 100755
--- a/src/ci/scripts/free-disk-space.sh
+++ b/src/ci/scripts/free-disk-space.sh
@@ -14,6 +14,17 @@ isX86() {
+# In aws codebuild, the variable RUNNER_ENVIRONMENT is "self-hosted".
+isGitHubRunner() {
+ # `:-` means "use the value of RUNNER_ENVIRONMENT if it exists, otherwise use an empty string".
+ if [[ "${RUNNER_ENVIRONMENT:-}" == "github-hosted" ]]; then
+ return 0
+ else
+ return 1
# print a line of the specified character
printSeparationLine() {
for ((i = 0; i < 80; i++)); do
@@ -32,7 +43,7 @@ getAvailableSpace() {
# make Kb human readable (assume the input is Kb)
# REF: https://unix.stackexchange.com/a/44087/60849
formatByteCount() {
- numfmt --to=iec-i --suffix=B --padding=7 "$1"'000'
+ numfmt --to=iec-i --suffix=B --padding=7 "${1}000"
# macro to output saved space
@@ -45,6 +56,11 @@ printSavedSpace() {
after=$(getAvailableSpace)
local saved=$((after - before))
+ echo "::warning::Saved space is negative: $saved. Using '0' as saved space."
+ saved=0
echo ""
printSeparationLine "*"
if [ -n "${title}" ]; then
@@ -118,10 +134,14 @@ removeUnusedFilesAndDirs() {
# Azure
"/opt/az"
"/usr/share/az_"*
+ )
+ if [ -n "${AGENT_TOOLSDIRECTORY:-}" ]; then
# Environment variable set by GitHub Actions
- "$AGENT_TOOLSDIRECTORY"
- )
+ to_remove+=(
+ "${AGENT_TOOLSDIRECTORY}"
+ )
for element in "${to_remove[@]}"; do
if [ ! -e "$element" ]; then
@@ -155,20 +175,25 @@ cleanPackages() {
'^dotnet-.*'
'^llvm-.*'
'^mongodb-.*'
- 'azure-cli'
'firefox'
'libgl1-mesa-dri'
'mono-devel'
'php.*'
)
- if isX86; then
+ if isGitHubRunner; then
packages+=(
- 'google-chrome-stable'
- 'google-cloud-cli'
- 'google-cloud-sdk'
- 'powershell'
+ azure-cli
)
+ if isX86; then
+ packages+=(
+ 'google-chrome-stable'
+ 'google-cloud-cli'
+ 'google-cloud-sdk'
+ 'powershell'
+ )
+ fi
sudo apt-get -qq remove -y --fix-missing "${packages[@]}" | [
"+ if: ${{ !matrix.codebuild }}",
"+#[serde(deny_unknown_fields)]",
"+/// Replace GitHub context variables with environment variables in job configs.",
"+ .into_iter()",
"+ .replace(\"$github.run_id\", &run_id)",
"+ })",
"+ codebuild: job.codebuild,",
"+ <<: *base-job",
"- <<: *job-linux-8c",
"+# Check if we're on a GitHub hosted runner.",
"+ if [ \"$saved\" -lt 0 ]; then"
] | [
27,
47,
77,
85,
89,
92,
112,
154,
163,
176,
203
] | {
"additions": 91,
"author": "marcoieni",
"deletions": 13,
"html_url": "https://github.com/rust-lang/rust/pull/140148",
"issue_id": 140148,
"merged_at": "2025-04-25T12:26:12Z",
"omission_probability": 0.1,
"pr_number": 140148,
"repo": "rust-lang/rust",
"title": "CI: use aws codebuild for job dist-arm-linux",
"total_changes": 104
} |
117 | diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index de93e2b99eede..31c696ed41ff4 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -415,13 +415,10 @@ pub struct Config {
/// ABI tests.
pub minicore_path: Utf8PathBuf,
- /// If true, disable the "new" executor, and use the older libtest-based
- /// executor to run tests instead. This is a temporary fallback, to make
- /// manual comparative testing easier if bugs are found in the new executor.
- ///
- /// FIXME(Zalathar): Eventually remove this flag and remove the libtest
- /// dependency.
- pub no_new_executor: bool,
+ /// If true, run tests with the "new" executor that was written to replace
+ /// compiletest's dependency on libtest. Eventually this will become the
+ /// default, and the libtest dependency will be removed.
+ pub new_executor: bool,
}
impl Config {
diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs
index 7948a273c1e86..b3b9299ea0787 100644
--- a/src/tools/compiletest/src/lib.rs
+++ b/src/tools/compiletest/src/lib.rs
@@ -203,7 +203,7 @@ pub fn parse_config(args: Vec<String>) -> Config {
"COMMAND",
)
.reqopt("", "minicore-path", "path to minicore aux library", "PATH")
- .optflag("N", "no-new-executor", "disables the new test executor, and uses libtest instead")
+ .optflag("n", "new-executor", "enables the new test executor instead of using libtest")
.optopt(
"",
"debugger",
@@ -450,7 +450,7 @@ pub fn parse_config(args: Vec<String>) -> Config {
minicore_path: opt_path(matches, "minicore-path"),
- no_new_executor: matches.opt_present("no-new-executor"),
+ new_executor: matches.opt_present("new-executor"),
}
}
@@ -577,10 +577,9 @@ pub fn run_tests(config: Arc<Config>) {
// Delegate to the executor to filter and run the big list of test structures
// created during test discovery. When the executor decides to run a test,
// it will return control to the rest of compiletest by calling `runtest::run`.
- let res = if !config.no_new_executor {
+ let res = if config.new_executor {
Ok(executor::run_tests(&config, tests))
} else {
- // FIXME(Zalathar): Eventually remove the libtest executor entirely.
crate::executor::libtest::execute_tests(&config, tests)
};
| diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index de93e2b99eede..31c696ed41ff4 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -415,13 +415,10 @@ pub struct Config {
/// ABI tests.
pub minicore_path: Utf8PathBuf,
- /// If true, disable the "new" executor, and use the older libtest-based
- /// manual comparative testing easier if bugs are found in the new executor.
- ///
- /// FIXME(Zalathar): Eventually remove this flag and remove the libtest
- /// dependency.
- pub no_new_executor: bool,
+ /// If true, run tests with the "new" executor that was written to replace
+ /// compiletest's dependency on libtest. Eventually this will become the
+ pub new_executor: bool,
impl Config {
diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs
index 7948a273c1e86..b3b9299ea0787 100644
--- a/src/tools/compiletest/src/lib.rs
+++ b/src/tools/compiletest/src/lib.rs
@@ -203,7 +203,7 @@ pub fn parse_config(args: Vec<String>) -> Config {
"COMMAND",
)
.reqopt("", "minicore-path", "path to minicore aux library", "PATH")
- .optflag("N", "no-new-executor", "disables the new test executor, and uses libtest instead")
+ .optflag("n", "new-executor", "enables the new test executor instead of using libtest")
.optopt(
"",
"debugger",
@@ -450,7 +450,7 @@ pub fn parse_config(args: Vec<String>) -> Config {
minicore_path: opt_path(matches, "minicore-path"),
+ new_executor: matches.opt_present("new-executor"),
}
@@ -577,10 +577,9 @@ pub fn run_tests(config: Arc<Config>) {
// Delegate to the executor to filter and run the big list of test structures
// created during test discovery. When the executor decides to run a test,
// it will return control to the rest of compiletest by calling `runtest::run`.
- let res = if !config.no_new_executor {
+ let res = if config.new_executor {
Ok(executor::run_tests(&config, tests))
} else {
- // FIXME(Zalathar): Eventually remove the libtest executor entirely.
crate::executor::libtest::execute_tests(&config, tests)
}; | [
"- /// executor to run tests instead. This is a temporary fallback, to make",
"+ /// default, and the libtest dependency will be removed.",
"- no_new_executor: matches.opt_present(\"no-new-executor\"),"
] | [
9,
17,
39
] | {
"additions": 7,
"author": "Zalathar",
"deletions": 11,
"html_url": "https://github.com/rust-lang/rust/pull/140233",
"issue_id": 140233,
"merged_at": "2025-04-25T09:08:24Z",
"omission_probability": 0.1,
"pr_number": 140233,
"repo": "rust-lang/rust",
"title": "Revert compiletest new-executor, to re-land without download-rustc",
"total_changes": 18
} |
118 | diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs
index 67fca1d7c2947..ad9cec6fed908 100644
--- a/compiler/rustc_monomorphize/src/collector.rs
+++ b/compiler/rustc_monomorphize/src/collector.rs
@@ -231,7 +231,7 @@ use rustc_middle::ty::{
use rustc_middle::util::Providers;
use rustc_middle::{bug, span_bug};
use rustc_session::Limit;
-use rustc_session::config::EntryFnType;
+use rustc_session::config::{DebugInfo, EntryFnType};
use rustc_span::source_map::{Spanned, dummy_spanned, respan};
use rustc_span::{DUMMY_SP, Span};
use tracing::{debug, instrument, trace};
@@ -1235,6 +1235,11 @@ fn collect_items_of_instance<'tcx>(
};
if mode == CollectionMode::UsedItems {
+ if tcx.sess.opts.debuginfo == DebugInfo::Full {
+ for var_debug_info in &body.var_debug_info {
+ collector.visit_var_debug_info(var_debug_info);
+ }
+ }
for (bb, data) in traversal::mono_reachable(body, tcx, instance) {
collector.visit_basic_block_data(bb, data)
}
diff --git a/tests/ui/mir/var_debug_ref.rs b/tests/ui/mir/var_debug_ref.rs
new file mode 100644
index 0000000000000..1dcf38b5bb9f7
--- /dev/null
+++ b/tests/ui/mir/var_debug_ref.rs
@@ -0,0 +1,24 @@
+// Regression test for #138942, where a function was incorrectly internalized, despite the fact
+// that it was referenced by a var debug info from another code generation unit.
+//
+//@ build-pass
+//@ revisions: limited full
+//@ compile-flags: -Ccodegen-units=4
+//@[limited] compile-flags: -Cdebuginfo=limited
+//@[full] compile-flags: -Cdebuginfo=full
+trait Fun {
+ const FUN: &'static fn();
+}
+impl Fun for () {
+ const FUN: &'static fn() = &(detail::f as fn());
+}
+mod detail {
+ // Place `f` in a distinct module to generate a separate code generation unit.
+ #[inline(never)]
+ pub(super) fn f() {}
+}
+fn main() {
+ // SingleUseConsts represents "x" using VarDebugInfoContents::Const.
+ // It is the only reference to `f` remaining.
+ let x = <() as ::Fun>::FUN;
+}
| diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs
index 67fca1d7c2947..ad9cec6fed908 100644
--- a/compiler/rustc_monomorphize/src/collector.rs
+++ b/compiler/rustc_monomorphize/src/collector.rs
@@ -231,7 +231,7 @@ use rustc_middle::ty::{
use rustc_middle::util::Providers;
use rustc_middle::{bug, span_bug};
use rustc_session::Limit;
+use rustc_session::config::{DebugInfo, EntryFnType};
use rustc_span::source_map::{Spanned, dummy_spanned, respan};
use rustc_span::{DUMMY_SP, Span};
use tracing::{debug, instrument, trace};
@@ -1235,6 +1235,11 @@ fn collect_items_of_instance<'tcx>(
};
if mode == CollectionMode::UsedItems {
+ if tcx.sess.opts.debuginfo == DebugInfo::Full {
+ for var_debug_info in &body.var_debug_info {
+ collector.visit_var_debug_info(var_debug_info);
+ }
+ }
for (bb, data) in traversal::mono_reachable(body, tcx, instance) {
collector.visit_basic_block_data(bb, data)
}
diff --git a/tests/ui/mir/var_debug_ref.rs b/tests/ui/mir/var_debug_ref.rs
new file mode 100644
index 0000000000000..1dcf38b5bb9f7
--- /dev/null
+++ b/tests/ui/mir/var_debug_ref.rs
@@ -0,0 +1,24 @@
+// Regression test for #138942, where a function was incorrectly internalized, despite the fact
+// that it was referenced by a var debug info from another code generation unit.
+//
+//@ build-pass
+//@ revisions: limited full
+//@ compile-flags: -Ccodegen-units=4
+//@[limited] compile-flags: -Cdebuginfo=limited
+//@[full] compile-flags: -Cdebuginfo=full
+trait Fun {
+ const FUN: &'static fn();
+ const FUN: &'static fn() = &(detail::f as fn());
+mod detail {
+ // Place `f` in a distinct module to generate a separate code generation unit.
+ #[inline(never)]
+ pub(super) fn f() {}
+fn main() {
+ // SingleUseConsts represents "x" using VarDebugInfoContents::Const.
+ // It is the only reference to `f` remaining.
+ let x = <() as ::Fun>::FUN; | [
"-use rustc_session::config::EntryFnType;",
"+impl Fun for () {"
] | [
8,
42
] | {
"additions": 30,
"author": "tmiasko",
"deletions": 1,
"html_url": "https://github.com/rust-lang/rust/pull/138980",
"issue_id": 138980,
"merged_at": "2025-03-27T10:59:55Z",
"omission_probability": 0.1,
"pr_number": 138980,
"repo": "rust-lang/rust",
"title": "Collect items referenced from var_debug_info",
"total_changes": 31
} |
119 | diff --git a/src/bootstrap/src/core/build_steps/suggest.rs b/src/bootstrap/src/core/build_steps/suggest.rs
index 6a6731cafc54a..fd4918961adba 100644
--- a/src/bootstrap/src/core/build_steps/suggest.rs
+++ b/src/bootstrap/src/core/build_steps/suggest.rs
@@ -13,7 +13,6 @@ pub fn suggest(builder: &Builder<'_>, run: bool) {
let git_config = builder.config.git_config();
let suggestions = builder
.tool_cmd(Tool::SuggestTests)
- .env("SUGGEST_TESTS_GIT_REPOSITORY", git_config.git_repository)
.env("SUGGEST_TESTS_NIGHTLY_BRANCH", git_config.nightly_branch)
.env("SUGGEST_TESTS_MERGE_COMMIT_EMAIL", git_config.git_merge_commit_email)
.run_capture_stdout(builder)
diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs
index 096f7de65975a..d4fccc535a6b0 100644
--- a/src/bootstrap/src/core/build_steps/test.rs
+++ b/src/bootstrap/src/core/build_steps/test.rs
@@ -2064,7 +2064,6 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the
}
let git_config = builder.config.git_config();
- cmd.arg("--git-repository").arg(git_config.git_repository);
cmd.arg("--nightly-branch").arg(git_config.nightly_branch);
cmd.arg("--git-merge-commit-email").arg(git_config.git_merge_commit_email);
cmd.force_coloring_in_ci();
diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs
index 419976c83b1d0..23b623d9bab23 100644
--- a/src/bootstrap/src/core/config/config.rs
+++ b/src/bootstrap/src/core/config/config.rs
@@ -2963,7 +2963,6 @@ impl Config {
pub fn git_config(&self) -> GitConfig<'_> {
GitConfig {
- git_repository: &self.stage0_metadata.config.git_repository,
nightly_branch: &self.stage0_metadata.config.nightly_branch,
git_merge_commit_email: &self.stage0_metadata.config.git_merge_commit_email,
}
diff --git a/src/bootstrap/src/utils/tests/git.rs b/src/bootstrap/src/utils/tests/git.rs
index 99e0793af4666..bd40f398c7b10 100644
--- a/src/bootstrap/src/utils/tests/git.rs
+++ b/src/bootstrap/src/utils/tests/git.rs
@@ -135,7 +135,6 @@ impl GitCtx {
fn git_config(&self) -> GitConfig<'_> {
GitConfig {
- git_repository: &self.git_repo,
nightly_branch: &self.nightly_branch,
git_merge_commit_email: &self.merge_bot_email,
}
diff --git a/src/build_helper/src/git.rs b/src/build_helper/src/git.rs
index 8d53a83ea3170..438cd14389c1c 100644
--- a/src/build_helper/src/git.rs
+++ b/src/build_helper/src/git.rs
@@ -5,7 +5,6 @@ use crate::ci::CiEnv;
#[derive(Debug)]
pub struct GitConfig<'a> {
- pub git_repository: &'a str,
pub nightly_branch: &'a str,
pub git_merge_commit_email: &'a str,
}
diff --git a/src/build_helper/src/stage0_parser.rs b/src/build_helper/src/stage0_parser.rs
index 2a0c12a1c91c7..2723f4aa7b914 100644
--- a/src/build_helper/src/stage0_parser.rs
+++ b/src/build_helper/src/stage0_parser.rs
@@ -20,7 +20,6 @@ pub struct Stage0Config {
pub artifacts_server: String,
pub artifacts_with_llvm_assertions_server: String,
pub git_merge_commit_email: String,
- pub git_repository: String,
pub nightly_branch: String,
}
@@ -49,7 +48,6 @@ pub fn parse_stage0_file() -> Stage0 {
stage0.config.artifacts_with_llvm_assertions_server = value.to_owned()
}
"git_merge_commit_email" => stage0.config.git_merge_commit_email = value.to_owned(),
- "git_repository" => stage0.config.git_repository = value.to_owned(),
"nightly_branch" => stage0.config.nightly_branch = value.to_owned(),
"compiler_date" => stage0.compiler.date = value.to_owned(),
diff --git a/src/stage0 b/src/stage0
index 6e86501a72ab4..06080e3a8c161 100644
--- a/src/stage0
+++ b/src/stage0
@@ -2,7 +2,6 @@ dist_server=https://static.rust-lang.org
artifacts_server=https://ci-artifacts.rust-lang.org/rustc-builds
artifacts_with_llvm_assertions_server=https://ci-artifacts.rust-lang.org/rustc-builds-alt
[email protected]
-git_repository=rust-lang/rust
nightly_branch=master
# The configuration above this comment is editable, and can be changed
diff --git a/src/tools/bump-stage0/src/main.rs b/src/tools/bump-stage0/src/main.rs
index d679084ae44bc..680437cce4faa 100644
--- a/src/tools/bump-stage0/src/main.rs
+++ b/src/tools/bump-stage0/src/main.rs
@@ -61,7 +61,6 @@ impl Tool {
artifacts_server,
artifacts_with_llvm_assertions_server,
git_merge_commit_email,
- git_repository,
nightly_branch,
} = &self.config;
@@ -72,7 +71,6 @@ impl Tool {
artifacts_with_llvm_assertions_server
));
file_content.push_str(&format!("git_merge_commit_email={}\n", git_merge_commit_email));
- file_content.push_str(&format!("git_repository={}\n", git_repository));
file_content.push_str(&format!("nightly_branch={}\n", nightly_branch));
file_content.push_str("\n");
diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index 31c696ed41ff4..b5bbe70c48ce4 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -399,7 +399,6 @@ pub struct Config {
pub nocapture: bool,
// Needed both to construct build_helper::git::GitConfig
- pub git_repository: String,
pub nightly_branch: String,
pub git_merge_commit_email: String,
@@ -511,7 +510,6 @@ impl Config {
pub fn git_config(&self) -> GitConfig<'_> {
GitConfig {
- git_repository: &self.git_repository,
nightly_branch: &self.nightly_branch,
git_merge_commit_email: &self.git_merge_commit_email,
}
diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs
index 2525e0adc8385..e7e5ff0ab0093 100644
--- a/src/tools/compiletest/src/header/tests.rs
+++ b/src/tools/compiletest/src/header/tests.rs
@@ -175,7 +175,6 @@ impl ConfigBuilder {
self.host.as_deref().unwrap_or("x86_64-unknown-linux-gnu"),
"--target",
self.target.as_deref().unwrap_or("x86_64-unknown-linux-gnu"),
- "--git-repository=",
"--nightly-branch=",
"--git-merge-commit-email=",
"--minicore-path=",
diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs
index b3b9299ea0787..3cf13671ef03b 100644
--- a/src/tools/compiletest/src/lib.rs
+++ b/src/tools/compiletest/src/lib.rs
@@ -188,7 +188,6 @@ pub fn parse_config(args: Vec<String>) -> Config {
"run tests which rely on commit version being compiled into the binaries",
)
.optopt("", "edition", "default Rust edition", "EDITION")
- .reqopt("", "git-repository", "name of the git repository", "ORG/REPO")
.reqopt("", "nightly-branch", "name of the git branch for nightly", "BRANCH")
.reqopt(
"",
@@ -440,7 +439,6 @@ pub fn parse_config(args: Vec<String>) -> Config {
nocapture: matches.opt_present("no-capture"),
- git_repository: matches.opt_str("git-repository").unwrap(),
nightly_branch: matches.opt_str("nightly-branch").unwrap(),
git_merge_commit_email: matches.opt_str("git-merge-commit-email").unwrap(),
diff --git a/src/tools/suggest-tests/src/main.rs b/src/tools/suggest-tests/src/main.rs
index ee212af36260a..d84f8e9fa1bab 100644
--- a/src/tools/suggest-tests/src/main.rs
+++ b/src/tools/suggest-tests/src/main.rs
@@ -6,7 +6,6 @@ use suggest_tests::get_suggestions;
fn main() -> ExitCode {
let modified_files = get_git_modified_files(
&GitConfig {
- git_repository: &env("SUGGEST_TESTS_GIT_REPOSITORY"),
nightly_branch: &env("SUGGEST_TESTS_NIGHTLY_BRANCH"),
git_merge_commit_email: &env("SUGGEST_TESTS_MERGE_COMMIT_EMAIL"),
},
| diff --git a/src/bootstrap/src/core/build_steps/suggest.rs b/src/bootstrap/src/core/build_steps/suggest.rs
index 6a6731cafc54a..fd4918961adba 100644
--- a/src/bootstrap/src/core/build_steps/suggest.rs
+++ b/src/bootstrap/src/core/build_steps/suggest.rs
@@ -13,7 +13,6 @@ pub fn suggest(builder: &Builder<'_>, run: bool) {
let git_config = builder.config.git_config();
let suggestions = builder
.tool_cmd(Tool::SuggestTests)
- .env("SUGGEST_TESTS_GIT_REPOSITORY", git_config.git_repository)
.env("SUGGEST_TESTS_NIGHTLY_BRANCH", git_config.nightly_branch)
.env("SUGGEST_TESTS_MERGE_COMMIT_EMAIL", git_config.git_merge_commit_email)
.run_capture_stdout(builder)
diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs
index 096f7de65975a..d4fccc535a6b0 100644
--- a/src/bootstrap/src/core/build_steps/test.rs
+++ b/src/bootstrap/src/core/build_steps/test.rs
@@ -2064,7 +2064,6 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the
let git_config = builder.config.git_config();
- cmd.arg("--git-repository").arg(git_config.git_repository);
cmd.arg("--nightly-branch").arg(git_config.nightly_branch);
cmd.arg("--git-merge-commit-email").arg(git_config.git_merge_commit_email);
cmd.force_coloring_in_ci();
diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs
index 419976c83b1d0..23b623d9bab23 100644
--- a/src/bootstrap/src/core/config/config.rs
+++ b/src/bootstrap/src/core/config/config.rs
@@ -2963,7 +2963,6 @@ impl Config {
- git_repository: &self.stage0_metadata.config.git_repository,
nightly_branch: &self.stage0_metadata.config.nightly_branch,
git_merge_commit_email: &self.stage0_metadata.config.git_merge_commit_email,
diff --git a/src/bootstrap/src/utils/tests/git.rs b/src/bootstrap/src/utils/tests/git.rs
index 99e0793af4666..bd40f398c7b10 100644
--- a/src/bootstrap/src/utils/tests/git.rs
+++ b/src/bootstrap/src/utils/tests/git.rs
@@ -135,7 +135,6 @@ impl GitCtx {
fn git_config(&self) -> GitConfig<'_> {
- git_repository: &self.git_repo,
git_merge_commit_email: &self.merge_bot_email,
diff --git a/src/build_helper/src/git.rs b/src/build_helper/src/git.rs
index 8d53a83ea3170..438cd14389c1c 100644
--- a/src/build_helper/src/git.rs
+++ b/src/build_helper/src/git.rs
@@ -5,7 +5,6 @@ use crate::ci::CiEnv;
#[derive(Debug)]
pub struct GitConfig<'a> {
pub nightly_branch: &'a str,
pub git_merge_commit_email: &'a str,
diff --git a/src/build_helper/src/stage0_parser.rs b/src/build_helper/src/stage0_parser.rs
index 2a0c12a1c91c7..2723f4aa7b914 100644
--- a/src/build_helper/src/stage0_parser.rs
+++ b/src/build_helper/src/stage0_parser.rs
@@ -20,7 +20,6 @@ pub struct Stage0Config {
pub artifacts_server: String,
pub artifacts_with_llvm_assertions_server: String,
@@ -49,7 +48,6 @@ pub fn parse_stage0_file() -> Stage0 {
stage0.config.artifacts_with_llvm_assertions_server = value.to_owned()
}
"git_merge_commit_email" => stage0.config.git_merge_commit_email = value.to_owned(),
- "git_repository" => stage0.config.git_repository = value.to_owned(),
"nightly_branch" => stage0.config.nightly_branch = value.to_owned(),
"compiler_date" => stage0.compiler.date = value.to_owned(),
diff --git a/src/stage0 b/src/stage0
index 6e86501a72ab4..06080e3a8c161 100644
--- a/src/stage0
+++ b/src/stage0
@@ -2,7 +2,6 @@ dist_server=https://static.rust-lang.org
artifacts_server=https://ci-artifacts.rust-lang.org/rustc-builds
artifacts_with_llvm_assertions_server=https://ci-artifacts.rust-lang.org/rustc-builds-alt
[email protected]
-git_repository=rust-lang/rust
nightly_branch=master
# The configuration above this comment is editable, and can be changed
diff --git a/src/tools/bump-stage0/src/main.rs b/src/tools/bump-stage0/src/main.rs
index d679084ae44bc..680437cce4faa 100644
--- a/src/tools/bump-stage0/src/main.rs
+++ b/src/tools/bump-stage0/src/main.rs
@@ -61,7 +61,6 @@ impl Tool {
artifacts_server,
artifacts_with_llvm_assertions_server,
git_merge_commit_email,
- git_repository,
nightly_branch,
} = &self.config;
@@ -72,7 +71,6 @@ impl Tool {
artifacts_with_llvm_assertions_server
));
file_content.push_str(&format!("git_merge_commit_email={}\n", git_merge_commit_email));
- file_content.push_str(&format!("git_repository={}\n", git_repository));
file_content.push_str(&format!("nightly_branch={}\n", nightly_branch));
file_content.push_str("\n");
diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index 31c696ed41ff4..b5bbe70c48ce4 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -399,7 +399,6 @@ pub struct Config {
pub nocapture: bool,
// Needed both to construct build_helper::git::GitConfig
@@ -511,7 +510,6 @@ impl Config {
- git_repository: &self.git_repository,
git_merge_commit_email: &self.git_merge_commit_email,
diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs
index 2525e0adc8385..e7e5ff0ab0093 100644
--- a/src/tools/compiletest/src/header/tests.rs
+++ b/src/tools/compiletest/src/header/tests.rs
@@ -175,7 +175,6 @@ impl ConfigBuilder {
self.host.as_deref().unwrap_or("x86_64-unknown-linux-gnu"),
"--target",
self.target.as_deref().unwrap_or("x86_64-unknown-linux-gnu"),
- "--git-repository=",
"--nightly-branch=",
"--git-merge-commit-email=",
"--minicore-path=",
diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs
index b3b9299ea0787..3cf13671ef03b 100644
--- a/src/tools/compiletest/src/lib.rs
+++ b/src/tools/compiletest/src/lib.rs
@@ -188,7 +188,6 @@ pub fn parse_config(args: Vec<String>) -> Config {
"run tests which rely on commit version being compiled into the binaries",
)
.optopt("", "edition", "default Rust edition", "EDITION")
- .reqopt("", "git-repository", "name of the git repository", "ORG/REPO")
.reqopt("", "nightly-branch", "name of the git branch for nightly", "BRANCH")
.reqopt(
"",
@@ -440,7 +439,6 @@ pub fn parse_config(args: Vec<String>) -> Config {
nocapture: matches.opt_present("no-capture"),
- git_repository: matches.opt_str("git-repository").unwrap(),
nightly_branch: matches.opt_str("nightly-branch").unwrap(),
git_merge_commit_email: matches.opt_str("git-merge-commit-email").unwrap(),
diff --git a/src/tools/suggest-tests/src/main.rs b/src/tools/suggest-tests/src/main.rs
index ee212af36260a..d84f8e9fa1bab 100644
--- a/src/tools/suggest-tests/src/main.rs
+++ b/src/tools/suggest-tests/src/main.rs
@@ -6,7 +6,6 @@ use suggest_tests::get_suggestions;
fn main() -> ExitCode {
let modified_files = get_git_modified_files(
&GitConfig {
- git_repository: &env("SUGGEST_TESTS_GIT_REPOSITORY"),
nightly_branch: &env("SUGGEST_TESTS_NIGHTLY_BRANCH"),
git_merge_commit_email: &env("SUGGEST_TESTS_MERGE_COMMIT_EMAIL"),
}, | [
"- pub git_repository: &'a str,"
] | [
56
] | {
"additions": 0,
"author": "Kobzol",
"deletions": 16,
"html_url": "https://github.com/rust-lang/rust/pull/140191",
"issue_id": 140191,
"merged_at": "2025-04-24T22:57:56Z",
"omission_probability": 0.1,
"pr_number": 140191,
"repo": "rust-lang/rust",
"title": "Remove git repository from git config",
"total_changes": 16
} |
120 | diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs
index 0985ebf945bbd..194ae9041b1a0 100644
--- a/compiler/rustc_ast_pretty/src/pprust/state.rs
+++ b/compiler/rustc_ast_pretty/src/pprust/state.rs
@@ -799,7 +799,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
has_bang,
Some(*ident),
macro_def.body.delim,
- ¯o_def.body.tokens.clone(),
+ ¯o_def.body.tokens,
true,
sp,
);
@@ -1469,7 +1469,7 @@ impl<'a> State<'a> {
true,
None,
m.args.delim,
- &m.args.tokens.clone(),
+ &m.args.tokens,
true,
m.span(),
);
diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs
index 146ba17d14fc8..8a7c1bd89fab6 100644
--- a/compiler/rustc_smir/src/rustc_internal/mod.rs
+++ b/compiler/rustc_smir/src/rustc_internal/mod.rs
@@ -256,7 +256,7 @@ where
/// // Your code goes in here.
/// # ControlFlow::Continue(())
/// }
-/// # let args = vec!["--verbose".to_string()];
+/// # let args = &["--verbose".to_string()];
/// let result = run!(args, analyze_code);
/// # assert_eq!(result, Err(CompilerError::Skipped))
/// # }
@@ -278,7 +278,7 @@ where
/// // Your code goes in here.
/// # ControlFlow::Continue(())
/// }
-/// # let args = vec!["--verbose".to_string()];
+/// # let args = &["--verbose".to_string()];
/// # let extra_args = vec![];
/// let result = run!(args, || analyze_code(extra_args));
/// # assert_eq!(result, Err(CompilerError::Skipped))
@@ -340,7 +340,6 @@ macro_rules! run_driver {
C: Send,
F: FnOnce($(optional!($with_tcx TyCtxt))?) -> ControlFlow<B, C> + Send,
{
- args: Vec<String>,
callback: Option<F>,
result: Option<ControlFlow<B, C>>,
}
@@ -352,14 +351,14 @@ macro_rules! run_driver {
F: FnOnce($(optional!($with_tcx TyCtxt))?) -> ControlFlow<B, C> + Send,
{
/// Creates a new `StableMir` instance, with given test_function and arguments.
- pub fn new(args: Vec<String>, callback: F) -> Self {
- StableMir { args, callback: Some(callback), result: None }
+ pub fn new(callback: F) -> Self {
+ StableMir { callback: Some(callback), result: None }
}
/// Runs the compiler against given target and tests it with `test_function`
- pub fn run(&mut self) -> Result<C, CompilerError<B>> {
+ pub fn run(&mut self, args: &[String]) -> Result<C, CompilerError<B>> {
let compiler_result = rustc_driver::catch_fatal_errors(|| -> interface::Result::<()> {
- run_compiler(&self.args.clone(), self);
+ run_compiler(&args, self);
Ok(())
});
match (compiler_result, self.result.take()) {
@@ -409,7 +408,7 @@ macro_rules! run_driver {
}
}
- StableMir::new($args, $callback).run()
+ StableMir::new($callback).run($args)
}};
}
diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs
index 4eecde00eaa1e..f059bd0076897 100644
--- a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs
+++ b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs
@@ -117,8 +117,7 @@ fn relate_mir_and_user_args<'tcx>(
CRATE_DEF_ID,
ObligationCauseCode::AscribeUserTypeProvePredicate(predicate_span),
);
- let instantiated_predicate =
- ocx.normalize(&cause.clone(), param_env, instantiated_predicate);
+ let instantiated_predicate = ocx.normalize(&cause, param_env, instantiated_predicate);
ocx.register_obligation(Obligation::new(tcx, cause, param_env, instantiated_predicate));
}
diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs
index 041f80c1f2c52..7ad9e59dfede1 100644
--- a/library/alloc/src/collections/btree/set.rs
+++ b/library/alloc/src/collections/btree/set.rs
@@ -139,7 +139,7 @@ pub struct Iter<'a, T: 'a> {
#[stable(feature = "collection_debug", since = "1.17.0")]
impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_tuple("Iter").field(&self.iter.clone()).finish()
+ f.debug_tuple("Iter").field(&self.iter).finish()
}
}
diff --git a/src/bootstrap/src/core/build_steps/setup.rs b/src/bootstrap/src/core/build_steps/setup.rs
index 83083e12ef1fc..9d07babe5196b 100644
--- a/src/bootstrap/src/core/build_steps/setup.rs
+++ b/src/bootstrap/src/core/build_steps/setup.rs
@@ -683,7 +683,7 @@ impl Step for Editor {
match EditorKind::prompt_user() {
Ok(editor_kind) => {
if let Some(editor_kind) = editor_kind {
- while !t!(create_editor_settings_maybe(config, editor_kind.clone())) {}
+ while !t!(create_editor_settings_maybe(config, &editor_kind)) {}
} else {
println!("Ok, skipping editor setup!");
}
@@ -695,7 +695,7 @@ impl Step for Editor {
/// Create the recommended editor LSP config file for rustc development, or just print it
/// If this method should be re-called, it returns `false`.
-fn create_editor_settings_maybe(config: &Config, editor: EditorKind) -> io::Result<bool> {
+fn create_editor_settings_maybe(config: &Config, editor: &EditorKind) -> io::Result<bool> {
let hashes = editor.hashes();
let (current_hash, historical_hashes) = hashes.split_last().unwrap();
let settings_path = editor.settings_path(config);
@@ -752,7 +752,7 @@ fn create_editor_settings_maybe(config: &Config, editor: EditorKind) -> io::Resu
// exists but user modified, back it up
Some(false) => {
// exists and is not current version or outdated, so back it up
- let backup = settings_path.clone().with_extension(editor.backup_extension());
+ let backup = settings_path.with_extension(editor.backup_extension());
eprintln!(
"WARNING: copying `{}` to `{}`",
settings_path.file_name().unwrap().to_str().unwrap(),
diff --git a/tests/ui-fulldeps/stable-mir/check_abi.rs b/tests/ui-fulldeps/stable-mir/check_abi.rs
index ebf2e333f085a..71edf813a7be2 100644
--- a/tests/ui-fulldeps/stable-mir/check_abi.rs
+++ b/tests/ui-fulldeps/stable-mir/check_abi.rs
@@ -145,7 +145,7 @@ fn get_item<'a>(
fn main() {
let path = "alloc_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-type=lib".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_allocation.rs b/tests/ui-fulldeps/stable-mir/check_allocation.rs
index ae2609bbc1221..692c24f054451 100644
--- a/tests/ui-fulldeps/stable-mir/check_allocation.rs
+++ b/tests/ui-fulldeps/stable-mir/check_allocation.rs
@@ -219,7 +219,7 @@ fn get_item<'a>(
fn main() {
let path = "alloc_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--edition=2021".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_assoc_items.rs b/tests/ui-fulldeps/stable-mir/check_assoc_items.rs
index 9d611543b5aa7..755bec8747bc8 100644
--- a/tests/ui-fulldeps/stable-mir/check_assoc_items.rs
+++ b/tests/ui-fulldeps/stable-mir/check_assoc_items.rs
@@ -85,7 +85,7 @@ fn check_items<T: CrateDef>(items: &[T], expected: &[&str]) {
fn main() {
let path = "assoc_items.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-type=lib".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_attribute.rs b/tests/ui-fulldeps/stable-mir/check_attribute.rs
index 4148fc0cb6a07..81d5399d88aa6 100644
--- a/tests/ui-fulldeps/stable-mir/check_attribute.rs
+++ b/tests/ui-fulldeps/stable-mir/check_attribute.rs
@@ -57,7 +57,7 @@ fn get_item<'a>(
fn main() {
let path = "attribute_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-type=lib".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_binop.rs b/tests/ui-fulldeps/stable-mir/check_binop.rs
index 6a141e9c5775c..f9559d9958d28 100644
--- a/tests/ui-fulldeps/stable-mir/check_binop.rs
+++ b/tests/ui-fulldeps/stable-mir/check_binop.rs
@@ -81,7 +81,7 @@ impl<'a> MirVisitor for Visitor<'a> {
fn main() {
let path = "binop_input.rs";
generate_input(&path).unwrap();
- let args = vec!["rustc".to_string(), "--crate-type=lib".to_string(), path.to_string()];
+ let args = &["rustc".to_string(), "--crate-type=lib".to_string(), path.to_string()];
run!(args, test_binops).unwrap();
}
diff --git a/tests/ui-fulldeps/stable-mir/check_crate_defs.rs b/tests/ui-fulldeps/stable-mir/check_crate_defs.rs
index 31c47192d090f..6863242f22571 100644
--- a/tests/ui-fulldeps/stable-mir/check_crate_defs.rs
+++ b/tests/ui-fulldeps/stable-mir/check_crate_defs.rs
@@ -84,7 +84,7 @@ fn contains<T: CrateDef + std::fmt::Debug>(items: &[T], expected: &[&str]) {
fn main() {
let path = "crate_definitions.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-type=lib".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_def_ty.rs b/tests/ui-fulldeps/stable-mir/check_def_ty.rs
index 00a34f138673b..f86a8e0ae6189 100644
--- a/tests/ui-fulldeps/stable-mir/check_def_ty.rs
+++ b/tests/ui-fulldeps/stable-mir/check_def_ty.rs
@@ -76,7 +76,7 @@ fn check_fn_def(ty: Ty) {
fn main() {
let path = "defs_ty_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"-Cpanic=abort".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_defs.rs b/tests/ui-fulldeps/stable-mir/check_defs.rs
index 1ba73377d6e9f..ab741378bb713 100644
--- a/tests/ui-fulldeps/stable-mir/check_defs.rs
+++ b/tests/ui-fulldeps/stable-mir/check_defs.rs
@@ -112,7 +112,7 @@ fn get_instances(body: mir::Body) -> Vec<Instance> {
fn main() {
let path = "defs_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"-Cpanic=abort".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_foreign.rs b/tests/ui-fulldeps/stable-mir/check_foreign.rs
index 4419050ceb2c1..398024c4ff082 100644
--- a/tests/ui-fulldeps/stable-mir/check_foreign.rs
+++ b/tests/ui-fulldeps/stable-mir/check_foreign.rs
@@ -58,7 +58,7 @@ fn test_foreign() -> ControlFlow<()> {
fn main() {
let path = "foreign_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"-Cpanic=abort".to_string(),
"--crate-type=lib".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_instance.rs b/tests/ui-fulldeps/stable-mir/check_instance.rs
index 1510a622cdfdb..b19e5b033c469 100644
--- a/tests/ui-fulldeps/stable-mir/check_instance.rs
+++ b/tests/ui-fulldeps/stable-mir/check_instance.rs
@@ -87,7 +87,7 @@ fn test_body(body: mir::Body) {
fn main() {
let path = "instance_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"-Cpanic=abort".to_string(),
"--crate-type=lib".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_intrinsics.rs b/tests/ui-fulldeps/stable-mir/check_intrinsics.rs
index 3f04abbb9d76d..52424857dc196 100644
--- a/tests/ui-fulldeps/stable-mir/check_intrinsics.rs
+++ b/tests/ui-fulldeps/stable-mir/check_intrinsics.rs
@@ -115,7 +115,7 @@ impl<'a> MirVisitor for CallsVisitor<'a> {
fn main() {
let path = "binop_input.rs";
generate_input(&path).unwrap();
- let args = vec!["rustc".to_string(), "--crate-type=lib".to_string(), path.to_string()];
+ let args = &["rustc".to_string(), "--crate-type=lib".to_string(), path.to_string()];
run!(args, test_intrinsics).unwrap();
}
diff --git a/tests/ui-fulldeps/stable-mir/check_item_kind.rs b/tests/ui-fulldeps/stable-mir/check_item_kind.rs
index bb8c00c64c955..d1124c75a8997 100644
--- a/tests/ui-fulldeps/stable-mir/check_item_kind.rs
+++ b/tests/ui-fulldeps/stable-mir/check_item_kind.rs
@@ -47,7 +47,7 @@ fn test_item_kind() -> ControlFlow<()> {
fn main() {
let path = "item_kind_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"-Cpanic=abort".to_string(),
"--crate-type=lib".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_normalization.rs b/tests/ui-fulldeps/stable-mir/check_normalization.rs
index 797cb4cd5d051..16e8c0339ed47 100644
--- a/tests/ui-fulldeps/stable-mir/check_normalization.rs
+++ b/tests/ui-fulldeps/stable-mir/check_normalization.rs
@@ -61,7 +61,7 @@ fn check_ty(ty: Ty) {
fn main() {
let path = "normalization_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"-Cpanic=abort".to_string(),
"--crate-type=lib".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_trait_queries.rs b/tests/ui-fulldeps/stable-mir/check_trait_queries.rs
index d9170d0c40811..fcf04a1fc3a3f 100644
--- a/tests/ui-fulldeps/stable-mir/check_trait_queries.rs
+++ b/tests/ui-fulldeps/stable-mir/check_trait_queries.rs
@@ -72,7 +72,7 @@ fn assert_impl(impl_names: &HashSet<String>, target: &str) {
fn main() {
let path = "trait_queries.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-type=lib".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_transform.rs b/tests/ui-fulldeps/stable-mir/check_transform.rs
index 604cc72c3418e..9087c1cf45027 100644
--- a/tests/ui-fulldeps/stable-mir/check_transform.rs
+++ b/tests/ui-fulldeps/stable-mir/check_transform.rs
@@ -120,7 +120,7 @@ fn get_item<'a>(
fn main() {
let path = "transform_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-type=lib".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_ty_fold.rs b/tests/ui-fulldeps/stable-mir/check_ty_fold.rs
index 23233f8406cf5..18b9e32e4e809 100644
--- a/tests/ui-fulldeps/stable-mir/check_ty_fold.rs
+++ b/tests/ui-fulldeps/stable-mir/check_ty_fold.rs
@@ -78,7 +78,7 @@ impl<'a> MirVisitor for PlaceVisitor<'a> {
fn main() {
let path = "ty_fold_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"-Cpanic=abort".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/compilation-result.rs b/tests/ui-fulldeps/stable-mir/compilation-result.rs
index 39416636fd673..19b9c8b7de508 100644
--- a/tests/ui-fulldeps/stable-mir/compilation-result.rs
+++ b/tests/ui-fulldeps/stable-mir/compilation-result.rs
@@ -25,40 +25,42 @@ use std::io::Write;
fn main() {
let path = "input_compilation_result_test.rs";
generate_input(&path).unwrap();
- let args = vec!["rustc".to_string(), path.to_string()];
- test_continue(args.clone());
- test_break(args.clone());
- test_failed(args.clone());
- test_skipped(args.clone());
+ let args = &["rustc".to_string(), path.to_string()];
+ test_continue(args);
+ test_break(args);
+ test_failed(args);
+ test_skipped(args);
test_captured(args)
}
-fn test_continue(args: Vec<String>) {
+fn test_continue(args: &[String]) {
let result = run!(args, || ControlFlow::Continue::<(), bool>(true));
assert_eq!(result, Ok(true));
}
-fn test_break(args: Vec<String>) {
+fn test_break(args: &[String]) {
let result = run!(args, || ControlFlow::Break::<bool, i32>(false));
assert_eq!(result, Err(stable_mir::CompilerError::Interrupted(false)));
}
#[allow(unreachable_code)]
-fn test_skipped(mut args: Vec<String>) {
+fn test_skipped(args: &[String]) {
+ let mut args = args.to_vec();
args.push("--version".to_string());
- let result = run!(args, || unreachable!() as ControlFlow<()>);
+ let result = run!(&args, || unreachable!() as ControlFlow<()>);
assert_eq!(result, Err(stable_mir::CompilerError::Skipped));
}
#[allow(unreachable_code)]
-fn test_failed(mut args: Vec<String>) {
+fn test_failed(args: &[String]) {
+ let mut args = args.to_vec();
args.push("--cfg=broken".to_string());
- let result = run!(args, || unreachable!() as ControlFlow<()>);
+ let result = run!(&args, || unreachable!() as ControlFlow<()>);
assert_eq!(result, Err(stable_mir::CompilerError::Failed));
}
/// Test that we are able to pass a closure and set the return according to the captured value.
-fn test_captured(args: Vec<String>) {
+fn test_captured(args: &[String]) {
let captured = "10".to_string();
let result = run!(args, || ControlFlow::Continue::<(), usize>(captured.len()));
assert_eq!(result, Ok(captured.len()));
diff --git a/tests/ui-fulldeps/stable-mir/crate-info.rs b/tests/ui-fulldeps/stable-mir/crate-info.rs
index e2086d5e57907..7fc4edafb9338 100644
--- a/tests/ui-fulldeps/stable-mir/crate-info.rs
+++ b/tests/ui-fulldeps/stable-mir/crate-info.rs
@@ -186,7 +186,7 @@ fn get_item<'a>(
fn main() {
let path = "input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-type=lib".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/projections.rs b/tests/ui-fulldeps/stable-mir/projections.rs
index f3bd894ac6903..103c97bc48e17 100644
--- a/tests/ui-fulldeps/stable-mir/projections.rs
+++ b/tests/ui-fulldeps/stable-mir/projections.rs
@@ -146,7 +146,7 @@ fn get_item<'a>(
fn main() {
let path = "input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-type=lib".to_string(),
"--crate-name".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/smir_internal.rs b/tests/ui-fulldeps/stable-mir/smir_internal.rs
index f9972dc27e3ff..0519b9de68050 100644
--- a/tests/ui-fulldeps/stable-mir/smir_internal.rs
+++ b/tests/ui-fulldeps/stable-mir/smir_internal.rs
@@ -40,7 +40,7 @@ fn test_translation(tcx: TyCtxt<'_>) -> ControlFlow<()> {
fn main() {
let path = "internal_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-name".to_string(),
CRATE_NAME.to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/smir_serde.rs b/tests/ui-fulldeps/stable-mir/smir_serde.rs
index 3b3d743ad3263..0b39ec050024e 100644
--- a/tests/ui-fulldeps/stable-mir/smir_serde.rs
+++ b/tests/ui-fulldeps/stable-mir/smir_serde.rs
@@ -46,7 +46,7 @@ fn serialize_to_json(_tcx: TyCtxt<'_>) -> ControlFlow<()> {
fn main() {
let path = "internal_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"--crate-name".to_string(),
CRATE_NAME.to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/smir_visitor.rs b/tests/ui-fulldeps/stable-mir/smir_visitor.rs
index d225d9773fe51..caf71de2556c4 100644
--- a/tests/ui-fulldeps/stable-mir/smir_visitor.rs
+++ b/tests/ui-fulldeps/stable-mir/smir_visitor.rs
@@ -183,14 +183,14 @@ impl mir::MutMirVisitor for TestMutVisitor {
fn main() {
let path = "sim_visitor_input.rs";
generate_input(&path).unwrap();
- let args = vec![
+ let args = &[
"rustc".to_string(),
"-Cpanic=abort".to_string(),
"--crate-name".to_string(),
CRATE_NAME.to_string(),
path.to_string(),
];
- run!(args.clone(), test_visitor).unwrap();
+ run!(args, test_visitor).unwrap();
run!(args, test_mut_visitor).unwrap();
}
| diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs
index 0985ebf945bbd..194ae9041b1a0 100644
--- a/compiler/rustc_ast_pretty/src/pprust/state.rs
+++ b/compiler/rustc_ast_pretty/src/pprust/state.rs
@@ -799,7 +799,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
has_bang,
Some(*ident),
macro_def.body.delim,
- ¯o_def.body.tokens.clone(),
+ ¯o_def.body.tokens,
sp,
@@ -1469,7 +1469,7 @@ impl<'a> State<'a> {
None,
m.args.delim,
- &m.args.tokens.clone(),
+ &m.args.tokens,
m.span(),
diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs
index 146ba17d14fc8..8a7c1bd89fab6 100644
--- a/compiler/rustc_smir/src/rustc_internal/mod.rs
+++ b/compiler/rustc_smir/src/rustc_internal/mod.rs
@@ -256,7 +256,7 @@ where
/// let result = run!(args, analyze_code);
/// # }
@@ -278,7 +278,7 @@ where
/// # let extra_args = vec![];
/// let result = run!(args, || analyze_code(extra_args));
@@ -340,7 +340,6 @@ macro_rules! run_driver {
C: Send,
- args: Vec<String>,
callback: Option<F>,
result: Option<ControlFlow<B, C>>,
@@ -352,14 +351,14 @@ macro_rules! run_driver {
/// Creates a new `StableMir` instance, with given test_function and arguments.
- pub fn new(args: Vec<String>, callback: F) -> Self {
- StableMir { args, callback: Some(callback), result: None }
+ StableMir { callback: Some(callback), result: None }
/// Runs the compiler against given target and tests it with `test_function`
- pub fn run(&mut self) -> Result<C, CompilerError<B>> {
+ pub fn run(&mut self, args: &[String]) -> Result<C, CompilerError<B>> {
let compiler_result = rustc_driver::catch_fatal_errors(|| -> interface::Result::<()> {
- run_compiler(&self.args.clone(), self);
Ok(())
});
match (compiler_result, self.result.take()) {
@@ -409,7 +408,7 @@ macro_rules! run_driver {
- StableMir::new($args, $callback).run()
+ StableMir::new($callback).run($args)
}};
diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs
index 4eecde00eaa1e..f059bd0076897 100644
--- a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs
+++ b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs
@@ -117,8 +117,7 @@ fn relate_mir_and_user_args<'tcx>(
CRATE_DEF_ID,
ObligationCauseCode::AscribeUserTypeProvePredicate(predicate_span),
- let instantiated_predicate =
- ocx.normalize(&cause.clone(), param_env, instantiated_predicate);
+ let instantiated_predicate = ocx.normalize(&cause, param_env, instantiated_predicate);
ocx.register_obligation(Obligation::new(tcx, cause, param_env, instantiated_predicate));
diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs
index 041f80c1f2c52..7ad9e59dfede1 100644
--- a/library/alloc/src/collections/btree/set.rs
+++ b/library/alloc/src/collections/btree/set.rs
@@ -139,7 +139,7 @@ pub struct Iter<'a, T: 'a> {
#[stable(feature = "collection_debug", since = "1.17.0")]
impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_tuple("Iter").field(&self.iter.clone()).finish()
+ f.debug_tuple("Iter").field(&self.iter).finish()
diff --git a/src/bootstrap/src/core/build_steps/setup.rs b/src/bootstrap/src/core/build_steps/setup.rs
index 83083e12ef1fc..9d07babe5196b 100644
--- a/src/bootstrap/src/core/build_steps/setup.rs
+++ b/src/bootstrap/src/core/build_steps/setup.rs
@@ -683,7 +683,7 @@ impl Step for Editor {
match EditorKind::prompt_user() {
Ok(editor_kind) => {
if let Some(editor_kind) = editor_kind {
- while !t!(create_editor_settings_maybe(config, editor_kind.clone())) {}
+ while !t!(create_editor_settings_maybe(config, &editor_kind)) {}
} else {
println!("Ok, skipping editor setup!");
}
@@ -695,7 +695,7 @@ impl Step for Editor {
/// Create the recommended editor LSP config file for rustc development, or just print it
/// If this method should be re-called, it returns `false`.
-fn create_editor_settings_maybe(config: &Config, editor: EditorKind) -> io::Result<bool> {
+fn create_editor_settings_maybe(config: &Config, editor: &EditorKind) -> io::Result<bool> {
let hashes = editor.hashes();
let (current_hash, historical_hashes) = hashes.split_last().unwrap();
let settings_path = editor.settings_path(config);
@@ -752,7 +752,7 @@ fn create_editor_settings_maybe(config: &Config, editor: EditorKind) -> io::Resu
// exists but user modified, back it up
Some(false) => {
// exists and is not current version or outdated, so back it up
- let backup = settings_path.clone().with_extension(editor.backup_extension());
+ let backup = settings_path.with_extension(editor.backup_extension());
eprintln!(
"WARNING: copying `{}` to `{}`",
settings_path.file_name().unwrap().to_str().unwrap(),
diff --git a/tests/ui-fulldeps/stable-mir/check_abi.rs b/tests/ui-fulldeps/stable-mir/check_abi.rs
index ebf2e333f085a..71edf813a7be2 100644
--- a/tests/ui-fulldeps/stable-mir/check_abi.rs
+++ b/tests/ui-fulldeps/stable-mir/check_abi.rs
@@ -145,7 +145,7 @@ fn get_item<'a>(
diff --git a/tests/ui-fulldeps/stable-mir/check_allocation.rs b/tests/ui-fulldeps/stable-mir/check_allocation.rs
index ae2609bbc1221..692c24f054451 100644
--- a/tests/ui-fulldeps/stable-mir/check_allocation.rs
+++ b/tests/ui-fulldeps/stable-mir/check_allocation.rs
@@ -219,7 +219,7 @@ fn get_item<'a>(
"--edition=2021".to_string(),
diff --git a/tests/ui-fulldeps/stable-mir/check_assoc_items.rs b/tests/ui-fulldeps/stable-mir/check_assoc_items.rs
index 9d611543b5aa7..755bec8747bc8 100644
--- a/tests/ui-fulldeps/stable-mir/check_assoc_items.rs
+++ b/tests/ui-fulldeps/stable-mir/check_assoc_items.rs
@@ -85,7 +85,7 @@ fn check_items<T: CrateDef>(items: &[T], expected: &[&str]) {
let path = "assoc_items.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_attribute.rs b/tests/ui-fulldeps/stable-mir/check_attribute.rs
index 4148fc0cb6a07..81d5399d88aa6 100644
--- a/tests/ui-fulldeps/stable-mir/check_attribute.rs
+++ b/tests/ui-fulldeps/stable-mir/check_attribute.rs
@@ -57,7 +57,7 @@ fn get_item<'a>(
let path = "attribute_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_binop.rs b/tests/ui-fulldeps/stable-mir/check_binop.rs
index 6a141e9c5775c..f9559d9958d28 100644
--- a/tests/ui-fulldeps/stable-mir/check_binop.rs
+++ b/tests/ui-fulldeps/stable-mir/check_binop.rs
@@ -81,7 +81,7 @@ impl<'a> MirVisitor for Visitor<'a> {
run!(args, test_binops).unwrap();
diff --git a/tests/ui-fulldeps/stable-mir/check_crate_defs.rs b/tests/ui-fulldeps/stable-mir/check_crate_defs.rs
index 31c47192d090f..6863242f22571 100644
--- a/tests/ui-fulldeps/stable-mir/check_crate_defs.rs
+++ b/tests/ui-fulldeps/stable-mir/check_crate_defs.rs
@@ -84,7 +84,7 @@ fn contains<T: CrateDef + std::fmt::Debug>(items: &[T], expected: &[&str]) {
let path = "crate_definitions.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_def_ty.rs b/tests/ui-fulldeps/stable-mir/check_def_ty.rs
index 00a34f138673b..f86a8e0ae6189 100644
--- a/tests/ui-fulldeps/stable-mir/check_def_ty.rs
+++ b/tests/ui-fulldeps/stable-mir/check_def_ty.rs
@@ -76,7 +76,7 @@ fn check_fn_def(ty: Ty) {
let path = "defs_ty_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_defs.rs b/tests/ui-fulldeps/stable-mir/check_defs.rs
index 1ba73377d6e9f..ab741378bb713 100644
--- a/tests/ui-fulldeps/stable-mir/check_defs.rs
+++ b/tests/ui-fulldeps/stable-mir/check_defs.rs
@@ -112,7 +112,7 @@ fn get_instances(body: mir::Body) -> Vec<Instance> {
let path = "defs_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_foreign.rs b/tests/ui-fulldeps/stable-mir/check_foreign.rs
index 4419050ceb2c1..398024c4ff082 100644
--- a/tests/ui-fulldeps/stable-mir/check_foreign.rs
+++ b/tests/ui-fulldeps/stable-mir/check_foreign.rs
@@ -58,7 +58,7 @@ fn test_foreign() -> ControlFlow<()> {
let path = "foreign_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_instance.rs b/tests/ui-fulldeps/stable-mir/check_instance.rs
index 1510a622cdfdb..b19e5b033c469 100644
--- a/tests/ui-fulldeps/stable-mir/check_instance.rs
+++ b/tests/ui-fulldeps/stable-mir/check_instance.rs
@@ -87,7 +87,7 @@ fn test_body(body: mir::Body) {
let path = "instance_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_intrinsics.rs b/tests/ui-fulldeps/stable-mir/check_intrinsics.rs
index 3f04abbb9d76d..52424857dc196 100644
--- a/tests/ui-fulldeps/stable-mir/check_intrinsics.rs
+++ b/tests/ui-fulldeps/stable-mir/check_intrinsics.rs
@@ -115,7 +115,7 @@ impl<'a> MirVisitor for CallsVisitor<'a> {
run!(args, test_intrinsics).unwrap();
diff --git a/tests/ui-fulldeps/stable-mir/check_item_kind.rs b/tests/ui-fulldeps/stable-mir/check_item_kind.rs
index bb8c00c64c955..d1124c75a8997 100644
--- a/tests/ui-fulldeps/stable-mir/check_item_kind.rs
+++ b/tests/ui-fulldeps/stable-mir/check_item_kind.rs
@@ -47,7 +47,7 @@ fn test_item_kind() -> ControlFlow<()> {
let path = "item_kind_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_normalization.rs b/tests/ui-fulldeps/stable-mir/check_normalization.rs
index 797cb4cd5d051..16e8c0339ed47 100644
--- a/tests/ui-fulldeps/stable-mir/check_normalization.rs
+++ b/tests/ui-fulldeps/stable-mir/check_normalization.rs
@@ -61,7 +61,7 @@ fn check_ty(ty: Ty) {
let path = "normalization_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_trait_queries.rs b/tests/ui-fulldeps/stable-mir/check_trait_queries.rs
index d9170d0c40811..fcf04a1fc3a3f 100644
--- a/tests/ui-fulldeps/stable-mir/check_trait_queries.rs
+++ b/tests/ui-fulldeps/stable-mir/check_trait_queries.rs
@@ -72,7 +72,7 @@ fn assert_impl(impl_names: &HashSet<String>, target: &str) {
let path = "trait_queries.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_transform.rs b/tests/ui-fulldeps/stable-mir/check_transform.rs
index 604cc72c3418e..9087c1cf45027 100644
--- a/tests/ui-fulldeps/stable-mir/check_transform.rs
+++ b/tests/ui-fulldeps/stable-mir/check_transform.rs
@@ -120,7 +120,7 @@ fn get_item<'a>(
let path = "transform_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/check_ty_fold.rs b/tests/ui-fulldeps/stable-mir/check_ty_fold.rs
index 23233f8406cf5..18b9e32e4e809 100644
--- a/tests/ui-fulldeps/stable-mir/check_ty_fold.rs
+++ b/tests/ui-fulldeps/stable-mir/check_ty_fold.rs
@@ -78,7 +78,7 @@ impl<'a> MirVisitor for PlaceVisitor<'a> {
let path = "ty_fold_input.rs";
diff --git a/tests/ui-fulldeps/stable-mir/compilation-result.rs b/tests/ui-fulldeps/stable-mir/compilation-result.rs
index 39416636fd673..19b9c8b7de508 100644
--- a/tests/ui-fulldeps/stable-mir/compilation-result.rs
+++ b/tests/ui-fulldeps/stable-mir/compilation-result.rs
@@ -25,40 +25,42 @@ use std::io::Write;
let path = "input_compilation_result_test.rs";
- let args = vec!["rustc".to_string(), path.to_string()];
- test_continue(args.clone());
- test_break(args.clone());
- test_failed(args.clone());
- test_skipped(args.clone());
+ let args = &["rustc".to_string(), path.to_string()];
+ test_continue(args);
+ test_break(args);
+ test_failed(args);
+ test_skipped(args);
test_captured(args)
-fn test_continue(args: Vec<String>) {
+fn test_continue(args: &[String]) {
let result = run!(args, || ControlFlow::Continue::<(), bool>(true));
assert_eq!(result, Ok(true));
-fn test_break(args: Vec<String>) {
let result = run!(args, || ControlFlow::Break::<bool, i32>(false));
assert_eq!(result, Err(stable_mir::CompilerError::Interrupted(false)));
-fn test_skipped(mut args: Vec<String>) {
+fn test_skipped(args: &[String]) {
args.push("--version".to_string());
assert_eq!(result, Err(stable_mir::CompilerError::Skipped));
-fn test_failed(mut args: Vec<String>) {
+fn test_failed(args: &[String]) {
args.push("--cfg=broken".to_string());
assert_eq!(result, Err(stable_mir::CompilerError::Failed));
/// Test that we are able to pass a closure and set the return according to the captured value.
-fn test_captured(args: Vec<String>) {
+fn test_captured(args: &[String]) {
let captured = "10".to_string();
let result = run!(args, || ControlFlow::Continue::<(), usize>(captured.len()));
assert_eq!(result, Ok(captured.len()));
diff --git a/tests/ui-fulldeps/stable-mir/crate-info.rs b/tests/ui-fulldeps/stable-mir/crate-info.rs
index e2086d5e57907..7fc4edafb9338 100644
--- a/tests/ui-fulldeps/stable-mir/crate-info.rs
+++ b/tests/ui-fulldeps/stable-mir/crate-info.rs
@@ -186,7 +186,7 @@ fn get_item<'a>(
diff --git a/tests/ui-fulldeps/stable-mir/projections.rs b/tests/ui-fulldeps/stable-mir/projections.rs
index f3bd894ac6903..103c97bc48e17 100644
--- a/tests/ui-fulldeps/stable-mir/projections.rs
+++ b/tests/ui-fulldeps/stable-mir/projections.rs
@@ -146,7 +146,7 @@ fn get_item<'a>(
diff --git a/tests/ui-fulldeps/stable-mir/smir_internal.rs b/tests/ui-fulldeps/stable-mir/smir_internal.rs
index f9972dc27e3ff..0519b9de68050 100644
--- a/tests/ui-fulldeps/stable-mir/smir_internal.rs
+++ b/tests/ui-fulldeps/stable-mir/smir_internal.rs
@@ -40,7 +40,7 @@ fn test_translation(tcx: TyCtxt<'_>) -> ControlFlow<()> {
diff --git a/tests/ui-fulldeps/stable-mir/smir_serde.rs b/tests/ui-fulldeps/stable-mir/smir_serde.rs
index 3b3d743ad3263..0b39ec050024e 100644
--- a/tests/ui-fulldeps/stable-mir/smir_serde.rs
+++ b/tests/ui-fulldeps/stable-mir/smir_serde.rs
@@ -46,7 +46,7 @@ fn serialize_to_json(_tcx: TyCtxt<'_>) -> ControlFlow<()> {
diff --git a/tests/ui-fulldeps/stable-mir/smir_visitor.rs b/tests/ui-fulldeps/stable-mir/smir_visitor.rs
index d225d9773fe51..caf71de2556c4 100644
--- a/tests/ui-fulldeps/stable-mir/smir_visitor.rs
+++ b/tests/ui-fulldeps/stable-mir/smir_visitor.rs
@@ -183,14 +183,14 @@ impl mir::MutMirVisitor for TestMutVisitor {
let path = "sim_visitor_input.rs";
path.to_string(),
];
- run!(args.clone(), test_visitor).unwrap();
+ run!(args, test_visitor).unwrap();
run!(args, test_mut_visitor).unwrap(); | [
"+ pub fn new(callback: F) -> Self {",
"+ run_compiler(&args, self);",
"+fn test_break(args: &[String]) {"
] | [
58,
67,
374
] | {
"additions": 50,
"author": "nnethercote",
"deletions": 50,
"html_url": "https://github.com/rust-lang/rust/pull/140232",
"issue_id": 140232,
"merged_at": "2025-04-24T12:05:12Z",
"omission_probability": 0.1,
"pr_number": 140232,
"repo": "rust-lang/rust",
"title": "Remove unnecessary clones",
"total_changes": 100
} |
121 | diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs
index 8de68925cabbc..f0c47ac41e8a0 100644
--- a/compiler/rustc_codegen_ssa/src/back/link.rs
+++ b/compiler/rustc_codegen_ssa/src/back/link.rs
@@ -2015,6 +2015,12 @@ fn add_linked_symbol_object(
file.set_mangling(object::write::Mangling::None);
}
+ if file.format() == object::BinaryFormat::MachO {
+ // Divide up the sections into sub-sections via symbols for dead code stripping.
+ // Without this flag, unused `#[no_mangle]` or `#[used]` cannot be discard on MachO targets.
+ file.set_subsections_via_symbols();
+ }
+
// ld64 requires a relocation to load undefined symbols, see below.
// Not strictly needed if linking with lld, but might as well do it there too.
let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
diff --git a/tests/ui/linking/cdylib-no-mangle.rs b/tests/ui/linking/cdylib-no-mangle.rs
new file mode 100644
index 0000000000000..f442c3f584d6e
--- /dev/null
+++ b/tests/ui/linking/cdylib-no-mangle.rs
@@ -0,0 +1,20 @@
+//@ only-apple
+//@ build-fail
+//@ dont-check-compiler-stderr
+//@ dont-check-compiler-stdout
+
+// Regression test for <https://github.com/rust-lang/rust/issues/139744>.
+// Functions in the dynamic library marked with no_mangle should not be GC-ed.
+
+#![crate_type = "cdylib"]
+
+unsafe extern "C" {
+ unsafe static THIS_SYMBOL_SHOULD_BE_UNDEFINED: usize;
+}
+
+#[unsafe(no_mangle)]
+pub unsafe fn function_marked_with_no_mangle() {
+ println!("FUNCTION_MARKED_WITH_NO_MANGLE = {}", unsafe { THIS_SYMBOL_SHOULD_BE_UNDEFINED });
+}
+
+//~? ERROR linking
diff --git a/tests/ui/linking/executable-no-mangle-strip.rs b/tests/ui/linking/executable-no-mangle-strip.rs
new file mode 100644
index 0000000000000..cc283dc53ee3a
--- /dev/null
+++ b/tests/ui/linking/executable-no-mangle-strip.rs
@@ -0,0 +1,27 @@
+//@ run-pass
+//@ ignore-windows-gnu: only statics marked with used can be GC-ed on windows-gnu
+
+// Regression test for <https://github.com/rust-lang/rust/issues/139744>.
+// Functions in the binary marked with no_mangle should be GC-ed if they
+// are not indirectly referenced by main.
+
+#![feature(used_with_arg)]
+
+#[cfg_attr(windows, link(name = "this_lib_does_not_exist", kind = "raw-dylib"))]
+unsafe extern "C" {
+ unsafe static THIS_SYMBOL_SHOULD_BE_UNDEFINED: usize;
+}
+
+#[unsafe(no_mangle)]
+pub unsafe fn function_marked_with_no_mangle() {
+ println!("FUNCTION_MARKED_WITH_NO_MANGLE = {}", unsafe { THIS_SYMBOL_SHOULD_BE_UNDEFINED });
+}
+
+#[used(compiler)]
+pub static FUNCTION_MARKED_WITH_USED: unsafe fn() = || {
+ println!("FUNCTION_MARKED_WITH_USED = {}", unsafe { THIS_SYMBOL_SHOULD_BE_UNDEFINED });
+};
+
+fn main() {
+ println!("MAIN");
+}
| diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs
index 8de68925cabbc..f0c47ac41e8a0 100644
--- a/compiler/rustc_codegen_ssa/src/back/link.rs
+++ b/compiler/rustc_codegen_ssa/src/back/link.rs
@@ -2015,6 +2015,12 @@ fn add_linked_symbol_object(
file.set_mangling(object::write::Mangling::None);
}
+ if file.format() == object::BinaryFormat::MachO {
+ // Divide up the sections into sub-sections via symbols for dead code stripping.
+ // Without this flag, unused `#[no_mangle]` or `#[used]` cannot be discard on MachO targets.
+ file.set_subsections_via_symbols();
+ }
// ld64 requires a relocation to load undefined symbols, see below.
// Not strictly needed if linking with lld, but might as well do it there too.
let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
diff --git a/tests/ui/linking/cdylib-no-mangle.rs b/tests/ui/linking/cdylib-no-mangle.rs
index 0000000000000..f442c3f584d6e
+++ b/tests/ui/linking/cdylib-no-mangle.rs
@@ -0,0 +1,20 @@
+//@ only-apple
+//@ build-fail
+//@ dont-check-compiler-stderr
+//@ dont-check-compiler-stdout
+#![crate_type = "cdylib"]
+//~? ERROR linking
diff --git a/tests/ui/linking/executable-no-mangle-strip.rs b/tests/ui/linking/executable-no-mangle-strip.rs
index 0000000000000..cc283dc53ee3a
+++ b/tests/ui/linking/executable-no-mangle-strip.rs
@@ -0,0 +1,27 @@
+//@ run-pass
+//@ ignore-windows-gnu: only statics marked with used can be GC-ed on windows-gnu
+// Functions in the binary marked with no_mangle should be GC-ed if they
+// are not indirectly referenced by main.
+#[cfg_attr(windows, link(name = "this_lib_does_not_exist", kind = "raw-dylib"))]
+#[used(compiler)]
+pub static FUNCTION_MARKED_WITH_USED: unsafe fn() = || {
+ println!("FUNCTION_MARKED_WITH_USED = {}", unsafe { THIS_SYMBOL_SHOULD_BE_UNDEFINED });
+};
+fn main() {
+ println!("MAIN"); | [
"+// Functions in the dynamic library marked with no_mangle should not be GC-ed.",
"+#![feature(used_with_arg)]"
] | [
29,
56
] | {
"additions": 53,
"author": "usamoi",
"deletions": 0,
"html_url": "https://github.com/rust-lang/rust/pull/139752",
"issue_id": 139752,
"merged_at": "2025-04-25T02:18:45Z",
"omission_probability": 0.1,
"pr_number": 139752,
"repo": "rust-lang/rust",
"title": "set subsections_via_symbols for ld64 helper sections",
"total_changes": 53
} |
122 | diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs
index 7109fefbe783e..69f650a49b1e6 100644
--- a/compiler/rustc_lint/src/types.rs
+++ b/compiler/rustc_lint/src/types.rs
@@ -1,7 +1,9 @@
use std::iter;
use std::ops::ControlFlow;
-use rustc_abi::{BackendRepr, TagEncoding, VariantIdx, Variants, WrappingRange};
+use rustc_abi::{
+ BackendRepr, Integer, IntegerType, TagEncoding, VariantIdx, Variants, WrappingRange,
+};
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::DiagMessage;
use rustc_hir::intravisit::VisitorExt;
@@ -1246,6 +1248,14 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
};
}
+ if let Some(IntegerType::Fixed(Integer::I128, _)) = def.repr().int {
+ return FfiUnsafe {
+ ty,
+ reason: fluent::lint_improper_ctypes_128bit,
+ help: None,
+ };
+ }
+
use improper_ctypes::check_non_exhaustive_variant;
let non_exhaustive = def.variant_list_has_applicable_non_exhaustive();
diff --git a/tests/ui/lint/lint-ctypes-enum.rs b/tests/ui/lint/lint-ctypes-enum.rs
index 0d19d5b534713..b2ef27b833bdb 100644
--- a/tests/ui/lint/lint-ctypes-enum.rs
+++ b/tests/ui/lint/lint-ctypes-enum.rs
@@ -2,6 +2,8 @@
#![deny(improper_ctypes)]
#![feature(ptr_internals)]
#![feature(transparent_unions)]
+#![feature(repr128)]
+#![allow(incomplete_features)]
use std::num;
@@ -40,6 +42,20 @@ enum Isize {
C,
}
+#[repr(u128)]
+enum U128 {
+ A,
+ B,
+ C,
+}
+
+#[repr(i128)]
+enum I128 {
+ A,
+ B,
+ C,
+}
+
#[repr(transparent)]
struct TransparentStruct<T>(T, std::marker::PhantomData<Z>);
@@ -71,6 +87,8 @@ extern "C" {
fn repr_c(x: ReprC);
fn repr_u8(x: U8);
fn repr_isize(x: Isize);
+ fn repr_u128(x: U128); //~ ERROR `extern` block uses type `U128`
+ fn repr_i128(x: I128); //~ ERROR `extern` block uses type `I128`
fn option_ref(x: Option<&'static u8>);
fn option_fn(x: Option<extern "C" fn()>);
fn option_nonnull(x: Option<std::ptr::NonNull<u8>>);
diff --git a/tests/ui/lint/lint-ctypes-enum.stderr b/tests/ui/lint/lint-ctypes-enum.stderr
index a491bd1960563..d5fc844f75607 100644
--- a/tests/ui/lint/lint-ctypes-enum.stderr
+++ b/tests/ui/lint/lint-ctypes-enum.stderr
@@ -1,5 +1,5 @@
error: `extern` block uses type `U`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:68:14
+ --> $DIR/lint-ctypes-enum.rs:84:14
|
LL | fn uf(x: U);
| ^ not FFI-safe
@@ -7,7 +7,7 @@ LL | fn uf(x: U);
= help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum
= note: enum has no representation hint
note: the type is defined here
- --> $DIR/lint-ctypes-enum.rs:9:1
+ --> $DIR/lint-ctypes-enum.rs:11:1
|
LL | enum U {
| ^^^^^^
@@ -18,7 +18,7 @@ LL | #![deny(improper_ctypes)]
| ^^^^^^^^^^^^^^^
error: `extern` block uses type `B`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:69:14
+ --> $DIR/lint-ctypes-enum.rs:85:14
|
LL | fn bf(x: B);
| ^ not FFI-safe
@@ -26,13 +26,13 @@ LL | fn bf(x: B);
= help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum
= note: enum has no representation hint
note: the type is defined here
- --> $DIR/lint-ctypes-enum.rs:12:1
+ --> $DIR/lint-ctypes-enum.rs:14:1
|
LL | enum B {
| ^^^^^^
error: `extern` block uses type `T`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:70:14
+ --> $DIR/lint-ctypes-enum.rs:86:14
|
LL | fn tf(x: T);
| ^ not FFI-safe
@@ -40,13 +40,39 @@ LL | fn tf(x: T);
= help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum
= note: enum has no representation hint
note: the type is defined here
- --> $DIR/lint-ctypes-enum.rs:16:1
+ --> $DIR/lint-ctypes-enum.rs:18:1
|
LL | enum T {
| ^^^^^^
+error: `extern` block uses type `U128`, which is not FFI-safe
+ --> $DIR/lint-ctypes-enum.rs:90:21
+ |
+LL | fn repr_u128(x: U128);
+ | ^^^^ not FFI-safe
+ |
+ = note: 128-bit integers don't currently have a known stable ABI
+note: the type is defined here
+ --> $DIR/lint-ctypes-enum.rs:46:1
+ |
+LL | enum U128 {
+ | ^^^^^^^^^
+
+error: `extern` block uses type `I128`, which is not FFI-safe
+ --> $DIR/lint-ctypes-enum.rs:91:21
+ |
+LL | fn repr_i128(x: I128);
+ | ^^^^ not FFI-safe
+ |
+ = note: 128-bit integers don't currently have a known stable ABI
+note: the type is defined here
+ --> $DIR/lint-ctypes-enum.rs:53:1
+ |
+LL | enum I128 {
+ | ^^^^^^^^^
+
error: `extern` block uses type `u128`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:82:31
+ --> $DIR/lint-ctypes-enum.rs:100:31
|
LL | fn option_nonzero_u128(x: Option<num::NonZero<u128>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -54,7 +80,7 @@ LL | fn option_nonzero_u128(x: Option<num::NonZero<u128>>);
= note: 128-bit integers don't currently have a known stable ABI
error: `extern` block uses type `i128`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:89:31
+ --> $DIR/lint-ctypes-enum.rs:107:31
|
LL | fn option_nonzero_i128(x: Option<num::NonZero<i128>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -62,7 +88,7 @@ LL | fn option_nonzero_i128(x: Option<num::NonZero<i128>>);
= note: 128-bit integers don't currently have a known stable ABI
error: `extern` block uses type `Option<TransparentUnion<NonZero<u8>>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:94:36
+ --> $DIR/lint-ctypes-enum.rs:112:36
|
LL | fn option_transparent_union(x: Option<TransparentUnion<num::NonZero<u8>>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -71,7 +97,7 @@ LL | fn option_transparent_union(x: Option<TransparentUnion<num::NonZero<u8>
= note: enum has no representation hint
error: `extern` block uses type `Option<Rust<NonZero<u8>>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:96:28
+ --> $DIR/lint-ctypes-enum.rs:114:28
|
LL | fn option_repr_rust(x: Option<Rust<num::NonZero<u8>>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -80,7 +106,7 @@ LL | fn option_repr_rust(x: Option<Rust<num::NonZero<u8>>>);
= note: enum has no representation hint
error: `extern` block uses type `Option<u8>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:97:21
+ --> $DIR/lint-ctypes-enum.rs:115:21
|
LL | fn option_u8(x: Option<u8>);
| ^^^^^^^^^^ not FFI-safe
@@ -89,7 +115,7 @@ LL | fn option_u8(x: Option<u8>);
= note: enum has no representation hint
error: `extern` block uses type `u128`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:107:33
+ --> $DIR/lint-ctypes-enum.rs:125:33
|
LL | fn result_nonzero_u128_t(x: Result<num::NonZero<u128>, ()>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -97,7 +123,7 @@ LL | fn result_nonzero_u128_t(x: Result<num::NonZero<u128>, ()>);
= note: 128-bit integers don't currently have a known stable ABI
error: `extern` block uses type `i128`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:114:33
+ --> $DIR/lint-ctypes-enum.rs:132:33
|
LL | fn result_nonzero_i128_t(x: Result<num::NonZero<i128>, ()>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -105,7 +131,7 @@ LL | fn result_nonzero_i128_t(x: Result<num::NonZero<i128>, ()>);
= note: 128-bit integers don't currently have a known stable ABI
error: `extern` block uses type `Result<TransparentUnion<NonZero<u8>>, ()>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:119:38
+ --> $DIR/lint-ctypes-enum.rs:137:38
|
LL | fn result_transparent_union_t(x: Result<TransparentUnion<num::NonZero<u8>>, ()>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -114,7 +140,7 @@ LL | fn result_transparent_union_t(x: Result<TransparentUnion<num::NonZero<u
= note: enum has no representation hint
error: `extern` block uses type `Result<Rust<NonZero<u8>>, ()>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:121:30
+ --> $DIR/lint-ctypes-enum.rs:139:30
|
LL | fn result_repr_rust_t(x: Result<Rust<num::NonZero<u8>>, ()>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -123,7 +149,7 @@ LL | fn result_repr_rust_t(x: Result<Rust<num::NonZero<u8>>, ()>);
= note: enum has no representation hint
error: `extern` block uses type `Result<NonZero<u8>, U>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:125:51
+ --> $DIR/lint-ctypes-enum.rs:143:51
|
LL | fn result_1zst_exhaustive_single_variant_t(x: Result<num::NonZero<u8>, U>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -132,7 +158,7 @@ LL | fn result_1zst_exhaustive_single_variant_t(x: Result<num::NonZero<u8>,
= note: enum has no representation hint
error: `extern` block uses type `Result<NonZero<u8>, B>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:127:53
+ --> $DIR/lint-ctypes-enum.rs:145:53
|
LL | fn result_1zst_exhaustive_multiple_variant_t(x: Result<num::NonZero<u8>, B>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -141,7 +167,7 @@ LL | fn result_1zst_exhaustive_multiple_variant_t(x: Result<num::NonZero<u8>
= note: enum has no representation hint
error: `extern` block uses type `Result<NonZero<u8>, NonExhaustive>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:129:51
+ --> $DIR/lint-ctypes-enum.rs:147:51
|
LL | fn result_1zst_non_exhaustive_no_variant_t(x: Result<num::NonZero<u8>, NonExhaustive>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -150,7 +176,7 @@ LL | fn result_1zst_non_exhaustive_no_variant_t(x: Result<num::NonZero<u8>,
= note: enum has no representation hint
error: `extern` block uses type `Result<NonZero<u8>, Field>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:132:49
+ --> $DIR/lint-ctypes-enum.rs:150:49
|
LL | fn result_1zst_exhaustive_single_field_t(x: Result<num::NonZero<u8>, Field>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -159,7 +185,7 @@ LL | fn result_1zst_exhaustive_single_field_t(x: Result<num::NonZero<u8>, Fi
= note: enum has no representation hint
error: `extern` block uses type `Result<Result<(), NonZero<u8>>, ()>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:134:30
+ --> $DIR/lint-ctypes-enum.rs:152:30
|
LL | fn result_cascading_t(x: Result<Result<(), num::NonZero<u8>>, ()>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -168,7 +194,7 @@ LL | fn result_cascading_t(x: Result<Result<(), num::NonZero<u8>>, ()>);
= note: enum has no representation hint
error: `extern` block uses type `u128`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:145:33
+ --> $DIR/lint-ctypes-enum.rs:163:33
|
LL | fn result_nonzero_u128_e(x: Result<(), num::NonZero<u128>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -176,7 +202,7 @@ LL | fn result_nonzero_u128_e(x: Result<(), num::NonZero<u128>>);
= note: 128-bit integers don't currently have a known stable ABI
error: `extern` block uses type `i128`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:152:33
+ --> $DIR/lint-ctypes-enum.rs:170:33
|
LL | fn result_nonzero_i128_e(x: Result<(), num::NonZero<i128>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -184,7 +210,7 @@ LL | fn result_nonzero_i128_e(x: Result<(), num::NonZero<i128>>);
= note: 128-bit integers don't currently have a known stable ABI
error: `extern` block uses type `Result<(), TransparentUnion<NonZero<u8>>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:157:38
+ --> $DIR/lint-ctypes-enum.rs:175:38
|
LL | fn result_transparent_union_e(x: Result<(), TransparentUnion<num::NonZero<u8>>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -193,7 +219,7 @@ LL | fn result_transparent_union_e(x: Result<(), TransparentUnion<num::NonZe
= note: enum has no representation hint
error: `extern` block uses type `Result<(), Rust<NonZero<u8>>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:159:30
+ --> $DIR/lint-ctypes-enum.rs:177:30
|
LL | fn result_repr_rust_e(x: Result<(), Rust<num::NonZero<u8>>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -202,7 +228,7 @@ LL | fn result_repr_rust_e(x: Result<(), Rust<num::NonZero<u8>>>);
= note: enum has no representation hint
error: `extern` block uses type `Result<U, NonZero<u8>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:163:51
+ --> $DIR/lint-ctypes-enum.rs:181:51
|
LL | fn result_1zst_exhaustive_single_variant_e(x: Result<U, num::NonZero<u8>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -211,7 +237,7 @@ LL | fn result_1zst_exhaustive_single_variant_e(x: Result<U, num::NonZero<u8
= note: enum has no representation hint
error: `extern` block uses type `Result<B, NonZero<u8>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:165:53
+ --> $DIR/lint-ctypes-enum.rs:183:53
|
LL | fn result_1zst_exhaustive_multiple_variant_e(x: Result<B, num::NonZero<u8>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -220,7 +246,7 @@ LL | fn result_1zst_exhaustive_multiple_variant_e(x: Result<B, num::NonZero<
= note: enum has no representation hint
error: `extern` block uses type `Result<NonExhaustive, NonZero<u8>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:167:51
+ --> $DIR/lint-ctypes-enum.rs:185:51
|
LL | fn result_1zst_non_exhaustive_no_variant_e(x: Result<NonExhaustive, num::NonZero<u8>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -229,7 +255,7 @@ LL | fn result_1zst_non_exhaustive_no_variant_e(x: Result<NonExhaustive, num
= note: enum has no representation hint
error: `extern` block uses type `Result<Field, NonZero<u8>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:170:49
+ --> $DIR/lint-ctypes-enum.rs:188:49
|
LL | fn result_1zst_exhaustive_single_field_e(x: Result<Field, num::NonZero<u8>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -238,7 +264,7 @@ LL | fn result_1zst_exhaustive_single_field_e(x: Result<Field, num::NonZero<
= note: enum has no representation hint
error: `extern` block uses type `Result<(), Result<(), NonZero<u8>>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:172:30
+ --> $DIR/lint-ctypes-enum.rs:190:30
|
LL | fn result_cascading_e(x: Result<(), Result<(), num::NonZero<u8>>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -247,7 +273,7 @@ LL | fn result_cascading_e(x: Result<(), Result<(), num::NonZero<u8>>>);
= note: enum has no representation hint
error: `extern` block uses type `Result<(), ()>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:174:27
+ --> $DIR/lint-ctypes-enum.rs:192:27
|
LL | fn result_unit_t_e(x: Result<(), ()>);
| ^^^^^^^^^^^^^^ not FFI-safe
@@ -255,5 +281,5 @@ LL | fn result_unit_t_e(x: Result<(), ()>);
= help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum
= note: enum has no representation hint
-error: aborting due to 27 previous errors
+error: aborting due to 29 previous errors
| diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs
index 7109fefbe783e..69f650a49b1e6 100644
--- a/compiler/rustc_lint/src/types.rs
+++ b/compiler/rustc_lint/src/types.rs
@@ -1,7 +1,9 @@
use std::iter;
use std::ops::ControlFlow;
-use rustc_abi::{BackendRepr, TagEncoding, VariantIdx, Variants, WrappingRange};
+ BackendRepr, Integer, IntegerType, TagEncoding, VariantIdx, Variants, WrappingRange,
+};
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::DiagMessage;
use rustc_hir::intravisit::VisitorExt;
@@ -1246,6 +1248,14 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
};
}
+ if let Some(IntegerType::Fixed(Integer::I128, _)) = def.repr().int {
+ return FfiUnsafe {
+ reason: fluent::lint_improper_ctypes_128bit,
+ help: None,
+ }
use improper_ctypes::check_non_exhaustive_variant;
let non_exhaustive = def.variant_list_has_applicable_non_exhaustive();
diff --git a/tests/ui/lint/lint-ctypes-enum.rs b/tests/ui/lint/lint-ctypes-enum.rs
index 0d19d5b534713..b2ef27b833bdb 100644
--- a/tests/ui/lint/lint-ctypes-enum.rs
+++ b/tests/ui/lint/lint-ctypes-enum.rs
@@ -2,6 +2,8 @@
#![deny(improper_ctypes)]
#![feature(ptr_internals)]
#![feature(transparent_unions)]
+#![feature(repr128)]
+#![allow(incomplete_features)]
use std::num;
@@ -40,6 +42,20 @@ enum Isize {
C,
}
+#[repr(u128)]
+enum U128 {
+#[repr(i128)]
+enum I128 {
#[repr(transparent)]
struct TransparentStruct<T>(T, std::marker::PhantomData<Z>);
@@ -71,6 +87,8 @@ extern "C" {
fn repr_c(x: ReprC);
fn repr_u8(x: U8);
fn repr_isize(x: Isize);
+ fn repr_u128(x: U128); //~ ERROR `extern` block uses type `U128`
fn option_ref(x: Option<&'static u8>);
fn option_fn(x: Option<extern "C" fn()>);
fn option_nonnull(x: Option<std::ptr::NonNull<u8>>);
diff --git a/tests/ui/lint/lint-ctypes-enum.stderr b/tests/ui/lint/lint-ctypes-enum.stderr
index a491bd1960563..d5fc844f75607 100644
--- a/tests/ui/lint/lint-ctypes-enum.stderr
+++ b/tests/ui/lint/lint-ctypes-enum.stderr
@@ -1,5 +1,5 @@
error: `extern` block uses type `U`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:68:14
+ --> $DIR/lint-ctypes-enum.rs:84:14
LL | fn uf(x: U);
@@ -7,7 +7,7 @@ LL | fn uf(x: U);
- --> $DIR/lint-ctypes-enum.rs:9:1
LL | enum U {
@@ -18,7 +18,7 @@ LL | #![deny(improper_ctypes)]
| ^^^^^^^^^^^^^^^
error: `extern` block uses type `B`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:69:14
+ --> $DIR/lint-ctypes-enum.rs:85:14
LL | fn bf(x: B);
@@ -26,13 +26,13 @@ LL | fn bf(x: B);
- --> $DIR/lint-ctypes-enum.rs:12:1
+ --> $DIR/lint-ctypes-enum.rs:14:1
LL | enum B {
error: `extern` block uses type `T`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:70:14
+ --> $DIR/lint-ctypes-enum.rs:86:14
LL | fn tf(x: T);
@@ -40,13 +40,39 @@ LL | fn tf(x: T);
- --> $DIR/lint-ctypes-enum.rs:16:1
+ --> $DIR/lint-ctypes-enum.rs:18:1
LL | enum T {
+error: `extern` block uses type `U128`, which is not FFI-safe
+ --> $DIR/lint-ctypes-enum.rs:90:21
+LL | fn repr_u128(x: U128);
+ --> $DIR/lint-ctypes-enum.rs:46:1
+LL | enum U128 {
+error: `extern` block uses type `I128`, which is not FFI-safe
+ --> $DIR/lint-ctypes-enum.rs:91:21
+LL | fn repr_i128(x: I128);
+ --> $DIR/lint-ctypes-enum.rs:53:1
+LL | enum I128 {
- --> $DIR/lint-ctypes-enum.rs:82:31
+ --> $DIR/lint-ctypes-enum.rs:100:31
LL | fn option_nonzero_u128(x: Option<num::NonZero<u128>>);
@@ -54,7 +80,7 @@ LL | fn option_nonzero_u128(x: Option<num::NonZero<u128>>);
- --> $DIR/lint-ctypes-enum.rs:89:31
+ --> $DIR/lint-ctypes-enum.rs:107:31
LL | fn option_nonzero_i128(x: Option<num::NonZero<i128>>);
@@ -62,7 +88,7 @@ LL | fn option_nonzero_i128(x: Option<num::NonZero<i128>>);
error: `extern` block uses type `Option<TransparentUnion<NonZero<u8>>>`, which is not FFI-safe
+ --> $DIR/lint-ctypes-enum.rs:112:36
LL | fn option_transparent_union(x: Option<TransparentUnion<num::NonZero<u8>>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -71,7 +97,7 @@ LL | fn option_transparent_union(x: Option<TransparentUnion<num::NonZero<u8>
error: `extern` block uses type `Option<Rust<NonZero<u8>>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:96:28
+ --> $DIR/lint-ctypes-enum.rs:114:28
LL | fn option_repr_rust(x: Option<Rust<num::NonZero<u8>>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe
@@ -80,7 +106,7 @@ LL | fn option_repr_rust(x: Option<Rust<num::NonZero<u8>>>);
error: `extern` block uses type `Option<u8>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:97:21
+ --> $DIR/lint-ctypes-enum.rs:115:21
LL | fn option_u8(x: Option<u8>);
| ^^^^^^^^^^ not FFI-safe
@@ -89,7 +115,7 @@ LL | fn option_u8(x: Option<u8>);
- --> $DIR/lint-ctypes-enum.rs:107:33
+ --> $DIR/lint-ctypes-enum.rs:125:33
LL | fn result_nonzero_u128_t(x: Result<num::NonZero<u128>, ()>);
@@ -97,7 +123,7 @@ LL | fn result_nonzero_u128_t(x: Result<num::NonZero<u128>, ()>);
- --> $DIR/lint-ctypes-enum.rs:114:33
LL | fn result_nonzero_i128_t(x: Result<num::NonZero<i128>, ()>);
@@ -105,7 +131,7 @@ LL | fn result_nonzero_i128_t(x: Result<num::NonZero<i128>, ()>);
error: `extern` block uses type `Result<TransparentUnion<NonZero<u8>>, ()>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:119:38
+ --> $DIR/lint-ctypes-enum.rs:137:38
LL | fn result_transparent_union_t(x: Result<TransparentUnion<num::NonZero<u8>>, ()>);
@@ -114,7 +140,7 @@ LL | fn result_transparent_union_t(x: Result<TransparentUnion<num::NonZero<u
error: `extern` block uses type `Result<Rust<NonZero<u8>>, ()>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:121:30
+ --> $DIR/lint-ctypes-enum.rs:139:30
LL | fn result_repr_rust_t(x: Result<Rust<num::NonZero<u8>>, ()>);
@@ -123,7 +149,7 @@ LL | fn result_repr_rust_t(x: Result<Rust<num::NonZero<u8>>, ()>);
error: `extern` block uses type `Result<NonZero<u8>, U>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:125:51
+ --> $DIR/lint-ctypes-enum.rs:143:51
LL | fn result_1zst_exhaustive_single_variant_t(x: Result<num::NonZero<u8>, U>);
@@ -132,7 +158,7 @@ LL | fn result_1zst_exhaustive_single_variant_t(x: Result<num::NonZero<u8>,
error: `extern` block uses type `Result<NonZero<u8>, B>`, which is not FFI-safe
+ --> $DIR/lint-ctypes-enum.rs:145:53
LL | fn result_1zst_exhaustive_multiple_variant_t(x: Result<num::NonZero<u8>, B>);
@@ -141,7 +167,7 @@ LL | fn result_1zst_exhaustive_multiple_variant_t(x: Result<num::NonZero<u8>
error: `extern` block uses type `Result<NonZero<u8>, NonExhaustive>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:129:51
+ --> $DIR/lint-ctypes-enum.rs:147:51
LL | fn result_1zst_non_exhaustive_no_variant_t(x: Result<num::NonZero<u8>, NonExhaustive>);
@@ -150,7 +176,7 @@ LL | fn result_1zst_non_exhaustive_no_variant_t(x: Result<num::NonZero<u8>,
error: `extern` block uses type `Result<NonZero<u8>, Field>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:132:49
+ --> $DIR/lint-ctypes-enum.rs:150:49
LL | fn result_1zst_exhaustive_single_field_t(x: Result<num::NonZero<u8>, Field>);
@@ -159,7 +185,7 @@ LL | fn result_1zst_exhaustive_single_field_t(x: Result<num::NonZero<u8>, Fi
error: `extern` block uses type `Result<Result<(), NonZero<u8>>, ()>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:134:30
+ --> $DIR/lint-ctypes-enum.rs:152:30
LL | fn result_cascading_t(x: Result<Result<(), num::NonZero<u8>>, ()>);
@@ -168,7 +194,7 @@ LL | fn result_cascading_t(x: Result<Result<(), num::NonZero<u8>>, ()>);
+ --> $DIR/lint-ctypes-enum.rs:163:33
LL | fn result_nonzero_u128_e(x: Result<(), num::NonZero<u128>>);
@@ -176,7 +202,7 @@ LL | fn result_nonzero_u128_e(x: Result<(), num::NonZero<u128>>);
- --> $DIR/lint-ctypes-enum.rs:152:33
+ --> $DIR/lint-ctypes-enum.rs:170:33
LL | fn result_nonzero_i128_e(x: Result<(), num::NonZero<i128>>);
@@ -184,7 +210,7 @@ LL | fn result_nonzero_i128_e(x: Result<(), num::NonZero<i128>>);
error: `extern` block uses type `Result<(), TransparentUnion<NonZero<u8>>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:157:38
+ --> $DIR/lint-ctypes-enum.rs:175:38
LL | fn result_transparent_union_e(x: Result<(), TransparentUnion<num::NonZero<u8>>>);
@@ -193,7 +219,7 @@ LL | fn result_transparent_union_e(x: Result<(), TransparentUnion<num::NonZe
error: `extern` block uses type `Result<(), Rust<NonZero<u8>>>`, which is not FFI-safe
+ --> $DIR/lint-ctypes-enum.rs:177:30
LL | fn result_repr_rust_e(x: Result<(), Rust<num::NonZero<u8>>>);
@@ -202,7 +228,7 @@ LL | fn result_repr_rust_e(x: Result<(), Rust<num::NonZero<u8>>>);
error: `extern` block uses type `Result<U, NonZero<u8>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:163:51
+ --> $DIR/lint-ctypes-enum.rs:181:51
LL | fn result_1zst_exhaustive_single_variant_e(x: Result<U, num::NonZero<u8>>);
@@ -211,7 +237,7 @@ LL | fn result_1zst_exhaustive_single_variant_e(x: Result<U, num::NonZero<u8
error: `extern` block uses type `Result<B, NonZero<u8>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:165:53
+ --> $DIR/lint-ctypes-enum.rs:183:53
LL | fn result_1zst_exhaustive_multiple_variant_e(x: Result<B, num::NonZero<u8>>);
@@ -220,7 +246,7 @@ LL | fn result_1zst_exhaustive_multiple_variant_e(x: Result<B, num::NonZero<
error: `extern` block uses type `Result<NonExhaustive, NonZero<u8>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:167:51
+ --> $DIR/lint-ctypes-enum.rs:185:51
LL | fn result_1zst_non_exhaustive_no_variant_e(x: Result<NonExhaustive, num::NonZero<u8>>);
@@ -229,7 +255,7 @@ LL | fn result_1zst_non_exhaustive_no_variant_e(x: Result<NonExhaustive, num
error: `extern` block uses type `Result<Field, NonZero<u8>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:170:49
+ --> $DIR/lint-ctypes-enum.rs:188:49
LL | fn result_1zst_exhaustive_single_field_e(x: Result<Field, num::NonZero<u8>>);
@@ -238,7 +264,7 @@ LL | fn result_1zst_exhaustive_single_field_e(x: Result<Field, num::NonZero<
error: `extern` block uses type `Result<(), Result<(), NonZero<u8>>>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:172:30
+ --> $DIR/lint-ctypes-enum.rs:190:30
LL | fn result_cascading_e(x: Result<(), Result<(), num::NonZero<u8>>>);
@@ -247,7 +273,7 @@ LL | fn result_cascading_e(x: Result<(), Result<(), num::NonZero<u8>>>);
error: `extern` block uses type `Result<(), ()>`, which is not FFI-safe
- --> $DIR/lint-ctypes-enum.rs:174:27
+ --> $DIR/lint-ctypes-enum.rs:192:27
LL | fn result_unit_t_e(x: Result<(), ()>);
| ^^^^^^^^^^^^^^ not FFI-safe
@@ -255,5 +281,5 @@ LL | fn result_unit_t_e(x: Result<(), ()>);
-error: aborting due to 27 previous errors
+error: aborting due to 29 previous errors | [
"+use rustc_abi::{",
"+ ty,",
"+ };",
"+ fn repr_i128(x: I128); //~ ERROR `extern` block uses type `I128`",
"+ --> $DIR/lint-ctypes-enum.rs:11:1",
"- --> $DIR/lint-ctypes-enum.rs:94:36",
"+ --> $DIR/lint-ctypes-enum.rs:132:33",
"- --> $DIR/lint-ctypes-enum.rs:127:53",
"- --> $DIR/lint-ctypes-enum.rs:145:33",
"- --> $DIR/lint-ctypes-enum.rs:159:30"
] | [
9,
21,
24,
69,
89,
173,
210,
245,
281,
308
] | {
"additions": 86,
"author": "beetrees",
"deletions": 32,
"html_url": "https://github.com/rust-lang/rust/pull/138282",
"issue_id": 138282,
"merged_at": "2025-04-24T22:57:57Z",
"omission_probability": 0.1,
"pr_number": 138282,
"repo": "rust-lang/rust",
"title": "Add `#[repr(u128)]`/`#[repr(i128)]` enums to `improper_ctypes_definitions`",
"total_changes": 118
} |
123 | diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs
index 4ca317e3a1e53..40c63f2b250f5 100644
--- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs
+++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs
@@ -158,6 +158,31 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
self.copy_op(&val, dest)?;
}
+ sym::fadd_algebraic
+ | sym::fsub_algebraic
+ | sym::fmul_algebraic
+ | sym::fdiv_algebraic
+ | sym::frem_algebraic => {
+ let a = self.read_immediate(&args[0])?;
+ let b = self.read_immediate(&args[1])?;
+
+ let op = match intrinsic_name {
+ sym::fadd_algebraic => BinOp::Add,
+ sym::fsub_algebraic => BinOp::Sub,
+ sym::fmul_algebraic => BinOp::Mul,
+ sym::fdiv_algebraic => BinOp::Div,
+ sym::frem_algebraic => BinOp::Rem,
+
+ _ => bug!(),
+ };
+
+ let res = self.binary_op(op, &a, &b)?;
+ // `binary_op` already called `generate_nan` if needed.
+
+ // FIXME: Miri should add some non-determinism to the result here to catch any dependences on exact computations. This has previously been done, but the behaviour was removed as part of constification.
+ self.write_immediate(*res, dest)?;
+ }
+
sym::ctpop
| sym::cttz
| sym::cttz_nonzero
diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs
index a01efb2adebe3..a700b98d06866 100644
--- a/library/core/src/intrinsics/mod.rs
+++ b/library/core/src/intrinsics/mod.rs
@@ -2429,35 +2429,35 @@ pub unsafe fn float_to_int_unchecked<Float: Copy, Int: Copy>(value: Float) -> In
/// Stabilized as [`f16::algebraic_add`], [`f32::algebraic_add`], [`f64::algebraic_add`] and [`f128::algebraic_add`].
#[rustc_nounwind]
#[rustc_intrinsic]
-pub fn fadd_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn fadd_algebraic<T: Copy>(a: T, b: T) -> T;
/// Float subtraction that allows optimizations based on algebraic rules.
///
/// Stabilized as [`f16::algebraic_sub`], [`f32::algebraic_sub`], [`f64::algebraic_sub`] and [`f128::algebraic_sub`].
#[rustc_nounwind]
#[rustc_intrinsic]
-pub fn fsub_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn fsub_algebraic<T: Copy>(a: T, b: T) -> T;
/// Float multiplication that allows optimizations based on algebraic rules.
///
/// Stabilized as [`f16::algebraic_mul`], [`f32::algebraic_mul`], [`f64::algebraic_mul`] and [`f128::algebraic_mul`].
#[rustc_nounwind]
#[rustc_intrinsic]
-pub fn fmul_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn fmul_algebraic<T: Copy>(a: T, b: T) -> T;
/// Float division that allows optimizations based on algebraic rules.
///
/// Stabilized as [`f16::algebraic_div`], [`f32::algebraic_div`], [`f64::algebraic_div`] and [`f128::algebraic_div`].
#[rustc_nounwind]
#[rustc_intrinsic]
-pub fn fdiv_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn fdiv_algebraic<T: Copy>(a: T, b: T) -> T;
/// Float remainder that allows optimizations based on algebraic rules.
///
/// Stabilized as [`f16::algebraic_rem`], [`f32::algebraic_rem`], [`f64::algebraic_rem`] and [`f128::algebraic_rem`].
#[rustc_nounwind]
#[rustc_intrinsic]
-pub fn frem_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn frem_algebraic<T: Copy>(a: T, b: T) -> T;
/// Returns the number of bits set in an integer type `T`
///
diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs
index d3d1eebc22753..3361409997e91 100644
--- a/library/core/src/num/f128.rs
+++ b/library/core/src/num/f128.rs
@@ -1370,8 +1370,9 @@ impl f128 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_add(self, rhs: f128) -> f128 {
+ pub const fn algebraic_add(self, rhs: f128) -> f128 {
intrinsics::fadd_algebraic(self, rhs)
}
@@ -1380,8 +1381,9 @@ impl f128 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_sub(self, rhs: f128) -> f128 {
+ pub const fn algebraic_sub(self, rhs: f128) -> f128 {
intrinsics::fsub_algebraic(self, rhs)
}
@@ -1390,8 +1392,9 @@ impl f128 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_mul(self, rhs: f128) -> f128 {
+ pub const fn algebraic_mul(self, rhs: f128) -> f128 {
intrinsics::fmul_algebraic(self, rhs)
}
@@ -1400,8 +1403,9 @@ impl f128 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_div(self, rhs: f128) -> f128 {
+ pub const fn algebraic_div(self, rhs: f128) -> f128 {
intrinsics::fdiv_algebraic(self, rhs)
}
@@ -1410,8 +1414,9 @@ impl f128 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_rem(self, rhs: f128) -> f128 {
+ pub const fn algebraic_rem(self, rhs: f128) -> f128 {
intrinsics::frem_algebraic(self, rhs)
}
}
diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs
index dceb30177e668..477fb0cf27ebb 100644
--- a/library/core/src/num/f16.rs
+++ b/library/core/src/num/f16.rs
@@ -1346,8 +1346,9 @@ impl f16 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_add(self, rhs: f16) -> f16 {
+ pub const fn algebraic_add(self, rhs: f16) -> f16 {
intrinsics::fadd_algebraic(self, rhs)
}
@@ -1356,8 +1357,9 @@ impl f16 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_sub(self, rhs: f16) -> f16 {
+ pub const fn algebraic_sub(self, rhs: f16) -> f16 {
intrinsics::fsub_algebraic(self, rhs)
}
@@ -1366,8 +1368,9 @@ impl f16 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_mul(self, rhs: f16) -> f16 {
+ pub const fn algebraic_mul(self, rhs: f16) -> f16 {
intrinsics::fmul_algebraic(self, rhs)
}
@@ -1376,8 +1379,9 @@ impl f16 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_div(self, rhs: f16) -> f16 {
+ pub const fn algebraic_div(self, rhs: f16) -> f16 {
intrinsics::fdiv_algebraic(self, rhs)
}
@@ -1386,8 +1390,9 @@ impl f16 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_rem(self, rhs: f16) -> f16 {
+ pub const fn algebraic_rem(self, rhs: f16) -> f16 {
intrinsics::frem_algebraic(self, rhs)
}
}
diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs
index c97dbfb63ae17..7bada4d62c038 100644
--- a/library/core/src/num/f32.rs
+++ b/library/core/src/num/f32.rs
@@ -1512,8 +1512,9 @@ impl f32 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_add(self, rhs: f32) -> f32 {
+ pub const fn algebraic_add(self, rhs: f32) -> f32 {
intrinsics::fadd_algebraic(self, rhs)
}
@@ -1522,8 +1523,9 @@ impl f32 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_sub(self, rhs: f32) -> f32 {
+ pub const fn algebraic_sub(self, rhs: f32) -> f32 {
intrinsics::fsub_algebraic(self, rhs)
}
@@ -1532,8 +1534,9 @@ impl f32 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_mul(self, rhs: f32) -> f32 {
+ pub const fn algebraic_mul(self, rhs: f32) -> f32 {
intrinsics::fmul_algebraic(self, rhs)
}
@@ -1542,8 +1545,9 @@ impl f32 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_div(self, rhs: f32) -> f32 {
+ pub const fn algebraic_div(self, rhs: f32) -> f32 {
intrinsics::fdiv_algebraic(self, rhs)
}
@@ -1552,8 +1556,9 @@ impl f32 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_rem(self, rhs: f32) -> f32 {
+ pub const fn algebraic_rem(self, rhs: f32) -> f32 {
intrinsics::frem_algebraic(self, rhs)
}
}
diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs
index 91affdb3794b0..3b06478f7e625 100644
--- a/library/core/src/num/f64.rs
+++ b/library/core/src/num/f64.rs
@@ -1511,8 +1511,9 @@ impl f64 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_add(self, rhs: f64) -> f64 {
+ pub const fn algebraic_add(self, rhs: f64) -> f64 {
intrinsics::fadd_algebraic(self, rhs)
}
@@ -1521,8 +1522,9 @@ impl f64 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_sub(self, rhs: f64) -> f64 {
+ pub const fn algebraic_sub(self, rhs: f64) -> f64 {
intrinsics::fsub_algebraic(self, rhs)
}
@@ -1531,8 +1533,9 @@ impl f64 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_mul(self, rhs: f64) -> f64 {
+ pub const fn algebraic_mul(self, rhs: f64) -> f64 {
intrinsics::fmul_algebraic(self, rhs)
}
@@ -1541,8 +1544,9 @@ impl f64 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_div(self, rhs: f64) -> f64 {
+ pub const fn algebraic_div(self, rhs: f64) -> f64 {
intrinsics::fdiv_algebraic(self, rhs)
}
@@ -1551,8 +1555,9 @@ impl f64 {
/// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
#[must_use = "method returns a new number and does not mutate the original value"]
#[unstable(feature = "float_algebraic", issue = "136469")]
+ #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
#[inline]
- pub fn algebraic_rem(self, rhs: f64) -> f64 {
+ pub const fn algebraic_rem(self, rhs: f64) -> f64 {
intrinsics::frem_algebraic(self, rhs)
}
}
diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs
index a3525dcc77ae6..7d60a7e5c4895 100644
--- a/src/tools/miri/src/intrinsics/mod.rs
+++ b/src/tools/miri/src/intrinsics/mod.rs
@@ -391,32 +391,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
this.write_scalar(res, dest)?;
}
- #[rustfmt::skip]
- | "fadd_algebraic"
- | "fsub_algebraic"
- | "fmul_algebraic"
- | "fdiv_algebraic"
- | "frem_algebraic"
- => {
- let [a, b] = check_intrinsic_arg_count(args)?;
- let a = this.read_immediate(a)?;
- let b = this.read_immediate(b)?;
- let op = match intrinsic_name {
- "fadd_algebraic" => mir::BinOp::Add,
- "fsub_algebraic" => mir::BinOp::Sub,
- "fmul_algebraic" => mir::BinOp::Mul,
- "fdiv_algebraic" => mir::BinOp::Div,
- "frem_algebraic" => mir::BinOp::Rem,
- _ => bug!(),
- };
- let res = this.binary_op(op, &a, &b)?;
- // `binary_op` already called `generate_nan` if needed.
- // Apply a relative error of 4ULP to simulate non-deterministic precision loss
- // due to optimizations.
- let res = apply_random_float_error_to_imm(this, res, 2 /* log2(4) */)?;
- this.write_immediate(*res, dest)?;
- }
-
#[rustfmt::skip]
| "fadd_fast"
| "fsub_fast"
| diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs
index 4ca317e3a1e53..40c63f2b250f5 100644
--- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs
+++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs
@@ -158,6 +158,31 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
self.copy_op(&val, dest)?;
+ sym::fadd_algebraic
+ | sym::fsub_algebraic
+ | sym::fmul_algebraic
+ | sym::fdiv_algebraic
+ let a = self.read_immediate(&args[0])?;
+ let b = self.read_immediate(&args[1])?;
+ let op = match intrinsic_name {
+ sym::fadd_algebraic => BinOp::Add,
+ sym::fsub_algebraic => BinOp::Sub,
+ sym::fmul_algebraic => BinOp::Mul,
+ sym::fdiv_algebraic => BinOp::Div,
+ sym::frem_algebraic => BinOp::Rem,
+ _ => bug!(),
+ };
+ let res = self.binary_op(op, &a, &b)?;
+ // `binary_op` already called `generate_nan` if needed.
+ // FIXME: Miri should add some non-determinism to the result here to catch any dependences on exact computations. This has previously been done, but the behaviour was removed as part of constification.
+ self.write_immediate(*res, dest)?;
+ }
sym::ctpop
| sym::cttz
| sym::cttz_nonzero
diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs
index a01efb2adebe3..a700b98d06866 100644
--- a/library/core/src/intrinsics/mod.rs
+++ b/library/core/src/intrinsics/mod.rs
@@ -2429,35 +2429,35 @@ pub unsafe fn float_to_int_unchecked<Float: Copy, Int: Copy>(value: Float) -> In
/// Stabilized as [`f16::algebraic_add`], [`f32::algebraic_add`], [`f64::algebraic_add`] and [`f128::algebraic_add`].
-pub fn fadd_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn fadd_algebraic<T: Copy>(a: T, b: T) -> T;
/// Float subtraction that allows optimizations based on algebraic rules.
/// Stabilized as [`f16::algebraic_sub`], [`f32::algebraic_sub`], [`f64::algebraic_sub`] and [`f128::algebraic_sub`].
-pub fn fsub_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn fsub_algebraic<T: Copy>(a: T, b: T) -> T;
/// Float multiplication that allows optimizations based on algebraic rules.
/// Stabilized as [`f16::algebraic_mul`], [`f32::algebraic_mul`], [`f64::algebraic_mul`] and [`f128::algebraic_mul`].
-pub fn fmul_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn fmul_algebraic<T: Copy>(a: T, b: T) -> T;
/// Float division that allows optimizations based on algebraic rules.
/// Stabilized as [`f16::algebraic_div`], [`f32::algebraic_div`], [`f64::algebraic_div`] and [`f128::algebraic_div`].
-pub fn fdiv_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn fdiv_algebraic<T: Copy>(a: T, b: T) -> T;
/// Float remainder that allows optimizations based on algebraic rules.
/// Stabilized as [`f16::algebraic_rem`], [`f32::algebraic_rem`], [`f64::algebraic_rem`] and [`f128::algebraic_rem`].
-pub fn frem_algebraic<T: Copy>(a: T, b: T) -> T;
+pub const fn frem_algebraic<T: Copy>(a: T, b: T) -> T;
/// Returns the number of bits set in an integer type `T`
diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs
index d3d1eebc22753..3361409997e91 100644
--- a/library/core/src/num/f128.rs
+++ b/library/core/src/num/f128.rs
@@ -1370,8 +1370,9 @@ impl f128 {
- pub fn algebraic_add(self, rhs: f128) -> f128 {
+ pub const fn algebraic_add(self, rhs: f128) -> f128 {
@@ -1380,8 +1381,9 @@ impl f128 {
- pub fn algebraic_sub(self, rhs: f128) -> f128 {
@@ -1390,8 +1392,9 @@ impl f128 {
- pub fn algebraic_mul(self, rhs: f128) -> f128 {
@@ -1400,8 +1403,9 @@ impl f128 {
- pub fn algebraic_div(self, rhs: f128) -> f128 {
+ pub const fn algebraic_div(self, rhs: f128) -> f128 {
@@ -1410,8 +1414,9 @@ impl f128 {
- pub fn algebraic_rem(self, rhs: f128) -> f128 {
+ pub const fn algebraic_rem(self, rhs: f128) -> f128 {
diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs
index dceb30177e668..477fb0cf27ebb 100644
--- a/library/core/src/num/f16.rs
+++ b/library/core/src/num/f16.rs
@@ -1346,8 +1346,9 @@ impl f16 {
- pub fn algebraic_add(self, rhs: f16) -> f16 {
@@ -1356,8 +1357,9 @@ impl f16 {
- pub fn algebraic_sub(self, rhs: f16) -> f16 {
+ pub const fn algebraic_sub(self, rhs: f16) -> f16 {
@@ -1366,8 +1368,9 @@ impl f16 {
- pub fn algebraic_mul(self, rhs: f16) -> f16 {
+ pub const fn algebraic_mul(self, rhs: f16) -> f16 {
@@ -1376,8 +1379,9 @@ impl f16 {
- pub fn algebraic_div(self, rhs: f16) -> f16 {
@@ -1386,8 +1390,9 @@ impl f16 {
- pub fn algebraic_rem(self, rhs: f16) -> f16 {
+ pub const fn algebraic_rem(self, rhs: f16) -> f16 {
diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs
index c97dbfb63ae17..7bada4d62c038 100644
--- a/library/core/src/num/f32.rs
+++ b/library/core/src/num/f32.rs
@@ -1512,8 +1512,9 @@ impl f32 {
+ pub const fn algebraic_add(self, rhs: f32) -> f32 {
@@ -1522,8 +1523,9 @@ impl f32 {
+ pub const fn algebraic_sub(self, rhs: f32) -> f32 {
@@ -1532,8 +1534,9 @@ impl f32 {
- pub fn algebraic_mul(self, rhs: f32) -> f32 {
+ pub const fn algebraic_mul(self, rhs: f32) -> f32 {
@@ -1542,8 +1545,9 @@ impl f32 {
- pub fn algebraic_div(self, rhs: f32) -> f32 {
+ pub const fn algebraic_div(self, rhs: f32) -> f32 {
@@ -1552,8 +1556,9 @@ impl f32 {
- pub fn algebraic_rem(self, rhs: f32) -> f32 {
+ pub const fn algebraic_rem(self, rhs: f32) -> f32 {
diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs
index 91affdb3794b0..3b06478f7e625 100644
--- a/library/core/src/num/f64.rs
+++ b/library/core/src/num/f64.rs
@@ -1511,8 +1511,9 @@ impl f64 {
- pub fn algebraic_add(self, rhs: f64) -> f64 {
+ pub const fn algebraic_add(self, rhs: f64) -> f64 {
@@ -1521,8 +1522,9 @@ impl f64 {
- pub fn algebraic_sub(self, rhs: f64) -> f64 {
+ pub const fn algebraic_sub(self, rhs: f64) -> f64 {
@@ -1531,8 +1533,9 @@ impl f64 {
- pub fn algebraic_mul(self, rhs: f64) -> f64 {
+ pub const fn algebraic_mul(self, rhs: f64) -> f64 {
@@ -1541,8 +1544,9 @@ impl f64 {
- pub fn algebraic_div(self, rhs: f64) -> f64 {
+ pub const fn algebraic_div(self, rhs: f64) -> f64 {
@@ -1551,8 +1555,9 @@ impl f64 {
- pub fn algebraic_rem(self, rhs: f64) -> f64 {
+ pub const fn algebraic_rem(self, rhs: f64) -> f64 {
diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs
index a3525dcc77ae6..7d60a7e5c4895 100644
--- a/src/tools/miri/src/intrinsics/mod.rs
+++ b/src/tools/miri/src/intrinsics/mod.rs
@@ -391,32 +391,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
this.write_scalar(res, dest)?;
- #[rustfmt::skip]
- | "fmul_algebraic"
- | "fdiv_algebraic"
- | "frem_algebraic"
- => {
- let [a, b] = check_intrinsic_arg_count(args)?;
- let a = this.read_immediate(a)?;
- let b = this.read_immediate(b)?;
- let op = match intrinsic_name {
- "fadd_algebraic" => mir::BinOp::Add,
- "fmul_algebraic" => mir::BinOp::Mul,
- "frem_algebraic" => mir::BinOp::Rem,
- _ => bug!(),
- };
- let res = this.binary_op(op, &a, &b)?;
- // `binary_op` already called `generate_nan` if needed.
- // Apply a relative error of 4ULP to simulate non-deterministic precision loss
- // due to optimizations.
- let res = apply_random_float_error_to_imm(this, res, 2 /* log2(4) */)?;
- this.write_immediate(*res, dest)?;
- }
-
#[rustfmt::skip]
| "fadd_fast"
| "fsub_fast" | [
"+ | sym::frem_algebraic => {",
"+ pub const fn algebraic_sub(self, rhs: f128) -> f128 {",
"+ pub const fn algebraic_mul(self, rhs: f128) -> f128 {",
"+ pub const fn algebraic_add(self, rhs: f16) -> f16 {",
"+ pub const fn algebraic_div(self, rhs: f16) -> f16 {",
"- pub fn algebraic_add(self, rhs: f32) -> f32 {",
"- pub fn algebraic_sub(self, rhs: f32) -> f32 {",
"- | \"fadd_algebraic\"",
"- | \"fsub_algebraic\"",
"- \"fsub_algebraic\" => mir::BinOp::Sub,",
"- \"fdiv_algebraic\" => mir::BinOp::Div,"
] | [
12,
103,
114,
151,
184,
209,
220,
326,
327,
337,
339
] | {
"additions": 70,
"author": "bjoernager",
"deletions": 51,
"html_url": "https://github.com/rust-lang/rust/pull/140172",
"issue_id": 140172,
"merged_at": "2025-04-24T22:57:56Z",
"omission_probability": 0.1,
"pr_number": 140172,
"repo": "rust-lang/rust",
"title": "Make algebraic functions into `const fn` items.",
"total_changes": 121
} |
124 | diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs
index d3d1eebc22753..c7c28f2af2a23 100644
--- a/library/core/src/num/f128.rs
+++ b/library/core/src/num/f128.rs
@@ -194,16 +194,22 @@ impl f128 {
#[unstable(feature = "f128", issue = "116909")]
pub const MAX: f128 = 1.18973149535723176508575932662800702e+4932_f128;
- /// One greater than the minimum possible normal power of 2 exponent.
+ /// One greater than the minimum possible *normal* power of 2 exponent
+ /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
///
- /// If <i>x</i> = `MIN_EXP`, then normal numbers
- /// ≥ 0.5 × 2<sup><i>x</i></sup>.
+ /// This corresponds to the exact minimum possible *normal* power of 2 exponent
+ /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
+ /// In other words, all normal numbers representable by this type are
+ /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
#[unstable(feature = "f128", issue = "116909")]
pub const MIN_EXP: i32 = -16_381;
- /// Maximum possible power of 2 exponent.
+ /// One greater than the maximum possible power of 2 exponent
+ /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
///
- /// If <i>x</i> = `MAX_EXP`, then normal numbers
- /// < 1 × 2<sup><i>x</i></sup>.
+ /// This corresponds to the exact maximum possible power of 2 exponent
+ /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
+ /// In other words, all numbers representable by this type are
+ /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
#[unstable(feature = "f128", issue = "116909")]
pub const MAX_EXP: i32 = 16_384;
diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs
index dceb30177e668..8615b8d82e64d 100644
--- a/library/core/src/num/f16.rs
+++ b/library/core/src/num/f16.rs
@@ -189,16 +189,22 @@ impl f16 {
#[unstable(feature = "f16", issue = "116909")]
pub const MAX: f16 = 6.5504e+4_f16;
- /// One greater than the minimum possible normal power of 2 exponent.
+ /// One greater than the minimum possible *normal* power of 2 exponent
+ /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
///
- /// If <i>x</i> = `MIN_EXP`, then normal numbers
- /// ≥ 0.5 × 2<sup><i>x</i></sup>.
+ /// This corresponds to the exact minimum possible *normal* power of 2 exponent
+ /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
+ /// In other words, all normal numbers representable by this type are
+ /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
#[unstable(feature = "f16", issue = "116909")]
pub const MIN_EXP: i32 = -13;
- /// Maximum possible power of 2 exponent.
+ /// One greater than the maximum possible power of 2 exponent
+ /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
///
- /// If <i>x</i> = `MAX_EXP`, then normal numbers
- /// < 1 × 2<sup><i>x</i></sup>.
+ /// This corresponds to the exact maximum possible power of 2 exponent
+ /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
+ /// In other words, all numbers representable by this type are
+ /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
#[unstable(feature = "f16", issue = "116909")]
pub const MAX_EXP: i32 = 16;
diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs
index c97dbfb63ae17..60e37c10fd2db 100644
--- a/library/core/src/num/f32.rs
+++ b/library/core/src/num/f32.rs
@@ -440,16 +440,22 @@ impl f32 {
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: f32 = 3.40282347e+38_f32;
- /// One greater than the minimum possible normal power of 2 exponent.
+ /// One greater than the minimum possible *normal* power of 2 exponent
+ /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
///
- /// If <i>x</i> = `MIN_EXP`, then normal numbers
- /// ≥ 0.5 × 2<sup><i>x</i></sup>.
+ /// This corresponds to the exact minimum possible *normal* power of 2 exponent
+ /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
+ /// In other words, all normal numbers representable by this type are
+ /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN_EXP: i32 = -125;
- /// Maximum possible power of 2 exponent.
+ /// One greater than the maximum possible power of 2 exponent
+ /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
///
- /// If <i>x</i> = `MAX_EXP`, then normal numbers
- /// < 1 × 2<sup><i>x</i></sup>.
+ /// This corresponds to the exact maximum possible power of 2 exponent
+ /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
+ /// In other words, all numbers representable by this type are
+ /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX_EXP: i32 = 128;
diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs
index 91affdb3794b0..48c7263447a79 100644
--- a/library/core/src/num/f64.rs
+++ b/library/core/src/num/f64.rs
@@ -439,16 +439,22 @@ impl f64 {
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: f64 = 1.7976931348623157e+308_f64;
- /// One greater than the minimum possible normal power of 2 exponent.
+ /// One greater than the minimum possible *normal* power of 2 exponent
+ /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
///
- /// If <i>x</i> = `MIN_EXP`, then normal numbers
- /// ≥ 0.5 × 2<sup><i>x</i></sup>.
+ /// This corresponds to the exact minimum possible *normal* power of 2 exponent
+ /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
+ /// In other words, all normal numbers representable by this type are
+ /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN_EXP: i32 = -1021;
- /// Maximum possible power of 2 exponent.
+ /// One greater than the maximum possible power of 2 exponent
+ /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
///
- /// If <i>x</i> = `MAX_EXP`, then normal numbers
- /// < 1 × 2<sup><i>x</i></sup>.
+ /// This corresponds to the exact maximum possible power of 2 exponent
+ /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
+ /// In other words, all numbers representable by this type are
+ /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX_EXP: i32 = 1024;
| diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs
index d3d1eebc22753..c7c28f2af2a23 100644
--- a/library/core/src/num/f128.rs
+++ b/library/core/src/num/f128.rs
@@ -194,16 +194,22 @@ impl f128 {
pub const MAX: f128 = 1.18973149535723176508575932662800702e+4932_f128;
pub const MIN_EXP: i32 = -16_381;
pub const MAX_EXP: i32 = 16_384;
diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs
index dceb30177e668..8615b8d82e64d 100644
--- a/library/core/src/num/f16.rs
+++ b/library/core/src/num/f16.rs
@@ -189,16 +189,22 @@ impl f16 {
pub const MAX: f16 = 6.5504e+4_f16;
pub const MIN_EXP: i32 = -13;
pub const MAX_EXP: i32 = 16;
diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs
index c97dbfb63ae17..60e37c10fd2db 100644
--- a/library/core/src/num/f32.rs
+++ b/library/core/src/num/f32.rs
@@ -440,16 +440,22 @@ impl f32 {
pub const MAX: f32 = 3.40282347e+38_f32;
pub const MIN_EXP: i32 = -125;
pub const MAX_EXP: i32 = 128;
diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs
index 91affdb3794b0..48c7263447a79 100644
--- a/library/core/src/num/f64.rs
+++ b/library/core/src/num/f64.rs
@@ -439,16 +439,22 @@ impl f64 {
pub const MAX: f64 = 1.7976931348623157e+308_f64;
pub const MIN_EXP: i32 = -1021;
pub const MAX_EXP: i32 = 1024; | [] | [] | {
"additions": 48,
"author": "RalfJung",
"deletions": 24,
"html_url": "https://github.com/rust-lang/rust/pull/140150",
"issue_id": 140150,
"merged_at": "2025-04-24T22:57:56Z",
"omission_probability": 0.1,
"pr_number": 140150,
"repo": "rust-lang/rust",
"title": "fix MAX_EXP and MIN_EXP docs",
"total_changes": 72
} |
125 | diff --git a/library/std/src/sys/env_consts.rs b/library/std/src/sys/env_consts.rs
index 018d7954db26a..9683fd47cf96b 100644
--- a/library/std/src/sys/env_consts.rs
+++ b/library/std/src/sys/env_consts.rs
@@ -389,6 +389,17 @@ pub mod os {
pub const EXE_EXTENSION: &str = "exe";
}
+#[cfg(target_os = "zkvm")]
+pub mod os {
+ pub const FAMILY: &str = "";
+ pub const OS: &str = "";
+ pub const DLL_PREFIX: &str = "";
+ pub const DLL_SUFFIX: &str = ".elf";
+ pub const DLL_EXTENSION: &str = "elf";
+ pub const EXE_SUFFIX: &str = ".elf";
+ pub const EXE_EXTENSION: &str = "elf";
+}
+
// The fallback when none of the other gates match.
#[else]
pub mod os {
diff --git a/library/std/src/sys/pal/zkvm/env.rs b/library/std/src/sys/pal/zkvm/env.rs
deleted file mode 100644
index b85153642b1c9..0000000000000
--- a/library/std/src/sys/pal/zkvm/env.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-pub mod os {
- pub const FAMILY: &str = "";
- pub const OS: &str = "";
- pub const DLL_PREFIX: &str = "";
- pub const DLL_SUFFIX: &str = ".elf";
- pub const DLL_EXTENSION: &str = "elf";
- pub const EXE_SUFFIX: &str = ".elf";
- pub const EXE_EXTENSION: &str = "elf";
-}
| diff --git a/library/std/src/sys/env_consts.rs b/library/std/src/sys/env_consts.rs
index 018d7954db26a..9683fd47cf96b 100644
--- a/library/std/src/sys/env_consts.rs
+++ b/library/std/src/sys/env_consts.rs
@@ -389,6 +389,17 @@ pub mod os {
pub const EXE_EXTENSION: &str = "exe";
}
+#[cfg(target_os = "zkvm")]
+pub mod os {
+ pub const FAMILY: &str = "";
+ pub const OS: &str = "";
+ pub const DLL_PREFIX: &str = "";
+ pub const DLL_SUFFIX: &str = ".elf";
+ pub const DLL_EXTENSION: &str = "elf";
+ pub const EXE_SUFFIX: &str = ".elf";
+ pub const EXE_EXTENSION: &str = "elf";
+}
+
// The fallback when none of the other gates match.
#[else]
pub mod os {
diff --git a/library/std/src/sys/pal/zkvm/env.rs b/library/std/src/sys/pal/zkvm/env.rs
deleted file mode 100644
index b85153642b1c9..0000000000000
--- a/library/std/src/sys/pal/zkvm/env.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-pub mod os {
- pub const FAMILY: &str = "";
- pub const OS: &str = "";
- pub const DLL_PREFIX: &str = "";
- pub const DLL_SUFFIX: &str = ".elf";
- pub const DLL_EXTENSION: &str = "elf";
- pub const EXE_SUFFIX: &str = ".elf";
- pub const EXE_EXTENSION: &str = "elf";
-} | [] | [] | {
"additions": 11,
"author": "thaliaarchi",
"deletions": 9,
"html_url": "https://github.com/rust-lang/rust/pull/140141",
"issue_id": 140141,
"merged_at": "2025-04-24T22:57:56Z",
"omission_probability": 0.1,
"pr_number": 140141,
"repo": "rust-lang/rust",
"title": "Move zkVM constants into `sys::env_consts`",
"total_changes": 20
} |
126 | diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs
index aeace6a40c72e..0450843b9285d 100644
--- a/compiler/rustc_target/src/target_features.rs
+++ b/compiler/rustc_target/src/target_features.rs
@@ -516,7 +516,7 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("zawrs", Unstable(sym::riscv_target_feature), &[]),
("zba", Stable, &[]),
("zbb", Stable, &[]),
- ("zbc", Stable, &[]),
+ ("zbc", Stable, &["zbkc"]), // Zbc ⊃ Zbkc
("zbkb", Stable, &[]),
("zbkc", Stable, &[]),
("zbkx", Stable, &[]),
@@ -545,20 +545,20 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("zknd", Stable, &[]),
("zkne", Stable, &[]),
("zknh", Stable, &[]),
- ("zkr", Stable, &["zicsr"]),
+ ("zkr", Stable, &[]),
("zks", Stable, &["zbkb", "zbkc", "zbkx", "zksed", "zksh"]),
("zksed", Stable, &[]),
("zksh", Stable, &[]),
("zkt", Stable, &[]),
("ztso", Unstable(sym::riscv_target_feature), &[]),
- ("zvbb", Unstable(sym::riscv_target_feature), &["zvkb"]),
+ ("zvbb", Unstable(sym::riscv_target_feature), &["zvkb"]), // Zvbb ⊃ Zvkb
("zvbc", Unstable(sym::riscv_target_feature), &["zve64x"]),
("zve32f", Unstable(sym::riscv_target_feature), &["zve32x", "f"]),
("zve32x", Unstable(sym::riscv_target_feature), &["zvl32b", "zicsr"]),
("zve64d", Unstable(sym::riscv_target_feature), &["zve64f", "d"]),
("zve64f", Unstable(sym::riscv_target_feature), &["zve32f", "zve64x"]),
("zve64x", Unstable(sym::riscv_target_feature), &["zve32x", "zvl64b"]),
- ("zvfh", Unstable(sym::riscv_target_feature), &["zvfhmin", "zfhmin"]),
+ ("zvfh", Unstable(sym::riscv_target_feature), &["zvfhmin", "zve32f", "zfhmin"]), // Zvfh ⊃ Zvfhmin
("zvfhmin", Unstable(sym::riscv_target_feature), &["zve32f"]),
("zvkb", Unstable(sym::riscv_target_feature), &["zve32x"]),
("zvkg", Unstable(sym::riscv_target_feature), &["zve32x"]),
@@ -567,7 +567,7 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("zvkned", Unstable(sym::riscv_target_feature), &["zve32x"]),
("zvkng", Unstable(sym::riscv_target_feature), &["zvkn", "zvkg"]),
("zvknha", Unstable(sym::riscv_target_feature), &["zve32x"]),
- ("zvknhb", Unstable(sym::riscv_target_feature), &["zve64x"]),
+ ("zvknhb", Unstable(sym::riscv_target_feature), &["zvknha", "zve64x"]), // Zvknhb ⊃ Zvknha
("zvks", Unstable(sym::riscv_target_feature), &["zvksed", "zvksh", "zvkb", "zvkt"]),
("zvksc", Unstable(sym::riscv_target_feature), &["zvks", "zvbc"]),
("zvksed", Unstable(sym::riscv_target_feature), &["zve32x"]),
| diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs
index aeace6a40c72e..0450843b9285d 100644
--- a/compiler/rustc_target/src/target_features.rs
+++ b/compiler/rustc_target/src/target_features.rs
@@ -516,7 +516,7 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("zawrs", Unstable(sym::riscv_target_feature), &[]),
("zba", Stable, &[]),
("zbb", Stable, &[]),
("zbkb", Stable, &[]),
("zbkc", Stable, &[]),
("zbkx", Stable, &[]),
@@ -545,20 +545,20 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("zknd", Stable, &[]),
("zkne", Stable, &[]),
("zknh", Stable, &[]),
+ ("zkr", Stable, &[]),
("zks", Stable, &["zbkb", "zbkc", "zbkx", "zksed", "zksh"]),
("zksed", Stable, &[]),
("zksh", Stable, &[]),
("zkt", Stable, &[]),
("ztso", Unstable(sym::riscv_target_feature), &[]),
- ("zvbb", Unstable(sym::riscv_target_feature), &["zvkb"]),
+ ("zvbb", Unstable(sym::riscv_target_feature), &["zvkb"]), // Zvbb ⊃ Zvkb
("zvbc", Unstable(sym::riscv_target_feature), &["zve64x"]),
("zve32f", Unstable(sym::riscv_target_feature), &["zve32x", "f"]),
("zve32x", Unstable(sym::riscv_target_feature), &["zvl32b", "zicsr"]),
("zve64d", Unstable(sym::riscv_target_feature), &["zve64f", "d"]),
("zve64f", Unstable(sym::riscv_target_feature), &["zve32f", "zve64x"]),
("zve64x", Unstable(sym::riscv_target_feature), &["zve32x", "zvl64b"]),
- ("zvfh", Unstable(sym::riscv_target_feature), &["zvfhmin", "zfhmin"]),
+ ("zvfh", Unstable(sym::riscv_target_feature), &["zvfhmin", "zve32f", "zfhmin"]), // Zvfh ⊃ Zvfhmin
("zvfhmin", Unstable(sym::riscv_target_feature), &["zve32f"]),
("zvkb", Unstable(sym::riscv_target_feature), &["zve32x"]),
("zvkg", Unstable(sym::riscv_target_feature), &["zve32x"]),
@@ -567,7 +567,7 @@ static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("zvkned", Unstable(sym::riscv_target_feature), &["zve32x"]),
("zvkng", Unstable(sym::riscv_target_feature), &["zvkn", "zvkg"]),
("zvknha", Unstable(sym::riscv_target_feature), &["zve32x"]),
- ("zvknhb", Unstable(sym::riscv_target_feature), &["zve64x"]),
+ ("zvknhb", Unstable(sym::riscv_target_feature), &["zvknha", "zve64x"]), // Zvknhb ⊃ Zvknha
("zvks", Unstable(sym::riscv_target_feature), &["zvksed", "zvksh", "zvkb", "zvkt"]),
("zvksc", Unstable(sym::riscv_target_feature), &["zvks", "zvbc"]),
("zvksed", Unstable(sym::riscv_target_feature), &["zve32x"]), | [
"- (\"zbc\", Stable, &[]),",
"+ (\"zbc\", Stable, &[\"zbkc\"]), // Zbc ⊃ Zbkc",
"- (\"zkr\", Stable, &[\"zicsr\"]),"
] | [
8,
9,
17
] | {
"additions": 5,
"author": "a4lg",
"deletions": 5,
"html_url": "https://github.com/rust-lang/rust/pull/140139",
"issue_id": 140139,
"merged_at": "2025-04-24T22:57:56Z",
"omission_probability": 0.1,
"pr_number": 140139,
"repo": "rust-lang/rust",
"title": "rustc_target: Adjust RISC-V feature implication",
"total_changes": 10
} |
127 | diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs
index a8b49e9552c30..925898d817371 100644
--- a/compiler/rustc_codegen_llvm/src/back/lto.rs
+++ b/compiler/rustc_codegen_llvm/src/back/lto.rs
@@ -584,12 +584,10 @@ fn thin_lto(
}
}
-fn enable_autodiff_settings(ad: &[config::AutoDiff], module: &mut ModuleCodegen<ModuleLlvm>) {
+fn enable_autodiff_settings(ad: &[config::AutoDiff]) {
for &val in ad {
+ // We intentionally don't use a wildcard, to not forget handling anything new.
match val {
- config::AutoDiff::PrintModBefore => {
- unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
- }
config::AutoDiff::PrintPerf => {
llvm::set_print_perf(true);
}
@@ -603,17 +601,23 @@ fn enable_autodiff_settings(ad: &[config::AutoDiff], module: &mut ModuleCodegen<
llvm::set_inline(true);
}
config::AutoDiff::LooseTypes => {
- llvm::set_loose_types(false);
+ llvm::set_loose_types(true);
}
config::AutoDiff::PrintSteps => {
llvm::set_print(true);
}
- // We handle this below
+ // We handle this in the PassWrapper.cpp
+ config::AutoDiff::PrintPasses => {}
+ // We handle this in the PassWrapper.cpp
+ config::AutoDiff::PrintModBefore => {}
+ // We handle this in the PassWrapper.cpp
config::AutoDiff::PrintModAfter => {}
- // We handle this below
+ // We handle this in the PassWrapper.cpp
config::AutoDiff::PrintModFinal => {}
// This is required and already checked
config::AutoDiff::Enable => {}
+ // We handle this below
+ config::AutoDiff::NoPostopt => {}
}
}
// This helps with handling enums for now.
@@ -647,27 +651,27 @@ pub(crate) fn run_pass_manager(
// We then run the llvm_optimize function a second time, to optimize the code which we generated
// in the enzyme differentiation pass.
let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable);
- let stage =
- if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD };
+ let stage = if thin {
+ write::AutodiffStage::PreAD
+ } else {
+ if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD }
+ };
if enable_ad {
- enable_autodiff_settings(&config.autodiff, module);
+ enable_autodiff_settings(&config.autodiff);
}
unsafe {
write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage)?;
}
- if cfg!(llvm_enzyme) && enable_ad {
- // This is the post-autodiff IR, mainly used for testing and educational purposes.
- if config.autodiff.contains(&config::AutoDiff::PrintModAfter) {
- unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
- }
-
+ if cfg!(llvm_enzyme) && enable_ad && !thin {
let opt_stage = llvm::OptStage::FatLTO;
let stage = write::AutodiffStage::PostAD;
- unsafe {
- write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage)?;
+ if !config.autodiff.contains(&config::AutoDiff::NoPostopt) {
+ unsafe {
+ write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage)?;
+ }
}
// This is the final IR, so people should be able to inspect the optimized autodiff output,
diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs
index 76d431a497561..3cfd739b70c9d 100644
--- a/compiler/rustc_codegen_llvm/src/back/write.rs
+++ b/compiler/rustc_codegen_llvm/src/back/write.rs
@@ -565,6 +565,10 @@ pub(crate) unsafe fn llvm_optimize(
let consider_ad = cfg!(llvm_enzyme) && config.autodiff.contains(&config::AutoDiff::Enable);
let run_enzyme = autodiff_stage == AutodiffStage::DuringAD;
+ let print_before_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModBefore);
+ let print_after_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModAfter);
+ let print_passes = config.autodiff.contains(&config::AutoDiff::PrintPasses);
+ let merge_functions;
let unroll_loops;
let vectorize_slp;
let vectorize_loop;
@@ -572,13 +576,20 @@ pub(crate) unsafe fn llvm_optimize(
// When we build rustc with enzyme/autodiff support, we want to postpone size-increasing
// optimizations until after differentiation. Our pipeline is thus: (opt + enzyme), (full opt).
// We therefore have two calls to llvm_optimize, if autodiff is used.
+ //
+ // We also must disable merge_functions, since autodiff placeholder/dummy bodies tend to be
+ // identical. We run opts before AD, so there is a chance that LLVM will merge our dummies.
+ // In that case, we lack some dummy bodies and can't replace them with the real AD code anymore.
+ // We then would need to abort compilation. This was especially common in test cases.
if consider_ad && autodiff_stage != AutodiffStage::PostAD {
+ merge_functions = false;
unroll_loops = false;
vectorize_slp = false;
vectorize_loop = false;
} else {
unroll_loops =
opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
+ merge_functions = config.merge_functions;
vectorize_slp = config.vectorize_slp;
vectorize_loop = config.vectorize_loop;
}
@@ -656,13 +667,16 @@ pub(crate) unsafe fn llvm_optimize(
thin_lto_buffer,
config.emit_thin_lto,
config.emit_thin_lto_summary,
- config.merge_functions,
+ merge_functions,
unroll_loops,
vectorize_slp,
vectorize_loop,
config.no_builtins,
config.emit_lifetime_markers,
run_enzyme,
+ print_before_enzyme,
+ print_after_enzyme,
+ print_passes,
sanitizer_options.as_ref(),
pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
diff --git a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs
index 5e7ef27143b14..f5023e0ca5a90 100644
--- a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs
+++ b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs
@@ -445,7 +445,7 @@ pub(crate) fn differentiate<'ll>(
return Err(diag_handler.handle().emit_almost_fatal(AutoDiffWithoutEnable));
}
- // Before dumping the module, we want all the TypeTrees to become part of the module.
+ // Here we replace the placeholder code with the actual autodiff code, which calls Enzyme.
for item in diff_items.iter() {
let name = item.source.clone();
let fn_def: Option<&llvm::Value> = cx.get_function(&name);
diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
index 9ff04f729030c..ffb490dcdc22b 100644
--- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
+++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
@@ -2454,6 +2454,9 @@ unsafe extern "C" {
DisableSimplifyLibCalls: bool,
EmitLifetimeMarkers: bool,
RunEnzyme: bool,
+ PrintBeforeEnzyme: bool,
+ PrintAfterEnzyme: bool,
+ PrintPasses: bool,
SanitizerOptions: Option<&SanitizerOptions>,
PGOGenPath: *const c_char,
PGOUsePath: *const c_char,
diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp
index e02c80c50b14a..8bee051dd4c3c 100644
--- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp
+++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp
@@ -14,6 +14,7 @@
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Verifier.h"
+#include "llvm/IRPrinter/IRPrintingPasses.h"
#include "llvm/LTO/LTO.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/TargetRegistry.h"
@@ -703,7 +704,8 @@ extern "C" LLVMRustResult LLVMRustOptimize(
bool LintIR, LLVMRustThinLTOBuffer **ThinLTOBufferRef, bool EmitThinLTO,
bool EmitThinLTOSummary, bool MergeFunctions, bool UnrollLoops,
bool SLPVectorize, bool LoopVectorize, bool DisableSimplifyLibCalls,
- bool EmitLifetimeMarkers, bool RunEnzyme,
+ bool EmitLifetimeMarkers, bool RunEnzyme, bool PrintBeforeEnzyme,
+ bool PrintAfterEnzyme, bool PrintPasses,
LLVMRustSanitizerOptions *SanitizerOptions, const char *PGOGenPath,
const char *PGOUsePath, bool InstrumentCoverage,
const char *InstrProfileOutput, const char *PGOSampleUsePath,
@@ -1048,14 +1050,38 @@ extern "C" LLVMRustResult LLVMRustOptimize(
// now load "-enzyme" pass:
#ifdef ENZYME
if (RunEnzyme) {
- registerEnzymeAndPassPipeline(PB, true);
+
+ if (PrintBeforeEnzyme) {
+ // Handle the Rust flag `-Zautodiff=PrintModBefore`.
+ std::string Banner = "Module before EnzymeNewPM";
+ MPM.addPass(PrintModulePass(outs(), Banner, true, false));
+ }
+
+ registerEnzymeAndPassPipeline(PB, false);
if (auto Err = PB.parsePassPipeline(MPM, "enzyme")) {
std::string ErrMsg = toString(std::move(Err));
LLVMRustSetLastError(ErrMsg.c_str());
return LLVMRustResult::Failure;
}
+
+ if (PrintAfterEnzyme) {
+ // Handle the Rust flag `-Zautodiff=PrintModAfter`.
+ std::string Banner = "Module after EnzymeNewPM";
+ MPM.addPass(PrintModulePass(outs(), Banner, true, false));
+ }
}
#endif
+ if (PrintPasses) {
+ // Print all passes from the PM:
+ std::string Pipeline;
+ raw_string_ostream SOS(Pipeline);
+ MPM.printPipeline(SOS, [&PIC](StringRef ClassName) {
+ auto PassName = PIC.getPassNameForClassName(ClassName);
+ return PassName.empty() ? ClassName : PassName;
+ });
+ outs() << Pipeline;
+ outs() << "\n";
+ }
// Upgrade all calls to old intrinsics first.
for (Module::iterator I = TheModule->begin(), E = TheModule->end(); I != E;)
diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs
index 56b3fe2ab4cb1..cc6c814e76eed 100644
--- a/compiler/rustc_session/src/config.rs
+++ b/compiler/rustc_session/src/config.rs
@@ -244,6 +244,10 @@ pub enum AutoDiff {
/// Print the module after running autodiff and optimizations.
PrintModFinal,
+ /// Print all passes scheduled by LLVM
+ PrintPasses,
+ /// Disable extra opt run after running autodiff
+ NoPostopt,
/// Enzyme's loose type debug helper (can cause incorrect gradients!!)
/// Usable in cases where Enzyme errors with `can not deduce type of X`.
LooseTypes,
diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs
index c70f1500d3930..2531b0c9d4219 100644
--- a/compiler/rustc_session/src/options.rs
+++ b/compiler/rustc_session/src/options.rs
@@ -711,7 +711,7 @@ mod desc {
pub(crate) const parse_list: &str = "a space-separated list of strings";
pub(crate) const parse_list_with_polarity: &str =
"a comma-separated list of strings, with elements beginning with + or -";
- pub(crate) const parse_autodiff: &str = "a comma separated list of settings: `Enable`, `PrintSteps`, `PrintTA`, `PrintAA`, `PrintPerf`, `PrintModBefore`, `PrintModAfter`, `PrintModFinal`, `LooseTypes`, `Inline`";
+ pub(crate) const parse_autodiff: &str = "a comma separated list of settings: `Enable`, `PrintSteps`, `PrintTA`, `PrintAA`, `PrintPerf`, `PrintModBefore`, `PrintModAfter`, `PrintModFinal`, `PrintPasses`, `NoPostopt`, `LooseTypes`, `Inline`";
pub(crate) const parse_comma_list: &str = "a comma-separated list of strings";
pub(crate) const parse_opt_comma_list: &str = parse_comma_list;
pub(crate) const parse_number: &str = "a number";
@@ -1360,6 +1360,8 @@ pub mod parse {
"PrintModBefore" => AutoDiff::PrintModBefore,
"PrintModAfter" => AutoDiff::PrintModAfter,
"PrintModFinal" => AutoDiff::PrintModFinal,
+ "NoPostopt" => AutoDiff::NoPostopt,
+ "PrintPasses" => AutoDiff::PrintPasses,
"LooseTypes" => AutoDiff::LooseTypes,
"Inline" => AutoDiff::Inline,
_ => {
@@ -2095,6 +2097,8 @@ options! {
`=PrintModBefore`
`=PrintModAfter`
`=PrintModFinal`
+ `=PrintPasses`,
+ `=NoPostopt`
`=LooseTypes`
`=Inline`
Multiple options can be combined with commas."),
diff --git a/tests/codegen/autodiff/identical_fnc.rs b/tests/codegen/autodiff/identical_fnc.rs
new file mode 100644
index 0000000000000..1c3277f52b488
--- /dev/null
+++ b/tests/codegen/autodiff/identical_fnc.rs
@@ -0,0 +1,45 @@
+//@ compile-flags: -Zautodiff=Enable -C opt-level=3 -Clto=fat
+//@ no-prefer-dynamic
+//@ needs-enzyme
+//
+// Each autodiff invocation creates a new placeholder function, which we will replace on llvm-ir
+// level. If a user tries to differentiate two identical functions within the same compilation unit,
+// then LLVM might merge them in release mode before AD. In that case we can't rewrite one of the
+// merged placeholder function anymore, and compilation would fail. We prevent this by disabling
+// LLVM's merge_function pass before AD. Here we implicetely test that our solution keeps working.
+// We also explicetly test that we keep running merge_function after AD, by checking for two
+// identical function calls in the LLVM-IR, while having two different calls in the Rust code.
+#![feature(autodiff)]
+
+use std::autodiff::autodiff;
+
+#[autodiff(d_square, Reverse, Duplicated, Active)]
+fn square(x: &f64) -> f64 {
+ x * x
+}
+
+#[autodiff(d_square2, Reverse, Duplicated, Active)]
+fn square2(x: &f64) -> f64 {
+ x * x
+}
+
+// CHECK:; identical_fnc::main
+// CHECK-NEXT:; Function Attrs:
+// CHECK-NEXT:define internal void @_ZN13identical_fnc4main17hf4dbc69c8d2f9130E()
+// CHECK-NEXT:start:
+// CHECK-NOT:br
+// CHECK-NOT:ret
+// CHECK:; call identical_fnc::d_square
+// CHECK-NEXT: call fastcc void @_ZN13identical_fnc8d_square17h4c364207a2f8e06dE(double %x.val, ptr noalias noundef nonnull align 8 dereferenceable(8) %dx1)
+// CHECK-NEXT:; call identical_fnc::d_square
+// CHECK-NEXT: call fastcc void @_ZN13identical_fnc8d_square17h4c364207a2f8e06dE(double %x.val, ptr noalias noundef nonnull align 8 dereferenceable(8) %dx2)
+
+fn main() {
+ let x = std::hint::black_box(3.0);
+ let mut dx1 = std::hint::black_box(1.0);
+ let mut dx2 = std::hint::black_box(1.0);
+ let _ = d_square(&x, &mut dx1, 1.0);
+ let _ = d_square2(&x, &mut dx2, 1.0);
+ assert_eq!(dx1, 6.0);
+ assert_eq!(dx2, 6.0);
+}
| diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs
index a8b49e9552c30..925898d817371 100644
--- a/compiler/rustc_codegen_llvm/src/back/lto.rs
+++ b/compiler/rustc_codegen_llvm/src/back/lto.rs
@@ -584,12 +584,10 @@ fn thin_lto(
}
-fn enable_autodiff_settings(ad: &[config::AutoDiff], module: &mut ModuleCodegen<ModuleLlvm>) {
+fn enable_autodiff_settings(ad: &[config::AutoDiff]) {
for &val in ad {
+ // We intentionally don't use a wildcard, to not forget handling anything new.
match val {
- config::AutoDiff::PrintModBefore => {
- unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
- }
config::AutoDiff::PrintPerf => {
llvm::set_print_perf(true);
@@ -603,17 +601,23 @@ fn enable_autodiff_settings(ad: &[config::AutoDiff], module: &mut ModuleCodegen<
llvm::set_inline(true);
config::AutoDiff::LooseTypes => {
- llvm::set_loose_types(false);
+ llvm::set_loose_types(true);
config::AutoDiff::PrintSteps => {
llvm::set_print(true);
+ config::AutoDiff::PrintPasses => {}
+ config::AutoDiff::PrintModBefore => {}
config::AutoDiff::PrintModAfter => {}
config::AutoDiff::PrintModFinal => {}
// This is required and already checked
config::AutoDiff::Enable => {}
+ // We handle this below
+ config::AutoDiff::NoPostopt => {}
// This helps with handling enums for now.
@@ -647,27 +651,27 @@ pub(crate) fn run_pass_manager(
// We then run the llvm_optimize function a second time, to optimize the code which we generated
// in the enzyme differentiation pass.
let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable);
- let stage =
- if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD };
+ let stage = if thin {
+ write::AutodiffStage::PreAD
+ } else {
+ if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD }
+ };
if enable_ad {
+ enable_autodiff_settings(&config.autodiff);
unsafe {
write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage)?;
- if cfg!(llvm_enzyme) && enable_ad {
- if config.autodiff.contains(&config::AutoDiff::PrintModAfter) {
- unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
- }
-
+ if cfg!(llvm_enzyme) && enable_ad && !thin {
let opt_stage = llvm::OptStage::FatLTO;
let stage = write::AutodiffStage::PostAD;
- unsafe {
- write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage)?;
+ if !config.autodiff.contains(&config::AutoDiff::NoPostopt) {
+ write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage)?;
+ }
// This is the final IR, so people should be able to inspect the optimized autodiff output,
diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs
index 76d431a497561..3cfd739b70c9d 100644
--- a/compiler/rustc_codegen_llvm/src/back/write.rs
+++ b/compiler/rustc_codegen_llvm/src/back/write.rs
@@ -565,6 +565,10 @@ pub(crate) unsafe fn llvm_optimize(
let consider_ad = cfg!(llvm_enzyme) && config.autodiff.contains(&config::AutoDiff::Enable);
let run_enzyme = autodiff_stage == AutodiffStage::DuringAD;
+ let print_before_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModBefore);
+ let print_after_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModAfter);
+ let print_passes = config.autodiff.contains(&config::AutoDiff::PrintPasses);
let unroll_loops;
let vectorize_slp;
let vectorize_loop;
@@ -572,13 +576,20 @@ pub(crate) unsafe fn llvm_optimize(
// When we build rustc with enzyme/autodiff support, we want to postpone size-increasing
// optimizations until after differentiation. Our pipeline is thus: (opt + enzyme), (full opt).
// We therefore have two calls to llvm_optimize, if autodiff is used.
+ //
+ // We also must disable merge_functions, since autodiff placeholder/dummy bodies tend to be
+ // identical. We run opts before AD, so there is a chance that LLVM will merge our dummies.
+ // In that case, we lack some dummy bodies and can't replace them with the real AD code anymore.
+ // We then would need to abort compilation. This was especially common in test cases.
if consider_ad && autodiff_stage != AutodiffStage::PostAD {
+ merge_functions = false;
unroll_loops = false;
vectorize_slp = false;
vectorize_loop = false;
} else {
unroll_loops =
opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
+ merge_functions = config.merge_functions;
vectorize_slp = config.vectorize_slp;
vectorize_loop = config.vectorize_loop;
@@ -656,13 +667,16 @@ pub(crate) unsafe fn llvm_optimize(
thin_lto_buffer,
config.emit_thin_lto,
config.emit_thin_lto_summary,
- config.merge_functions,
+ merge_functions,
unroll_loops,
vectorize_slp,
vectorize_loop,
config.no_builtins,
config.emit_lifetime_markers,
run_enzyme,
+ print_before_enzyme,
+ print_after_enzyme,
sanitizer_options.as_ref(),
pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
diff --git a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs
index 5e7ef27143b14..f5023e0ca5a90 100644
--- a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs
+++ b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs
@@ -445,7 +445,7 @@ pub(crate) fn differentiate<'ll>(
return Err(diag_handler.handle().emit_almost_fatal(AutoDiffWithoutEnable));
- // Before dumping the module, we want all the TypeTrees to become part of the module.
for item in diff_items.iter() {
let name = item.source.clone();
let fn_def: Option<&llvm::Value> = cx.get_function(&name);
diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
index 9ff04f729030c..ffb490dcdc22b 100644
--- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
+++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
@@ -2454,6 +2454,9 @@ unsafe extern "C" {
DisableSimplifyLibCalls: bool,
EmitLifetimeMarkers: bool,
RunEnzyme: bool,
+ PrintBeforeEnzyme: bool,
+ PrintAfterEnzyme: bool,
SanitizerOptions: Option<&SanitizerOptions>,
PGOGenPath: *const c_char,
PGOUsePath: *const c_char,
diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp
index e02c80c50b14a..8bee051dd4c3c 100644
--- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp
+++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp
@@ -14,6 +14,7 @@
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Verifier.h"
+#include "llvm/IRPrinter/IRPrintingPasses.h"
#include "llvm/LTO/LTO.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/TargetRegistry.h"
@@ -703,7 +704,8 @@ extern "C" LLVMRustResult LLVMRustOptimize(
bool LintIR, LLVMRustThinLTOBuffer **ThinLTOBufferRef, bool EmitThinLTO,
bool EmitThinLTOSummary, bool MergeFunctions, bool UnrollLoops,
bool SLPVectorize, bool LoopVectorize, bool DisableSimplifyLibCalls,
LLVMRustSanitizerOptions *SanitizerOptions, const char *PGOGenPath,
const char *PGOUsePath, bool InstrumentCoverage,
const char *InstrProfileOutput, const char *PGOSampleUsePath,
@@ -1048,14 +1050,38 @@ extern "C" LLVMRustResult LLVMRustOptimize(
// now load "-enzyme" pass:
#ifdef ENZYME
if (RunEnzyme) {
- registerEnzymeAndPassPipeline(PB, true);
+ if (PrintBeforeEnzyme) {
+ std::string Banner = "Module before EnzymeNewPM";
if (auto Err = PB.parsePassPipeline(MPM, "enzyme")) {
std::string ErrMsg = toString(std::move(Err));
LLVMRustSetLastError(ErrMsg.c_str());
return LLVMRustResult::Failure;
+ if (PrintAfterEnzyme) {
+ // Handle the Rust flag `-Zautodiff=PrintModAfter`.
+ std::string Banner = "Module after EnzymeNewPM";
}
#endif
+ if (PrintPasses) {
+ std::string Pipeline;
+ raw_string_ostream SOS(Pipeline);
+ MPM.printPipeline(SOS, [&PIC](StringRef ClassName) {
+ auto PassName = PIC.getPassNameForClassName(ClassName);
+ return PassName.empty() ? ClassName : PassName;
+ });
+ outs() << Pipeline;
+ }
// Upgrade all calls to old intrinsics first.
for (Module::iterator I = TheModule->begin(), E = TheModule->end(); I != E;)
diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs
index 56b3fe2ab4cb1..cc6c814e76eed 100644
--- a/compiler/rustc_session/src/config.rs
+++ b/compiler/rustc_session/src/config.rs
@@ -244,6 +244,10 @@ pub enum AutoDiff {
/// Print the module after running autodiff and optimizations.
PrintModFinal,
+ /// Print all passes scheduled by LLVM
+ PrintPasses,
+ NoPostopt,
/// Enzyme's loose type debug helper (can cause incorrect gradients!!)
/// Usable in cases where Enzyme errors with `can not deduce type of X`.
LooseTypes,
diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs
index c70f1500d3930..2531b0c9d4219 100644
--- a/compiler/rustc_session/src/options.rs
+++ b/compiler/rustc_session/src/options.rs
@@ -711,7 +711,7 @@ mod desc {
pub(crate) const parse_list: &str = "a space-separated list of strings";
pub(crate) const parse_list_with_polarity: &str =
"a comma-separated list of strings, with elements beginning with + or -";
- pub(crate) const parse_autodiff: &str = "a comma separated list of settings: `Enable`, `PrintSteps`, `PrintTA`, `PrintAA`, `PrintPerf`, `PrintModBefore`, `PrintModAfter`, `PrintModFinal`, `LooseTypes`, `Inline`";
+ pub(crate) const parse_autodiff: &str = "a comma separated list of settings: `Enable`, `PrintSteps`, `PrintTA`, `PrintAA`, `PrintPerf`, `PrintModBefore`, `PrintModAfter`, `PrintModFinal`, `PrintPasses`, `NoPostopt`, `LooseTypes`, `Inline`";
pub(crate) const parse_comma_list: &str = "a comma-separated list of strings";
pub(crate) const parse_opt_comma_list: &str = parse_comma_list;
pub(crate) const parse_number: &str = "a number";
@@ -1360,6 +1360,8 @@ pub mod parse {
"PrintModBefore" => AutoDiff::PrintModBefore,
"PrintModAfter" => AutoDiff::PrintModAfter,
"PrintModFinal" => AutoDiff::PrintModFinal,
+ "NoPostopt" => AutoDiff::NoPostopt,
+ "PrintPasses" => AutoDiff::PrintPasses,
"LooseTypes" => AutoDiff::LooseTypes,
"Inline" => AutoDiff::Inline,
_ => {
@@ -2095,6 +2097,8 @@ options! {
`=PrintModBefore`
`=PrintModAfter`
`=PrintModFinal`
+ `=PrintPasses`,
+ `=NoPostopt`
`=LooseTypes`
`=Inline`
Multiple options can be combined with commas."),
diff --git a/tests/codegen/autodiff/identical_fnc.rs b/tests/codegen/autodiff/identical_fnc.rs
new file mode 100644
index 0000000000000..1c3277f52b488
--- /dev/null
+++ b/tests/codegen/autodiff/identical_fnc.rs
@@ -0,0 +1,45 @@
+//@ compile-flags: -Zautodiff=Enable -C opt-level=3 -Clto=fat
+//@ no-prefer-dynamic
+//@ needs-enzyme
+// Each autodiff invocation creates a new placeholder function, which we will replace on llvm-ir
+// level. If a user tries to differentiate two identical functions within the same compilation unit,
+// then LLVM might merge them in release mode before AD. In that case we can't rewrite one of the
+// merged placeholder function anymore, and compilation would fail. We prevent this by disabling
+// LLVM's merge_function pass before AD. Here we implicetely test that our solution keeps working.
+// We also explicetly test that we keep running merge_function after AD, by checking for two
+// identical function calls in the LLVM-IR, while having two different calls in the Rust code.
+#![feature(autodiff)]
+use std::autodiff::autodiff;
+#[autodiff(d_square, Reverse, Duplicated, Active)]
+fn square(x: &f64) -> f64 {
+#[autodiff(d_square2, Reverse, Duplicated, Active)]
+fn square2(x: &f64) -> f64 {
+// CHECK:; identical_fnc::main
+// CHECK-NEXT:; Function Attrs:
+// CHECK-NEXT:define internal void @_ZN13identical_fnc4main17hf4dbc69c8d2f9130E()
+// CHECK-NEXT:start:
+// CHECK-NOT:br
+// CHECK-NOT:ret
+// CHECK:; call identical_fnc::d_square
+// CHECK-NEXT: call fastcc void @_ZN13identical_fnc8d_square17h4c364207a2f8e06dE(double %x.val, ptr noalias noundef nonnull align 8 dereferenceable(8) %dx1)
+// CHECK-NEXT:; call identical_fnc::d_square
+// CHECK-NEXT: call fastcc void @_ZN13identical_fnc8d_square17h4c364207a2f8e06dE(double %x.val, ptr noalias noundef nonnull align 8 dereferenceable(8) %dx2)
+fn main() {
+ let x = std::hint::black_box(3.0);
+ let mut dx1 = std::hint::black_box(1.0);
+ let _ = d_square(&x, &mut dx1, 1.0);
+ let _ = d_square2(&x, &mut dx2, 1.0);
+ assert_eq!(dx1, 6.0);
+ assert_eq!(dx2, 6.0); | [
"- enable_autodiff_settings(&config.autodiff, module);",
"- // This is the post-autodiff IR, mainly used for testing and educational purposes.",
"+ unsafe {",
"+ let merge_functions;",
"+ print_passes,",
"+ // Here we replace the placeholder code with the actual autodiff code, which calls Enzyme.",
"+ PrintPasses: bool,",
"- bool EmitLifetimeMarkers, bool RunEnzyme,",
"+ bool EmitLifetimeMarkers, bool RunEnzyme, bool PrintBeforeEnzyme,",
"+ bool PrintAfterEnzyme, bool PrintPasses,",
"+ // Handle the Rust flag `-Zautodiff=PrintModBefore`.",
"+ registerEnzymeAndPassPipeline(PB, false);",
"+ // Print all passes from the PM:",
"+ outs() << \"\\n\";",
"+ /// Disable extra opt run after running autodiff",
"+//",
"+ let mut dx2 = std::hint::black_box(1.0);"
] | [
59,
68,
79,
96,
135,
148,
162,
182,
183,
184,
195,
200,
215,
223,
238,
283,
319
] | {
"additions": 123,
"author": "ZuseZ4",
"deletions": 23,
"html_url": "https://github.com/rust-lang/rust/pull/139700",
"issue_id": 139700,
"merged_at": "2025-04-24T22:57:56Z",
"omission_probability": 0.1,
"pr_number": 139700,
"repo": "rust-lang/rust",
"title": "Autodiff flags",
"total_changes": 146
} |
128 | diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs
index 39251f1ce2737..4be8a90368d29 100644
--- a/compiler/rustc_parse/src/parser/item.rs
+++ b/compiler/rustc_parse/src/parser/item.rs
@@ -2058,6 +2058,17 @@ impl<'a> Parser<'a> {
}
self.expect_field_ty_separator()?;
let ty = self.parse_ty()?;
+ if self.token == token::Colon && self.look_ahead(1, |&t| t != token::Colon) {
+ self.dcx()
+ .struct_span_err(self.token.span, "found single colon in a struct field type path")
+ .with_span_suggestion_verbose(
+ self.token.span,
+ "write a path separator here",
+ "::",
+ Applicability::MaybeIncorrect,
+ )
+ .emit();
+ }
let default = if self.token == token::Eq {
self.bump();
let const_expr = self.parse_expr_anon_const()?;
diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs
index 1a02d45f0e3ce..1093e4f4af0a5 100644
--- a/compiler/rustc_parse/src/parser/path.rs
+++ b/compiler/rustc_parse/src/parser/path.rs
@@ -248,19 +248,13 @@ impl<'a> Parser<'a> {
segments.push(segment);
if self.is_import_coupler() || !self.eat_path_sep() {
- let ok_for_recovery = self.may_recover()
- && match style {
- PathStyle::Expr => true,
- PathStyle::Type if let Some((ident, _)) = self.prev_token.ident() => {
- self.token == token::Colon
- && ident.as_str().chars().all(|c| c.is_lowercase())
- && self.token.span.lo() == self.prev_token.span.hi()
- && self
- .look_ahead(1, |token| self.token.span.hi() == token.span.lo())
- }
- _ => false,
- };
- if ok_for_recovery
+ // IMPORTANT: We can *only ever* treat single colons as typo'ed double colons in
+ // expression contexts (!) since only there paths cannot possibly be followed by
+ // a colon and still form a syntactically valid construct. In pattern contexts,
+ // a path may be followed by a type annotation. E.g., `let pat:ty`. In type
+ // contexts, a path may be followed by a list of bounds. E.g., `where ty:bound`.
+ if self.may_recover()
+ && style == PathStyle::Expr // (!)
&& self.token == token::Colon
&& self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
{
diff --git a/tests/ui/generics/single-colon-path-not-const-generics.stderr b/tests/ui/generics/single-colon-path-not-const-generics.stderr
index 9eb62de275614..163ea4bbda6cd 100644
--- a/tests/ui/generics/single-colon-path-not-const-generics.stderr
+++ b/tests/ui/generics/single-colon-path-not-const-generics.stderr
@@ -1,13 +1,15 @@
error: path separator must be a double colon
--> $DIR/single-colon-path-not-const-generics.rs:8:18
|
+LL | pub struct Foo {
+ | --- while parsing this struct
LL | a: Vec<foo::bar:A>,
| ^
|
help: use a double colon instead
|
LL | a: Vec<foo::bar::A>,
- | +
+ | +
error: aborting due to 1 previous error
diff --git a/tests/ui/parser/ty-path-followed-by-single-colon.rs b/tests/ui/parser/ty-path-followed-by-single-colon.rs
new file mode 100644
index 0000000000000..a9082ea317a78
--- /dev/null
+++ b/tests/ui/parser/ty-path-followed-by-single-colon.rs
@@ -0,0 +1,22 @@
+// Paths in type contexts may be followed by single colons.
+// This means we can't generally assume that the user typo'ed a double colon.
+// issue: <https://github.com/rust-lang/rust/issues/140227>
+//@ check-pass
+#![crate_type = "lib"]
+#![expect(non_camel_case_types)]
+
+#[rustfmt::skip]
+mod garden {
+
+ fn f<path>() where path:to::somewhere {} // OK!
+
+ fn g(_: impl Take<path:to::somewhere>) {} // OK!
+
+ #[cfg(any())] fn h() where a::path:to::nowhere {} // OK!
+
+ fn i(_: impl Take<path::<>:to::somewhere>) {} // OK!
+
+ mod to { pub(super) trait somewhere {} }
+ trait Take { type path; }
+
+}
diff --git a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.fixed b/tests/ui/suggestions/argument-list-from-path-sep-error-129273.fixed
deleted file mode 100644
index f5dbf0c8b6f4e..0000000000000
--- a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.fixed
+++ /dev/null
@@ -1,15 +0,0 @@
-//@ run-rustfix
-
-use std::fmt;
-
-struct Hello;
-
-impl fmt::Display for Hello {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //~ ERROR path separator must be a double colon
- write!(f, "hello")
- }
-}
-
-fn main() {
- let _ = Hello;
-}
diff --git a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.rs b/tests/ui/suggestions/argument-list-from-path-sep-error-129273.rs
deleted file mode 100644
index c41880a26f6ec..0000000000000
--- a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-//@ run-rustfix
-
-use std::fmt;
-
-struct Hello;
-
-impl fmt::Display for Hello {
- fn fmt(&self, f: &mut fmt:Formatter) -> fmt::Result { //~ ERROR path separator must be a double colon
- write!(f, "hello")
- }
-}
-
-fn main() {
- let _ = Hello;
-}
diff --git a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr b/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr
deleted file mode 100644
index 713b071a625a0..0000000000000
--- a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr
+++ /dev/null
@@ -1,13 +0,0 @@
-error: path separator must be a double colon
- --> $DIR/argument-list-from-path-sep-error-129273.rs:8:30
- |
-LL | fn fmt(&self, f: &mut fmt:Formatter) -> fmt::Result {
- | ^
- |
-help: use a double colon instead
- |
-LL | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- | +
-
-error: aborting due to 1 previous error
-
diff --git a/tests/ui/suggestions/struct-field-type-including-single-colon.rs b/tests/ui/suggestions/struct-field-type-including-single-colon.rs
index a3111028895dd..482641fc7cac9 100644
--- a/tests/ui/suggestions/struct-field-type-including-single-colon.rs
+++ b/tests/ui/suggestions/struct-field-type-including-single-colon.rs
@@ -7,14 +7,14 @@ mod foo {
struct Foo {
a: foo:A,
- //~^ ERROR path separator must be a double colon
- //~| ERROR struct `A` is private
+ //~^ ERROR found single colon in a struct field type path
+ //~| ERROR expected `,`, or `}`, found `:`
}
struct Bar {
b: foo::bar:B,
- //~^ ERROR path separator must be a double colon
- //~| ERROR module `bar` is private
+ //~^ ERROR found single colon in a struct field type path
+ //~| ERROR expected `,`, or `}`, found `:`
}
fn main() {}
diff --git a/tests/ui/suggestions/struct-field-type-including-single-colon.stderr b/tests/ui/suggestions/struct-field-type-including-single-colon.stderr
index b9302b0453d5b..5ffc5b40849b6 100644
--- a/tests/ui/suggestions/struct-field-type-including-single-colon.stderr
+++ b/tests/ui/suggestions/struct-field-type-including-single-colon.stderr
@@ -1,51 +1,40 @@
-error: path separator must be a double colon
+error: found single colon in a struct field type path
--> $DIR/struct-field-type-including-single-colon.rs:9:11
|
LL | a: foo:A,
| ^
|
-help: use a double colon instead
+help: write a path separator here
|
LL | a: foo::A,
| +
-error: path separator must be a double colon
+error: expected `,`, or `}`, found `:`
+ --> $DIR/struct-field-type-including-single-colon.rs:9:11
+ |
+LL | struct Foo {
+ | --- while parsing this struct
+LL | a: foo:A,
+ | ^
+
+error: found single colon in a struct field type path
--> $DIR/struct-field-type-including-single-colon.rs:15:16
|
LL | b: foo::bar:B,
| ^
|
-help: use a double colon instead
+help: write a path separator here
|
LL | b: foo::bar::B,
| +
-error[E0603]: struct `A` is private
- --> $DIR/struct-field-type-including-single-colon.rs:9:12
- |
-LL | a: foo:A,
- | ^ private struct
- |
-note: the struct `A` is defined here
- --> $DIR/struct-field-type-including-single-colon.rs:2:5
- |
-LL | struct A;
- | ^^^^^^^^^
-
-error[E0603]: module `bar` is private
- --> $DIR/struct-field-type-including-single-colon.rs:15:13
+error: expected `,`, or `}`, found `:`
+ --> $DIR/struct-field-type-including-single-colon.rs:15:16
|
+LL | struct Bar {
+ | --- while parsing this struct
LL | b: foo::bar:B,
- | ^^^ - struct `B` is not publicly re-exported
- | |
- | private module
- |
-note: the module `bar` is defined here
- --> $DIR/struct-field-type-including-single-colon.rs:3:5
- |
-LL | mod bar {
- | ^^^^^^^
+ | ^
error: aborting due to 4 previous errors
-For more information about this error, try `rustc --explain E0603`.
| diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs
index 39251f1ce2737..4be8a90368d29 100644
--- a/compiler/rustc_parse/src/parser/item.rs
+++ b/compiler/rustc_parse/src/parser/item.rs
@@ -2058,6 +2058,17 @@ impl<'a> Parser<'a> {
}
self.expect_field_ty_separator()?;
let ty = self.parse_ty()?;
+ if self.token == token::Colon && self.look_ahead(1, |&t| t != token::Colon) {
+ self.dcx()
+ .struct_span_err(self.token.span, "found single colon in a struct field type path")
+ .with_span_suggestion_verbose(
+ self.token.span,
+ "write a path separator here",
+ "::",
+ Applicability::MaybeIncorrect,
+ )
+ .emit();
+ }
let default = if self.token == token::Eq {
self.bump();
let const_expr = self.parse_expr_anon_const()?;
diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs
index 1a02d45f0e3ce..1093e4f4af0a5 100644
--- a/compiler/rustc_parse/src/parser/path.rs
+++ b/compiler/rustc_parse/src/parser/path.rs
@@ -248,19 +248,13 @@ impl<'a> Parser<'a> {
segments.push(segment);
if self.is_import_coupler() || !self.eat_path_sep() {
- let ok_for_recovery = self.may_recover()
- && match style {
- PathStyle::Expr => true,
- PathStyle::Type if let Some((ident, _)) = self.prev_token.ident() => {
- && ident.as_str().chars().all(|c| c.is_lowercase())
- && self.token.span.lo() == self.prev_token.span.hi()
- .look_ahead(1, |token| self.token.span.hi() == token.span.lo())
- }
- _ => false,
- };
- if ok_for_recovery
+ // IMPORTANT: We can *only ever* treat single colons as typo'ed double colons in
+ // expression contexts (!) since only there paths cannot possibly be followed by
+ // a colon and still form a syntactically valid construct. In pattern contexts,
+ // a path may be followed by a type annotation. E.g., `let pat:ty`. In type
+ // contexts, a path may be followed by a list of bounds. E.g., `where ty:bound`.
+ if self.may_recover()
+ && style == PathStyle::Expr // (!)
&& self.token == token::Colon
&& self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
{
diff --git a/tests/ui/generics/single-colon-path-not-const-generics.stderr b/tests/ui/generics/single-colon-path-not-const-generics.stderr
index 9eb62de275614..163ea4bbda6cd 100644
--- a/tests/ui/generics/single-colon-path-not-const-generics.stderr
+++ b/tests/ui/generics/single-colon-path-not-const-generics.stderr
@@ -1,13 +1,15 @@
error: path separator must be a double colon
--> $DIR/single-colon-path-not-const-generics.rs:8:18
+LL | pub struct Foo {
+ | --- while parsing this struct
LL | a: Vec<foo::bar:A>,
| ^
help: use a double colon instead
LL | a: Vec<foo::bar::A>,
- | +
+ | +
error: aborting due to 1 previous error
diff --git a/tests/ui/parser/ty-path-followed-by-single-colon.rs b/tests/ui/parser/ty-path-followed-by-single-colon.rs
new file mode 100644
index 0000000000000..a9082ea317a78
--- /dev/null
+++ b/tests/ui/parser/ty-path-followed-by-single-colon.rs
@@ -0,0 +1,22 @@
+// Paths in type contexts may be followed by single colons.
+// This means we can't generally assume that the user typo'ed a double colon.
+// issue: <https://github.com/rust-lang/rust/issues/140227>
+//@ check-pass
+#![expect(non_camel_case_types)]
+#[rustfmt::skip]
+mod garden {
+ fn f<path>() where path:to::somewhere {} // OK!
+ fn g(_: impl Take<path:to::somewhere>) {} // OK!
+ fn i(_: impl Take<path::<>:to::somewhere>) {} // OK!
+ mod to { pub(super) trait somewhere {} }
+}
diff --git a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.fixed b/tests/ui/suggestions/argument-list-from-path-sep-error-129273.fixed
index f5dbf0c8b6f4e..0000000000000
--- a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.fixed
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //~ ERROR path separator must be a double colon
diff --git a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.rs b/tests/ui/suggestions/argument-list-from-path-sep-error-129273.rs
index c41880a26f6ec..0000000000000
--- a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.rs
- fn fmt(&self, f: &mut fmt:Formatter) -> fmt::Result { //~ ERROR path separator must be a double colon
diff --git a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr b/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr
index 713b071a625a0..0000000000000
--- a/tests/ui/suggestions/argument-list-from-path-sep-error-129273.stderr
@@ -1,13 +0,0 @@
- --> $DIR/argument-list-from-path-sep-error-129273.rs:8:30
-LL | fn fmt(&self, f: &mut fmt:Formatter) -> fmt::Result {
- | ^
- | +
-error: aborting due to 1 previous error
diff --git a/tests/ui/suggestions/struct-field-type-including-single-colon.rs b/tests/ui/suggestions/struct-field-type-including-single-colon.rs
index a3111028895dd..482641fc7cac9 100644
--- a/tests/ui/suggestions/struct-field-type-including-single-colon.rs
+++ b/tests/ui/suggestions/struct-field-type-including-single-colon.rs
@@ -7,14 +7,14 @@ mod foo {
struct Foo {
a: foo:A,
struct Bar {
b: foo::bar:B,
- //~| ERROR module `bar` is private
fn main() {}
diff --git a/tests/ui/suggestions/struct-field-type-including-single-colon.stderr b/tests/ui/suggestions/struct-field-type-including-single-colon.stderr
index b9302b0453d5b..5ffc5b40849b6 100644
--- a/tests/ui/suggestions/struct-field-type-including-single-colon.stderr
+++ b/tests/ui/suggestions/struct-field-type-including-single-colon.stderr
@@ -1,51 +1,40 @@
--> $DIR/struct-field-type-including-single-colon.rs:9:11
LL | a: foo:A,
| ^
LL | a: foo::A,
| +
+ --> $DIR/struct-field-type-including-single-colon.rs:9:11
+ |
+LL | struct Foo {
+LL | a: foo:A,
--> $DIR/struct-field-type-including-single-colon.rs:15:16
| ^
LL | b: foo::bar::B,
| +
-error[E0603]: struct `A` is private
- --> $DIR/struct-field-type-including-single-colon.rs:9:12
-LL | a: foo:A,
- | ^ private struct
-note: the struct `A` is defined here
- --> $DIR/struct-field-type-including-single-colon.rs:2:5
-LL | struct A;
- | ^^^^^^^^^
-error[E0603]: module `bar` is private
- --> $DIR/struct-field-type-including-single-colon.rs:15:13
+ --> $DIR/struct-field-type-including-single-colon.rs:15:16
+LL | struct Bar {
- | ^^^ - struct `B` is not publicly re-exported
- | |
- | private module
-note: the module `bar` is defined here
- --> $DIR/struct-field-type-including-single-colon.rs:3:5
-LL | mod bar {
- | ^^^^^^^
+ | ^
error: aborting due to 4 previous errors
-For more information about this error, try `rustc --explain E0603`. | [
"- self.token == token::Colon",
"- && self",
"+#![crate_type = \"lib\"]",
"+ #[cfg(any())] fn h() where a::path:to::nowhere {} // OK!",
"+ trait Take { type path; }",
"-LL | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {",
"- //~| ERROR struct `A` is private",
"+ | ^"
] | [
34,
37,
84,
94,
99,
158,
172,
211
] | {
"additions": 64,
"author": "fmease",
"deletions": 89,
"html_url": "https://github.com/rust-lang/rust/pull/140228",
"issue_id": 140228,
"merged_at": "2025-04-24T15:17:06Z",
"omission_probability": 0.1,
"pr_number": 140228,
"repo": "rust-lang/rust",
"title": "Revert overzealous parse recovery for single colons in paths",
"total_changes": 153
} |
129 | diff --git a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
index 94ee34c8b7bf3..81bf8c5d21c73 100644
--- a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
+++ b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
@@ -99,6 +99,12 @@ fn wasm_abi_safe<'tcx>(tcx: TyCtxt<'tcx>, arg: &ArgAbi<'tcx, Ty<'tcx>>) -> bool
return true;
}
+ // Both the old and the new ABIs treat vector types like `v128` the same
+ // way.
+ if uses_vector_registers(&arg.mode, &arg.layout.backend_repr) {
+ return true;
+ }
+
// This matches `unwrap_trivial_aggregate` in the wasm ABI logic.
if arg.layout.is_aggregate() {
let cx = LayoutCx::new(tcx, TypingEnv::fully_monomorphized());
diff --git a/tests/ui/lint/wasm_c_abi_transition.rs b/tests/ui/lint/wasm_c_abi_transition.rs
index 6a933a0de036f..411772ae890b7 100644
--- a/tests/ui/lint/wasm_c_abi_transition.rs
+++ b/tests/ui/lint/wasm_c_abi_transition.rs
@@ -3,7 +3,7 @@
//@ add-core-stubs
//@ build-fail
-#![feature(no_core)]
+#![feature(no_core, repr_simd)]
#![no_core]
#![crate_type = "lib"]
#![deny(wasm_c_abi)]
@@ -45,3 +45,13 @@ pub fn call_other_fun(x: MyType) {
pub struct MyZstType;
#[allow(improper_ctypes_definitions)]
pub extern "C" fn zst_safe(_x: (), _y: MyZstType) {}
+
+// The old and new wasm ABI treats simd types like `v128` the same way, so no
+// wasm_c_abi warning should be emitted.
+#[repr(simd)]
+#[allow(non_camel_case_types)]
+pub struct v128([i32; 4]);
+#[target_feature(enable = "simd128")]
+pub extern "C" fn my_safe_simd(x: v128) -> v128 { x }
+//~^ WARN `extern` fn uses type `v128`, which is not FFI-safe
+//~| WARN `extern` fn uses type `v128`, which is not FFI-safe
diff --git a/tests/ui/lint/wasm_c_abi_transition.stderr b/tests/ui/lint/wasm_c_abi_transition.stderr
index 389710d5cb3a2..b4526bf8d6873 100644
--- a/tests/ui/lint/wasm_c_abi_transition.stderr
+++ b/tests/ui/lint/wasm_c_abi_transition.stderr
@@ -1,3 +1,32 @@
+warning: `extern` fn uses type `v128`, which is not FFI-safe
+ --> $DIR/wasm_c_abi_transition.rs:55:35
+ |
+LL | pub extern "C" fn my_safe_simd(x: v128) -> v128 { x }
+ | ^^^^ not FFI-safe
+ |
+ = help: consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct
+ = note: this struct has unspecified layout
+note: the type is defined here
+ --> $DIR/wasm_c_abi_transition.rs:53:1
+ |
+LL | pub struct v128([i32; 4]);
+ | ^^^^^^^^^^^^^^^
+ = note: `#[warn(improper_ctypes_definitions)]` on by default
+
+warning: `extern` fn uses type `v128`, which is not FFI-safe
+ --> $DIR/wasm_c_abi_transition.rs:55:44
+ |
+LL | pub extern "C" fn my_safe_simd(x: v128) -> v128 { x }
+ | ^^^^ not FFI-safe
+ |
+ = help: consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct
+ = note: this struct has unspecified layout
+note: the type is defined here
+ --> $DIR/wasm_c_abi_transition.rs:53:1
+ |
+LL | pub struct v128([i32; 4]);
+ | ^^^^^^^^^^^^^^^
+
error: this function definition involves an argument of type `MyType` which is affected by the wasm ABI transition
--> $DIR/wasm_c_abi_transition.rs:18:1
|
@@ -33,7 +62,7 @@ LL | unsafe { other_fun(x) }
= note: for more information, see issue #138762 <https://github.com/rust-lang/rust/issues/138762>
= help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target
-error: aborting due to 3 previous errors
+error: aborting due to 3 previous errors; 2 warnings emitted
Future incompatibility report: Future breakage diagnostic:
error: this function definition involves an argument of type `MyType` which is affected by the wasm ABI transition
| diff --git a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
index 94ee34c8b7bf3..81bf8c5d21c73 100644
--- a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
+++ b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
@@ -99,6 +99,12 @@ fn wasm_abi_safe<'tcx>(tcx: TyCtxt<'tcx>, arg: &ArgAbi<'tcx, Ty<'tcx>>) -> bool
return true;
}
+ // Both the old and the new ABIs treat vector types like `v128` the same
+ // way.
+ if uses_vector_registers(&arg.mode, &arg.layout.backend_repr) {
+ return true;
+ }
// This matches `unwrap_trivial_aggregate` in the wasm ABI logic.
if arg.layout.is_aggregate() {
let cx = LayoutCx::new(tcx, TypingEnv::fully_monomorphized());
diff --git a/tests/ui/lint/wasm_c_abi_transition.rs b/tests/ui/lint/wasm_c_abi_transition.rs
index 6a933a0de036f..411772ae890b7 100644
--- a/tests/ui/lint/wasm_c_abi_transition.rs
+++ b/tests/ui/lint/wasm_c_abi_transition.rs
@@ -3,7 +3,7 @@
//@ add-core-stubs
//@ build-fail
-#![feature(no_core)]
+#![feature(no_core, repr_simd)]
#![no_core]
#![crate_type = "lib"]
#![deny(wasm_c_abi)]
@@ -45,3 +45,13 @@ pub fn call_other_fun(x: MyType) {
pub struct MyZstType;
#[allow(improper_ctypes_definitions)]
pub extern "C" fn zst_safe(_x: (), _y: MyZstType) {}
+// The old and new wasm ABI treats simd types like `v128` the same way, so no
+// wasm_c_abi warning should be emitted.
+#[repr(simd)]
+#[allow(non_camel_case_types)]
+#[target_feature(enable = "simd128")]
+pub extern "C" fn my_safe_simd(x: v128) -> v128 { x }
+//~^ WARN `extern` fn uses type `v128`, which is not FFI-safe
+//~| WARN `extern` fn uses type `v128`, which is not FFI-safe
diff --git a/tests/ui/lint/wasm_c_abi_transition.stderr b/tests/ui/lint/wasm_c_abi_transition.stderr
index 389710d5cb3a2..b4526bf8d6873 100644
--- a/tests/ui/lint/wasm_c_abi_transition.stderr
+++ b/tests/ui/lint/wasm_c_abi_transition.stderr
@@ -1,3 +1,32 @@
+ --> $DIR/wasm_c_abi_transition.rs:55:35
+ = note: `#[warn(improper_ctypes_definitions)]` on by default
+ --> $DIR/wasm_c_abi_transition.rs:55:44
+ | ^^^^ not FFI-safe
--> $DIR/wasm_c_abi_transition.rs:18:1
|
@@ -33,7 +62,7 @@ LL | unsafe { other_fun(x) }
= note: for more information, see issue #138762 <https://github.com/rust-lang/rust/issues/138762>
= help: the "C" ABI Rust uses on wasm32-unknown-unknown will change to align with the standard "C" ABI for this target
-error: aborting due to 3 previous errors
+error: aborting due to 3 previous errors; 2 warnings emitted
Future incompatibility report: Future breakage diagnostic: | [
"+pub struct v128([i32; 4]);",
"+ | ^^^^ not FFI-safe"
] | [
39,
53
] | {
"additions": 47,
"author": "alexcrichton",
"deletions": 2,
"html_url": "https://github.com/rust-lang/rust/pull/139809",
"issue_id": 139809,
"merged_at": "2025-04-24T12:05:12Z",
"omission_probability": 0.1,
"pr_number": 139809,
"repo": "rust-lang/rust",
"title": "Don't warn about `v128` in wasm ABI transition",
"total_changes": 49
} |
130 | diff --git a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
index 0f5bdc8d7683f..94ee34c8b7bf3 100644
--- a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
+++ b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
@@ -111,6 +111,11 @@ fn wasm_abi_safe<'tcx>(tcx: TyCtxt<'tcx>, arg: &ArgAbi<'tcx, Ty<'tcx>>) -> bool
}
}
+ // Zero-sized types are dropped in both ABIs, so they're safe
+ if arg.layout.is_zst() {
+ return true;
+ }
+
false
}
diff --git a/tests/ui/lint/wasm_c_abi_transition.rs b/tests/ui/lint/wasm_c_abi_transition.rs
index 1fe81679e65d0..6a933a0de036f 100644
--- a/tests/ui/lint/wasm_c_abi_transition.rs
+++ b/tests/ui/lint/wasm_c_abi_transition.rs
@@ -39,3 +39,9 @@ pub fn call_other_fun(x: MyType) {
unsafe { other_fun(x) } //~ERROR: wasm ABI transition
//~^WARN: previously accepted
}
+
+// Zero-sized types are safe in both ABIs
+#[repr(C)]
+pub struct MyZstType;
+#[allow(improper_ctypes_definitions)]
+pub extern "C" fn zst_safe(_x: (), _y: MyZstType) {}
| diff --git a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
index 0f5bdc8d7683f..94ee34c8b7bf3 100644
--- a/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
+++ b/compiler/rustc_monomorphize/src/mono_checks/abi_check.rs
@@ -111,6 +111,11 @@ fn wasm_abi_safe<'tcx>(tcx: TyCtxt<'tcx>, arg: &ArgAbi<'tcx, Ty<'tcx>>) -> bool
}
}
+ // Zero-sized types are dropped in both ABIs, so they're safe
+ return true;
+ }
false
diff --git a/tests/ui/lint/wasm_c_abi_transition.rs b/tests/ui/lint/wasm_c_abi_transition.rs
index 1fe81679e65d0..6a933a0de036f 100644
--- a/tests/ui/lint/wasm_c_abi_transition.rs
+++ b/tests/ui/lint/wasm_c_abi_transition.rs
@@ -39,3 +39,9 @@ pub fn call_other_fun(x: MyType) {
unsafe { other_fun(x) } //~ERROR: wasm ABI transition
//~^WARN: previously accepted
+// Zero-sized types are safe in both ABIs
+#[repr(C)]
+pub struct MyZstType;
+#[allow(improper_ctypes_definitions)]
+pub extern "C" fn zst_safe(_x: (), _y: MyZstType) {} | [
"+ if arg.layout.is_zst() {"
] | [
9
] | {
"additions": 11,
"author": "alexcrichton",
"deletions": 0,
"html_url": "https://github.com/rust-lang/rust/pull/139498",
"issue_id": 139498,
"merged_at": "2025-04-18T00:44:44Z",
"omission_probability": 0.1,
"pr_number": 139498,
"repo": "rust-lang/rust",
"title": "Ignore zero-sized types in wasm future-compat warning",
"total_changes": 11
} |
131 | diff --git a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs
index 78a452439836f..fa6bbf1d6e57b 100644
--- a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs
+++ b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs
@@ -583,27 +583,36 @@ fn receiver_is_dispatchable<'tcx>(
// create a modified param env, with `Self: Unsize<U>` and `U: Trait` (and all of
// its supertraits) added to caller bounds. `U: ?Sized` is already implied here.
let param_env = {
- let param_env = tcx.param_env(method.def_id);
+ // N.B. We generally want to emulate the construction of the `unnormalized_param_env`
+ // in the param-env query here. The fact that we don't just start with the clauses
+ // in the param-env of the method is because those are already normalized, and mixing
+ // normalized and unnormalized copies of predicates in `normalize_param_env_or_error`
+ // will cause ambiguity that the user can't really avoid.
+ //
+ // We leave out certain complexities of the param-env query here. Specifically, we:
+ // 1. Do not add `~const` bounds since there are no `dyn const Trait`s.
+ // 2. Do not add RPITIT self projection bounds for defaulted methods, since we
+ // are not constructing a param-env for "inside" of the body of the defaulted
+ // method, so we don't really care about projecting to a specific RPIT type,
+ // and because RPITITs are not dyn compatible (yet).
+ let mut predicates = tcx.predicates_of(method.def_id).instantiate_identity(tcx).predicates;
// Self: Unsize<U>
let unsize_predicate =
- ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty]).upcast(tcx);
+ ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty]);
+ predicates.push(unsize_predicate.upcast(tcx));
// U: Trait<Arg1, ..., ArgN>
- let trait_predicate = {
- let trait_def_id = method.trait_container(tcx).unwrap();
- let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| {
- if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }
- });
-
- ty::TraitRef::new_from_args(tcx, trait_def_id, args).upcast(tcx)
- };
+ let trait_def_id = method.trait_container(tcx).unwrap();
+ let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| {
+ if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }
+ });
+ let trait_predicate = ty::TraitRef::new_from_args(tcx, trait_def_id, args);
+ predicates.push(trait_predicate.upcast(tcx));
normalize_param_env_or_error(
tcx,
- ty::ParamEnv::new(tcx.mk_clauses_from_iter(
- param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]),
- )),
+ ty::ParamEnv::new(tcx.mk_clauses(&predicates)),
ObligationCause::dummy_with_span(tcx.def_span(method.def_id)),
)
};
diff --git a/tests/ui/associated-types/issue-59324.stderr b/tests/ui/associated-types/issue-59324.stderr
index f5e696b7ac1ce..f79afc89d10fb 100644
--- a/tests/ui/associated-types/issue-59324.stderr
+++ b/tests/ui/associated-types/issue-59324.stderr
@@ -36,11 +36,18 @@ LL | |
LL | | &self,
LL | | ) -> Self::AssocType;
| |_________________________^ the trait `Foo` is not implemented for `Bug`
+
+error[E0277]: the trait bound `(): Foo` is not satisfied
+ --> $DIR/issue-59324.rs:24:29
|
-help: consider further restricting type parameter `Bug` with trait `Foo`
+LL | fn with_factory<H>(factory: dyn ThriftService<()>) {}
+ | ^^^^^^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `()`
|
-LL | pub trait ThriftService<Bug: NotFoo + Foo>:
- | +++++
+help: this trait has no implementations, consider adding one
+ --> $DIR/issue-59324.rs:3:1
+ |
+LL | pub trait Foo: NotFoo {
+ | ^^^^^^^^^^^^^^^^^^^^^
error[E0277]: the trait bound `Bug: Foo` is not satisfied
--> $DIR/issue-59324.rs:16:5
@@ -51,18 +58,11 @@ LL | |
LL | | &self,
LL | | ) -> Self::AssocType;
| |_________________________^ the trait `Foo` is not implemented for `Bug`
-
-error[E0277]: the trait bound `(): Foo` is not satisfied
- --> $DIR/issue-59324.rs:24:29
|
-LL | fn with_factory<H>(factory: dyn ThriftService<()>) {}
- | ^^^^^^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `()`
- |
-help: this trait has no implementations, consider adding one
- --> $DIR/issue-59324.rs:3:1
+help: consider further restricting type parameter `Bug` with trait `Foo`
|
-LL | pub trait Foo: NotFoo {
- | ^^^^^^^^^^^^^^^^^^^^^
+LL | pub trait ThriftService<Bug: NotFoo + Foo>:
+ | +++++
error[E0277]: the trait bound `Bug: Foo` is not satisfied
--> $DIR/issue-59324.rs:20:10
diff --git a/tests/ui/self/dyn-dispatch-do-not-mix-normalized-and-unnormalized.rs b/tests/ui/self/dyn-dispatch-do-not-mix-normalized-and-unnormalized.rs
new file mode 100644
index 0000000000000..2bc70de2a340d
--- /dev/null
+++ b/tests/ui/self/dyn-dispatch-do-not-mix-normalized-and-unnormalized.rs
@@ -0,0 +1,26 @@
+//@ check-pass
+
+// Regression test for <https://github.com/rust-lang/rust/issues/138937>.
+
+// Previously, we'd take the normalized param env's clauses which included
+// `<PF as TraitC>::Value = i32`, which comes from the supertraits of `TraitD`
+// after normalizing `<PF as TraitC>::Value = <PF as TraitD>::Scalar`. Since
+// `normalize_param_env_or_error` ends up re-elaborating `PF: TraitD`, we'd
+// end up with both versions of this predicate (normalized and unnormalized).
+// Since these projections preds are not equal, we'd fail with ambiguity.
+
+trait TraitB<T> {}
+
+trait TraitC: TraitB<Self::Value> {
+ type Value;
+}
+
+trait TraitD: TraitC<Value = Self::Scalar> {
+ type Scalar;
+}
+
+trait TraitE {
+ fn apply<PF: TraitD<Scalar = i32>>(&self);
+}
+
+fn main() {}
| diff --git a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs
index 78a452439836f..fa6bbf1d6e57b 100644
--- a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs
+++ b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs
@@ -583,27 +583,36 @@ fn receiver_is_dispatchable<'tcx>(
// create a modified param env, with `Self: Unsize<U>` and `U: Trait` (and all of
// its supertraits) added to caller bounds. `U: ?Sized` is already implied here.
let param_env = {
- let param_env = tcx.param_env(method.def_id);
+ // N.B. We generally want to emulate the construction of the `unnormalized_param_env`
+ // in the param-env query here. The fact that we don't just start with the clauses
+ // in the param-env of the method is because those are already normalized, and mixing
+ // normalized and unnormalized copies of predicates in `normalize_param_env_or_error`
+ // will cause ambiguity that the user can't really avoid.
+ //
+ // We leave out certain complexities of the param-env query here. Specifically, we:
+ // 1. Do not add `~const` bounds since there are no `dyn const Trait`s.
+ // 2. Do not add RPITIT self projection bounds for defaulted methods, since we
+ // are not constructing a param-env for "inside" of the body of the defaulted
+ // method, so we don't really care about projecting to a specific RPIT type,
+ // and because RPITITs are not dyn compatible (yet).
+ let mut predicates = tcx.predicates_of(method.def_id).instantiate_identity(tcx).predicates;
// Self: Unsize<U>
let unsize_predicate =
- ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty]).upcast(tcx);
+ ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty]);
+ predicates.push(unsize_predicate.upcast(tcx));
// U: Trait<Arg1, ..., ArgN>
- let trait_predicate = {
- let trait_def_id = method.trait_container(tcx).unwrap();
- let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| {
- if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }
- });
- ty::TraitRef::new_from_args(tcx, trait_def_id, args).upcast(tcx)
- };
+ let trait_def_id = method.trait_container(tcx).unwrap();
+ });
+ let trait_predicate = ty::TraitRef::new_from_args(tcx, trait_def_id, args);
+ predicates.push(trait_predicate.upcast(tcx));
normalize_param_env_or_error(
tcx,
- ty::ParamEnv::new(tcx.mk_clauses_from_iter(
- param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]),
- )),
+ ty::ParamEnv::new(tcx.mk_clauses(&predicates)),
ObligationCause::dummy_with_span(tcx.def_span(method.def_id)),
)
};
diff --git a/tests/ui/associated-types/issue-59324.stderr b/tests/ui/associated-types/issue-59324.stderr
index f5e696b7ac1ce..f79afc89d10fb 100644
--- a/tests/ui/associated-types/issue-59324.stderr
+++ b/tests/ui/associated-types/issue-59324.stderr
@@ -36,11 +36,18 @@ LL | |
+error[E0277]: the trait bound `(): Foo` is not satisfied
+ --> $DIR/issue-59324.rs:24:29
-help: consider further restricting type parameter `Bug` with trait `Foo`
+LL | fn with_factory<H>(factory: dyn ThriftService<()>) {}
+ | ^^^^^^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `()`
-LL | pub trait ThriftService<Bug: NotFoo + Foo>:
- | +++++
+help: this trait has no implementations, consider adding one
+ --> $DIR/issue-59324.rs:3:1
+ |
+LL | pub trait Foo: NotFoo {
+ | ^^^^^^^^^^^^^^^^^^^^^
--> $DIR/issue-59324.rs:16:5
@@ -51,18 +58,11 @@ LL | |
-error[E0277]: the trait bound `(): Foo` is not satisfied
- --> $DIR/issue-59324.rs:24:29
-LL | fn with_factory<H>(factory: dyn ThriftService<()>) {}
- | ^^^^^^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `()`
- |
- --> $DIR/issue-59324.rs:3:1
+help: consider further restricting type parameter `Bug` with trait `Foo`
-LL | pub trait Foo: NotFoo {
- | ^^^^^^^^^^^^^^^^^^^^^
+LL | pub trait ThriftService<Bug: NotFoo + Foo>:
+ | +++++
--> $DIR/issue-59324.rs:20:10
diff --git a/tests/ui/self/dyn-dispatch-do-not-mix-normalized-and-unnormalized.rs b/tests/ui/self/dyn-dispatch-do-not-mix-normalized-and-unnormalized.rs
new file mode 100644
index 0000000000000..2bc70de2a340d
--- /dev/null
+++ b/tests/ui/self/dyn-dispatch-do-not-mix-normalized-and-unnormalized.rs
@@ -0,0 +1,26 @@
+//@ check-pass
+// Regression test for <https://github.com/rust-lang/rust/issues/138937>.
+// Previously, we'd take the normalized param env's clauses which included
+// `<PF as TraitC>::Value = i32`, which comes from the supertraits of `TraitD`
+// after normalizing `<PF as TraitC>::Value = <PF as TraitD>::Scalar`. Since
+// `normalize_param_env_or_error` ends up re-elaborating `PF: TraitD`, we'd
+// end up with both versions of this predicate (normalized and unnormalized).
+// Since these projections preds are not equal, we'd fail with ambiguity.
+trait TraitB<T> {}
+trait TraitC: TraitB<Self::Value> {
+ type Value;
+trait TraitD: TraitC<Value = Self::Scalar> {
+trait TraitE {
+ fn apply<PF: TraitD<Scalar = i32>>(&self);
+fn main() {} | [
"+ let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| {",
"+ if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }",
"-help: this trait has no implementations, consider adding one",
"+ type Scalar;"
] | [
39,
40,
91,
126
] | {
"additions": 61,
"author": "compiler-errors",
"deletions": 26,
"html_url": "https://github.com/rust-lang/rust/pull/138941",
"issue_id": 138941,
"merged_at": "2025-04-02T06:57:53Z",
"omission_probability": 0.1,
"pr_number": 138941,
"repo": "rust-lang/rust",
"title": "Do not mix normalized and unnormalized caller bounds when constructing param-env for `receiver_is_dispatchable`",
"total_changes": 87
} |
132 | diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs
index 35134e9f5a050..cf98cee0c15ed 100644
--- a/compiler/rustc_codegen_llvm/src/builder.rs
+++ b/compiler/rustc_codegen_llvm/src/builder.rs
@@ -594,6 +594,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
unsafe {
let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
+ let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
load
}
@@ -807,6 +808,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
unsafe {
let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
+ let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
let align =
if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
llvm::LLVMSetAlignment(store, align);
diff --git a/compiler/rustc_mir_transform/src/check_alignment.rs b/compiler/rustc_mir_transform/src/check_alignment.rs
index b70cca1484070..5115583f37c0f 100644
--- a/compiler/rustc_mir_transform/src/check_alignment.rs
+++ b/compiler/rustc_mir_transform/src/check_alignment.rs
@@ -1,3 +1,4 @@
+use rustc_abi::Align;
use rustc_index::IndexVec;
use rustc_middle::mir::interpret::Scalar;
use rustc_middle::mir::visit::PlaceContext;
@@ -11,10 +12,6 @@ pub(super) struct CheckAlignment;
impl<'tcx> crate::MirPass<'tcx> for CheckAlignment {
fn is_enabled(&self, sess: &Session) -> bool {
- // FIXME(#112480) MSVC and rustc disagree on minimum stack alignment on x86 Windows
- if sess.target.llvm_target == "i686-pc-windows-msvc" {
- return false;
- }
sess.ub_checks()
}
@@ -87,6 +84,33 @@ fn insert_alignment_check<'tcx>(
))),
});
+ // If this target does not have reliable alignment, further limit the mask by anding it with
+ // the mask for the highest reliable alignment.
+ #[allow(irrefutable_let_patterns)]
+ if let max_align = tcx.sess.target.max_reliable_alignment()
+ && max_align < Align::MAX
+ {
+ let max_mask = max_align.bytes() - 1;
+ let max_mask = Operand::Constant(Box::new(ConstOperand {
+ span: source_info.span,
+ user_ty: None,
+ const_: Const::Val(
+ ConstValue::Scalar(Scalar::from_target_usize(max_mask, &tcx)),
+ tcx.types.usize,
+ ),
+ }));
+ stmts.push(Statement {
+ source_info,
+ kind: StatementKind::Assign(Box::new((
+ alignment_mask,
+ Rvalue::BinaryOp(
+ BinOp::BitAnd,
+ Box::new((Operand::Copy(alignment_mask), max_mask)),
+ ),
+ ))),
+ });
+ }
+
// BitAnd the alignment mask with the pointer
let alignment_bits =
local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs
index 7ecc46cc69db9..ae366e29e3232 100644
--- a/compiler/rustc_target/src/callconv/mod.rs
+++ b/compiler/rustc_target/src/callconv/mod.rs
@@ -144,6 +144,7 @@ pub struct ArgAttributes {
/// (corresponding to LLVM's dereferenceable_or_null attributes, i.e., it is okay for this to be
/// set on a null pointer, but all non-null pointers must be dereferenceable).
pub pointee_size: Size,
+ /// The minimum alignment of the pointee, if any.
pub pointee_align: Option<Align>,
}
diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs
index 64171fcc7ab34..300e1ec372ac2 100644
--- a/compiler/rustc_target/src/spec/mod.rs
+++ b/compiler/rustc_target/src/spec/mod.rs
@@ -42,7 +42,9 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{fmt, io};
-use rustc_abi::{Endian, ExternAbi, Integer, Size, TargetDataLayout, TargetDataLayoutErrors};
+use rustc_abi::{
+ Align, Endian, ExternAbi, Integer, Size, TargetDataLayout, TargetDataLayoutErrors,
+};
use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
use rustc_fs_util::try_canonicalize;
use rustc_macros::{Decodable, Encodable, HashStable_Generic};
@@ -3598,6 +3600,25 @@ impl Target {
_ => return None,
})
}
+
+ /// Returns whether this target is known to have unreliable alignment:
+ /// native C code for the target fails to align some data to the degree
+ /// required by the C standard. We can't *really* do anything about that
+ /// since unsafe Rust code may assume alignment any time, but we can at least
+ /// inhibit some optimizations, and we suppress the alignment checks that
+ /// would detect this unsoundness.
+ ///
+ /// Every target that returns less than `Align::MAX` here is still has a soundness bug.
+ pub fn max_reliable_alignment(&self) -> Align {
+ // FIXME(#112480) MSVC on x86-32 is unsound and fails to properly align many types with
+ // more-than-4-byte-alignment on the stack. This makes alignments larger than 4 generally
+ // unreliable on 32bit Windows.
+ if self.is_like_windows && self.arch == "x86" {
+ Align::from_bytes(4).unwrap()
+ } else {
+ Align::MAX
+ }
+ }
}
/// Either a target tuple string or a path to a JSON file.
diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs
index 3d4ab33240af2..63ea035bd0e8e 100644
--- a/compiler/rustc_ty_utils/src/abi.rs
+++ b/compiler/rustc_ty_utils/src/abi.rs
@@ -347,7 +347,8 @@ fn adjust_for_rust_scalar<'tcx>(
None
};
if let Some(kind) = kind {
- attrs.pointee_align = Some(pointee.align);
+ attrs.pointee_align =
+ Some(pointee.align.min(cx.tcx().sess.target.max_reliable_alignment()));
// `Box` are not necessarily dereferenceable for the entire duration of the function as
// they can be deallocated at any time. Same for non-frozen shared references (see
diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md
index 4149b4cb92020..04e061276ea71 100644
--- a/src/doc/rustc/src/platform-support.md
+++ b/src/doc/rustc/src/platform-support.md
@@ -34,7 +34,7 @@ target | notes
-------|-------
[`aarch64-apple-darwin`](platform-support/apple-darwin.md) | ARM64 macOS (11.0+, Big Sur+)
`aarch64-unknown-linux-gnu` | ARM64 Linux (kernel 4.1, glibc 2.17+)
-`i686-pc-windows-msvc` | 32-bit MSVC (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI]
+`i686-pc-windows-msvc` | 32-bit MSVC (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI] [^win32-msvc-alignment]
`i686-unknown-linux-gnu` | 32-bit Linux (kernel 3.2+, glibc 2.17+, Pentium 4) [^x86_32-floats-return-ABI]
[`x86_64-apple-darwin`](platform-support/apple-darwin.md) | 64-bit macOS (10.12+, Sierra+)
[`x86_64-pc-windows-gnu`](platform-support/windows-gnu.md) | 64-bit MinGW (Windows 10+, Windows Server 2016+)
@@ -43,6 +43,8 @@ target | notes
[^x86_32-floats-return-ABI]: Due to limitations of the C ABI, floating-point support on `i686` targets is non-compliant: floating-point return values are passed via an x87 register, so NaN payload bits can be lost. Functions with the default Rust ABI are not affected. See [issue #115567][x86-32-float-return-issue].
+[^win32-msvc-alignment]: Due to non-standard behavior of MSVC, native C code on this target can cause types with an alignment of more than 4 bytes to be incorrectly aligned to only 4 bytes (this affects, e.g., `u64` and `i64`). Rust applies some mitigations to reduce the impact of this issue, but this can still cause unsoundness due to unsafe code that (correctly) assumes that references are always properly aligned. See [issue #112480](https://github.com/rust-lang/rust/issues/112480).
+
[77071]: https://github.com/rust-lang/rust/issues/77071
[x86-32-float-return-issue]: https://github.com/rust-lang/rust/issues/115567
@@ -95,7 +97,7 @@ target | notes
[`armv7-unknown-linux-ohos`](platform-support/openharmony.md) | Armv7-A OpenHarmony
[`loongarch64-unknown-linux-gnu`](platform-support/loongarch-linux.md) | LoongArch64 Linux, LP64D ABI (kernel 5.19, glibc 2.36)
[`loongarch64-unknown-linux-musl`](platform-support/loongarch-linux.md) | LoongArch64 Linux, LP64D ABI (kernel 5.19, musl 1.2.5)
-[`i686-pc-windows-gnu`](platform-support/windows-gnu.md) | 32-bit MinGW (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI]
+[`i686-pc-windows-gnu`](platform-support/windows-gnu.md) | 32-bit MinGW (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI] [^win32-msvc-alignment]
`powerpc-unknown-linux-gnu` | PowerPC Linux (kernel 3.2, glibc 2.17)
`powerpc64-unknown-linux-gnu` | PPC64 Linux (kernel 3.2, glibc 2.17)
[`powerpc64le-unknown-linux-gnu`](platform-support/powerpc64le-unknown-linux-gnu.md) | PPC64LE Linux (kernel 3.10, glibc 2.17)
@@ -169,7 +171,7 @@ target | std | notes
[`i686-pc-windows-gnullvm`](platform-support/windows-gnullvm.md) | ✓ | 32-bit x86 MinGW (Windows 10+, Pentium 4), LLVM ABI [^x86_32-floats-return-ABI]
[`i686-unknown-freebsd`](platform-support/freebsd.md) | ✓ | 32-bit x86 FreeBSD (Pentium 4) [^x86_32-floats-return-ABI]
`i686-unknown-linux-musl` | ✓ | 32-bit Linux with musl 1.2.3 (Pentium 4) [^x86_32-floats-return-ABI]
-[`i686-unknown-uefi`](platform-support/unknown-uefi.md) | ? | 32-bit UEFI (Pentium 4, softfloat)
+[`i686-unknown-uefi`](platform-support/unknown-uefi.md) | ? | 32-bit UEFI (Pentium 4, softfloat) [^win32-msvc-alignment]
[`loongarch64-unknown-none`](platform-support/loongarch-none.md) | * | LoongArch64 Bare-metal (LP64D ABI)
[`loongarch64-unknown-none-softfloat`](platform-support/loongarch-none.md) | * | LoongArch64 Bare-metal (LP64S ABI)
[`nvptx64-nvidia-cuda`](platform-support/nvptx64-nvidia-cuda.md) | * | --emit=asm generates PTX code that [runs on NVIDIA GPUs]
@@ -317,9 +319,9 @@ target | std | host | notes
[`i686-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD/i386 (Pentium 4) [^x86_32-floats-return-ABI]
[`i686-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | 32-bit OpenBSD (Pentium 4) [^x86_32-floats-return-ABI]
`i686-uwp-windows-gnu` | ✓ | | [^x86_32-floats-return-ABI]
-[`i686-uwp-windows-msvc`](platform-support/uwp-windows-msvc.md) | ✓ | | [^x86_32-floats-return-ABI]
+[`i686-uwp-windows-msvc`](platform-support/uwp-windows-msvc.md) | ✓ | | [^x86_32-floats-return-ABI] [^win32-msvc-alignment]
[`i686-win7-windows-gnu`](platform-support/win7-windows-gnu.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI]
-[`i686-win7-windows-msvc`](platform-support/win7-windows-msvc.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI]
+[`i686-win7-windows-msvc`](platform-support/win7-windows-msvc.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI] [^win32-msvc-alignment]
[`i686-wrs-vxworks`](platform-support/vxworks.md) | ✓ | | [^x86_32-floats-return-ABI]
[`loongarch64-unknown-linux-ohos`](platform-support/openharmony.md) | ✓ | | LoongArch64 OpenHarmony
[`m68k-unknown-linux-gnu`](platform-support/m68k-unknown-linux-gnu.md) | ? | | Motorola 680x0 Linux
diff --git a/tests/codegen/align-struct.rs b/tests/codegen/align-struct.rs
index cc65b08a9223c..402a184d4c07e 100644
--- a/tests/codegen/align-struct.rs
+++ b/tests/codegen/align-struct.rs
@@ -1,5 +1,7 @@
//@ compile-flags: -C no-prepopulate-passes -Z mir-opt-level=0
-//
+// 32bit MSVC does not align things properly so we suppress high alignment annotations (#112480)
+//@ ignore-i686-pc-windows-msvc
+//@ ignore-i686-pc-windows-gnu
#![crate_type = "lib"]
diff --git a/tests/codegen/issues/issue-56927.rs b/tests/codegen/issues/issue-56927.rs
index a40718689b3e0..415ef073e03ac 100644
--- a/tests/codegen/issues/issue-56927.rs
+++ b/tests/codegen/issues/issue-56927.rs
@@ -1,4 +1,7 @@
//@ compile-flags: -C no-prepopulate-passes
+// 32bit MSVC does not align things properly so we suppress high alignment annotations (#112480)
+//@ ignore-i686-pc-windows-msvc
+//@ ignore-i686-pc-windows-gnu
#![crate_type = "rlib"]
| diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs
index 35134e9f5a050..cf98cee0c15ed 100644
--- a/compiler/rustc_codegen_llvm/src/builder.rs
+++ b/compiler/rustc_codegen_llvm/src/builder.rs
@@ -594,6 +594,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
load
}
@@ -807,6 +808,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
let align =
if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
llvm::LLVMSetAlignment(store, align);
diff --git a/compiler/rustc_mir_transform/src/check_alignment.rs b/compiler/rustc_mir_transform/src/check_alignment.rs
index b70cca1484070..5115583f37c0f 100644
--- a/compiler/rustc_mir_transform/src/check_alignment.rs
+++ b/compiler/rustc_mir_transform/src/check_alignment.rs
@@ -1,3 +1,4 @@
+use rustc_abi::Align;
use rustc_index::IndexVec;
use rustc_middle::mir::interpret::Scalar;
use rustc_middle::mir::visit::PlaceContext;
@@ -11,10 +12,6 @@ pub(super) struct CheckAlignment;
impl<'tcx> crate::MirPass<'tcx> for CheckAlignment {
fn is_enabled(&self, sess: &Session) -> bool {
- // FIXME(#112480) MSVC and rustc disagree on minimum stack alignment on x86 Windows
- if sess.target.llvm_target == "i686-pc-windows-msvc" {
- return false;
- }
sess.ub_checks()
@@ -87,6 +84,33 @@ fn insert_alignment_check<'tcx>(
))),
});
+ // If this target does not have reliable alignment, further limit the mask by anding it with
+ #[allow(irrefutable_let_patterns)]
+ if let max_align = tcx.sess.target.max_reliable_alignment()
+ && max_align < Align::MAX
+ {
+ let max_mask = max_align.bytes() - 1;
+ let max_mask = Operand::Constant(Box::new(ConstOperand {
+ span: source_info.span,
+ user_ty: None,
+ const_: Const::Val(
+ tcx.types.usize,
+ ),
+ }));
+ stmts.push(Statement {
+ source_info,
+ kind: StatementKind::Assign(Box::new((
+ alignment_mask,
+ Rvalue::BinaryOp(
+ BinOp::BitAnd,
+ Box::new((Operand::Copy(alignment_mask), max_mask)),
+ ),
+ ))),
+ });
// BitAnd the alignment mask with the pointer
let alignment_bits =
local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs
index 7ecc46cc69db9..ae366e29e3232 100644
--- a/compiler/rustc_target/src/callconv/mod.rs
+++ b/compiler/rustc_target/src/callconv/mod.rs
@@ -144,6 +144,7 @@ pub struct ArgAttributes {
/// (corresponding to LLVM's dereferenceable_or_null attributes, i.e., it is okay for this to be
/// set on a null pointer, but all non-null pointers must be dereferenceable).
pub pointee_size: Size,
+ /// The minimum alignment of the pointee, if any.
pub pointee_align: Option<Align>,
diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs
index 64171fcc7ab34..300e1ec372ac2 100644
--- a/compiler/rustc_target/src/spec/mod.rs
+++ b/compiler/rustc_target/src/spec/mod.rs
@@ -42,7 +42,9 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{fmt, io};
-use rustc_abi::{Endian, ExternAbi, Integer, Size, TargetDataLayout, TargetDataLayoutErrors};
+use rustc_abi::{
+ Align, Endian, ExternAbi, Integer, Size, TargetDataLayout, TargetDataLayoutErrors,
+};
use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
use rustc_fs_util::try_canonicalize;
use rustc_macros::{Decodable, Encodable, HashStable_Generic};
@@ -3598,6 +3600,25 @@ impl Target {
_ => return None,
})
+ /// Returns whether this target is known to have unreliable alignment:
+ /// native C code for the target fails to align some data to the degree
+ /// required by the C standard. We can't *really* do anything about that
+ /// since unsafe Rust code may assume alignment any time, but we can at least
+ /// inhibit some optimizations, and we suppress the alignment checks that
+ /// would detect this unsoundness.
+ ///
+ /// Every target that returns less than `Align::MAX` here is still has a soundness bug.
+ pub fn max_reliable_alignment(&self) -> Align {
+ // FIXME(#112480) MSVC on x86-32 is unsound and fails to properly align many types with
+ // more-than-4-byte-alignment on the stack. This makes alignments larger than 4 generally
+ // unreliable on 32bit Windows.
+ if self.is_like_windows && self.arch == "x86" {
+ Align::from_bytes(4).unwrap()
+ } else {
+ Align::MAX
/// Either a target tuple string or a path to a JSON file.
diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs
index 3d4ab33240af2..63ea035bd0e8e 100644
--- a/compiler/rustc_ty_utils/src/abi.rs
+++ b/compiler/rustc_ty_utils/src/abi.rs
@@ -347,7 +347,8 @@ fn adjust_for_rust_scalar<'tcx>(
None
};
if let Some(kind) = kind {
- attrs.pointee_align = Some(pointee.align);
+ attrs.pointee_align =
+ Some(pointee.align.min(cx.tcx().sess.target.max_reliable_alignment()));
// `Box` are not necessarily dereferenceable for the entire duration of the function as
// they can be deallocated at any time. Same for non-frozen shared references (see
diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md
index 4149b4cb92020..04e061276ea71 100644
--- a/src/doc/rustc/src/platform-support.md
+++ b/src/doc/rustc/src/platform-support.md
@@ -34,7 +34,7 @@ target | notes
-------|-------
[`aarch64-apple-darwin`](platform-support/apple-darwin.md) | ARM64 macOS (11.0+, Big Sur+)
`aarch64-unknown-linux-gnu` | ARM64 Linux (kernel 4.1, glibc 2.17+)
-`i686-pc-windows-msvc` | 32-bit MSVC (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI]
+`i686-pc-windows-msvc` | 32-bit MSVC (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI] [^win32-msvc-alignment]
`i686-unknown-linux-gnu` | 32-bit Linux (kernel 3.2+, glibc 2.17+, Pentium 4) [^x86_32-floats-return-ABI]
[`x86_64-apple-darwin`](platform-support/apple-darwin.md) | 64-bit macOS (10.12+, Sierra+)
[`x86_64-pc-windows-gnu`](platform-support/windows-gnu.md) | 64-bit MinGW (Windows 10+, Windows Server 2016+)
@@ -43,6 +43,8 @@ target | notes
[^x86_32-floats-return-ABI]: Due to limitations of the C ABI, floating-point support on `i686` targets is non-compliant: floating-point return values are passed via an x87 register, so NaN payload bits can be lost. Functions with the default Rust ABI are not affected. See [issue #115567][x86-32-float-return-issue].
+[^win32-msvc-alignment]: Due to non-standard behavior of MSVC, native C code on this target can cause types with an alignment of more than 4 bytes to be incorrectly aligned to only 4 bytes (this affects, e.g., `u64` and `i64`). Rust applies some mitigations to reduce the impact of this issue, but this can still cause unsoundness due to unsafe code that (correctly) assumes that references are always properly aligned. See [issue #112480](https://github.com/rust-lang/rust/issues/112480).
[77071]: https://github.com/rust-lang/rust/issues/77071
[x86-32-float-return-issue]: https://github.com/rust-lang/rust/issues/115567
@@ -95,7 +97,7 @@ target | notes
[`armv7-unknown-linux-ohos`](platform-support/openharmony.md) | Armv7-A OpenHarmony
[`loongarch64-unknown-linux-gnu`](platform-support/loongarch-linux.md) | LoongArch64 Linux, LP64D ABI (kernel 5.19, glibc 2.36)
[`loongarch64-unknown-linux-musl`](platform-support/loongarch-linux.md) | LoongArch64 Linux, LP64D ABI (kernel 5.19, musl 1.2.5)
-[`i686-pc-windows-gnu`](platform-support/windows-gnu.md) | 32-bit MinGW (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI]
+[`i686-pc-windows-gnu`](platform-support/windows-gnu.md) | 32-bit MinGW (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI] [^win32-msvc-alignment]
`powerpc-unknown-linux-gnu` | PowerPC Linux (kernel 3.2, glibc 2.17)
`powerpc64-unknown-linux-gnu` | PPC64 Linux (kernel 3.2, glibc 2.17)
[`powerpc64le-unknown-linux-gnu`](platform-support/powerpc64le-unknown-linux-gnu.md) | PPC64LE Linux (kernel 3.10, glibc 2.17)
@@ -169,7 +171,7 @@ target | std | notes
[`i686-pc-windows-gnullvm`](platform-support/windows-gnullvm.md) | ✓ | 32-bit x86 MinGW (Windows 10+, Pentium 4), LLVM ABI [^x86_32-floats-return-ABI]
[`i686-unknown-freebsd`](platform-support/freebsd.md) | ✓ | 32-bit x86 FreeBSD (Pentium 4) [^x86_32-floats-return-ABI]
`i686-unknown-linux-musl` | ✓ | 32-bit Linux with musl 1.2.3 (Pentium 4) [^x86_32-floats-return-ABI]
-[`i686-unknown-uefi`](platform-support/unknown-uefi.md) | ? | 32-bit UEFI (Pentium 4, softfloat)
+[`i686-unknown-uefi`](platform-support/unknown-uefi.md) | ? | 32-bit UEFI (Pentium 4, softfloat) [^win32-msvc-alignment]
[`loongarch64-unknown-none`](platform-support/loongarch-none.md) | * | LoongArch64 Bare-metal (LP64D ABI)
[`loongarch64-unknown-none-softfloat`](platform-support/loongarch-none.md) | * | LoongArch64 Bare-metal (LP64S ABI)
[`nvptx64-nvidia-cuda`](platform-support/nvptx64-nvidia-cuda.md) | * | --emit=asm generates PTX code that [runs on NVIDIA GPUs]
@@ -317,9 +319,9 @@ target | std | host | notes
[`i686-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD/i386 (Pentium 4) [^x86_32-floats-return-ABI]
[`i686-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | 32-bit OpenBSD (Pentium 4) [^x86_32-floats-return-ABI]
`i686-uwp-windows-gnu` | ✓ | | [^x86_32-floats-return-ABI]
-[`i686-uwp-windows-msvc`](platform-support/uwp-windows-msvc.md) | ✓ | | [^x86_32-floats-return-ABI]
+[`i686-uwp-windows-msvc`](platform-support/uwp-windows-msvc.md) | ✓ | | [^x86_32-floats-return-ABI] [^win32-msvc-alignment]
[`i686-win7-windows-gnu`](platform-support/win7-windows-gnu.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI]
-[`i686-win7-windows-msvc`](platform-support/win7-windows-msvc.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI]
+[`i686-win7-windows-msvc`](platform-support/win7-windows-msvc.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI] [^win32-msvc-alignment]
[`i686-wrs-vxworks`](platform-support/vxworks.md) | ✓ | | [^x86_32-floats-return-ABI]
[`loongarch64-unknown-linux-ohos`](platform-support/openharmony.md) | ✓ | | LoongArch64 OpenHarmony
[`m68k-unknown-linux-gnu`](platform-support/m68k-unknown-linux-gnu.md) | ? | | Motorola 680x0 Linux
diff --git a/tests/codegen/align-struct.rs b/tests/codegen/align-struct.rs
index cc65b08a9223c..402a184d4c07e 100644
--- a/tests/codegen/align-struct.rs
+++ b/tests/codegen/align-struct.rs
@@ -1,5 +1,7 @@
//@ compile-flags: -C no-prepopulate-passes -Z mir-opt-level=0
-//
#![crate_type = "lib"]
diff --git a/tests/codegen/issues/issue-56927.rs b/tests/codegen/issues/issue-56927.rs
index a40718689b3e0..415ef073e03ac 100644
--- a/tests/codegen/issues/issue-56927.rs
+++ b/tests/codegen/issues/issue-56927.rs
@@ -1,4 +1,7 @@
//@ compile-flags: -C no-prepopulate-passes
#![crate_type = "rlib"] | [
"+ // the mask for the highest reliable alignment.",
"+ ConstValue::Scalar(Scalar::from_target_usize(max_mask, &tcx)),",
"+ }"
] | [
45,
55,
122
] | {
"additions": 68,
"author": "RalfJung",
"deletions": 12,
"html_url": "https://github.com/rust-lang/rust/pull/139261",
"issue_id": 139261,
"merged_at": "2025-04-24T15:17:07Z",
"omission_probability": 0.1,
"pr_number": 139261,
"repo": "rust-lang/rust",
"title": "mitigate MSVC alignment issue on x86-32",
"total_changes": 80
} |
133 | diff --git a/src/doc/rustc-dev-guide/src/tests/minicore.md b/src/doc/rustc-dev-guide/src/tests/minicore.md
index e4853b6d40e35..507b259e0275d 100644
--- a/src/doc/rustc-dev-guide/src/tests/minicore.md
+++ b/src/doc/rustc-dev-guide/src/tests/minicore.md
@@ -6,25 +6,37 @@
ui/codegen/assembly test suites. It provides `core` stubs for tests that need to
build for cross-compiled targets but do not need/want to run.
+<div class="warning">
+Please note that [`minicore`] is only intended for `core` items, and explicitly
+**not** `std` or `alloc` items because `core` items are applicable to a wider
+range of tests.
+</div>
+
A test can use [`minicore`] by specifying the `//@ add-core-stubs` directive.
Then, mark the test with `#![feature(no_core)]` + `#![no_std]` + `#![no_core]`.
Due to Edition 2015 extern prelude rules, you will probably need to declare
`minicore` as an extern crate.
+## Implied compiler flags
+
Due to the `no_std` + `no_core` nature of these tests, `//@ add-core-stubs`
implies and requires that the test will be built with `-C panic=abort`.
-Unwinding panics are not supported.
+**Unwinding panics are not supported.**
+
+Tests will also be built with `-C force-unwind-tables=yes` to preserve CFI
+directives in assembly tests.
+
+TL;DR: `//@ add-core-stubs` implies two compiler flags:
+
+1. `-C panic=abort`
+2. `-C force-unwind-tables=yes`
+
+## Adding more `core` stubs
If you find a `core` item to be missing from the [`minicore`] stub, consider
adding it to the test auxiliary if it's likely to be used or is already needed
by more than one test.
-<div class="warning">
-Please note that [`minicore`] is only intended for `core` items, and explicitly
-**not** `std` or `alloc` items because `core` items are applicable to a wider
-range of tests.
-</div>
-
## Example codegen test that uses `minicore`
```rust,no_run
diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs
index cc09463c358a7..fe23cce81e908 100644
--- a/src/tools/compiletest/src/runtest.rs
+++ b/src/tools/compiletest/src/runtest.rs
@@ -1710,12 +1710,16 @@ impl<'test> TestCx<'test> {
rustc.args(&self.props.compile_flags);
// FIXME(jieyouxu): we should report a fatal error or warning if user wrote `-Cpanic=` with
- // something that's not `abort`, however, by moving this last we should override previous
- // `-Cpanic=`s
+ // something that's not `abort` and `-Cforce-unwind-tables` with a value that is not `yes`,
+ // however, by moving this last we should override previous `-Cpanic`s and
+ // `-Cforce-unwind-tables`s. Note that checking here is very fragile, because we'd have to
+ // account for all possible compile flag splittings (they have some... intricacies and are
+ // not yet normalized).
//
// `minicore` requires `#![no_std]` and `#![no_core]`, which means no unwinding panics.
if self.props.add_core_stubs {
rustc.arg("-Cpanic=abort");
+ rustc.arg("-Cforce-unwind-tables=yes");
}
rustc
diff --git a/tests/assembly/x86-return-float.rs b/tests/assembly/x86-return-float.rs
index 2c39c830684ec..165c11d228011 100644
--- a/tests/assembly/x86-return-float.rs
+++ b/tests/assembly/x86-return-float.rs
@@ -35,6 +35,7 @@ use minicore::*;
pub fn return_f32(x: f32) -> f32 {
// CHECK: movss {{.*}}(%ebp), %xmm0
// CHECK-NEXT: popl %ebp
+ // linux-NEXT: .cfi_def_cfa
// CHECK-NEXT: retl
x
}
@@ -44,6 +45,7 @@ pub fn return_f32(x: f32) -> f32 {
pub fn return_f64(x: f64) -> f64 {
// CHECK: movsd {{.*}}(%ebp), %xmm0
// CHECK-NEXT: popl %ebp
+ // linux-NEXT: .cfi_def_cfa
// CHECK-NEXT: retl
x
}
@@ -313,9 +315,13 @@ pub unsafe fn call_other_f64(x: &mut (usize, f64)) {
#[no_mangle]
pub fn return_f16(x: f16) -> f16 {
// CHECK: pushl %ebp
+ // linux-NEXT: .cfi_def_cfa_offset
+ // linux-NEXT: .cfi_offset
// CHECK-NEXT: movl %esp, %ebp
+ // linux-NEXT: .cfi_def_cfa_register
// CHECK-NEXT: pinsrw $0, 8(%ebp), %xmm0
// CHECK-NEXT: popl %ebp
+ // linux-NEXT: .cfi_def_cfa
// CHECK-NEXT: retl
x
}
@@ -324,10 +330,14 @@ pub fn return_f16(x: f16) -> f16 {
#[no_mangle]
pub fn return_f128(x: f128) -> f128 {
// CHECK: pushl %ebp
+ // linux-NEXT: .cfi_def_cfa_offset
+ // linux-NEXT: .cfi_offset
// CHECK-NEXT: movl %esp, %ebp
+ // linux-NEXT: .cfi_def_cfa_register
// linux-NEXT: movaps 8(%ebp), %xmm0
// win-NEXT: movups 8(%ebp), %xmm0
// CHECK-NEXT: popl %ebp
+ // linux-NEXT: .cfi_def_cfa
// CHECK-NEXT: retl
x
}
| diff --git a/src/doc/rustc-dev-guide/src/tests/minicore.md b/src/doc/rustc-dev-guide/src/tests/minicore.md
index e4853b6d40e35..507b259e0275d 100644
--- a/src/doc/rustc-dev-guide/src/tests/minicore.md
+++ b/src/doc/rustc-dev-guide/src/tests/minicore.md
@@ -6,25 +6,37 @@
ui/codegen/assembly test suites. It provides `core` stubs for tests that need to
build for cross-compiled targets but do not need/want to run.
+<div class="warning">
+Please note that [`minicore`] is only intended for `core` items, and explicitly
+**not** `std` or `alloc` items because `core` items are applicable to a wider
+range of tests.
A test can use [`minicore`] by specifying the `//@ add-core-stubs` directive.
Then, mark the test with `#![feature(no_core)]` + `#![no_std]` + `#![no_core]`.
Due to Edition 2015 extern prelude rules, you will probably need to declare
`minicore` as an extern crate.
+## Implied compiler flags
Due to the `no_std` + `no_core` nature of these tests, `//@ add-core-stubs`
implies and requires that the test will be built with `-C panic=abort`.
-Unwinding panics are not supported.
+**Unwinding panics are not supported.**
+Tests will also be built with `-C force-unwind-tables=yes` to preserve CFI
+directives in assembly tests.
+TL;DR: `//@ add-core-stubs` implies two compiler flags:
+1. `-C panic=abort`
+2. `-C force-unwind-tables=yes`
+## Adding more `core` stubs
If you find a `core` item to be missing from the [`minicore`] stub, consider
adding it to the test auxiliary if it's likely to be used or is already needed
by more than one test.
-<div class="warning">
-Please note that [`minicore`] is only intended for `core` items, and explicitly
-**not** `std` or `alloc` items because `core` items are applicable to a wider
-range of tests.
-</div>
-
## Example codegen test that uses `minicore`
```rust,no_run
diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs
index cc09463c358a7..fe23cce81e908 100644
--- a/src/tools/compiletest/src/runtest.rs
+++ b/src/tools/compiletest/src/runtest.rs
@@ -1710,12 +1710,16 @@ impl<'test> TestCx<'test> {
rustc.args(&self.props.compile_flags);
// FIXME(jieyouxu): we should report a fatal error or warning if user wrote `-Cpanic=` with
- // something that's not `abort`, however, by moving this last we should override previous
- // `-Cpanic=`s
+ // something that's not `abort` and `-Cforce-unwind-tables` with a value that is not `yes`,
+ // however, by moving this last we should override previous `-Cpanic`s and
+ // account for all possible compile flag splittings (they have some... intricacies and are
+ // not yet normalized).
//
// `minicore` requires `#![no_std]` and `#![no_core]`, which means no unwinding panics.
if self.props.add_core_stubs {
rustc.arg("-Cpanic=abort");
+ rustc.arg("-Cforce-unwind-tables=yes");
}
rustc
diff --git a/tests/assembly/x86-return-float.rs b/tests/assembly/x86-return-float.rs
index 2c39c830684ec..165c11d228011 100644
--- a/tests/assembly/x86-return-float.rs
+++ b/tests/assembly/x86-return-float.rs
@@ -35,6 +35,7 @@ use minicore::*;
pub fn return_f32(x: f32) -> f32 {
// CHECK: movss {{.*}}(%ebp), %xmm0
@@ -44,6 +45,7 @@ pub fn return_f32(x: f32) -> f32 {
pub fn return_f64(x: f64) -> f64 {
// CHECK: movsd {{.*}}(%ebp), %xmm0
@@ -313,9 +315,13 @@ pub unsafe fn call_other_f64(x: &mut (usize, f64)) {
pub fn return_f16(x: f16) -> f16 {
// CHECK-NEXT: pinsrw $0, 8(%ebp), %xmm0
@@ -324,10 +330,14 @@ pub fn return_f16(x: f16) -> f16 {
pub fn return_f128(x: f128) -> f128 {
// linux-NEXT: movaps 8(%ebp), %xmm0
// win-NEXT: movups 8(%ebp), %xmm0 | [
"+</div>",
"+ // `-Cforce-unwind-tables`s. Note that checking here is very fragile, because we'd have to"
] | [
12,
61
] | {
"additions": 35,
"author": "jieyouxu",
"deletions": 9,
"html_url": "https://github.com/rust-lang/rust/pull/140194",
"issue_id": 140194,
"merged_at": "2025-04-24T15:17:07Z",
"omission_probability": 0.1,
"pr_number": 140194,
"repo": "rust-lang/rust",
"title": "minicore: Have `//@ add-core-stubs` also imply `-Cforce-unwind-tables=yes`",
"total_changes": 44
} |
134 | diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs
index 54b6c22b2d821..cad7e42fd8212 100644
--- a/compiler/rustc_trait_selection/src/traits/wf.rs
+++ b/compiler/rustc_trait_selection/src/traits/wf.rs
@@ -1,3 +1,8 @@
+//! Core logic responsible for determining what it means for various type system
+//! primitives to be "well formed". Actually checking whether these primitives are
+//! well formed is performed elsewhere (e.g. during type checking or item well formedness
+//! checking).
+
use std::iter;
use rustc_hir as hir;
@@ -15,12 +20,13 @@ use tracing::{debug, instrument, trace};
use crate::infer::InferCtxt;
use crate::traits;
+
/// Returns the set of obligations needed to make `arg` well-formed.
/// If `arg` contains unresolved inference variables, this may include
/// further WF obligations. However, if `arg` IS an unresolved
/// inference variable, returns `None`, because we are not able to
-/// make any progress at all. This is to prevent "livelock" where we
-/// say "$0 is WF if $0 is WF".
+/// make any progress at all. This is to prevent cycles where we
+/// say "?0 is WF if ?0 is WF".
pub fn obligations<'tcx>(
infcx: &InferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
@@ -29,14 +35,14 @@ pub fn obligations<'tcx>(
arg: GenericArg<'tcx>,
span: Span,
) -> Option<PredicateObligations<'tcx>> {
- // Handle the "livelock" case (see comment above) by bailing out if necessary.
+ // Handle the "cycle" case (see comment above) by bailing out if necessary.
let arg = match arg.unpack() {
GenericArgKind::Type(ty) => {
match ty.kind() {
ty::Infer(ty::TyVar(_)) => {
let resolved_ty = infcx.shallow_resolve(ty);
if resolved_ty == ty {
- // No progress, bail out to prevent "livelock".
+ // No progress, bail out to prevent cycles.
return None;
} else {
resolved_ty
@@ -51,7 +57,7 @@ pub fn obligations<'tcx>(
ty::ConstKind::Infer(_) => {
let resolved = infcx.shallow_resolve_const(ct);
if resolved == ct {
- // No progress.
+ // No progress, bail out to prevent cycles.
return None;
} else {
resolved
@@ -74,7 +80,7 @@ pub fn obligations<'tcx>(
recursion_depth,
item: None,
};
- wf.compute(arg);
+ wf.add_wf_preds_for_generic_arg(arg);
debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
let result = wf.normalize(infcx);
@@ -97,7 +103,7 @@ pub fn unnormalized_obligations<'tcx>(
// However, if `arg` IS an unresolved inference variable, returns `None`,
// because we are not able to make any progress at all. This is to prevent
- // "livelock" where we say "$0 is WF if $0 is WF".
+ // cycles where we say "?0 is WF if ?0 is WF".
if arg.is_non_region_infer() {
return None;
}
@@ -115,7 +121,7 @@ pub fn unnormalized_obligations<'tcx>(
recursion_depth: 0,
item: None,
};
- wf.compute(arg);
+ wf.add_wf_preds_for_generic_arg(arg);
Some(wf.out)
}
@@ -140,7 +146,7 @@ pub fn trait_obligations<'tcx>(
recursion_depth: 0,
item: Some(item),
};
- wf.compute_trait_pred(trait_pred, Elaborate::All);
+ wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
debug!(obligations = ?wf.out);
wf.normalize(infcx)
}
@@ -171,7 +177,7 @@ pub fn clause_obligations<'tcx>(
// It's ok to skip the binder here because wf code is prepared for it
match clause.kind().skip_binder() {
ty::ClauseKind::Trait(t) => {
- wf.compute_trait_pred(t, Elaborate::None);
+ wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
}
ty::ClauseKind::HostEffect(..) => {
// Technically the well-formedness of this predicate is implied by
@@ -179,22 +185,22 @@ pub fn clause_obligations<'tcx>(
}
ty::ClauseKind::RegionOutlives(..) => {}
ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
- wf.compute(ty.into());
+ wf.add_wf_preds_for_generic_arg(ty.into());
}
ty::ClauseKind::Projection(t) => {
- wf.compute_alias_term(t.projection_term);
- wf.compute(t.term.into_arg());
+ wf.add_wf_preds_for_alias_term(t.projection_term);
+ wf.add_wf_preds_for_generic_arg(t.term.into_arg());
}
ty::ClauseKind::ConstArgHasType(ct, ty) => {
- wf.compute(ct.into());
- wf.compute(ty.into());
+ wf.add_wf_preds_for_generic_arg(ct.into());
+ wf.add_wf_preds_for_generic_arg(ty.into());
}
ty::ClauseKind::WellFormed(arg) => {
- wf.compute(arg);
+ wf.add_wf_preds_for_generic_arg(arg);
}
ty::ClauseKind::ConstEvaluatable(ct) => {
- wf.compute(ct.into());
+ wf.add_wf_preds_for_generic_arg(ct.into());
}
}
@@ -372,14 +378,18 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
}
/// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
- fn compute_trait_pred(&mut self, trait_pred: ty::TraitPredicate<'tcx>, elaborate: Elaborate) {
+ fn add_wf_preds_for_trait_pred(
+ &mut self,
+ trait_pred: ty::TraitPredicate<'tcx>,
+ elaborate: Elaborate,
+ ) {
let tcx = self.tcx();
let trait_ref = trait_pred.trait_ref;
// Negative trait predicates don't require supertraits to hold, just
// that their args are WF.
if trait_pred.polarity == ty::PredicatePolarity::Negative {
- self.compute_negative_trait_pred(trait_ref);
+ self.add_wf_preds_for_negative_trait_pred(trait_ref);
return;
}
@@ -445,15 +455,15 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
// Compute the obligations that are required for `trait_ref` to be WF,
// given that it is a *negative* trait predicate.
- fn compute_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
+ fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
for arg in trait_ref.args {
- self.compute(arg);
+ self.add_wf_preds_for_generic_arg(arg);
}
}
/// Pushes the obligations required for an alias (except inherent) to be WF
/// into `self.out`.
- fn compute_alias_term(&mut self, data: ty::AliasTerm<'tcx>) {
+ fn add_wf_preds_for_alias_term(&mut self, data: ty::AliasTerm<'tcx>) {
// A projection is well-formed if
//
// (a) its predicates hold (*)
@@ -478,13 +488,13 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
let obligations = self.nominal_obligations(data.def_id, data.args);
self.out.extend(obligations);
- self.compute_projection_args(data.args);
+ self.add_wf_preds_for_projection_args(data.args);
}
/// Pushes the obligations required for an inherent alias to be WF
/// into `self.out`.
// FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
- fn compute_inherent_projection(&mut self, data: ty::AliasTy<'tcx>) {
+ fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTy<'tcx>) {
// An inherent projection is well-formed if
//
// (a) its predicates hold (*)
@@ -511,7 +521,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
data.args.visit_with(self);
}
- fn compute_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
+ fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
let tcx = self.tcx();
let cause = self.cause(ObligationCauseCode::WellFormed(None));
let param_env = self.param_env;
@@ -557,7 +567,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
/// Pushes all the predicates needed to validate that `ty` is WF into `out`.
#[instrument(level = "debug", skip(self))]
- fn compute(&mut self, arg: GenericArg<'tcx>) {
+ fn add_wf_preds_for_generic_arg(&mut self, arg: GenericArg<'tcx>) {
arg.visit_with(self);
debug!(?self.out);
}
@@ -596,7 +606,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
.collect()
}
- fn from_object_ty(
+ fn add_wf_preds_for_dyn_ty(
&mut self,
ty: Ty<'tcx>,
data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
@@ -651,6 +661,13 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
outlives,
));
}
+
+ // We don't add any wf predicates corresponding to the trait ref's generic arguments
+ // which allows code like this to compile:
+ // ```rust
+ // trait Trait<T: Sized> {}
+ // fn foo(_: &dyn Trait<[u32]>) {}
+ // ```
}
}
}
@@ -761,7 +778,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
self.out.extend(obligations);
}
ty::Alias(ty::Inherent, data) => {
- self.compute_inherent_projection(data);
+ self.add_wf_preds_for_inherent_projection(data);
return; // Subtree handled by compute_inherent_projection.
}
@@ -895,7 +912,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
//
// Here, we defer WF checking due to higher-ranked
// regions. This is perhaps not ideal.
- self.from_object_ty(t, data, r);
+ self.add_wf_preds_for_dyn_ty(t, data, r);
// FIXME(#27579) RFC also considers adding trait
// obligations that don't refer to Self and
@@ -917,11 +934,11 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
// 1. Check if they have been resolved, and if so proceed with
// THAT type.
// 2. If not, we've at least simplified things (e.g., we went
- // from `Vec<$0>: WF` to `$0: WF`), so we can
+ // from `Vec?0>: WF` to `?0: WF`), so we can
// register a pending obligation and keep
// moving. (Goal is that an "inductive hypothesis"
// is satisfied to ensure termination.)
- // See also the comment on `fn obligations`, describing "livelock"
+ // See also the comment on `fn obligations`, describing cycle
// prevention, which happens before this can be reached.
ty::Infer(_) => {
let cause = self.cause(ObligationCauseCode::WellFormed(None));
| diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs
index 54b6c22b2d821..cad7e42fd8212 100644
--- a/compiler/rustc_trait_selection/src/traits/wf.rs
+++ b/compiler/rustc_trait_selection/src/traits/wf.rs
@@ -1,3 +1,8 @@
+//! Core logic responsible for determining what it means for various type system
+//! primitives to be "well formed". Actually checking whether these primitives are
+//! well formed is performed elsewhere (e.g. during type checking or item well formedness
+//! checking).
use std::iter;
use rustc_hir as hir;
@@ -15,12 +20,13 @@ use tracing::{debug, instrument, trace};
use crate::infer::InferCtxt;
use crate::traits;
/// Returns the set of obligations needed to make `arg` well-formed.
/// If `arg` contains unresolved inference variables, this may include
/// further WF obligations. However, if `arg` IS an unresolved
/// inference variable, returns `None`, because we are not able to
-/// make any progress at all. This is to prevent "livelock" where we
-/// say "$0 is WF if $0 is WF".
+/// make any progress at all. This is to prevent cycles where we
+/// say "?0 is WF if ?0 is WF".
pub fn obligations<'tcx>(
infcx: &InferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
@@ -29,14 +35,14 @@ pub fn obligations<'tcx>(
arg: GenericArg<'tcx>,
span: Span,
) -> Option<PredicateObligations<'tcx>> {
- // Handle the "livelock" case (see comment above) by bailing out if necessary.
+ // Handle the "cycle" case (see comment above) by bailing out if necessary.
let arg = match arg.unpack() {
GenericArgKind::Type(ty) => {
match ty.kind() {
ty::Infer(ty::TyVar(_)) => {
let resolved_ty = infcx.shallow_resolve(ty);
if resolved_ty == ty {
- // No progress, bail out to prevent "livelock".
resolved_ty
@@ -51,7 +57,7 @@ pub fn obligations<'tcx>(
ty::ConstKind::Infer(_) => {
let resolved = infcx.shallow_resolve_const(ct);
if resolved == ct {
resolved
@@ -74,7 +80,7 @@ pub fn obligations<'tcx>(
recursion_depth,
debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
let result = wf.normalize(infcx);
@@ -97,7 +103,7 @@ pub fn unnormalized_obligations<'tcx>(
// However, if `arg` IS an unresolved inference variable, returns `None`,
// because we are not able to make any progress at all. This is to prevent
- // "livelock" where we say "$0 is WF if $0 is WF".
+ // cycles where we say "?0 is WF if ?0 is WF".
if arg.is_non_region_infer() {
return None;
@@ -115,7 +121,7 @@ pub fn unnormalized_obligations<'tcx>(
Some(wf.out)
@@ -140,7 +146,7 @@ pub fn trait_obligations<'tcx>(
item: Some(item),
+ wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
debug!(obligations = ?wf.out);
wf.normalize(infcx)
@@ -171,7 +177,7 @@ pub fn clause_obligations<'tcx>(
// It's ok to skip the binder here because wf code is prepared for it
match clause.kind().skip_binder() {
ty::ClauseKind::Trait(t) => {
- wf.compute_trait_pred(t, Elaborate::None);
+ wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
ty::ClauseKind::HostEffect(..) => {
// Technically the well-formedness of this predicate is implied by
@@ -179,22 +185,22 @@ pub fn clause_obligations<'tcx>(
ty::ClauseKind::RegionOutlives(..) => {}
ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
ty::ClauseKind::Projection(t) => {
- wf.compute_alias_term(t.projection_term);
- wf.compute(t.term.into_arg());
+ wf.add_wf_preds_for_generic_arg(t.term.into_arg());
ty::ClauseKind::ConstArgHasType(ct, ty) => {
ty::ClauseKind::WellFormed(arg) => {
- wf.compute(arg);
+ wf.add_wf_preds_for_generic_arg(arg);
ty::ClauseKind::ConstEvaluatable(ct) => {
@@ -372,14 +378,18 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
/// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
- fn compute_trait_pred(&mut self, trait_pred: ty::TraitPredicate<'tcx>, elaborate: Elaborate) {
+ fn add_wf_preds_for_trait_pred(
+ &mut self,
+ trait_pred: ty::TraitPredicate<'tcx>,
+ elaborate: Elaborate,
+ ) {
let trait_ref = trait_pred.trait_ref;
// Negative trait predicates don't require supertraits to hold, just
// that their args are WF.
if trait_pred.polarity == ty::PredicatePolarity::Negative {
- self.compute_negative_trait_pred(trait_ref);
+ self.add_wf_preds_for_negative_trait_pred(trait_ref);
return;
@@ -445,15 +455,15 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
// Compute the obligations that are required for `trait_ref` to be WF,
// given that it is a *negative* trait predicate.
- fn compute_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
+ fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
for arg in trait_ref.args {
- self.compute(arg);
+ self.add_wf_preds_for_generic_arg(arg);
/// Pushes the obligations required for an alias (except inherent) to be WF
- fn compute_alias_term(&mut self, data: ty::AliasTerm<'tcx>) {
+ fn add_wf_preds_for_alias_term(&mut self, data: ty::AliasTerm<'tcx>) {
// A projection is well-formed if
@@ -478,13 +488,13 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
let obligations = self.nominal_obligations(data.def_id, data.args);
self.out.extend(obligations);
- self.compute_projection_args(data.args);
+ self.add_wf_preds_for_projection_args(data.args);
/// Pushes the obligations required for an inherent alias to be WF
// FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
- fn compute_inherent_projection(&mut self, data: ty::AliasTy<'tcx>) {
+ fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTy<'tcx>) {
// An inherent projection is well-formed if
@@ -511,7 +521,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
data.args.visit_with(self);
- fn compute_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
+ fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
let cause = self.cause(ObligationCauseCode::WellFormed(None));
let param_env = self.param_env;
@@ -557,7 +567,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
/// Pushes all the predicates needed to validate that `ty` is WF into `out`.
#[instrument(level = "debug", skip(self))]
- fn compute(&mut self, arg: GenericArg<'tcx>) {
+ fn add_wf_preds_for_generic_arg(&mut self, arg: GenericArg<'tcx>) {
arg.visit_with(self);
debug!(?self.out);
@@ -596,7 +606,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
.collect()
+ fn add_wf_preds_for_dyn_ty(
&mut self,
ty: Ty<'tcx>,
data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
@@ -651,6 +661,13 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
outlives,
));
+ // which allows code like this to compile:
+ // ```rust
+ // fn foo(_: &dyn Trait<[u32]>) {}
+ // ```
@@ -761,7 +778,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
self.out.extend(obligations);
ty::Alias(ty::Inherent, data) => {
- self.compute_inherent_projection(data);
+ self.add_wf_preds_for_inherent_projection(data);
return; // Subtree handled by compute_inherent_projection.
@@ -895,7 +912,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
//
// Here, we defer WF checking due to higher-ranked
// regions. This is perhaps not ideal.
- self.from_object_ty(t, data, r);
+ self.add_wf_preds_for_dyn_ty(t, data, r);
// FIXME(#27579) RFC also considers adding trait
// obligations that don't refer to Self and
@@ -917,11 +934,11 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
// 1. Check if they have been resolved, and if so proceed with
// THAT type.
// 2. If not, we've at least simplified things (e.g., we went
- // from `Vec<$0>: WF` to `$0: WF`), so we can
+ // from `Vec?0>: WF` to `?0: WF`), so we can
// register a pending obligation and keep
// moving. (Goal is that an "inductive hypothesis"
// is satisfied to ensure termination.)
- // See also the comment on `fn obligations`, describing "livelock"
+ // See also the comment on `fn obligations`, describing cycle
// prevention, which happens before this can be reached.
ty::Infer(_) => {
let cause = self.cause(ObligationCauseCode::WellFormed(None)); | [
"- // No progress.",
"- wf.compute_trait_pred(trait_pred, Elaborate::All);",
"+ wf.add_wf_preds_for_alias_term(t.projection_term);",
"- fn from_object_ty(",
"+ // We don't add any wf predicates corresponding to the trait ref's generic arguments",
"+ // trait Trait<T: Sized> {}"
] | [
50,
86,
110,
208,
218,
221
] | {
"additions": 48,
"author": "BoxyUwU",
"deletions": 31,
"html_url": "https://github.com/rust-lang/rust/pull/140186",
"issue_id": 140186,
"merged_at": "2025-04-24T15:17:06Z",
"omission_probability": 0.1,
"pr_number": 140186,
"repo": "rust-lang/rust",
"title": "Rename `compute_x` methods",
"total_changes": 79
} |
135 | diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs
index d3d1eebc22753..2d08c3709a5ce 100644
--- a/library/core/src/num/f128.rs
+++ b/library/core/src/num/f128.rs
@@ -801,7 +801,7 @@ impl f128 {
}
}
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// This returns NaN when *either* argument is NaN or if a combination of
/// +inf and -inf is provided as arguments.
@@ -818,6 +818,7 @@ impl f128 {
/// # }
/// ```
#[inline]
+ #[doc(alias = "average")]
#[unstable(feature = "f128", issue = "116909")]
#[rustc_const_unstable(feature = "f128", issue = "116909")]
pub const fn midpoint(self, other: f128) -> f128 {
diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs
index dceb30177e668..4430f0a4ac479 100644
--- a/library/core/src/num/f16.rs
+++ b/library/core/src/num/f16.rs
@@ -789,7 +789,7 @@ impl f16 {
}
}
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// This returns NaN when *either* argument is NaN or if a combination of
/// +inf and -inf is provided as arguments.
@@ -805,6 +805,7 @@ impl f16 {
/// # }
/// ```
#[inline]
+ #[doc(alias = "average")]
#[unstable(feature = "f16", issue = "116909")]
#[rustc_const_unstable(feature = "f16", issue = "116909")]
pub const fn midpoint(self, other: f16) -> f16 {
diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs
index c97dbfb63ae17..ffb389062df4d 100644
--- a/library/core/src/num/f32.rs
+++ b/library/core/src/num/f32.rs
@@ -983,7 +983,7 @@ impl f32 {
}
}
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// This returns NaN when *either* argument is NaN or if a combination of
/// +inf and -inf is provided as arguments.
@@ -995,6 +995,7 @@ impl f32 {
/// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
/// ```
#[inline]
+ #[doc(alias = "average")]
#[stable(feature = "num_midpoint", since = "1.85.0")]
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
pub const fn midpoint(self, other: f32) -> f32 {
diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs
index 91affdb3794b0..3bfb1ef110d5f 100644
--- a/library/core/src/num/f64.rs
+++ b/library/core/src/num/f64.rs
@@ -1001,7 +1001,7 @@ impl f64 {
}
}
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// This returns NaN when *either* argument is NaN or if a combination of
/// +inf and -inf is provided as arguments.
@@ -1013,6 +1013,7 @@ impl f64 {
/// assert_eq!((-5.5f64).midpoint(8.0), 1.25);
/// ```
#[inline]
+ #[doc(alias = "average")]
#[stable(feature = "num_midpoint", since = "1.85.0")]
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
pub const fn midpoint(self, other: f64) -> f64 {
diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs
index 348457e2c00f6..ecc1c7bf9021d 100644
--- a/library/core/src/num/mod.rs
+++ b/library/core/src/num/mod.rs
@@ -130,7 +130,7 @@ depending on the target pointer size.
macro_rules! midpoint_impl {
($SelfT:ty, unsigned) => {
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large unsigned integral type. This implies that the result is
@@ -146,6 +146,8 @@ macro_rules! midpoint_impl {
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
+ #[doc(alias = "average_floor")]
+ #[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
// Use the well known branchless algorithm from Hacker's Delight to compute
@@ -154,7 +156,7 @@ macro_rules! midpoint_impl {
}
};
($SelfT:ty, signed) => {
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
@@ -173,6 +175,9 @@ macro_rules! midpoint_impl {
#[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
+ #[doc(alias = "average_floor")]
+ #[doc(alias = "average_ceil")]
+ #[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: Self) -> Self {
// Use the well known branchless algorithm from Hacker's Delight to compute
@@ -184,7 +189,7 @@ macro_rules! midpoint_impl {
}
};
($SelfT:ty, $WideT:ty, unsigned) => {
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large unsigned integral type. This implies that the result is
@@ -200,13 +205,15 @@ macro_rules! midpoint_impl {
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
+ #[doc(alias = "average_floor")]
+ #[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
((self as $WideT + rhs as $WideT) / 2) as $SelfT
}
};
($SelfT:ty, $WideT:ty, signed) => {
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
@@ -225,6 +232,9 @@ macro_rules! midpoint_impl {
#[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
+ #[doc(alias = "average_floor")]
+ #[doc(alias = "average_ceil")]
+ #[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
((self as $WideT + rhs as $WideT) / 2) as $SelfT
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs
index 1b79112aec1fe..8a8b2733d5e88 100644
--- a/library/core/src/num/nonzero.rs
+++ b/library/core/src/num/nonzero.rs
@@ -1589,7 +1589,7 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
super::int_log10::$Int(self.get())
}
- /// Calculates the middle point of `self` and `rhs`.
+ /// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
@@ -1615,6 +1615,8 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
+ #[doc(alias = "average_floor")]
+ #[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: Self) -> Self {
// SAFETY: The only way to get `0` with midpoint is to have two opposite or
| diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs
index d3d1eebc22753..2d08c3709a5ce 100644
--- a/library/core/src/num/f128.rs
+++ b/library/core/src/num/f128.rs
@@ -801,7 +801,7 @@ impl f128 {
@@ -818,6 +818,7 @@ impl f128 {
#[unstable(feature = "f128", issue = "116909")]
#[rustc_const_unstable(feature = "f128", issue = "116909")]
pub const fn midpoint(self, other: f128) -> f128 {
diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs
index dceb30177e668..4430f0a4ac479 100644
--- a/library/core/src/num/f16.rs
+++ b/library/core/src/num/f16.rs
@@ -789,7 +789,7 @@ impl f16 {
@@ -805,6 +805,7 @@ impl f16 {
#[unstable(feature = "f16", issue = "116909")]
#[rustc_const_unstable(feature = "f16", issue = "116909")]
pub const fn midpoint(self, other: f16) -> f16 {
diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs
index c97dbfb63ae17..ffb389062df4d 100644
--- a/library/core/src/num/f32.rs
+++ b/library/core/src/num/f32.rs
@@ -983,7 +983,7 @@ impl f32 {
@@ -995,6 +995,7 @@ impl f32 {
/// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
pub const fn midpoint(self, other: f32) -> f32 {
diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs
index 91affdb3794b0..3bfb1ef110d5f 100644
--- a/library/core/src/num/f64.rs
+++ b/library/core/src/num/f64.rs
@@ -1001,7 +1001,7 @@ impl f64 {
@@ -1013,6 +1013,7 @@ impl f64 {
/// assert_eq!((-5.5f64).midpoint(8.0), 1.25);
pub const fn midpoint(self, other: f64) -> f64 {
diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs
index 348457e2c00f6..ecc1c7bf9021d 100644
--- a/library/core/src/num/mod.rs
+++ b/library/core/src/num/mod.rs
@@ -130,7 +130,7 @@ depending on the target pointer size.
macro_rules! midpoint_impl {
($SelfT:ty, unsigned) => {
@@ -146,6 +146,8 @@ macro_rules! midpoint_impl {
@@ -154,7 +156,7 @@ macro_rules! midpoint_impl {
($SelfT:ty, signed) => {
@@ -173,6 +175,9 @@ macro_rules! midpoint_impl {
@@ -184,7 +189,7 @@ macro_rules! midpoint_impl {
($SelfT:ty, $WideT:ty, unsigned) => {
@@ -200,13 +205,15 @@ macro_rules! midpoint_impl {
($SelfT:ty, $WideT:ty, signed) => {
@@ -225,6 +232,9 @@ macro_rules! midpoint_impl {
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs
index 1b79112aec1fe..8a8b2733d5e88 100644
--- a/library/core/src/num/nonzero.rs
+++ b/library/core/src/num/nonzero.rs
@@ -1589,7 +1589,7 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
super::int_log10::$Int(self.get())
/// `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a
@@ -1615,6 +1615,8 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
// SAFETY: The only way to get `0` with midpoint is to have two opposite or | [] | [] | {
"additions": 25,
"author": "Urgau",
"deletions": 9,
"html_url": "https://github.com/rust-lang/rust/pull/140075",
"issue_id": 140075,
"merged_at": "2025-04-24T15:17:07Z",
"omission_probability": 0.1,
"pr_number": 140075,
"repo": "rust-lang/rust",
"title": "Mention average in midpoint documentations",
"total_changes": 34
} |
136 | diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs
index 7bd1300f34ed7..8ce436bade867 100644
--- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs
+++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs
@@ -1298,18 +1298,6 @@ where
return true;
}
- // We don't consider a trait-bound global if it has a projection bound.
- //
- // See ui/traits/next-solver/normalization-shadowing/global-trait-with-project.rs
- // for an example where this is necessary.
- for p in goal.param_env.caller_bounds().iter() {
- if let ty::ClauseKind::Projection(proj) = p.kind().skip_binder() {
- if proj.projection_term.trait_ref(self.cx()) == trait_pred.trait_ref {
- return true;
- }
- }
- }
-
false
}
_ => false,
diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
index cf6d2bc151fb0..00101010f14fa 100644
--- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
+++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
@@ -240,8 +240,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
if !drcx.args_may_unify(obligation_args, bound_trait_ref.skip_binder().args) {
continue;
}
- // FIXME(oli-obk): it is suspicious that we are dropping the constness and
- // polarity here.
let wc = self.where_clause_may_apply(stack, bound_trait_ref)?;
if wc.may_apply() {
candidates.vec.push(ParamCandidate(bound));
| diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs
index 7bd1300f34ed7..8ce436bade867 100644
--- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs
+++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs
@@ -1298,18 +1298,6 @@ where
return true;
}
- // We don't consider a trait-bound global if it has a projection bound.
- //
- // See ui/traits/next-solver/normalization-shadowing/global-trait-with-project.rs
- // for an example where this is necessary.
- if let ty::ClauseKind::Projection(proj) = p.kind().skip_binder() {
- if proj.projection_term.trait_ref(self.cx()) == trait_pred.trait_ref {
- return true;
- }
- }
- }
-
false
_ => false,
diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
index cf6d2bc151fb0..00101010f14fa 100644
--- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
+++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
@@ -240,8 +240,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
if !drcx.args_may_unify(obligation_args, bound_trait_ref.skip_binder().args) {
continue;
- // FIXME(oli-obk): it is suspicious that we are dropping the constness and
- // polarity here.
let wc = self.where_clause_may_apply(stack, bound_trait_ref)?;
if wc.may_apply() {
candidates.vec.push(ParamCandidate(bound)); | [
"- for p in goal.param_env.caller_bounds().iter() {"
] | [
12
] | {
"additions": 0,
"author": "compiler-errors",
"deletions": 14,
"html_url": "https://github.com/rust-lang/rust/pull/140214",
"issue_id": 140214,
"merged_at": "2025-04-24T15:17:07Z",
"omission_probability": 0.1,
"pr_number": 140214,
"repo": "rust-lang/rust",
"title": "Remove comment about handling non-global where bounds with corresponding projection",
"total_changes": 14
} |
137 | diff --git a/compiler/rustc_macros/src/diagnostics/mod.rs b/compiler/rustc_macros/src/diagnostics/mod.rs
index 91398f1a9da9d..55228248188e5 100644
--- a/compiler/rustc_macros/src/diagnostics/mod.rs
+++ b/compiler/rustc_macros/src/diagnostics/mod.rs
@@ -55,8 +55,7 @@ use synstructure::Structure;
///
/// See rustc dev guide for more examples on using the `#[derive(Diagnostic)]`:
/// <https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html>
-pub(super) fn diagnostic_derive(mut s: Structure<'_>) -> TokenStream {
- s.underscore_const(true);
+pub(super) fn diagnostic_derive(s: Structure<'_>) -> TokenStream {
DiagnosticDerive::new(s).into_tokens()
}
@@ -102,8 +101,7 @@ pub(super) fn diagnostic_derive(mut s: Structure<'_>) -> TokenStream {
///
/// See rustc dev guide for more examples on using the `#[derive(LintDiagnostic)]`:
/// <https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html#reference>
-pub(super) fn lint_diagnostic_derive(mut s: Structure<'_>) -> TokenStream {
- s.underscore_const(true);
+pub(super) fn lint_diagnostic_derive(s: Structure<'_>) -> TokenStream {
LintDiagnosticDerive::new(s).into_tokens()
}
@@ -153,7 +151,6 @@ pub(super) fn lint_diagnostic_derive(mut s: Structure<'_>) -> TokenStream {
///
/// diag.subdiagnostic(RawIdentifierSuggestion { span, applicability, ident });
/// ```
-pub(super) fn subdiagnostic_derive(mut s: Structure<'_>) -> TokenStream {
- s.underscore_const(true);
+pub(super) fn subdiagnostic_derive(s: Structure<'_>) -> TokenStream {
SubdiagnosticDerive::new().into_tokens(s)
}
diff --git a/compiler/rustc_macros/src/hash_stable.rs b/compiler/rustc_macros/src/hash_stable.rs
index 6b3210cad7be6..a6396ba687d11 100644
--- a/compiler/rustc_macros/src/hash_stable.rs
+++ b/compiler/rustc_macros/src/hash_stable.rs
@@ -74,8 +74,6 @@ fn hash_stable_derive_with_mode(
HashStableMode::Generic | HashStableMode::NoContext => parse_quote!(__CTX),
};
- s.underscore_const(true);
-
// no_context impl is able to derive by-field, which is closer to a perfect derive.
s.add_bounds(match mode {
HashStableMode::Normal | HashStableMode::Generic => synstructure::AddBounds::Generics,
diff --git a/compiler/rustc_macros/src/lift.rs b/compiler/rustc_macros/src/lift.rs
index 341447f7e6f26..03ea396a42c75 100644
--- a/compiler/rustc_macros/src/lift.rs
+++ b/compiler/rustc_macros/src/lift.rs
@@ -4,7 +4,6 @@ use syn::parse_quote;
pub(super) fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream {
s.add_bounds(synstructure::AddBounds::Generics);
s.bind_with(|_| synstructure::BindStyle::Move);
- s.underscore_const(true);
let tcx: syn::Lifetime = parse_quote!('tcx);
let newtcx: syn::GenericParam = parse_quote!('__lifted);
diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs
index 673e6cd618ff8..c7aaaf0da4679 100644
--- a/compiler/rustc_macros/src/serialize.rs
+++ b/compiler/rustc_macros/src/serialize.rs
@@ -12,7 +12,6 @@ pub(super) fn type_decodable_derive(
let decoder_ty = quote! { __D };
s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_middle::ty::codec::TyDecoder<'tcx> });
s.add_bounds(synstructure::AddBounds::Fields);
- s.underscore_const(true);
decodable_body(s, decoder_ty)
}
@@ -26,7 +25,6 @@ pub(super) fn meta_decodable_derive(
s.add_impl_generic(parse_quote! { '__a });
let decoder_ty = quote! { DecodeContext<'__a, 'tcx> };
s.add_bounds(synstructure::AddBounds::Generics);
- s.underscore_const(true);
decodable_body(s, decoder_ty)
}
@@ -35,7 +33,6 @@ pub(super) fn decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro
let decoder_ty = quote! { __D };
s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_span::SpanDecoder });
s.add_bounds(synstructure::AddBounds::Generics);
- s.underscore_const(true);
decodable_body(s, decoder_ty)
}
@@ -46,13 +43,12 @@ pub(super) fn decodable_nocontext_derive(
let decoder_ty = quote! { __D };
s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_serialize::Decoder });
s.add_bounds(synstructure::AddBounds::Fields);
- s.underscore_const(true);
decodable_body(s, decoder_ty)
}
fn decodable_body(
- mut s: synstructure::Structure<'_>,
+ s: synstructure::Structure<'_>,
decoder_ty: TokenStream,
) -> proc_macro2::TokenStream {
if let syn::Data::Union(_) = s.ast().data {
@@ -98,7 +94,6 @@ fn decodable_body(
}
}
};
- s.underscore_const(true);
s.bound_impl(
quote!(::rustc_serialize::Decodable<#decoder_ty>),
@@ -133,7 +128,6 @@ pub(super) fn type_encodable_derive(
}
s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_middle::ty::codec::TyEncoder<'tcx> });
s.add_bounds(synstructure::AddBounds::Fields);
- s.underscore_const(true);
encodable_body(s, encoder_ty, false)
}
@@ -147,7 +141,6 @@ pub(super) fn meta_encodable_derive(
s.add_impl_generic(parse_quote! { '__a });
let encoder_ty = quote! { EncodeContext<'__a, 'tcx> };
s.add_bounds(synstructure::AddBounds::Generics);
- s.underscore_const(true);
encodable_body(s, encoder_ty, true)
}
@@ -156,7 +149,6 @@ pub(super) fn encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro
let encoder_ty = quote! { __E };
s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_span::SpanEncoder });
s.add_bounds(synstructure::AddBounds::Generics);
- s.underscore_const(true);
encodable_body(s, encoder_ty, false)
}
@@ -167,7 +159,6 @@ pub(super) fn encodable_nocontext_derive(
let encoder_ty = quote! { __E };
s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_serialize::Encoder });
s.add_bounds(synstructure::AddBounds::Fields);
- s.underscore_const(true);
encodable_body(s, encoder_ty, false)
}
@@ -181,7 +172,6 @@ fn encodable_body(
panic!("cannot derive on union")
}
- s.underscore_const(true);
s.bind_with(|binding| {
// Handle the lack of a blanket reference impl.
if let syn::Type::Reference(_) = binding.ast().ty {
diff --git a/compiler/rustc_macros/src/type_foldable.rs b/compiler/rustc_macros/src/type_foldable.rs
index 85051311bee9e..91b747f18569d 100644
--- a/compiler/rustc_macros/src/type_foldable.rs
+++ b/compiler/rustc_macros/src/type_foldable.rs
@@ -6,8 +6,6 @@ pub(super) fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_m
panic!("cannot derive on union")
}
- s.underscore_const(true);
-
if !s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") {
s.add_impl_generic(parse_quote! { 'tcx });
}
diff --git a/compiler/rustc_macros/src/type_visitable.rs b/compiler/rustc_macros/src/type_visitable.rs
index fb37e1a39edbe..f99c5113a6053 100644
--- a/compiler/rustc_macros/src/type_visitable.rs
+++ b/compiler/rustc_macros/src/type_visitable.rs
@@ -8,8 +8,6 @@ pub(super) fn type_visitable_derive(
panic!("cannot derive on union")
}
- s.underscore_const(true);
-
// ignore fields with #[type_visitable(ignore)]
s.filter(|bi| {
let mut ignored = false;
| diff --git a/compiler/rustc_macros/src/diagnostics/mod.rs b/compiler/rustc_macros/src/diagnostics/mod.rs
index 91398f1a9da9d..55228248188e5 100644
--- a/compiler/rustc_macros/src/diagnostics/mod.rs
+++ b/compiler/rustc_macros/src/diagnostics/mod.rs
@@ -55,8 +55,7 @@ use synstructure::Structure;
/// See rustc dev guide for more examples on using the `#[derive(Diagnostic)]`:
/// <https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html>
-pub(super) fn diagnostic_derive(mut s: Structure<'_>) -> TokenStream {
+pub(super) fn diagnostic_derive(s: Structure<'_>) -> TokenStream {
DiagnosticDerive::new(s).into_tokens()
@@ -102,8 +101,7 @@ pub(super) fn diagnostic_derive(mut s: Structure<'_>) -> TokenStream {
/// See rustc dev guide for more examples on using the `#[derive(LintDiagnostic)]`:
/// <https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html#reference>
-pub(super) fn lint_diagnostic_derive(mut s: Structure<'_>) -> TokenStream {
+pub(super) fn lint_diagnostic_derive(s: Structure<'_>) -> TokenStream {
LintDiagnosticDerive::new(s).into_tokens()
@@ -153,7 +151,6 @@ pub(super) fn lint_diagnostic_derive(mut s: Structure<'_>) -> TokenStream {
/// diag.subdiagnostic(RawIdentifierSuggestion { span, applicability, ident });
/// ```
-pub(super) fn subdiagnostic_derive(mut s: Structure<'_>) -> TokenStream {
+pub(super) fn subdiagnostic_derive(s: Structure<'_>) -> TokenStream {
SubdiagnosticDerive::new().into_tokens(s)
diff --git a/compiler/rustc_macros/src/hash_stable.rs b/compiler/rustc_macros/src/hash_stable.rs
index 6b3210cad7be6..a6396ba687d11 100644
--- a/compiler/rustc_macros/src/hash_stable.rs
+++ b/compiler/rustc_macros/src/hash_stable.rs
@@ -74,8 +74,6 @@ fn hash_stable_derive_with_mode(
HashStableMode::Generic | HashStableMode::NoContext => parse_quote!(__CTX),
// no_context impl is able to derive by-field, which is closer to a perfect derive.
s.add_bounds(match mode {
HashStableMode::Normal | HashStableMode::Generic => synstructure::AddBounds::Generics,
diff --git a/compiler/rustc_macros/src/lift.rs b/compiler/rustc_macros/src/lift.rs
index 341447f7e6f26..03ea396a42c75 100644
--- a/compiler/rustc_macros/src/lift.rs
+++ b/compiler/rustc_macros/src/lift.rs
@@ -4,7 +4,6 @@ use syn::parse_quote;
pub(super) fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream {
s.bind_with(|_| synstructure::BindStyle::Move);
let tcx: syn::Lifetime = parse_quote!('tcx);
let newtcx: syn::GenericParam = parse_quote!('__lifted);
diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs
index 673e6cd618ff8..c7aaaf0da4679 100644
--- a/compiler/rustc_macros/src/serialize.rs
+++ b/compiler/rustc_macros/src/serialize.rs
@@ -12,7 +12,6 @@ pub(super) fn type_decodable_derive(
s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_middle::ty::codec::TyDecoder<'tcx> });
@@ -26,7 +25,6 @@ pub(super) fn meta_decodable_derive(
let decoder_ty = quote! { DecodeContext<'__a, 'tcx> };
@@ -35,7 +33,6 @@ pub(super) fn decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro
s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_span::SpanDecoder });
@@ -46,13 +43,12 @@ pub(super) fn decodable_nocontext_derive(
s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_serialize::Decoder });
fn decodable_body(
- mut s: synstructure::Structure<'_>,
+ s: synstructure::Structure<'_>,
decoder_ty: TokenStream,
) -> proc_macro2::TokenStream {
if let syn::Data::Union(_) = s.ast().data {
@@ -98,7 +94,6 @@ fn decodable_body(
}
}
s.bound_impl(
quote!(::rustc_serialize::Decodable<#decoder_ty>),
@@ -133,7 +128,6 @@ pub(super) fn type_encodable_derive(
s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_middle::ty::codec::TyEncoder<'tcx> });
@@ -147,7 +141,6 @@ pub(super) fn meta_encodable_derive(
let encoder_ty = quote! { EncodeContext<'__a, 'tcx> };
encodable_body(s, encoder_ty, true)
@@ -156,7 +149,6 @@ pub(super) fn encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro
s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_span::SpanEncoder });
@@ -167,7 +159,6 @@ pub(super) fn encodable_nocontext_derive(
s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_serialize::Encoder });
@@ -181,7 +172,6 @@ fn encodable_body(
s.bind_with(|binding| {
// Handle the lack of a blanket reference impl.
if let syn::Type::Reference(_) = binding.ast().ty {
diff --git a/compiler/rustc_macros/src/type_foldable.rs b/compiler/rustc_macros/src/type_foldable.rs
index 85051311bee9e..91b747f18569d 100644
--- a/compiler/rustc_macros/src/type_foldable.rs
+++ b/compiler/rustc_macros/src/type_foldable.rs
@@ -6,8 +6,6 @@ pub(super) fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_m
if !s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") {
s.add_impl_generic(parse_quote! { 'tcx });
diff --git a/compiler/rustc_macros/src/type_visitable.rs b/compiler/rustc_macros/src/type_visitable.rs
index fb37e1a39edbe..f99c5113a6053 100644
--- a/compiler/rustc_macros/src/type_visitable.rs
+++ b/compiler/rustc_macros/src/type_visitable.rs
@@ -8,8 +8,6 @@ pub(super) fn type_visitable_derive(
// ignore fields with #[type_visitable(ignore)]
s.filter(|bi| {
let mut ignored = false; | [] | [] | {
"additions": 4,
"author": "nnethercote",
"deletions": 24,
"html_url": "https://github.com/rust-lang/rust/pull/140181",
"issue_id": 140181,
"merged_at": "2025-04-24T12:05:12Z",
"omission_probability": 0.1,
"pr_number": 140181,
"repo": "rust-lang/rust",
"title": "Remove `synstructure::Structure::underscore_const` calls.",
"total_changes": 28
} |
138 | diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs
index 0427feb29550f..4f9259f39c1ab 100644
--- a/library/std/src/os/unix/fs.rs
+++ b/library/std/src/os/unix/fs.rs
@@ -1100,3 +1100,39 @@ pub fn lchown<P: AsRef<Path>>(dir: P, uid: Option<u32>, gid: Option<u32>) -> io:
pub fn chroot<P: AsRef<Path>>(dir: P) -> io::Result<()> {
sys::fs::chroot(dir.as_ref())
}
+
+/// Create a FIFO special file at the specified path with the specified mode.
+///
+/// # Examples
+///
+/// ```no_run
+/// # #![feature(unix_mkfifo)]
+/// # #[cfg(not(unix))]
+/// # fn main() {}
+/// # #[cfg(unix)]
+/// # fn main() -> std::io::Result<()> {
+/// # use std::{
+/// # os::unix::fs::{mkfifo, PermissionsExt},
+/// # fs::{File, Permissions, remove_file},
+/// # io::{Write, Read},
+/// # };
+/// # let _ = remove_file("/tmp/fifo");
+/// mkfifo("/tmp/fifo", Permissions::from_mode(0o774))?;
+///
+/// let mut wx = File::options().read(true).write(true).open("/tmp/fifo")?;
+/// let mut rx = File::open("/tmp/fifo")?;
+///
+/// wx.write_all(b"hello, world!")?;
+/// drop(wx);
+///
+/// let mut s = String::new();
+/// rx.read_to_string(&mut s)?;
+///
+/// assert_eq!(s, "hello, world!");
+/// # Ok(())
+/// # }
+/// ```
+#[unstable(feature = "unix_mkfifo", issue = "139324")]
+pub fn mkfifo<P: AsRef<Path>>(path: P, permissions: Permissions) -> io::Result<()> {
+ sys::fs::mkfifo(path.as_ref(), permissions.mode())
+}
diff --git a/library/std/src/os/unix/fs/tests.rs b/library/std/src/os/unix/fs/tests.rs
index db9621c8c205c..1840bb38c17c8 100644
--- a/library/std/src/os/unix/fs/tests.rs
+++ b/library/std/src/os/unix/fs/tests.rs
@@ -55,3 +55,23 @@ fn write_vectored_at() {
let content = fs::read(&filename).unwrap();
assert_eq!(&content, expected);
}
+
+#[test]
+fn test_mkfifo() {
+ let tmp_dir = crate::test_helpers::tmpdir();
+
+ let fifo = tmp_dir.path().join("fifo");
+
+ mkfifo(&fifo, Permissions::from_mode(0o774)).unwrap();
+
+ let mut wx = fs::File::options().read(true).write(true).open(&fifo).unwrap();
+ let mut rx = fs::File::open(fifo).unwrap();
+
+ wx.write_all(b"hello, world!").unwrap();
+ drop(wx);
+
+ let mut s = String::new();
+ rx.read_to_string(&mut s).unwrap();
+
+ assert_eq!(s, "hello, world!");
+}
diff --git a/library/std/src/sys/fs/mod.rs b/library/std/src/sys/fs/mod.rs
index 3b176d0d16c44..221795077fa67 100644
--- a/library/std/src/sys/fs/mod.rs
+++ b/library/std/src/sys/fs/mod.rs
@@ -9,7 +9,7 @@ cfg_if::cfg_if! {
if #[cfg(target_family = "unix")] {
mod unix;
use unix as imp;
- pub use unix::{chown, fchown, lchown};
+ pub use unix::{chown, fchown, lchown, mkfifo};
#[cfg(not(target_os = "fuchsia"))]
pub use unix::chroot;
pub(crate) use unix::debug_assert_fd_is_open;
diff --git a/library/std/src/sys/fs/unix.rs b/library/std/src/sys/fs/unix.rs
index 87865be0387d5..018e7e98c23e3 100644
--- a/library/std/src/sys/fs/unix.rs
+++ b/library/std/src/sys/fs/unix.rs
@@ -2148,6 +2148,12 @@ pub fn chroot(dir: &Path) -> io::Result<()> {
Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
}
+pub fn mkfifo(path: &Path, mode: u32) -> io::Result<()> {
+ run_path_with_cstr(path, &|path| {
+ cvt(unsafe { libc::mkfifo(path.as_ptr(), mode.try_into().unwrap()) }).map(|_| ())
+ })
+}
+
pub use remove_dir_impl::remove_dir_all;
// Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri
| diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs
index 0427feb29550f..4f9259f39c1ab 100644
--- a/library/std/src/os/unix/fs.rs
+++ b/library/std/src/os/unix/fs.rs
@@ -1100,3 +1100,39 @@ pub fn lchown<P: AsRef<Path>>(dir: P, uid: Option<u32>, gid: Option<u32>) -> io:
pub fn chroot<P: AsRef<Path>>(dir: P) -> io::Result<()> {
sys::fs::chroot(dir.as_ref())
+/// Create a FIFO special file at the specified path with the specified mode.
+/// # Examples
+/// ```no_run
+/// # #![feature(unix_mkfifo)]
+/// # #[cfg(not(unix))]
+/// # #[cfg(unix)]
+/// # fn main() -> std::io::Result<()> {
+/// # os::unix::fs::{mkfifo, PermissionsExt},
+/// # fs::{File, Permissions, remove_file},
+/// # io::{Write, Read},
+/// # };
+/// # let _ = remove_file("/tmp/fifo");
+/// mkfifo("/tmp/fifo", Permissions::from_mode(0o774))?;
+/// let mut wx = File::options().read(true).write(true).open("/tmp/fifo")?;
+/// let mut rx = File::open("/tmp/fifo")?;
+/// wx.write_all(b"hello, world!")?;
+/// drop(wx);
+/// let mut s = String::new();
+/// assert_eq!(s, "hello, world!");
+/// # Ok(())
+/// # }
+/// ```
+#[unstable(feature = "unix_mkfifo", issue = "139324")]
+pub fn mkfifo<P: AsRef<Path>>(path: P, permissions: Permissions) -> io::Result<()> {
+ sys::fs::mkfifo(path.as_ref(), permissions.mode())
diff --git a/library/std/src/os/unix/fs/tests.rs b/library/std/src/os/unix/fs/tests.rs
index db9621c8c205c..1840bb38c17c8 100644
--- a/library/std/src/os/unix/fs/tests.rs
+++ b/library/std/src/os/unix/fs/tests.rs
@@ -55,3 +55,23 @@ fn write_vectored_at() {
let content = fs::read(&filename).unwrap();
assert_eq!(&content, expected);
+#[test]
+fn test_mkfifo() {
+ let tmp_dir = crate::test_helpers::tmpdir();
+ let fifo = tmp_dir.path().join("fifo");
+ mkfifo(&fifo, Permissions::from_mode(0o774)).unwrap();
+ let mut wx = fs::File::options().read(true).write(true).open(&fifo).unwrap();
+ let mut rx = fs::File::open(fifo).unwrap();
+ wx.write_all(b"hello, world!").unwrap();
+ drop(wx);
diff --git a/library/std/src/sys/fs/mod.rs b/library/std/src/sys/fs/mod.rs
index 3b176d0d16c44..221795077fa67 100644
--- a/library/std/src/sys/fs/mod.rs
+++ b/library/std/src/sys/fs/mod.rs
@@ -9,7 +9,7 @@ cfg_if::cfg_if! {
if #[cfg(target_family = "unix")] {
mod unix;
use unix as imp;
- pub use unix::{chown, fchown, lchown};
+ pub use unix::{chown, fchown, lchown, mkfifo};
#[cfg(not(target_os = "fuchsia"))]
pub use unix::chroot;
pub(crate) use unix::debug_assert_fd_is_open;
diff --git a/library/std/src/sys/fs/unix.rs b/library/std/src/sys/fs/unix.rs
index 87865be0387d5..018e7e98c23e3 100644
--- a/library/std/src/sys/fs/unix.rs
+++ b/library/std/src/sys/fs/unix.rs
@@ -2148,6 +2148,12 @@ pub fn chroot(dir: &Path) -> io::Result<()> {
Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
+pub fn mkfifo(path: &Path, mode: u32) -> io::Result<()> {
+ run_path_with_cstr(path, &|path| {
+ cvt(unsafe { libc::mkfifo(path.as_ptr(), mode.try_into().unwrap()) }).map(|_| ())
pub use remove_dir_impl::remove_dir_all;
// Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri | [
"+/// # fn main() {}",
"+/// # use std::{",
"+/// rx.read_to_string(&mut s)?;",
"+ let mut s = String::new();",
"+ rx.read_to_string(&mut s).unwrap();",
"+ assert_eq!(s, \"hello, world!\");",
"+ })"
] | [
16,
19,
34,
67,
68,
70,
96
] | {
"additions": 63,
"author": "NobodyXu",
"deletions": 1,
"html_url": "https://github.com/rust-lang/rust/pull/139450",
"issue_id": 139450,
"merged_at": "2025-04-24T12:05:12Z",
"omission_probability": 0.1,
"pr_number": 139450,
"repo": "rust-lang/rust",
"title": "Impl new API `std::os::unix::fs::mkfifo` under feature `unix_fifo`",
"total_changes": 64
} |
139 | diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs
index a1487ca74be87..da739b0e4532b 100644
--- a/compiler/rustc_ast_passes/src/ast_validation.rs
+++ b/compiler/rustc_ast_passes/src/ast_validation.rs
@@ -334,8 +334,7 @@ impl<'a> AstValidator<'a> {
.filter(|attr| {
let arr = [
sym::allow,
- sym::cfg,
- sym::cfg_attr,
+ sym::cfg_trace,
sym::cfg_attr_trace,
sym::deny,
sym::expect,
diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs
index cdb1817944987..3dbfc191f8f50 100644
--- a/compiler/rustc_ast_pretty/src/pprust/state.rs
+++ b/compiler/rustc_ast_pretty/src/pprust/state.rs
@@ -593,7 +593,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
}
fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) -> bool {
- if attr.has_name(sym::cfg_attr_trace) {
+ if attr.has_name(sym::cfg_trace) || attr.has_name(sym::cfg_attr_trace) {
// It's not a valid identifier, so avoid printing it
// to keep the printed code reasonably parse-able.
return false;
diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs
index ada49eef7b2d9..bcc2703c39b39 100644
--- a/compiler/rustc_expand/src/config.rs
+++ b/compiler/rustc_expand/src/config.rs
@@ -156,6 +156,19 @@ pub fn pre_configure_attrs(sess: &Session, attrs: &[Attribute]) -> ast::AttrVec
.collect()
}
+pub(crate) fn attr_into_trace(mut attr: Attribute, trace_name: Symbol) -> Attribute {
+ match &mut attr.kind {
+ AttrKind::Normal(normal) => {
+ let NormalAttr { item, tokens } = &mut **normal;
+ item.path.segments[0].ident.name = trace_name;
+ // This makes the trace attributes unobservable to token-based proc macros.
+ *tokens = Some(LazyAttrTokenStream::new(AttrTokenStream::default()));
+ }
+ AttrKind::DocComment(..) => unreachable!(),
+ }
+ attr
+}
+
#[macro_export]
macro_rules! configure {
($this:ident, $node:ident) => {
@@ -280,16 +293,7 @@ impl<'a> StripUnconfigured<'a> {
// A trace attribute left in AST in place of the original `cfg_attr` attribute.
// It can later be used by lints or other diagnostics.
- let mut trace_attr = cfg_attr.clone();
- match &mut trace_attr.kind {
- AttrKind::Normal(normal) => {
- let NormalAttr { item, tokens } = &mut **normal;
- item.path.segments[0].ident.name = sym::cfg_attr_trace;
- // This makes the trace attributes unobservable to token-based proc macros.
- *tokens = Some(LazyAttrTokenStream::new(AttrTokenStream::default()));
- }
- AttrKind::DocComment(..) => unreachable!(),
- }
+ let trace_attr = attr_into_trace(cfg_attr.clone(), sym::cfg_attr_trace);
let Some((cfg_predicate, expanded_attrs)) =
rustc_parse::parse_cfg_attr(cfg_attr, &self.sess.psess)
diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs
index d0bd8a89d9bdb..22da1179feb98 100644
--- a/compiler/rustc_expand/src/expand.rs
+++ b/compiler/rustc_expand/src/expand.rs
@@ -33,7 +33,7 @@ use rustc_span::{ErrorGuaranteed, FileName, Ident, LocalExpnId, Span, sym};
use smallvec::SmallVec;
use crate::base::*;
-use crate::config::StripUnconfigured;
+use crate::config::{StripUnconfigured, attr_into_trace};
use crate::errors::{
EmptyDelegationMac, GlobDelegationOutsideImpls, GlobDelegationTraitlessQpath, IncompleteParse,
RecursionLimitReached, RemoveExprNotSupported, RemoveNodeNotSupported, UnsupportedKeyValue,
@@ -2003,7 +2003,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
let attr_name = attr.ident().unwrap().name;
// `#[cfg]` and `#[cfg_attr]` are special - they are
// eagerly evaluated.
- if attr_name != sym::cfg && attr_name != sym::cfg_attr_trace {
+ if attr_name != sym::cfg_trace && attr_name != sym::cfg_attr_trace {
self.cx.sess.psess.buffer_lint(
UNUSED_ATTRIBUTES,
attr.span,
@@ -2027,11 +2027,10 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
) -> (bool, Option<ast::MetaItem>) {
let (res, meta_item) = self.cfg().cfg_true(&attr);
if res {
- // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion,
- // and some tools like rustdoc and clippy rely on that. Find a way to remove them
- // while keeping the tools working.
- self.cx.expanded_inert_attrs.mark(&attr);
- node.visit_attrs(|attrs| attrs.insert(pos, attr));
+ // A trace attribute left in AST in place of the original `cfg` attribute.
+ // It can later be used by lints or other diagnostics.
+ let trace_attr = attr_into_trace(attr, sym::cfg_trace);
+ node.visit_attrs(|attrs| attrs.insert(pos, trace_attr));
}
(res, meta_item)
diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs
index fd936458f1115..6fe65c88f712a 100644
--- a/compiler/rustc_feature/src/builtin_attrs.rs
+++ b/compiler/rustc_feature/src/builtin_attrs.rs
@@ -760,10 +760,14 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
template!(Word, List: r#""...""#), DuplicatesOk,
EncodeCrossCrate::Yes, INTERNAL_UNSTABLE
),
- // Trace that is left when a `cfg_attr` attribute is expanded.
- // The attribute is not gated, to avoid stability errors, but it cannot be used in stable or
- // unstable code directly because `sym::cfg_attr_trace` is not a valid identifier, it can only
- // be generated by the compiler.
+ // Traces that are left when `cfg` and `cfg_attr` attributes are expanded.
+ // The attributes are not gated, to avoid stability errors, but they cannot be used in stable
+ // or unstable code directly because `sym::cfg_(attr_)trace` are not valid identifiers, they
+ // can only be generated by the compiler.
+ ungated!(
+ cfg_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk,
+ EncodeCrossCrate::No
+ ),
ungated!(
cfg_attr_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk,
EncodeCrossCrate::No
diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs
index 9ecde2a9eb504..6bbd650dcdfe3 100644
--- a/compiler/rustc_parse/src/validate_attr.rs
+++ b/compiler/rustc_parse/src/validate_attr.rs
@@ -16,7 +16,8 @@ use rustc_span::{Span, Symbol, sym};
use crate::{errors, parse_in};
pub fn check_attr(psess: &ParseSess, attr: &Attribute) {
- if attr.is_doc_comment() || attr.has_name(sym::cfg_attr_trace) {
+ if attr.is_doc_comment() || attr.has_name(sym::cfg_trace) || attr.has_name(sym::cfg_attr_trace)
+ {
return;
}
@@ -215,11 +216,7 @@ pub fn check_builtin_meta_item(
template: AttributeTemplate,
deny_unsafety: bool,
) {
- // Some special attributes like `cfg` must be checked
- // before the generic check, so we skip them here.
- let should_skip = |name| name == sym::cfg;
-
- if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
+ if !is_attr_template_compatible(&template, &meta.kind) {
emit_malformed_attribute(psess, style, meta.span, name, template);
}
diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs
index 9238c73cdb113..1e1fb42a48fe2 100644
--- a/compiler/rustc_passes/src/check_attr.rs
+++ b/compiler/rustc_passes/src/check_attr.rs
@@ -272,6 +272,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
| sym::forbid
| sym::cfg
| sym::cfg_attr
+ | sym::cfg_trace
| sym::cfg_attr_trace
// need to be fixed
| sym::cfi_encoding // FIXME(cfi_encoding)
@@ -574,8 +575,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
// NOTE: when making changes to this list, check that `error_codes/E0736.md` remains accurate
const ALLOW_LIST: &[rustc_span::Symbol] = &[
// conditional compilation
- sym::cfg,
- sym::cfg_attr,
+ sym::cfg_trace,
sym::cfg_attr_trace,
// testing (allowed here so better errors can be generated in `rustc_builtin_macros::test`)
sym::test,
@@ -2656,7 +2656,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
// only `#[cfg]` and `#[cfg_attr]` are allowed, but it should be removed
// if we allow more attributes (e.g., tool attributes and `allow/deny/warn`)
// in where clauses. After that, only `self.check_attributes` should be enough.
- const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg, sym::cfg_attr, sym::cfg_attr_trace];
+ const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg_trace, sym::cfg_attr_trace];
let spans = self
.tcx
.hir_attrs(where_predicate.hir_id)
diff --git a/compiler/rustc_query_system/src/ich/mod.rs b/compiler/rustc_query_system/src/ich/mod.rs
index 852d93b711f88..25778add60a98 100644
--- a/compiler/rustc_query_system/src/ich/mod.rs
+++ b/compiler/rustc_query_system/src/ich/mod.rs
@@ -8,7 +8,7 @@ mod hcx;
mod impls_syntax;
pub const IGNORED_ATTRIBUTES: &[Symbol] = &[
- sym::cfg,
+ sym::cfg_trace, // FIXME should this really be ignored?
sym::rustc_if_this_changed,
sym::rustc_then_this_would_need,
sym::rustc_dirty,
diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs
index 3e4742439655a..171f553e9c1a3 100644
--- a/compiler/rustc_span/src/symbol.rs
+++ b/compiler/rustc_span/src/symbol.rs
@@ -623,6 +623,7 @@ symbols! {
cfg_target_has_atomic_equal_alignment,
cfg_target_thread_local,
cfg_target_vendor,
+ cfg_trace: "<cfg>", // must not be a valid identifier
cfg_ub_checks,
cfg_version,
cfi,
diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs
index de6dc088176ff..6f660df4d7d45 100644
--- a/src/librustdoc/clean/mod.rs
+++ b/src/librustdoc/clean/mod.rs
@@ -2773,7 +2773,7 @@ fn add_without_unwanted_attributes<'hir>(
if ident == sym::doc {
filter_doc_attr(&mut normal.args, is_inline);
attrs.push((Cow::Owned(attr), import_parent));
- } else if is_inline || ident != sym::cfg {
+ } else if is_inline || ident != sym::cfg_trace {
// If it's not a `cfg()` attribute, we keep it.
attrs.push((Cow::Owned(attr), import_parent));
}
diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs
index 27eb56a9858b8..150b00dbb48a4 100644
--- a/src/librustdoc/clean/types.rs
+++ b/src/librustdoc/clean/types.rs
@@ -1059,7 +1059,7 @@ pub(crate) fn extract_cfg_from_attrs<'a, I: Iterator<Item = &'a hir::Attribute>
// `doc(cfg())` overrides `cfg()`).
attrs
.clone()
- .filter(|attr| attr.has_name(sym::cfg))
+ .filter(|attr| attr.has_name(sym::cfg_trace))
.filter_map(|attr| single(attr.meta_item_list()?))
.filter_map(|attr| Cfg::parse_without(attr.meta_item()?, hidden_cfg).ok().flatten())
.fold(Cfg::True, |cfg, new_cfg| cfg & new_cfg)
diff --git a/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs
index 5c486eb90cc2b..4c84e61b1f26c 100644
--- a/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs
+++ b/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs
@@ -37,7 +37,6 @@ fn check_duplicated_attr(
let Some(ident) = attr.ident() else { return };
let name = ident.name;
if name == sym::doc
- || name == sym::cfg_attr
|| name == sym::cfg_attr_trace
|| name == sym::rustc_on_unimplemented
|| name == sym::reason {
@@ -47,7 +46,7 @@ fn check_duplicated_attr(
return;
}
if let Some(direct_parent) = parent.last()
- && ["cfg", "cfg_attr"].contains(&direct_parent.as_str())
+ && direct_parent == sym::cfg_trace.as_str()
&& [sym::all, sym::not, sym::any].contains(&name)
{
// FIXME: We don't correctly check `cfg`s for now, so if it's more complex than just a one
diff --git a/src/tools/clippy/clippy_lints/src/cfg_not_test.rs b/src/tools/clippy/clippy_lints/src/cfg_not_test.rs
index 84136a2e6c28f..7590fe96fd214 100644
--- a/src/tools/clippy/clippy_lints/src/cfg_not_test.rs
+++ b/src/tools/clippy/clippy_lints/src/cfg_not_test.rs
@@ -32,7 +32,7 @@ declare_lint_pass!(CfgNotTest => [CFG_NOT_TEST]);
impl EarlyLintPass for CfgNotTest {
fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &rustc_ast::Attribute) {
- if attr.has_name(rustc_span::sym::cfg) && contains_not_test(attr.meta_item_list().as_deref(), false) {
+ if attr.has_name(rustc_span::sym::cfg_trace) && contains_not_test(attr.meta_item_list().as_deref(), false) {
span_lint_and_then(
cx,
CFG_NOT_TEST,
diff --git a/src/tools/clippy/clippy_lints/src/methods/is_empty.rs b/src/tools/clippy/clippy_lints/src/methods/is_empty.rs
index 7c190e123b72e..4c81b22861b4c 100644
--- a/src/tools/clippy/clippy_lints/src/methods/is_empty.rs
+++ b/src/tools/clippy/clippy_lints/src/methods/is_empty.rs
@@ -41,7 +41,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &'_ Expr<'_>, receiver: &Expr<'_
fn is_under_cfg(cx: &LateContext<'_>, id: HirId) -> bool {
cx.tcx
.hir_parent_id_iter(id)
- .any(|id| cx.tcx.hir_attrs(id).iter().any(|attr| attr.has_name(sym::cfg)))
+ .any(|id| cx.tcx.hir_attrs(id).iter().any(|attr| attr.has_name(sym::cfg_trace)))
}
/// Similar to [`clippy_utils::expr_or_init`], but does not go up the chain if the initialization
diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs
index 1307ff79bc5dd..668b0cb69e204 100644
--- a/src/tools/clippy/clippy_utils/src/lib.rs
+++ b/src/tools/clippy/clippy_utils/src/lib.rs
@@ -2629,7 +2629,7 @@ pub fn peel_ref_operators<'hir>(cx: &LateContext<'_>, mut expr: &'hir Expr<'hir>
pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
if let Res::Def(_, def_id) = path.res {
- return cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr);
+ return cx.tcx.has_attr(def_id, sym::cfg_trace) || cx.tcx.has_attr(def_id, sym::cfg_attr);
}
}
false
@@ -2699,7 +2699,7 @@ pub fn is_in_test_function(tcx: TyCtxt<'_>, id: HirId) -> bool {
/// use [`is_in_cfg_test`]
pub fn is_cfg_test(tcx: TyCtxt<'_>, id: HirId) -> bool {
tcx.hir_attrs(id).iter().any(|attr| {
- if attr.has_name(sym::cfg)
+ if attr.has_name(sym::cfg_trace)
&& let Some(items) = attr.meta_item_list()
&& let [item] = &*items
&& item.has_name(sym::test)
@@ -2723,11 +2723,11 @@ pub fn is_in_test(tcx: TyCtxt<'_>, hir_id: HirId) -> bool {
/// Checks if the item of any of its parents has `#[cfg(...)]` attribute applied.
pub fn inherits_cfg(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
- tcx.has_attr(def_id, sym::cfg)
+ tcx.has_attr(def_id, sym::cfg_trace)
|| tcx
.hir_parent_iter(tcx.local_def_id_to_hir_id(def_id))
.flat_map(|(parent_id, _)| tcx.hir_attrs(parent_id))
- .any(|attr| attr.has_name(sym::cfg))
+ .any(|attr| attr.has_name(sym::cfg_trace))
}
/// Walks up the HIR tree from the given expression in an attempt to find where the value is
diff --git a/tests/pretty/tests-are-sorted.pp b/tests/pretty/tests-are-sorted.pp
index 31449b51dc3e1..d6a2c0ff9796b 100644
--- a/tests/pretty/tests-are-sorted.pp
+++ b/tests/pretty/tests-are-sorted.pp
@@ -10,7 +10,6 @@
//@ pp-exact:tests-are-sorted.pp
extern crate test;
-#[cfg(test)]
#[rustc_test_marker = "m_test"]
#[doc(hidden)]
pub const m_test: test::TestDescAndFn =
@@ -35,7 +34,6 @@
fn m_test() {}
extern crate test;
-#[cfg(test)]
#[rustc_test_marker = "z_test"]
#[doc(hidden)]
pub const z_test: test::TestDescAndFn =
@@ -61,7 +59,6 @@
fn z_test() {}
extern crate test;
-#[cfg(test)]
#[rustc_test_marker = "a_test"]
#[doc(hidden)]
pub const a_test: test::TestDescAndFn =
diff --git a/tests/ui/conditional-compilation/cfg-attr-syntax-validation.rs b/tests/ui/conditional-compilation/cfg-attr-syntax-validation.rs
index 9a041557c7cc9..416145a0c1560 100644
--- a/tests/ui/conditional-compilation/cfg-attr-syntax-validation.rs
+++ b/tests/ui/conditional-compilation/cfg-attr-syntax-validation.rs
@@ -29,7 +29,6 @@ macro_rules! generate_s10 {
($expr: expr) => {
#[cfg(feature = $expr)]
//~^ ERROR expected unsuffixed literal, found expression `concat!("nonexistent")`
- //~| ERROR expected unsuffixed literal, found expression `concat!("nonexistent")`
struct S10;
}
}
diff --git a/tests/ui/conditional-compilation/cfg-attr-syntax-validation.stderr b/tests/ui/conditional-compilation/cfg-attr-syntax-validation.stderr
index 21a3712d9391a..d02d0d70a8bcf 100644
--- a/tests/ui/conditional-compilation/cfg-attr-syntax-validation.stderr
+++ b/tests/ui/conditional-compilation/cfg-attr-syntax-validation.stderr
@@ -65,19 +65,7 @@ LL | generate_s10!(concat!("nonexistent"));
|
= note: this error originates in the macro `generate_s10` (in Nightly builds, run with -Z macro-backtrace for more info)
-error: expected unsuffixed literal, found expression `concat!("nonexistent")`
- --> $DIR/cfg-attr-syntax-validation.rs:30:25
- |
-LL | #[cfg(feature = $expr)]
- | ^^^^^
-...
-LL | generate_s10!(concat!("nonexistent"));
- | ------------------------------------- in this macro invocation
- |
- = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
- = note: this error originates in the macro `generate_s10` (in Nightly builds, run with -Z macro-backtrace for more info)
-
-error: aborting due to 11 previous errors
+error: aborting due to 10 previous errors
Some errors have detailed explanations: E0537, E0565.
For more information about an error, try `rustc --explain E0537`.
diff --git a/tests/ui/conditional-compilation/invalid-node-range-issue-129166.rs b/tests/ui/conditional-compilation/invalid-node-range-issue-129166.rs
index 794e6fad3fc22..7c42be3ed4d6e 100644
--- a/tests/ui/conditional-compilation/invalid-node-range-issue-129166.rs
+++ b/tests/ui/conditional-compilation/invalid-node-range-issue-129166.rs
@@ -1,11 +1,12 @@
// This was triggering an assertion failure in `NodeRange::new`.
+//@ check-pass
+
#![feature(cfg_eval)]
#![feature(stmt_expr_attributes)]
fn f() -> u32 {
#[cfg_eval] #[cfg(not(FALSE))] 0
- //~^ ERROR removing an expression is not supported in this position
}
fn main() {}
diff --git a/tests/ui/conditional-compilation/invalid-node-range-issue-129166.stderr b/tests/ui/conditional-compilation/invalid-node-range-issue-129166.stderr
deleted file mode 100644
index 0699e182bd5f2..0000000000000
--- a/tests/ui/conditional-compilation/invalid-node-range-issue-129166.stderr
+++ /dev/null
@@ -1,8 +0,0 @@
-error: removing an expression is not supported in this position
- --> $DIR/invalid-node-range-issue-129166.rs:7:17
- |
-LL | #[cfg_eval] #[cfg(not(FALSE))] 0
- | ^^^^^^^^^^^^^^^^^^
-
-error: aborting due to 1 previous error
-
diff --git a/tests/ui/parser/attribute/attr-bad-meta-4.rs b/tests/ui/parser/attribute/attr-bad-meta-4.rs
index 2d0c6dbb50ab8..937390a6da5ba 100644
--- a/tests/ui/parser/attribute/attr-bad-meta-4.rs
+++ b/tests/ui/parser/attribute/attr-bad-meta-4.rs
@@ -2,7 +2,6 @@ macro_rules! mac {
($attr_item: meta) => {
#[cfg($attr_item)]
//~^ ERROR expected unsuffixed literal, found `meta` metavariable
- //~| ERROR expected unsuffixed literal, found `meta` metavariable
struct S;
}
}
@@ -11,7 +10,6 @@ mac!(an(arbitrary token stream));
#[cfg(feature = -1)]
//~^ ERROR expected unsuffixed literal, found `-`
-//~| ERROR expected unsuffixed literal, found `-`
fn handler() {}
fn main() {}
diff --git a/tests/ui/parser/attribute/attr-bad-meta-4.stderr b/tests/ui/parser/attribute/attr-bad-meta-4.stderr
index dea574fd36d5b..9c6ab5adadf70 100644
--- a/tests/ui/parser/attribute/attr-bad-meta-4.stderr
+++ b/tests/ui/parser/attribute/attr-bad-meta-4.stderr
@@ -1,5 +1,5 @@
error: expected unsuffixed literal, found `-`
- --> $DIR/attr-bad-meta-4.rs:12:17
+ --> $DIR/attr-bad-meta-4.rs:11:17
|
LL | #[cfg(feature = -1)]
| ^
@@ -15,25 +15,5 @@ LL | mac!(an(arbitrary token stream));
|
= note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info)
-error: expected unsuffixed literal, found `meta` metavariable
- --> $DIR/attr-bad-meta-4.rs:3:15
- |
-LL | #[cfg($attr_item)]
- | ^^^^^^^^^^
-...
-LL | mac!(an(arbitrary token stream));
- | -------------------------------- in this macro invocation
- |
- = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
- = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info)
-
-error: expected unsuffixed literal, found `-`
- --> $DIR/attr-bad-meta-4.rs:12:17
- |
-LL | #[cfg(feature = -1)]
- | ^
- |
- = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
-
-error: aborting due to 4 previous errors
+error: aborting due to 2 previous errors
diff --git a/tests/ui/proc-macro/cfg-attr-trace.rs b/tests/ui/proc-macro/cfg-attr-trace.rs
index b4927f7a730b6..140dd10a7e047 100644
--- a/tests/ui/proc-macro/cfg-attr-trace.rs
+++ b/tests/ui/proc-macro/cfg-attr-trace.rs
@@ -3,6 +3,7 @@
//@ check-pass
//@ proc-macro: test-macros.rs
+#![feature(cfg_boolean_literals)]
#![feature(cfg_eval)]
#[macro_use]
@@ -10,8 +11,13 @@ extern crate test_macros;
#[cfg_eval]
#[test_macros::print_attr]
-#[cfg_attr(FALSE, test_macros::print_attr)]
-#[cfg_attr(all(), test_macros::print_attr)]
+#[cfg_attr(false, test_macros::print_attr)]
+#[cfg_attr(true, test_macros::print_attr)]
struct S;
+#[cfg_eval]
+#[test_macros::print_attr]
+#[cfg(true)]
+struct Z;
+
fn main() {}
diff --git a/tests/ui/proc-macro/cfg-attr-trace.stdout b/tests/ui/proc-macro/cfg-attr-trace.stdout
index 394c3887fe79c..52f9ff4e05c59 100644
--- a/tests/ui/proc-macro/cfg-attr-trace.stdout
+++ b/tests/ui/proc-macro/cfg-attr-trace.stdout
@@ -4,59 +4,75 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [
Punct {
ch: '#',
spacing: Alone,
- span: #0 bytes(271..272),
+ span: #0 bytes(305..306),
},
Group {
delimiter: Bracket,
stream: TokenStream [
Ident {
ident: "test_macros",
- span: #0 bytes(289..300),
+ span: #0 bytes(322..333),
},
Punct {
ch: ':',
spacing: Joint,
- span: #0 bytes(300..301),
+ span: #0 bytes(333..334),
},
Punct {
ch: ':',
spacing: Alone,
- span: #0 bytes(301..302),
+ span: #0 bytes(334..335),
},
Ident {
ident: "print_attr",
- span: #0 bytes(302..312),
+ span: #0 bytes(335..345),
},
],
- span: #0 bytes(272..314),
+ span: #0 bytes(306..347),
},
Ident {
ident: "struct",
- span: #0 bytes(315..321),
+ span: #0 bytes(348..354),
},
Ident {
ident: "S",
- span: #0 bytes(322..323),
+ span: #0 bytes(355..356),
},
Punct {
ch: ';',
spacing: Alone,
- span: #0 bytes(323..324),
+ span: #0 bytes(356..357),
},
]
PRINT-ATTR INPUT (DISPLAY): struct S;
PRINT-ATTR INPUT (DEBUG): TokenStream [
Ident {
ident: "struct",
- span: #0 bytes(315..321),
+ span: #0 bytes(348..354),
},
Ident {
ident: "S",
- span: #0 bytes(322..323),
+ span: #0 bytes(355..356),
},
Punct {
ch: ';',
spacing: Alone,
- span: #0 bytes(323..324),
+ span: #0 bytes(356..357),
+ },
+]
+PRINT-ATTR INPUT (DISPLAY): struct Z;
+PRINT-ATTR INPUT (DEBUG): TokenStream [
+ Ident {
+ ident: "struct",
+ span: #0 bytes(411..417),
+ },
+ Ident {
+ ident: "Z",
+ span: #0 bytes(418..419),
+ },
+ Punct {
+ ch: ';',
+ spacing: Alone,
+ span: #0 bytes(419..420),
},
]
| diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs
index a1487ca74be87..da739b0e4532b 100644
--- a/compiler/rustc_ast_passes/src/ast_validation.rs
+++ b/compiler/rustc_ast_passes/src/ast_validation.rs
@@ -334,8 +334,7 @@ impl<'a> AstValidator<'a> {
.filter(|attr| {
let arr = [
sym::allow,
- sym::cfg,
- sym::cfg_attr,
+ sym::cfg_trace,
sym::cfg_attr_trace,
sym::deny,
sym::expect,
diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs
index cdb1817944987..3dbfc191f8f50 100644
--- a/compiler/rustc_ast_pretty/src/pprust/state.rs
+++ b/compiler/rustc_ast_pretty/src/pprust/state.rs
@@ -593,7 +593,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) -> bool {
- if attr.has_name(sym::cfg_attr_trace) {
+ if attr.has_name(sym::cfg_trace) || attr.has_name(sym::cfg_attr_trace) {
// It's not a valid identifier, so avoid printing it
// to keep the printed code reasonably parse-able.
return false;
diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs
index ada49eef7b2d9..bcc2703c39b39 100644
--- a/compiler/rustc_expand/src/config.rs
+++ b/compiler/rustc_expand/src/config.rs
@@ -156,6 +156,19 @@ pub fn pre_configure_attrs(sess: &Session, attrs: &[Attribute]) -> ast::AttrVec
.collect()
+pub(crate) fn attr_into_trace(mut attr: Attribute, trace_name: Symbol) -> Attribute {
+ AttrKind::Normal(normal) => {
+ let NormalAttr { item, tokens } = &mut **normal;
+ // This makes the trace attributes unobservable to token-based proc macros.
+ *tokens = Some(LazyAttrTokenStream::new(AttrTokenStream::default()));
+ }
+ AttrKind::DocComment(..) => unreachable!(),
+ }
+ attr
#[macro_export]
macro_rules! configure {
($this:ident, $node:ident) => {
@@ -280,16 +293,7 @@ impl<'a> StripUnconfigured<'a> {
// A trace attribute left in AST in place of the original `cfg_attr` attribute.
// It can later be used by lints or other diagnostics.
- let mut trace_attr = cfg_attr.clone();
- match &mut trace_attr.kind {
- AttrKind::Normal(normal) => {
- let NormalAttr { item, tokens } = &mut **normal;
- item.path.segments[0].ident.name = sym::cfg_attr_trace;
- // This makes the trace attributes unobservable to token-based proc macros.
- *tokens = Some(LazyAttrTokenStream::new(AttrTokenStream::default()));
- }
- AttrKind::DocComment(..) => unreachable!(),
- }
+ let trace_attr = attr_into_trace(cfg_attr.clone(), sym::cfg_attr_trace);
let Some((cfg_predicate, expanded_attrs)) =
rustc_parse::parse_cfg_attr(cfg_attr, &self.sess.psess)
diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs
index d0bd8a89d9bdb..22da1179feb98 100644
--- a/compiler/rustc_expand/src/expand.rs
+++ b/compiler/rustc_expand/src/expand.rs
@@ -33,7 +33,7 @@ use rustc_span::{ErrorGuaranteed, FileName, Ident, LocalExpnId, Span, sym};
use smallvec::SmallVec;
use crate::base::*;
-use crate::config::StripUnconfigured;
use crate::errors::{
EmptyDelegationMac, GlobDelegationOutsideImpls, GlobDelegationTraitlessQpath, IncompleteParse,
RecursionLimitReached, RemoveExprNotSupported, RemoveNodeNotSupported, UnsupportedKeyValue,
@@ -2003,7 +2003,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
let attr_name = attr.ident().unwrap().name;
// `#[cfg]` and `#[cfg_attr]` are special - they are
// eagerly evaluated.
- if attr_name != sym::cfg && attr_name != sym::cfg_attr_trace {
+ if attr_name != sym::cfg_trace && attr_name != sym::cfg_attr_trace {
self.cx.sess.psess.buffer_lint(
UNUSED_ATTRIBUTES,
attr.span,
@@ -2027,11 +2027,10 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
) -> (bool, Option<ast::MetaItem>) {
let (res, meta_item) = self.cfg().cfg_true(&attr);
if res {
- // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion,
- // and some tools like rustdoc and clippy rely on that. Find a way to remove them
- // while keeping the tools working.
- self.cx.expanded_inert_attrs.mark(&attr);
- node.visit_attrs(|attrs| attrs.insert(pos, attr));
+ // A trace attribute left in AST in place of the original `cfg` attribute.
+ // It can later be used by lints or other diagnostics.
+ let trace_attr = attr_into_trace(attr, sym::cfg_trace);
(res, meta_item)
diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs
index fd936458f1115..6fe65c88f712a 100644
--- a/compiler/rustc_feature/src/builtin_attrs.rs
+++ b/compiler/rustc_feature/src/builtin_attrs.rs
@@ -760,10 +760,14 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
template!(Word, List: r#""...""#), DuplicatesOk,
EncodeCrossCrate::Yes, INTERNAL_UNSTABLE
),
- // Trace that is left when a `cfg_attr` attribute is expanded.
- // The attribute is not gated, to avoid stability errors, but it cannot be used in stable or
- // unstable code directly because `sym::cfg_attr_trace` is not a valid identifier, it can only
- // be generated by the compiler.
+ // Traces that are left when `cfg` and `cfg_attr` attributes are expanded.
+ // The attributes are not gated, to avoid stability errors, but they cannot be used in stable
+ // or unstable code directly because `sym::cfg_(attr_)trace` are not valid identifiers, they
+ // can only be generated by the compiler.
+ ungated!(
+ cfg_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk,
+ EncodeCrossCrate::No
+ ),
ungated!(
cfg_attr_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk,
EncodeCrossCrate::No
diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs
index 9ecde2a9eb504..6bbd650dcdfe3 100644
--- a/compiler/rustc_parse/src/validate_attr.rs
+++ b/compiler/rustc_parse/src/validate_attr.rs
@@ -16,7 +16,8 @@ use rustc_span::{Span, Symbol, sym};
use crate::{errors, parse_in};
pub fn check_attr(psess: &ParseSess, attr: &Attribute) {
- if attr.is_doc_comment() || attr.has_name(sym::cfg_attr_trace) {
+ if attr.is_doc_comment() || attr.has_name(sym::cfg_trace) || attr.has_name(sym::cfg_attr_trace)
+ {
@@ -215,11 +216,7 @@ pub fn check_builtin_meta_item(
template: AttributeTemplate,
deny_unsafety: bool,
) {
- // Some special attributes like `cfg` must be checked
- // before the generic check, so we skip them here.
- let should_skip = |name| name == sym::cfg;
- if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
+ if !is_attr_template_compatible(&template, &meta.kind) {
emit_malformed_attribute(psess, style, meta.span, name, template);
diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs
index 9238c73cdb113..1e1fb42a48fe2 100644
--- a/compiler/rustc_passes/src/check_attr.rs
+++ b/compiler/rustc_passes/src/check_attr.rs
@@ -272,6 +272,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
| sym::forbid
| sym::cfg
| sym::cfg_attr
+ | sym::cfg_trace
| sym::cfg_attr_trace
// need to be fixed
| sym::cfi_encoding // FIXME(cfi_encoding)
@@ -574,8 +575,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
// NOTE: when making changes to this list, check that `error_codes/E0736.md` remains accurate
const ALLOW_LIST: &[rustc_span::Symbol] = &[
// conditional compilation
- sym::cfg,
- sym::cfg_attr,
+ sym::cfg_trace,
sym::cfg_attr_trace,
// testing (allowed here so better errors can be generated in `rustc_builtin_macros::test`)
sym::test,
@@ -2656,7 +2656,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
// only `#[cfg]` and `#[cfg_attr]` are allowed, but it should be removed
// if we allow more attributes (e.g., tool attributes and `allow/deny/warn`)
// in where clauses. After that, only `self.check_attributes` should be enough.
- const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg, sym::cfg_attr, sym::cfg_attr_trace];
let spans = self
.tcx
.hir_attrs(where_predicate.hir_id)
diff --git a/compiler/rustc_query_system/src/ich/mod.rs b/compiler/rustc_query_system/src/ich/mod.rs
index 852d93b711f88..25778add60a98 100644
--- a/compiler/rustc_query_system/src/ich/mod.rs
+++ b/compiler/rustc_query_system/src/ich/mod.rs
@@ -8,7 +8,7 @@ mod hcx;
mod impls_syntax;
pub const IGNORED_ATTRIBUTES: &[Symbol] = &[
- sym::cfg,
+ sym::cfg_trace, // FIXME should this really be ignored?
sym::rustc_if_this_changed,
sym::rustc_then_this_would_need,
sym::rustc_dirty,
diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs
index 3e4742439655a..171f553e9c1a3 100644
--- a/compiler/rustc_span/src/symbol.rs
+++ b/compiler/rustc_span/src/symbol.rs
@@ -623,6 +623,7 @@ symbols! {
cfg_target_has_atomic_equal_alignment,
cfg_target_thread_local,
cfg_target_vendor,
+ cfg_trace: "<cfg>", // must not be a valid identifier
cfg_ub_checks,
cfg_version,
cfi,
diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs
index de6dc088176ff..6f660df4d7d45 100644
--- a/src/librustdoc/clean/mod.rs
+++ b/src/librustdoc/clean/mod.rs
@@ -2773,7 +2773,7 @@ fn add_without_unwanted_attributes<'hir>(
if ident == sym::doc {
filter_doc_attr(&mut normal.args, is_inline);
- } else if is_inline || ident != sym::cfg {
// If it's not a `cfg()` attribute, we keep it.
}
diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs
index 27eb56a9858b8..150b00dbb48a4 100644
--- a/src/librustdoc/clean/types.rs
+++ b/src/librustdoc/clean/types.rs
@@ -1059,7 +1059,7 @@ pub(crate) fn extract_cfg_from_attrs<'a, I: Iterator<Item = &'a hir::Attribute>
// `doc(cfg())` overrides `cfg()`).
attrs
.clone()
- .filter(|attr| attr.has_name(sym::cfg))
+ .filter(|attr| attr.has_name(sym::cfg_trace))
.filter_map(|attr| single(attr.meta_item_list()?))
.filter_map(|attr| Cfg::parse_without(attr.meta_item()?, hidden_cfg).ok().flatten())
.fold(Cfg::True, |cfg, new_cfg| cfg & new_cfg)
diff --git a/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs
index 5c486eb90cc2b..4c84e61b1f26c 100644
--- a/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs
+++ b/src/tools/clippy/clippy_lints/src/attrs/duplicated_attributes.rs
@@ -37,7 +37,6 @@ fn check_duplicated_attr(
let Some(ident) = attr.ident() else { return };
let name = ident.name;
if name == sym::doc
- || name == sym::cfg_attr
|| name == sym::cfg_attr_trace
|| name == sym::rustc_on_unimplemented
|| name == sym::reason {
@@ -47,7 +46,7 @@ fn check_duplicated_attr(
if let Some(direct_parent) = parent.last()
- && ["cfg", "cfg_attr"].contains(&direct_parent.as_str())
+ && direct_parent == sym::cfg_trace.as_str()
&& [sym::all, sym::not, sym::any].contains(&name)
{
// FIXME: We don't correctly check `cfg`s for now, so if it's more complex than just a one
diff --git a/src/tools/clippy/clippy_lints/src/cfg_not_test.rs b/src/tools/clippy/clippy_lints/src/cfg_not_test.rs
index 84136a2e6c28f..7590fe96fd214 100644
--- a/src/tools/clippy/clippy_lints/src/cfg_not_test.rs
+++ b/src/tools/clippy/clippy_lints/src/cfg_not_test.rs
@@ -32,7 +32,7 @@ declare_lint_pass!(CfgNotTest => [CFG_NOT_TEST]);
impl EarlyLintPass for CfgNotTest {
fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &rustc_ast::Attribute) {
- if attr.has_name(rustc_span::sym::cfg) && contains_not_test(attr.meta_item_list().as_deref(), false) {
+ if attr.has_name(rustc_span::sym::cfg_trace) && contains_not_test(attr.meta_item_list().as_deref(), false) {
span_lint_and_then(
cx,
CFG_NOT_TEST,
diff --git a/src/tools/clippy/clippy_lints/src/methods/is_empty.rs b/src/tools/clippy/clippy_lints/src/methods/is_empty.rs
index 7c190e123b72e..4c81b22861b4c 100644
--- a/src/tools/clippy/clippy_lints/src/methods/is_empty.rs
+++ b/src/tools/clippy/clippy_lints/src/methods/is_empty.rs
@@ -41,7 +41,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &'_ Expr<'_>, receiver: &Expr<'_
fn is_under_cfg(cx: &LateContext<'_>, id: HirId) -> bool {
cx.tcx
.hir_parent_id_iter(id)
+ .any(|id| cx.tcx.hir_attrs(id).iter().any(|attr| attr.has_name(sym::cfg_trace)))
/// Similar to [`clippy_utils::expr_or_init`], but does not go up the chain if the initialization
diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs
index 1307ff79bc5dd..668b0cb69e204 100644
--- a/src/tools/clippy/clippy_utils/src/lib.rs
+++ b/src/tools/clippy/clippy_utils/src/lib.rs
@@ -2629,7 +2629,7 @@ pub fn peel_ref_operators<'hir>(cx: &LateContext<'_>, mut expr: &'hir Expr<'hir>
pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
if let Res::Def(_, def_id) = path.res {
- return cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr);
+ return cx.tcx.has_attr(def_id, sym::cfg_trace) || cx.tcx.has_attr(def_id, sym::cfg_attr);
false
@@ -2699,7 +2699,7 @@ pub fn is_in_test_function(tcx: TyCtxt<'_>, id: HirId) -> bool {
/// use [`is_in_cfg_test`]
pub fn is_cfg_test(tcx: TyCtxt<'_>, id: HirId) -> bool {
tcx.hir_attrs(id).iter().any(|attr| {
- if attr.has_name(sym::cfg)
+ if attr.has_name(sym::cfg_trace)
&& let Some(items) = attr.meta_item_list()
&& let [item] = &*items
&& item.has_name(sym::test)
@@ -2723,11 +2723,11 @@ pub fn is_in_test(tcx: TyCtxt<'_>, hir_id: HirId) -> bool {
/// Checks if the item of any of its parents has `#[cfg(...)]` attribute applied.
pub fn inherits_cfg(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
- tcx.has_attr(def_id, sym::cfg)
+ tcx.has_attr(def_id, sym::cfg_trace)
|| tcx
.hir_parent_iter(tcx.local_def_id_to_hir_id(def_id))
.flat_map(|(parent_id, _)| tcx.hir_attrs(parent_id))
- .any(|attr| attr.has_name(sym::cfg))
+ .any(|attr| attr.has_name(sym::cfg_trace))
/// Walks up the HIR tree from the given expression in an attempt to find where the value is
diff --git a/tests/pretty/tests-are-sorted.pp b/tests/pretty/tests-are-sorted.pp
index 31449b51dc3e1..d6a2c0ff9796b 100644
--- a/tests/pretty/tests-are-sorted.pp
+++ b/tests/pretty/tests-are-sorted.pp
@@ -10,7 +10,6 @@
//@ pp-exact:tests-are-sorted.pp
#[rustc_test_marker = "m_test"]
pub const m_test: test::TestDescAndFn =
@@ -35,7 +34,6 @@
fn m_test() {}
#[rustc_test_marker = "z_test"]
pub const z_test: test::TestDescAndFn =
@@ -61,7 +59,6 @@
fn z_test() {}
#[rustc_test_marker = "a_test"]
pub const a_test: test::TestDescAndFn =
diff --git a/tests/ui/conditional-compilation/cfg-attr-syntax-validation.rs b/tests/ui/conditional-compilation/cfg-attr-syntax-validation.rs
index 9a041557c7cc9..416145a0c1560 100644
--- a/tests/ui/conditional-compilation/cfg-attr-syntax-validation.rs
+++ b/tests/ui/conditional-compilation/cfg-attr-syntax-validation.rs
@@ -29,7 +29,6 @@ macro_rules! generate_s10 {
($expr: expr) => {
#[cfg(feature = $expr)]
//~^ ERROR expected unsuffixed literal, found expression `concat!("nonexistent")`
struct S10;
diff --git a/tests/ui/conditional-compilation/cfg-attr-syntax-validation.stderr b/tests/ui/conditional-compilation/cfg-attr-syntax-validation.stderr
index 21a3712d9391a..d02d0d70a8bcf 100644
--- a/tests/ui/conditional-compilation/cfg-attr-syntax-validation.stderr
+++ b/tests/ui/conditional-compilation/cfg-attr-syntax-validation.stderr
@@ -65,19 +65,7 @@ LL | generate_s10!(concat!("nonexistent"));
= note: this error originates in the macro `generate_s10` (in Nightly builds, run with -Z macro-backtrace for more info)
-error: expected unsuffixed literal, found expression `concat!("nonexistent")`
- --> $DIR/cfg-attr-syntax-validation.rs:30:25
-LL | #[cfg(feature = $expr)]
- | ^^^^^
-LL | generate_s10!(concat!("nonexistent"));
- = note: this error originates in the macro `generate_s10` (in Nightly builds, run with -Z macro-backtrace for more info)
-error: aborting due to 11 previous errors
+error: aborting due to 10 previous errors
Some errors have detailed explanations: E0537, E0565.
For more information about an error, try `rustc --explain E0537`.
diff --git a/tests/ui/conditional-compilation/invalid-node-range-issue-129166.rs b/tests/ui/conditional-compilation/invalid-node-range-issue-129166.rs
index 794e6fad3fc22..7c42be3ed4d6e 100644
--- a/tests/ui/conditional-compilation/invalid-node-range-issue-129166.rs
+++ b/tests/ui/conditional-compilation/invalid-node-range-issue-129166.rs
@@ -1,11 +1,12 @@
// This was triggering an assertion failure in `NodeRange::new`.
+//@ check-pass
#![feature(stmt_expr_attributes)]
fn f() -> u32 {
#[cfg_eval] #[cfg(not(FALSE))] 0
- //~^ ERROR removing an expression is not supported in this position
diff --git a/tests/ui/conditional-compilation/invalid-node-range-issue-129166.stderr b/tests/ui/conditional-compilation/invalid-node-range-issue-129166.stderr
deleted file mode 100644
index 0699e182bd5f2..0000000000000
--- a/tests/ui/conditional-compilation/invalid-node-range-issue-129166.stderr
+++ /dev/null
@@ -1,8 +0,0 @@
-error: removing an expression is not supported in this position
- --> $DIR/invalid-node-range-issue-129166.rs:7:17
-LL | #[cfg_eval] #[cfg(not(FALSE))] 0
- | ^^^^^^^^^^^^^^^^^^
-error: aborting due to 1 previous error
diff --git a/tests/ui/parser/attribute/attr-bad-meta-4.rs b/tests/ui/parser/attribute/attr-bad-meta-4.rs
index 2d0c6dbb50ab8..937390a6da5ba 100644
--- a/tests/ui/parser/attribute/attr-bad-meta-4.rs
+++ b/tests/ui/parser/attribute/attr-bad-meta-4.rs
@@ -2,7 +2,6 @@ macro_rules! mac {
($attr_item: meta) => {
#[cfg($attr_item)]
//~^ ERROR expected unsuffixed literal, found `meta` metavariable
- //~| ERROR expected unsuffixed literal, found `meta` metavariable
struct S;
@@ -11,7 +10,6 @@ mac!(an(arbitrary token stream));
#[cfg(feature = -1)]
//~^ ERROR expected unsuffixed literal, found `-`
fn handler() {}
diff --git a/tests/ui/parser/attribute/attr-bad-meta-4.stderr b/tests/ui/parser/attribute/attr-bad-meta-4.stderr
index dea574fd36d5b..9c6ab5adadf70 100644
--- a/tests/ui/parser/attribute/attr-bad-meta-4.stderr
+++ b/tests/ui/parser/attribute/attr-bad-meta-4.stderr
@@ -1,5 +1,5 @@
error: expected unsuffixed literal, found `-`
+ --> $DIR/attr-bad-meta-4.rs:11:17
LL | #[cfg(feature = -1)]
| ^
@@ -15,25 +15,5 @@ LL | mac!(an(arbitrary token stream));
= note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info)
-error: expected unsuffixed literal, found `meta` metavariable
- --> $DIR/attr-bad-meta-4.rs:3:15
- | ^^^^^^^^^^
-LL | mac!(an(arbitrary token stream));
- | -------------------------------- in this macro invocation
- = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info)
-error: expected unsuffixed literal, found `-`
-LL | #[cfg(feature = -1)]
-error: aborting due to 4 previous errors
+error: aborting due to 2 previous errors
diff --git a/tests/ui/proc-macro/cfg-attr-trace.rs b/tests/ui/proc-macro/cfg-attr-trace.rs
index b4927f7a730b6..140dd10a7e047 100644
--- a/tests/ui/proc-macro/cfg-attr-trace.rs
+++ b/tests/ui/proc-macro/cfg-attr-trace.rs
@@ -3,6 +3,7 @@
//@ check-pass
//@ proc-macro: test-macros.rs
+#![feature(cfg_boolean_literals)]
#[macro_use]
@@ -10,8 +11,13 @@ extern crate test_macros;
#[cfg_eval]
#[test_macros::print_attr]
-#[cfg_attr(FALSE, test_macros::print_attr)]
-#[cfg_attr(all(), test_macros::print_attr)]
+#[cfg_attr(false, test_macros::print_attr)]
+#[cfg_attr(true, test_macros::print_attr)]
struct S;
+#[test_macros::print_attr]
+#[cfg(true)]
diff --git a/tests/ui/proc-macro/cfg-attr-trace.stdout b/tests/ui/proc-macro/cfg-attr-trace.stdout
index 394c3887fe79c..52f9ff4e05c59 100644
--- a/tests/ui/proc-macro/cfg-attr-trace.stdout
+++ b/tests/ui/proc-macro/cfg-attr-trace.stdout
@@ -4,59 +4,75 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [
ch: '#',
- span: #0 bytes(271..272),
+ span: #0 bytes(305..306),
Group {
delimiter: Bracket,
stream: TokenStream [
ident: "test_macros",
- span: #0 bytes(289..300),
+ span: #0 bytes(322..333),
spacing: Joint,
+ span: #0 bytes(333..334),
spacing: Alone,
- span: #0 bytes(301..302),
+ span: #0 bytes(334..335),
ident: "print_attr",
- span: #0 bytes(302..312),
+ span: #0 bytes(335..345),
],
- span: #0 bytes(272..314),
+ span: #0 bytes(306..347),
PRINT-ATTR INPUT (DISPLAY): struct S;
PRINT-ATTR INPUT (DEBUG): TokenStream [
+]
+PRINT-ATTR INPUT (DISPLAY): struct Z;
+PRINT-ATTR INPUT (DEBUG): TokenStream [
+ ident: "struct",
+ span: #0 bytes(411..417),
+ ident: "Z",
+ Punct {
+ ch: ';', | [
"+ match &mut attr.kind {",
"+ item.path.segments[0].ident.name = trace_name;",
"+}",
"+use crate::config::{StripUnconfigured, attr_into_trace};",
"+ node.visit_attrs(|attrs| attrs.insert(pos, trace_attr));",
"+ const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg_trace, sym::cfg_attr_trace];",
"+ } else if is_inline || ident != sym::cfg_trace {",
"- .any(|id| cx.tcx.hir_attrs(id).iter().any(|attr| attr.has_name(sym::cfg)))",
"- //~| ERROR expected unsuffixed literal, found expression `concat!(\"nonexistent\")`",
"- | ------------------------------------- in this macro invocation",
"-//~| ERROR expected unsuffixed literal, found `-`",
"-LL | #[cfg($attr_item)]",
"- | ^",
"+#[cfg_eval]",
"+struct Z;",
"- span: #0 bytes(300..301),",
"+ span: #0 bytes(418..419),",
"+ spacing: Alone,",
"+ span: #0 bytes(419..420),"
] | [
36,
39,
46,
78,
103,
184,
222,
281,
358,
377,
435,
457,
470,
499,
502,
527,
589,
593,
594
] | {
"additions": 88,
"author": "petrochenkov",
"deletions": 108,
"html_url": "https://github.com/rust-lang/rust/pull/138844",
"issue_id": 138844,
"merged_at": "2025-03-27T21:44:44Z",
"omission_probability": 0.1,
"pr_number": 138844,
"repo": "rust-lang/rust",
"title": "expand: Leave traces when expanding `cfg` attributes",
"total_changes": 196
} |
140 | diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index 31c696ed41ff4..de93e2b99eede 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -415,10 +415,13 @@ pub struct Config {
/// ABI tests.
pub minicore_path: Utf8PathBuf,
- /// If true, run tests with the "new" executor that was written to replace
- /// compiletest's dependency on libtest. Eventually this will become the
- /// default, and the libtest dependency will be removed.
- pub new_executor: bool,
+ /// If true, disable the "new" executor, and use the older libtest-based
+ /// executor to run tests instead. This is a temporary fallback, to make
+ /// manual comparative testing easier if bugs are found in the new executor.
+ ///
+ /// FIXME(Zalathar): Eventually remove this flag and remove the libtest
+ /// dependency.
+ pub no_new_executor: bool,
}
impl Config {
diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs
index 4bbd4ab4790d8..65b7f2e0c6db5 100644
--- a/src/tools/compiletest/src/lib.rs
+++ b/src/tools/compiletest/src/lib.rs
@@ -203,7 +203,7 @@ pub fn parse_config(args: Vec<String>) -> Config {
"COMMAND",
)
.reqopt("", "minicore-path", "path to minicore aux library", "PATH")
- .optflag("n", "new-executor", "enables the new test executor instead of using libtest")
+ .optflag("N", "no-new-executor", "disables the new test executor, and uses libtest instead")
.optopt(
"",
"debugger",
@@ -450,7 +450,7 @@ pub fn parse_config(args: Vec<String>) -> Config {
minicore_path: opt_path(matches, "minicore-path"),
- new_executor: matches.opt_present("new-executor"),
+ no_new_executor: matches.opt_present("no-new-executor"),
}
}
@@ -577,9 +577,10 @@ pub fn run_tests(config: Arc<Config>) {
// Delegate to the executor to filter and run the big list of test structures
// created during test discovery. When the executor decides to run a test,
// it will return control to the rest of compiletest by calling `runtest::run`.
- let res = if config.new_executor {
+ let res = if !config.no_new_executor {
Ok(executor::run_tests(&config, tests))
} else {
+ // FIXME(Zalathar): Eventually remove the libtest executor entirely.
crate::executor::libtest::execute_tests(&config, tests)
};
| diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index 31c696ed41ff4..de93e2b99eede 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -415,10 +415,13 @@ pub struct Config {
/// ABI tests.
pub minicore_path: Utf8PathBuf,
- /// If true, run tests with the "new" executor that was written to replace
- /// compiletest's dependency on libtest. Eventually this will become the
- /// default, and the libtest dependency will be removed.
- pub new_executor: bool,
+ /// If true, disable the "new" executor, and use the older libtest-based
+ /// executor to run tests instead. This is a temporary fallback, to make
+ /// manual comparative testing easier if bugs are found in the new executor.
+ /// FIXME(Zalathar): Eventually remove this flag and remove the libtest
+ /// dependency.
+ pub no_new_executor: bool,
impl Config {
diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs
index 4bbd4ab4790d8..65b7f2e0c6db5 100644
--- a/src/tools/compiletest/src/lib.rs
+++ b/src/tools/compiletest/src/lib.rs
@@ -203,7 +203,7 @@ pub fn parse_config(args: Vec<String>) -> Config {
"COMMAND",
)
.reqopt("", "minicore-path", "path to minicore aux library", "PATH")
- .optflag("n", "new-executor", "enables the new test executor instead of using libtest")
+ .optflag("N", "no-new-executor", "disables the new test executor, and uses libtest instead")
.optopt(
"",
"debugger",
@@ -450,7 +450,7 @@ pub fn parse_config(args: Vec<String>) -> Config {
minicore_path: opt_path(matches, "minicore-path"),
- new_executor: matches.opt_present("new-executor"),
+ no_new_executor: matches.opt_present("no-new-executor"),
}
@@ -577,9 +577,10 @@ pub fn run_tests(config: Arc<Config>) {
// Delegate to the executor to filter and run the big list of test structures
// created during test discovery. When the executor decides to run a test,
// it will return control to the rest of compiletest by calling `runtest::run`.
- let res = if config.new_executor {
+ let res = if !config.no_new_executor {
Ok(executor::run_tests(&config, tests))
} else {
+ // FIXME(Zalathar): Eventually remove the libtest executor entirely.
crate::executor::libtest::execute_tests(&config, tests)
}; | [
"+ ///"
] | [
15
] | {
"additions": 11,
"author": "Zalathar",
"deletions": 7,
"html_url": "https://github.com/rust-lang/rust/pull/139998",
"issue_id": 139998,
"merged_at": "2025-04-23T15:11:33Z",
"omission_probability": 0.1,
"pr_number": 139998,
"repo": "rust-lang/rust",
"title": "compiletest: Use the new non-libtest executor by default",
"total_changes": 18
} |
141 | diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs
index 3b66142eb2cec..83a9827e8f81f 100644
--- a/compiler/rustc_borrowck/src/lib.rs
+++ b/compiler/rustc_borrowck/src/lib.rs
@@ -702,12 +702,12 @@ struct MirBorrowckCtxt<'a, 'infcx, 'tcx> {
// 2. loans made in overlapping scopes do not conflict
// 3. assignments do not affect things loaned out as immutable
// 4. moves do not affect things loaned out in any way
-impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
+impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
fn visit_after_early_statement_effect(
&mut self,
_results: &mut Results<'tcx, Borrowck<'a, 'tcx>>,
state: &BorrowckDomain,
- stmt: &'a Statement<'tcx>,
+ stmt: &Statement<'tcx>,
location: Location,
) {
debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
@@ -783,7 +783,7 @@ impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<
&mut self,
_results: &mut Results<'tcx, Borrowck<'a, 'tcx>>,
state: &BorrowckDomain,
- term: &'a Terminator<'tcx>,
+ term: &Terminator<'tcx>,
loc: Location,
) {
debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
@@ -896,7 +896,7 @@ impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<
&mut self,
_results: &mut Results<'tcx, Borrowck<'a, 'tcx>>,
state: &BorrowckDomain,
- term: &'a Terminator<'tcx>,
+ term: &Terminator<'tcx>,
loc: Location,
) {
let span = term.source_info.span;
@@ -1363,7 +1363,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
fn consume_rvalue(
&mut self,
location: Location,
- (rvalue, span): (&'a Rvalue<'tcx>, Span),
+ (rvalue, span): (&Rvalue<'tcx>, Span),
state: &BorrowckDomain,
) {
match rvalue {
@@ -1636,7 +1636,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
fn consume_operand(
&mut self,
location: Location,
- (operand, span): (&'a Operand<'tcx>, Span),
+ (operand, span): (&Operand<'tcx>, Span),
state: &BorrowckDomain,
) {
match *operand {
diff --git a/compiler/rustc_mir_dataflow/src/framework/cursor.rs b/compiler/rustc_mir_dataflow/src/framework/cursor.rs
index c46ae9775cf68..d5005768b80bd 100644
--- a/compiler/rustc_mir_dataflow/src/framework/cursor.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/cursor.rs
@@ -114,26 +114,11 @@ where
self.reachable_blocks.insert_all()
}
- /// Returns the underlying `Results`.
- pub fn results(&self) -> &Results<'tcx, A> {
- &self.results
- }
-
- /// Returns the underlying `Results`.
- pub fn mut_results(&mut self) -> &mut Results<'tcx, A> {
- &mut self.results
- }
-
/// Returns the `Analysis` used to generate the underlying `Results`.
pub fn analysis(&self) -> &A {
&self.results.analysis
}
- /// Returns the `Analysis` used to generate the underlying `Results`.
- pub fn mut_analysis(&mut self) -> &mut A {
- &mut self.results.analysis
- }
-
/// Resets the cursor to hold the entry set for the given basic block.
///
/// For forward dataflow analyses, this is the dataflow state prior to the first statement.
diff --git a/compiler/rustc_mir_dataflow/src/framework/direction.rs b/compiler/rustc_mir_dataflow/src/framework/direction.rs
index 3d7f9e2d8e71b..b8c26dad59f41 100644
--- a/compiler/rustc_mir_dataflow/src/framework/direction.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/direction.rs
@@ -43,7 +43,7 @@ pub trait Direction {
block: BasicBlock,
block_data: &'mir mir::BasicBlockData<'tcx>,
results: &mut Results<'tcx, A>,
- vis: &mut impl ResultsVisitor<'mir, 'tcx, A>,
+ vis: &mut impl ResultsVisitor<'tcx, A>,
) where
A: Analysis<'tcx>;
}
@@ -212,7 +212,7 @@ impl Direction for Backward {
block: BasicBlock,
block_data: &'mir mir::BasicBlockData<'tcx>,
results: &mut Results<'tcx, A>,
- vis: &mut impl ResultsVisitor<'mir, 'tcx, A>,
+ vis: &mut impl ResultsVisitor<'tcx, A>,
) where
A: Analysis<'tcx>,
{
@@ -394,7 +394,7 @@ impl Direction for Forward {
block: BasicBlock,
block_data: &'mir mir::BasicBlockData<'tcx>,
results: &mut Results<'tcx, A>,
- vis: &mut impl ResultsVisitor<'mir, 'tcx, A>,
+ vis: &mut impl ResultsVisitor<'tcx, A>,
) where
A: Analysis<'tcx>,
{
diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs
index 95f488a925b2c..b5e9a0b893247 100644
--- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs
@@ -201,11 +201,12 @@ struct Formatter<'mir, 'tcx, A>
where
A: Analysis<'tcx>,
{
+ body: &'mir Body<'tcx>,
// The `RefCell` is used because `<Formatter as Labeller>::node_label`
- // takes `&self`, but it needs to modify the cursor. This is also the
+ // takes `&self`, but it needs to modify the results. This is also the
// reason for the `Formatter`/`BlockFormatter` split; `BlockFormatter` has
// the operations that involve the mutation, i.e. within the `borrow_mut`.
- cursor: RefCell<ResultsCursor<'mir, 'tcx, A>>,
+ results: RefCell<&'mir mut Results<'tcx, A>>,
style: OutputStyle,
reachable: DenseBitSet<BasicBlock>,
}
@@ -220,11 +221,7 @@ where
style: OutputStyle,
) -> Self {
let reachable = traversal::reachable_as_bitset(body);
- Formatter { cursor: results.as_results_cursor(body).into(), style, reachable }
- }
-
- fn body(&self) -> &'mir Body<'tcx> {
- self.cursor.borrow().body()
+ Formatter { body, results: results.into(), style, reachable }
}
}
@@ -253,7 +250,7 @@ where
type Edge = CfgEdge;
fn graph_id(&self) -> dot::Id<'_> {
- let name = graphviz_safe_def_name(self.body().source.def_id());
+ let name = graphviz_safe_def_name(self.body.source.def_id());
dot::Id::new(format!("graph_for_def_id_{name}")).unwrap()
}
@@ -262,10 +259,16 @@ where
}
fn node_label(&self, block: &Self::Node) -> dot::LabelText<'_> {
- let mut cursor = self.cursor.borrow_mut();
- let mut fmt =
- BlockFormatter { cursor: &mut cursor, style: self.style, bg: Background::Light };
- let label = fmt.write_node_label(*block).unwrap();
+ let mut results = self.results.borrow_mut();
+
+ let diffs = StateDiffCollector::run(self.body, *block, *results, self.style);
+
+ let mut fmt = BlockFormatter {
+ cursor: results.as_results_cursor(self.body),
+ style: self.style,
+ bg: Background::Light,
+ };
+ let label = fmt.write_node_label(*block, diffs).unwrap();
dot::LabelText::html(String::from_utf8(label).unwrap())
}
@@ -275,7 +278,7 @@ where
}
fn edge_label(&self, e: &Self::Edge) -> dot::LabelText<'_> {
- let label = &self.body()[e.source].terminator().kind.fmt_successor_labels()[e.index];
+ let label = &self.body[e.source].terminator().kind.fmt_successor_labels()[e.index];
dot::LabelText::label(label.clone())
}
}
@@ -288,7 +291,7 @@ where
type Edge = CfgEdge;
fn nodes(&self) -> dot::Nodes<'_, Self::Node> {
- self.body()
+ self.body
.basic_blocks
.indices()
.filter(|&idx| self.reachable.contains(idx))
@@ -297,10 +300,10 @@ where
}
fn edges(&self) -> dot::Edges<'_, Self::Edge> {
- let body = self.body();
- body.basic_blocks
+ self.body
+ .basic_blocks
.indices()
- .flat_map(|bb| dataflow_successors(body, bb))
+ .flat_map(|bb| dataflow_successors(self.body, bb))
.collect::<Vec<_>>()
.into()
}
@@ -310,20 +313,20 @@ where
}
fn target(&self, edge: &Self::Edge) -> Self::Node {
- self.body()[edge.source].terminator().successors().nth(edge.index).unwrap()
+ self.body[edge.source].terminator().successors().nth(edge.index).unwrap()
}
}
-struct BlockFormatter<'a, 'mir, 'tcx, A>
+struct BlockFormatter<'mir, 'tcx, A>
where
A: Analysis<'tcx>,
{
- cursor: &'a mut ResultsCursor<'mir, 'tcx, A>,
+ cursor: ResultsCursor<'mir, 'tcx, A>,
bg: Background,
style: OutputStyle,
}
-impl<'tcx, A> BlockFormatter<'_, '_, 'tcx, A>
+impl<'tcx, A> BlockFormatter<'_, 'tcx, A>
where
A: Analysis<'tcx>,
A::Domain: DebugWithContext<A>,
@@ -336,7 +339,11 @@ where
bg
}
- fn write_node_label(&mut self, block: BasicBlock) -> io::Result<Vec<u8>> {
+ fn write_node_label(
+ &mut self,
+ block: BasicBlock,
+ diffs: StateDiffCollector<A::Domain>,
+ ) -> io::Result<Vec<u8>> {
use std::io::Write;
// Sample output:
@@ -392,7 +399,7 @@ where
self.write_row_with_full_state(w, "", "(on start)")?;
// D + E: Statement and terminator transfer functions
- self.write_statements_and_terminator(w, block)?;
+ self.write_statements_and_terminator(w, block, diffs)?;
// F: State at end of block
@@ -575,14 +582,8 @@ where
&mut self,
w: &mut impl io::Write,
block: BasicBlock,
+ diffs: StateDiffCollector<A::Domain>,
) -> io::Result<()> {
- let diffs = StateDiffCollector::run(
- self.cursor.body(),
- block,
- self.cursor.mut_results(),
- self.style,
- );
-
let mut diffs_before = diffs.before.map(|v| v.into_iter());
let mut diffs_after = diffs.after.into_iter();
@@ -709,7 +710,7 @@ impl<D> StateDiffCollector<D> {
}
}
-impl<'tcx, A> ResultsVisitor<'_, 'tcx, A> for StateDiffCollector<A::Domain>
+impl<'tcx, A> ResultsVisitor<'tcx, A> for StateDiffCollector<A::Domain>
where
A: Analysis<'tcx>,
A::Domain: DebugWithContext<A>,
diff --git a/compiler/rustc_mir_dataflow/src/framework/results.rs b/compiler/rustc_mir_dataflow/src/framework/results.rs
index 8e2c3afddb352..93dfc06a878aa 100644
--- a/compiler/rustc_mir_dataflow/src/framework/results.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/results.rs
@@ -47,7 +47,7 @@ where
&mut self,
body: &'mir Body<'tcx>,
blocks: impl IntoIterator<Item = BasicBlock>,
- vis: &mut impl ResultsVisitor<'mir, 'tcx, A>,
+ vis: &mut impl ResultsVisitor<'tcx, A>,
) {
visit_results(body, blocks, self, vis)
}
@@ -55,7 +55,7 @@ where
pub fn visit_reachable_with<'mir>(
&mut self,
body: &'mir Body<'tcx>,
- vis: &mut impl ResultsVisitor<'mir, 'tcx, A>,
+ vis: &mut impl ResultsVisitor<'tcx, A>,
) {
let blocks = traversal::reachable(body);
visit_results(body, blocks.map(|(bb, _)| bb), self, vis)
diff --git a/compiler/rustc_mir_dataflow/src/framework/visitor.rs b/compiler/rustc_mir_dataflow/src/framework/visitor.rs
index a03aecee7be12..c9fdf46c4f5b2 100644
--- a/compiler/rustc_mir_dataflow/src/framework/visitor.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/visitor.rs
@@ -8,7 +8,7 @@ pub fn visit_results<'mir, 'tcx, A>(
body: &'mir mir::Body<'tcx>,
blocks: impl IntoIterator<Item = BasicBlock>,
results: &mut Results<'tcx, A>,
- vis: &mut impl ResultsVisitor<'mir, 'tcx, A>,
+ vis: &mut impl ResultsVisitor<'tcx, A>,
) where
A: Analysis<'tcx>,
{
@@ -29,7 +29,7 @@ pub fn visit_results<'mir, 'tcx, A>(
/// A visitor over the results of an `Analysis`. Use this when you want to inspect domain values in
/// many or all locations; use `ResultsCursor` if you want to inspect domain values only in certain
/// locations.
-pub trait ResultsVisitor<'mir, 'tcx, A>
+pub trait ResultsVisitor<'tcx, A>
where
A: Analysis<'tcx>,
{
@@ -40,7 +40,7 @@ where
&mut self,
_results: &mut Results<'tcx, A>,
_state: &A::Domain,
- _statement: &'mir mir::Statement<'tcx>,
+ _statement: &mir::Statement<'tcx>,
_location: Location,
) {
}
@@ -50,7 +50,7 @@ where
&mut self,
_results: &mut Results<'tcx, A>,
_state: &A::Domain,
- _statement: &'mir mir::Statement<'tcx>,
+ _statement: &mir::Statement<'tcx>,
_location: Location,
) {
}
@@ -60,7 +60,7 @@ where
&mut self,
_results: &mut Results<'tcx, A>,
_state: &A::Domain,
- _terminator: &'mir mir::Terminator<'tcx>,
+ _terminator: &mir::Terminator<'tcx>,
_location: Location,
) {
}
@@ -72,7 +72,7 @@ where
&mut self,
_results: &mut Results<'tcx, A>,
_state: &A::Domain,
- _terminator: &'mir mir::Terminator<'tcx>,
+ _terminator: &mir::Terminator<'tcx>,
_location: Location,
) {
}
diff --git a/compiler/rustc_mir_dataflow/src/points.rs b/compiler/rustc_mir_dataflow/src/points.rs
index 5d2a78acbf526..21590ff1bbad4 100644
--- a/compiler/rustc_mir_dataflow/src/points.rs
+++ b/compiler/rustc_mir_dataflow/src/points.rs
@@ -120,12 +120,12 @@ struct Visitor<'a, N: Idx> {
values: SparseIntervalMatrix<N, PointIndex>,
}
-impl<'mir, 'tcx, A, N> ResultsVisitor<'mir, 'tcx, A> for Visitor<'_, N>
+impl<'tcx, A, N> ResultsVisitor<'tcx, A> for Visitor<'_, N>
where
A: Analysis<'tcx, Domain = DenseBitSet<N>>,
N: Idx,
{
- fn visit_after_primary_statement_effect(
+ fn visit_after_primary_statement_effect<'mir>(
&mut self,
_results: &mut Results<'tcx, A>,
state: &A::Domain,
@@ -139,7 +139,7 @@ where
});
}
- fn visit_after_primary_terminator_effect(
+ fn visit_after_primary_terminator_effect<'mir>(
&mut self,
_results: &mut Results<'tcx, A>,
state: &A::Domain,
diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs
index 92d5e152f58e6..0eed46c72f993 100644
--- a/compiler/rustc_mir_transform/src/coroutine.rs
+++ b/compiler/rustc_mir_transform/src/coroutine.rs
@@ -875,14 +875,14 @@ struct StorageConflictVisitor<'a, 'tcx> {
eligible_storage_live: DenseBitSet<Local>,
}
-impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, MaybeRequiresStorage<'a, 'tcx>>
+impl<'a, 'tcx> ResultsVisitor<'tcx, MaybeRequiresStorage<'a, 'tcx>>
for StorageConflictVisitor<'a, 'tcx>
{
fn visit_after_early_statement_effect(
&mut self,
_results: &mut Results<'tcx, MaybeRequiresStorage<'a, 'tcx>>,
state: &DenseBitSet<Local>,
- _statement: &'a Statement<'tcx>,
+ _statement: &Statement<'tcx>,
loc: Location,
) {
self.apply_state(state, loc);
@@ -892,7 +892,7 @@ impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, MaybeRequiresStorage<'a, 'tcx>>
&mut self,
_results: &mut Results<'tcx, MaybeRequiresStorage<'a, 'tcx>>,
state: &DenseBitSet<Local>,
- _terminator: &'a Terminator<'tcx>,
+ _terminator: &Terminator<'tcx>,
loc: Location,
) {
self.apply_state(state, loc);
diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs
index 90173da17f0fc..a2103a004d2d1 100644
--- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs
+++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs
@@ -958,13 +958,13 @@ fn try_write_constant<'tcx>(
interp_ok(())
}
-impl<'mir, 'tcx> ResultsVisitor<'mir, 'tcx, ConstAnalysis<'_, 'tcx>> for Collector<'_, 'tcx> {
+impl<'tcx> ResultsVisitor<'tcx, ConstAnalysis<'_, 'tcx>> for Collector<'_, 'tcx> {
#[instrument(level = "trace", skip(self, results, statement))]
fn visit_after_early_statement_effect(
&mut self,
results: &mut Results<'tcx, ConstAnalysis<'_, 'tcx>>,
state: &State<FlatSet<Scalar>>,
- statement: &'mir Statement<'tcx>,
+ statement: &Statement<'tcx>,
location: Location,
) {
match &statement.kind {
@@ -986,7 +986,7 @@ impl<'mir, 'tcx> ResultsVisitor<'mir, 'tcx, ConstAnalysis<'_, 'tcx>> for Collect
&mut self,
results: &mut Results<'tcx, ConstAnalysis<'_, 'tcx>>,
state: &State<FlatSet<Scalar>>,
- statement: &'mir Statement<'tcx>,
+ statement: &Statement<'tcx>,
location: Location,
) {
match statement.kind {
@@ -1011,7 +1011,7 @@ impl<'mir, 'tcx> ResultsVisitor<'mir, 'tcx, ConstAnalysis<'_, 'tcx>> for Collect
&mut self,
results: &mut Results<'tcx, ConstAnalysis<'_, 'tcx>>,
state: &State<FlatSet<Scalar>>,
- terminator: &'mir Terminator<'tcx>,
+ terminator: &Terminator<'tcx>,
location: Location,
) {
OperandCollector {
| diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs
index 3b66142eb2cec..83a9827e8f81f 100644
--- a/compiler/rustc_borrowck/src/lib.rs
+++ b/compiler/rustc_borrowck/src/lib.rs
@@ -702,12 +702,12 @@ struct MirBorrowckCtxt<'a, 'infcx, 'tcx> {
// 2. loans made in overlapping scopes do not conflict
// 3. assignments do not affect things loaned out as immutable
// 4. moves do not affect things loaned out in any way
-impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
+impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
- stmt: &'a Statement<'tcx>,
+ stmt: &Statement<'tcx>,
debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
@@ -783,7 +783,7 @@ impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<
debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
@@ -896,7 +896,7 @@ impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<
let span = term.source_info.span;
@@ -1363,7 +1363,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
fn consume_rvalue(
- (rvalue, span): (&'a Rvalue<'tcx>, Span),
+ (rvalue, span): (&Rvalue<'tcx>, Span),
match rvalue {
@@ -1636,7 +1636,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
fn consume_operand(
- (operand, span): (&'a Operand<'tcx>, Span),
+ (operand, span): (&Operand<'tcx>, Span),
match *operand {
diff --git a/compiler/rustc_mir_dataflow/src/framework/cursor.rs b/compiler/rustc_mir_dataflow/src/framework/cursor.rs
index c46ae9775cf68..d5005768b80bd 100644
--- a/compiler/rustc_mir_dataflow/src/framework/cursor.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/cursor.rs
@@ -114,26 +114,11 @@ where
self.reachable_blocks.insert_all()
- pub fn results(&self) -> &Results<'tcx, A> {
- &self.results
- pub fn mut_results(&mut self) -> &mut Results<'tcx, A> {
- &mut self.results
/// Returns the `Analysis` used to generate the underlying `Results`.
pub fn analysis(&self) -> &A {
&self.results.analysis
- /// Returns the `Analysis` used to generate the underlying `Results`.
- pub fn mut_analysis(&mut self) -> &mut A {
- &mut self.results.analysis
/// Resets the cursor to hold the entry set for the given basic block.
///
/// For forward dataflow analyses, this is the dataflow state prior to the first statement.
diff --git a/compiler/rustc_mir_dataflow/src/framework/direction.rs b/compiler/rustc_mir_dataflow/src/framework/direction.rs
index 3d7f9e2d8e71b..b8c26dad59f41 100644
--- a/compiler/rustc_mir_dataflow/src/framework/direction.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/direction.rs
@@ -43,7 +43,7 @@ pub trait Direction {
A: Analysis<'tcx>;
@@ -212,7 +212,7 @@ impl Direction for Backward {
@@ -394,7 +394,7 @@ impl Direction for Forward {
diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs
index 95f488a925b2c..b5e9a0b893247 100644
--- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs
@@ -201,11 +201,12 @@ struct Formatter<'mir, 'tcx, A>
+ body: &'mir Body<'tcx>,
// The `RefCell` is used because `<Formatter as Labeller>::node_label`
- // takes `&self`, but it needs to modify the cursor. This is also the
+ // takes `&self`, but it needs to modify the results. This is also the
// reason for the `Formatter`/`BlockFormatter` split; `BlockFormatter` has
// the operations that involve the mutation, i.e. within the `borrow_mut`.
- cursor: RefCell<ResultsCursor<'mir, 'tcx, A>>,
+ results: RefCell<&'mir mut Results<'tcx, A>>,
reachable: DenseBitSet<BasicBlock>,
@@ -220,11 +221,7 @@ where
style: OutputStyle,
) -> Self {
let reachable = traversal::reachable_as_bitset(body);
- fn body(&self) -> &'mir Body<'tcx> {
- self.cursor.borrow().body()
+ Formatter { body, results: results.into(), style, reachable }
@@ -253,7 +250,7 @@ where
fn graph_id(&self) -> dot::Id<'_> {
- let name = graphviz_safe_def_name(self.body().source.def_id());
+ let name = graphviz_safe_def_name(self.body.source.def_id());
dot::Id::new(format!("graph_for_def_id_{name}")).unwrap()
@@ -262,10 +259,16 @@ where
fn node_label(&self, block: &Self::Node) -> dot::LabelText<'_> {
- let mut cursor = self.cursor.borrow_mut();
- let mut fmt =
- BlockFormatter { cursor: &mut cursor, style: self.style, bg: Background::Light };
- let label = fmt.write_node_label(*block).unwrap();
+ let mut results = self.results.borrow_mut();
+ let diffs = StateDiffCollector::run(self.body, *block, *results, self.style);
+ let mut fmt = BlockFormatter {
+ cursor: results.as_results_cursor(self.body),
+ style: self.style,
+ bg: Background::Light,
+ };
+ let label = fmt.write_node_label(*block, diffs).unwrap();
dot::LabelText::html(String::from_utf8(label).unwrap())
@@ -275,7 +278,7 @@ where
fn edge_label(&self, e: &Self::Edge) -> dot::LabelText<'_> {
- let label = &self.body()[e.source].terminator().kind.fmt_successor_labels()[e.index];
dot::LabelText::label(label.clone())
@@ -288,7 +291,7 @@ where
fn nodes(&self) -> dot::Nodes<'_, Self::Node> {
- self.body()
.basic_blocks
.filter(|&idx| self.reachable.contains(idx))
@@ -297,10 +300,10 @@ where
fn edges(&self) -> dot::Edges<'_, Self::Edge> {
- let body = self.body();
- body.basic_blocks
+ .basic_blocks
- .flat_map(|bb| dataflow_successors(body, bb))
+ .flat_map(|bb| dataflow_successors(self.body, bb))
.collect::<Vec<_>>()
.into()
@@ -310,20 +313,20 @@ where
fn target(&self, edge: &Self::Edge) -> Self::Node {
- self.body()[edge.source].terminator().successors().nth(edge.index).unwrap()
+ self.body[edge.source].terminator().successors().nth(edge.index).unwrap()
-struct BlockFormatter<'a, 'mir, 'tcx, A>
+struct BlockFormatter<'mir, 'tcx, A>
- cursor: &'a mut ResultsCursor<'mir, 'tcx, A>,
+ cursor: ResultsCursor<'mir, 'tcx, A>,
bg: Background,
-impl<'tcx, A> BlockFormatter<'_, '_, 'tcx, A>
+impl<'tcx, A> BlockFormatter<'_, 'tcx, A>
@@ -336,7 +339,11 @@ where
bg
- fn write_node_label(&mut self, block: BasicBlock) -> io::Result<Vec<u8>> {
+ &mut self,
+ block: BasicBlock,
use std::io::Write;
// Sample output:
@@ -392,7 +399,7 @@ where
self.write_row_with_full_state(w, "", "(on start)")?;
// D + E: Statement and terminator transfer functions
- self.write_statements_and_terminator(w, block)?;
+ self.write_statements_and_terminator(w, block, diffs)?;
// F: State at end of block
@@ -575,14 +582,8 @@ where
w: &mut impl io::Write,
) -> io::Result<()> {
- let diffs = StateDiffCollector::run(
- self.cursor.body(),
- block,
- self.cursor.mut_results(),
- self.style,
- );
let mut diffs_before = diffs.before.map(|v| v.into_iter());
let mut diffs_after = diffs.after.into_iter();
@@ -709,7 +710,7 @@ impl<D> StateDiffCollector<D> {
-impl<'tcx, A> ResultsVisitor<'_, 'tcx, A> for StateDiffCollector<A::Domain>
+impl<'tcx, A> ResultsVisitor<'tcx, A> for StateDiffCollector<A::Domain>
diff --git a/compiler/rustc_mir_dataflow/src/framework/results.rs b/compiler/rustc_mir_dataflow/src/framework/results.rs
index 8e2c3afddb352..93dfc06a878aa 100644
--- a/compiler/rustc_mir_dataflow/src/framework/results.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/results.rs
@@ -47,7 +47,7 @@ where
blocks: impl IntoIterator<Item = BasicBlock>,
visit_results(body, blocks, self, vis)
@@ -55,7 +55,7 @@ where
pub fn visit_reachable_with<'mir>(
let blocks = traversal::reachable(body);
visit_results(body, blocks.map(|(bb, _)| bb), self, vis)
diff --git a/compiler/rustc_mir_dataflow/src/framework/visitor.rs b/compiler/rustc_mir_dataflow/src/framework/visitor.rs
index a03aecee7be12..c9fdf46c4f5b2 100644
--- a/compiler/rustc_mir_dataflow/src/framework/visitor.rs
+++ b/compiler/rustc_mir_dataflow/src/framework/visitor.rs
@@ -8,7 +8,7 @@ pub fn visit_results<'mir, 'tcx, A>(
body: &'mir mir::Body<'tcx>,
blocks: impl IntoIterator<Item = BasicBlock>,
results: &mut Results<'tcx, A>,
- vis: &mut impl ResultsVisitor<'mir, 'tcx, A>,
) where
@@ -29,7 +29,7 @@ pub fn visit_results<'mir, 'tcx, A>(
/// A visitor over the results of an `Analysis`. Use this when you want to inspect domain values in
/// many or all locations; use `ResultsCursor` if you want to inspect domain values only in certain
/// locations.
+pub trait ResultsVisitor<'tcx, A>
@@ -40,7 +40,7 @@ where
@@ -50,7 +50,7 @@ where
@@ -60,7 +60,7 @@ where
@@ -72,7 +72,7 @@ where
diff --git a/compiler/rustc_mir_dataflow/src/points.rs b/compiler/rustc_mir_dataflow/src/points.rs
index 5d2a78acbf526..21590ff1bbad4 100644
--- a/compiler/rustc_mir_dataflow/src/points.rs
+++ b/compiler/rustc_mir_dataflow/src/points.rs
@@ -120,12 +120,12 @@ struct Visitor<'a, N: Idx> {
values: SparseIntervalMatrix<N, PointIndex>,
-impl<'mir, 'tcx, A, N> ResultsVisitor<'mir, 'tcx, A> for Visitor<'_, N>
+impl<'tcx, A, N> ResultsVisitor<'tcx, A> for Visitor<'_, N>
A: Analysis<'tcx, Domain = DenseBitSet<N>>,
N: Idx,
- fn visit_after_primary_statement_effect(
+ fn visit_after_primary_statement_effect<'mir>(
@@ -139,7 +139,7 @@ where
});
- fn visit_after_primary_terminator_effect(
+ fn visit_after_primary_terminator_effect<'mir>(
diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs
index 92d5e152f58e6..0eed46c72f993 100644
--- a/compiler/rustc_mir_transform/src/coroutine.rs
+++ b/compiler/rustc_mir_transform/src/coroutine.rs
@@ -875,14 +875,14 @@ struct StorageConflictVisitor<'a, 'tcx> {
eligible_storage_live: DenseBitSet<Local>,
-impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, MaybeRequiresStorage<'a, 'tcx>>
+impl<'a, 'tcx> ResultsVisitor<'tcx, MaybeRequiresStorage<'a, 'tcx>>
for StorageConflictVisitor<'a, 'tcx>
- _statement: &'a Statement<'tcx>,
+ _statement: &Statement<'tcx>,
@@ -892,7 +892,7 @@ impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, MaybeRequiresStorage<'a, 'tcx>>
- _terminator: &'a Terminator<'tcx>,
diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs
index 90173da17f0fc..a2103a004d2d1 100644
--- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs
+++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs
@@ -958,13 +958,13 @@ fn try_write_constant<'tcx>(
interp_ok(())
-impl<'mir, 'tcx> ResultsVisitor<'mir, 'tcx, ConstAnalysis<'_, 'tcx>> for Collector<'_, 'tcx> {
+impl<'tcx> ResultsVisitor<'tcx, ConstAnalysis<'_, 'tcx>> for Collector<'_, 'tcx> {
#[instrument(level = "trace", skip(self, results, statement))]
match &statement.kind {
@@ -986,7 +986,7 @@ impl<'mir, 'tcx> ResultsVisitor<'mir, 'tcx, ConstAnalysis<'_, 'tcx>> for Collect
match statement.kind {
@@ -1011,7 +1011,7 @@ impl<'mir, 'tcx> ResultsVisitor<'mir, 'tcx, ConstAnalysis<'_, 'tcx>> for Collect
+ terminator: &Terminator<'tcx>,
OperandCollector { | [
"- Formatter { cursor: results.as_results_cursor(body).into(), style, reachable }",
"+ let label = &self.body[e.source].terminator().kind.fmt_successor_labels()[e.index];",
"+ fn write_node_label(",
"+ ) -> io::Result<Vec<u8>> {",
"+ vis: &mut impl ResultsVisitor<'tcx, A>,",
"-pub trait ResultsVisitor<'mir, 'tcx, A>",
"+ _terminator: &Terminator<'tcx>,",
"- terminator: &'mir Terminator<'tcx>,"
] | [
140,
184,
241,
245,
314,
322,
417,
454
] | {
"additions": 59,
"author": "nnethercote",
"deletions": 73,
"html_url": "https://github.com/rust-lang/rust/pull/140142",
"issue_id": 140142,
"merged_at": "2025-04-23T18:22:48Z",
"omission_probability": 0.1,
"pr_number": 140142,
"repo": "rust-lang/rust",
"title": "Some more graphviz tweaks",
"total_changes": 132
} |
142 | diff --git a/library/std/src/path.rs b/library/std/src/path.rs
index 50f403ba411b6..7cd20c48d8939 100644
--- a/library/std/src/path.rs
+++ b/library/std/src/path.rs
@@ -353,6 +353,15 @@ fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
}
}
+/// Checks whether the string is valid as a file extension, or panics otherwise.
+fn validate_extension(extension: &OsStr) {
+ for &b in extension.as_encoded_bytes() {
+ if is_sep_byte(b) {
+ panic!("extension cannot contain path separators: {extension:?}");
+ }
+ }
+}
+
////////////////////////////////////////////////////////////////////////////////
// The core iterators
////////////////////////////////////////////////////////////////////////////////
@@ -1507,13 +1516,7 @@ impl PathBuf {
}
fn _set_extension(&mut self, extension: &OsStr) -> bool {
- for &b in extension.as_encoded_bytes() {
- if b < 128 {
- if is_separator(b as char) {
- panic!("extension cannot contain path separators: {:?}", extension);
- }
- }
- }
+ validate_extension(extension);
let file_stem = match self.file_stem() {
None => return false,
@@ -1541,6 +1544,11 @@ impl PathBuf {
/// Returns `false` and does nothing if [`self.file_name`] is [`None`],
/// returns `true` and updates the extension otherwise.
///
+ /// # Panics
+ ///
+ /// Panics if the passed extension contains a path separator (see
+ /// [`is_separator`]).
+ ///
/// # Caveats
///
/// The appended `extension` may contain dots and will be used in its entirety,
@@ -1582,6 +1590,8 @@ impl PathBuf {
}
fn _add_extension(&mut self, extension: &OsStr) -> bool {
+ validate_extension(extension);
+
let file_name = match self.file_name() {
None => return false,
Some(f) => f.as_encoded_bytes(),
| diff --git a/library/std/src/path.rs b/library/std/src/path.rs
index 50f403ba411b6..7cd20c48d8939 100644
--- a/library/std/src/path.rs
+++ b/library/std/src/path.rs
@@ -353,6 +353,15 @@ fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
}
+/// Checks whether the string is valid as a file extension, or panics otherwise.
+fn validate_extension(extension: &OsStr) {
+ for &b in extension.as_encoded_bytes() {
+ if is_sep_byte(b) {
+ panic!("extension cannot contain path separators: {extension:?}");
+ }
+ }
+}
// The core iterators
@@ -1507,13 +1516,7 @@ impl PathBuf {
fn _set_extension(&mut self, extension: &OsStr) -> bool {
- for &b in extension.as_encoded_bytes() {
- if b < 128 {
- if is_separator(b as char) {
- panic!("extension cannot contain path separators: {:?}", extension);
- }
- }
- }
let file_stem = match self.file_stem() {
@@ -1541,6 +1544,11 @@ impl PathBuf {
/// Returns `false` and does nothing if [`self.file_name`] is [`None`],
/// returns `true` and updates the extension otherwise.
+ /// # Panics
+ /// Panics if the passed extension contains a path separator (see
+ /// [`is_separator`]).
/// # Caveats
/// The appended `extension` may contain dots and will be used in its entirety,
@@ -1582,6 +1590,8 @@ impl PathBuf {
fn _add_extension(&mut self, extension: &OsStr) -> bool {
let file_name = match self.file_name() {
Some(f) => f.as_encoded_bytes(), | [] | [] | {
"additions": 17,
"author": "thaliaarchi",
"deletions": 7,
"html_url": "https://github.com/rust-lang/rust/pull/140163",
"issue_id": 140163,
"merged_at": "2025-04-23T18:22:48Z",
"omission_probability": 0.1,
"pr_number": 140163,
"repo": "rust-lang/rust",
"title": "Validate extension in `PathBuf::add_extension`",
"total_changes": 24
} |
143 | diff --git a/src/tools/nix-dev-shell/flake.nix b/src/tools/nix-dev-shell/flake.nix
index 1b838bd2f7b37..b8287de5fcf09 100644
--- a/src/tools/nix-dev-shell/flake.nix
+++ b/src/tools/nix-dev-shell/flake.nix
@@ -1,32 +1,24 @@
{
description = "rustc dev shell";
- inputs = {
- nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
- flake-utils.url = "github:numtide/flake-utils";
- };
+ inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
- outputs = { self, nixpkgs, flake-utils, ... }:
- flake-utils.lib.eachDefaultSystem (system:
- let
- pkgs = import nixpkgs { inherit system; };
- x = import ./x { inherit pkgs; };
- in
- {
- devShells.default = with pkgs; mkShell {
- name = "rustc-dev-shell";
- nativeBuildInputs = with pkgs; [
- binutils cmake ninja pkg-config python3 git curl cacert patchelf nix
- ];
- buildInputs = with pkgs; [
- openssl glibc.out glibc.static x
- ];
- # Avoid creating text files for ICEs.
- RUSTC_ICE = "0";
- # Provide `libstdc++.so.6` for the self-contained lld.
- # Provide `libz.so.1`.
- LD_LIBRARY_PATH = "${with pkgs; lib.makeLibraryPath [stdenv.cc.cc.lib zlib]}";
- };
- }
- );
+ outputs =
+ {
+ self,
+ nixpkgs,
+ }:
+ let
+ inherit (nixpkgs) lib;
+ forEachSystem = lib.genAttrs lib.systems.flakeExposed;
+ in
+ {
+ devShells = forEachSystem (system: {
+ default = nixpkgs.legacyPackages.${system}.callPackage ./shell.nix { };
+ });
+
+ packages = forEachSystem (system: {
+ default = nixpkgs.legacyPackages.${system}.callPackage ./x { };
+ });
+ };
}
diff --git a/src/tools/nix-dev-shell/shell.nix b/src/tools/nix-dev-shell/shell.nix
index a3f5969bd812d..0adbacf7e8d56 100644
--- a/src/tools/nix-dev-shell/shell.nix
+++ b/src/tools/nix-dev-shell/shell.nix
@@ -1,18 +1,26 @@
-{ pkgs ? import <nixpkgs> {} }:
-let
- x = import ./x { inherit pkgs; };
+{
+ pkgs ? import <nixpkgs> { },
+}:
+let
+ inherit (pkgs.lib) lists attrsets;
+
+ x = pkgs.callPackage ./x { };
+ inherit (x.passthru) cacert env;
in
pkgs.mkShell {
- name = "rustc";
- nativeBuildInputs = with pkgs; [
- binutils cmake ninja pkg-config python3 git curl cacert patchelf nix
- ];
- buildInputs = with pkgs; [
- openssl glibc.out glibc.static x
- ];
- # Avoid creating text files for ICEs.
- RUSTC_ICE = "0";
- # Provide `libstdc++.so.6` for the self-contained lld.
- # Provide `libz.so.1`
- LD_LIBRARY_PATH = "${with pkgs; lib.makeLibraryPath [stdenv.cc.cc.lib zlib]}";
+ name = "rustc-shell";
+
+ inputsFrom = [ x ];
+ packages = [
+ pkgs.git
+ pkgs.nix
+ x
+ # Get the runtime deps of the x wrapper
+ ] ++ lists.flatten (attrsets.attrValues env);
+
+ env = {
+ # Avoid creating text files for ICEs.
+ RUSTC_ICE = 0;
+ SSL_CERT_FILE = cacert;
+ };
}
diff --git a/src/tools/nix-dev-shell/x/default.nix b/src/tools/nix-dev-shell/x/default.nix
index e6dfbad6f19c8..422c1c4a2aed8 100644
--- a/src/tools/nix-dev-shell/x/default.nix
+++ b/src/tools/nix-dev-shell/x/default.nix
@@ -1,22 +1,83 @@
{
- pkgs ? import <nixpkgs> { },
+ pkgs,
+ lib,
+ stdenv,
+ rustc,
+ python3,
+ makeBinaryWrapper,
+ # Bootstrap
+ curl,
+ pkg-config,
+ libiconv,
+ openssl,
+ patchelf,
+ cacert,
+ zlib,
+ # LLVM Deps
+ ninja,
+ cmake,
+ glibc,
}:
-pkgs.stdenv.mkDerivation {
- name = "x";
+stdenv.mkDerivation (self: {
+ strictDeps = true;
+ name = "x-none";
+
+ outputs = [
+ "out"
+ "unwrapped"
+ ];
src = ./x.rs;
dontUnpack = true;
- nativeBuildInputs = with pkgs; [ rustc ];
+ nativeBuildInputs = [
+ rustc
+ makeBinaryWrapper
+ ];
+ env.PYTHON = python3.interpreter;
buildPhase = ''
- PYTHON=${pkgs.lib.getExe pkgs.python3} rustc -Copt-level=3 --crate-name x $src --out-dir $out/bin
+ rustc -Copt-level=3 --crate-name x $src --out-dir $unwrapped/bin
'';
- meta = with pkgs.lib; {
+ installPhase =
+ let
+ inherit (self.passthru) cacert env;
+ in
+ ''
+ makeWrapper $unwrapped/bin/x $out/bin/x \
+ --set-default SSL_CERT_FILE ${cacert} \
+ --prefix CPATH ";" "${lib.makeSearchPath "include" env.cpath}" \
+ --prefix PATH : ${lib.makeBinPath env.path} \
+ --prefix LD_LIBRARY_PATH : ${lib.makeLibraryPath env.ldLib}
+ '';
+
+ # For accessing them in the devshell
+ passthru = {
+ env = {
+ cpath = [ libiconv ];
+ path = [
+ python3
+ patchelf
+ curl
+ pkg-config
+ cmake
+ ninja
+ stdenv.cc
+ ];
+ ldLib = [
+ openssl
+ zlib
+ stdenv.cc.cc.lib
+ ];
+ };
+ cacert = "${cacert}/etc/ssl/certs/ca-bundle.crt";
+ };
+
+ meta = {
description = "Helper for rust-lang/rust x.py";
homepage = "https://github.com/rust-lang/rust/blob/master/src/tools/x";
- license = licenses.mit;
+ license = lib.licenses.mit;
mainProgram = "x";
};
-}
+})
| diff --git a/src/tools/nix-dev-shell/flake.nix b/src/tools/nix-dev-shell/flake.nix
index 1b838bd2f7b37..b8287de5fcf09 100644
--- a/src/tools/nix-dev-shell/flake.nix
+++ b/src/tools/nix-dev-shell/flake.nix
@@ -1,32 +1,24 @@
description = "rustc dev shell";
- inputs = {
- nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
- flake-utils.url = "github:numtide/flake-utils";
- };
+ inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
- outputs = { self, nixpkgs, flake-utils, ... }:
- flake-utils.lib.eachDefaultSystem (system:
- let
- pkgs = import nixpkgs { inherit system; };
- x = import ./x { inherit pkgs; };
- {
- devShells.default = with pkgs; mkShell {
- name = "rustc-dev-shell";
- nativeBuildInputs = with pkgs; [
- binutils cmake ninja pkg-config python3 git curl cacert patchelf nix
- buildInputs = with pkgs; [
- openssl glibc.out glibc.static x
- # Avoid creating text files for ICEs.
- RUSTC_ICE = "0";
- # Provide `libstdc++.so.6` for the self-contained lld.
- # Provide `libz.so.1`.
- LD_LIBRARY_PATH = "${with pkgs; lib.makeLibraryPath [stdenv.cc.cc.lib zlib]}";
- };
- }
- );
+ outputs =
+ self,
+ }:
+ inherit (nixpkgs) lib;
+ devShells = forEachSystem (system: {
+ default = nixpkgs.legacyPackages.${system}.callPackage ./shell.nix { };
+ packages = forEachSystem (system: {
+ default = nixpkgs.legacyPackages.${system}.callPackage ./x { };
diff --git a/src/tools/nix-dev-shell/shell.nix b/src/tools/nix-dev-shell/shell.nix
index a3f5969bd812d..0adbacf7e8d56 100644
--- a/src/tools/nix-dev-shell/shell.nix
+++ b/src/tools/nix-dev-shell/shell.nix
@@ -1,18 +1,26 @@
- x = import ./x { inherit pkgs; };
+{
+}:
+let
+ inherit (pkgs.lib) lists attrsets;
+ x = pkgs.callPackage ./x { };
+ inherit (x.passthru) cacert env;
in
pkgs.mkShell {
- name = "rustc";
- nativeBuildInputs = with pkgs; [
- binutils cmake ninja pkg-config python3 git curl cacert patchelf nix
- buildInputs = with pkgs; [
- openssl glibc.out glibc.static x
- RUSTC_ICE = "0";
- # Provide `libstdc++.so.6` for the self-contained lld.
- LD_LIBRARY_PATH = "${with pkgs; lib.makeLibraryPath [stdenv.cc.cc.lib zlib]}";
+ name = "rustc-shell";
+ inputsFrom = [ x ];
+ packages = [
+ pkgs.git
+ pkgs.nix
+ x
+ # Get the runtime deps of the x wrapper
+ ] ++ lists.flatten (attrsets.attrValues env);
+ env = {
+ # Avoid creating text files for ICEs.
+ RUSTC_ICE = 0;
+ SSL_CERT_FILE = cacert;
diff --git a/src/tools/nix-dev-shell/x/default.nix b/src/tools/nix-dev-shell/x/default.nix
index e6dfbad6f19c8..422c1c4a2aed8 100644
--- a/src/tools/nix-dev-shell/x/default.nix
+++ b/src/tools/nix-dev-shell/x/default.nix
@@ -1,22 +1,83 @@
- pkgs ? import <nixpkgs> { },
+ pkgs,
+ lib,
+ stdenv,
+ rustc,
+ python3,
+ makeBinaryWrapper,
+ # Bootstrap
+ curl,
+ pkg-config,
+ libiconv,
+ openssl,
+ patchelf,
+ cacert,
+ zlib,
+ # LLVM Deps
+ cmake,
+ glibc,
}:
-pkgs.stdenv.mkDerivation {
- name = "x";
+ strictDeps = true;
+ name = "x-none";
+ outputs = [
+ "out"
src = ./x.rs;
dontUnpack = true;
- nativeBuildInputs = with pkgs; [ rustc ];
+ nativeBuildInputs = [
+ makeBinaryWrapper
+ env.PYTHON = python3.interpreter;
buildPhase = ''
- PYTHON=${pkgs.lib.getExe pkgs.python3} rustc -Copt-level=3 --crate-name x $src --out-dir $out/bin
+ rustc -Copt-level=3 --crate-name x $src --out-dir $unwrapped/bin
'';
- meta = with pkgs.lib; {
+ inherit (self.passthru) cacert env;
+ ''
+ makeWrapper $unwrapped/bin/x $out/bin/x \
+ --set-default SSL_CERT_FILE ${cacert} \
+ --prefix CPATH ";" "${lib.makeSearchPath "include" env.cpath}" \
+ --prefix PATH : ${lib.makeBinPath env.path} \
+ --prefix LD_LIBRARY_PATH : ${lib.makeLibraryPath env.ldLib}
+ '';
+ # For accessing them in the devshell
+ passthru = {
+ cpath = [ libiconv ];
+ path = [
+ python3
+ patchelf
+ pkg-config
+ cmake
+ ninja
+ stdenv.cc
+ ldLib = [
+ openssl
+ stdenv.cc.cc.lib
+ meta = {
description = "Helper for rust-lang/rust x.py";
homepage = "https://github.com/rust-lang/rust/blob/master/src/tools/x";
- license = licenses.mit;
+ license = lib.licenses.mit;
mainProgram = "x";
};
-}
+}) | [
"- in",
"+ nixpkgs,",
"+ forEachSystem = lib.genAttrs lib.systems.flakeExposed;",
"-{ pkgs ? import <nixpkgs> {} }:",
"-let ",
"+ pkgs ? import <nixpkgs> { },",
"- # Avoid creating text files for ICEs.",
"- # Provide `libz.so.1`",
"+ ninja,",
"+stdenv.mkDerivation (self: {",
"+ \"unwrapped\"",
"+ rustc",
"+ installPhase =",
"+ env = {",
"+ curl",
"+ zlib",
"+ cacert = \"${cacert}/etc/ssl/certs/ca-bundle.crt\";"
] | [
19,
40,
44,
61,
62,
65,
81,
84,
124,
130,
136,
144,
155,
169,
174,
182,
186
] | {
"additions": 111,
"author": "RossSmyth",
"deletions": 50,
"html_url": "https://github.com/rust-lang/rust/pull/139297",
"issue_id": 139297,
"merged_at": "2025-04-19T19:11:12Z",
"omission_probability": 0.1,
"pr_number": 139297,
"repo": "rust-lang/rust",
"title": "Deduplicate & clean up Nix shell",
"total_changes": 161
} |
144 | diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl
index e7f17bb6f996d..d2502c99b9bcc 100644
--- a/compiler/rustc_parse/messages.ftl
+++ b/compiler/rustc_parse/messages.ftl
@@ -893,6 +893,7 @@ parse_unknown_prefix = prefix `{$prefix}` is unknown
.label = unknown prefix
.note = prefixed identifiers and literals are reserved since Rust 2021
.suggestion_br = use `br` for a raw byte string
+ .suggestion_cr = use `cr` for a raw C-string
.suggestion_str = if you meant to write a string literal, use double quotes
.suggestion_whitespace = consider inserting whitespace here
diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs
index 44b4e1a3e47a0..35cf4c1b00d4b 100644
--- a/compiler/rustc_parse/src/errors.rs
+++ b/compiler/rustc_parse/src/errors.rs
@@ -2140,6 +2140,13 @@ pub(crate) enum UnknownPrefixSugg {
style = "verbose"
)]
UseBr(#[primary_span] Span),
+ #[suggestion(
+ parse_suggestion_cr,
+ code = "cr",
+ applicability = "maybe-incorrect",
+ style = "verbose"
+ )]
+ UseCr(#[primary_span] Span),
#[suggestion(
parse_suggestion_whitespace,
code = " ",
diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs
index 4935fc03256f4..788b82114045a 100644
--- a/compiler/rustc_parse/src/lexer/mod.rs
+++ b/compiler/rustc_parse/src/lexer/mod.rs
@@ -256,7 +256,6 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
let lit_start = start + BytePos(prefix_len);
self.pos = lit_start;
self.cursor = Cursor::new(&str_before[prefix_len as usize..]);
-
self.report_unknown_prefix(start);
let prefix_span = self.mk_sp(start, lit_start);
return (Token::new(self.ident(start), prefix_span), preceded_by_whitespace);
@@ -789,13 +788,14 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
fn report_unknown_prefix(&self, start: BytePos) {
let prefix_span = self.mk_sp(start, self.pos);
let prefix = self.str_from_to(start, self.pos);
-
let expn_data = prefix_span.ctxt().outer_expn_data();
if expn_data.edition.at_least_rust_2021() {
// In Rust 2021, this is a hard error.
let sugg = if prefix == "rb" {
Some(errors::UnknownPrefixSugg::UseBr(prefix_span))
+ } else if prefix == "rc" {
+ Some(errors::UnknownPrefixSugg::UseCr(prefix_span))
} else if expn_data.is_root() {
if self.cursor.first() == '\''
&& let Some(start) = self.last_lifetime
diff --git a/tests/ui/suggestions/raw-c-string-prefix.rs b/tests/ui/suggestions/raw-c-string-prefix.rs
new file mode 100644
index 0000000000000..6af72df40242c
--- /dev/null
+++ b/tests/ui/suggestions/raw-c-string-prefix.rs
@@ -0,0 +1,10 @@
+// `rc` and `cr` are easy to confuse; check that we issue a suggestion to help.
+
+//@ edition:2021
+
+fn main() {
+ rc"abc";
+ //~^ ERROR: prefix `rc` is unknown
+ //~| HELP: use `cr` for a raw C-string
+ //~| ERROR: expected one of
+}
diff --git a/tests/ui/suggestions/raw-c-string-prefix.stderr b/tests/ui/suggestions/raw-c-string-prefix.stderr
new file mode 100644
index 0000000000000..5341e3d04e8a1
--- /dev/null
+++ b/tests/ui/suggestions/raw-c-string-prefix.stderr
@@ -0,0 +1,21 @@
+error: prefix `rc` is unknown
+ --> $DIR/raw-c-string-prefix.rs:6:5
+ |
+LL | rc"abc";
+ | ^^ unknown prefix
+ |
+ = note: prefixed identifiers and literals are reserved since Rust 2021
+help: use `cr` for a raw C-string
+ |
+LL - rc"abc";
+LL + cr"abc";
+ |
+
+error: expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `"abc"`
+ --> $DIR/raw-c-string-prefix.rs:6:7
+ |
+LL | rc"abc";
+ | ^^^^^ expected one of 8 possible tokens
+
+error: aborting due to 2 previous errors
+
| diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl
index e7f17bb6f996d..d2502c99b9bcc 100644
--- a/compiler/rustc_parse/messages.ftl
+++ b/compiler/rustc_parse/messages.ftl
@@ -893,6 +893,7 @@ parse_unknown_prefix = prefix `{$prefix}` is unknown
.label = unknown prefix
.note = prefixed identifiers and literals are reserved since Rust 2021
.suggestion_br = use `br` for a raw byte string
+ .suggestion_cr = use `cr` for a raw C-string
.suggestion_str = if you meant to write a string literal, use double quotes
.suggestion_whitespace = consider inserting whitespace here
diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs
index 44b4e1a3e47a0..35cf4c1b00d4b 100644
--- a/compiler/rustc_parse/src/errors.rs
+++ b/compiler/rustc_parse/src/errors.rs
@@ -2140,6 +2140,13 @@ pub(crate) enum UnknownPrefixSugg {
style = "verbose"
)]
UseBr(#[primary_span] Span),
+ #[suggestion(
+ parse_suggestion_cr,
+ code = "cr",
+ applicability = "maybe-incorrect",
+ style = "verbose"
+ )]
+ UseCr(#[primary_span] Span),
#[suggestion(
parse_suggestion_whitespace,
code = " ",
diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs
index 4935fc03256f4..788b82114045a 100644
--- a/compiler/rustc_parse/src/lexer/mod.rs
+++ b/compiler/rustc_parse/src/lexer/mod.rs
@@ -256,7 +256,6 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
let lit_start = start + BytePos(prefix_len);
self.pos = lit_start;
self.cursor = Cursor::new(&str_before[prefix_len as usize..]);
self.report_unknown_prefix(start);
let prefix_span = self.mk_sp(start, lit_start);
return (Token::new(self.ident(start), prefix_span), preceded_by_whitespace);
@@ -789,13 +788,14 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
fn report_unknown_prefix(&self, start: BytePos) {
let prefix_span = self.mk_sp(start, self.pos);
let prefix = self.str_from_to(start, self.pos);
let expn_data = prefix_span.ctxt().outer_expn_data();
if expn_data.edition.at_least_rust_2021() {
// In Rust 2021, this is a hard error.
let sugg = if prefix == "rb" {
Some(errors::UnknownPrefixSugg::UseBr(prefix_span))
+ } else if prefix == "rc" {
+ Some(errors::UnknownPrefixSugg::UseCr(prefix_span))
} else if expn_data.is_root() {
if self.cursor.first() == '\''
&& let Some(start) = self.last_lifetime
diff --git a/tests/ui/suggestions/raw-c-string-prefix.rs b/tests/ui/suggestions/raw-c-string-prefix.rs
index 0000000000000..6af72df40242c
+++ b/tests/ui/suggestions/raw-c-string-prefix.rs
@@ -0,0 +1,10 @@
+// `rc` and `cr` are easy to confuse; check that we issue a suggestion to help.
+//@ edition:2021
+fn main() {
+ rc"abc";
+ //~^ ERROR: prefix `rc` is unknown
+ //~| HELP: use `cr` for a raw C-string
+ //~| ERROR: expected one of
+}
diff --git a/tests/ui/suggestions/raw-c-string-prefix.stderr b/tests/ui/suggestions/raw-c-string-prefix.stderr
index 0000000000000..5341e3d04e8a1
+++ b/tests/ui/suggestions/raw-c-string-prefix.stderr
@@ -0,0 +1,21 @@
+error: prefix `rc` is unknown
+ --> $DIR/raw-c-string-prefix.rs:6:5
+ | ^^ unknown prefix
+ = note: prefixed identifiers and literals are reserved since Rust 2021
+LL - rc"abc";
+error: expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `"abc"`
+ --> $DIR/raw-c-string-prefix.rs:6:7
+ | ^^^^^ expected one of 8 possible tokens
+error: aborting due to 2 previous errors | [
"+help: use `cr` for a raw C-string",
"+LL + cr\"abc\";"
] | [
87,
90
] | {
"additions": 41,
"author": "Kivooeo",
"deletions": 2,
"html_url": "https://github.com/rust-lang/rust/pull/140175",
"issue_id": 140175,
"merged_at": "2025-04-23T18:22:48Z",
"omission_probability": 0.1,
"pr_number": 140175,
"repo": "rust-lang/rust",
"title": "`rc\"\"` more clear error message",
"total_changes": 43
} |
145 | diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs
index e1f19beb53aee..0b97d4e6993bb 100644
--- a/compiler/rustc_parse/src/lexer/diagnostics.rs
+++ b/compiler/rustc_parse/src/lexer/diagnostics.rs
@@ -1,14 +1,17 @@
use rustc_ast::token::Delimiter;
use rustc_errors::Diag;
+use rustc_session::parse::ParseSess;
use rustc_span::Span;
use rustc_span::source_map::SourceMap;
use super::UnmatchedDelim;
+use crate::errors::MismatchedClosingDelimiter;
+use crate::pprust;
#[derive(Default)]
pub(super) struct TokenTreeDiagInfo {
/// Stack of open delimiters and their spans. Used for error message.
- pub open_braces: Vec<(Delimiter, Span)>,
+ pub open_delimiters: Vec<(Delimiter, Span)>,
pub unmatched_delims: Vec<UnmatchedDelim>,
/// Used only for error recovery when arriving to EOF with mismatched braces.
@@ -108,7 +111,7 @@ pub(super) fn report_suspicious_mismatch_block(
} else {
// If there is no suspicious span, give the last properly closed block may help
if let Some(parent) = diag_info.matching_block_spans.last()
- && diag_info.open_braces.last().is_none()
+ && diag_info.open_delimiters.last().is_none()
&& diag_info.empty_block_spans.iter().all(|&sp| sp != parent.0.to(parent.1))
{
err.span_label(parent.0, "this opening brace...");
@@ -116,3 +119,24 @@ pub(super) fn report_suspicious_mismatch_block(
}
}
}
+
+pub(crate) fn make_unclosed_delims_error(
+ unmatched: UnmatchedDelim,
+ psess: &ParseSess,
+) -> Option<Diag<'_>> {
+ // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
+ // `unmatched_delims` only for error recovery in the `Parser`.
+ let found_delim = unmatched.found_delim?;
+ let mut spans = vec![unmatched.found_span];
+ if let Some(sp) = unmatched.unclosed_span {
+ spans.push(sp);
+ };
+ let err = psess.dcx().create_err(MismatchedClosingDelimiter {
+ spans,
+ delimiter: pprust::token_kind_to_string(&found_delim.as_close_token_kind()).to_string(),
+ unmatched: unmatched.found_span,
+ opening_candidate: unmatched.candidate_span,
+ unclosed: unmatched.unclosed_span,
+ });
+ Some(err)
+}
diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs
index a8ec9a1e952ef..da4f11a3f46a6 100644
--- a/compiler/rustc_parse/src/lexer/mod.rs
+++ b/compiler/rustc_parse/src/lexer/mod.rs
@@ -1,5 +1,6 @@
use std::ops::Range;
+use diagnostics::make_unclosed_delims_error;
use rustc_ast::ast::{self, AttrStyle};
use rustc_ast::token::{self, CommentKind, Delimiter, IdentIsRaw, Token, TokenKind};
use rustc_ast::tokenstream::TokenStream;
@@ -17,9 +18,9 @@ use rustc_session::parse::ParseSess;
use rustc_span::{BytePos, Pos, Span, Symbol};
use tracing::debug;
+use crate::errors;
use crate::lexer::diagnostics::TokenTreeDiagInfo;
use crate::lexer::unicode_chars::UNICODE_ARRAY;
-use crate::{errors, make_unclosed_delims_error};
mod diagnostics;
mod tokentrees;
diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs
index 0ddd9a85df867..fbea958dcc598 100644
--- a/compiler/rustc_parse/src/lexer/tokentrees.rs
+++ b/compiler/rustc_parse/src/lexer/tokentrees.rs
@@ -54,8 +54,8 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
let mut err = self.dcx().struct_span_err(self.token.span, msg);
let unclosed_delimiter_show_limit = 5;
- let len = usize::min(unclosed_delimiter_show_limit, self.diag_info.open_braces.len());
- for &(_, span) in &self.diag_info.open_braces[..len] {
+ let len = usize::min(unclosed_delimiter_show_limit, self.diag_info.open_delimiters.len());
+ for &(_, span) in &self.diag_info.open_delimiters[..len] {
err.span_label(span, "unclosed delimiter");
self.diag_info.unmatched_delims.push(UnmatchedDelim {
found_delim: None,
@@ -65,19 +65,19 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
});
}
- if let Some((_, span)) = self.diag_info.open_braces.get(unclosed_delimiter_show_limit)
- && self.diag_info.open_braces.len() >= unclosed_delimiter_show_limit + 2
+ if let Some((_, span)) = self.diag_info.open_delimiters.get(unclosed_delimiter_show_limit)
+ && self.diag_info.open_delimiters.len() >= unclosed_delimiter_show_limit + 2
{
err.span_label(
*span,
format!(
"another {} unclosed delimiters begin from here",
- self.diag_info.open_braces.len() - unclosed_delimiter_show_limit
+ self.diag_info.open_delimiters.len() - unclosed_delimiter_show_limit
),
);
}
- if let Some((delim, _)) = self.diag_info.open_braces.last() {
+ if let Some((delim, _)) = self.diag_info.open_delimiters.last() {
report_suspicious_mismatch_block(
&mut err,
&self.diag_info,
@@ -95,7 +95,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
// The span for beginning of the delimited section.
let pre_span = self.token.span;
- self.diag_info.open_braces.push((open_delim, self.token.span));
+ self.diag_info.open_delimiters.push((open_delim, self.token.span));
// Lex the token trees within the delimiters.
// We stop at any delimiter so we can try to recover if the user
@@ -109,11 +109,12 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
let close_spacing = if let Some(close_delim) = self.token.kind.close_delim() {
if close_delim == open_delim {
// Correct delimiter.
- let (open_brace, open_brace_span) = self.diag_info.open_braces.pop().unwrap();
- let close_brace_span = self.token.span;
+ let (open_delimiter, open_delimiter_span) =
+ self.diag_info.open_delimiters.pop().unwrap();
+ let close_delimiter_span = self.token.span;
if tts.is_empty() && close_delim == Delimiter::Brace {
- let empty_block_span = open_brace_span.to(close_brace_span);
+ let empty_block_span = open_delimiter_span.to(close_delimiter_span);
if !sm.is_multiline(empty_block_span) {
// Only track if the block is in the form of `{}`, otherwise it is
// likely that it was written on purpose.
@@ -122,9 +123,11 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
}
// only add braces
- if let (Delimiter::Brace, Delimiter::Brace) = (open_brace, open_delim) {
+ if let (Delimiter::Brace, Delimiter::Brace) = (open_delimiter, open_delim) {
// Add all the matching spans, we will sort by span later
- self.diag_info.matching_block_spans.push((open_brace_span, close_brace_span));
+ self.diag_info
+ .matching_block_spans
+ .push((open_delimiter_span, close_delimiter_span));
}
// Move past the closing delimiter.
@@ -140,18 +143,18 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
// This is a conservative error: only report the last unclosed
// delimiter. The previous unclosed delimiters could actually be
// closed! The lexer just hasn't gotten to them yet.
- if let Some(&(_, sp)) = self.diag_info.open_braces.last() {
+ if let Some(&(_, sp)) = self.diag_info.open_delimiters.last() {
unclosed_delimiter = Some(sp);
};
- for (brace, brace_span) in &self.diag_info.open_braces {
- if same_indentation_level(sm, self.token.span, *brace_span)
- && brace == &close_delim
+ for (delimiter, delimiter_span) in &self.diag_info.open_delimiters {
+ if same_indentation_level(sm, self.token.span, *delimiter_span)
+ && delimiter == &close_delim
{
// high likelihood of these two corresponding
- candidate = Some(*brace_span);
+ candidate = Some(*delimiter_span);
}
}
- let (_, _) = self.diag_info.open_braces.pop().unwrap();
+ let (_, _) = self.diag_info.open_delimiters.pop().unwrap();
self.diag_info.unmatched_delims.push(UnmatchedDelim {
found_delim: Some(close_delim),
found_span: self.token.span,
@@ -159,7 +162,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
candidate_span: candidate,
});
} else {
- self.diag_info.open_braces.pop();
+ self.diag_info.open_delimiters.pop();
}
// If the incorrect delimiter matches an earlier opening
@@ -169,7 +172,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
// fn foo() {
// bar(baz(
// } // Incorrect delimiter but matches the earlier `{`
- if !self.diag_info.open_braces.iter().any(|&(b, _)| b == close_delim) {
+ if !self.diag_info.open_delimiters.iter().any(|&(d, _)| d == close_delim) {
self.bump_minimal()
} else {
// The choice of value here doesn't matter.
@@ -180,7 +183,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
assert_eq!(self.token.kind, token::Eof);
// Silently recover, the EOF token will be seen again
// and an error emitted then. Thus we don't pop from
- // self.open_braces here. The choice of spacing value here
+ // self.open_delimiters here. The choice of spacing value here
// doesn't matter.
Spacing::Alone
};
diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs
index 2edc8c83017d8..896e348a12dc1 100644
--- a/compiler/rustc_parse/src/lib.rs
+++ b/compiler/rustc_parse/src/lib.rs
@@ -32,7 +32,7 @@ pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
#[macro_use]
pub mod parser;
-use parser::{Parser, make_unclosed_delims_error};
+use parser::Parser;
pub mod lexer;
pub mod validate_attr;
diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs
index d73adb39826f4..48df8b59d55ad 100644
--- a/compiler/rustc_parse/src/parser/mod.rs
+++ b/compiler/rustc_parse/src/parser/mod.rs
@@ -43,11 +43,8 @@ use token_type::TokenTypeSet;
pub use token_type::{ExpKeywordPair, ExpTokenPair, TokenType};
use tracing::debug;
-use crate::errors::{
- self, IncorrectVisibilityRestriction, MismatchedClosingDelimiter, NonStringAbiLiteral,
-};
+use crate::errors::{self, IncorrectVisibilityRestriction, NonStringAbiLiteral};
use crate::exp;
-use crate::lexer::UnmatchedDelim;
#[cfg(test)]
mod tests;
@@ -1745,27 +1742,6 @@ impl<'a> Parser<'a> {
}
}
-pub(crate) fn make_unclosed_delims_error(
- unmatched: UnmatchedDelim,
- psess: &ParseSess,
-) -> Option<Diag<'_>> {
- // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
- // `unmatched_delims` only for error recovery in the `Parser`.
- let found_delim = unmatched.found_delim?;
- let mut spans = vec![unmatched.found_span];
- if let Some(sp) = unmatched.unclosed_span {
- spans.push(sp);
- };
- let err = psess.dcx().create_err(MismatchedClosingDelimiter {
- spans,
- delimiter: pprust::token_kind_to_string(&found_delim.as_close_token_kind()).to_string(),
- unmatched: unmatched.found_span,
- opening_candidate: unmatched.candidate_span,
- unclosed: unmatched.unclosed_span,
- });
- Some(err)
-}
-
/// A helper struct used when building an `AttrTokenStream` from
/// a `LazyAttrTokenStream`. Both delimiter and non-delimited tokens
/// are stored as `FlatToken::Token`. A vector of `FlatToken`s
| diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs
index e1f19beb53aee..0b97d4e6993bb 100644
--- a/compiler/rustc_parse/src/lexer/diagnostics.rs
+++ b/compiler/rustc_parse/src/lexer/diagnostics.rs
@@ -1,14 +1,17 @@
use rustc_ast::token::Delimiter;
use rustc_errors::Diag;
+use rustc_session::parse::ParseSess;
use rustc_span::Span;
use rustc_span::source_map::SourceMap;
use super::UnmatchedDelim;
+use crate::errors::MismatchedClosingDelimiter;
+use crate::pprust;
#[derive(Default)]
pub(super) struct TokenTreeDiagInfo {
/// Stack of open delimiters and their spans. Used for error message.
- pub open_braces: Vec<(Delimiter, Span)>,
+ pub open_delimiters: Vec<(Delimiter, Span)>,
pub unmatched_delims: Vec<UnmatchedDelim>,
/// Used only for error recovery when arriving to EOF with mismatched braces.
@@ -108,7 +111,7 @@ pub(super) fn report_suspicious_mismatch_block(
} else {
// If there is no suspicious span, give the last properly closed block may help
if let Some(parent) = diag_info.matching_block_spans.last()
- && diag_info.open_braces.last().is_none()
+ && diag_info.open_delimiters.last().is_none()
&& diag_info.empty_block_spans.iter().all(|&sp| sp != parent.0.to(parent.1))
err.span_label(parent.0, "this opening brace...");
@@ -116,3 +119,24 @@ pub(super) fn report_suspicious_mismatch_block(
+
+ unmatched: UnmatchedDelim,
+ psess: &ParseSess,
+) -> Option<Diag<'_>> {
+ // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
+ // `unmatched_delims` only for error recovery in the `Parser`.
+ let found_delim = unmatched.found_delim?;
+ let mut spans = vec![unmatched.found_span];
+ if let Some(sp) = unmatched.unclosed_span {
+ spans.push(sp);
+ };
+ let err = psess.dcx().create_err(MismatchedClosingDelimiter {
+ spans,
+ delimiter: pprust::token_kind_to_string(&found_delim.as_close_token_kind()).to_string(),
+ unmatched: unmatched.found_span,
+ unclosed: unmatched.unclosed_span,
+ });
+ Some(err)
diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs
index a8ec9a1e952ef..da4f11a3f46a6 100644
--- a/compiler/rustc_parse/src/lexer/mod.rs
+++ b/compiler/rustc_parse/src/lexer/mod.rs
@@ -1,5 +1,6 @@
use std::ops::Range;
+use diagnostics::make_unclosed_delims_error;
use rustc_ast::ast::{self, AttrStyle};
use rustc_ast::token::{self, CommentKind, Delimiter, IdentIsRaw, Token, TokenKind};
use rustc_ast::tokenstream::TokenStream;
@@ -17,9 +18,9 @@ use rustc_session::parse::ParseSess;
use rustc_span::{BytePos, Pos, Span, Symbol};
+use crate::errors;
use crate::lexer::diagnostics::TokenTreeDiagInfo;
use crate::lexer::unicode_chars::UNICODE_ARRAY;
-use crate::{errors, make_unclosed_delims_error};
mod diagnostics;
mod tokentrees;
diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs
index 0ddd9a85df867..fbea958dcc598 100644
--- a/compiler/rustc_parse/src/lexer/tokentrees.rs
+++ b/compiler/rustc_parse/src/lexer/tokentrees.rs
@@ -54,8 +54,8 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
let mut err = self.dcx().struct_span_err(self.token.span, msg);
let unclosed_delimiter_show_limit = 5;
- let len = usize::min(unclosed_delimiter_show_limit, self.diag_info.open_braces.len());
- for &(_, span) in &self.diag_info.open_braces[..len] {
+ let len = usize::min(unclosed_delimiter_show_limit, self.diag_info.open_delimiters.len());
+ for &(_, span) in &self.diag_info.open_delimiters[..len] {
err.span_label(span, "unclosed delimiter");
self.diag_info.unmatched_delims.push(UnmatchedDelim {
found_delim: None,
@@ -65,19 +65,19 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
});
- if let Some((_, span)) = self.diag_info.open_braces.get(unclosed_delimiter_show_limit)
- && self.diag_info.open_braces.len() >= unclosed_delimiter_show_limit + 2
+ if let Some((_, span)) = self.diag_info.open_delimiters.get(unclosed_delimiter_show_limit)
+ && self.diag_info.open_delimiters.len() >= unclosed_delimiter_show_limit + 2
err.span_label(
*span,
format!(
"another {} unclosed delimiters begin from here",
- self.diag_info.open_braces.len() - unclosed_delimiter_show_limit
+ self.diag_info.open_delimiters.len() - unclosed_delimiter_show_limit
),
);
- if let Some((delim, _)) = self.diag_info.open_braces.last() {
+ if let Some((delim, _)) = self.diag_info.open_delimiters.last() {
report_suspicious_mismatch_block(
&mut err,
&self.diag_info,
@@ -95,7 +95,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
// The span for beginning of the delimited section.
let pre_span = self.token.span;
- self.diag_info.open_braces.push((open_delim, self.token.span));
+ self.diag_info.open_delimiters.push((open_delim, self.token.span));
// Lex the token trees within the delimiters.
// We stop at any delimiter so we can try to recover if the user
@@ -109,11 +109,12 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
let close_spacing = if let Some(close_delim) = self.token.kind.close_delim() {
if close_delim == open_delim {
// Correct delimiter.
- let (open_brace, open_brace_span) = self.diag_info.open_braces.pop().unwrap();
- let close_brace_span = self.token.span;
+ self.diag_info.open_delimiters.pop().unwrap();
+ let close_delimiter_span = self.token.span;
if tts.is_empty() && close_delim == Delimiter::Brace {
- let empty_block_span = open_brace_span.to(close_brace_span);
+ let empty_block_span = open_delimiter_span.to(close_delimiter_span);
if !sm.is_multiline(empty_block_span) {
// Only track if the block is in the form of `{}`, otherwise it is
// likely that it was written on purpose.
@@ -122,9 +123,11 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
// only add braces
- if let (Delimiter::Brace, Delimiter::Brace) = (open_brace, open_delim) {
+ if let (Delimiter::Brace, Delimiter::Brace) = (open_delimiter, open_delim) {
// Add all the matching spans, we will sort by span later
- self.diag_info.matching_block_spans.push((open_brace_span, close_brace_span));
+ self.diag_info
+ .matching_block_spans
+ .push((open_delimiter_span, close_delimiter_span));
// Move past the closing delimiter.
@@ -140,18 +143,18 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
// This is a conservative error: only report the last unclosed
// delimiter. The previous unclosed delimiters could actually be
// closed! The lexer just hasn't gotten to them yet.
- if let Some(&(_, sp)) = self.diag_info.open_braces.last() {
+ if let Some(&(_, sp)) = self.diag_info.open_delimiters.last() {
unclosed_delimiter = Some(sp);
};
- if same_indentation_level(sm, self.token.span, *brace_span)
- && brace == &close_delim
+ if same_indentation_level(sm, self.token.span, *delimiter_span)
+ && delimiter == &close_delim
{
// high likelihood of these two corresponding
- candidate = Some(*brace_span);
+ candidate = Some(*delimiter_span);
}
}
self.diag_info.unmatched_delims.push(UnmatchedDelim {
found_delim: Some(close_delim),
found_span: self.token.span,
@@ -159,7 +162,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
candidate_span: candidate,
});
- self.diag_info.open_braces.pop();
+ self.diag_info.open_delimiters.pop();
// If the incorrect delimiter matches an earlier opening
@@ -169,7 +172,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
// fn foo() {
// bar(baz(
// } // Incorrect delimiter but matches the earlier `{`
- if !self.diag_info.open_braces.iter().any(|&(b, _)| b == close_delim) {
+ if !self.diag_info.open_delimiters.iter().any(|&(d, _)| d == close_delim) {
self.bump_minimal()
// The choice of value here doesn't matter.
@@ -180,7 +183,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> {
assert_eq!(self.token.kind, token::Eof);
// Silently recover, the EOF token will be seen again
// and an error emitted then. Thus we don't pop from
- // self.open_braces here. The choice of spacing value here
+ // self.open_delimiters here. The choice of spacing value here
// doesn't matter.
Spacing::Alone
};
diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs
index 2edc8c83017d8..896e348a12dc1 100644
--- a/compiler/rustc_parse/src/lib.rs
+++ b/compiler/rustc_parse/src/lib.rs
@@ -32,7 +32,7 @@ pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
#[macro_use]
pub mod parser;
-use parser::{Parser, make_unclosed_delims_error};
+use parser::Parser;
pub mod lexer;
pub mod validate_attr;
diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs
index d73adb39826f4..48df8b59d55ad 100644
--- a/compiler/rustc_parse/src/parser/mod.rs
+++ b/compiler/rustc_parse/src/parser/mod.rs
@@ -43,11 +43,8 @@ use token_type::TokenTypeSet;
pub use token_type::{ExpKeywordPair, ExpTokenPair, TokenType};
-use crate::errors::{
- self, IncorrectVisibilityRestriction, MismatchedClosingDelimiter, NonStringAbiLiteral,
-};
+use crate::errors::{self, IncorrectVisibilityRestriction, NonStringAbiLiteral};
use crate::exp;
-use crate::lexer::UnmatchedDelim;
#[cfg(test)]
mod tests;
@@ -1745,27 +1742,6 @@ impl<'a> Parser<'a> {
-pub(crate) fn make_unclosed_delims_error(
- unmatched: UnmatchedDelim,
- psess: &ParseSess,
-) -> Option<Diag<'_>> {
- // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
- // `unmatched_delims` only for error recovery in the `Parser`.
- if let Some(sp) = unmatched.unclosed_span {
- spans.push(sp);
- };
- let err = psess.dcx().create_err(MismatchedClosingDelimiter {
- spans,
- delimiter: pprust::token_kind_to_string(&found_delim.as_close_token_kind()).to_string(),
- unmatched: unmatched.found_span,
- opening_candidate: unmatched.candidate_span,
- unclosed: unmatched.unclosed_span,
- });
- Some(err)
-}
/// A helper struct used when building an `AttrTokenStream` from
/// a `LazyAttrTokenStream`. Both delimiter and non-delimited tokens
/// are stored as `FlatToken::Token`. A vector of `FlatToken`s | [
"+pub(crate) fn make_unclosed_delims_error(",
"+ opening_candidate: unmatched.candidate_span,",
"+}",
"+ let (open_delimiter, open_delimiter_span) =",
"- for (brace, brace_span) in &self.diag_info.open_braces {",
"+ for (delimiter, delimiter_span) in &self.diag_info.open_delimiters {",
"- let (_, _) = self.diag_info.open_braces.pop().unwrap();",
"+ let (_, _) = self.diag_info.open_delimiters.pop().unwrap();",
"- let found_delim = unmatched.found_delim?;",
"- let mut spans = vec![unmatched.found_span];",
"-"
] | [
37,
52,
56,
133,
165,
168,
177,
178,
249,
250,
263
] | {
"additions": 54,
"author": "xizheyin",
"deletions": 50,
"html_url": "https://github.com/rust-lang/rust/pull/140147",
"issue_id": 140147,
"merged_at": "2025-04-23T18:22:48Z",
"omission_probability": 0.1,
"pr_number": 140147,
"repo": "rust-lang/rust",
"title": "Clean: rename `open_braces` to `open_delimiters` in lexer and move `make_unclosed_delims_error` into `diagnostics.rs`.",
"total_changes": 104
} |
146 | diff --git a/tests/ui/writing-to-immutable-vec.rs b/tests/ui/borrowck/writing-to-immutable-vec.rs
similarity index 100%
rename from tests/ui/writing-to-immutable-vec.rs
rename to tests/ui/borrowck/writing-to-immutable-vec.rs
diff --git a/tests/ui/writing-to-immutable-vec.stderr b/tests/ui/borrowck/writing-to-immutable-vec.stderr
similarity index 100%
rename from tests/ui/writing-to-immutable-vec.stderr
rename to tests/ui/borrowck/writing-to-immutable-vec.stderr
diff --git a/tests/ui/deref-non-pointer.rs b/tests/ui/deref-patterns/deref-non-pointer.rs
similarity index 100%
rename from tests/ui/deref-non-pointer.rs
rename to tests/ui/deref-patterns/deref-non-pointer.rs
diff --git a/tests/ui/deref-non-pointer.stderr b/tests/ui/deref-patterns/deref-non-pointer.stderr
similarity index 100%
rename from tests/ui/deref-non-pointer.stderr
rename to tests/ui/deref-patterns/deref-non-pointer.stderr
diff --git a/tests/ui/lazy-and-or.rs b/tests/ui/lazy-and-or.rs
deleted file mode 100644
index f9dbeb68959a3..0000000000000
--- a/tests/ui/lazy-and-or.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-//@ run-pass
-
-fn incr(x: &mut isize) -> bool { *x += 1; assert!((false)); return false; }
-
-pub fn main() {
- let x = 1 == 2 || 3 == 3;
- assert!((x));
- let mut y: isize = 10;
- println!("{}", x || incr(&mut y));
- assert_eq!(y, 10);
- if true && x { assert!((true)); } else { assert!((false)); }
-}
diff --git a/tests/ui/list.rs b/tests/ui/list.rs
deleted file mode 100644
index 443c4c9f28f88..0000000000000
--- a/tests/ui/list.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-//@ run-pass
-
-#![allow(non_camel_case_types)]
-
-enum list { #[allow(dead_code)] cons(isize, Box<list>), nil, }
-
-pub fn main() {
- list::cons(10, Box::new(list::cons(11, Box::new(list::cons(12, Box::new(list::nil))))));
-}
diff --git a/tests/ui/minus-string.rs b/tests/ui/minus-string.rs
deleted file mode 100644
index b83347b937edf..0000000000000
--- a/tests/ui/minus-string.rs
+++ /dev/null
@@ -1 +0,0 @@
-fn main() { -"foo".to_string(); } //~ ERROR cannot apply unary operator `-` to type `String`
diff --git a/tests/ui/or-patterns/lazy-and-or.rs b/tests/ui/or-patterns/lazy-and-or.rs
new file mode 100644
index 0000000000000..3d69553132b98
--- /dev/null
+++ b/tests/ui/or-patterns/lazy-and-or.rs
@@ -0,0 +1,25 @@
+//@ run-pass
+// This test verifies the short-circuiting behavior of logical operators `||` and `&&`.
+// It ensures that the right-hand expression is not evaluated when the left-hand
+// expression is sufficient to determine the result.
+
+fn would_panic_if_called(x: &mut isize) -> bool {
+ *x += 1;
+ assert!(false, "This function should never be called due to short-circuiting");
+ false
+}
+
+fn main() {
+ let x = 1 == 2 || 3 == 3;
+ assert!(x);
+
+ let mut y: isize = 10;
+ println!("Result of short-circuit: {}", x || would_panic_if_called(&mut y));
+ assert_eq!(y, 10, "y should remain 10 if short-circuiting works correctly");
+
+ if true && x {
+ assert!(true);
+ } else {
+ assert!(false, "This branch should not be reached");
+ }
+}
diff --git a/tests/ui/recursion/recursive-enum-box.rs b/tests/ui/recursion/recursive-enum-box.rs
new file mode 100644
index 0000000000000..540b0c553603c
--- /dev/null
+++ b/tests/ui/recursion/recursive-enum-box.rs
@@ -0,0 +1,21 @@
+//@ run-pass
+// A smoke test for recursive enum structures using Box<T>.
+// This test constructs a linked list-like structure to exercise memory allocation and ownership.
+// Originally introduced in 2010, this is one of Rust’s earliest test cases.
+
+#![allow(dead_code)]
+
+enum List {
+ Cons(isize, Box<List>),
+ Nil,
+}
+
+fn main() {
+ List::Cons(
+ 10,
+ Box::new(List::Cons(
+ 11,
+ Box::new(List::Cons(12, Box::new(List::Nil))),
+ )),
+ );
+}
diff --git a/tests/ui/typeck/minus-string.rs b/tests/ui/typeck/minus-string.rs
new file mode 100644
index 0000000000000..1c0f73a37132c
--- /dev/null
+++ b/tests/ui/typeck/minus-string.rs
@@ -0,0 +1,7 @@
+// Regression test for issue #813.
+// This ensures that the unary negation operator `-` cannot be applied to an owned `String`.
+// Previously, due to a type-checking bug, this was mistakenly accepted by the compiler.
+
+fn main() {
+ -"foo".to_string(); //~ ERROR cannot apply unary operator `-` to type `String`
+}
diff --git a/tests/ui/minus-string.stderr b/tests/ui/typeck/minus-string.stderr
similarity index 69%
rename from tests/ui/minus-string.stderr
rename to tests/ui/typeck/minus-string.stderr
index 153965c810ea7..d2ebcd01ff9c1 100644
--- a/tests/ui/minus-string.stderr
+++ b/tests/ui/typeck/minus-string.stderr
@@ -1,8 +1,8 @@
error[E0600]: cannot apply unary operator `-` to type `String`
- --> $DIR/minus-string.rs:1:13
+ --> $DIR/minus-string.rs:6:5
|
-LL | fn main() { -"foo".to_string(); }
- | ^^^^^^^^^^^^^^^^^^ cannot apply unary operator `-`
+LL | -"foo".to_string();
+ | ^^^^^^^^^^^^^^^^^^ cannot apply unary operator `-`
|
note: the foreign item type `String` doesn't implement `Neg`
--> $SRC_DIR/alloc/src/string.rs:LL:COL
| diff --git a/tests/ui/writing-to-immutable-vec.rs b/tests/ui/borrowck/writing-to-immutable-vec.rs
rename from tests/ui/writing-to-immutable-vec.rs
rename to tests/ui/borrowck/writing-to-immutable-vec.rs
diff --git a/tests/ui/writing-to-immutable-vec.stderr b/tests/ui/borrowck/writing-to-immutable-vec.stderr
rename from tests/ui/writing-to-immutable-vec.stderr
rename to tests/ui/borrowck/writing-to-immutable-vec.stderr
diff --git a/tests/ui/deref-non-pointer.rs b/tests/ui/deref-patterns/deref-non-pointer.rs
rename from tests/ui/deref-non-pointer.rs
rename to tests/ui/deref-patterns/deref-non-pointer.rs
diff --git a/tests/ui/deref-non-pointer.stderr b/tests/ui/deref-patterns/deref-non-pointer.stderr
rename from tests/ui/deref-non-pointer.stderr
rename to tests/ui/deref-patterns/deref-non-pointer.stderr
diff --git a/tests/ui/lazy-and-or.rs b/tests/ui/lazy-and-or.rs
index f9dbeb68959a3..0000000000000
--- a/tests/ui/lazy-and-or.rs
@@ -1,12 +0,0 @@
-fn incr(x: &mut isize) -> bool { *x += 1; assert!((false)); return false; }
- let x = 1 == 2 || 3 == 3;
- assert!((x));
- let mut y: isize = 10;
- assert_eq!(y, 10);
- if true && x { assert!((true)); } else { assert!((false)); }
diff --git a/tests/ui/list.rs b/tests/ui/list.rs
index 443c4c9f28f88..0000000000000
--- a/tests/ui/list.rs
@@ -1,9 +0,0 @@
-#![allow(non_camel_case_types)]
-enum list { #[allow(dead_code)] cons(isize, Box<list>), nil, }
- list::cons(10, Box::new(list::cons(11, Box::new(list::cons(12, Box::new(list::nil))))));
diff --git a/tests/ui/minus-string.rs b/tests/ui/minus-string.rs
index b83347b937edf..0000000000000
--- a/tests/ui/minus-string.rs
@@ -1 +0,0 @@
-fn main() { -"foo".to_string(); } //~ ERROR cannot apply unary operator `-` to type `String`
diff --git a/tests/ui/or-patterns/lazy-and-or.rs b/tests/ui/or-patterns/lazy-and-or.rs
index 0000000000000..3d69553132b98
+++ b/tests/ui/or-patterns/lazy-and-or.rs
@@ -0,0 +1,25 @@
+// It ensures that the right-hand expression is not evaluated when the left-hand
+// expression is sufficient to determine the result.
+fn would_panic_if_called(x: &mut isize) -> bool {
+ *x += 1;
+ false
+ let x = 1 == 2 || 3 == 3;
+ assert!(x);
+ println!("Result of short-circuit: {}", x || would_panic_if_called(&mut y));
+ if true && x {
+ assert!(true);
+ } else {
+ assert!(false, "This branch should not be reached");
+ }
diff --git a/tests/ui/recursion/recursive-enum-box.rs b/tests/ui/recursion/recursive-enum-box.rs
index 0000000000000..540b0c553603c
+++ b/tests/ui/recursion/recursive-enum-box.rs
@@ -0,0 +1,21 @@
+// A smoke test for recursive enum structures using Box<T>.
+// This test constructs a linked list-like structure to exercise memory allocation and ownership.
+// Originally introduced in 2010, this is one of Rust’s earliest test cases.
+#![allow(dead_code)]
+enum List {
+ Cons(isize, Box<List>),
+ Nil,
+ List::Cons(
+ 10,
+ Box::new(List::Cons(
+ 11,
+ Box::new(List::Cons(12, Box::new(List::Nil))),
+ )),
+ );
diff --git a/tests/ui/typeck/minus-string.rs b/tests/ui/typeck/minus-string.rs
index 0000000000000..1c0f73a37132c
+++ b/tests/ui/typeck/minus-string.rs
@@ -0,0 +1,7 @@
+// Regression test for issue #813.
+// This ensures that the unary negation operator `-` cannot be applied to an owned `String`.
+// Previously, due to a type-checking bug, this was mistakenly accepted by the compiler.
+ -"foo".to_string(); //~ ERROR cannot apply unary operator `-` to type `String`
diff --git a/tests/ui/minus-string.stderr b/tests/ui/typeck/minus-string.stderr
similarity index 69%
rename from tests/ui/minus-string.stderr
rename to tests/ui/typeck/minus-string.stderr
index 153965c810ea7..d2ebcd01ff9c1 100644
--- a/tests/ui/minus-string.stderr
+++ b/tests/ui/typeck/minus-string.stderr
@@ -1,8 +1,8 @@
error[E0600]: cannot apply unary operator `-` to type `String`
- --> $DIR/minus-string.rs:1:13
+ --> $DIR/minus-string.rs:6:5
-LL | fn main() { -"foo".to_string(); }
- | ^^^^^^^^^^^^^^^^^^ cannot apply unary operator `-`
+LL | -"foo".to_string();
+ | ^^^^^^^^^^^^^^^^^^ cannot apply unary operator `-`
note: the foreign item type `String` doesn't implement `Neg`
--> $SRC_DIR/alloc/src/string.rs:LL:COL | [
"- println!(\"{}\", x || incr(&mut y));",
"+// This test verifies the short-circuiting behavior of logical operators `||` and `&&`.",
"+ assert!(false, \"This function should never be called due to short-circuiting\");",
"+ let mut y: isize = 10;",
"+ assert_eq!(y, 10, \"y should remain 10 if short-circuiting works correctly\");"
] | [
30,
63,
69,
77,
79
] | {
"additions": 56,
"author": "reddevilmidzy",
"deletions": 25,
"html_url": "https://github.com/rust-lang/rust/pull/140029",
"issue_id": 140029,
"merged_at": "2025-04-21T19:27:12Z",
"omission_probability": 0.1,
"pr_number": 140029,
"repo": "rust-lang/rust",
"title": "Tidying up UI tests [1/N]",
"total_changes": 81
} |
147 | diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs
index d3d1eebc22753..2ee25969289fc 100644
--- a/library/core/src/num/f128.rs
+++ b/library/core/src/num/f128.rs
@@ -145,6 +145,9 @@ impl f128 {
pub const RADIX: u32 = 2;
/// Number of significant digits in base 2.
+ ///
+ /// Note that the size of the mantissa in the bitwise representation is one
+ /// smaller than this since the leading 1 is not stored explicitly.
#[unstable(feature = "f128", issue = "116909")]
pub const MANTISSA_DIGITS: u32 = 113;
diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs
index dceb30177e668..69882d13c177f 100644
--- a/library/core/src/num/f16.rs
+++ b/library/core/src/num/f16.rs
@@ -140,6 +140,9 @@ impl f16 {
pub const RADIX: u32 = 2;
/// Number of significant digits in base 2.
+ ///
+ /// Note that the size of the mantissa in the bitwise representation is one
+ /// smaller than this since the leading 1 is not stored explicitly.
#[unstable(feature = "f16", issue = "116909")]
pub const MANTISSA_DIGITS: u32 = 11;
diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs
index c97dbfb63ae17..7e056a6c1f3fa 100644
--- a/library/core/src/num/f32.rs
+++ b/library/core/src/num/f32.rs
@@ -390,6 +390,9 @@ impl f32 {
pub const RADIX: u32 = 2;
/// Number of significant digits in base 2.
+ ///
+ /// Note that the size of the mantissa in the bitwise representation is one
+ /// smaller than this since the leading 1 is not stored explicitly.
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MANTISSA_DIGITS: u32 = 24;
diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs
index 91affdb3794b0..b9ebbb1d76497 100644
--- a/library/core/src/num/f64.rs
+++ b/library/core/src/num/f64.rs
@@ -390,6 +390,9 @@ impl f64 {
pub const RADIX: u32 = 2;
/// Number of significant digits in base 2.
+ ///
+ /// Note that the size of the mantissa in the bitwise representation is one
+ /// smaller than this since the leading 1 is not stored explicitly.
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MANTISSA_DIGITS: u32 = 53;
/// Approximate number of significant digits in base 10.
diff --git a/library/std/tests/floats/f128.rs b/library/std/tests/floats/f128.rs
index df28e8129ddd9..677738bac8f98 100644
--- a/library/std/tests/floats/f128.rs
+++ b/library/std/tests/floats/f128.rs
@@ -112,6 +112,8 @@ fn test_nan() {
assert!(!nan.is_sign_negative());
assert!(!nan.is_normal());
assert_eq!(Fp::Nan, nan.classify());
+ // Ensure the quiet bit is set.
+ assert!(nan.to_bits() & (1 << (f128::MANTISSA_DIGITS - 2)) != 0);
}
#[test]
diff --git a/library/std/tests/floats/f16.rs b/library/std/tests/floats/f16.rs
index 1a90f00aecceb..0fc4df8115a24 100644
--- a/library/std/tests/floats/f16.rs
+++ b/library/std/tests/floats/f16.rs
@@ -95,6 +95,8 @@ fn test_nan() {
assert!(!nan.is_sign_negative());
assert!(!nan.is_normal());
assert_eq!(Fp::Nan, nan.classify());
+ // Ensure the quiet bit is set.
+ assert!(nan.to_bits() & (1 << (f16::MANTISSA_DIGITS - 2)) != 0);
}
#[test]
diff --git a/library/std/tests/floats/f32.rs b/library/std/tests/floats/f32.rs
index d99b03cb255f7..9af23afc5bbfc 100644
--- a/library/std/tests/floats/f32.rs
+++ b/library/std/tests/floats/f32.rs
@@ -72,6 +72,8 @@ fn test_nan() {
assert!(nan.is_sign_positive());
assert!(!nan.is_sign_negative());
assert_eq!(Fp::Nan, nan.classify());
+ // Ensure the quiet bit is set.
+ assert!(nan.to_bits() & (1 << (f32::MANTISSA_DIGITS - 2)) != 0);
}
#[test]
diff --git a/library/std/tests/floats/f64.rs b/library/std/tests/floats/f64.rs
index 611670751bb52..de9c27eb33d39 100644
--- a/library/std/tests/floats/f64.rs
+++ b/library/std/tests/floats/f64.rs
@@ -60,6 +60,8 @@ fn test_nan() {
assert!(nan.is_sign_positive());
assert!(!nan.is_sign_negative());
assert_eq!(Fp::Nan, nan.classify());
+ // Ensure the quiet bit is set.
+ assert!(nan.to_bits() & (1 << (f64::MANTISSA_DIGITS - 2)) != 0);
}
#[test]
| diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs
index d3d1eebc22753..2ee25969289fc 100644
--- a/library/core/src/num/f128.rs
+++ b/library/core/src/num/f128.rs
@@ -145,6 +145,9 @@ impl f128 {
#[unstable(feature = "f128", issue = "116909")]
pub const MANTISSA_DIGITS: u32 = 113;
diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs
index dceb30177e668..69882d13c177f 100644
--- a/library/core/src/num/f16.rs
+++ b/library/core/src/num/f16.rs
@@ -140,6 +140,9 @@ impl f16 {
#[unstable(feature = "f16", issue = "116909")]
pub const MANTISSA_DIGITS: u32 = 11;
diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs
index c97dbfb63ae17..7e056a6c1f3fa 100644
--- a/library/core/src/num/f32.rs
+++ b/library/core/src/num/f32.rs
@@ -390,6 +390,9 @@ impl f32 {
pub const MANTISSA_DIGITS: u32 = 24;
diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs
index 91affdb3794b0..b9ebbb1d76497 100644
--- a/library/core/src/num/f64.rs
+++ b/library/core/src/num/f64.rs
@@ -390,6 +390,9 @@ impl f64 {
pub const MANTISSA_DIGITS: u32 = 53;
/// Approximate number of significant digits in base 10.
diff --git a/library/std/tests/floats/f128.rs b/library/std/tests/floats/f128.rs
index df28e8129ddd9..677738bac8f98 100644
--- a/library/std/tests/floats/f128.rs
+++ b/library/std/tests/floats/f128.rs
@@ -112,6 +112,8 @@ fn test_nan() {
+ assert!(nan.to_bits() & (1 << (f128::MANTISSA_DIGITS - 2)) != 0);
diff --git a/library/std/tests/floats/f16.rs b/library/std/tests/floats/f16.rs
index 1a90f00aecceb..0fc4df8115a24 100644
--- a/library/std/tests/floats/f16.rs
+++ b/library/std/tests/floats/f16.rs
@@ -95,6 +95,8 @@ fn test_nan() {
+ assert!(nan.to_bits() & (1 << (f16::MANTISSA_DIGITS - 2)) != 0);
diff --git a/library/std/tests/floats/f32.rs b/library/std/tests/floats/f32.rs
index d99b03cb255f7..9af23afc5bbfc 100644
--- a/library/std/tests/floats/f32.rs
+++ b/library/std/tests/floats/f32.rs
@@ -72,6 +72,8 @@ fn test_nan() {
+ assert!(nan.to_bits() & (1 << (f32::MANTISSA_DIGITS - 2)) != 0);
diff --git a/library/std/tests/floats/f64.rs b/library/std/tests/floats/f64.rs
index 611670751bb52..de9c27eb33d39 100644
--- a/library/std/tests/floats/f64.rs
+++ b/library/std/tests/floats/f64.rs
@@ -60,6 +60,8 @@ fn test_nan() {
+ assert!(nan.to_bits() & (1 << (f64::MANTISSA_DIGITS - 2)) != 0); | [] | [] | {
"additions": 20,
"author": "RalfJung",
"deletions": 0,
"html_url": "https://github.com/rust-lang/rust/pull/140149",
"issue_id": 140149,
"merged_at": "2025-04-23T01:16:10Z",
"omission_probability": 0.1,
"pr_number": 140149,
"repo": "rust-lang/rust",
"title": "test_nan: ensure the NAN contant is quiet",
"total_changes": 20
} |
148 | diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs
index c2c78dd9c67eb..a033b8bd30514 100644
--- a/library/core/src/fmt/mod.rs
+++ b/library/core/src/fmt/mod.rs
@@ -596,7 +596,7 @@ impl<'a> Arguments<'a> {
/// When using the format_args!() macro, this function is used to generate the
/// Arguments structure.
#[inline]
- pub fn new_v1<const P: usize, const A: usize>(
+ pub const fn new_v1<const P: usize, const A: usize>(
pieces: &'a [&'static str; P],
args: &'a [rt::Argument<'a>; A],
) -> Arguments<'a> {
@@ -612,7 +612,7 @@ impl<'a> Arguments<'a> {
/// 2. Every `rt::Placeholder::position` value within `fmt` must be a valid index of `args`.
/// 3. Every `rt::Count::Param` within `fmt` must contain a valid index of `args`.
#[inline]
- pub fn new_v1_formatted(
+ pub const fn new_v1_formatted(
pieces: &'a [&'static str],
args: &'a [rt::Argument<'a>],
fmt: &'a [rt::Placeholder],
diff --git a/library/core/src/fmt/rt.rs b/library/core/src/fmt/rt.rs
index 94341a4da66cd..85d089a079082 100644
--- a/library/core/src/fmt/rt.rs
+++ b/library/core/src/fmt/rt.rs
@@ -96,12 +96,12 @@ pub struct Argument<'a> {
#[rustc_diagnostic_item = "ArgumentMethods"]
impl Argument<'_> {
#[inline]
- fn new<'a, T>(x: &'a T, f: fn(&T, &mut Formatter<'_>) -> Result) -> Argument<'a> {
+ const fn new<'a, T>(x: &'a T, f: fn(&T, &mut Formatter<'_>) -> Result) -> Argument<'a> {
Argument {
// INVARIANT: this creates an `ArgumentType<'a>` from a `&'a T` and
// a `fn(&T, ...)`, so the invariant is maintained.
ty: ArgumentType::Placeholder {
- value: NonNull::from(x).cast(),
+ value: NonNull::from_ref(x).cast(),
// SAFETY: function pointers always have the same layout.
formatter: unsafe { mem::transmute(f) },
_lifetime: PhantomData,
@@ -150,7 +150,7 @@ impl Argument<'_> {
Self::new(x, UpperExp::fmt)
}
#[inline]
- pub fn from_usize(x: &usize) -> Argument<'_> {
+ pub const fn from_usize(x: &usize) -> Argument<'_> {
Argument { ty: ArgumentType::Count(*x) }
}
@@ -181,7 +181,7 @@ impl Argument<'_> {
}
#[inline]
- pub(super) fn as_usize(&self) -> Option<usize> {
+ pub(super) const fn as_usize(&self) -> Option<usize> {
match self.ty {
ArgumentType::Count(count) => Some(count),
ArgumentType::Placeholder { .. } => None,
@@ -199,7 +199,7 @@ impl Argument<'_> {
/// println!("{f}");
/// ```
#[inline]
- pub fn none() -> [Self; 0] {
+ pub const fn none() -> [Self; 0] {
[]
}
}
@@ -216,7 +216,7 @@ impl UnsafeArg {
/// See documentation where `UnsafeArg` is required to know when it is safe to
/// create and use `UnsafeArg`.
#[inline]
- pub unsafe fn new() -> Self {
+ pub const unsafe fn new() -> Self {
Self { _private: () }
}
}
diff --git a/tests/ui/consts/const-eval/format.rs b/tests/ui/consts/const-eval/format.rs
index e56d15e935bc5..1878fc0382767 100644
--- a/tests/ui/consts/const-eval/format.rs
+++ b/tests/ui/consts/const-eval/format.rs
@@ -1,13 +1,11 @@
const fn failure() {
panic!("{:?}", 0);
//~^ ERROR cannot call non-const formatting macro in constant functions
- //~| ERROR cannot call non-const associated function `Arguments::<'_>::new_v1::<1, 1>` in constant functions
}
const fn print() {
println!("{:?}", 0);
//~^ ERROR cannot call non-const formatting macro in constant functions
- //~| ERROR cannot call non-const associated function `Arguments::<'_>::new_v1::<2, 1>` in constant functions
//~| ERROR cannot call non-const function `_print` in constant functions
}
diff --git a/tests/ui/consts/const-eval/format.stderr b/tests/ui/consts/const-eval/format.stderr
index 25ed44e0f3382..af90acc2a2605 100644
--- a/tests/ui/consts/const-eval/format.stderr
+++ b/tests/ui/consts/const-eval/format.stderr
@@ -7,17 +7,8 @@ LL | panic!("{:?}", 0);
= note: calls in constant functions are limited to constant functions, tuple structs and tuple variants
= note: this error originates in the macro `$crate::const_format_args` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
-error[E0015]: cannot call non-const associated function `Arguments::<'_>::new_v1::<1, 1>` in constant functions
- --> $DIR/format.rs:2:5
- |
-LL | panic!("{:?}", 0);
- | ^^^^^^^^^^^^^^^^^
- |
- = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants
- = note: this error originates in the macro `$crate::const_format_args` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
-
error[E0015]: cannot call non-const formatting macro in constant functions
- --> $DIR/format.rs:8:15
+ --> $DIR/format.rs:7:15
|
LL | println!("{:?}", 0);
| ^^^^
@@ -25,17 +16,8 @@ LL | println!("{:?}", 0);
= note: calls in constant functions are limited to constant functions, tuple structs and tuple variants
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
-error[E0015]: cannot call non-const associated function `Arguments::<'_>::new_v1::<2, 1>` in constant functions
- --> $DIR/format.rs:8:5
- |
-LL | println!("{:?}", 0);
- | ^^^^^^^^^^^^^^^^^^^
- |
- = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants
- = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
-
error[E0015]: cannot call non-const function `_print` in constant functions
- --> $DIR/format.rs:8:5
+ --> $DIR/format.rs:7:5
|
LL | println!("{:?}", 0);
| ^^^^^^^^^^^^^^^^^^^
@@ -43,6 +25,6 @@ LL | println!("{:?}", 0);
= note: calls in constant functions are limited to constant functions, tuple structs and tuple variants
= note: this error originates in the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
-error: aborting due to 5 previous errors
+error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0015`.
| diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs
index c2c78dd9c67eb..a033b8bd30514 100644
--- a/library/core/src/fmt/mod.rs
+++ b/library/core/src/fmt/mod.rs
@@ -596,7 +596,7 @@ impl<'a> Arguments<'a> {
/// When using the format_args!() macro, this function is used to generate the
/// Arguments structure.
- pub fn new_v1<const P: usize, const A: usize>(
pieces: &'a [&'static str; P],
args: &'a [rt::Argument<'a>; A],
) -> Arguments<'a> {
@@ -612,7 +612,7 @@ impl<'a> Arguments<'a> {
/// 2. Every `rt::Placeholder::position` value within `fmt` must be a valid index of `args`.
/// 3. Every `rt::Count::Param` within `fmt` must contain a valid index of `args`.
- pub fn new_v1_formatted(
+ pub const fn new_v1_formatted(
pieces: &'a [&'static str],
args: &'a [rt::Argument<'a>],
fmt: &'a [rt::Placeholder],
diff --git a/library/core/src/fmt/rt.rs b/library/core/src/fmt/rt.rs
index 94341a4da66cd..85d089a079082 100644
--- a/library/core/src/fmt/rt.rs
+++ b/library/core/src/fmt/rt.rs
@@ -96,12 +96,12 @@ pub struct Argument<'a> {
#[rustc_diagnostic_item = "ArgumentMethods"]
impl Argument<'_> {
- fn new<'a, T>(x: &'a T, f: fn(&T, &mut Formatter<'_>) -> Result) -> Argument<'a> {
+ const fn new<'a, T>(x: &'a T, f: fn(&T, &mut Formatter<'_>) -> Result) -> Argument<'a> {
Argument {
// INVARIANT: this creates an `ArgumentType<'a>` from a `&'a T` and
// a `fn(&T, ...)`, so the invariant is maintained.
ty: ArgumentType::Placeholder {
- value: NonNull::from(x).cast(),
+ value: NonNull::from_ref(x).cast(),
// SAFETY: function pointers always have the same layout.
formatter: unsafe { mem::transmute(f) },
_lifetime: PhantomData,
@@ -150,7 +150,7 @@ impl Argument<'_> {
Self::new(x, UpperExp::fmt)
+ pub const fn from_usize(x: &usize) -> Argument<'_> {
Argument { ty: ArgumentType::Count(*x) }
@@ -181,7 +181,7 @@ impl Argument<'_> {
- pub(super) fn as_usize(&self) -> Option<usize> {
+ pub(super) const fn as_usize(&self) -> Option<usize> {
match self.ty {
ArgumentType::Count(count) => Some(count),
ArgumentType::Placeholder { .. } => None,
@@ -199,7 +199,7 @@ impl Argument<'_> {
/// println!("{f}");
/// ```
- pub fn none() -> [Self; 0] {
+ pub const fn none() -> [Self; 0] {
[]
@@ -216,7 +216,7 @@ impl UnsafeArg {
/// See documentation where `UnsafeArg` is required to know when it is safe to
/// create and use `UnsafeArg`.
- pub unsafe fn new() -> Self {
+ pub const unsafe fn new() -> Self {
Self { _private: () }
diff --git a/tests/ui/consts/const-eval/format.rs b/tests/ui/consts/const-eval/format.rs
index e56d15e935bc5..1878fc0382767 100644
--- a/tests/ui/consts/const-eval/format.rs
+++ b/tests/ui/consts/const-eval/format.rs
@@ -1,13 +1,11 @@
const fn failure() {
panic!("{:?}", 0);
- //~| ERROR cannot call non-const associated function `Arguments::<'_>::new_v1::<1, 1>` in constant functions
const fn print() {
println!("{:?}", 0);
- //~| ERROR cannot call non-const associated function `Arguments::<'_>::new_v1::<2, 1>` in constant functions
//~| ERROR cannot call non-const function `_print` in constant functions
diff --git a/tests/ui/consts/const-eval/format.stderr b/tests/ui/consts/const-eval/format.stderr
index 25ed44e0f3382..af90acc2a2605 100644
--- a/tests/ui/consts/const-eval/format.stderr
+++ b/tests/ui/consts/const-eval/format.stderr
@@ -7,17 +7,8 @@ LL | panic!("{:?}", 0);
= note: this error originates in the macro `$crate::const_format_args` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
-error[E0015]: cannot call non-const associated function `Arguments::<'_>::new_v1::<1, 1>` in constant functions
- --> $DIR/format.rs:2:5
-LL | panic!("{:?}", 0);
- = note: this error originates in the macro `$crate::const_format_args` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0015]: cannot call non-const formatting macro in constant functions
- --> $DIR/format.rs:8:15
+ --> $DIR/format.rs:7:15
| ^^^^
@@ -25,17 +16,8 @@ LL | println!("{:?}", 0);
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
-error[E0015]: cannot call non-const associated function `Arguments::<'_>::new_v1::<2, 1>` in constant functions
-LL | println!("{:?}", 0);
- | ^^^^^^^^^^^^^^^^^^^
- = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0015]: cannot call non-const function `_print` in constant functions
+ --> $DIR/format.rs:7:5
| ^^^^^^^^^^^^^^^^^^^
@@ -43,6 +25,6 @@ LL | println!("{:?}", 0);
= note: this error originates in the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
-error: aborting due to 5 previous errors
+error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0015`. | [
"+ pub const fn new_v1<const P: usize, const A: usize>(",
"- pub fn from_usize(x: &usize) -> Argument<'_> {",
"- | ^^^^^^^^^^^^^^^^^"
] | [
9,
45,
107
] | {
"additions": 11,
"author": "c410-f3r",
"deletions": 31,
"html_url": "https://github.com/rust-lang/rust/pull/135139",
"issue_id": 135139,
"merged_at": "2025-01-07T07:20:09Z",
"omission_probability": 0.1,
"pr_number": 135139,
"repo": "rust-lang/rust",
"title": "[generic_assert] Constify methods used by the formatting system",
"total_changes": 42
} |
149 | diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs
index 763e9207a126b..42fe01b1c84c3 100644
--- a/compiler/rustc_resolve/src/build_reduced_graph.rs
+++ b/compiler/rustc_resolve/src/build_reduced_graph.rs
@@ -1115,7 +1115,6 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
}
});
} else {
- #[allow(rustc::potential_query_instability)] // FIXME
for ident in single_imports.iter().cloned() {
let result = self.r.maybe_resolve_ident_in_module(
ModuleOrUniformRoot::Module(module),
diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs
index 5361af98f3c74..7decc2a09721f 100644
--- a/compiler/rustc_resolve/src/diagnostics.rs
+++ b/compiler/rustc_resolve/src/diagnostics.rs
@@ -1468,7 +1468,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
return;
}
- #[allow(rustc::potential_query_instability)] // FIXME
let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
});
diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs
index 27d63198836a3..5f0a2a597e9b4 100644
--- a/compiler/rustc_resolve/src/ident.rs
+++ b/compiler/rustc_resolve/src/ident.rs
@@ -946,7 +946,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// Check if one of single imports can still define the name,
// if it can then our result is not determined and can be invalidated.
- #[allow(rustc::potential_query_instability)] // FIXME
for single_import in &resolution.single_imports {
if ignore_import == Some(*single_import) {
// This branch handles a cycle in single imports.
diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs
index 89b9a07435183..454460e10dc98 100644
--- a/compiler/rustc_resolve/src/imports.rs
+++ b/compiler/rustc_resolve/src/imports.rs
@@ -4,7 +4,7 @@ use std::cell::Cell;
use std::mem;
use rustc_ast::NodeId;
-use rustc_data_structures::fx::FxHashSet;
+use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
use rustc_data_structures::intern::Interned;
use rustc_errors::codes::*;
use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err};
@@ -233,7 +233,7 @@ impl<'ra> ImportData<'ra> {
pub(crate) struct NameResolution<'ra> {
/// Single imports that may define the name in the namespace.
/// Imports are arena-allocated, so it's ok to use pointers as keys.
- pub single_imports: FxHashSet<Import<'ra>>,
+ pub single_imports: FxIndexSet<Import<'ra>>,
/// The least shadowable known binding for this name, or None if there are no known bindings.
pub binding: Option<NameBinding<'ra>>,
pub shadowed_glob: Option<NameBinding<'ra>>,
@@ -494,7 +494,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let key = BindingKey::new(target, ns);
let _ = this.try_define(import.parent_scope.module, key, dummy_binding, false);
this.update_resolution(import.parent_scope.module, key, false, |_, resolution| {
- resolution.single_imports.remove(&import);
+ resolution.single_imports.swap_remove(&import);
})
});
self.record_use(target, dummy_binding, Used::Other);
@@ -862,7 +862,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
}
let key = BindingKey::new(target, ns);
this.update_resolution(parent, key, false, |_, resolution| {
- resolution.single_imports.remove(&import);
+ resolution.single_imports.swap_remove(&import);
});
}
}
diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs
index 6056a69ee71f6..dd663ce057e2e 100644
--- a/compiler/rustc_resolve/src/late.rs
+++ b/compiler/rustc_resolve/src/late.rs
@@ -672,7 +672,7 @@ struct DiagMetadata<'ast> {
/// A list of labels as of yet unused. Labels will be removed from this map when
/// they are used (in a `break` or `continue` statement)
- unused_labels: FxHashMap<NodeId, Span>,
+ unused_labels: FxIndexMap<NodeId, Span>,
/// Only used for better errors on `let x = { foo: bar };`.
/// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
@@ -4779,7 +4779,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
Ok((node_id, _)) => {
// Since this res is a label, it is never read.
self.r.label_res_map.insert(expr.id, node_id);
- self.diag_metadata.unused_labels.remove(&node_id);
+ self.diag_metadata.unused_labels.swap_remove(&node_id);
}
Err(error) => {
self.report_error(label.ident.span, error);
@@ -5201,7 +5201,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let mut late_resolution_visitor = LateResolutionVisitor::new(self);
late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
visit::walk_crate(&mut late_resolution_visitor, krate);
- #[allow(rustc::potential_query_instability)] // FIXME
for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
self.lint_buffer.buffer_lint(
lint::builtin::UNUSED_LABELS,
diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs
index 3d666055a94fb..69a7c81956aad 100644
--- a/compiler/rustc_resolve/src/late/diagnostics.rs
+++ b/compiler/rustc_resolve/src/late/diagnostics.rs
@@ -1036,7 +1036,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
Applicability::MaybeIncorrect,
);
// Do not lint against unused label when we suggest them.
- self.diag_metadata.unused_labels.remove(node_id);
+ self.diag_metadata.unused_labels.swap_remove(node_id);
}
}
}
diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs
index ff31af0025b54..78153fd417407 100644
--- a/compiler/rustc_resolve/src/lib.rs
+++ b/compiler/rustc_resolve/src/lib.rs
@@ -1137,7 +1137,7 @@ pub struct Resolver<'ra, 'tcx> {
non_macro_attr: MacroData,
local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
- unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
+ unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
/// A map from the macro to all its potentially unused arms.
unused_macro_rules: FxIndexMap<LocalDefId, UnordMap<usize, (Ident, Span)>>,
proc_macro_stubs: FxHashSet<LocalDefId>,
diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs
index c4304a7a6df6a..d577d7e807928 100644
--- a/compiler/rustc_resolve/src/macros.rs
+++ b/compiler/rustc_resolve/src/macros.rs
@@ -323,7 +323,6 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
}
fn check_unused_macros(&mut self) {
- #[allow(rustc::potential_query_instability)] // FIXME
for (_, &(node_id, ident)) in self.unused_macros.iter() {
self.lint_buffer.buffer_lint(
UNUSED_MACROS,
@@ -576,7 +575,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
match res {
Res::Def(DefKind::Macro(_), def_id) => {
if let Some(def_id) = def_id.as_local() {
- self.unused_macros.remove(&def_id);
+ self.unused_macros.swap_remove(&def_id);
if self.proc_macro_stubs.contains(&def_id) {
self.dcx().emit_err(errors::ProcMacroSameCrate {
span: path.span,
| diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs
index 763e9207a126b..42fe01b1c84c3 100644
--- a/compiler/rustc_resolve/src/build_reduced_graph.rs
+++ b/compiler/rustc_resolve/src/build_reduced_graph.rs
@@ -1115,7 +1115,6 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
} else {
- #[allow(rustc::potential_query_instability)] // FIXME
for ident in single_imports.iter().cloned() {
let result = self.r.maybe_resolve_ident_in_module(
ModuleOrUniformRoot::Module(module),
diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs
index 5361af98f3c74..7decc2a09721f 100644
--- a/compiler/rustc_resolve/src/diagnostics.rs
+++ b/compiler/rustc_resolve/src/diagnostics.rs
@@ -1468,7 +1468,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
return;
}
let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
});
diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs
index 27d63198836a3..5f0a2a597e9b4 100644
--- a/compiler/rustc_resolve/src/ident.rs
+++ b/compiler/rustc_resolve/src/ident.rs
@@ -946,7 +946,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// Check if one of single imports can still define the name,
// if it can then our result is not determined and can be invalidated.
for single_import in &resolution.single_imports {
if ignore_import == Some(*single_import) {
// This branch handles a cycle in single imports.
diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs
index 89b9a07435183..454460e10dc98 100644
--- a/compiler/rustc_resolve/src/imports.rs
+++ b/compiler/rustc_resolve/src/imports.rs
@@ -4,7 +4,7 @@ use std::cell::Cell;
use std::mem;
use rustc_ast::NodeId;
-use rustc_data_structures::fx::FxHashSet;
+use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
use rustc_data_structures::intern::Interned;
use rustc_errors::codes::*;
use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err};
@@ -233,7 +233,7 @@ impl<'ra> ImportData<'ra> {
pub(crate) struct NameResolution<'ra> {
/// Single imports that may define the name in the namespace.
/// Imports are arena-allocated, so it's ok to use pointers as keys.
+ pub single_imports: FxIndexSet<Import<'ra>>,
/// The least shadowable known binding for this name, or None if there are no known bindings.
pub binding: Option<NameBinding<'ra>>,
pub shadowed_glob: Option<NameBinding<'ra>>,
@@ -494,7 +494,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let key = BindingKey::new(target, ns);
let _ = this.try_define(import.parent_scope.module, key, dummy_binding, false);
this.update_resolution(import.parent_scope.module, key, false, |_, resolution| {
- resolution.single_imports.remove(&import);
+ resolution.single_imports.swap_remove(&import);
})
self.record_use(target, dummy_binding, Used::Other);
@@ -862,7 +862,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let key = BindingKey::new(target, ns);
this.update_resolution(parent, key, false, |_, resolution| {
- resolution.single_imports.remove(&import);
+ resolution.single_imports.swap_remove(&import);
});
diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs
index 6056a69ee71f6..dd663ce057e2e 100644
--- a/compiler/rustc_resolve/src/late.rs
+++ b/compiler/rustc_resolve/src/late.rs
@@ -672,7 +672,7 @@ struct DiagMetadata<'ast> {
/// A list of labels as of yet unused. Labels will be removed from this map when
/// they are used (in a `break` or `continue` statement)
- unused_labels: FxHashMap<NodeId, Span>,
/// Only used for better errors on `let x = { foo: bar };`.
/// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
@@ -4779,7 +4779,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
Ok((node_id, _)) => {
// Since this res is a label, it is never read.
self.r.label_res_map.insert(expr.id, node_id);
- self.diag_metadata.unused_labels.remove(&node_id);
+ self.diag_metadata.unused_labels.swap_remove(&node_id);
Err(error) => {
self.report_error(label.ident.span, error);
@@ -5201,7 +5201,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let mut late_resolution_visitor = LateResolutionVisitor::new(self);
late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
visit::walk_crate(&mut late_resolution_visitor, krate);
for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
lint::builtin::UNUSED_LABELS,
diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs
index 3d666055a94fb..69a7c81956aad 100644
--- a/compiler/rustc_resolve/src/late/diagnostics.rs
+++ b/compiler/rustc_resolve/src/late/diagnostics.rs
@@ -1036,7 +1036,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
Applicability::MaybeIncorrect,
);
// Do not lint against unused label when we suggest them.
- self.diag_metadata.unused_labels.remove(node_id);
+ self.diag_metadata.unused_labels.swap_remove(node_id);
}
diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs
index ff31af0025b54..78153fd417407 100644
--- a/compiler/rustc_resolve/src/lib.rs
+++ b/compiler/rustc_resolve/src/lib.rs
@@ -1137,7 +1137,7 @@ pub struct Resolver<'ra, 'tcx> {
non_macro_attr: MacroData,
local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
- unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
+ unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
/// A map from the macro to all its potentially unused arms.
unused_macro_rules: FxIndexMap<LocalDefId, UnordMap<usize, (Ident, Span)>>,
proc_macro_stubs: FxHashSet<LocalDefId>,
diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs
index c4304a7a6df6a..d577d7e807928 100644
--- a/compiler/rustc_resolve/src/macros.rs
+++ b/compiler/rustc_resolve/src/macros.rs
@@ -323,7 +323,6 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
}
fn check_unused_macros(&mut self) {
for (_, &(node_id, ident)) in self.unused_macros.iter() {
UNUSED_MACROS,
@@ -576,7 +575,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
match res {
Res::Def(DefKind::Macro(_), def_id) => {
if let Some(def_id) = def_id.as_local() {
- self.unused_macros.remove(&def_id);
+ self.unused_macros.swap_remove(&def_id);
if self.proc_macro_stubs.contains(&def_id) {
self.dcx().emit_err(errors::ProcMacroSameCrate {
span: path.span, | [
"- pub single_imports: FxHashSet<Import<'ra>>,",
"+ unused_labels: FxIndexMap<NodeId, Span>,"
] | [
53,
85
] | {
"additions": 9,
"author": "petrochenkov",
"deletions": 14,
"html_url": "https://github.com/rust-lang/rust/pull/138580",
"issue_id": 138580,
"merged_at": "2025-03-25T16:41:36Z",
"omission_probability": 0.1,
"pr_number": 138580,
"repo": "rust-lang/rust",
"title": "resolve: Avoid some unstable iteration 2",
"total_changes": 23
} |
150 | diff --git a/package.json b/package.json
index b5e435d6dd68..03b0538361e3 100644
--- a/package.json
+++ b/package.json
@@ -140,7 +140,7 @@
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
- "knip": "5.47.0",
+ "knip": "5.50.5",
"magic-string": "0.30.17",
"nano-spawn": "0.2.0",
"node-style-text": "0.0.7",
diff --git a/yarn.lock b/yarn.lock
index 47dd283d3e71..5b0857fbbebe 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1907,16 +1907,6 @@ __metadata:
languageName: node
linkType: hard
-"@nodelib/fs.scandir@npm:4.0.1":
- version: 4.0.1
- resolution: "@nodelib/fs.scandir@npm:4.0.1"
- dependencies:
- "@nodelib/fs.stat": "npm:4.0.0"
- run-parallel: "npm:^1.2.0"
- checksum: 10/44b2b2b34e48ca88ee004413f5033db31cd6d5ecf8c7bbef0e33b6672d603f3e23b57d5fbb1bd5f83f8992df58381be6600006d92a903f085e698a37bdfe3c89
- languageName: node
- linkType: hard
-
"@nodelib/fs.stat@npm:2.0.5, @nodelib/fs.stat@npm:^2.0.2":
version: 2.0.5
resolution: "@nodelib/fs.stat@npm:2.0.5"
@@ -1924,23 +1914,6 @@ __metadata:
languageName: node
linkType: hard
-"@nodelib/fs.stat@npm:4.0.0":
- version: 4.0.0
- resolution: "@nodelib/fs.stat@npm:4.0.0"
- checksum: 10/1f87199fdab938d2ed6f5e10debc006f7965081e2cd147ed3d2333049a030cad1949bd76556a5f5364f062c3e1edcc3d0981189b065336fc92c503ead463f4e1
- languageName: node
- linkType: hard
-
-"@nodelib/fs.walk@npm:3.0.1":
- version: 3.0.1
- resolution: "@nodelib/fs.walk@npm:3.0.1"
- dependencies:
- "@nodelib/fs.scandir": "npm:4.0.1"
- fastq: "npm:^1.15.0"
- checksum: 10/7b76a0139dec52e3f2a3a0bb4f13dbf72a6b79d8076ec4b5deea9e75bd1b79d7abda53776f93b5aefda9a5e40f0e31f49f6e35bf5460a402f0aee7bcf3b26d85
- languageName: node
- linkType: hard
-
"@nodelib/fs.walk@npm:^1.2.3":
version: 1.2.8
resolution: "@nodelib/fs.walk@npm:1.2.8"
@@ -2069,19 +2042,6 @@ __metadata:
languageName: node
linkType: hard
-"@snyk/github-codeowners@npm:1.1.0":
- version: 1.1.0
- resolution: "@snyk/github-codeowners@npm:1.1.0"
- dependencies:
- commander: "npm:^4.1.1"
- ignore: "npm:^5.1.8"
- p-map: "npm:^4.0.0"
- bin:
- github-codeowners: dist/cli.js
- checksum: 10/34120ef622616fef1ed8af12869d8c1803842aafa3fbacca263805ee7c85f58d11bdc301ef698c9b41268b275b9fd090f5d9f6d89c556abe9d52196e72d1c510
- languageName: node
- linkType: hard
-
"@stylistic/eslint-plugin-js@npm:4.2.0":
version: 4.2.0
resolution: "@stylistic/eslint-plugin-js@npm:4.2.0"
@@ -2380,16 +2340,6 @@ __metadata:
languageName: node
linkType: hard
-"aggregate-error@npm:^3.0.0":
- version: 3.1.0
- resolution: "aggregate-error@npm:3.1.0"
- dependencies:
- clean-stack: "npm:^2.0.0"
- indent-string: "npm:^4.0.0"
- checksum: 10/1101a33f21baa27a2fa8e04b698271e64616b886795fd43c31068c07533c7b3facfcaf4e9e0cab3624bd88f729a592f1c901a1a229c9e490eafce411a8644b79
- languageName: node
- linkType: hard
-
"ajv@npm:^6.12.4":
version: 6.12.6
resolution: "ajv@npm:6.12.6"
@@ -3000,13 +2950,6 @@ __metadata:
languageName: node
linkType: hard
-"clean-stack@npm:^2.0.0":
- version: 2.2.0
- resolution: "clean-stack@npm:2.2.0"
- checksum: 10/2ac8cd2b2f5ec986a3c743935ec85b07bc174d5421a5efc8017e1f146a1cf5f781ae962618f416352103b32c9cd7e203276e8c28241bbe946160cab16149fb68
- languageName: node
- linkType: hard
-
"clear-module@npm:^4.1.2":
version: 4.1.2
resolution: "clear-module@npm:4.1.2"
@@ -3102,13 +3045,6 @@ __metadata:
languageName: node
linkType: hard
-"commander@npm:^4.1.1":
- version: 4.1.1
- resolution: "commander@npm:4.1.1"
- checksum: 10/3b2dc4125f387dab73b3294dbcb0ab2a862f9c0ad748ee2b27e3544d25325b7a8cdfbcc228d103a98a716960b14478114a5206b5415bd48cdafa38797891562c
- languageName: node
- linkType: hard
-
"comment-json@npm:^4.2.5":
version: 4.2.5
resolution: "comment-json@npm:4.2.5"
@@ -4353,7 +4289,7 @@ __metadata:
languageName: node
linkType: hard
-"fastq@npm:^1.15.0, fastq@npm:^1.6.0":
+"fastq@npm:^1.6.0":
version: 1.19.1
resolution: "fastq@npm:1.19.1"
dependencies:
@@ -4919,7 +4855,7 @@ __metadata:
languageName: node
linkType: hard
-"ignore@npm:^5.1.8, ignore@npm:^5.2.0, ignore@npm:^5.3.1, ignore@npm:^5.3.2":
+"ignore@npm:^5.2.0, ignore@npm:^5.3.1, ignore@npm:^5.3.2":
version: 5.3.2
resolution: "ignore@npm:5.3.2"
checksum: 10/cceb6a457000f8f6a50e1196429750d782afce5680dd878aa4221bd79972d68b3a55b4b1458fc682be978f4d3c6a249046aa0880637367216444ab7b014cfc98
@@ -4962,13 +4898,6 @@ __metadata:
languageName: node
linkType: hard
-"indent-string@npm:^4.0.0":
- version: 4.0.0
- resolution: "indent-string@npm:4.0.0"
- checksum: 10/cd3f5cbc9ca2d624c6a1f53f12e6b341659aba0e2d3254ae2b4464aaea8b4294cdb09616abbc59458f980531f2429784ed6a420d48d245bcad0811980c9efae9
- languageName: node
- linkType: hard
-
"indent-string@npm:^5.0.0":
version: 5.0.0
resolution: "indent-string@npm:5.0.0"
@@ -6114,12 +6043,11 @@ __metadata:
languageName: node
linkType: hard
-"knip@npm:5.47.0":
- version: 5.47.0
- resolution: "knip@npm:5.47.0"
+"knip@npm:5.50.5":
+ version: 5.50.5
+ resolution: "knip@npm:5.50.5"
dependencies:
- "@nodelib/fs.walk": "npm:3.0.1"
- "@snyk/github-codeowners": "npm:1.1.0"
+ "@nodelib/fs.walk": "npm:^1.2.3"
easy-table: "npm:1.2.0"
enhanced-resolve: "npm:^5.18.1"
fast-glob: "npm:^3.3.3"
@@ -6131,7 +6059,6 @@ __metadata:
pretty-ms: "npm:^9.0.0"
smol-toml: "npm:^1.3.1"
strip-json-comments: "npm:5.0.1"
- summary: "npm:2.1.0"
zod: "npm:^3.22.4"
zod-validation-error: "npm:^3.0.3"
peerDependencies:
@@ -6140,7 +6067,7 @@ __metadata:
bin:
knip: bin/knip.js
knip-bun: bin/knip-bun.js
- checksum: 10/3ce2f98c39cb81a7ac1a3ae78471b219bbebaa4f470153265fbc8fdd5b40f63e314113934cc72adfb5d7ae2e1549d1bb415e49569d0d8a0abe61f32ab078f848
+ checksum: 10/d98db9d0b81a0e6113fe412e3063e9a9e49f9ab15f9a9a729301c73df27c9ffd458d7ed5df291075bcda0c0baaad6e0395af827c57a0947f86ceff901682b6e9
languageName: node
linkType: hard
@@ -6752,15 +6679,6 @@ __metadata:
languageName: node
linkType: hard
-"p-map@npm:^4.0.0":
- version: 4.0.0
- resolution: "p-map@npm:4.0.0"
- dependencies:
- aggregate-error: "npm:^3.0.0"
- checksum: 10/7ba4a2b1e24c05e1fc14bbaea0fc6d85cf005ae7e9c9425d4575550f37e2e584b1af97bcde78eacd7559208f20995988d52881334db16cf77bc1bcf68e48ed7c
- languageName: node
- linkType: hard
-
"p-map@npm:^7.0.2":
version: 7.0.3
resolution: "p-map@npm:7.0.3"
@@ -7153,7 +7071,7 @@ __metadata:
jest-watch-typeahead: "npm:2.2.2"
js-yaml: "npm:4.1.0"
json5: "npm:2.2.3"
- knip: "npm:5.47.0"
+ knip: "npm:5.50.5"
leven: "npm:4.0.0"
linguist-languages: "npm:7.29.0"
magic-string: "npm:0.30.17"
@@ -7567,7 +7485,7 @@ __metadata:
languageName: node
linkType: hard
-"run-parallel@npm:^1.1.9, run-parallel@npm:^1.2.0":
+"run-parallel@npm:^1.1.9":
version: 1.2.0
resolution: "run-parallel@npm:1.2.0"
dependencies:
@@ -8045,13 +7963,6 @@ __metadata:
languageName: node
linkType: hard
-"summary@npm:2.1.0":
- version: 2.1.0
- resolution: "summary@npm:2.1.0"
- checksum: 10/10ac12ce12c013b56ad44c37cfac206961f0993d98867b33b1b03a27b38a1cf8dd2db0b788883356c5335bbbb37d953772ef4a381d6fc8f408faf99f2bc54af5
- languageName: node
- linkType: hard
-
"supports-color@npm:^5.3.0":
version: 5.5.0
resolution: "supports-color@npm:5.5.0"
| diff --git a/package.json b/package.json
index b5e435d6dd68..03b0538361e3 100644
--- a/package.json
+++ b/package.json
@@ -140,7 +140,7 @@
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
- "knip": "5.47.0",
+ "knip": "5.50.5",
"magic-string": "0.30.17",
"nano-spawn": "0.2.0",
"node-style-text": "0.0.7",
diff --git a/yarn.lock b/yarn.lock
index 47dd283d3e71..5b0857fbbebe 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1907,16 +1907,6 @@ __metadata:
-"@nodelib/fs.scandir@npm:4.0.1":
- resolution: "@nodelib/fs.scandir@npm:4.0.1"
- "@nodelib/fs.stat": "npm:4.0.0"
- run-parallel: "npm:^1.2.0"
- checksum: 10/44b2b2b34e48ca88ee004413f5033db31cd6d5ecf8c7bbef0e33b6672d603f3e23b57d5fbb1bd5f83f8992df58381be6600006d92a903f085e698a37bdfe3c89
"@nodelib/fs.stat@npm:2.0.5, @nodelib/fs.stat@npm:^2.0.2":
version: 2.0.5
resolution: "@nodelib/fs.stat@npm:2.0.5"
@@ -1924,23 +1914,6 @@ __metadata:
-"@nodelib/fs.stat@npm:4.0.0":
- resolution: "@nodelib/fs.stat@npm:4.0.0"
- checksum: 10/1f87199fdab938d2ed6f5e10debc006f7965081e2cd147ed3d2333049a030cad1949bd76556a5f5364f062c3e1edcc3d0981189b065336fc92c503ead463f4e1
-"@nodelib/fs.walk@npm:3.0.1":
- version: 3.0.1
- resolution: "@nodelib/fs.walk@npm:3.0.1"
- "@nodelib/fs.scandir": "npm:4.0.1"
- fastq: "npm:^1.15.0"
"@nodelib/fs.walk@npm:^1.2.3":
version: 1.2.8
resolution: "@nodelib/fs.walk@npm:1.2.8"
@@ -2069,19 +2042,6 @@ __metadata:
-"@snyk/github-codeowners@npm:1.1.0":
- version: 1.1.0
- resolution: "@snyk/github-codeowners@npm:1.1.0"
- commander: "npm:^4.1.1"
- ignore: "npm:^5.1.8"
- p-map: "npm:^4.0.0"
- bin:
- github-codeowners: dist/cli.js
- checksum: 10/34120ef622616fef1ed8af12869d8c1803842aafa3fbacca263805ee7c85f58d11bdc301ef698c9b41268b275b9fd090f5d9f6d89c556abe9d52196e72d1c510
"@stylistic/eslint-plugin-js@npm:4.2.0":
version: 4.2.0
resolution: "@stylistic/eslint-plugin-js@npm:4.2.0"
@@ -2380,16 +2340,6 @@ __metadata:
-"aggregate-error@npm:^3.0.0":
- version: 3.1.0
- resolution: "aggregate-error@npm:3.1.0"
- clean-stack: "npm:^2.0.0"
- indent-string: "npm:^4.0.0"
- checksum: 10/1101a33f21baa27a2fa8e04b698271e64616b886795fd43c31068c07533c7b3facfcaf4e9e0cab3624bd88f729a592f1c901a1a229c9e490eafce411a8644b79
"ajv@npm:^6.12.4":
version: 6.12.6
resolution: "ajv@npm:6.12.6"
@@ -3000,13 +2950,6 @@ __metadata:
-"clean-stack@npm:^2.0.0":
- version: 2.2.0
- resolution: "clean-stack@npm:2.2.0"
- checksum: 10/2ac8cd2b2f5ec986a3c743935ec85b07bc174d5421a5efc8017e1f146a1cf5f781ae962618f416352103b32c9cd7e203276e8c28241bbe946160cab16149fb68
"clear-module@npm:^4.1.2":
version: 4.1.2
resolution: "clear-module@npm:4.1.2"
@@ -3102,13 +3045,6 @@ __metadata:
-"commander@npm:^4.1.1":
- version: 4.1.1
- resolution: "commander@npm:4.1.1"
- checksum: 10/3b2dc4125f387dab73b3294dbcb0ab2a862f9c0ad748ee2b27e3544d25325b7a8cdfbcc228d103a98a716960b14478114a5206b5415bd48cdafa38797891562c
"comment-json@npm:^4.2.5":
version: 4.2.5
resolution: "comment-json@npm:4.2.5"
@@ -4353,7 +4289,7 @@ __metadata:
-"fastq@npm:^1.15.0, fastq@npm:^1.6.0":
+"fastq@npm:^1.6.0":
version: 1.19.1
resolution: "fastq@npm:1.19.1"
@@ -4919,7 +4855,7 @@ __metadata:
-"ignore@npm:^5.1.8, ignore@npm:^5.2.0, ignore@npm:^5.3.1, ignore@npm:^5.3.2":
+"ignore@npm:^5.2.0, ignore@npm:^5.3.1, ignore@npm:^5.3.2":
version: 5.3.2
resolution: "ignore@npm:5.3.2"
checksum: 10/cceb6a457000f8f6a50e1196429750d782afce5680dd878aa4221bd79972d68b3a55b4b1458fc682be978f4d3c6a249046aa0880637367216444ab7b014cfc98
@@ -4962,13 +4898,6 @@ __metadata:
-"indent-string@npm:^4.0.0":
- resolution: "indent-string@npm:4.0.0"
- checksum: 10/cd3f5cbc9ca2d624c6a1f53f12e6b341659aba0e2d3254ae2b4464aaea8b4294cdb09616abbc59458f980531f2429784ed6a420d48d245bcad0811980c9efae9
"indent-string@npm:^5.0.0":
version: 5.0.0
resolution: "indent-string@npm:5.0.0"
@@ -6114,12 +6043,11 @@ __metadata:
-"knip@npm:5.47.0":
- version: 5.47.0
- resolution: "knip@npm:5.47.0"
+"knip@npm:5.50.5":
+ version: 5.50.5
- "@nodelib/fs.walk": "npm:3.0.1"
+ "@nodelib/fs.walk": "npm:^1.2.3"
easy-table: "npm:1.2.0"
enhanced-resolve: "npm:^5.18.1"
fast-glob: "npm:^3.3.3"
@@ -6131,7 +6059,6 @@ __metadata:
pretty-ms: "npm:^9.0.0"
smol-toml: "npm:^1.3.1"
strip-json-comments: "npm:5.0.1"
zod: "npm:^3.22.4"
zod-validation-error: "npm:^3.0.3"
peerDependencies:
@@ -6140,7 +6067,7 @@ __metadata:
bin:
knip: bin/knip.js
knip-bun: bin/knip-bun.js
- checksum: 10/3ce2f98c39cb81a7ac1a3ae78471b219bbebaa4f470153265fbc8fdd5b40f63e314113934cc72adfb5d7ae2e1549d1bb415e49569d0d8a0abe61f32ab078f848
+ checksum: 10/d98db9d0b81a0e6113fe412e3063e9a9e49f9ab15f9a9a729301c73df27c9ffd458d7ed5df291075bcda0c0baaad6e0395af827c57a0947f86ceff901682b6e9
@@ -6752,15 +6679,6 @@ __metadata:
-"p-map@npm:^4.0.0":
- resolution: "p-map@npm:4.0.0"
- aggregate-error: "npm:^3.0.0"
- checksum: 10/7ba4a2b1e24c05e1fc14bbaea0fc6d85cf005ae7e9c9425d4575550f37e2e584b1af97bcde78eacd7559208f20995988d52881334db16cf77bc1bcf68e48ed7c
"p-map@npm:^7.0.2":
version: 7.0.3
resolution: "p-map@npm:7.0.3"
@@ -7153,7 +7071,7 @@ __metadata:
jest-watch-typeahead: "npm:2.2.2"
js-yaml: "npm:4.1.0"
json5: "npm:2.2.3"
- knip: "npm:5.47.0"
+ knip: "npm:5.50.5"
leven: "npm:4.0.0"
linguist-languages: "npm:7.29.0"
magic-string: "npm:0.30.17"
@@ -7567,7 +7485,7 @@ __metadata:
-"run-parallel@npm:^1.1.9, run-parallel@npm:^1.2.0":
+"run-parallel@npm:^1.1.9":
version: 1.2.0
resolution: "run-parallel@npm:1.2.0"
@@ -8045,13 +7963,6 @@ __metadata:
-"summary@npm:2.1.0":
- version: 2.1.0
- resolution: "summary@npm:2.1.0"
- checksum: 10/10ac12ce12c013b56ad44c37cfac206961f0993d98867b33b1b03a27b38a1cf8dd2db0b788883356c5335bbbb37d953772ef4a381d6fc8f408faf99f2bc54af5
"supports-color@npm:^5.3.0":
version: 5.5.0
resolution: "supports-color@npm:5.5.0" | [
"- version: 4.0.1",
"- checksum: 10/7b76a0139dec52e3f2a3a0bb4f13dbf72a6b79d8076ec4b5deea9e75bd1b79d7abda53776f93b5aefda9a5e40f0e31f49f6e35bf5460a402f0aee7bcf3b26d85",
"+ resolution: \"knip@npm:5.50.5\"",
"- \"@snyk/github-codeowners\": \"npm:1.1.0\"",
"- summary: \"npm:2.1.0\""
] | [
22,
51,
164,
167,
176
] | {
"additions": 10,
"author": "renovate[bot]",
"deletions": 99,
"html_url": "https://github.com/prettier/prettier/pull/17404",
"issue_id": 17404,
"merged_at": "2025-04-25T02:40:03Z",
"omission_probability": 0.1,
"pr_number": 17404,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency knip to v5.50.5",
"total_changes": 109
} |
151 | diff --git a/package.json b/package.json
index b5e435d6dd68..dfaa3f3a3095 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"bin"
],
"dependencies": {
- "@angular/compiler": "19.2.7",
+ "@angular/compiler": "19.2.8",
"@babel/code-frame": "7.26.2",
"@babel/parser": "7.27.0",
"@babel/types": "7.27.0",
diff --git a/yarn.lock b/yarn.lock
index 47dd283d3e71..6256658eb8ba 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -15,12 +15,12 @@ __metadata:
languageName: node
linkType: hard
-"@angular/compiler@npm:19.2.7":
- version: 19.2.7
- resolution: "@angular/compiler@npm:19.2.7"
+"@angular/compiler@npm:19.2.8":
+ version: 19.2.8
+ resolution: "@angular/compiler@npm:19.2.8"
dependencies:
tslib: "npm:^2.3.0"
- checksum: 10/b6545922029a74387a6680f84147a9d16c222ad16e601ccde5696231332a278357ba43d593157b71859f9f1631c3178423f552fcf70ef8dcb3d66cbf1bffea71
+ checksum: 10/829585e245591d84ac2369c1e3089216b2c393e41b7eb5efc527b30404b7b70bdb62b10f36e3cbdbfdc714692a1973eaa51588fddf60b34198322b2f7035b153
languageName: node
linkType: hard
@@ -7077,7 +7077,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "prettier@workspace:."
dependencies:
- "@angular/compiler": "npm:19.2.7"
+ "@angular/compiler": "npm:19.2.8"
"@babel/code-frame": "npm:7.26.2"
"@babel/generator": "npm:7.27.0"
"@babel/parser": "npm:7.27.0"
| diff --git a/package.json b/package.json
index b5e435d6dd68..dfaa3f3a3095 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"bin"
],
"dependencies": {
- "@angular/compiler": "19.2.7",
+ "@angular/compiler": "19.2.8",
"@babel/code-frame": "7.26.2",
"@babel/parser": "7.27.0",
"@babel/types": "7.27.0",
diff --git a/yarn.lock b/yarn.lock
index 47dd283d3e71..6256658eb8ba 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -15,12 +15,12 @@ __metadata:
-"@angular/compiler@npm:19.2.7":
- version: 19.2.7
- resolution: "@angular/compiler@npm:19.2.7"
+"@angular/compiler@npm:19.2.8":
+ version: 19.2.8
+ resolution: "@angular/compiler@npm:19.2.8"
tslib: "npm:^2.3.0"
- checksum: 10/b6545922029a74387a6680f84147a9d16c222ad16e601ccde5696231332a278357ba43d593157b71859f9f1631c3178423f552fcf70ef8dcb3d66cbf1bffea71
+ checksum: 10/829585e245591d84ac2369c1e3089216b2c393e41b7eb5efc527b30404b7b70bdb62b10f36e3cbdbfdc714692a1973eaa51588fddf60b34198322b2f7035b153
@@ -7077,7 +7077,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "prettier@workspace:."
- "@angular/compiler": "npm:19.2.7"
+ "@angular/compiler": "npm:19.2.8"
"@babel/code-frame": "npm:7.26.2"
"@babel/generator": "npm:7.27.0"
"@babel/parser": "npm:7.27.0" | [] | [] | {
"additions": 6,
"author": "renovate[bot]",
"deletions": 6,
"html_url": "https://github.com/prettier/prettier/pull/17403",
"issue_id": 17403,
"merged_at": "2025-04-25T02:36:56Z",
"omission_probability": 0.1,
"pr_number": 17403,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency @angular/compiler to v19.2.8",
"total_changes": 12
} |
152 | diff --git a/package.json b/package.json
index b5e435d6dd68..ff1e648c1c83 100644
--- a/package.json
+++ b/package.json
@@ -94,7 +94,7 @@
"remark-math": "3.0.1",
"remark-parse": "8.0.3",
"sdbm": "2.0.0",
- "smol-toml": "1.3.3",
+ "smol-toml": "1.3.4",
"strip-ansi": "7.1.0",
"to-fast-properties": "4.0.0",
"trim-newlines": "5.0.0",
diff --git a/yarn.lock b/yarn.lock
index 47dd283d3e71..3657d788fa80 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -7184,7 +7184,7 @@ __metadata:
sdbm: "npm:2.0.0"
semver: "npm:7.7.1"
serialize-javascript: "npm:6.0.2"
- smol-toml: "npm:1.3.3"
+ smol-toml: "npm:1.3.4"
snapshot-diff: "npm:0.10.0"
strip-ansi: "npm:7.1.0"
tempy: "npm:3.1.0"
@@ -7723,10 +7723,10 @@ __metadata:
languageName: node
linkType: hard
-"smol-toml@npm:1.3.3, smol-toml@npm:^1.3.1":
- version: 1.3.3
- resolution: "smol-toml@npm:1.3.3"
- checksum: 10/22dabed8f48860b285718aa33a10729da4aa5ceaa58b4d215d9879ddccad07b0690bd3183dbf88572a2cb805aac5b10b3a7d6e29632f33e83aa6170a95d56882
+"smol-toml@npm:1.3.4, smol-toml@npm:^1.3.1":
+ version: 1.3.4
+ resolution: "smol-toml@npm:1.3.4"
+ checksum: 10/795db36448db6b353ea1171fad8b72ae2fea3b5f9aa48d2f4c79699e10bdca74d59202f6715ff738fae817bf1f80e0c38c4d3ddf8b812cac26cc6255eaa0caa2
languageName: node
linkType: hard
| diff --git a/package.json b/package.json
index b5e435d6dd68..ff1e648c1c83 100644
--- a/package.json
+++ b/package.json
@@ -94,7 +94,7 @@
"remark-math": "3.0.1",
"remark-parse": "8.0.3",
"sdbm": "2.0.0",
- "smol-toml": "1.3.3",
+ "smol-toml": "1.3.4",
"strip-ansi": "7.1.0",
"to-fast-properties": "4.0.0",
"trim-newlines": "5.0.0",
diff --git a/yarn.lock b/yarn.lock
index 47dd283d3e71..3657d788fa80 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -7184,7 +7184,7 @@ __metadata:
sdbm: "npm:2.0.0"
semver: "npm:7.7.1"
serialize-javascript: "npm:6.0.2"
- smol-toml: "npm:1.3.3"
+ smol-toml: "npm:1.3.4"
snapshot-diff: "npm:0.10.0"
strip-ansi: "npm:7.1.0"
tempy: "npm:3.1.0"
@@ -7723,10 +7723,10 @@ __metadata:
-"smol-toml@npm:1.3.3, smol-toml@npm:^1.3.1":
- version: 1.3.3
- resolution: "smol-toml@npm:1.3.3"
- checksum: 10/22dabed8f48860b285718aa33a10729da4aa5ceaa58b4d215d9879ddccad07b0690bd3183dbf88572a2cb805aac5b10b3a7d6e29632f33e83aa6170a95d56882
+"smol-toml@npm:1.3.4, smol-toml@npm:^1.3.1":
+ version: 1.3.4
+ resolution: "smol-toml@npm:1.3.4"
+ checksum: 10/795db36448db6b353ea1171fad8b72ae2fea3b5f9aa48d2f4c79699e10bdca74d59202f6715ff738fae817bf1f80e0c38c4d3ddf8b812cac26cc6255eaa0caa2 | [] | [] | {
"additions": 6,
"author": "renovate[bot]",
"deletions": 6,
"html_url": "https://github.com/prettier/prettier/pull/17402",
"issue_id": 17402,
"merged_at": "2025-04-25T02:36:37Z",
"omission_probability": 0.1,
"pr_number": 17402,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency smol-toml to v1.3.4",
"total_changes": 12
} |
153 | diff --git a/changelog_unreleased/javascript/17398.md b/changelog_unreleased/javascript/17398.md
new file mode 100644
index 000000000000..a45a7831f55f
--- /dev/null
+++ b/changelog_unreleased/javascript/17398.md
@@ -0,0 +1,19 @@
+#### Preserve spaces between CSS words and embedded expression (#17398 by @sosukesuzuki)
+
+<!-- prettier-ignore -->
+```jsx
+// Input
+const Heading = styled.h1`
+ font-size: var(--font-size-h${level});
+`;
+
+// Prettier stable
+const Heading = styled.h1`
+ font-size: var(--font-size-h ${level});
+`;
+
+// Prettier main
+const Heading = styled.h1`
+ font-size: var(--font-size-h${level});
+`;
+```
diff --git a/src/language-css/loc.js b/src/language-css/loc.js
index c01e5f896d52..6b4ea4dc478a 100644
--- a/src/language-css/loc.js
+++ b/src/language-css/loc.js
@@ -2,6 +2,14 @@ import isNonEmptyArray from "../utils/is-non-empty-array.js";
import lineColumnToIndex from "../utils/line-column-to-index.js";
import { skipEverythingButNewLine } from "../utils/skip.js";
+function fixValueWordLoc(node, originalIndex) {
+ const { value } = node;
+ if (value === "-" || value === "--" || value.charAt(0) !== "-") {
+ return originalIndex;
+ }
+ return originalIndex - (value.charAt(1) === "-" ? 2 : 1);
+}
+
function calculateLocStart(node, text) {
// `postcss>=8`
if (typeof node.source?.start?.offset === "number") {
@@ -10,6 +18,9 @@ function calculateLocStart(node, text) {
// value-* nodes have this
if (typeof node.sourceIndex === "number") {
+ if (node.type === "value-word") {
+ return fixValueWordLoc(node, node.sourceIndex);
+ }
return node.sourceIndex;
}
@@ -33,7 +44,11 @@ function calculateLocEnd(node, text) {
if (node.source) {
if (node.source.end) {
- return lineColumnToIndex(node.source.end, text);
+ const index = lineColumnToIndex(node.source.end, text);
+ if (node.type === "value-word") {
+ return fixValueWordLoc(node, index);
+ }
+ return index;
}
if (isNonEmptyArray(node.nodes)) {
diff --git a/src/language-css/print/comma-separated-value-group.js b/src/language-css/print/comma-separated-value-group.js
index ab4cdce7f791..37f11225553c 100644
--- a/src/language-css/print/comma-separated-value-group.js
+++ b/src/language-css/print/comma-separated-value-group.js
@@ -147,11 +147,15 @@ function printCommaSeparatedValueGroup(path, options, print) {
continue;
}
- // styled.div` background: var(--${one}); `
+ // We should keep spaces between words in a embedded JS expression
+ // examples:
+ // styled.div` font-size: var(--font-size-h${({ level }) => level}); `;
+ // styled.div` grid-area: area-${({ area }) => area}; `;
+ // styled.div` border: 1px ${solid} red; `;
if (
iNode.type === "value-word" &&
- iNode.value.endsWith("-") &&
- isAtWordPlaceholderNode(iNextNode)
+ isAtWordPlaceholderNode(iNextNode) &&
+ locEnd(iNode) === locStart(iNextNode)
) {
continue;
}
diff --git a/tests/format/js/multiparser-css/__snapshots__/format.test.js.snap b/tests/format/js/multiparser-css/__snapshots__/format.test.js.snap
index b64f76fdcc38..2fdb0057b6bb 100644
--- a/tests/format/js/multiparser-css/__snapshots__/format.test.js.snap
+++ b/tests/format/js/multiparser-css/__snapshots__/format.test.js.snap
@@ -480,6 +480,56 @@ const paragraph3 = css\`
================================================================================
`;
+exports[`issue-16692.js format 1`] = `
+====================================options=====================================
+parsers: ["babel", "typescript", "flow"]
+printWidth: 80
+ | printWidth
+=====================================input======================================
+const c1 = styled.div\`
+ border: 1px \${solid} red;
+\`;
+
+const c2 = styled.div\`
+ font-size: var(--font-size-h\${level});
+\`;
+
+const c3 = styled.div\`
+ grid-area: area-\${area};
+\`;
+
+const c4 = styled.div\`
+ grid-area: var(--\${one});
+\`;
+
+const c5 = styled.div\`
+ font-size: var(--font-size-h \${level});
+\`;
+
+=====================================output=====================================
+const c1 = styled.div\`
+ border: 1px \${solid} red;
+\`;
+
+const c2 = styled.div\`
+ font-size: var(--font-size-h\${level});
+\`;
+
+const c3 = styled.div\`
+ grid-area: area-\${area};
+\`;
+
+const c4 = styled.div\`
+ grid-area: var(--\${one});
+\`;
+
+const c5 = styled.div\`
+ font-size: var(--font-size-h \${level});
+\`;
+
+================================================================================
+`;
+
exports[`styled-components.js format 1`] = `
====================================options=====================================
parsers: ["babel", "typescript", "flow"]
diff --git a/tests/format/js/multiparser-css/issue-16692.js b/tests/format/js/multiparser-css/issue-16692.js
new file mode 100644
index 000000000000..40febe8e1ce5
--- /dev/null
+++ b/tests/format/js/multiparser-css/issue-16692.js
@@ -0,0 +1,19 @@
+const c1 = styled.div`
+ border: 1px ${solid} red;
+`;
+
+const c2 = styled.div`
+ font-size: var(--font-size-h${level});
+`;
+
+const c3 = styled.div`
+ grid-area: area-${area};
+`;
+
+const c4 = styled.div`
+ grid-area: var(--${one});
+`;
+
+const c5 = styled.div`
+ font-size: var(--font-size-h ${level});
+`;
| diff --git a/changelog_unreleased/javascript/17398.md b/changelog_unreleased/javascript/17398.md
index 000000000000..a45a7831f55f
+++ b/changelog_unreleased/javascript/17398.md
+#### Preserve spaces between CSS words and embedded expression (#17398 by @sosukesuzuki)
+<!-- prettier-ignore -->
+```jsx
+// Input
+ font-size: var(--font-size-h ${level});
+// Prettier main
+```
diff --git a/src/language-css/loc.js b/src/language-css/loc.js
index c01e5f896d52..6b4ea4dc478a 100644
--- a/src/language-css/loc.js
+++ b/src/language-css/loc.js
@@ -2,6 +2,14 @@ import isNonEmptyArray from "../utils/is-non-empty-array.js";
import lineColumnToIndex from "../utils/line-column-to-index.js";
import { skipEverythingButNewLine } from "../utils/skip.js";
+function fixValueWordLoc(node, originalIndex) {
+ const { value } = node;
+ if (value === "-" || value === "--" || value.charAt(0) !== "-") {
+ return originalIndex;
+}
function calculateLocStart(node, text) {
// `postcss>=8`
if (typeof node.source?.start?.offset === "number") {
@@ -10,6 +18,9 @@ function calculateLocStart(node, text) {
// value-* nodes have this
if (typeof node.sourceIndex === "number") {
+ if (node.type === "value-word") {
+ return fixValueWordLoc(node, node.sourceIndex);
+ }
return node.sourceIndex;
}
@@ -33,7 +44,11 @@ function calculateLocEnd(node, text) {
if (node.source) {
if (node.source.end) {
- return lineColumnToIndex(node.source.end, text);
+ const index = lineColumnToIndex(node.source.end, text);
+ if (node.type === "value-word") {
+ }
+ return index;
if (isNonEmptyArray(node.nodes)) {
diff --git a/src/language-css/print/comma-separated-value-group.js b/src/language-css/print/comma-separated-value-group.js
index ab4cdce7f791..37f11225553c 100644
--- a/src/language-css/print/comma-separated-value-group.js
+++ b/src/language-css/print/comma-separated-value-group.js
@@ -147,11 +147,15 @@ function printCommaSeparatedValueGroup(path, options, print) {
+ // We should keep spaces between words in a embedded JS expression
+ // styled.div` font-size: var(--font-size-h${({ level }) => level}); `;
+ // styled.div` grid-area: area-${({ area }) => area}; `;
+ // styled.div` border: 1px ${solid} red; `;
if (
iNode.type === "value-word" &&
- iNode.value.endsWith("-") &&
- isAtWordPlaceholderNode(iNextNode)
+ isAtWordPlaceholderNode(iNextNode) &&
+ locEnd(iNode) === locStart(iNextNode)
) {
diff --git a/tests/format/js/multiparser-css/__snapshots__/format.test.js.snap b/tests/format/js/multiparser-css/__snapshots__/format.test.js.snap
index b64f76fdcc38..2fdb0057b6bb 100644
--- a/tests/format/js/multiparser-css/__snapshots__/format.test.js.snap
+++ b/tests/format/js/multiparser-css/__snapshots__/format.test.js.snap
@@ -480,6 +480,56 @@ const paragraph3 = css\`
================================================================================
`;
+exports[`issue-16692.js format 1`] = `
+====================================options=====================================
+parsers: ["babel", "typescript", "flow"]
+printWidth: 80
+ | printWidth
+=====================================input======================================
+ border: 1px \${solid} red;
+ font-size: var(--font-size-h\${level});
+ grid-area: area-\${area};
+ grid-area: var(--\${one});
+ font-size: var(--font-size-h \${level});
+=====================================output=====================================
+ font-size: var(--font-size-h\${level});
+ grid-area: area-\${area};
+ grid-area: var(--\${one});
+================================================================================
exports[`styled-components.js format 1`] = `
====================================options=====================================
parsers: ["babel", "typescript", "flow"]
diff --git a/tests/format/js/multiparser-css/issue-16692.js b/tests/format/js/multiparser-css/issue-16692.js
index 000000000000..40febe8e1ce5
+++ b/tests/format/js/multiparser-css/issue-16692.js
+const c1 = styled.div`
+ border: 1px ${solid} red;
+const c2 = styled.div`
+ font-size: var(--font-size-h${level});
+const c3 = styled.div`
+const c4 = styled.div`
+ grid-area: var(--${one});
+const c5 = styled.div`
+ font-size: var(--font-size-h ${level}); | [
"+// Prettier stable",
"+ }",
"+ return originalIndex - (value.charAt(1) === \"-\" ? 2 : 1);",
"+ return fixValueWordLoc(node, index);",
"- // styled.div` background: var(--${one}); `",
"+ // examples:",
"+ border: 1px \\${solid} red;",
"+ font-size: var(--font-size-h \\${level});",
"+ grid-area: area-${area};"
] | [
15,
37,
38,
61,
75,
77,
126,
142,
166
] | {
"additions": 111,
"author": "sosukesuzuki",
"deletions": 4,
"html_url": "https://github.com/prettier/prettier/pull/17398",
"issue_id": 17398,
"merged_at": "2025-04-25T02:11:50Z",
"omission_probability": 0.1,
"pr_number": 17398,
"repo": "prettier/prettier",
"title": "Preserve spaces between CSS words and embedded expression",
"total_changes": 115
} |
154 | diff --git a/cspell.json b/cspell.json
index d9c898528322..246432cdd2e3 100644
--- a/cspell.json
+++ b/cspell.json
@@ -159,6 +159,7 @@
"lintstaged",
"lintstagedrc",
"literalline",
+ "llms",
"loglevel",
"lydell",
"Marek",
diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js
index 30d627db51de..7fb3f039f419 100644
--- a/website/docusaurus.config.js
+++ b/website/docusaurus.config.js
@@ -4,6 +4,7 @@ import fs from "node:fs";
import { createRequire } from "node:module";
import { load as parseYaml } from "js-yaml";
import { themes as prismThemes } from "prism-react-renderer";
+import llmsTxtPlugin from "./plugins/llms-txt-plugin.mjs";
const require = createRequire(import.meta.url);
@@ -258,7 +259,7 @@ const config = {
darkTheme: prismThemes.dracula,
},
},
-
+ plugins: [llmsTxtPlugin],
future: {
experimental_faster: {
swcJsLoader: true,
diff --git a/website/plugins/llms-txt-plugin.mjs b/website/plugins/llms-txt-plugin.mjs
new file mode 100644
index 000000000000..dd60b5c9cd63
--- /dev/null
+++ b/website/plugins/llms-txt-plugin.mjs
@@ -0,0 +1,100 @@
+// https://github.com/facebook/docusaurus/issues/10899
+// https://github.com/defi-wonderland/handbook/blob/dev/plugins/llmsTxtPlugin.ts
+import fs from "node:fs/promises";
+import path from "node:path";
+
+export default function llmsTxtPlugin(context) {
+ return {
+ name: "llms-txt-plugin",
+ async loadContent() {
+ const { siteDir } = context;
+ const contentDir = path.join(siteDir, "versioned_docs/version-stable");
+ const allMdx = [];
+ const docsRecords = [];
+
+ const getMdxFiles = async (dir, relativePath = "", depth = 0) => {
+ const entries = await fs.readdir(dir, {
+ withFileTypes: true,
+ });
+
+ entries.sort((a, b) => {
+ if (a.isDirectory() && !b.isDirectory()) {
+ return -1;
+ }
+ if (!a.isDirectory() && b.isDirectory()) {
+ return 1;
+ }
+ return a.name.localeCompare(b.name);
+ });
+
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+ const currentRelativePath = path.join(relativePath, entry.name);
+
+ if (entry.isDirectory()) {
+ const dirName = entry.name
+ .split("-")
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(" ");
+ const headingLevel = "#".repeat(depth + 2);
+ allMdx.push(`\n${headingLevel} ${dirName}\n`);
+ await getMdxFiles(fullPath, currentRelativePath, depth + 1);
+ } else if (entry.name.endsWith(".md")) {
+ const content = await fs.readFile(fullPath, "utf8");
+ let title = entry.name.replace(".md", "");
+ let description = "";
+
+ const frontmatterMatch = content.match(/^---\n(.*?)\n---/su);
+ if (frontmatterMatch) {
+ const titleMatch = frontmatterMatch[1].match(/title:\s*(.+)/u);
+ const descriptionMatch =
+ frontmatterMatch[1].match(/description:\s*(.+)/u);
+
+ if (titleMatch) {
+ title = titleMatch[1].trim();
+ }
+ if (descriptionMatch) {
+ description = descriptionMatch[1].trim();
+ }
+ }
+
+ const headingLevel = "#".repeat(depth + 3);
+ allMdx.push(`\n${headingLevel} ${title}\n\n${content}`);
+
+ // Add to docs records for llms.txt
+ docsRecords.push({
+ title,
+ path: currentRelativePath.replaceAll("\\", "/"),
+ description,
+ });
+ }
+ }
+ };
+
+ await getMdxFiles(contentDir);
+ return { allMdx, docsRecords };
+ },
+ async postBuild({ content, outDir }) {
+ const { allMdx, docsRecords } = content;
+
+ // Write concatenated MDX content
+ const concatenatedPath = path.join(outDir, "llms-full.txt");
+ await fs.writeFile(concatenatedPath, allMdx.join("\n\n---\n\n"));
+
+ // Create llms.txt with the requested format
+ const llmsTxt = `# ${
+ context.siteConfig.title
+ }\n\n## Documentation\n\n${docsRecords
+ .map(
+ (doc) =>
+ `- [${doc.title}](${context.siteConfig.url}/docs/${doc.path.replace(
+ ".md",
+ "",
+ )}): ${doc.description}`,
+ )
+ .join("\n")}`;
+ const llmsTxtPath = path.join(outDir, "llms.txt");
+ await fs.writeFile(llmsTxtPath, llmsTxt);
+ },
+ };
+}
| diff --git a/cspell.json b/cspell.json
index d9c898528322..246432cdd2e3 100644
--- a/cspell.json
+++ b/cspell.json
@@ -159,6 +159,7 @@
"lintstaged",
"lintstagedrc",
"literalline",
+ "llms",
"loglevel",
"lydell",
"Marek",
diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js
index 30d627db51de..7fb3f039f419 100644
--- a/website/docusaurus.config.js
+++ b/website/docusaurus.config.js
@@ -4,6 +4,7 @@ import fs from "node:fs";
import { createRequire } from "node:module";
import { load as parseYaml } from "js-yaml";
import { themes as prismThemes } from "prism-react-renderer";
+import llmsTxtPlugin from "./plugins/llms-txt-plugin.mjs";
const require = createRequire(import.meta.url);
@@ -258,7 +259,7 @@ const config = {
darkTheme: prismThemes.dracula,
},
},
+ plugins: [llmsTxtPlugin],
future: {
experimental_faster: {
swcJsLoader: true,
diff --git a/website/plugins/llms-txt-plugin.mjs b/website/plugins/llms-txt-plugin.mjs
new file mode 100644
index 000000000000..dd60b5c9cd63
--- /dev/null
+++ b/website/plugins/llms-txt-plugin.mjs
@@ -0,0 +1,100 @@
+// https://github.com/facebook/docusaurus/issues/10899
+// https://github.com/defi-wonderland/handbook/blob/dev/plugins/llmsTxtPlugin.ts
+import fs from "node:fs/promises";
+import path from "node:path";
+export default function llmsTxtPlugin(context) {
+ return {
+ name: "llms-txt-plugin",
+ async loadContent() {
+ const { siteDir } = context;
+ const contentDir = path.join(siteDir, "versioned_docs/version-stable");
+ const allMdx = [];
+ const docsRecords = [];
+ const getMdxFiles = async (dir, relativePath = "", depth = 0) => {
+ const entries = await fs.readdir(dir, {
+ withFileTypes: true,
+ entries.sort((a, b) => {
+ if (a.isDirectory() && !b.isDirectory()) {
+ if (!a.isDirectory() && b.isDirectory()) {
+ return 1;
+ return a.name.localeCompare(b.name);
+ const fullPath = path.join(dir, entry.name);
+ const currentRelativePath = path.join(relativePath, entry.name);
+ if (entry.isDirectory()) {
+ const dirName = entry.name
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(" ");
+ const headingLevel = "#".repeat(depth + 2);
+ allMdx.push(`\n${headingLevel} ${dirName}\n`);
+ await getMdxFiles(fullPath, currentRelativePath, depth + 1);
+ } else if (entry.name.endsWith(".md")) {
+ const content = await fs.readFile(fullPath, "utf8");
+ let title = entry.name.replace(".md", "");
+ let description = "";
+ const frontmatterMatch = content.match(/^---\n(.*?)\n---/su);
+ if (frontmatterMatch) {
+ const titleMatch = frontmatterMatch[1].match(/title:\s*(.+)/u);
+ const descriptionMatch =
+ frontmatterMatch[1].match(/description:\s*(.+)/u);
+ if (titleMatch) {
+ title = titleMatch[1].trim();
+ if (descriptionMatch) {
+ }
+ const headingLevel = "#".repeat(depth + 3);
+ allMdx.push(`\n${headingLevel} ${title}\n\n${content}`);
+ // Add to docs records for llms.txt
+ docsRecords.push({
+ title,
+ path: currentRelativePath.replaceAll("\\", "/"),
+ description,
+ });
+ }
+ };
+ await getMdxFiles(contentDir);
+ return { allMdx, docsRecords };
+ const { allMdx, docsRecords } = content;
+ // Write concatenated MDX content
+ const concatenatedPath = path.join(outDir, "llms-full.txt");
+ await fs.writeFile(concatenatedPath, allMdx.join("\n\n---\n\n"));
+ // Create llms.txt with the requested format
+ const llmsTxt = `# ${
+ context.siteConfig.title
+ .map(
+ (doc) =>
+ ".md",
+ "",
+ )}): ${doc.description}`,
+ )
+ .join("\n")}`;
+ const llmsTxtPath = path.join(outDir, "llms.txt");
+ await fs.writeFile(llmsTxtPath, llmsTxt);
+ };
+} | [
"-",
"+ return -1;",
"+ for (const entry of entries) {",
"+ .split(\"-\")",
"+ description = descriptionMatch[1].trim();",
"+ async postBuild({ content, outDir }) {",
"+ }\\n\\n## Documentation\\n\\n${docsRecords",
"+ `- [${doc.title}](${context.siteConfig.url}/docs/${doc.path.replace("
] | [
28,
60,
68,
74,
95,
115,
125,
128
] | {
"additions": 103,
"author": "fisker",
"deletions": 1,
"html_url": "https://github.com/prettier/prettier/pull/17388",
"issue_id": 17388,
"merged_at": "2025-04-24T09:04:42Z",
"omission_probability": 0.1,
"pr_number": 17388,
"repo": "prettier/prettier",
"title": "Website: generate `llms-full.txt` and `llms.txt` files",
"total_changes": 104
} |
155 | diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js
index da50dff68b24..d10c8219fc8f 100644
--- a/src/language-html/print/tag.js
+++ b/src/language-html/print/tag.js
@@ -355,15 +355,17 @@ function printOpeningTagStartMarker(node, options) {
case "docType": {
// Only lowercase HTML5 doctype in `.html` and `.htm` files
if (node.value === "html") {
- const filepath = options.filepath ?? "";
- if (/\.html?$/u.test(filepath)) {
+ const { filepath } = options;
+ if (filepath && /\.html?$/u.test(filepath)) {
return HTML5_DOCTYPE_START_MARKER;
}
}
- const original = options.originalText.slice(locStart(node), locEnd(node));
-
- return original.slice(0, HTML5_DOCTYPE_START_MARKER.length);
+ const start = locStart(node);
+ return options.originalText.slice(
+ start,
+ start + HTML5_DOCTYPE_START_MARKER.length,
+ );
}
case "angularIcuExpression":
| diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js
index da50dff68b24..d10c8219fc8f 100644
--- a/src/language-html/print/tag.js
+++ b/src/language-html/print/tag.js
@@ -355,15 +355,17 @@ function printOpeningTagStartMarker(node, options) {
case "docType": {
// Only lowercase HTML5 doctype in `.html` and `.htm` files
if (node.value === "html") {
- const filepath = options.filepath ?? "";
+ const { filepath } = options;
+ if (filepath && /\.html?$/u.test(filepath)) {
return HTML5_DOCTYPE_START_MARKER;
}
}
- const original = options.originalText.slice(locStart(node), locEnd(node));
-
- return original.slice(0, HTML5_DOCTYPE_START_MARKER.length);
+ const start = locStart(node);
+ return options.originalText.slice(
+ start,
+ start + HTML5_DOCTYPE_START_MARKER.length,
+ );
}
case "angularIcuExpression": | [
"- if (/\\.html?$/u.test(filepath)) {"
] | [
9
] | {
"additions": 7,
"author": "fisker",
"deletions": 5,
"html_url": "https://github.com/prettier/prettier/pull/17395",
"issue_id": 17395,
"merged_at": "2025-04-24T09:04:12Z",
"omission_probability": 0.1,
"pr_number": 17395,
"repo": "prettier/prettier",
"title": "Minor improvement to `doctype` print",
"total_changes": 12
} |
156 | diff --git a/eslint.config.js b/eslint.config.js
index e7711753bd37..63ccda881a21 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -74,6 +74,7 @@ export default [
"no-implicit-coercion": "error",
"no-inner-declarations": "error",
"no-lonely-if": "error",
+ "no-restricted-imports": ["error", "assert", "node:assert"],
"no-unneeded-ternary": "error",
"no-useless-return": "error",
"no-unused-expressions": [
diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js
index f83e7e413bfd..8c3979bb9edf 100644
--- a/scripts/build/build-javascript-module.js
+++ b/scripts/build/build-javascript-module.js
@@ -179,7 +179,7 @@ function getEsbuildOptions({ packageConfig, file, cliOptions }) {
// TODO[@fisker]: Find a better way
{
module: "*",
- find: ' from "node:assert";',
+ find: ' from "node:assert/strict";',
replacement: ` from ${JSON.stringify(
path.join(dirname, "./shims/assert.js"),
)};`,
diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js
index da50dff68b24..a06abe83d2e9 100644
--- a/src/language-html/print/tag.js
+++ b/src/language-html/print/tag.js
@@ -2,7 +2,7 @@
* @import {Doc} from "../../document/builders.js"
*/
-import assert from "node:assert";
+import assert from "node:assert/strict";
import {
hardline,
indent,
diff --git a/src/language-js/parse/postprocess/index.js b/src/language-js/parse/postprocess/index.js
index d00896f690cd..e67963a89531 100644
--- a/src/language-js/parse/postprocess/index.js
+++ b/src/language-js/parse/postprocess/index.js
@@ -1,4 +1,4 @@
-import assert from "node:assert";
+import assert from "node:assert/strict";
import isNonEmptyArray from "../../../utils/is-non-empty-array.js";
import { locEnd, locStart } from "../../loc.js";
import createTypeCheckFunction from "../../utils/create-type-check-function.js";
diff --git a/src/language-js/print/flow.js b/src/language-js/print/flow.js
index 0005631cd220..082778b5c793 100644
--- a/src/language-js/print/flow.js
+++ b/src/language-js/print/flow.js
@@ -1,6 +1,6 @@
/** @import {Doc} from "../../document/builders.js" */
-import assert from "node:assert";
+import assert from "node:assert/strict";
import { replaceEndOfLine } from "../../document/utils.js";
import printNumber from "../../utils/print-number.js";
import printString from "../../utils/print-string.js";
diff --git a/src/language-js/print/function.js b/src/language-js/print/function.js
index 0c71e4b1cd92..10bb06b780f1 100644
--- a/src/language-js/print/function.js
+++ b/src/language-js/print/function.js
@@ -1,4 +1,4 @@
-import assert from "node:assert";
+import assert from "node:assert/strict";
import {
group,
hardline,
diff --git a/src/language-js/utils/get-text-without-comments.js b/src/language-js/utils/get-text-without-comments.js
index 385ec4ee2aee..93114a4f8732 100644
--- a/src/language-js/utils/get-text-without-comments.js
+++ b/src/language-js/utils/get-text-without-comments.js
@@ -1,4 +1,4 @@
-import assert from "node:assert";
+import assert from "node:assert/strict";
import { locEnd, locStart } from "../loc.js";
function getTextWithoutComments(options, start, end) {
diff --git a/src/language-markdown/utils.js b/src/language-markdown/utils.js
index bb0baf37095a..542e4ab5e4e8 100644
--- a/src/language-markdown/utils.js
+++ b/src/language-markdown/utils.js
@@ -1,4 +1,4 @@
-import assert from "node:assert";
+import assert from "node:assert/strict";
import { CJK_REGEXP, PUNCTUATION_REGEXP } from "./constants.evaluate.js";
import { locEnd, locStart } from "./loc.js";
diff --git a/src/main/comments/attach.js b/src/main/comments/attach.js
index 956d8267b280..3a4d0bd4bc33 100644
--- a/src/main/comments/attach.js
+++ b/src/main/comments/attach.js
@@ -1,4 +1,4 @@
-import assert from "node:assert";
+import assert from "node:assert/strict";
import { getChildren } from "../../utils/ast-utils.js";
import hasNewline from "../../utils/has-newline.js";
import isNonEmptyArray from "../../utils/is-non-empty-array.js";
diff --git a/src/main/range-util.js b/src/main/range-util.js
index cdf28aa9250c..19e9efd00b0a 100644
--- a/src/main/range-util.js
+++ b/src/main/range-util.js
@@ -1,4 +1,4 @@
-import assert from "node:assert";
+import assert from "node:assert/strict";
import { getSortedChildNodes } from "./comments/attach.js";
const isJsonParser = ({ parser }) =>
diff --git a/src/utils/print-string.js b/src/utils/print-string.js
index 945e10264986..77cd7e77c476 100644
--- a/src/utils/print-string.js
+++ b/src/utils/print-string.js
@@ -1,4 +1,4 @@
-import assert from "node:assert";
+import assert from "node:assert/strict";
import getPreferredQuote from "./get-preferred-quote.js";
import makeString from "./make-string.js";
| diff --git a/eslint.config.js b/eslint.config.js
index e7711753bd37..63ccda881a21 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -74,6 +74,7 @@ export default [
"no-implicit-coercion": "error",
"no-inner-declarations": "error",
"no-lonely-if": "error",
+ "no-restricted-imports": ["error", "assert", "node:assert"],
"no-unneeded-ternary": "error",
"no-useless-return": "error",
"no-unused-expressions": [
diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js
index f83e7e413bfd..8c3979bb9edf 100644
--- a/scripts/build/build-javascript-module.js
+++ b/scripts/build/build-javascript-module.js
@@ -179,7 +179,7 @@ function getEsbuildOptions({ packageConfig, file, cliOptions }) {
// TODO[@fisker]: Find a better way
{
module: "*",
- find: ' from "node:assert";',
+ find: ' from "node:assert/strict";',
replacement: ` from ${JSON.stringify(
path.join(dirname, "./shims/assert.js"),
)};`,
diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js
index da50dff68b24..a06abe83d2e9 100644
--- a/src/language-html/print/tag.js
+++ b/src/language-html/print/tag.js
@@ -2,7 +2,7 @@
* @import {Doc} from "../../document/builders.js"
*/
indent,
diff --git a/src/language-js/parse/postprocess/index.js b/src/language-js/parse/postprocess/index.js
index d00896f690cd..e67963a89531 100644
--- a/src/language-js/parse/postprocess/index.js
+++ b/src/language-js/parse/postprocess/index.js
import isNonEmptyArray from "../../../utils/is-non-empty-array.js";
import { locEnd, locStart } from "../../loc.js";
import createTypeCheckFunction from "../../utils/create-type-check-function.js";
diff --git a/src/language-js/print/flow.js b/src/language-js/print/flow.js
index 0005631cd220..082778b5c793 100644
--- a/src/language-js/print/flow.js
+++ b/src/language-js/print/flow.js
@@ -1,6 +1,6 @@
/** @import {Doc} from "../../document/builders.js" */
import { replaceEndOfLine } from "../../document/utils.js";
import printNumber from "../../utils/print-number.js";
import printString from "../../utils/print-string.js";
diff --git a/src/language-js/print/function.js b/src/language-js/print/function.js
index 0c71e4b1cd92..10bb06b780f1 100644
--- a/src/language-js/print/function.js
+++ b/src/language-js/print/function.js
group,
diff --git a/src/language-js/utils/get-text-without-comments.js b/src/language-js/utils/get-text-without-comments.js
index 385ec4ee2aee..93114a4f8732 100644
--- a/src/language-js/utils/get-text-without-comments.js
+++ b/src/language-js/utils/get-text-without-comments.js
import { locEnd, locStart } from "../loc.js";
function getTextWithoutComments(options, start, end) {
diff --git a/src/language-markdown/utils.js b/src/language-markdown/utils.js
index bb0baf37095a..542e4ab5e4e8 100644
--- a/src/language-markdown/utils.js
+++ b/src/language-markdown/utils.js
import { CJK_REGEXP, PUNCTUATION_REGEXP } from "./constants.evaluate.js";
import { locEnd, locStart } from "./loc.js";
diff --git a/src/main/comments/attach.js b/src/main/comments/attach.js
index 956d8267b280..3a4d0bd4bc33 100644
--- a/src/main/comments/attach.js
+++ b/src/main/comments/attach.js
import { getChildren } from "../../utils/ast-utils.js";
import hasNewline from "../../utils/has-newline.js";
import isNonEmptyArray from "../../utils/is-non-empty-array.js";
diff --git a/src/main/range-util.js b/src/main/range-util.js
index cdf28aa9250c..19e9efd00b0a 100644
--- a/src/main/range-util.js
+++ b/src/main/range-util.js
import { getSortedChildNodes } from "./comments/attach.js";
const isJsonParser = ({ parser }) =>
diff --git a/src/utils/print-string.js b/src/utils/print-string.js
index 945e10264986..77cd7e77c476 100644
--- a/src/utils/print-string.js
+++ b/src/utils/print-string.js
import getPreferredQuote from "./get-preferred-quote.js";
import makeString from "./make-string.js"; | [] | [] | {
"additions": 11,
"author": "fisker",
"deletions": 10,
"html_url": "https://github.com/prettier/prettier/pull/15728",
"issue_id": 15728,
"merged_at": "2025-04-23T17:44:04Z",
"omission_probability": 0.1,
"pr_number": 15728,
"repo": "prettier/prettier",
"title": "[V4] Use `node:assert/strict`",
"total_changes": 21
} |
157 | diff --git a/src/cli/format.js b/src/cli/format.js
index cfeac1dad057..30abf3d50cc7 100644
--- a/src/cli/format.js
+++ b/src/cli/format.js
@@ -16,7 +16,7 @@ import {
} from "./prettier-internal.js";
import { normalizeToPosix, statSafe } from "./utils.js";
-const { writeFormattedFile } = mockable;
+const { writeFormattedFile, getTimestamp } = mockable;
function diff(a, b) {
return createTwoFilesPatch("", "", a, b, "", "", { context: 2 });
@@ -193,14 +193,11 @@ async function format(context, input, opt) {
context.logger.debug(
`'${performanceTestFlag.name}' found, running formatWithCursor ${repeat} times.`,
);
- let totalMs = 0;
+ const start = getTimestamp();
for (let i = 0; i < repeat; ++i) {
- // should be using `performance.now()`, but only `Date` is cross-platform enough
- const startMs = Date.now();
await prettier.formatWithCursor(input, opt);
- totalMs += Date.now() - startMs;
}
- const averageMs = totalMs / repeat;
+ const averageMs = (getTimestamp() - start) / repeat;
const results = {
repeat,
hz: 1000 / averageMs,
@@ -366,7 +363,7 @@ async function formatFiles(context) {
continue;
}
- const start = Date.now();
+ const start = getTimestamp();
const isCacheExists = formatResultsCache?.existsAvailableFormatResultsCache(
filename,
@@ -408,11 +405,12 @@ async function formatFiles(context) {
}
if (context.argv.write) {
+ const timeToDisplay = `${Math.round(getTimestamp() - start)}ms`;
// Don't write the file if it won't change in order not to invalidate
// mtime based caches.
if (isDifferent) {
if (!context.argv.check && !context.argv.listDifferent) {
- context.logger.log(`${fileNameToDisplay} ${Date.now() - start}ms`);
+ context.logger.log(`${fileNameToDisplay} ${timeToDisplay}`);
}
try {
@@ -429,9 +427,7 @@ async function formatFiles(context) {
process.exitCode = 2;
}
} else if (!context.argv.check && !context.argv.listDifferent) {
- const message = `${picocolors.gray(fileNameToDisplay)} ${
- Date.now() - start
- }ms (unchanged)`;
+ const message = `${picocolors.gray(fileNameToDisplay)} ${timeToDisplay} (unchanged)`;
if (isCacheExists) {
context.logger.log(`${message} (cached)`);
} else {
diff --git a/src/common/mockable.js b/src/common/mockable.js
index 15937268d548..f57bf94792a8 100644
--- a/src/common/mockable.js
+++ b/src/common/mockable.js
@@ -1,4 +1,5 @@
import fs from "node:fs/promises";
+import { performance } from "node:perf_hooks";
import { isCI } from "ci-info";
function writeFormattedFile(file, data) {
@@ -9,6 +10,7 @@ const mockable = {
getPrettierConfigSearchStopDirectory: () => undefined,
isCI: () => isCI,
writeFormattedFile,
+ getTimestamp: performance.now.bind(performance),
};
export default mockable;
diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js
index 4abd4337bd2a..a4433839b605 100644
--- a/tests/integration/cli-worker.js
+++ b/tests/integration/cli-worker.js
@@ -18,8 +18,6 @@ const replaceAll = (text, find, replacement) =>
: text.split(find).join(replacement);
async function run(options) {
- Date.now = () => 0;
-
readline.clearLine = (stream) => {
stream.write(
`\n[[called readline.clearLine(${
@@ -38,6 +36,8 @@ async function run(options) {
const prettier = await import(url.pathToFileURL(prettierMainEntry));
const { mockable } = prettier.__debug;
+ // Time measure in format test
+ mockable.getTimestamp = () => 0;
mockable.isCI = () => Boolean(options.ci);
mockable.getPrettierConfigSearchStopDirectory = () =>
url.fileURLToPath(new URL("./cli", import.meta.url));
| diff --git a/src/cli/format.js b/src/cli/format.js
index cfeac1dad057..30abf3d50cc7 100644
--- a/src/cli/format.js
+++ b/src/cli/format.js
@@ -16,7 +16,7 @@ import {
} from "./prettier-internal.js";
import { normalizeToPosix, statSafe } from "./utils.js";
-const { writeFormattedFile } = mockable;
+const { writeFormattedFile, getTimestamp } = mockable;
function diff(a, b) {
return createTwoFilesPatch("", "", a, b, "", "", { context: 2 });
@@ -193,14 +193,11 @@ async function format(context, input, opt) {
context.logger.debug(
`'${performanceTestFlag.name}' found, running formatWithCursor ${repeat} times.`,
);
- let totalMs = 0;
for (let i = 0; i < repeat; ++i) {
- // should be using `performance.now()`, but only `Date` is cross-platform enough
- const startMs = Date.now();
await prettier.formatWithCursor(input, opt);
- totalMs += Date.now() - startMs;
- const averageMs = totalMs / repeat;
+ const averageMs = (getTimestamp() - start) / repeat;
const results = {
repeat,
hz: 1000 / averageMs,
@@ -366,7 +363,7 @@ async function formatFiles(context) {
continue;
- const start = Date.now();
const isCacheExists = formatResultsCache?.existsAvailableFormatResultsCache(
filename,
@@ -408,11 +405,12 @@ async function formatFiles(context) {
if (context.argv.write) {
+ const timeToDisplay = `${Math.round(getTimestamp() - start)}ms`;
// Don't write the file if it won't change in order not to invalidate
// mtime based caches.
if (isDifferent) {
if (!context.argv.check && !context.argv.listDifferent) {
- context.logger.log(`${fileNameToDisplay} ${Date.now() - start}ms`);
+ context.logger.log(`${fileNameToDisplay} ${timeToDisplay}`);
try {
@@ -429,9 +427,7 @@ async function formatFiles(context) {
process.exitCode = 2;
} else if (!context.argv.check && !context.argv.listDifferent) {
- const message = `${picocolors.gray(fileNameToDisplay)} ${
- Date.now() - start
- }ms (unchanged)`;
if (isCacheExists) {
context.logger.log(`${message} (cached)`);
} else {
diff --git a/src/common/mockable.js b/src/common/mockable.js
index 15937268d548..f57bf94792a8 100644
--- a/src/common/mockable.js
+++ b/src/common/mockable.js
@@ -1,4 +1,5 @@
import fs from "node:fs/promises";
+import { performance } from "node:perf_hooks";
import { isCI } from "ci-info";
function writeFormattedFile(file, data) {
@@ -9,6 +10,7 @@ const mockable = {
getPrettierConfigSearchStopDirectory: () => undefined,
isCI: () => isCI,
writeFormattedFile,
+ getTimestamp: performance.now.bind(performance),
};
export default mockable;
diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js
index 4abd4337bd2a..a4433839b605 100644
--- a/tests/integration/cli-worker.js
+++ b/tests/integration/cli-worker.js
@@ -18,8 +18,6 @@ const replaceAll = (text, find, replacement) =>
: text.split(find).join(replacement);
async function run(options) {
- Date.now = () => 0;
-
readline.clearLine = (stream) => {
stream.write(
`\n[[called readline.clearLine(${
@@ -38,6 +36,8 @@ async function run(options) {
const prettier = await import(url.pathToFileURL(prettierMainEntry));
const { mockable } = prettier.__debug;
+ // Time measure in format test
mockable.isCI = () => Boolean(options.ci);
mockable.getPrettierConfigSearchStopDirectory = () =>
url.fileURLToPath(new URL("./cli", import.meta.url)); | [
"+ const message = `${picocolors.gray(fileNameToDisplay)} ${timeToDisplay} (unchanged)`;",
"+ mockable.getTimestamp = () => 0;"
] | [
60,
100
] | {
"additions": 11,
"author": "fisker",
"deletions": 13,
"html_url": "https://github.com/prettier/prettier/pull/17390",
"issue_id": 17390,
"merged_at": "2025-04-22T18:51:20Z",
"omission_probability": 0.1,
"pr_number": 17390,
"repo": "prettier/prettier",
"title": "Measure time with `performance.now()` instead of `Date.now()`",
"total_changes": 24
} |
158 | diff --git a/src/cli/format.js b/src/cli/format.js
index 5f3e04b51245..cfeac1dad057 100644
--- a/src/cli/format.js
+++ b/src/cli/format.js
@@ -1,5 +1,6 @@
import fs from "node:fs/promises";
import path from "node:path";
+import getStdin from "get-stdin";
import * as prettier from "../index.js";
import { expandPatterns } from "./expand-patterns.js";
import findCacheFile from "./find-cache-file.js";
@@ -15,7 +16,7 @@ import {
} from "./prettier-internal.js";
import { normalizeToPosix, statSafe } from "./utils.js";
-const { getStdin, writeFormattedFile } = mockable;
+const { writeFormattedFile } = mockable;
function diff(a, b) {
return createTwoFilesPatch("", "", a, b, "", "", { context: 2 });
diff --git a/src/common/mockable.js b/src/common/mockable.js
index 97acb8c6bf91..15937268d548 100644
--- a/src/common/mockable.js
+++ b/src/common/mockable.js
@@ -1,6 +1,5 @@
import fs from "node:fs/promises";
import { isCI } from "ci-info";
-import getStdin from "get-stdin";
function writeFormattedFile(file, data) {
return fs.writeFile(file, data);
@@ -8,7 +7,6 @@ function writeFormattedFile(file, data) {
const mockable = {
getPrettierConfigSearchStopDirectory: () => undefined,
- getStdin,
isCI: () => isCI,
writeFormattedFile,
};
diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js
index 217e136e5680..8f1add87dd56 100644
--- a/tests/integration/cli-worker.js
+++ b/tests/integration/cli-worker.js
@@ -55,11 +55,6 @@ async function run(options) {
const prettier = await import(url.pathToFileURL(prettierMainEntry));
const { mockable } = prettier.__debug;
- // We cannot use `jest.setMock("get-stream", impl)` here, because in the
- // production build everything is bundled into one file so there is no
- // "get-stream" module to mock.
- // eslint-disable-next-line require-await
- mockable.getStdin = async () => options.input || "";
mockable.isCI = () => Boolean(options.ci);
mockable.getPrettierConfigSearchStopDirectory = () =>
url.fileURLToPath(new URL("./cli", import.meta.url));
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index 819a3fa8545b..84cb53d3d773 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -2,6 +2,17 @@ import childProcess from "node:child_process";
import path from "node:path";
import url from "node:url";
+/**
+@typedef {{
+ isTTY?: boolean,
+ stdoutIsTTY?: boolean,
+ ci?: boolean,
+ mockWriteFileErrors?: Record<string, string>,
+ nodeOptions?: string[],
+ input?: string,
+}} CliTestOptions
+*/
+
// Though the doc says `childProcess.fork` accepts `URL`, but seems not true
// TODO: Use `URL` directly when we drop support for Node.js v14
const CLI_WORKER_FILE = url.fileURLToPath(
@@ -16,6 +27,11 @@ const removeFinalNewLine = (string) =>
const SUPPORTS_DISABLE_WARNING_FLAG =
Number(process.versions.node.split(".")[0]) >= 20;
+/**
+ * @param {string} dir
+ * @param {string[]} args
+ * @param {CliTestOptions} options
+ */
function runCliWorker(dir, args, options) {
const result = {
status: undefined,
@@ -34,7 +50,7 @@ function runCliWorker(dir, args, options) {
: []),
...nodeOptions,
],
- stdio: "pipe",
+ stdio: [options.input ? "pipe" : "ignore", "pipe", "pipe", "ipc"],
env: {
...process.env,
NO_COLOR: "1",
@@ -53,6 +69,10 @@ function runCliWorker(dir, args, options) {
});
}
+ if (options.input) {
+ worker.stdin.end(options.input);
+ }
+
const removeStdioFinalNewLine = () => {
for (const stream of ["stdout", "stderr"]) {
result[stream] = removeFinalNewLine(result[stream]);
@@ -101,6 +121,11 @@ function runPrettierCli(dir, args, options) {
return runCliWorker(dir, args, options);
}
+/**
+ * @param {string} dir
+ * @param {string[]} [args]
+ * @param {CliTestOptions} [options]
+ */
function runCli(dir, args = [], options = {}) {
const promise = runPrettierCli(dir, args, options);
const getters = {
| diff --git a/src/cli/format.js b/src/cli/format.js
index 5f3e04b51245..cfeac1dad057 100644
--- a/src/cli/format.js
+++ b/src/cli/format.js
@@ -1,5 +1,6 @@
+import getStdin from "get-stdin";
import * as prettier from "../index.js";
import { expandPatterns } from "./expand-patterns.js";
import findCacheFile from "./find-cache-file.js";
@@ -15,7 +16,7 @@ import {
} from "./prettier-internal.js";
import { normalizeToPosix, statSafe } from "./utils.js";
-const { getStdin, writeFormattedFile } = mockable;
function diff(a, b) {
return createTwoFilesPatch("", "", a, b, "", "", { context: 2 });
diff --git a/src/common/mockable.js b/src/common/mockable.js
index 97acb8c6bf91..15937268d548 100644
--- a/src/common/mockable.js
+++ b/src/common/mockable.js
@@ -1,6 +1,5 @@
import { isCI } from "ci-info";
-import getStdin from "get-stdin";
function writeFormattedFile(file, data) {
return fs.writeFile(file, data);
@@ -8,7 +7,6 @@ function writeFormattedFile(file, data) {
const mockable = {
getPrettierConfigSearchStopDirectory: () => undefined,
- getStdin,
isCI: () => isCI,
writeFormattedFile,
};
diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js
index 217e136e5680..8f1add87dd56 100644
--- a/tests/integration/cli-worker.js
+++ b/tests/integration/cli-worker.js
@@ -55,11 +55,6 @@ async function run(options) {
const prettier = await import(url.pathToFileURL(prettierMainEntry));
const { mockable } = prettier.__debug;
- // We cannot use `jest.setMock("get-stream", impl)` here, because in the
- // production build everything is bundled into one file so there is no
- // "get-stream" module to mock.
- // eslint-disable-next-line require-await
- mockable.getStdin = async () => options.input || "";
mockable.isCI = () => Boolean(options.ci);
mockable.getPrettierConfigSearchStopDirectory = () =>
url.fileURLToPath(new URL("./cli", import.meta.url));
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index 819a3fa8545b..84cb53d3d773 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -2,6 +2,17 @@ import childProcess from "node:child_process";
import url from "node:url";
+ isTTY?: boolean,
+ stdoutIsTTY?: boolean,
+ ci?: boolean,
+ mockWriteFileErrors?: Record<string, string>,
+ nodeOptions?: string[],
+ input?: string,
+}} CliTestOptions
+*/
// Though the doc says `childProcess.fork` accepts `URL`, but seems not true
// TODO: Use `URL` directly when we drop support for Node.js v14
const CLI_WORKER_FILE = url.fileURLToPath(
@@ -16,6 +27,11 @@ const removeFinalNewLine = (string) =>
const SUPPORTS_DISABLE_WARNING_FLAG =
Number(process.versions.node.split(".")[0]) >= 20;
+ * @param {string[]} args
+ * @param {CliTestOptions} options
function runCliWorker(dir, args, options) {
const result = {
status: undefined,
@@ -34,7 +50,7 @@ function runCliWorker(dir, args, options) {
: []),
...nodeOptions,
],
- stdio: "pipe",
+ stdio: [options.input ? "pipe" : "ignore", "pipe", "pipe", "ipc"],
env: {
...process.env,
NO_COLOR: "1",
@@ -53,6 +69,10 @@ function runCliWorker(dir, args, options) {
});
}
+ if (options.input) {
+ worker.stdin.end(options.input);
+ }
const removeStdioFinalNewLine = () => {
for (const stream of ["stdout", "stderr"]) {
result[stream] = removeFinalNewLine(result[stream]);
@@ -101,6 +121,11 @@ function runPrettierCli(dir, args, options) {
return runCliWorker(dir, args, options);
}
+ * @param {string[]} [args]
+ * @param {CliTestOptions} [options]
function runCli(dir, args = [], options = {}) {
const promise = runPrettierCli(dir, args, options);
const getters = { | [
"+const { writeFormattedFile } = mockable;",
"+@typedef {{"
] | [
16,
64
] | {
"additions": 28,
"author": "fisker",
"deletions": 9,
"html_url": "https://github.com/prettier/prettier/pull/17389",
"issue_id": 17389,
"merged_at": "2025-04-22T18:30:55Z",
"omission_probability": 0.1,
"pr_number": 17389,
"repo": "prettier/prettier",
"title": "Remove `stdin` mock",
"total_changes": 37
} |
159 | diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js
index 217e136e5680..5a143a2becc3 100644
--- a/tests/integration/cli-worker.js
+++ b/tests/integration/cli-worker.js
@@ -1,4 +1,3 @@
-import fs from "node:fs";
import path from "node:path";
import readline from "node:readline";
import url from "node:url";
@@ -21,22 +20,6 @@ const replaceAll = (text, find, replacement) =>
async function run(options) {
Date.now = () => 0;
- /*
- A fake non-existing directory to test plugin search won't crash.
-
- See:
- - `isDirectory` function in `src/common/load-plugins.js`
- - Test file `./__tests__/plugin-virtual-directory.js`
- - Pull request #5819
- */
- const originalStat = fs.promises.stat;
- fs.promises.statSync = (filename) =>
- originalStat(
- path.basename(filename) === "virtualDirectory"
- ? import.meta.url
- : filename,
- );
-
readline.clearLine = (stream) => {
stream.write(
`\n[[called readline.clearLine(${
| diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js
index 217e136e5680..5a143a2becc3 100644
--- a/tests/integration/cli-worker.js
+++ b/tests/integration/cli-worker.js
@@ -1,4 +1,3 @@
import path from "node:path";
import readline from "node:readline";
import url from "node:url";
@@ -21,22 +20,6 @@ const replaceAll = (text, find, replacement) =>
async function run(options) {
Date.now = () => 0;
- /*
- A fake non-existing directory to test plugin search won't crash.
- - `isDirectory` function in `src/common/load-plugins.js`
- - Test file `./__tests__/plugin-virtual-directory.js`
- - Pull request #5819
- */
- const originalStat = fs.promises.stat;
- fs.promises.statSync = (filename) =>
- originalStat(
- path.basename(filename) === "virtualDirectory"
- ? import.meta.url
- : filename,
readline.clearLine = (stream) => {
stream.write(
`\n[[called readline.clearLine(${ | [
"-import fs from \"node:fs\";",
"- See:",
"- );"
] | [
5,
16,
27
] | {
"additions": 0,
"author": "fisker",
"deletions": 17,
"html_url": "https://github.com/prettier/prettier/pull/17391",
"issue_id": 17391,
"merged_at": "2025-04-22T18:25:01Z",
"omission_probability": 0.1,
"pr_number": 17391,
"repo": "prettier/prettier",
"title": "Remove outdated mock",
"total_changes": 17
} |
160 | diff --git a/jest.config.js b/jest.config.js
index c24814188931..873afa7beceb 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -55,8 +55,6 @@ if (SKIP_TESTS_WITH_NEW_SYNTAX) {
"<rootDir>/tests/integration/__tests__/config-invalid.js",
// Fails on Node.js v14
"<rootDir>/tests/dts/unit/run.js",
- // Unknown reason, fails on Node.js v14
- "<rootDir>/tests/integration/__tests__/config-file-typescript.js",
);
}
diff --git a/tests/integration/cli/patterns-backslashes/.gitignore b/tests/integration/cli/patterns-backslashes/.gitignore
index 96fef51b56e3..e53c48ff5ab1 100644
--- a/tests/integration/cli/patterns-backslashes/.gitignore
+++ b/tests/integration/cli/patterns-backslashes/.gitignore
@@ -1,2 +1,2 @@
# dynamically created by tests
-*
+test-*
diff --git a/tests/integration/cli/patterns-symlinks/.gitignore b/tests/integration/cli/patterns-symlinks/.gitignore
index 96fef51b56e3..e53c48ff5ab1 100644
--- a/tests/integration/cli/patterns-symlinks/.gitignore
+++ b/tests/integration/cli/patterns-symlinks/.gitignore
@@ -1,2 +1,2 @@
# dynamically created by tests
-*
+test-*
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index 45849482991c..819a3fa8545b 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -10,6 +10,7 @@ const CLI_WORKER_FILE = url.fileURLToPath(
const INTEGRATION_TEST_DIRECTORY = url.fileURLToPath(
new URL("./", import.meta.url),
);
+const IS_CI = Boolean(process.env.CI);
const removeFinalNewLine = (string) =>
string.endsWith("\n") ? string.slice(0, -1) : string;
const SUPPORTS_DISABLE_WARNING_FLAG =
@@ -39,7 +40,6 @@ function runCliWorker(dir, args, options) {
NO_COLOR: "1",
},
});
- worker.unref();
worker.on("message", ({ action, data }) => {
if (action === "write-file") {
@@ -70,7 +70,27 @@ function runCliWorker(dir, args, options) {
reject(error);
});
- worker.send(options);
+ worker.send(options, (error) => {
+ if (!error) {
+ return;
+ }
+
+ // It can fail with `write EPIPE` error when running node with unsupported flags like `--experimental-strip-types`
+ // Let's ignore and wait for the `close` event
+ if (
+ error.code === "EPIPE" &&
+ error.syscall === "write" &&
+ nodeOptions.length > 0
+ ) {
+ if (IS_CI) {
+ // eslint-disable-next-line no-console
+ console.error(Object.assign(error, { dir, args, options, worker }));
+ }
+ return;
+ }
+
+ reject(error);
+ });
});
}
@@ -130,7 +150,7 @@ function runCli(dir, args = [], options = {}) {
expect(value).toEqual(testOptions[name]);
}
} else {
- snapshot = snapshot || {};
+ snapshot = snapshot ?? {};
snapshot[name] = value;
}
}
| diff --git a/jest.config.js b/jest.config.js
index c24814188931..873afa7beceb 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -55,8 +55,6 @@ if (SKIP_TESTS_WITH_NEW_SYNTAX) {
"<rootDir>/tests/integration/__tests__/config-invalid.js",
// Fails on Node.js v14
"<rootDir>/tests/dts/unit/run.js",
- "<rootDir>/tests/integration/__tests__/config-file-typescript.js",
);
diff --git a/tests/integration/cli/patterns-backslashes/.gitignore b/tests/integration/cli/patterns-backslashes/.gitignore
--- a/tests/integration/cli/patterns-backslashes/.gitignore
+++ b/tests/integration/cli/patterns-backslashes/.gitignore
diff --git a/tests/integration/cli/patterns-symlinks/.gitignore b/tests/integration/cli/patterns-symlinks/.gitignore
--- a/tests/integration/cli/patterns-symlinks/.gitignore
+++ b/tests/integration/cli/patterns-symlinks/.gitignore
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index 45849482991c..819a3fa8545b 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -10,6 +10,7 @@ const CLI_WORKER_FILE = url.fileURLToPath(
const INTEGRATION_TEST_DIRECTORY = url.fileURLToPath(
new URL("./", import.meta.url),
);
+const IS_CI = Boolean(process.env.CI);
const removeFinalNewLine = (string) =>
string.endsWith("\n") ? string.slice(0, -1) : string;
const SUPPORTS_DISABLE_WARNING_FLAG =
@@ -39,7 +40,6 @@ function runCliWorker(dir, args, options) {
NO_COLOR: "1",
},
- worker.unref();
worker.on("message", ({ action, data }) => {
if (action === "write-file") {
@@ -70,7 +70,27 @@ function runCliWorker(dir, args, options) {
reject(error);
});
- worker.send(options);
+ worker.send(options, (error) => {
+ if (!error) {
+ // It can fail with `write EPIPE` error when running node with unsupported flags like `--experimental-strip-types`
+ // Let's ignore and wait for the `close` event
+ if (
+ error.code === "EPIPE" &&
+ error.syscall === "write" &&
+ ) {
+ if (IS_CI) {
+ // eslint-disable-next-line no-console
+ console.error(Object.assign(error, { dir, args, options, worker }));
+ }
+ reject(error);
+ });
@@ -130,7 +150,7 @@ function runCli(dir, args = [], options = {}) {
expect(value).toEqual(testOptions[name]);
}
} else {
- snapshot = snapshot || {};
+ snapshot = snapshot ?? {};
snapshot[name] = value;
}
} | [
"- // Unknown reason, fails on Node.js v14",
"+ nodeOptions.length > 0"
] | [
8,
64
] | {
"additions": 25,
"author": "fisker",
"deletions": 7,
"html_url": "https://github.com/prettier/prettier/pull/17384",
"issue_id": 17384,
"merged_at": "2025-04-22T09:17:47Z",
"omission_probability": 0.1,
"pr_number": 17384,
"repo": "prettier/prettier",
"title": "Add failed test back",
"total_changes": 32
} |
161 | diff --git a/package.json b/package.json
index f1ed9e1cf3f1..b5e435d6dd68 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.6",
+ "jest-light-runner": "0.7.8",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/yarn.lock b/yarn.lock
index de24f5420900..47dd283d3e71 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
languageName: node
linkType: hard
-"jest-light-runner@npm:0.7.6":
- version: 0.7.6
- resolution: "jest-light-runner@npm:0.7.6"
+"jest-light-runner@npm:0.7.8":
+ version: 0.7.8
+ resolution: "jest-light-runner@npm:0.7.8"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/949f0f18ae762ba8025091bd96ac1e3b0e84e2eb406ac1233f46293bd9dbdd9e0452a2b1f4270958236233f854ff16fe0b788e7a6b6bc88dd0daa5ce2cc28ede
+ checksum: 10/e0e4057c7f5bbf3fcb559b1aa92966ec4323df94af3f00c8306426c1a92e5eca3106c8ea737a46c47baf4ea8da0255330f6e1bf0c107fec52a8e6dc5a02a6067
languageName: node
linkType: hard
@@ -7147,7 +7147,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.6"
+ jest-light-runner: "npm:0.7.8"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
| diff --git a/package.json b/package.json
index f1ed9e1cf3f1..b5e435d6dd68 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.6",
+ "jest-light-runner": "0.7.8",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/yarn.lock b/yarn.lock
index de24f5420900..47dd283d3e71 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
-"jest-light-runner@npm:0.7.6":
- version: 0.7.6
- resolution: "jest-light-runner@npm:0.7.6"
+"jest-light-runner@npm:0.7.8":
+ version: 0.7.8
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
+ checksum: 10/e0e4057c7f5bbf3fcb559b1aa92966ec4323df94af3f00c8306426c1a92e5eca3106c8ea737a46c47baf4ea8da0255330f6e1bf0c107fec52a8e6dc5a02a6067
@@ -7147,7 +7147,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.6"
+ jest-light-runner: "npm:0.7.8"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2" | [
"+ resolution: \"jest-light-runner@npm:0.7.8\"",
"- checksum: 10/949f0f18ae762ba8025091bd96ac1e3b0e84e2eb406ac1233f46293bd9dbdd9e0452a2b1f4270958236233f854ff16fe0b788e7a6b6bc88dd0daa5ce2cc28ede"
] | [
26,
34
] | {
"additions": 6,
"author": "renovate[bot]",
"deletions": 6,
"html_url": "https://github.com/prettier/prettier/pull/17385",
"issue_id": 17385,
"merged_at": "2025-04-21T14:11:42Z",
"omission_probability": 0.1,
"pr_number": 17385,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency jest-light-runner to v0.7.8",
"total_changes": 12
} |
162 | diff --git a/package.json b/package.json
index fdd7a43f295d..f1ed9e1cf3f1 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.5",
+ "jest-light-runner": "0.7.6",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/yarn.lock b/yarn.lock
index 0b234789d4bf..de24f5420900 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
languageName: node
linkType: hard
-"jest-light-runner@npm:0.7.5":
- version: 0.7.5
- resolution: "jest-light-runner@npm:0.7.5"
+"jest-light-runner@npm:0.7.6":
+ version: 0.7.6
+ resolution: "jest-light-runner@npm:0.7.6"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/6d0ab4a8594672bf238a6b82bca03147f90cba8e2bd8ccaa39cdafa7157ca1e64d606a72cfb5e840599750bcdd157b62294f8825af064672da355cf746956707
+ checksum: 10/949f0f18ae762ba8025091bd96ac1e3b0e84e2eb406ac1233f46293bd9dbdd9e0452a2b1f4270958236233f854ff16fe0b788e7a6b6bc88dd0daa5ce2cc28ede
languageName: node
linkType: hard
@@ -7147,7 +7147,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.5"
+ jest-light-runner: "npm:0.7.6"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
| diff --git a/package.json b/package.json
index fdd7a43f295d..f1ed9e1cf3f1 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.5",
+ "jest-light-runner": "0.7.6",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/yarn.lock b/yarn.lock
index 0b234789d4bf..de24f5420900 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
- version: 0.7.5
- resolution: "jest-light-runner@npm:0.7.5"
+"jest-light-runner@npm:0.7.6":
+ version: 0.7.6
+ resolution: "jest-light-runner@npm:0.7.6"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
+ checksum: 10/949f0f18ae762ba8025091bd96ac1e3b0e84e2eb406ac1233f46293bd9dbdd9e0452a2b1f4270958236233f854ff16fe0b788e7a6b6bc88dd0daa5ce2cc28ede
@@ -7147,7 +7147,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.5"
+ jest-light-runner: "npm:0.7.6"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2" | [
"-\"jest-light-runner@npm:0.7.5\":",
"- checksum: 10/6d0ab4a8594672bf238a6b82bca03147f90cba8e2bd8ccaa39cdafa7157ca1e64d606a72cfb5e840599750bcdd157b62294f8825af064672da355cf746956707"
] | [
21,
34
] | {
"additions": 6,
"author": "renovate[bot]",
"deletions": 6,
"html_url": "https://github.com/prettier/prettier/pull/17383",
"issue_id": 17383,
"merged_at": "2025-04-21T08:17:59Z",
"omission_probability": 0.1,
"pr_number": 17383,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency jest-light-runner to v0.7.6",
"total_changes": 12
} |
163 | diff --git a/.github/workflows/prod-test.yml b/.github/workflows/prod-test.yml
index 4a12cf2d204a..bf6c995297e3 100644
--- a/.github/workflows/prod-test.yml
+++ b/.github/workflows/prod-test.yml
@@ -75,9 +75,8 @@ jobs:
- os: "ubuntu-latest"
node: "16"
# Tests on Intel Mac x Node.js 14 ( https://github.com/prettier/prettier/issues/16248 )
- # We are disabling MacOS x Node.js 14 temporary ( https://github.com/prettier/prettier/issues/16964 )
- # - os: "macos-13"
- # node: "14"
+ - os: "macos-13"
+ node: "14"
# setup-node does not support Node.js 14 x M1 Mac
exclude:
- os: "macos-latest"
diff --git a/jest.config.js b/jest.config.js
index 4376f74e1c5b..c24814188931 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -55,6 +55,8 @@ if (SKIP_TESTS_WITH_NEW_SYNTAX) {
"<rootDir>/tests/integration/__tests__/config-invalid.js",
// Fails on Node.js v14
"<rootDir>/tests/dts/unit/run.js",
+ // Unknown reason, fails on Node.js v14
+ "<rootDir>/tests/integration/__tests__/config-file-typescript.js",
);
}
@@ -63,7 +65,7 @@ const config = {
"<rootDir>/tests/config/format-test-setup.js",
"<rootDir>/tests/integration/integration-test-setup.js",
],
- runner: "jest-light-runner",
+ runner: "jest-light-runner/child-process",
snapshotSerializers: [
"jest-snapshot-serializer-raw",
"jest-snapshot-serializer-ansi",
diff --git a/package.json b/package.json
index dac94147d8bc..79610cf07d0a 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.6.0",
+ "jest-light-runner": "0.7.5",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
@@ -160,7 +160,7 @@
},
"scripts": {
"prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1",
- "test": "jest --runInBand",
+ "test": "jest",
"test:dev-package": "cross-env INSTALL_PACKAGE=1 yarn test",
"test:dist": "cross-env NODE_ENV=production yarn test",
"test:dist-standalone": "cross-env TEST_STANDALONE=1 yarn test:dist",
diff --git a/yarn.lock b/yarn.lock
index d0d568c7b5e1..b2b30bc90912 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
languageName: node
linkType: hard
-"jest-light-runner@npm:0.6.0":
- version: 0.6.0
- resolution: "jest-light-runner@npm:0.6.0"
+"jest-light-runner@npm:0.7.5":
+ version: 0.7.5
+ resolution: "jest-light-runner@npm:0.7.5"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5568,11 +5568,12 @@ __metadata:
jest-each: "npm:^30.0.0-alpha.1"
jest-mock: "npm:^30.0.0-alpha.1"
jest-snapshot: "npm:^30.0.0-alpha.1"
+ p-limit: "npm:^6.2.0"
supports-color: "npm:^9.2.1"
- tinypool: "npm:^0.8.1"
+ tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/74103180fa2b997e46b7ba08e3afa6b673dd35d0c15fcecf825f9b7768c53c4f416bcdb261285b234375caaf45dd7cab397d5def7d95271c8d75ac59237fbf86
+ checksum: 10/6d0ab4a8594672bf238a6b82bca03147f90cba8e2bd8ccaa39cdafa7157ca1e64d606a72cfb5e840599750bcdd157b62294f8825af064672da355cf746956707
languageName: node
linkType: hard
@@ -6724,6 +6725,15 @@ __metadata:
languageName: node
linkType: hard
+"p-limit@npm:^6.2.0":
+ version: 6.2.0
+ resolution: "p-limit@npm:6.2.0"
+ dependencies:
+ yocto-queue: "npm:^1.1.1"
+ checksum: 10/70e8df3e5f1c173c9bd9fa8390a3c5c2797505240ae42973536992b1f5f59a922153c2f35ff1bf36fb72a0f025b0f13fca062a4233e830adad446960d56b4d84
+ languageName: node
+ linkType: hard
+
"p-locate@npm:^4.1.0":
version: 4.1.0
resolution: "p-locate@npm:4.1.0"
@@ -7137,7 +7147,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.6.0"
+ jest-light-runner: "npm:0.7.5"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
@@ -8295,7 +8305,7 @@ __metadata:
languageName: node
linkType: hard
-"tinypool@npm:^0.8.1":
+"tinypool@npm:0.8.4":
version: 0.8.4
resolution: "tinypool@npm:0.8.4"
checksum: 10/7365944c2532f240111443e7012be31a634faf1a02db08a91db3aa07361c26a374d0be00a0f2ea052c4bee39c107ba67f1f814c108d9d51dfc725c559c1a9c03
@@ -8938,6 +8948,13 @@ __metadata:
languageName: node
linkType: hard
+"yocto-queue@npm:^1.1.1":
+ version: 1.2.1
+ resolution: "yocto-queue@npm:1.2.1"
+ checksum: 10/0843d6c2c0558e5c06e98edf9c17942f25c769e21b519303a5c2adefd5b738c9b2054204dc856ac0cd9d134b1bc27d928ce84fd23c9e2423b7e013d5a6f50577
+ languageName: node
+ linkType: hard
+
"zeptomatch-escape@npm:^1.0.0":
version: 1.0.1
resolution: "zeptomatch-escape@npm:1.0.1"
| diff --git a/.github/workflows/prod-test.yml b/.github/workflows/prod-test.yml
index 4a12cf2d204a..bf6c995297e3 100644
--- a/.github/workflows/prod-test.yml
+++ b/.github/workflows/prod-test.yml
@@ -75,9 +75,8 @@ jobs:
- os: "ubuntu-latest"
node: "16"
# Tests on Intel Mac x Node.js 14 ( https://github.com/prettier/prettier/issues/16248 )
- # - os: "macos-13"
- # node: "14"
+ - os: "macos-13"
+ node: "14"
# setup-node does not support Node.js 14 x M1 Mac
exclude:
- os: "macos-latest"
diff --git a/jest.config.js b/jest.config.js
index 4376f74e1c5b..c24814188931 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -55,6 +55,8 @@ if (SKIP_TESTS_WITH_NEW_SYNTAX) {
"<rootDir>/tests/integration/__tests__/config-invalid.js",
// Fails on Node.js v14
"<rootDir>/tests/dts/unit/run.js",
+ // Unknown reason, fails on Node.js v14
+ "<rootDir>/tests/integration/__tests__/config-file-typescript.js",
);
}
@@ -63,7 +65,7 @@ const config = {
"<rootDir>/tests/config/format-test-setup.js",
"<rootDir>/tests/integration/integration-test-setup.js",
],
+ runner: "jest-light-runner/child-process",
snapshotSerializers: [
"jest-snapshot-serializer-raw",
"jest-snapshot-serializer-ansi",
diff --git a/package.json b/package.json
index dac94147d8bc..79610cf07d0a 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.6.0",
+ "jest-light-runner": "0.7.5",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
@@ -160,7 +160,7 @@
},
"scripts": {
"prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1",
- "test": "jest --runInBand",
"test:dev-package": "cross-env INSTALL_PACKAGE=1 yarn test",
"test:dist": "cross-env NODE_ENV=production yarn test",
"test:dist-standalone": "cross-env TEST_STANDALONE=1 yarn test:dist",
diff --git a/yarn.lock b/yarn.lock
index d0d568c7b5e1..b2b30bc90912 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
-"jest-light-runner@npm:0.6.0":
- version: 0.6.0
- resolution: "jest-light-runner@npm:0.6.0"
+"jest-light-runner@npm:0.7.5":
+ version: 0.7.5
+ resolution: "jest-light-runner@npm:0.7.5"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5568,11 +5568,12 @@ __metadata:
jest-each: "npm:^30.0.0-alpha.1"
jest-mock: "npm:^30.0.0-alpha.1"
jest-snapshot: "npm:^30.0.0-alpha.1"
+ p-limit: "npm:^6.2.0"
supports-color: "npm:^9.2.1"
- tinypool: "npm:^0.8.1"
+ tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/74103180fa2b997e46b7ba08e3afa6b673dd35d0c15fcecf825f9b7768c53c4f416bcdb261285b234375caaf45dd7cab397d5def7d95271c8d75ac59237fbf86
+ checksum: 10/6d0ab4a8594672bf238a6b82bca03147f90cba8e2bd8ccaa39cdafa7157ca1e64d606a72cfb5e840599750bcdd157b62294f8825af064672da355cf746956707
@@ -6724,6 +6725,15 @@ __metadata:
+"p-limit@npm:^6.2.0":
+ version: 6.2.0
+ resolution: "p-limit@npm:6.2.0"
+ dependencies:
+ checksum: 10/70e8df3e5f1c173c9bd9fa8390a3c5c2797505240ae42973536992b1f5f59a922153c2f35ff1bf36fb72a0f025b0f13fca062a4233e830adad446960d56b4d84
"p-locate@npm:^4.1.0":
version: 4.1.0
resolution: "p-locate@npm:4.1.0"
@@ -7137,7 +7147,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.6.0"
+ jest-light-runner: "npm:0.7.5"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
@@ -8295,7 +8305,7 @@ __metadata:
-"tinypool@npm:^0.8.1":
version: 0.8.4
resolution: "tinypool@npm:0.8.4"
checksum: 10/7365944c2532f240111443e7012be31a634faf1a02db08a91db3aa07361c26a374d0be00a0f2ea052c4bee39c107ba67f1f814c108d9d51dfc725c559c1a9c03
@@ -8938,6 +8948,13 @@ __metadata:
+"yocto-queue@npm:^1.1.1":
+ version: 1.2.1
+ resolution: "yocto-queue@npm:1.2.1"
+ checksum: 10/0843d6c2c0558e5c06e98edf9c17942f25c769e21b519303a5c2adefd5b738c9b2054204dc856ac0cd9d134b1bc27d928ce84fd23c9e2423b7e013d5a6f50577
"zeptomatch-escape@npm:^1.0.0":
version: 1.0.1
resolution: "zeptomatch-escape@npm:1.0.1" | [
"- # We are disabling MacOS x Node.js 14 temporary ( https://github.com/prettier/prettier/issues/16964 )",
"- runner: \"jest-light-runner\",",
"+ \"test\": \"jest\",",
"+ yocto-queue: \"npm:^1.1.1\"",
"+\"tinypool@npm:0.8.4\":"
] | [
8,
33,
56,
100,
122
] | {
"additions": 31,
"author": "fisker",
"deletions": 13,
"html_url": "https://github.com/prettier/prettier/pull/17378",
"issue_id": 17378,
"merged_at": "2025-04-20T14:23:37Z",
"omission_probability": 0.1,
"pr_number": 17378,
"repo": "prettier/prettier",
"title": "Test: Remove `--runInBand`",
"total_changes": 44
} |
164 | diff --git a/package.json b/package.json
index dac94147d8bc..3b051234a9c3 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"bin"
],
"dependencies": {
- "@angular/compiler": "19.2.5",
+ "@angular/compiler": "19.2.7",
"@babel/code-frame": "7.26.2",
"@babel/parser": "7.27.0",
"@babel/types": "7.27.0",
diff --git a/yarn.lock b/yarn.lock
index d0d568c7b5e1..a521ae7be6f5 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -15,12 +15,12 @@ __metadata:
languageName: node
linkType: hard
-"@angular/compiler@npm:19.2.5":
- version: 19.2.5
- resolution: "@angular/compiler@npm:19.2.5"
+"@angular/compiler@npm:19.2.7":
+ version: 19.2.7
+ resolution: "@angular/compiler@npm:19.2.7"
dependencies:
tslib: "npm:^2.3.0"
- checksum: 10/3a36f13228a49fe7e4c8630df47a6220ef5164b62a5c3e7d883f811bcffce0319fcdcc1bdf20d358fb37ebf52be6a1b73cebaa0565b86e540eb0f21ac0979e5b
+ checksum: 10/b6545922029a74387a6680f84147a9d16c222ad16e601ccde5696231332a278357ba43d593157b71859f9f1631c3178423f552fcf70ef8dcb3d66cbf1bffea71
languageName: node
linkType: hard
@@ -7067,7 +7067,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "prettier@workspace:."
dependencies:
- "@angular/compiler": "npm:19.2.5"
+ "@angular/compiler": "npm:19.2.7"
"@babel/code-frame": "npm:7.26.2"
"@babel/generator": "npm:7.27.0"
"@babel/parser": "npm:7.27.0"
| diff --git a/package.json b/package.json
index dac94147d8bc..3b051234a9c3 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"bin"
],
"dependencies": {
- "@angular/compiler": "19.2.5",
+ "@angular/compiler": "19.2.7",
"@babel/code-frame": "7.26.2",
"@babel/parser": "7.27.0",
"@babel/types": "7.27.0",
diff --git a/yarn.lock b/yarn.lock
index d0d568c7b5e1..a521ae7be6f5 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -15,12 +15,12 @@ __metadata:
-"@angular/compiler@npm:19.2.5":
- resolution: "@angular/compiler@npm:19.2.5"
+"@angular/compiler@npm:19.2.7":
+ version: 19.2.7
tslib: "npm:^2.3.0"
- checksum: 10/3a36f13228a49fe7e4c8630df47a6220ef5164b62a5c3e7d883f811bcffce0319fcdcc1bdf20d358fb37ebf52be6a1b73cebaa0565b86e540eb0f21ac0979e5b
+ checksum: 10/b6545922029a74387a6680f84147a9d16c222ad16e601ccde5696231332a278357ba43d593157b71859f9f1631c3178423f552fcf70ef8dcb3d66cbf1bffea71
@@ -7067,7 +7067,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "prettier@workspace:."
- "@angular/compiler": "npm:19.2.5"
+ "@angular/compiler": "npm:19.2.7"
"@babel/code-frame": "npm:7.26.2"
"@babel/generator": "npm:7.27.0"
"@babel/parser": "npm:7.27.0" | [
"- version: 19.2.5",
"+ resolution: \"@angular/compiler@npm:19.2.7\""
] | [
22,
26
] | {
"additions": 6,
"author": "renovate[bot]",
"deletions": 6,
"html_url": "https://github.com/prettier/prettier/pull/17379",
"issue_id": 17379,
"merged_at": "2025-04-18T14:17:28Z",
"omission_probability": 0.1,
"pr_number": 17379,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency @angular/compiler to v19.2.7",
"total_changes": 12
} |
165 | diff --git a/.github/workflows/dev-test.yml b/.github/workflows/dev-test.yml
index 5b144d010fb2..b51a9a67b890 100644
--- a/.github/workflows/dev-test.yml
+++ b/.github/workflows/dev-test.yml
@@ -66,8 +66,7 @@ jobs:
- name: Run Tests (coverage)
if: ${{ matrix.ENABLE_CODE_COVERAGE }}
- # Use `--runInBand` gets better coverage https://github.com/nicolo-ribaudo/jest-light-runner/pull/92
- run: yarn c8 yarn test --runInBand
+ run: yarn c8 yarn test
- name: Upload Coverage
uses: codecov/codecov-action@v5
diff --git a/package.json b/package.json
index 30f02b2f1491..6680108f5574 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.2",
+ "jest-light-runner": "0.7.4",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/yarn.lock b/yarn.lock
index 2e3d371b1c02..713ee0a15ce6 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
languageName: node
linkType: hard
-"jest-light-runner@npm:0.7.2":
- version: 0.7.2
- resolution: "jest-light-runner@npm:0.7.2"
+"jest-light-runner@npm:0.7.4":
+ version: 0.7.4
+ resolution: "jest-light-runner@npm:0.7.4"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/0983d9e8db30506a57aae9566e9abdacee0a2730ce7fd26311940f86530744a4b7e1ebe1ae2a7c9ac863ba297da14d6800a4e671580aa0c9afaf6573fb2541c1
+ checksum: 10/470b5afc624134835bd73632d6e2d17fe75f70cdba7cee95b56b1a82cbde921f2f7e7e3108f4af561116d4f45158aa97ae7d035347487e8451f43d6eb37bf0d7
languageName: node
linkType: hard
@@ -7138,7 +7138,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.2"
+ jest-light-runner: "npm:0.7.4"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
| diff --git a/.github/workflows/dev-test.yml b/.github/workflows/dev-test.yml
index 5b144d010fb2..b51a9a67b890 100644
--- a/.github/workflows/dev-test.yml
+++ b/.github/workflows/dev-test.yml
@@ -66,8 +66,7 @@ jobs:
- name: Run Tests (coverage)
if: ${{ matrix.ENABLE_CODE_COVERAGE }}
- # Use `--runInBand` gets better coverage https://github.com/nicolo-ribaudo/jest-light-runner/pull/92
- run: yarn c8 yarn test --runInBand
+ run: yarn c8 yarn test
- name: Upload Coverage
uses: codecov/codecov-action@v5
diff --git a/package.json b/package.json
index 30f02b2f1491..6680108f5574 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.2",
+ "jest-light-runner": "0.7.4",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/yarn.lock b/yarn.lock
index 2e3d371b1c02..713ee0a15ce6 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
-"jest-light-runner@npm:0.7.2":
- version: 0.7.2
+"jest-light-runner@npm:0.7.4":
+ version: 0.7.4
+ resolution: "jest-light-runner@npm:0.7.4"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/0983d9e8db30506a57aae9566e9abdacee0a2730ce7fd26311940f86530744a4b7e1ebe1ae2a7c9ac863ba297da14d6800a4e671580aa0c9afaf6573fb2541c1
+ checksum: 10/470b5afc624134835bd73632d6e2d17fe75f70cdba7cee95b56b1a82cbde921f2f7e7e3108f4af561116d4f45158aa97ae7d035347487e8451f43d6eb37bf0d7
@@ -7138,7 +7138,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.2"
+ jest-light-runner: "npm:0.7.4"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2" | [
"- resolution: \"jest-light-runner@npm:0.7.2\""
] | [
37
] | {
"additions": 7,
"author": "fisker",
"deletions": 8,
"html_url": "https://github.com/prettier/prettier/pull/17377",
"issue_id": 17377,
"merged_at": "2025-04-18T07:27:14Z",
"omission_probability": 0.1,
"pr_number": 17377,
"repo": "prettier/prettier",
"title": "[V4] Update jest-light-runner to v0.7.4",
"total_changes": 15
} |
166 | diff --git a/eslint.config.js b/eslint.config.js
index 8a22cc627165..e7711753bd37 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -356,13 +356,6 @@ export default [
},
{
files: ["tests/**/*.js"],
- rules: {
- // TODO: Enable this when we drop support for Node.js v14
- "logical-assignment-operators": "off",
- "unicorn/prefer-array-flat": "off",
- "unicorn/prefer-array-flat-map": "off",
- "unicorn/prefer-string-replace-all": "off",
- },
languageOptions: {
globals: {
runCli: "readonly",
diff --git a/tests/config/get-prettier.js b/tests/config/get-prettier.js
index ea9ea97b8cc6..7409debc5fbf 100644
--- a/tests/config/get-prettier.js
+++ b/tests/config/get-prettier.js
@@ -26,7 +26,7 @@ function getPrettierInternal() {
let promise;
function getPrettier() {
- promise = promise ?? getPrettierInternal();
+ promise ??= getPrettierInternal();
return promise;
}
diff --git a/tests/config/run-format-test.js b/tests/config/run-format-test.js
index 0e08fcc48ee5..b34ce0e0b5f7 100644
--- a/tests/config/run-format-test.js
+++ b/tests/config/run-format-test.js
@@ -409,7 +409,7 @@ async function runTest({
if (!shouldSkipEolTest(code, formatResult.options)) {
for (const eol of ["\r\n", "\r"]) {
const { eolVisualizedOutput: output } = await format(
- code.replace(/\n/gu, eol),
+ code.replaceAll("\n", eol),
formatOptions,
);
// Only if `endOfLine: "auto"` the result will be different
@@ -417,7 +417,7 @@ async function runTest({
formatOptions.endOfLine === "auto"
? visualizeEndOfLine(
// All `code` use `LF`, so the `eol` of result is always `LF`
- formatResult.outputWithCursor.replace(/\n/gu, eol),
+ formatResult.outputWithCursor.replaceAll("\n", eol),
)
: formatResult.eolVisualizedOutput;
expect(output).toEqual(expected);
diff --git a/tests/config/utils/consistent-end-of-line.js b/tests/config/utils/consistent-end-of-line.js
index ecedbf7b0354..5ea72a1df9fa 100644
--- a/tests/config/utils/consistent-end-of-line.js
+++ b/tests/config/utils/consistent-end-of-line.js
@@ -1,7 +1,7 @@
function consistentEndOfLine(text) {
let firstEndOfLine;
- return text.replace(/\r\n?|\n/gu, (endOfLine) => {
- firstEndOfLine = firstEndOfLine ?? endOfLine;
+ return text.replaceAll(/\r\n?|\n/gu, (endOfLine) => {
+ firstEndOfLine ??= endOfLine;
return firstEndOfLine;
});
}
diff --git a/tests/config/utils/visualize-end-of-line.js b/tests/config/utils/visualize-end-of-line.js
index 1db619aeb368..8556039b6539 100644
--- a/tests/config/utils/visualize-end-of-line.js
+++ b/tests/config/utils/visualize-end-of-line.js
@@ -1,5 +1,5 @@
function visualizeEndOfLine(text) {
- return text.replace(/\r\n?|\n/gu, (endOfLine) => {
+ return text.replaceAll(/\r\n?|\n/gu, (endOfLine) => {
switch (endOfLine) {
case "\n":
return "<LF>\n";
diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js
index 79d7cff75155..492f70b5e5a0 100644
--- a/tests/integration/cli-worker.js
+++ b/tests/integration/cli-worker.js
@@ -7,17 +7,8 @@ import { prettierCli, prettierMainEntry } from "./env.js";
const normalizeToPosix =
path.sep === "\\"
- ? (filepath) => replaceAll(filepath, "\\", "/")
+ ? (filepath) => filepath.replaceAll("\\", "/")
: (filepath) => filepath;
-const hasOwn =
- Object.hasOwn ??
- ((object, property) =>
- // eslint-disable-next-line prefer-object-has-own
- Object.prototype.hasOwnProperty.call(object, property));
-const replaceAll = (text, find, replacement) =>
- text.replaceAll
- ? text.replaceAll(find, replacement)
- : text.split(find).join(replacement);
async function run() {
const { options } = workerData;
@@ -71,7 +62,7 @@ async function run() {
filename = normalizeToPosix(path.relative(process.cwd(), filename));
if (
options.mockWriteFileErrors &&
- hasOwn(options.mockWriteFileErrors, filename)
+ Object.hasOwn(options.mockWriteFileErrors, filename)
) {
throw new Error(
options.mockWriteFileErrors[filename] + " (mocked error)",
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index ec580dce41cc..7e11dc54892a 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -146,8 +146,8 @@ function runCli(dir, args = [], options = {}) {
// manually replacing this character with /*CR*/ to test its true presence
// If ignoreLineEndings is specified, \r is simply deleted instead
if (name === "stdout" || name === "stderr") {
- value = result[name].replace(
- /\r/gu,
+ value = result[name].replaceAll(
+ "\r",
options.ignoreLineEndings ? "" : "/*CR*/",
);
}
| diff --git a/eslint.config.js b/eslint.config.js
index 8a22cc627165..e7711753bd37 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -356,13 +356,6 @@ export default [
},
{
files: ["tests/**/*.js"],
- rules: {
- // TODO: Enable this when we drop support for Node.js v14
- "logical-assignment-operators": "off",
- "unicorn/prefer-array-flat": "off",
- "unicorn/prefer-string-replace-all": "off",
- },
languageOptions: {
globals: {
runCli: "readonly",
diff --git a/tests/config/get-prettier.js b/tests/config/get-prettier.js
index ea9ea97b8cc6..7409debc5fbf 100644
--- a/tests/config/get-prettier.js
+++ b/tests/config/get-prettier.js
@@ -26,7 +26,7 @@ function getPrettierInternal() {
let promise;
function getPrettier() {
- promise = promise ?? getPrettierInternal();
+ promise ??= getPrettierInternal();
return promise;
diff --git a/tests/config/run-format-test.js b/tests/config/run-format-test.js
index 0e08fcc48ee5..b34ce0e0b5f7 100644
--- a/tests/config/run-format-test.js
+++ b/tests/config/run-format-test.js
@@ -409,7 +409,7 @@ async function runTest({
if (!shouldSkipEolTest(code, formatResult.options)) {
for (const eol of ["\r\n", "\r"]) {
const { eolVisualizedOutput: output } = await format(
- code.replace(/\n/gu, eol),
+ code.replaceAll("\n", eol),
formatOptions,
);
// Only if `endOfLine: "auto"` the result will be different
@@ -417,7 +417,7 @@ async function runTest({
formatOptions.endOfLine === "auto"
? visualizeEndOfLine(
// All `code` use `LF`, so the `eol` of result is always `LF`
- formatResult.outputWithCursor.replace(/\n/gu, eol),
+ formatResult.outputWithCursor.replaceAll("\n", eol),
)
: formatResult.eolVisualizedOutput;
expect(output).toEqual(expected);
diff --git a/tests/config/utils/consistent-end-of-line.js b/tests/config/utils/consistent-end-of-line.js
index ecedbf7b0354..5ea72a1df9fa 100644
--- a/tests/config/utils/consistent-end-of-line.js
+++ b/tests/config/utils/consistent-end-of-line.js
@@ -1,7 +1,7 @@
function consistentEndOfLine(text) {
let firstEndOfLine;
- firstEndOfLine = firstEndOfLine ?? endOfLine;
+ firstEndOfLine ??= endOfLine;
return firstEndOfLine;
});
diff --git a/tests/config/utils/visualize-end-of-line.js b/tests/config/utils/visualize-end-of-line.js
index 1db619aeb368..8556039b6539 100644
--- a/tests/config/utils/visualize-end-of-line.js
+++ b/tests/config/utils/visualize-end-of-line.js
@@ -1,5 +1,5 @@
function visualizeEndOfLine(text) {
switch (endOfLine) {
case "\n":
return "<LF>\n";
diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js
index 79d7cff75155..492f70b5e5a0 100644
--- a/tests/integration/cli-worker.js
+++ b/tests/integration/cli-worker.js
@@ -7,17 +7,8 @@ import { prettierCli, prettierMainEntry } from "./env.js";
const normalizeToPosix =
path.sep === "\\"
- ? (filepath) => replaceAll(filepath, "\\", "/")
+ ? (filepath) => filepath.replaceAll("\\", "/")
: (filepath) => filepath;
-const hasOwn =
- Object.hasOwn ??
- ((object, property) =>
- // eslint-disable-next-line prefer-object-has-own
- Object.prototype.hasOwnProperty.call(object, property));
-const replaceAll = (text, find, replacement) =>
- text.replaceAll
- ? text.replaceAll(find, replacement)
- : text.split(find).join(replacement);
async function run() {
const { options } = workerData;
@@ -71,7 +62,7 @@ async function run() {
filename = normalizeToPosix(path.relative(process.cwd(), filename));
if (
options.mockWriteFileErrors &&
+ Object.hasOwn(options.mockWriteFileErrors, filename)
) {
throw new Error(
options.mockWriteFileErrors[filename] + " (mocked error)",
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index ec580dce41cc..7e11dc54892a 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -146,8 +146,8 @@ function runCli(dir, args = [], options = {}) {
// manually replacing this character with /*CR*/ to test its true presence
// If ignoreLineEndings is specified, \r is simply deleted instead
if (name === "stdout" || name === "stderr") {
- value = result[name].replace(
- /\r/gu,
+ value = result[name].replaceAll(
options.ignoreLineEndings ? "" : "/*CR*/",
);
} | [
"- \"unicorn/prefer-array-flat-map\": \"off\",",
"- hasOwn(options.mockWriteFileErrors, filename)",
"+ \"\\r\","
] | [
12,
105,
121
] | {
"additions": 10,
"author": "fisker",
"deletions": 26,
"html_url": "https://github.com/prettier/prettier/pull/17369",
"issue_id": 17369,
"merged_at": "2025-04-18T06:12:42Z",
"omission_probability": 0.1,
"pr_number": 17369,
"repo": "prettier/prettier",
"title": "[V4] Update ESLint config",
"total_changes": 36
} |
167 | diff --git a/.github/workflows/dev-test.yml b/.github/workflows/dev-test.yml
index b51a9a67b890..5b144d010fb2 100644
--- a/.github/workflows/dev-test.yml
+++ b/.github/workflows/dev-test.yml
@@ -66,7 +66,8 @@ jobs:
- name: Run Tests (coverage)
if: ${{ matrix.ENABLE_CODE_COVERAGE }}
- run: yarn c8 yarn test
+ # Use `--runInBand` gets better coverage https://github.com/nicolo-ribaudo/jest-light-runner/pull/92
+ run: yarn c8 yarn test --runInBand
- name: Upload Coverage
uses: codecov/codecov-action@v5
diff --git a/package.json b/package.json
index ddb9cfff4833..30f02b2f1491 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.1",
+ "jest-light-runner": "0.7.2",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/yarn.lock b/yarn.lock
index f9d7c2803d4c..2e3d371b1c02 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
languageName: node
linkType: hard
-"jest-light-runner@npm:0.7.1":
- version: 0.7.1
- resolution: "jest-light-runner@npm:0.7.1"
+"jest-light-runner@npm:0.7.2":
+ version: 0.7.2
+ resolution: "jest-light-runner@npm:0.7.2"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/860800c4eda36d928d1ba3f7923102e2b7af595cd1c6d2def704ee33b6919d93e7795f507a0ab6e953983d65240e23eac4a2dc61f5cb030f24278f39e895f1f6
+ checksum: 10/0983d9e8db30506a57aae9566e9abdacee0a2730ce7fd26311940f86530744a4b7e1ebe1ae2a7c9ac863ba297da14d6800a4e671580aa0c9afaf6573fb2541c1
languageName: node
linkType: hard
@@ -7138,7 +7138,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.1"
+ jest-light-runner: "npm:0.7.2"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
| diff --git a/.github/workflows/dev-test.yml b/.github/workflows/dev-test.yml
index b51a9a67b890..5b144d010fb2 100644
--- a/.github/workflows/dev-test.yml
+++ b/.github/workflows/dev-test.yml
@@ -66,7 +66,8 @@ jobs:
- name: Run Tests (coverage)
if: ${{ matrix.ENABLE_CODE_COVERAGE }}
+ # Use `--runInBand` gets better coverage https://github.com/nicolo-ribaudo/jest-light-runner/pull/92
+ run: yarn c8 yarn test --runInBand
- name: Upload Coverage
uses: codecov/codecov-action@v5
diff --git a/package.json b/package.json
index ddb9cfff4833..30f02b2f1491 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.1",
+ "jest-light-runner": "0.7.2",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/yarn.lock b/yarn.lock
index f9d7c2803d4c..2e3d371b1c02 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
-"jest-light-runner@npm:0.7.1":
- version: 0.7.1
+"jest-light-runner@npm:0.7.2":
+ version: 0.7.2
+ resolution: "jest-light-runner@npm:0.7.2"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/860800c4eda36d928d1ba3f7923102e2b7af595cd1c6d2def704ee33b6919d93e7795f507a0ab6e953983d65240e23eac4a2dc61f5cb030f24278f39e895f1f6
+ checksum: 10/0983d9e8db30506a57aae9566e9abdacee0a2730ce7fd26311940f86530744a4b7e1ebe1ae2a7c9ac863ba297da14d6800a4e671580aa0c9afaf6573fb2541c1
@@ -7138,7 +7138,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.1"
+ jest-light-runner: "npm:0.7.2"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2" | [
"- run: yarn c8 yarn test",
"- resolution: \"jest-light-runner@npm:0.7.1\""
] | [
8,
37
] | {
"additions": 8,
"author": "fisker",
"deletions": 7,
"html_url": "https://github.com/prettier/prettier/pull/17375",
"issue_id": 17375,
"merged_at": "2025-04-17T18:54:08Z",
"omission_probability": 0.1,
"pr_number": 17375,
"repo": "prettier/prettier",
"title": "[V4] Test: Fix coverage collect",
"total_changes": 15
} |
168 | diff --git a/package.json b/package.json
index 49fc90923889..ddb9cfff4833 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.0",
+ "jest-light-runner": "0.7.1",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index 429a8f7c569f..ec580dce41cc 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -1,7 +1,6 @@
import path from "node:path";
import url from "node:url";
import { Worker } from "node:worker_threads";
-import stripAnsi from "strip-ansi";
const CLI_WORKER_FILE = new URL("./cli-worker.js", import.meta.url);
const INTEGRATION_TEST_DIRECTORY = url.fileURLToPath(
@@ -52,6 +51,10 @@ function runCliWorker(dir, args, options) {
],
stdout: true,
stderr: true,
+ env: {
+ ...process.env,
+ NO_COLOR: "1",
+ },
workerData: {
dir,
options,
@@ -68,12 +71,8 @@ function runCliWorker(dir, args, options) {
return new Promise((resolve, reject) => {
worker.on("exit", async (code) => {
result.status = code;
- result.stdout = stripAnsi(
- removeFinalNewLine(await streamToString(worker.stdout)),
- );
- result.stderr = stripAnsi(
- removeFinalNewLine(await streamToString(worker.stderr)),
- );
+ result.stdout = removeFinalNewLine(await streamToString(worker.stdout));
+ result.stderr = removeFinalNewLine(await streamToString(worker.stderr));
resolve(result);
});
diff --git a/yarn.lock b/yarn.lock
index 510596a98230..f9d7c2803d4c 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
languageName: node
linkType: hard
-"jest-light-runner@npm:0.7.0":
- version: 0.7.0
- resolution: "jest-light-runner@npm:0.7.0"
+"jest-light-runner@npm:0.7.1":
+ version: 0.7.1
+ resolution: "jest-light-runner@npm:0.7.1"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/d30bbb7822ba21906a47cb025e0198e74cd9063f5da862c1e2ec54353ada5fec172b0a30cb01074029183acc59d85fd102baa46c7cb90d22cf717d9b57dd045b
+ checksum: 10/860800c4eda36d928d1ba3f7923102e2b7af595cd1c6d2def704ee33b6919d93e7795f507a0ab6e953983d65240e23eac4a2dc61f5cb030f24278f39e895f1f6
languageName: node
linkType: hard
@@ -7138,7 +7138,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.0"
+ jest-light-runner: "npm:0.7.1"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
| diff --git a/package.json b/package.json
index 49fc90923889..ddb9cfff4833 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.7.0",
+ "jest-light-runner": "0.7.1",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index 429a8f7c569f..ec580dce41cc 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -1,7 +1,6 @@
import path from "node:path";
import url from "node:url";
import { Worker } from "node:worker_threads";
-import stripAnsi from "strip-ansi";
const CLI_WORKER_FILE = new URL("./cli-worker.js", import.meta.url);
const INTEGRATION_TEST_DIRECTORY = url.fileURLToPath(
@@ -52,6 +51,10 @@ function runCliWorker(dir, args, options) {
],
stdout: true,
stderr: true,
+ ...process.env,
+ NO_COLOR: "1",
+ },
workerData: {
dir,
options,
@@ -68,12 +71,8 @@ function runCliWorker(dir, args, options) {
return new Promise((resolve, reject) => {
worker.on("exit", async (code) => {
result.status = code;
- result.stdout = stripAnsi(
- removeFinalNewLine(await streamToString(worker.stdout)),
- result.stderr = stripAnsi(
- removeFinalNewLine(await streamToString(worker.stderr)),
+ result.stdout = removeFinalNewLine(await streamToString(worker.stdout));
+ result.stderr = removeFinalNewLine(await streamToString(worker.stderr));
resolve(result);
});
diff --git a/yarn.lock b/yarn.lock
index 510596a98230..f9d7c2803d4c 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
-"jest-light-runner@npm:0.7.0":
- version: 0.7.0
- resolution: "jest-light-runner@npm:0.7.0"
+"jest-light-runner@npm:0.7.1":
+ version: 0.7.1
+ resolution: "jest-light-runner@npm:0.7.1"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5573,7 +5573,7 @@ __metadata:
tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/d30bbb7822ba21906a47cb025e0198e74cd9063f5da862c1e2ec54353ada5fec172b0a30cb01074029183acc59d85fd102baa46c7cb90d22cf717d9b57dd045b
+ checksum: 10/860800c4eda36d928d1ba3f7923102e2b7af595cd1c6d2def704ee33b6919d93e7795f507a0ab6e953983d65240e23eac4a2dc61f5cb030f24278f39e895f1f6
@@ -7138,7 +7138,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.7.0"
+ jest-light-runner: "npm:0.7.1"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2" | [
"+ env: {"
] | [
29
] | {
"additions": 12,
"author": "fisker",
"deletions": 13,
"html_url": "https://github.com/prettier/prettier/pull/17372",
"issue_id": 17372,
"merged_at": "2025-04-17T10:34:42Z",
"omission_probability": 0.1,
"pr_number": 17372,
"repo": "prettier/prettier",
"title": "[V4] Update `jest-light-runner` to v0.7.1",
"total_changes": 25
} |
169 | diff --git a/bin/prettier.cjs b/bin/prettier.cjs
index 78532120ec86..474e748630fc 100755
--- a/bin/prettier.cjs
+++ b/bin/prettier.cjs
@@ -14,11 +14,12 @@ var packageJson = require("../package.json");
pleaseUpgradeNode(packageJson);
var dynamicImport = new Function("module", "return import(module)");
-if (process.env.PRETTIER_LEGACY_CLI) {
+
+if (process.env.PRETTIER_EXPERIMENTAL_CLI) {
+ dynamicImport("@prettier/cli/bin");
+} else {
var promise = dynamicImport("../src/cli/index.js").then(function runCli(cli) {
return cli.run();
});
module.exports.__promise = promise;
-} else {
- dynamicImport("@prettier/cli/bin");
}
diff --git a/jest.config.js b/jest.config.js
index 6adf230173f5..713d193dca5d 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -11,6 +11,10 @@ const INSTALL_PACKAGE = Boolean(process.env.INSTALL_PACKAGE);
// When debugging production test, this flag can skip installing package
const SKIP_PRODUCTION_INSTALL = Boolean(process.env.SKIP_PRODUCTION_INSTALL);
+if (PROJECT_ROOT) {
+ process.env.PRETTIER_LEGACY_CLI = "1";
+}
+
let PRETTIER_DIR = isProduction
? path.join(PROJECT_ROOT, "dist/prettier")
: PROJECT_ROOT;
diff --git a/package.json b/package.json
index 1037f78c8691..49fc90923889 100644
--- a/package.json
+++ b/package.json
@@ -160,7 +160,7 @@
},
"scripts": {
"prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1",
- "test": "cross-env PRETTIER_LEGACY_CLI=1 jest",
+ "test": "jest",
"test:dev-package": "cross-env INSTALL_PACKAGE=1 yarn test",
"test:dist": "cross-env NODE_ENV=production yarn test",
"test:dist-standalone": "cross-env TEST_STANDALONE=1 yarn test:dist",
diff --git a/scripts/build/config.js b/scripts/build/config.js
index ddcb3069938e..0fd3858248fe 100644
--- a/scripts/build/config.js
+++ b/scripts/build/config.js
@@ -791,8 +791,17 @@ const nodejsFiles = [
replaceModule: [
{
module: path.join(PROJECT_ROOT, "bin/prettier.cjs"),
- process: (text) =>
- text.replace("../src/cli/index.js", "../internal/legacy-cli.mjs"),
+ process(text) {
+ text = text.replace(
+ "../src/cli/index.js",
+ "../internal/legacy-cli.mjs",
+ );
+ text = text.replace(
+ "process.env.PRETTIER_EXPERIMENTAL_CLI",
+ "!process.env.PRETTIER_LEGACY_CLI",
+ );
+ return text;
+ },
},
],
external: ["@prettier/cli"],
| diff --git a/bin/prettier.cjs b/bin/prettier.cjs
index 78532120ec86..474e748630fc 100755
--- a/bin/prettier.cjs
+++ b/bin/prettier.cjs
@@ -14,11 +14,12 @@ var packageJson = require("../package.json");
pleaseUpgradeNode(packageJson);
var dynamicImport = new Function("module", "return import(module)");
-if (process.env.PRETTIER_LEGACY_CLI) {
+ dynamicImport("@prettier/cli/bin");
+} else {
var promise = dynamicImport("../src/cli/index.js").then(function runCli(cli) {
return cli.run();
});
module.exports.__promise = promise;
-} else {
- dynamicImport("@prettier/cli/bin");
}
diff --git a/jest.config.js b/jest.config.js
index 6adf230173f5..713d193dca5d 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -11,6 +11,10 @@ const INSTALL_PACKAGE = Boolean(process.env.INSTALL_PACKAGE);
// When debugging production test, this flag can skip installing package
const SKIP_PRODUCTION_INSTALL = Boolean(process.env.SKIP_PRODUCTION_INSTALL);
+if (PROJECT_ROOT) {
+ process.env.PRETTIER_LEGACY_CLI = "1";
+}
let PRETTIER_DIR = isProduction
? path.join(PROJECT_ROOT, "dist/prettier")
: PROJECT_ROOT;
diff --git a/package.json b/package.json
index 1037f78c8691..49fc90923889 100644
--- a/package.json
+++ b/package.json
@@ -160,7 +160,7 @@
},
"scripts": {
"prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1",
- "test": "cross-env PRETTIER_LEGACY_CLI=1 jest",
+ "test": "jest",
"test:dev-package": "cross-env INSTALL_PACKAGE=1 yarn test",
"test:dist": "cross-env NODE_ENV=production yarn test",
"test:dist-standalone": "cross-env TEST_STANDALONE=1 yarn test:dist",
diff --git a/scripts/build/config.js b/scripts/build/config.js
index ddcb3069938e..0fd3858248fe 100644
--- a/scripts/build/config.js
+++ b/scripts/build/config.js
@@ -791,8 +791,17 @@ const nodejsFiles = [
replaceModule: [
{
module: path.join(PROJECT_ROOT, "bin/prettier.cjs"),
- process: (text) =>
- text.replace("../src/cli/index.js", "../internal/legacy-cli.mjs"),
+ process(text) {
+ "../src/cli/index.js",
+ "../internal/legacy-cli.mjs",
+ "process.env.PRETTIER_EXPERIMENTAL_CLI",
+ "!process.env.PRETTIER_LEGACY_CLI",
+ return text;
+ },
},
],
external: ["@prettier/cli"], | [
"+if (process.env.PRETTIER_EXPERIMENTAL_CLI) {"
] | [
10
] | {
"additions": 20,
"author": "fisker",
"deletions": 6,
"html_url": "https://github.com/prettier/prettier/pull/17368",
"issue_id": 17368,
"merged_at": "2025-04-17T09:12:45Z",
"omission_probability": 0.1,
"pr_number": 17368,
"repo": "prettier/prettier",
"title": "[V4] Use legacy CLI by default during development",
"total_changes": 26
} |
170 | diff --git a/package.json b/package.json
index 8c4fbcf9fefd..dac94147d8bc 100644
--- a/package.json
+++ b/package.json
@@ -94,7 +94,7 @@
"remark-math": "3.0.1",
"remark-parse": "8.0.3",
"sdbm": "2.0.0",
- "smol-toml": "1.3.1",
+ "smol-toml": "1.3.3",
"strip-ansi": "7.1.0",
"to-fast-properties": "4.0.0",
"trim-newlines": "5.0.0",
diff --git a/yarn.lock b/yarn.lock
index afd0ae322a49..d0d568c7b5e1 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -7174,7 +7174,7 @@ __metadata:
sdbm: "npm:2.0.0"
semver: "npm:7.7.1"
serialize-javascript: "npm:6.0.2"
- smol-toml: "npm:1.3.1"
+ smol-toml: "npm:1.3.3"
snapshot-diff: "npm:0.10.0"
strip-ansi: "npm:7.1.0"
tempy: "npm:3.1.0"
@@ -7713,10 +7713,10 @@ __metadata:
languageName: node
linkType: hard
-"smol-toml@npm:1.3.1, smol-toml@npm:^1.3.1":
- version: 1.3.1
- resolution: "smol-toml@npm:1.3.1"
- checksum: 10/b999828ea46cf44ae90b6293884d6a139dfb4545ac6f86cbd1002568a943a43d8895ad82413855d095eec0c0bc21d23413c0a25a26c7fad6395c2ce42c2fdbd0
+"smol-toml@npm:1.3.3, smol-toml@npm:^1.3.1":
+ version: 1.3.3
+ resolution: "smol-toml@npm:1.3.3"
+ checksum: 10/22dabed8f48860b285718aa33a10729da4aa5ceaa58b4d215d9879ddccad07b0690bd3183dbf88572a2cb805aac5b10b3a7d6e29632f33e83aa6170a95d56882
languageName: node
linkType: hard
| diff --git a/package.json b/package.json
index 8c4fbcf9fefd..dac94147d8bc 100644
--- a/package.json
+++ b/package.json
@@ -94,7 +94,7 @@
"remark-math": "3.0.1",
"remark-parse": "8.0.3",
"sdbm": "2.0.0",
- "smol-toml": "1.3.1",
+ "smol-toml": "1.3.3",
"strip-ansi": "7.1.0",
"to-fast-properties": "4.0.0",
"trim-newlines": "5.0.0",
diff --git a/yarn.lock b/yarn.lock
index afd0ae322a49..d0d568c7b5e1 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -7174,7 +7174,7 @@ __metadata:
sdbm: "npm:2.0.0"
semver: "npm:7.7.1"
serialize-javascript: "npm:6.0.2"
- smol-toml: "npm:1.3.1"
+ smol-toml: "npm:1.3.3"
snapshot-diff: "npm:0.10.0"
strip-ansi: "npm:7.1.0"
tempy: "npm:3.1.0"
@@ -7713,10 +7713,10 @@ __metadata:
-"smol-toml@npm:1.3.1, smol-toml@npm:^1.3.1":
- version: 1.3.1
- resolution: "smol-toml@npm:1.3.1"
- checksum: 10/b999828ea46cf44ae90b6293884d6a139dfb4545ac6f86cbd1002568a943a43d8895ad82413855d095eec0c0bc21d23413c0a25a26c7fad6395c2ce42c2fdbd0
+"smol-toml@npm:1.3.3, smol-toml@npm:^1.3.1":
+ version: 1.3.3
+ resolution: "smol-toml@npm:1.3.3"
+ checksum: 10/22dabed8f48860b285718aa33a10729da4aa5ceaa58b4d215d9879ddccad07b0690bd3183dbf88572a2cb805aac5b10b3a7d6e29632f33e83aa6170a95d56882 | [] | [] | {
"additions": 6,
"author": "renovate[bot]",
"deletions": 6,
"html_url": "https://github.com/prettier/prettier/pull/17370",
"issue_id": 17370,
"merged_at": "2025-04-17T07:05:43Z",
"omission_probability": 0.1,
"pr_number": 17370,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency smol-toml to v1.3.3",
"total_changes": 12
} |
171 | diff --git a/jest.config.js b/jest.config.js
index aaa654d68f0d..6adf230173f5 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -44,7 +44,7 @@ const config = {
"<rootDir>/tests/config/format-test-setup.js",
"<rootDir>/tests/integration/integration-test-setup.js",
],
- runner: "jest-light-runner",
+ runner: "./scripts/jest-light-process-runner.js",
snapshotSerializers: [
"jest-snapshot-serializer-raw",
"jest-snapshot-serializer-ansi",
diff --git a/package.json b/package.json
index 2692b6c67800..1037f78c8691 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.6.0",
+ "jest-light-runner": "0.7.0",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
@@ -160,7 +160,7 @@
},
"scripts": {
"prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1",
- "test": "cross-env PRETTIER_LEGACY_CLI=1 jest --runInBand",
+ "test": "cross-env PRETTIER_LEGACY_CLI=1 jest",
"test:dev-package": "cross-env INSTALL_PACKAGE=1 yarn test",
"test:dist": "cross-env NODE_ENV=production yarn test",
"test:dist-standalone": "cross-env TEST_STANDALONE=1 yarn test:dist",
diff --git a/scripts/jest-light-process-runner.js b/scripts/jest-light-process-runner.js
new file mode 100644
index 000000000000..c82983974fef
--- /dev/null
+++ b/scripts/jest-light-process-runner.js
@@ -0,0 +1,3 @@
+import { createRunner } from "jest-light-runner";
+
+export default createRunner({ runtime: "child_process" });
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index ec580dce41cc..429a8f7c569f 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -1,6 +1,7 @@
import path from "node:path";
import url from "node:url";
import { Worker } from "node:worker_threads";
+import stripAnsi from "strip-ansi";
const CLI_WORKER_FILE = new URL("./cli-worker.js", import.meta.url);
const INTEGRATION_TEST_DIRECTORY = url.fileURLToPath(
@@ -51,10 +52,6 @@ function runCliWorker(dir, args, options) {
],
stdout: true,
stderr: true,
- env: {
- ...process.env,
- NO_COLOR: "1",
- },
workerData: {
dir,
options,
@@ -71,8 +68,12 @@ function runCliWorker(dir, args, options) {
return new Promise((resolve, reject) => {
worker.on("exit", async (code) => {
result.status = code;
- result.stdout = removeFinalNewLine(await streamToString(worker.stdout));
- result.stderr = removeFinalNewLine(await streamToString(worker.stderr));
+ result.stdout = stripAnsi(
+ removeFinalNewLine(await streamToString(worker.stdout)),
+ );
+ result.stderr = stripAnsi(
+ removeFinalNewLine(await streamToString(worker.stderr)),
+ );
resolve(result);
});
diff --git a/yarn.lock b/yarn.lock
index afd0ae322a49..510596a98230 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
languageName: node
linkType: hard
-"jest-light-runner@npm:0.6.0":
- version: 0.6.0
- resolution: "jest-light-runner@npm:0.6.0"
+"jest-light-runner@npm:0.7.0":
+ version: 0.7.0
+ resolution: "jest-light-runner@npm:0.7.0"
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5568,11 +5568,12 @@ __metadata:
jest-each: "npm:^30.0.0-alpha.1"
jest-mock: "npm:^30.0.0-alpha.1"
jest-snapshot: "npm:^30.0.0-alpha.1"
+ p-map: "npm:^7.0.3"
supports-color: "npm:^9.2.1"
- tinypool: "npm:^0.8.1"
+ tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/74103180fa2b997e46b7ba08e3afa6b673dd35d0c15fcecf825f9b7768c53c4f416bcdb261285b234375caaf45dd7cab397d5def7d95271c8d75ac59237fbf86
+ checksum: 10/d30bbb7822ba21906a47cb025e0198e74cd9063f5da862c1e2ec54353ada5fec172b0a30cb01074029183acc59d85fd102baa46c7cb90d22cf717d9b57dd045b
languageName: node
linkType: hard
@@ -6751,7 +6752,7 @@ __metadata:
languageName: node
linkType: hard
-"p-map@npm:^7.0.2":
+"p-map@npm:^7.0.2, p-map@npm:^7.0.3":
version: 7.0.3
resolution: "p-map@npm:7.0.3"
checksum: 10/2ef48ccfc6dd387253d71bf502604f7893ed62090b2c9d73387f10006c342606b05233da0e4f29388227b61eb5aeface6197e166520c465c234552eeab2fe633
@@ -7137,7 +7138,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.6.0"
+ jest-light-runner: "npm:0.7.0"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
@@ -8295,7 +8296,7 @@ __metadata:
languageName: node
linkType: hard
-"tinypool@npm:^0.8.1":
+"tinypool@npm:0.8.4":
version: 0.8.4
resolution: "tinypool@npm:0.8.4"
checksum: 10/7365944c2532f240111443e7012be31a634faf1a02db08a91db3aa07361c26a374d0be00a0f2ea052c4bee39c107ba67f1f814c108d9d51dfc725c559c1a9c03
| diff --git a/jest.config.js b/jest.config.js
index aaa654d68f0d..6adf230173f5 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -44,7 +44,7 @@ const config = {
"<rootDir>/tests/config/format-test-setup.js",
"<rootDir>/tests/integration/integration-test-setup.js",
],
- runner: "jest-light-runner",
+ runner: "./scripts/jest-light-process-runner.js",
snapshotSerializers: [
"jest-snapshot-serializer-raw",
"jest-snapshot-serializer-ansi",
diff --git a/package.json b/package.json
index 2692b6c67800..1037f78c8691 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"globals": "16.0.0",
"index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
- "jest-light-runner": "0.6.0",
+ "jest-light-runner": "0.7.0",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
@@ -160,7 +160,7 @@
},
"scripts": {
"prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1",
- "test": "cross-env PRETTIER_LEGACY_CLI=1 jest --runInBand",
"test:dev-package": "cross-env INSTALL_PACKAGE=1 yarn test",
"test:dist": "cross-env NODE_ENV=production yarn test",
"test:dist-standalone": "cross-env TEST_STANDALONE=1 yarn test:dist",
diff --git a/scripts/jest-light-process-runner.js b/scripts/jest-light-process-runner.js
new file mode 100644
index 000000000000..c82983974fef
--- /dev/null
+++ b/scripts/jest-light-process-runner.js
@@ -0,0 +1,3 @@
+import { createRunner } from "jest-light-runner";
+
+export default createRunner({ runtime: "child_process" });
diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js
index ec580dce41cc..429a8f7c569f 100644
--- a/tests/integration/run-cli.js
+++ b/tests/integration/run-cli.js
@@ -1,6 +1,7 @@
import path from "node:path";
import url from "node:url";
import { Worker } from "node:worker_threads";
+import stripAnsi from "strip-ansi";
const CLI_WORKER_FILE = new URL("./cli-worker.js", import.meta.url);
const INTEGRATION_TEST_DIRECTORY = url.fileURLToPath(
@@ -51,10 +52,6 @@ function runCliWorker(dir, args, options) {
],
stdout: true,
stderr: true,
- env: {
- ...process.env,
- },
workerData: {
dir,
options,
@@ -71,8 +68,12 @@ function runCliWorker(dir, args, options) {
return new Promise((resolve, reject) => {
worker.on("exit", async (code) => {
result.status = code;
- result.stdout = removeFinalNewLine(await streamToString(worker.stdout));
- result.stderr = removeFinalNewLine(await streamToString(worker.stderr));
+ result.stdout = stripAnsi(
+ removeFinalNewLine(await streamToString(worker.stdout)),
+ result.stderr = stripAnsi(
+ removeFinalNewLine(await streamToString(worker.stderr)),
resolve(result);
});
diff --git a/yarn.lock b/yarn.lock
index afd0ae322a49..510596a98230 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5558,9 +5558,9 @@ __metadata:
-"jest-light-runner@npm:0.6.0":
- version: 0.6.0
- resolution: "jest-light-runner@npm:0.6.0"
+"jest-light-runner@npm:0.7.0":
+ version: 0.7.0
dependencies:
"@jest/expect": "npm:^30.0.0-alpha.1"
"@jest/fake-timers": "npm:^30.0.0-alpha.1"
@@ -5568,11 +5568,12 @@ __metadata:
jest-each: "npm:^30.0.0-alpha.1"
jest-mock: "npm:^30.0.0-alpha.1"
jest-snapshot: "npm:^30.0.0-alpha.1"
+ p-map: "npm:^7.0.3"
supports-color: "npm:^9.2.1"
+ tinypool: "npm:0.8.4"
peerDependencies:
jest: ^27.5.0 || ^28.0.0 || ^29.0.0|| ^30.0.0-0
- checksum: 10/74103180fa2b997e46b7ba08e3afa6b673dd35d0c15fcecf825f9b7768c53c4f416bcdb261285b234375caaf45dd7cab397d5def7d95271c8d75ac59237fbf86
+ checksum: 10/d30bbb7822ba21906a47cb025e0198e74cd9063f5da862c1e2ec54353ada5fec172b0a30cb01074029183acc59d85fd102baa46c7cb90d22cf717d9b57dd045b
@@ -6751,7 +6752,7 @@ __metadata:
-"p-map@npm:^7.0.2":
+"p-map@npm:^7.0.2, p-map@npm:^7.0.3":
version: 7.0.3
resolution: "p-map@npm:7.0.3"
checksum: 10/2ef48ccfc6dd387253d71bf502604f7893ed62090b2c9d73387f10006c342606b05233da0e4f29388227b61eb5aeface6197e166520c465c234552eeab2fe633
@@ -7137,7 +7138,7 @@ __metadata:
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
jest-docblock: "npm:30.0.0-alpha.7"
- jest-light-runner: "npm:0.6.0"
+ jest-light-runner: "npm:0.7.0"
jest-snapshot-serializer-ansi: "npm:2.2.1"
jest-snapshot-serializer-raw: "npm:2.0.0"
jest-watch-typeahead: "npm:2.2.2"
@@ -8295,7 +8296,7 @@ __metadata:
-"tinypool@npm:^0.8.1":
version: 0.8.4
resolution: "tinypool@npm:0.8.4"
checksum: 10/7365944c2532f240111443e7012be31a634faf1a02db08a91db3aa07361c26a374d0be00a0f2ea052c4bee39c107ba67f1f814c108d9d51dfc725c559c1a9c03 | [
"+ \"test\": \"cross-env PRETTIER_LEGACY_CLI=1 jest\",",
"- NO_COLOR: \"1\",",
"+ resolution: \"jest-light-runner@npm:0.7.0\"",
"- tinypool: \"npm:^0.8.1\"",
"+\"tinypool@npm:0.8.4\":"
] | [
31,
62,
95,
105,
137
] | {
"additions": 22,
"author": "fisker",
"deletions": 17,
"html_url": "https://github.com/prettier/prettier/pull/17131",
"issue_id": 17131,
"merged_at": "2025-04-17T05:57:24Z",
"omission_probability": 0.1,
"pr_number": 17131,
"repo": "prettier/prettier",
"title": "[V4] Remove `--runInBand`",
"total_changes": 39
} |
172 | diff --git a/scripts/build/shims/string-replace-all.js b/scripts/build/shims/string-replace-all.js
deleted file mode 100644
index d6a2bc55d2ad..000000000000
--- a/scripts/build/shims/string-replace-all.js
+++ /dev/null
@@ -1,19 +0,0 @@
-const stringReplaceAll = (isOptionalObject, original, pattern, replacement) => {
- if (isOptionalObject && (original === undefined || original === null)) {
- return;
- }
-
- if (original.replaceAll) {
- return original.replaceAll(pattern, replacement);
- }
-
- // Simple detection to check if pattern is a `RegExp`
- if (pattern.global) {
- return original.replace(pattern, replacement);
- }
-
- // Doesn't work for substitutes, eg `.replaceAll("*", "\\$&")`
- return original.split(pattern).join(replacement);
-};
-
-export default stringReplaceAll;
diff --git a/scripts/build/transform/transforms/index.js b/scripts/build/transform/transforms/index.js
index 2126260487d8..2c35414dbec6 100644
--- a/scripts/build/transform/transforms/index.js
+++ b/scripts/build/transform/transforms/index.js
@@ -1,8 +1,6 @@
import transformArrayFindLast from "./transform-array-find-last.js";
import transformArrayFindLastIndex from "./transform-array-find-last-index.js";
-import transformObjectHasOwnCall from "./transform-object-has-own.js";
import transformRelativeIndexing from "./transform-relative-indexing.js";
-import transformStringReplaceAll from "./transform-string-replace-all.js";
// These transforms are like Babel and core-js
// Allow us to use JavaScript features in our source code that are not yet
@@ -12,10 +10,6 @@ export default [
// Node.js 18.0.0
transformArrayFindLast,
transformArrayFindLastIndex,
- // Node.js 16.9.0
- transformObjectHasOwnCall,
// Node.js 16.6.0
transformRelativeIndexing,
- // Node.js 15.0.0
- transformStringReplaceAll,
];
diff --git a/scripts/build/transform/transforms/transform-object-has-own.js b/scripts/build/transform/transforms/transform-object-has-own.js
deleted file mode 100644
index 0f4ca2ee914d..000000000000
--- a/scripts/build/transform/transforms/transform-object-has-own.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
-`Object.hasOwn(foo, "bar")` -> `Object.prototype.hasOwnProperty.call(foo, "bar")`
-*/
-
-const transformObjectHasOwnCall = {
- shouldSkip: (text) => !text.includes("Object.hasOwn("),
- /**
- * @param {import("@babel/types").Node} node
- * @returns {boolean}
- */
- test(node) {
- return (
- node.type === "CallExpression" &&
- !node.optional &&
- node.arguments.length === 2 &&
- node.arguments.every(({ type }) => type !== "SpreadElement") &&
- node.callee.type === "MemberExpression" &&
- !node.callee.optional &&
- !node.callee.computed &&
- node.callee.object.type === "Identifier" &&
- node.callee.object.name === "Object" &&
- node.callee.property.type === "Identifier" &&
- node.callee.property.name === "hasOwn"
- );
- },
- /**
- * @param {import("@babel/types").CallExpression} node
- * @returns {import("@babel/types").CallExpression}
- */
- transform(node) {
- node.callee = {
- type: "MemberExpression",
- object: {
- type: "MemberExpression",
- object: {
- type: "MemberExpression",
- object: { type: "Identifier", name: "Object" },
- property: { type: "Identifier", name: "prototype" },
- },
- property: { type: "Identifier", name: "hasOwnProperty" },
- },
- property: { type: "Identifier", name: "call" },
- };
- },
-};
-
-export default transformObjectHasOwnCall;
diff --git a/scripts/build/transform/transforms/transform-string-replace-all.js b/scripts/build/transform/transforms/transform-string-replace-all.js
deleted file mode 100644
index f3038fcde672..000000000000
--- a/scripts/build/transform/transforms/transform-string-replace-all.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import createMethodCallTransform from "./create-method-call-transform.js";
-
-const transformStringReplaceAll = createMethodCallTransform({
- methodName: "replaceAll",
- argumentsLength: 2,
- functionName: "__stringReplaceAll",
- functionImplementationUrl: new URL(
- "../../shims/string-replace-all.js",
- import.meta.url,
- ),
-});
-
-export default transformStringReplaceAll;
diff --git a/tests/unit/syntax-transform.js b/tests/unit/syntax-transform.js
index f6aec8015a17..173dd4419325 100644
--- a/tests/unit/syntax-transform.js
+++ b/tests/unit/syntax-transform.js
@@ -14,12 +14,6 @@ const transform = (code) =>
"<SHIMS>/",
);
-test("Object.hasOwn", () => {
- expect(transform("Object.hasOwn(foo, bar)")).toMatchInlineSnapshot(
- `"Object.prototype.hasOwnProperty.call(foo,bar)"`,
- );
-});
-
test(".at", () => {
expect(transform("foo.at(-1)")).toMatchInlineSnapshot(`
"import __at from "<SHIMS>/at.js";
@@ -49,14 +43,6 @@ test(".at", () => {
expect(transform("foo.at?.(-1)")).toMatchInlineSnapshot(`"foo.at?.(-1)"`);
});
-test("String#replaceAll", () => {
- expect(transform("foo.replaceAll('a', 'b')")).toMatchInlineSnapshot(`
- "import __stringReplaceAll from "<SHIMS>/string-replace-all.js";
-
- __stringReplaceAll(/* isOptionalObject */false,foo,'a','b')"
- `);
-});
-
test("Array#findLast", () => {
expect(transform("foo.findLast(callback)")).toMatchInlineSnapshot(`
"import __arrayFindLast from "<SHIMS>/array-find-last.js";
| diff --git a/scripts/build/shims/string-replace-all.js b/scripts/build/shims/string-replace-all.js
index d6a2bc55d2ad..000000000000
--- a/scripts/build/shims/string-replace-all.js
@@ -1,19 +0,0 @@
- return;
- if (original.replaceAll) {
- return original.replaceAll(pattern, replacement);
- if (pattern.global) {
- return original.replace(pattern, replacement);
- // Doesn't work for substitutes, eg `.replaceAll("*", "\\$&")`
- return original.split(pattern).join(replacement);
-export default stringReplaceAll;
diff --git a/scripts/build/transform/transforms/index.js b/scripts/build/transform/transforms/index.js
index 2126260487d8..2c35414dbec6 100644
--- a/scripts/build/transform/transforms/index.js
+++ b/scripts/build/transform/transforms/index.js
@@ -1,8 +1,6 @@
import transformArrayFindLast from "./transform-array-find-last.js";
import transformArrayFindLastIndex from "./transform-array-find-last-index.js";
import transformRelativeIndexing from "./transform-relative-indexing.js";
-import transformStringReplaceAll from "./transform-string-replace-all.js";
// These transforms are like Babel and core-js
// Allow us to use JavaScript features in our source code that are not yet
@@ -12,10 +10,6 @@ export default [
// Node.js 18.0.0
transformArrayFindLast,
transformArrayFindLastIndex,
- // Node.js 16.9.0
- transformObjectHasOwnCall,
// Node.js 16.6.0
transformRelativeIndexing,
- // Node.js 15.0.0
- transformStringReplaceAll,
];
diff --git a/scripts/build/transform/transforms/transform-object-has-own.js b/scripts/build/transform/transforms/transform-object-has-own.js
index 0f4ca2ee914d..000000000000
--- a/scripts/build/transform/transforms/transform-object-has-own.js
@@ -1,47 +0,0 @@
-/*
-*/
-const transformObjectHasOwnCall = {
- shouldSkip: (text) => !text.includes("Object.hasOwn("),
- * @param {import("@babel/types").Node} node
- * @returns {boolean}
- test(node) {
- return (
- node.type === "CallExpression" &&
- !node.optional &&
- node.arguments.length === 2 &&
- node.arguments.every(({ type }) => type !== "SpreadElement") &&
- node.callee.type === "MemberExpression" &&
- !node.callee.optional &&
- !node.callee.computed &&
- node.callee.object.type === "Identifier" &&
- node.callee.object.name === "Object" &&
- node.callee.property.type === "Identifier" &&
- node.callee.property.name === "hasOwn"
- );
- transform(node) {
- node.callee = {
- type: "MemberExpression",
- object: {
- object: {
- type: "MemberExpression",
- object: { type: "Identifier", name: "Object" },
- },
- property: { type: "Identifier", name: "hasOwnProperty" },
- },
- property: { type: "Identifier", name: "call" },
- };
diff --git a/scripts/build/transform/transforms/transform-string-replace-all.js b/scripts/build/transform/transforms/transform-string-replace-all.js
index f3038fcde672..000000000000
--- a/scripts/build/transform/transforms/transform-string-replace-all.js
@@ -1,13 +0,0 @@
-import createMethodCallTransform from "./create-method-call-transform.js";
-const transformStringReplaceAll = createMethodCallTransform({
- methodName: "replaceAll",
- functionName: "__stringReplaceAll",
- functionImplementationUrl: new URL(
- import.meta.url,
- ),
-export default transformStringReplaceAll;
diff --git a/tests/unit/syntax-transform.js b/tests/unit/syntax-transform.js
index f6aec8015a17..173dd4419325 100644
--- a/tests/unit/syntax-transform.js
+++ b/tests/unit/syntax-transform.js
@@ -14,12 +14,6 @@ const transform = (code) =>
"<SHIMS>/",
);
-test("Object.hasOwn", () => {
- expect(transform("Object.hasOwn(foo, bar)")).toMatchInlineSnapshot(
- `"Object.prototype.hasOwnProperty.call(foo,bar)"`,
- );
test(".at", () => {
expect(transform("foo.at(-1)")).toMatchInlineSnapshot(`
"import __at from "<SHIMS>/at.js";
@@ -49,14 +43,6 @@ test(".at", () => {
expect(transform("foo.at?.(-1)")).toMatchInlineSnapshot(`"foo.at?.(-1)"`);
});
-test("String#replaceAll", () => {
- expect(transform("foo.replaceAll('a', 'b')")).toMatchInlineSnapshot(`
- "import __stringReplaceAll from "<SHIMS>/string-replace-all.js";
- __stringReplaceAll(/* isOptionalObject */false,foo,'a','b')"
- `);
test("Array#findLast", () => {
expect(transform("foo.findLast(callback)")).toMatchInlineSnapshot(`
"import __arrayFindLast from "<SHIMS>/array-find-last.js"; | [
"-const stringReplaceAll = (isOptionalObject, original, pattern, replacement) => {",
"- if (isOptionalObject && (original === undefined || original === null)) {",
"- // Simple detection to check if pattern is a `RegExp`",
"-import transformObjectHasOwnCall from \"./transform-object-has-own.js\";",
"-`Object.hasOwn(foo, \"bar\")` -> `Object.prototype.hasOwnProperty.call(foo, \"bar\")`",
"- * @param {import(\"@babel/types\").CallExpression} node",
"- * @returns {import(\"@babel/types\").CallExpression}",
"- type: \"MemberExpression\",",
"- property: { type: \"Identifier\", name: \"prototype\" },",
"-export default transformObjectHasOwnCall;",
"- argumentsLength: 2,",
"- \"../../shims/string-replace-all.js\","
] | [
6,
7,
15,
32,
56,
81,
82,
88,
92,
101,
112,
115
] | {
"additions": 0,
"author": "fisker",
"deletions": 99,
"html_url": "https://github.com/prettier/prettier/pull/17355",
"issue_id": 17355,
"merged_at": "2025-04-16T05:40:17Z",
"omission_probability": 0.1,
"pr_number": 17355,
"repo": "prettier/prettier",
"title": "[V4] Build: remove transforming `Object.hasOwn()` and `String#replaceAll()`",
"total_changes": 99
} |
173 | diff --git a/jest.config.js b/jest.config.js
index acce11cf91e4..4376f74e1c5b 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -40,9 +40,15 @@ if (isProduction) {
);
}
-if (SKIP_TESTS_WITH_NEW_SYNTAX) {
+if (SKIP_TESTS_WITH_NEW_SYNTAX || process.versions.node.startsWith("16.")) {
+ // Uses import attributes
testPathIgnorePatterns.push(
"<rootDir>/tests/integration/__tests__/help-options.js",
+ );
+}
+
+if (SKIP_TESTS_WITH_NEW_SYNTAX) {
+ testPathIgnorePatterns.push(
"<rootDir>/tests/integration/__tests__/plugin-parsers.js",
"<rootDir>/tests/integration/__tests__/normalize-doc.js",
"<rootDir>/tests/integration/__tests__/doc-utils-clean-doc.js",
diff --git a/scripts/build/esbuild-plugins/evaluate.js b/scripts/build/esbuild-plugins/evaluate.js
index 3e7ee5d2b862..009bdd09027a 100644
--- a/scripts/build/esbuild-plugins/evaluate.js
+++ b/scripts/build/esbuild-plugins/evaluate.js
@@ -6,14 +6,11 @@ export default function esbuildPluginEvaluate() {
return {
name: "evaluate",
setup(build) {
- const { format } = build.initialOptions;
-
build.onLoad(
- { filter: /\.evaluate\.c?js$/, namespace: "file" },
+ { filter: /\.evaluate\.[cm]?js$/, namespace: "file" },
async ({ path }) => {
const module = await import(url.pathToFileURL(path));
const text = Object.entries(module)
- .filter(([specifier]) => specifier !== "module.exports")
.map(([specifier, value]) => {
const code =
value instanceof RegExp
@@ -21,18 +18,14 @@ export default function esbuildPluginEvaluate() {
: serialize(value, { space: 2 });
if (specifier === "default") {
- return format === "cjs"
- ? `module.exports = ${code};`
- : `export default ${code};`;
+ return `export default ${code};`;
}
if (!isValidIdentifier(specifier)) {
throw new Error(`${specifier} is not a valid specifier`);
}
- return format === "cjs"
- ? `exports.${specifier} = ${code};`
- : `export const ${specifier} = ${code};`;
+ return `export const ${specifier} = ${code};`;
})
.join("\n");
return { contents: text };
diff --git a/src/index.cjs b/src/index.cjs
index f84b6843b91b..b8e3befb0681 100644
--- a/src/index.cjs
+++ b/src/index.cjs
@@ -41,6 +41,7 @@ prettier.__debug = debugApis;
if (process.env.NODE_ENV === "production") {
prettier.util = require("./utils/public.js");
prettier.doc = require("./document/public.js");
+ prettier.version = require("./main/version.evaluate.js").default;
} else {
Object.defineProperties(prettier, {
util: {
@@ -70,7 +71,7 @@ if (process.env.NODE_ENV === "production") {
},
},
});
+ prettier.version = require("../package.json").version;
}
-prettier.version = require("./main/version.evaluate.cjs");
module.exports = prettier;
diff --git a/src/index.js b/src/index.js
index e5c25d368ed1..0a108d1eac8b 100644
--- a/src/index.js
+++ b/src/index.js
@@ -133,5 +133,5 @@ export {
resolveConfigFile,
};
export * as doc from "./document/public.js";
-export { default as version } from "./main/version.evaluate.cjs";
+export { default as version } from "./main/version.evaluate.js";
export * as util from "./utils/public.js";
diff --git a/src/main/version.evaluate.cjs b/src/main/version.evaluate.cjs
deleted file mode 100644
index 5850ec2db68d..000000000000
--- a/src/main/version.evaluate.cjs
+++ /dev/null
@@ -1,3 +0,0 @@
-"use strict";
-
-module.exports = require("../../package.json").version;
diff --git a/src/main/version.evaluate.js b/src/main/version.evaluate.js
new file mode 100644
index 000000000000..311cf0a1cf88
--- /dev/null
+++ b/src/main/version.evaluate.js
@@ -0,0 +1,3 @@
+import packageJson from "../../package.json" with { type: "json" };
+
+export default packageJson.version;
diff --git a/src/standalone.js b/src/standalone.js
index cf0635ab4f45..8277956eed58 100644
--- a/src/standalone.js
+++ b/src/standalone.js
@@ -52,5 +52,5 @@ export {
getSupportInfo,
};
export * as doc from "./document/public.js";
-export { default as version } from "./main/version.evaluate.cjs";
+export { default as version } from "./main/version.evaluate.js";
export * as util from "./utils/public.js";
| diff --git a/jest.config.js b/jest.config.js
index acce11cf91e4..4376f74e1c5b 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -40,9 +40,15 @@ if (isProduction) {
);
+if (SKIP_TESTS_WITH_NEW_SYNTAX || process.versions.node.startsWith("16.")) {
+ // Uses import attributes
testPathIgnorePatterns.push(
"<rootDir>/tests/integration/__tests__/help-options.js",
+ );
+}
+if (SKIP_TESTS_WITH_NEW_SYNTAX) {
+ testPathIgnorePatterns.push(
"<rootDir>/tests/integration/__tests__/plugin-parsers.js",
"<rootDir>/tests/integration/__tests__/normalize-doc.js",
"<rootDir>/tests/integration/__tests__/doc-utils-clean-doc.js",
diff --git a/scripts/build/esbuild-plugins/evaluate.js b/scripts/build/esbuild-plugins/evaluate.js
index 3e7ee5d2b862..009bdd09027a 100644
--- a/scripts/build/esbuild-plugins/evaluate.js
+++ b/scripts/build/esbuild-plugins/evaluate.js
@@ -6,14 +6,11 @@ export default function esbuildPluginEvaluate() {
return {
name: "evaluate",
setup(build) {
- const { format } = build.initialOptions;
build.onLoad(
- { filter: /\.evaluate\.c?js$/, namespace: "file" },
+ { filter: /\.evaluate\.[cm]?js$/, namespace: "file" },
async ({ path }) => {
const module = await import(url.pathToFileURL(path));
const text = Object.entries(module)
- .filter(([specifier]) => specifier !== "module.exports")
.map(([specifier, value]) => {
const code =
value instanceof RegExp
@@ -21,18 +18,14 @@ export default function esbuildPluginEvaluate() {
: serialize(value, { space: 2 });
if (specifier === "default") {
- return format === "cjs"
- ? `module.exports = ${code};`
- : `export default ${code};`;
+ return `export default ${code};`;
if (!isValidIdentifier(specifier)) {
throw new Error(`${specifier} is not a valid specifier`);
- return format === "cjs"
- ? `exports.${specifier} = ${code};`
- : `export const ${specifier} = ${code};`;
+ return `export const ${specifier} = ${code};`;
})
.join("\n");
return { contents: text };
diff --git a/src/index.cjs b/src/index.cjs
index f84b6843b91b..b8e3befb0681 100644
--- a/src/index.cjs
+++ b/src/index.cjs
@@ -41,6 +41,7 @@ prettier.__debug = debugApis;
if (process.env.NODE_ENV === "production") {
prettier.util = require("./utils/public.js");
prettier.doc = require("./document/public.js");
+ prettier.version = require("./main/version.evaluate.js").default;
} else {
Object.defineProperties(prettier, {
util: {
@@ -70,7 +71,7 @@ if (process.env.NODE_ENV === "production") {
},
},
});
+ prettier.version = require("../package.json").version;
-prettier.version = require("./main/version.evaluate.cjs");
module.exports = prettier;
diff --git a/src/index.js b/src/index.js
index e5c25d368ed1..0a108d1eac8b 100644
--- a/src/index.js
+++ b/src/index.js
@@ -133,5 +133,5 @@ export {
resolveConfigFile,
diff --git a/src/main/version.evaluate.cjs b/src/main/version.evaluate.cjs
deleted file mode 100644
index 5850ec2db68d..000000000000
--- a/src/main/version.evaluate.cjs
+++ /dev/null
@@ -1,3 +0,0 @@
-"use strict";
diff --git a/src/main/version.evaluate.js b/src/main/version.evaluate.js
new file mode 100644
index 000000000000..311cf0a1cf88
--- /dev/null
+++ b/src/main/version.evaluate.js
@@ -0,0 +1,3 @@
+import packageJson from "../../package.json" with { type: "json" };
+export default packageJson.version;
diff --git a/src/standalone.js b/src/standalone.js
index cf0635ab4f45..8277956eed58 100644
--- a/src/standalone.js
+++ b/src/standalone.js
@@ -52,5 +52,5 @@ export {
getSupportInfo, | [
"-if (SKIP_TESTS_WITH_NEW_SYNTAX) {",
"-module.exports = require(\"../../package.json\").version;"
] | [
8,
102
] | {
"additions": 17,
"author": "fisker",
"deletions": 17,
"html_url": "https://github.com/prettier/prettier/pull/17347",
"issue_id": 17347,
"merged_at": "2025-04-16T05:39:48Z",
"omission_probability": 0.1,
"pr_number": 17347,
"repo": "prettier/prettier",
"title": "Migrated version.evaluate.cjs to ES Module",
"total_changes": 34
} |
174 | diff --git a/changelog_unreleased/css/17362.md b/changelog_unreleased/css/17362.md
new file mode 100644
index 000000000000..d604c822a859
--- /dev/null
+++ b/changelog_unreleased/css/17362.md
@@ -0,0 +1,21 @@
+#### Support `@utility` directive for Tailwind (#17362 by @sosukesuzuki)
+
+This changes supports `@utility` directive for Tailwind CSS V4.
+
+<!-- prettier-ignore -->
+```css
+/* Input */
+@utility tab-* {
+ tab-size: --value(--tab-size-*);
+}
+
+/* Prettier stable */
+@utility tab-* {
+ tab-size: --value(--tab-size- *);
+}
+
+/* Prettier main */
+@utility tab-* {
+ tab-size: --value(--tab-size-*);
+}
+```
diff --git a/src/language-css/print/comma-separated-value-group.js b/src/language-css/print/comma-separated-value-group.js
index 8f6e2197ff7f..ab4cdce7f791 100644
--- a/src/language-css/print/comma-separated-value-group.js
+++ b/src/language-css/print/comma-separated-value-group.js
@@ -131,6 +131,17 @@ function printCommaSeparatedValueGroup(path, options, print) {
continue;
}
+ // Ignore Tailwind `@utility` directive ( https://tailwindcss.com/docs/adding-custom-styles#functional-utilities )
+ if (
+ insideAtRuleNode(path, "utility") &&
+ iNode.type === "value-word" &&
+ iNextNode &&
+ iNextNode.type === "value-operator" &&
+ iNextNode.value === "*"
+ ) {
+ continue;
+ }
+
// Ignore after latest node (i.e. before semicolon)
if (!iNextNode) {
continue;
diff --git a/tests/format/css/tailwind/__snapshots__/format.test.js.snap b/tests/format/css/tailwind/__snapshots__/format.test.js.snap
new file mode 100644
index 000000000000..03352385e364
--- /dev/null
+++ b/tests/format/css/tailwind/__snapshots__/format.test.js.snap
@@ -0,0 +1,103 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`utility-directive.css format 1`] = `
+====================================options=====================================
+parsers: ["css"]
+printWidth: 80
+ | printWidth
+=====================================input======================================
+@utility tab-* {
+ tab-size: --value(--tab-size-*);
+}
+
+@utility tab-* {
+ tab-size: --value(integer);
+}
+
+@utility tab-* {
+ tab-size: --value([integer]);
+ tab-size: --value(integer);
+ tab-size: --value(--tab-size-*);
+}
+
+@utility opacity-* {
+ opacity: --value([percentage]);
+ opacity: calc(--value(integer) * 1%);
+ opacity: --value(--opacity-*);
+}
+
+@utility tab-* {
+ tab-size: --value(--tab-size-*, integer, [integer]);
+}
+
+@utility opacity-* {
+ opacity: calc(--value(integer) * 1%);
+ opacity: --value(--opacity-*, [percentage]);
+}
+
+@utility inset-* {
+ inset: calc(--var(--spacing) * --value([percentage], [length]));
+}
+
+@utility -inset-* {
+ inset: calc(--var(--spacing) * --value([percentage], [length]) * -1);
+}
+
+@utility text-* {
+ font-size: --value(--font-size-*, [length]);
+ line-height: --modifier(--line-height-*, [length], [*]);
+}
+
+@utility aspect-* {
+ aspect-ratio: --value(--aspect-ratio-*, ratio, [ratio]);
+}
+
+=====================================output=====================================
+@utility tab-* {
+ tab-size: --value(--tab-size-*);
+}
+
+@utility tab-* {
+ tab-size: --value(integer);
+}
+
+@utility tab-* {
+ tab-size: --value([integer]);
+ tab-size: --value(integer);
+ tab-size: --value(--tab-size-*);
+}
+
+@utility opacity-* {
+ opacity: --value([percentage]);
+ opacity: calc(--value(integer) * 1%);
+ opacity: --value(--opacity-*);
+}
+
+@utility tab-* {
+ tab-size: --value(--tab-size-*, integer, [integer]);
+}
+
+@utility opacity-* {
+ opacity: calc(--value(integer) * 1%);
+ opacity: --value(--opacity-*, [percentage]);
+}
+
+@utility inset-* {
+ inset: calc(--var(--spacing) * --value([percentage], [length]));
+}
+
+@utility -inset-* {
+ inset: calc(--var(--spacing) * --value([percentage], [length]) * -1);
+}
+
+@utility text-* {
+ font-size: --value(--font-size-*, [length]);
+ line-height: --modifier(--line-height-*, [length], [*]);
+}
+
+@utility aspect-* {
+ aspect-ratio: --value(--aspect-ratio-*, ratio, [ratio]);
+}
+
+================================================================================
+`;
diff --git a/tests/format/css/tailwind/format.test.js b/tests/format/css/tailwind/format.test.js
new file mode 100644
index 000000000000..96617399ecbb
--- /dev/null
+++ b/tests/format/css/tailwind/format.test.js
@@ -0,0 +1 @@
+runFormatTest(import.meta, ["css"]);
diff --git a/tests/format/css/tailwind/utility-directive.css b/tests/format/css/tailwind/utility-directive.css
new file mode 100644
index 000000000000..2f267db043c6
--- /dev/null
+++ b/tests/format/css/tailwind/utility-directive.css
@@ -0,0 +1,45 @@
+@utility tab-* {
+ tab-size: --value(--tab-size-*);
+}
+
+@utility tab-* {
+ tab-size: --value(integer);
+}
+
+@utility tab-* {
+ tab-size: --value([integer]);
+ tab-size: --value(integer);
+ tab-size: --value(--tab-size-*);
+}
+
+@utility opacity-* {
+ opacity: --value([percentage]);
+ opacity: calc(--value(integer) * 1%);
+ opacity: --value(--opacity-*);
+}
+
+@utility tab-* {
+ tab-size: --value(--tab-size-*, integer, [integer]);
+}
+
+@utility opacity-* {
+ opacity: calc(--value(integer) * 1%);
+ opacity: --value(--opacity-*, [percentage]);
+}
+
+@utility inset-* {
+ inset: calc(--var(--spacing) * --value([percentage], [length]));
+}
+
+@utility -inset-* {
+ inset: calc(--var(--spacing) * --value([percentage], [length]) * -1);
+}
+
+@utility text-* {
+ font-size: --value(--font-size-*, [length]);
+ line-height: --modifier(--line-height-*, [length], [*]);
+}
+
+@utility aspect-* {
+ aspect-ratio: --value(--aspect-ratio-*, ratio, [ratio]);
+}
| diff --git a/changelog_unreleased/css/17362.md b/changelog_unreleased/css/17362.md
index 000000000000..d604c822a859
+++ b/changelog_unreleased/css/17362.md
@@ -0,0 +1,21 @@
+#### Support `@utility` directive for Tailwind (#17362 by @sosukesuzuki)
+This changes supports `@utility` directive for Tailwind CSS V4.
+<!-- prettier-ignore -->
+```css
+/* Input */
+/* Prettier stable */
+ tab-size: --value(--tab-size- *);
+/* Prettier main */
+```
diff --git a/src/language-css/print/comma-separated-value-group.js b/src/language-css/print/comma-separated-value-group.js
index 8f6e2197ff7f..ab4cdce7f791 100644
--- a/src/language-css/print/comma-separated-value-group.js
+++ b/src/language-css/print/comma-separated-value-group.js
@@ -131,6 +131,17 @@ function printCommaSeparatedValueGroup(path, options, print) {
}
+ // Ignore Tailwind `@utility` directive ( https://tailwindcss.com/docs/adding-custom-styles#functional-utilities )
+ if (
+ insideAtRuleNode(path, "utility") &&
+ iNode.type === "value-word" &&
+ iNextNode &&
+ iNextNode.type === "value-operator" &&
+ iNextNode.value === "*"
+ ) {
+ continue;
+ }
// Ignore after latest node (i.e. before semicolon)
if (!iNextNode) {
diff --git a/tests/format/css/tailwind/__snapshots__/format.test.js.snap b/tests/format/css/tailwind/__snapshots__/format.test.js.snap
index 000000000000..03352385e364
+++ b/tests/format/css/tailwind/__snapshots__/format.test.js.snap
@@ -0,0 +1,103 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+exports[`utility-directive.css format 1`] = `
+====================================options=====================================
+parsers: ["css"]
+printWidth: 80
+ | printWidth
+=====================================input======================================
+=====================================output=====================================
+================================================================================
+`;
diff --git a/tests/format/css/tailwind/format.test.js b/tests/format/css/tailwind/format.test.js
index 000000000000..96617399ecbb
+++ b/tests/format/css/tailwind/format.test.js
@@ -0,0 +1 @@
+runFormatTest(import.meta, ["css"]);
diff --git a/tests/format/css/tailwind/utility-directive.css b/tests/format/css/tailwind/utility-directive.css
index 000000000000..2f267db043c6
+++ b/tests/format/css/tailwind/utility-directive.css
@@ -0,0 +1,45 @@ | [] | [] | {
"additions": 181,
"author": "sosukesuzuki",
"deletions": 0,
"html_url": "https://github.com/prettier/prettier/pull/17362",
"issue_id": 17362,
"merged_at": "2025-04-16T02:55:21Z",
"omission_probability": 0.1,
"pr_number": 17362,
"repo": "prettier/prettier",
"title": "Support `@utility` directive for Tailwind",
"total_changes": 181
} |
175 | diff --git a/.github/workflows/prod-test.yml b/.github/workflows/prod-test.yml
index 4a12cf2d204a..146b2d17b181 100644
--- a/.github/workflows/prod-test.yml
+++ b/.github/workflows/prod-test.yml
@@ -58,7 +58,7 @@ jobs:
# Latest even version
- "22"
# Minimal version for production
- - "14"
+ - "18"
include:
- os: "ubuntu-latest"
# Pick a version that is fast (normally highest LTS version)
@@ -70,18 +70,6 @@ jobs:
node: "23"
- os: "ubuntu-latest"
node: "20"
- - os: "ubuntu-latest"
- node: "18"
- - os: "ubuntu-latest"
- node: "16"
- # Tests on Intel Mac x Node.js 14 ( https://github.com/prettier/prettier/issues/16248 )
- # We are disabling MacOS x Node.js 14 temporary ( https://github.com/prettier/prettier/issues/16964 )
- # - os: "macos-13"
- # node: "14"
- # setup-node does not support Node.js 14 x M1 Mac
- exclude:
- - os: "macos-latest"
- node: "14"
env:
FULL_TEST: ${{ matrix.FULL_TEST }}
name: ${{ matrix.FULL_TEST && '[Full Test] ' || '' }} Node.js ${{ matrix.node }} on ${{ startsWith(matrix.os, 'macos') && 'MacOS' || startsWith(matrix.os, 'windows') && 'Windows' || 'Linux' }}
@@ -91,29 +79,12 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- - name: Install yarn@3
- if: ${{ matrix.node == '14' || matrix.node == '16' }}
- run: |
- yarn set version 3
- cat .yarnrc.yml
-
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: "yarn"
- # `[email protected]` is the last version that supports Node.js v14
- - name: Install [email protected]
- if: ${{ matrix.node == '14' }}
- run: node ./scripts/prepare-nodejs-14-test.js
-
- - name: Install Dependencies(yarn@3,mutable)
- if: ${{ matrix.node == '14' || matrix.node == '16' }}
- env:
- YARN_ENABLE_IMMUTABLE_INSTALLS: false
- run: yarn install
-
- name: Install Dependencies
run: yarn install --immutable
@@ -152,7 +123,7 @@ jobs:
run: node -v | grep "v0.10.48" || exit 1
- name: Run CLI on Node.js v0.10.48
- run: node dist/prettier/bin/prettier.cjs --version 2>&1 >/dev/null | grep "prettier requires at least version 14 of Node, please upgrade" || exit 1
+ run: node dist/prettier/bin/prettier.cjs --version 2>&1 >/dev/null | grep "prettier requires at least version 18 of Node, please upgrade" || exit 1
preview:
if: github.event_name == 'pull_request' && github.repository == 'prettier/prettier'
diff --git a/changelog_unreleased/api/17354.md b/changelog_unreleased/api/17354.md
new file mode 100644
index 000000000000..f223d68b5c81
--- /dev/null
+++ b/changelog_unreleased/api/17354.md
@@ -0,0 +1,3 @@
+#### [BREAKING] Drop support for Node.js 14 and 16 (#17354 by @fisker)
+
+The minimal required Node.js version is v18
diff --git a/jest.config.js b/jest.config.js
index acce11cf91e4..aaa654d68f0d 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -10,7 +10,6 @@ const TEST_STANDALONE = Boolean(process.env.TEST_STANDALONE);
const INSTALL_PACKAGE = Boolean(process.env.INSTALL_PACKAGE);
// When debugging production test, this flag can skip installing package
const SKIP_PRODUCTION_INSTALL = Boolean(process.env.SKIP_PRODUCTION_INSTALL);
-const SKIP_TESTS_WITH_NEW_SYNTAX = process.versions.node.startsWith("14.");
let PRETTIER_DIR = isProduction
? path.join(PROJECT_ROOT, "dist/prettier")
@@ -40,18 +39,6 @@ if (isProduction) {
);
}
-if (SKIP_TESTS_WITH_NEW_SYNTAX) {
- testPathIgnorePatterns.push(
- "<rootDir>/tests/integration/__tests__/help-options.js",
- "<rootDir>/tests/integration/__tests__/plugin-parsers.js",
- "<rootDir>/tests/integration/__tests__/normalize-doc.js",
- "<rootDir>/tests/integration/__tests__/doc-utils-clean-doc.js",
- "<rootDir>/tests/integration/__tests__/config-invalid.js",
- // Fails on Node.js v14
- "<rootDir>/tests/dts/unit/run.js",
- );
-}
-
const config = {
setupFiles: [
"<rootDir>/tests/config/format-test-setup.js",
diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js
index 876dec206ab0..f83e7e413bfd 100644
--- a/scripts/build/build-javascript-module.js
+++ b/scripts/build/build-javascript-module.js
@@ -231,7 +231,7 @@ function getEsbuildOptions({ packageConfig, file, cliOptions }) {
external: ["pnpapi", ...(buildOptions.external ?? [])],
// Disable esbuild auto discover `tsconfig.json` file
tsconfigRaw: JSON.stringify({}),
- target: [...(buildOptions.target ?? ["node14"])],
+ target: [...(buildOptions.target ?? ["node18"])],
logLevel: "error",
format: file.output.format,
outfile: path.join(distDirectory, cliOptions.saveAs ?? file.output.file),
diff --git a/scripts/build/build-package-json.js b/scripts/build/build-package-json.js
index f9a245d1cea7..11c1be17e450 100644
--- a/scripts/build/build-package-json.js
+++ b/scripts/build/build-package-json.js
@@ -37,7 +37,7 @@ async function buildPackageJson({ packageConfig, file }) {
...packageJson.engines,
// https://github.com/prettier/prettier/pull/13118#discussion_r922708068
// Don't delete, comment out if we don't want override
- node: ">=14",
+ // node: ">=18",
},
type: "commonjs",
exports: {
diff --git a/scripts/prepare-nodejs-14-test.js b/scripts/prepare-nodejs-14-test.js
deleted file mode 100644
index 97b70a344164..000000000000
--- a/scripts/prepare-nodejs-14-test.js
+++ /dev/null
@@ -1,77 +0,0 @@
-import fs from "node:fs";
-
-const packageJsonFile = new URL("../package.json", import.meta.url);
-const packageJson = JSON.parse(fs.readFileSync(packageJsonFile));
-
-// Script to get dependencies
-// console.log(
-// Object.fromEntries(
-// Array.from(
-// fs
-// .readFileSync("./yarn.lock", "utf8")
-// .matchAll(/"(.*?)@npm:30\.0\.0-alpha\.3[",]/g),
-// (match) => match[1],
-// )
-// .sort()
-// .map((dependency) => [dependency, "30.0.0-alpha.2"]),
-// ),
-// );
-
-fs.writeFileSync(
- packageJsonFile,
- JSON.stringify(
- {
- ...packageJson,
- resolutions: {
- ...packageJson.resolutions,
- "@jest/console": "30.0.0-alpha.2",
- "@jest/core": "30.0.0-alpha.2",
- "@jest/environment": "30.0.0-alpha.2",
- "@jest/expect": "30.0.0-alpha.2",
- "@jest/expect-utils": "30.0.0-alpha.2",
- "@jest/fake-timers": "30.0.0-alpha.2",
- "@jest/globals": "30.0.0-alpha.2",
- "@jest/reporters": "30.0.0-alpha.2",
- "@jest/schemas": "30.0.0-alpha.2",
- "@jest/source-map": "30.0.0-alpha.2",
- "@jest/test-result": "30.0.0-alpha.2",
- "@jest/test-sequencer": "30.0.0-alpha.2",
- "@jest/transform": "30.0.0-alpha.2",
- // "@jest/types": "30.0.0-alpha.2",
- "babel-jest": "30.0.0-alpha.2",
- "babel-plugin-jest-hoist": "30.0.0-alpha.2",
- "babel-preset-jest": "30.0.0-alpha.2",
- "diff-sequences": "30.0.0-alpha.2",
- expect: "30.0.0-alpha.2",
- jest: "30.0.0-alpha.2",
- "jest-changed-files": "30.0.0-alpha.2",
- "jest-circus": "30.0.0-alpha.2",
- "jest-cli": "30.0.0-alpha.2",
- "jest-config": "30.0.0-alpha.2",
- "jest-diff": "30.0.0-alpha.2",
- // "jest-docblock": "30.0.0-alpha.2",
- "jest-each": "30.0.0-alpha.2",
- "jest-environment-node": "30.0.0-alpha.2",
- "jest-get-type": "30.0.0-alpha.2",
- "jest-haste-map": "30.0.0-alpha.2",
- "jest-leak-detector": "30.0.0-alpha.2",
- "jest-matcher-utils": "30.0.0-alpha.2",
- "jest-message-util": "30.0.0-alpha.2",
- "jest-mock": "30.0.0-alpha.2",
- "jest-regex-util": "30.0.0-alpha.2",
- "jest-resolve": "30.0.0-alpha.2",
- "jest-resolve-dependencies": "30.0.0-alpha.2",
- "jest-runner": "30.0.0-alpha.2",
- "jest-runtime": "30.0.0-alpha.2",
- "jest-snapshot": "30.0.0-alpha.2",
- "jest-util": "30.0.0-alpha.2",
- "jest-validate": "30.0.0-alpha.2",
- "jest-watcher": "30.0.0-alpha.2",
- "jest-worker": "30.0.0-alpha.2",
- "pretty-format": "30.0.0-alpha.2",
- },
- },
- undefined,
- 2,
- ),
-);
| diff --git a/.github/workflows/prod-test.yml b/.github/workflows/prod-test.yml
index 4a12cf2d204a..146b2d17b181 100644
--- a/.github/workflows/prod-test.yml
+++ b/.github/workflows/prod-test.yml
@@ -58,7 +58,7 @@ jobs:
# Latest even version
- "22"
# Minimal version for production
+ - "18"
include:
# Pick a version that is fast (normally highest LTS version)
@@ -70,18 +70,6 @@ jobs:
node: "23"
node: "20"
- node: "18"
- # Tests on Intel Mac x Node.js 14 ( https://github.com/prettier/prettier/issues/16248 )
- # We are disabling MacOS x Node.js 14 temporary ( https://github.com/prettier/prettier/issues/16964 )
- # - os: "macos-13"
- # setup-node does not support Node.js 14 x M1 Mac
- exclude:
- - os: "macos-latest"
- node: "14"
env:
FULL_TEST: ${{ matrix.FULL_TEST }}
name: ${{ matrix.FULL_TEST && '[Full Test] ' || '' }} Node.js ${{ matrix.node }} on ${{ startsWith(matrix.os, 'macos') && 'MacOS' || startsWith(matrix.os, 'windows') && 'Windows' || 'Linux' }}
@@ -91,29 +79,12 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- - name: Install yarn@3
- run: |
- yarn set version 3
- cat .yarnrc.yml
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: "yarn"
- # `[email protected]` is the last version that supports Node.js v14
- - name: Install [email protected]
- if: ${{ matrix.node == '14' }}
- run: node ./scripts/prepare-nodejs-14-test.js
- - name: Install Dependencies(yarn@3,mutable)
- YARN_ENABLE_IMMUTABLE_INSTALLS: false
- run: yarn install
- name: Install Dependencies
run: yarn install --immutable
@@ -152,7 +123,7 @@ jobs:
run: node -v | grep "v0.10.48" || exit 1
- name: Run CLI on Node.js v0.10.48
- run: node dist/prettier/bin/prettier.cjs --version 2>&1 >/dev/null | grep "prettier requires at least version 14 of Node, please upgrade" || exit 1
+ run: node dist/prettier/bin/prettier.cjs --version 2>&1 >/dev/null | grep "prettier requires at least version 18 of Node, please upgrade" || exit 1
preview:
if: github.event_name == 'pull_request' && github.repository == 'prettier/prettier'
diff --git a/changelog_unreleased/api/17354.md b/changelog_unreleased/api/17354.md
new file mode 100644
index 000000000000..f223d68b5c81
--- /dev/null
+++ b/changelog_unreleased/api/17354.md
@@ -0,0 +1,3 @@
+#### [BREAKING] Drop support for Node.js 14 and 16 (#17354 by @fisker)
+
+The minimal required Node.js version is v18
diff --git a/jest.config.js b/jest.config.js
index acce11cf91e4..aaa654d68f0d 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -10,7 +10,6 @@ const TEST_STANDALONE = Boolean(process.env.TEST_STANDALONE);
const INSTALL_PACKAGE = Boolean(process.env.INSTALL_PACKAGE);
// When debugging production test, this flag can skip installing package
const SKIP_PRODUCTION_INSTALL = Boolean(process.env.SKIP_PRODUCTION_INSTALL);
-const SKIP_TESTS_WITH_NEW_SYNTAX = process.versions.node.startsWith("14.");
let PRETTIER_DIR = isProduction
? path.join(PROJECT_ROOT, "dist/prettier")
@@ -40,18 +39,6 @@ if (isProduction) {
);
}
- testPathIgnorePatterns.push(
- "<rootDir>/tests/integration/__tests__/help-options.js",
- "<rootDir>/tests/integration/__tests__/plugin-parsers.js",
- "<rootDir>/tests/integration/__tests__/normalize-doc.js",
- "<rootDir>/tests/integration/__tests__/doc-utils-clean-doc.js",
- "<rootDir>/tests/integration/__tests__/config-invalid.js",
- // Fails on Node.js v14
- "<rootDir>/tests/dts/unit/run.js",
-}
const config = {
setupFiles: [
"<rootDir>/tests/config/format-test-setup.js",
diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js
index 876dec206ab0..f83e7e413bfd 100644
--- a/scripts/build/build-javascript-module.js
+++ b/scripts/build/build-javascript-module.js
@@ -231,7 +231,7 @@ function getEsbuildOptions({ packageConfig, file, cliOptions }) {
external: ["pnpapi", ...(buildOptions.external ?? [])],
// Disable esbuild auto discover `tsconfig.json` file
tsconfigRaw: JSON.stringify({}),
+ target: [...(buildOptions.target ?? ["node18"])],
logLevel: "error",
format: file.output.format,
outfile: path.join(distDirectory, cliOptions.saveAs ?? file.output.file),
diff --git a/scripts/build/build-package-json.js b/scripts/build/build-package-json.js
index f9a245d1cea7..11c1be17e450 100644
--- a/scripts/build/build-package-json.js
+++ b/scripts/build/build-package-json.js
@@ -37,7 +37,7 @@ async function buildPackageJson({ packageConfig, file }) {
...packageJson.engines,
// https://github.com/prettier/prettier/pull/13118#discussion_r922708068
// Don't delete, comment out if we don't want override
- node: ">=14",
+ // node: ">=18",
},
type: "commonjs",
exports: {
diff --git a/scripts/prepare-nodejs-14-test.js b/scripts/prepare-nodejs-14-test.js
deleted file mode 100644
index 97b70a344164..000000000000
--- a/scripts/prepare-nodejs-14-test.js
+++ /dev/null
@@ -1,77 +0,0 @@
-import fs from "node:fs";
-const packageJsonFile = new URL("../package.json", import.meta.url);
-const packageJson = JSON.parse(fs.readFileSync(packageJsonFile));
-// Script to get dependencies
-// console.log(
-// Object.fromEntries(
-// Array.from(
-// fs
-// .readFileSync("./yarn.lock", "utf8")
-// .matchAll(/"(.*?)@npm:30\.0\.0-alpha\.3[",]/g),
-// (match) => match[1],
-// )
-// .sort()
-// .map((dependency) => [dependency, "30.0.0-alpha.2"]),
-// ),
-// );
-fs.writeFileSync(
- packageJsonFile,
- JSON.stringify(
- {
- ...packageJson,
- resolutions: {
- "@jest/console": "30.0.0-alpha.2",
- "@jest/core": "30.0.0-alpha.2",
- "@jest/environment": "30.0.0-alpha.2",
- "@jest/expect": "30.0.0-alpha.2",
- "@jest/expect-utils": "30.0.0-alpha.2",
- "@jest/fake-timers": "30.0.0-alpha.2",
- "@jest/globals": "30.0.0-alpha.2",
- "@jest/reporters": "30.0.0-alpha.2",
- "@jest/schemas": "30.0.0-alpha.2",
- "@jest/test-result": "30.0.0-alpha.2",
- "@jest/test-sequencer": "30.0.0-alpha.2",
- "@jest/transform": "30.0.0-alpha.2",
- // "@jest/types": "30.0.0-alpha.2",
- "babel-jest": "30.0.0-alpha.2",
- "babel-plugin-jest-hoist": "30.0.0-alpha.2",
- "babel-preset-jest": "30.0.0-alpha.2",
- "diff-sequences": "30.0.0-alpha.2",
- expect: "30.0.0-alpha.2",
- jest: "30.0.0-alpha.2",
- "jest-changed-files": "30.0.0-alpha.2",
- "jest-circus": "30.0.0-alpha.2",
- "jest-config": "30.0.0-alpha.2",
- // "jest-docblock": "30.0.0-alpha.2",
- "jest-each": "30.0.0-alpha.2",
- "jest-environment-node": "30.0.0-alpha.2",
- "jest-get-type": "30.0.0-alpha.2",
- "jest-haste-map": "30.0.0-alpha.2",
- "jest-leak-detector": "30.0.0-alpha.2",
- "jest-matcher-utils": "30.0.0-alpha.2",
- "jest-mock": "30.0.0-alpha.2",
- "jest-regex-util": "30.0.0-alpha.2",
- "jest-resolve": "30.0.0-alpha.2",
- "jest-resolve-dependencies": "30.0.0-alpha.2",
- "jest-runner": "30.0.0-alpha.2",
- "jest-runtime": "30.0.0-alpha.2",
- "jest-snapshot": "30.0.0-alpha.2",
- "jest-util": "30.0.0-alpha.2",
- "jest-validate": "30.0.0-alpha.2",
- "jest-watcher": "30.0.0-alpha.2",
- "jest-worker": "30.0.0-alpha.2",
- "pretty-format": "30.0.0-alpha.2",
- },
- },
- undefined,
- 2,
- ),
-); | [
"- - \"14\"",
"- node: \"16\"",
"- # node: \"14\"",
"- env:",
"-if (SKIP_TESTS_WITH_NEW_SYNTAX) {",
"- );",
"- target: [...(buildOptions.target ?? [\"node14\"])],",
"- ...packageJson.resolutions,",
"- \"@jest/source-map\": \"30.0.0-alpha.2\",",
"- \"jest-cli\": \"30.0.0-alpha.2\",",
"- \"jest-diff\": \"30.0.0-alpha.2\",",
"- \"jest-message-util\": \"30.0.0-alpha.2\","
] | [
8,
20,
24,
55,
96,
105,
119,
168,
178,
191,
193,
201
] | {
"additions": 7,
"author": "fisker",
"deletions": 123,
"html_url": "https://github.com/prettier/prettier/pull/17354",
"issue_id": 17354,
"merged_at": "2025-04-15T05:36:29Z",
"omission_probability": 0.1,
"pr_number": 17354,
"repo": "prettier/prettier",
"title": "[V4] Bump minimal required Node.js version to 18",
"total_changes": 130
} |
176 | diff --git a/package.json b/package.json
index fbb39cc10797..81827f333fac 100644
--- a/package.json
+++ b/package.json
@@ -37,8 +37,8 @@
"@glimmer/syntax": "0.94.9",
"@prettier/cli": "0.7.1",
"@prettier/parse-srcset": "3.1.0",
- "@typescript-eslint/typescript-estree": "8.29.0",
- "@typescript-eslint/visitor-keys": "8.29.0",
+ "@typescript-eslint/typescript-estree": "8.30.1",
+ "@typescript-eslint/visitor-keys": "8.30.1",
"acorn": "8.14.1",
"acorn-jsx": "5.3.2",
"angular-estree-parser": "11.1.1",
@@ -112,7 +112,8 @@
"@eslint/js": "9.24.0",
"@stylistic/eslint-plugin-js": "4.2.0",
"@types/estree": "1.0.7",
- "@typescript-eslint/eslint-plugin": "8.29.0",
+ "@typescript-eslint/eslint-plugin": "8.30.1",
+ "@typescript-eslint/parser": "8.30.1",
"browserslist": "4.24.4",
"browserslist-to-esbuild": "2.1.1",
"c8": "10.1.3",
diff --git a/yarn.lock b/yarn.lock
index 250aff5f2a05..6b73851e25f8 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2211,15 +2211,15 @@ __metadata:
languageName: node
linkType: hard
-"@typescript-eslint/eslint-plugin@npm:8.29.0":
- version: 8.29.0
- resolution: "@typescript-eslint/eslint-plugin@npm:8.29.0"
+"@typescript-eslint/eslint-plugin@npm:8.30.1":
+ version: 8.30.1
+ resolution: "@typescript-eslint/eslint-plugin@npm:8.30.1"
dependencies:
"@eslint-community/regexpp": "npm:^4.10.0"
- "@typescript-eslint/scope-manager": "npm:8.29.0"
- "@typescript-eslint/type-utils": "npm:8.29.0"
- "@typescript-eslint/utils": "npm:8.29.0"
- "@typescript-eslint/visitor-keys": "npm:8.29.0"
+ "@typescript-eslint/scope-manager": "npm:8.30.1"
+ "@typescript-eslint/type-utils": "npm:8.30.1"
+ "@typescript-eslint/utils": "npm:8.30.1"
+ "@typescript-eslint/visitor-keys": "npm:8.30.1"
graphemer: "npm:^1.4.0"
ignore: "npm:^5.3.1"
natural-compare: "npm:^1.4.0"
@@ -2228,48 +2228,64 @@ __metadata:
"@typescript-eslint/parser": ^8.0.0 || ^8.0.0-alpha.0
eslint: ^8.57.0 || ^9.0.0
typescript: ">=4.8.4 <5.9.0"
- checksum: 10/1df4b43c209e40a00ec77e572b575760a9ac93967b6ebcc13f36587bf2881fc891c158f62cf25e8c2b8ca1ecd05b3eb583b30869ba6c2fa558435f0574773df8
+ checksum: 10/769b0365c1eda5d15ecb24cd297ca60d264001d46e14f42fae30f6f519610414726885a8d5cf57ef5a01484f92166104a74fb2ca2fd2af28f11cab149b6de591
languageName: node
linkType: hard
-"@typescript-eslint/scope-manager@npm:8.29.0, @typescript-eslint/scope-manager@npm:^8.29.0":
- version: 8.29.0
- resolution: "@typescript-eslint/scope-manager@npm:8.29.0"
+"@typescript-eslint/parser@npm:8.30.1":
+ version: 8.30.1
+ resolution: "@typescript-eslint/parser@npm:8.30.1"
dependencies:
- "@typescript-eslint/types": "npm:8.29.0"
- "@typescript-eslint/visitor-keys": "npm:8.29.0"
- checksum: 10/23ce9962d57607f91a8a4a9bc43e64bd91cd933b53e61765924704614e52f39e8ccb28276b60b7472fb6dffe52fa681f114b73e4561fb4dcb74910a4e6a3629f
+ "@typescript-eslint/scope-manager": "npm:8.30.1"
+ "@typescript-eslint/types": "npm:8.30.1"
+ "@typescript-eslint/typescript-estree": "npm:8.30.1"
+ "@typescript-eslint/visitor-keys": "npm:8.30.1"
+ debug: "npm:^4.3.4"
+ peerDependencies:
+ eslint: ^8.57.0 || ^9.0.0
+ typescript: ">=4.8.4 <5.9.0"
+ checksum: 10/ffff7bfa7e6b0233feb2d2c9bc27e0fd16faa50a00e9853efcc59de312420ef5a54b94833e80727bc5c966c1b211d70601c2337e33cc5610fa2f28d858642f5b
+ languageName: node
+ linkType: hard
+
+"@typescript-eslint/scope-manager@npm:8.30.1, @typescript-eslint/scope-manager@npm:^8.29.0":
+ version: 8.30.1
+ resolution: "@typescript-eslint/scope-manager@npm:8.30.1"
+ dependencies:
+ "@typescript-eslint/types": "npm:8.30.1"
+ "@typescript-eslint/visitor-keys": "npm:8.30.1"
+ checksum: 10/ecae69888a06126d57f3ac2db9935199b708406e8cd84e0918dd8302f31771145d62b52bf3c454be43c5aa4f93685d3f8c15b118d0de1c0323e02113c127aa66
languageName: node
linkType: hard
-"@typescript-eslint/type-utils@npm:8.29.0, @typescript-eslint/type-utils@npm:^8.0.0, @typescript-eslint/type-utils@npm:^8.29.0":
- version: 8.29.0
- resolution: "@typescript-eslint/type-utils@npm:8.29.0"
+"@typescript-eslint/type-utils@npm:8.30.1, @typescript-eslint/type-utils@npm:^8.0.0, @typescript-eslint/type-utils@npm:^8.29.0":
+ version: 8.30.1
+ resolution: "@typescript-eslint/type-utils@npm:8.30.1"
dependencies:
- "@typescript-eslint/typescript-estree": "npm:8.29.0"
- "@typescript-eslint/utils": "npm:8.29.0"
+ "@typescript-eslint/typescript-estree": "npm:8.30.1"
+ "@typescript-eslint/utils": "npm:8.30.1"
debug: "npm:^4.3.4"
ts-api-utils: "npm:^2.0.1"
peerDependencies:
eslint: ^8.57.0 || ^9.0.0
typescript: ">=4.8.4 <5.9.0"
- checksum: 10/3b18caf6d3d16461d462b8960e1fa7fdb94f0eb2aa8afb9c95e2e458af32ffc82b14f1d26bb635b5e751bd0a7ff5c10fa1754377fff0dea760d1a96848705f88
+ checksum: 10/c7a285bae7806a1e4aa9840feb727fe47f5de4ef3d68ecd1bbebc593a72ec08df17953098d71dc83a6936a42d5a44bcd4a49e6f067ec0947293795b0a389498f
languageName: node
linkType: hard
-"@typescript-eslint/types@npm:8.29.0, @typescript-eslint/types@npm:^8.29.0":
- version: 8.29.0
- resolution: "@typescript-eslint/types@npm:8.29.0"
- checksum: 10/d65b9f2f6d87a3744788b09d9112c4a0298f1215138d8677240aae3bfa37ddc24a59315536cd9aab63c7608909ae2c5f436924c889b98986b78003b6028b5c35
+"@typescript-eslint/types@npm:8.30.1, @typescript-eslint/types@npm:^8.29.0":
+ version: 8.30.1
+ resolution: "@typescript-eslint/types@npm:8.30.1"
+ checksum: 10/342ec75ba2c596ffaa93612c6c6afd2b0a05c346bdfa73ac208b49f1969b48a3f739f306431f9a10cf34e99e8585ca924fdde7f9508dd7869142b25f399d6bd6
languageName: node
linkType: hard
-"@typescript-eslint/typescript-estree@npm:8.29.0, @typescript-eslint/typescript-estree@npm:^8.29.0":
- version: 8.29.0
- resolution: "@typescript-eslint/typescript-estree@npm:8.29.0"
+"@typescript-eslint/typescript-estree@npm:8.30.1, @typescript-eslint/typescript-estree@npm:^8.29.0":
+ version: 8.30.1
+ resolution: "@typescript-eslint/typescript-estree@npm:8.30.1"
dependencies:
- "@typescript-eslint/types": "npm:8.29.0"
- "@typescript-eslint/visitor-keys": "npm:8.29.0"
+ "@typescript-eslint/types": "npm:8.30.1"
+ "@typescript-eslint/visitor-keys": "npm:8.30.1"
debug: "npm:^4.3.4"
fast-glob: "npm:^3.3.2"
is-glob: "npm:^4.0.3"
@@ -2278,32 +2294,32 @@ __metadata:
ts-api-utils: "npm:^2.0.1"
peerDependencies:
typescript: ">=4.8.4 <5.9.0"
- checksum: 10/276e6ea97857ef0fd940578d4b8f1677fd68d2bb62603c85d7aa97fcf86c1f66c5da962393254b605c7025f0cda74395904053891088cbe405b899afc1180e9c
+ checksum: 10/60c307fbb8ec86d28e4b2237b624427b7aee737bced82e5f94acc84229eae907e7742ccf0c9c0825326b3ccb9f72b14075893d90e06c28f8ce2fd04502c0b410
languageName: node
linkType: hard
-"@typescript-eslint/utils@npm:8.29.0, @typescript-eslint/utils@npm:^6.0.0 || ^7.0.0 || ^8.0.0, @typescript-eslint/utils@npm:^8.29.0":
- version: 8.29.0
- resolution: "@typescript-eslint/utils@npm:8.29.0"
+"@typescript-eslint/utils@npm:8.30.1, @typescript-eslint/utils@npm:^6.0.0 || ^7.0.0 || ^8.0.0, @typescript-eslint/utils@npm:^8.29.0":
+ version: 8.30.1
+ resolution: "@typescript-eslint/utils@npm:8.30.1"
dependencies:
"@eslint-community/eslint-utils": "npm:^4.4.0"
- "@typescript-eslint/scope-manager": "npm:8.29.0"
- "@typescript-eslint/types": "npm:8.29.0"
- "@typescript-eslint/typescript-estree": "npm:8.29.0"
+ "@typescript-eslint/scope-manager": "npm:8.30.1"
+ "@typescript-eslint/types": "npm:8.30.1"
+ "@typescript-eslint/typescript-estree": "npm:8.30.1"
peerDependencies:
eslint: ^8.57.0 || ^9.0.0
typescript: ">=4.8.4 <5.9.0"
- checksum: 10/1fd17a28b8b57fc73c0455dea43a8185d3a4421f4a21ece01009b5e6a2974c8d4113f90d27993f668fa97077891b4464588d380c25116d351eb12ad7ef0d468d
+ checksum: 10/97d27d2f0bce6f60a1857d511dba401f076766477a2896405aca52e860f9c5460111299f6e17642e18e578be1dbf850a0b1202ba61aa65d6a52646429ff9c99c
languageName: node
linkType: hard
-"@typescript-eslint/visitor-keys@npm:8.29.0":
- version: 8.29.0
- resolution: "@typescript-eslint/visitor-keys@npm:8.29.0"
+"@typescript-eslint/visitor-keys@npm:8.30.1":
+ version: 8.30.1
+ resolution: "@typescript-eslint/visitor-keys@npm:8.30.1"
dependencies:
- "@typescript-eslint/types": "npm:8.29.0"
+ "@typescript-eslint/types": "npm:8.30.1"
eslint-visitor-keys: "npm:^4.2.0"
- checksum: 10/02e0e86ab112849a31b7d06c767be0ca7802385bf953d3b75f4ba6d06741d9492773325bc69d4c2a1c191b08f1c4c4b33f8e062d6d5d9f0f4f78f1b8b3cc2d41
+ checksum: 10/0c08169123ebca4ab04464486a7f41093ba77e75fb088e2c8af9f36bb4c0f785d4e82940f6b62e47457d4758fa57a53423db4226250d6eb284e75a3f96f03f2b
languageName: node
linkType: hard
@@ -7048,9 +7064,10 @@ __metadata:
"@prettier/parse-srcset": "npm:3.1.0"
"@stylistic/eslint-plugin-js": "npm:4.2.0"
"@types/estree": "npm:1.0.7"
- "@typescript-eslint/eslint-plugin": "npm:8.29.0"
- "@typescript-eslint/typescript-estree": "npm:8.29.0"
- "@typescript-eslint/visitor-keys": "npm:8.29.0"
+ "@typescript-eslint/eslint-plugin": "npm:8.30.1"
+ "@typescript-eslint/parser": "npm:8.30.1"
+ "@typescript-eslint/typescript-estree": "npm:8.30.1"
+ "@typescript-eslint/visitor-keys": "npm:8.30.1"
acorn: "npm:8.14.1"
acorn-jsx: "npm:5.3.2"
angular-estree-parser: "npm:11.1.1"
| diff --git a/package.json b/package.json
index fbb39cc10797..81827f333fac 100644
--- a/package.json
+++ b/package.json
@@ -37,8 +37,8 @@
"@glimmer/syntax": "0.94.9",
"@prettier/cli": "0.7.1",
"@prettier/parse-srcset": "3.1.0",
- "@typescript-eslint/typescript-estree": "8.29.0",
- "@typescript-eslint/visitor-keys": "8.29.0",
+ "@typescript-eslint/typescript-estree": "8.30.1",
+ "@typescript-eslint/visitor-keys": "8.30.1",
"acorn": "8.14.1",
"acorn-jsx": "5.3.2",
"angular-estree-parser": "11.1.1",
@@ -112,7 +112,8 @@
"@eslint/js": "9.24.0",
"@stylistic/eslint-plugin-js": "4.2.0",
"@types/estree": "1.0.7",
- "@typescript-eslint/eslint-plugin": "8.29.0",
+ "@typescript-eslint/eslint-plugin": "8.30.1",
+ "@typescript-eslint/parser": "8.30.1",
"browserslist": "4.24.4",
"browserslist-to-esbuild": "2.1.1",
"c8": "10.1.3",
diff --git a/yarn.lock b/yarn.lock
index 250aff5f2a05..6b73851e25f8 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2211,15 +2211,15 @@ __metadata:
-"@typescript-eslint/eslint-plugin@npm:8.29.0":
- resolution: "@typescript-eslint/eslint-plugin@npm:8.29.0"
+"@typescript-eslint/eslint-plugin@npm:8.30.1":
+ resolution: "@typescript-eslint/eslint-plugin@npm:8.30.1"
"@eslint-community/regexpp": "npm:^4.10.0"
- "@typescript-eslint/type-utils": "npm:8.29.0"
+ "@typescript-eslint/type-utils": "npm:8.30.1"
graphemer: "npm:^1.4.0"
ignore: "npm:^5.3.1"
natural-compare: "npm:^1.4.0"
@@ -2228,48 +2228,64 @@ __metadata:
"@typescript-eslint/parser": ^8.0.0 || ^8.0.0-alpha.0
- checksum: 10/1df4b43c209e40a00ec77e572b575760a9ac93967b6ebcc13f36587bf2881fc891c158f62cf25e8c2b8ca1ecd05b3eb583b30869ba6c2fa558435f0574773df8
+ checksum: 10/769b0365c1eda5d15ecb24cd297ca60d264001d46e14f42fae30f6f519610414726885a8d5cf57ef5a01484f92166104a74fb2ca2fd2af28f11cab149b6de591
-"@typescript-eslint/scope-manager@npm:8.29.0, @typescript-eslint/scope-manager@npm:^8.29.0":
- resolution: "@typescript-eslint/scope-manager@npm:8.29.0"
+"@typescript-eslint/parser@npm:8.30.1":
+ resolution: "@typescript-eslint/parser@npm:8.30.1"
- checksum: 10/23ce9962d57607f91a8a4a9bc43e64bd91cd933b53e61765924704614e52f39e8ccb28276b60b7472fb6dffe52fa681f114b73e4561fb4dcb74910a4e6a3629f
+ peerDependencies:
+ eslint: ^8.57.0 || ^9.0.0
+ typescript: ">=4.8.4 <5.9.0"
+ checksum: 10/ffff7bfa7e6b0233feb2d2c9bc27e0fd16faa50a00e9853efcc59de312420ef5a54b94833e80727bc5c966c1b211d70601c2337e33cc5610fa2f28d858642f5b
+ languageName: node
+ linkType: hard
+
+"@typescript-eslint/scope-manager@npm:8.30.1, @typescript-eslint/scope-manager@npm:^8.29.0":
+ resolution: "@typescript-eslint/scope-manager@npm:8.30.1"
+ dependencies:
-"@typescript-eslint/type-utils@npm:8.29.0, @typescript-eslint/type-utils@npm:^8.0.0, @typescript-eslint/type-utils@npm:^8.29.0":
+"@typescript-eslint/type-utils@npm:8.30.1, @typescript-eslint/type-utils@npm:^8.0.0, @typescript-eslint/type-utils@npm:^8.29.0":
+ resolution: "@typescript-eslint/type-utils@npm:8.30.1"
- checksum: 10/3b18caf6d3d16461d462b8960e1fa7fdb94f0eb2aa8afb9c95e2e458af32ffc82b14f1d26bb635b5e751bd0a7ff5c10fa1754377fff0dea760d1a96848705f88
+ checksum: 10/c7a285bae7806a1e4aa9840feb727fe47f5de4ef3d68ecd1bbebc593a72ec08df17953098d71dc83a6936a42d5a44bcd4a49e6f067ec0947293795b0a389498f
-"@typescript-eslint/types@npm:8.29.0, @typescript-eslint/types@npm:^8.29.0":
- resolution: "@typescript-eslint/types@npm:8.29.0"
+"@typescript-eslint/types@npm:8.30.1, @typescript-eslint/types@npm:^8.29.0":
+ resolution: "@typescript-eslint/types@npm:8.30.1"
+ checksum: 10/342ec75ba2c596ffaa93612c6c6afd2b0a05c346bdfa73ac208b49f1969b48a3f739f306431f9a10cf34e99e8585ca924fdde7f9508dd7869142b25f399d6bd6
-"@typescript-eslint/typescript-estree@npm:8.29.0, @typescript-eslint/typescript-estree@npm:^8.29.0":
- resolution: "@typescript-eslint/typescript-estree@npm:8.29.0"
+"@typescript-eslint/typescript-estree@npm:8.30.1, @typescript-eslint/typescript-estree@npm:^8.29.0":
+ resolution: "@typescript-eslint/typescript-estree@npm:8.30.1"
fast-glob: "npm:^3.3.2"
is-glob: "npm:^4.0.3"
@@ -2278,32 +2294,32 @@ __metadata:
- checksum: 10/276e6ea97857ef0fd940578d4b8f1677fd68d2bb62603c85d7aa97fcf86c1f66c5da962393254b605c7025f0cda74395904053891088cbe405b899afc1180e9c
+ checksum: 10/60c307fbb8ec86d28e4b2237b624427b7aee737bced82e5f94acc84229eae907e7742ccf0c9c0825326b3ccb9f72b14075893d90e06c28f8ce2fd04502c0b410
-"@typescript-eslint/utils@npm:8.29.0, @typescript-eslint/utils@npm:^6.0.0 || ^7.0.0 || ^8.0.0, @typescript-eslint/utils@npm:^8.29.0":
- resolution: "@typescript-eslint/utils@npm:8.29.0"
+"@typescript-eslint/utils@npm:8.30.1, @typescript-eslint/utils@npm:^6.0.0 || ^7.0.0 || ^8.0.0, @typescript-eslint/utils@npm:^8.29.0":
"@eslint-community/eslint-utils": "npm:^4.4.0"
- checksum: 10/1fd17a28b8b57fc73c0455dea43a8185d3a4421f4a21ece01009b5e6a2974c8d4113f90d27993f668fa97077891b4464588d380c25116d351eb12ad7ef0d468d
+ checksum: 10/97d27d2f0bce6f60a1857d511dba401f076766477a2896405aca52e860f9c5460111299f6e17642e18e578be1dbf850a0b1202ba61aa65d6a52646429ff9c99c
-"@typescript-eslint/visitor-keys@npm:8.29.0":
- resolution: "@typescript-eslint/visitor-keys@npm:8.29.0"
+"@typescript-eslint/visitor-keys@npm:8.30.1":
+ resolution: "@typescript-eslint/visitor-keys@npm:8.30.1"
eslint-visitor-keys: "npm:^4.2.0"
- checksum: 10/02e0e86ab112849a31b7d06c767be0ca7802385bf953d3b75f4ba6d06741d9492773325bc69d4c2a1c191b08f1c4c4b33f8e062d6d5d9f0f4f78f1b8b3cc2d41
+ checksum: 10/0c08169123ebca4ab04464486a7f41093ba77e75fb088e2c8af9f36bb4c0f785d4e82940f6b62e47457d4758fa57a53423db4226250d6eb284e75a3f96f03f2b
@@ -7048,9 +7064,10 @@ __metadata:
"@prettier/parse-srcset": "npm:3.1.0"
"@stylistic/eslint-plugin-js": "npm:4.2.0"
"@types/estree": "npm:1.0.7"
- "@typescript-eslint/eslint-plugin": "npm:8.29.0"
+ "@typescript-eslint/eslint-plugin": "npm:8.30.1"
acorn: "npm:8.14.1"
acorn-jsx: "npm:5.3.2"
angular-estree-parser: "npm:11.1.1" | [
"+ debug: \"npm:^4.3.4\"",
"+ checksum: 10/ecae69888a06126d57f3ac2db9935199b708406e8cd84e0918dd8302f31771145d62b52bf3c454be43c5aa4f93685d3f8c15b118d0de1c0323e02113c127aa66",
"- resolution: \"@typescript-eslint/type-utils@npm:8.29.0\"",
"- checksum: 10/d65b9f2f6d87a3744788b09d9112c4a0298f1215138d8677240aae3bfa37ddc24a59315536cd9aab63c7608909ae2c5f436924c889b98986b78003b6028b5c35",
"+ resolution: \"@typescript-eslint/utils@npm:8.30.1\"",
"+ \"@typescript-eslint/parser\": \"npm:8.30.1\""
] | [
75,
89,
95,
117,
153,
193
] | {
"additions": 66,
"author": "renovate[bot]",
"deletions": 48,
"html_url": "https://github.com/prettier/prettier/pull/17356",
"issue_id": 17356,
"merged_at": "2025-04-15T06:08:29Z",
"omission_probability": 0.1,
"pr_number": 17356,
"repo": "prettier/prettier",
"title": "chore(deps): update typescript-eslint to v8.30.1",
"total_changes": 114
} |
177 | diff --git a/changelog_unreleased/api/17331.md b/changelog_unreleased/api/17331.md
new file mode 100644
index 000000000000..1c222e246f11
--- /dev/null
+++ b/changelog_unreleased/api/17331.md
@@ -0,0 +1,17 @@
+#### Add `isSupported` function support for `languages` API (#17331 by @JounQin)
+
+Previously, `languages` API for custom plugin only supported to infer parser based on the file basename or extension.
+
+Prettier main added `isSupported: (file: string) => boolean` function to allow plugin check if file is supported based on the full path (eg: files in a specific directory), the `file` parameter could be a normal path or a url string like `file:///C:/test.txt`.
+
+If no `isSupported` provided, it just behaviors the same way as before.
+
+```js
+export const languages = [
+ {
+ name: "foo",
+ parsers: ["foo"],
+ isSupported: (file) => file.includes(".foo"),
+ },
+];
+```
diff --git a/docs/api.md b/docs/api.md
index ec7efc10b161..fe7d29b9a5a8 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -124,6 +124,7 @@ The support information looks like this:
filenames?: string[];
linguistLanguageId?: number;
vscodeLanguageIds?: string[];
+ isSupported?(file: string): boolean;
}>;
}
```
diff --git a/docs/plugins.md b/docs/plugins.md
index 10b059b030b2..7597a6e232a1 100644
--- a/docs/plugins.md
+++ b/docs/plugins.md
@@ -70,7 +70,7 @@ Strings provided to `plugins` are ultimately passed to [`import()` expression](h
- [`prettier-plugin-sql-cst`](https://github.com/nene/prettier-plugin-sql-cst) by [**@nene**](https://github.com/nene)
- [`prettier-plugin-solidity`](https://github.com/prettier-solidity/prettier-plugin-solidity) by [**@mattiaerre**](https://github.com/mattiaerre)
- [`prettier-plugin-svelte`](https://github.com/sveltejs/prettier-plugin-svelte) by [**@sveltejs**](https://github.com/sveltejs)
-- [`prettier-plugin-toml`](https://github.com/bd82/toml-tools/tree/master/packages/prettier-plugin-toml) by [**@bd82**](https://github.com/bd82)
+- [`prettier-plugin-toml`](https://github.com/un-ts/prettier/tree/master/packages/toml) by [**@JounQin**](https://github.com/JounQin) and [**@so1ve**](https://github.com/so1ve)
## Developing Plugins
diff --git a/src/cli/file-info.js b/src/cli/file-info.js
index a84bf7ea02c3..377445757991 100644
--- a/src/cli/file-info.js
+++ b/src/cli/file-info.js
@@ -1,3 +1,4 @@
+import path from "node:path";
import stringify from "fast-json-stable-stringify";
import { format, getFileInfo } from "../index.js";
import { printToScreen } from "./utils.js";
@@ -11,7 +12,7 @@ async function logFileInfoOrDie(context) {
config,
} = context.argv;
- const fileInfo = await getFileInfo(file, {
+ const fileInfo = await getFileInfo(path.resolve(file), {
ignorePath,
withNodeModules,
plugins,
diff --git a/src/cli/format.js b/src/cli/format.js
index 9385eeff8516..5f3e04b51245 100644
--- a/src/cli/format.js
+++ b/src/cli/format.js
@@ -239,10 +239,12 @@ async function formatStdin(context) {
// TODO[@fisker]: Exit if no input.
// `prettier --config-precedence cli-override`
+ const absoluteFilepath = filepath ? path.resolve(filepath) : undefined;
+
let isFileIgnored = false;
- if (filepath) {
+ if (absoluteFilepath) {
const isIgnored = await createIsIgnoredFromContextOrDie(context);
- isFileIgnored = isIgnored(filepath);
+ isFileIgnored = isIgnored(absoluteFilepath);
}
if (isFileIgnored) {
@@ -250,10 +252,11 @@ async function formatStdin(context) {
return;
}
- const options = await getOptionsForFile(
- context,
- filepath ? path.resolve(filepath) : undefined,
- );
+ const options = {
+ ...(await getOptionsForFile(context, absoluteFilepath)),
+ // `getOptionsForFile` forwards `--stdin-filepath` directly, which can be a relative path
+ filepath: absoluteFilepath,
+ };
if (await listDifferent(context, input, options, "(stdin)")) {
return;
diff --git a/src/index.d.ts b/src/index.d.ts
index 7a7841ec834d..84cf02a8d0c2 100644
--- a/src/index.d.ts
+++ b/src/index.d.ts
@@ -673,6 +673,7 @@ export interface SupportLanguage {
linguistLanguageId?: number | undefined;
vscodeLanguageIds?: string[] | undefined;
interpreters?: string[] | undefined;
+ isSupported?: ((file: string) => boolean) | undefined;
}
export interface SupportOptionRange {
diff --git a/src/utils/infer-parser.js b/src/utils/infer-parser.js
index 0b1b4a0131c6..7f23a7b24140 100644
--- a/src/utils/infer-parser.js
+++ b/src/utils/infer-parser.js
@@ -1,11 +1,19 @@
import getInterpreter from "./get-interpreter.js";
-/** @import {Options} from "../index.js" */
+/** @import {Options, SupportLanguage} from "../index.js" */
-// Didn't use `path.basename` since this module need work in browsers too
-// And `file` can be a `URL`
+/**
+ * Didn't use `path.basename` since this module should work in browsers too
+ * And `file` can be a `URL`
+ * @param {string | URL} file
+ */
const getFileBasename = (file) => String(file).split(/[/\\]/u).pop();
+/**
+ * @param {SupportLanguage[]} languages
+ * @param {string | URL | undefined} [file]
+ * @returns {SupportLanguage | undefined}
+ */
function getLanguageByFileName(languages, file) {
if (!file) {
return;
@@ -23,6 +31,11 @@ function getLanguageByFileName(languages, file) {
);
}
+/**
+ * @param {SupportLanguage[]} languages
+ * @param {string | undefined} [languageName]
+ * @returns {SupportLanguage | undefined}
+ */
function getLanguageByLanguageName(languages, languageName) {
if (!languageName) {
return;
@@ -35,6 +48,11 @@ function getLanguageByLanguageName(languages, languageName) {
);
}
+/**
+ * @param {SupportLanguage[]} languages
+ * @param {string | URL | undefined} [file]
+ * @returns {SupportLanguage | undefined}
+ */
function getLanguageByInterpreter(languages, file) {
if (
process.env.PRETTIER_TARGET === "universal" ||
@@ -55,10 +73,30 @@ function getLanguageByInterpreter(languages, file) {
);
}
+/**
+ * @param {SupportLanguage[]} languages
+ * @param {string | URL | undefined} [file]
+ * @returns {SupportLanguage | undefined}
+ */
+function getLanguageByIsSupported(languages, file) {
+ if (!file) {
+ return;
+ }
+
+ /*
+ We can't use `url.fileURLToPath` here since this module should work in browsers too
+ `URL#pathname` won't work either since `new URL('file:///C:/path/to/file').pathname`
+ equals to `/C:/path/to/file`, try to improve this part in future
+ */
+ file = String(file);
+
+ return languages.find(({ isSupported }) => isSupported?.(file));
+}
+
/**
* @param {Options} options
- * @param {{physicalFile?: string | URL, file?: string | URL, language?: string}} fileInfo
- * @returns {string | void} matched parser name if found
+ * @param {{physicalFile?: string | URL | undefined, file?: string | URL | undefined, language?: string | undefined}} fileInfo
+ * @returns {string | undefined} matched parser name if found
*/
function inferParser(options, fileInfo) {
const languages = options.plugins.flatMap(
@@ -74,6 +112,8 @@ function inferParser(options, fileInfo) {
getLanguageByLanguageName(languages, fileInfo.language) ??
getLanguageByFileName(languages, fileInfo.physicalFile) ??
getLanguageByFileName(languages, fileInfo.file) ??
+ getLanguageByIsSupported(languages, fileInfo.physicalFile) ??
+ getLanguageByIsSupported(languages, fileInfo.file) ??
getLanguageByInterpreter(languages, fileInfo.physicalFile);
return language?.parsers[0];
diff --git a/tests/integration/__tests__/__snapshots__/infer-parser.js.snap b/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
index 84a12db4719e..a08d690bb57c 100644
--- a/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
+++ b/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
@@ -80,17 +80,34 @@ exports[`Interpreters (stdout) 1`] = `"{ "ignored": false, "inferredParser": "ba
exports[`Known/Unknown (stdout) 1`] = `"known.js"`;
+exports[`isSupported (stdout) 1`] = `
+"{
+ "ignored": false,
+ "inferredParser": "parser-name-inferred-from-language-is-supported"
+}"
+`;
+
+exports[`isSupported (stdout) 2`] = `
+"content from file
+formatted by 'parser-name-inferred-from-language-is-supported' parser"
+`;
+
+exports[`isSupported (stdout) 3`] = `
+"content from stdin
+formatted by 'parser-name-inferred-from-language-is-supported' parser"
+`;
+
exports[`stdin no path and no parser --check logs error but exits with 0 (stderr) 1`] = `"[error] No parser and no file path given, couldn't infer a parser."`;
exports[`stdin no path and no parser --list-different logs error but exits with 0 (stderr) 1`] = `"[error] No parser and no file path given, couldn't infer a parser."`;
exports[`stdin no path and no parser logs error and exits with 2 (stderr) 1`] = `"[error] No parser and no file path given, couldn't infer a parser."`;
-exports[`stdin with unknown path and no parser --check logs error but exits with 0 (stderr) 1`] = `"[error] No parser could be inferred for file "foo"."`;
+exports[`stdin with unknown path and no parser --check logs error but exits with 0 (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/foo"."`;
-exports[`stdin with unknown path and no parser --list-different logs error but exits with 0 (stderr) 1`] = `"[error] No parser could be inferred for file "foo"."`;
+exports[`stdin with unknown path and no parser --list-different logs error but exits with 0 (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/foo"."`;
-exports[`stdin with unknown path and no parser logs error and exits with 2 (stderr) 1`] = `"[error] No parser could be inferred for file "foo"."`;
+exports[`stdin with unknown path and no parser logs error and exits with 2 (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/foo"."`;
exports[`unknown path and no parser multiple files (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/FOO"."`;
diff --git a/tests/integration/__tests__/infer-parser.js b/tests/integration/__tests__/infer-parser.js
index f6bbf787921c..2d331bc012e1 100644
--- a/tests/integration/__tests__/infer-parser.js
+++ b/tests/integration/__tests__/infer-parser.js
@@ -199,3 +199,41 @@ describe("Interpreters", () => {
write: [],
});
});
+
+describe("isSupported", () => {
+ runCli("cli/infer-parser", [
+ "--plugin",
+ "../../plugins/languages/is-supported.js",
+ "--file-info",
+ ".husky/pre-commit",
+ ]).test({
+ status: 0,
+ stderr: "",
+ write: [],
+ });
+
+ runCli("cli/infer-parser", [
+ "--plugin",
+ "../../plugins/languages/is-supported.js",
+ ".husky/pre-commit",
+ ]).test({
+ status: 0,
+ stderr: "",
+ write: [],
+ });
+
+ runCli(
+ "cli/infer-parser",
+ [
+ "--plugin",
+ "../../plugins/languages/is-supported.js",
+ "--stdin-filepath",
+ ".husky/pre-commit",
+ ],
+ { input: "content from stdin" },
+ ).test({
+ status: 0,
+ stderr: "",
+ write: [],
+ });
+});
diff --git a/tests/integration/cli/infer-parser/.husky/pre-commit b/tests/integration/cli/infer-parser/.husky/pre-commit
new file mode 100644
index 000000000000..f221ff072173
--- /dev/null
+++ b/tests/integration/cli/infer-parser/.husky/pre-commit
@@ -0,0 +1 @@
+content from file
diff --git a/tests/integration/plugins/languages/is-supported.js b/tests/integration/plugins/languages/is-supported.js
new file mode 100644
index 000000000000..6b8350406d8e
--- /dev/null
+++ b/tests/integration/plugins/languages/is-supported.js
@@ -0,0 +1,28 @@
+import path from "node:path";
+import createPlugin from "../../../config/utils/create-plugin.cjs";
+
+const PARSER_NAME = "parser-name-inferred-from-language-is-supported";
+const PRINT_MARK = `formatted by '${PARSER_NAME}' parser`
+
+const languages = [
+ {
+ name: "language-name-does-not-matter",
+ parsers: [PARSER_NAME],
+ isSupported(file) {
+ if (!path.isAbsolute(file)) {
+ throw new Error("Unexpected non absolute path");
+ }
+
+ return /(?<separator>[\\/])\.husky\k<separator>[^\\/]+$/u.test(file);
+ },
+ },
+];
+
+export default {
+ ...createPlugin({
+ name: PARSER_NAME,
+ print: (content) => `${content.replace(PRINT_MARK,"").trim()}\n${PRINT_MARK}`,
+ finalNewLine: false,
+ }),
+ languages,
+};
| diff --git a/changelog_unreleased/api/17331.md b/changelog_unreleased/api/17331.md
index 000000000000..1c222e246f11
+++ b/changelog_unreleased/api/17331.md
@@ -0,0 +1,17 @@
+#### Add `isSupported` function support for `languages` API (#17331 by @JounQin)
+Previously, `languages` API for custom plugin only supported to infer parser based on the file basename or extension.
+Prettier main added `isSupported: (file: string) => boolean` function to allow plugin check if file is supported based on the full path (eg: files in a specific directory), the `file` parameter could be a normal path or a url string like `file:///C:/test.txt`.
+```js
+export const languages = [
+ name: "foo",
+ parsers: ["foo"],
+ isSupported: (file) => file.includes(".foo"),
+```
diff --git a/docs/api.md b/docs/api.md
index ec7efc10b161..fe7d29b9a5a8 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -124,6 +124,7 @@ The support information looks like this:
filenames?: string[];
linguistLanguageId?: number;
vscodeLanguageIds?: string[];
+ isSupported?(file: string): boolean;
}>;
```
diff --git a/docs/plugins.md b/docs/plugins.md
index 10b059b030b2..7597a6e232a1 100644
--- a/docs/plugins.md
+++ b/docs/plugins.md
@@ -70,7 +70,7 @@ Strings provided to `plugins` are ultimately passed to [`import()` expression](h
- [`prettier-plugin-sql-cst`](https://github.com/nene/prettier-plugin-sql-cst) by [**@nene**](https://github.com/nene)
- [`prettier-plugin-solidity`](https://github.com/prettier-solidity/prettier-plugin-solidity) by [**@mattiaerre**](https://github.com/mattiaerre)
- [`prettier-plugin-svelte`](https://github.com/sveltejs/prettier-plugin-svelte) by [**@sveltejs**](https://github.com/sveltejs)
-- [`prettier-plugin-toml`](https://github.com/bd82/toml-tools/tree/master/packages/prettier-plugin-toml) by [**@bd82**](https://github.com/bd82)
+- [`prettier-plugin-toml`](https://github.com/un-ts/prettier/tree/master/packages/toml) by [**@JounQin**](https://github.com/JounQin) and [**@so1ve**](https://github.com/so1ve)
## Developing Plugins
diff --git a/src/cli/file-info.js b/src/cli/file-info.js
index a84bf7ea02c3..377445757991 100644
--- a/src/cli/file-info.js
+++ b/src/cli/file-info.js
@@ -1,3 +1,4 @@
import stringify from "fast-json-stable-stringify";
import { format, getFileInfo } from "../index.js";
import { printToScreen } from "./utils.js";
@@ -11,7 +12,7 @@ async function logFileInfoOrDie(context) {
config,
} = context.argv;
- const fileInfo = await getFileInfo(file, {
+ const fileInfo = await getFileInfo(path.resolve(file), {
ignorePath,
withNodeModules,
plugins,
diff --git a/src/cli/format.js b/src/cli/format.js
index 9385eeff8516..5f3e04b51245 100644
--- a/src/cli/format.js
+++ b/src/cli/format.js
@@ -239,10 +239,12 @@ async function formatStdin(context) {
// TODO[@fisker]: Exit if no input.
// `prettier --config-precedence cli-override`
+ const absoluteFilepath = filepath ? path.resolve(filepath) : undefined;
let isFileIgnored = false;
- if (filepath) {
+ if (absoluteFilepath) {
const isIgnored = await createIsIgnoredFromContextOrDie(context);
- isFileIgnored = isIgnored(filepath);
if (isFileIgnored) {
@@ -250,10 +252,11 @@ async function formatStdin(context) {
- const options = await getOptionsForFile(
- context,
- filepath ? path.resolve(filepath) : undefined,
+ const options = {
+ ...(await getOptionsForFile(context, absoluteFilepath)),
+ // `getOptionsForFile` forwards `--stdin-filepath` directly, which can be a relative path
+ filepath: absoluteFilepath,
+ };
if (await listDifferent(context, input, options, "(stdin)")) {
diff --git a/src/index.d.ts b/src/index.d.ts
index 7a7841ec834d..84cf02a8d0c2 100644
--- a/src/index.d.ts
+++ b/src/index.d.ts
@@ -673,6 +673,7 @@ export interface SupportLanguage {
linguistLanguageId?: number | undefined;
vscodeLanguageIds?: string[] | undefined;
interpreters?: string[] | undefined;
+ isSupported?: ((file: string) => boolean) | undefined;
export interface SupportOptionRange {
diff --git a/src/utils/infer-parser.js b/src/utils/infer-parser.js
index 0b1b4a0131c6..7f23a7b24140 100644
--- a/src/utils/infer-parser.js
+++ b/src/utils/infer-parser.js
@@ -1,11 +1,19 @@
import getInterpreter from "./get-interpreter.js";
-/** @import {Options} from "../index.js" */
+/** @import {Options, SupportLanguage} from "../index.js" */
-// Didn't use `path.basename` since this module need work in browsers too
-// And `file` can be a `URL`
+ * Didn't use `path.basename` since this module should work in browsers too
+ * And `file` can be a `URL`
+ * @param {string | URL} file
const getFileBasename = (file) => String(file).split(/[/\\]/u).pop();
function getLanguageByFileName(languages, file) {
if (!file) {
@@ -23,6 +31,11 @@ function getLanguageByFileName(languages, file) {
function getLanguageByLanguageName(languages, languageName) {
if (!languageName) {
@@ -35,6 +48,11 @@ function getLanguageByLanguageName(languages, languageName) {
function getLanguageByInterpreter(languages, file) {
if (
process.env.PRETTIER_TARGET === "universal" ||
@@ -55,10 +73,30 @@ function getLanguageByInterpreter(languages, file) {
+function getLanguageByIsSupported(languages, file) {
+ if (!file) {
+ return;
+ }
+ /*
+ We can't use `url.fileURLToPath` here since this module should work in browsers too
+ `URL#pathname` won't work either since `new URL('file:///C:/path/to/file').pathname`
+ equals to `/C:/path/to/file`, try to improve this part in future
+ file = String(file);
+ return languages.find(({ isSupported }) => isSupported?.(file));
+}
/**
* @param {Options} options
- * @param {{physicalFile?: string | URL, file?: string | URL, language?: string}} fileInfo
- * @returns {string | void} matched parser name if found
+ * @param {{physicalFile?: string | URL | undefined, file?: string | URL | undefined, language?: string | undefined}} fileInfo
+ * @returns {string | undefined} matched parser name if found
*/
function inferParser(options, fileInfo) {
const languages = options.plugins.flatMap(
@@ -74,6 +112,8 @@ function inferParser(options, fileInfo) {
getLanguageByLanguageName(languages, fileInfo.language) ??
getLanguageByFileName(languages, fileInfo.physicalFile) ??
getLanguageByFileName(languages, fileInfo.file) ??
+ getLanguageByIsSupported(languages, fileInfo.physicalFile) ??
+ getLanguageByIsSupported(languages, fileInfo.file) ??
getLanguageByInterpreter(languages, fileInfo.physicalFile);
return language?.parsers[0];
diff --git a/tests/integration/__tests__/__snapshots__/infer-parser.js.snap b/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
index 84a12db4719e..a08d690bb57c 100644
--- a/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
+++ b/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
@@ -80,17 +80,34 @@ exports[`Interpreters (stdout) 1`] = `"{ "ignored": false, "inferredParser": "ba
exports[`Known/Unknown (stdout) 1`] = `"known.js"`;
+exports[`isSupported (stdout) 1`] = `
+"{
+ "ignored": false,
+ "inferredParser": "parser-name-inferred-from-language-is-supported"
+}"
+exports[`isSupported (stdout) 2`] = `
+"content from stdin
exports[`stdin no path and no parser --check logs error but exits with 0 (stderr) 1`] = `"[error] No parser and no file path given, couldn't infer a parser."`;
exports[`stdin no path and no parser --list-different logs error but exits with 0 (stderr) 1`] = `"[error] No parser and no file path given, couldn't infer a parser."`;
exports[`stdin no path and no parser logs error and exits with 2 (stderr) 1`] = `"[error] No parser and no file path given, couldn't infer a parser."`;
+exports[`stdin with unknown path and no parser --check logs error but exits with 0 (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/foo"."`;
-exports[`stdin with unknown path and no parser --list-different logs error but exits with 0 (stderr) 1`] = `"[error] No parser could be inferred for file "foo"."`;
+exports[`stdin with unknown path and no parser --list-different logs error but exits with 0 (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/foo"."`;
-exports[`stdin with unknown path and no parser logs error and exits with 2 (stderr) 1`] = `"[error] No parser could be inferred for file "foo"."`;
+exports[`stdin with unknown path and no parser logs error and exits with 2 (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/foo"."`;
exports[`unknown path and no parser multiple files (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/FOO"."`;
diff --git a/tests/integration/__tests__/infer-parser.js b/tests/integration/__tests__/infer-parser.js
index f6bbf787921c..2d331bc012e1 100644
--- a/tests/integration/__tests__/infer-parser.js
+++ b/tests/integration/__tests__/infer-parser.js
@@ -199,3 +199,41 @@ describe("Interpreters", () => {
write: [],
});
});
+describe("isSupported", () => {
+ "--file-info",
+ runCli(
+ "cli/infer-parser",
+ [
+ "../../plugins/languages/is-supported.js",
+ "--stdin-filepath",
+ ".husky/pre-commit",
+ ],
+ { input: "content from stdin" },
+ ).test({
+});
diff --git a/tests/integration/cli/infer-parser/.husky/pre-commit b/tests/integration/cli/infer-parser/.husky/pre-commit
index 000000000000..f221ff072173
+++ b/tests/integration/cli/infer-parser/.husky/pre-commit
@@ -0,0 +1 @@
diff --git a/tests/integration/plugins/languages/is-supported.js b/tests/integration/plugins/languages/is-supported.js
index 000000000000..6b8350406d8e
+++ b/tests/integration/plugins/languages/is-supported.js
@@ -0,0 +1,28 @@
+import createPlugin from "../../../config/utils/create-plugin.cjs";
+const PARSER_NAME = "parser-name-inferred-from-language-is-supported";
+const PRINT_MARK = `formatted by '${PARSER_NAME}' parser`
+const languages = [
+ name: "language-name-does-not-matter",
+ parsers: [PARSER_NAME],
+ isSupported(file) {
+ if (!path.isAbsolute(file)) {
+ throw new Error("Unexpected non absolute path");
+ }
+ return /(?<separator>[\\/])\.husky\k<separator>[^\\/]+$/u.test(file);
+ },
+export default {
+ ...createPlugin({
+ name: PARSER_NAME,
+ print: (content) => `${content.replace(PRINT_MARK,"").trim()}\n${PRINT_MARK}`,
+ finalNewLine: false,
+ }),
+}; | [
"+If no `isSupported` provided, it just behaviors the same way as before.",
"+ isFileIgnored = isIgnored(absoluteFilepath);",
"- );",
"+ * @param {string | undefined} [languageName]",
"+ */",
"+\"content from file",
"+exports[`isSupported (stdout) 3`] = `",
"-exports[`stdin with unknown path and no parser --check logs error but exits with 0 (stderr) 1`] = `\"[error] No parser could be inferred for file \"foo\".\"`;",
"+ \"--plugin\",",
"+content from file",
"+ languages,"
] | [
12,
81,
92,
146,
182,
222,
226,
237,
282,
300,
333
] | {
"additions": 163,
"author": "JounQin",
"deletions": 16,
"html_url": "https://github.com/prettier/prettier/pull/17331",
"issue_id": 17331,
"merged_at": "2025-04-14T01:15:43Z",
"omission_probability": 0.1,
"pr_number": 17331,
"repo": "prettier/prettier",
"title": "Add `isSupported` function support for language",
"total_changes": 179
} |
178 | diff --git a/src/cli/directory-ignorer.js b/src/cli/directory-ignorer.js
new file mode 100644
index 000000000000..89ce3a63e3d7
--- /dev/null
+++ b/src/cli/directory-ignorer.js
@@ -0,0 +1,42 @@
+import path from "node:path";
+
+// Ignores files in version control systems directories and `node_modules`
+const alwaysIgnoredDirectories = [".git", ".sl", ".svn", ".hg", ".jj"];
+const withNodeModules = [...alwaysIgnoredDirectories, "node_modules"];
+const cwd = process.cwd();
+
+class DirectoryIgnorer {
+ #directories;
+ ignorePatterns;
+
+ constructor(shouldIgnoreNodeModules) {
+ const directories = shouldIgnoreNodeModules
+ ? withNodeModules
+ : alwaysIgnoredDirectories;
+ const patterns = directories.map((directory) => `**/${directory}`);
+
+ this.#directories = new Set(directories);
+ this.ignorePatterns = patterns;
+ }
+
+ /**
+ * @param {string} absolutePathOrPattern
+ */
+ shouldIgnore(absolutePathOrPattern) {
+ const directoryNames = path
+ .relative(cwd, absolutePathOrPattern)
+ .split(path.sep);
+ return directoryNames.some((directoryName) =>
+ this.#directories.has(directoryName),
+ );
+ }
+}
+
+const directoryIgnorerWithNodeModules = new DirectoryIgnorer(
+ /* shouldIgnoreNodeModules */ true,
+);
+const directoryIgnorerWithoutNodeModules = new DirectoryIgnorer(
+ /* shouldIgnoreNodeModules */ false,
+);
+
+export { directoryIgnorerWithNodeModules, directoryIgnorerWithoutNodeModules };
diff --git a/src/cli/expand-patterns.js b/src/cli/expand-patterns.js
index ffc6f8cdc0b0..6e75e585ed68 100644
--- a/src/cli/expand-patterns.js
+++ b/src/cli/expand-patterns.js
@@ -1,4 +1,8 @@
import path from "node:path";
+import {
+ directoryIgnorerWithNodeModules,
+ directoryIgnorerWithoutNodeModules,
+} from "./directory-ignorer.js";
import { fastGlob } from "./prettier-internal.js";
import { lstatSafe, normalizeToPosix } from "./utils.js";
@@ -43,26 +47,24 @@ async function* expandPatterns(context) {
* @param {Context} context
*/
async function* expandPatternsInternal(context) {
- // Ignores files in version control systems directories and `node_modules`
- const silentlyIgnoredDirs = [".git", ".sl", ".svn", ".hg", ".jj"];
- if (context.argv.withNodeModules !== true) {
- silentlyIgnoredDirs.push("node_modules");
- }
+ const directoryIgnorer =
+ context.argv.withNodeModules === true
+ ? directoryIgnorerWithoutNodeModules
+ : directoryIgnorerWithNodeModules;
const globOptions = {
dot: true,
- ignore: silentlyIgnoredDirs.map((dir) => "**/" + dir),
+ ignore: [...directoryIgnorer.ignorePatterns],
followSymbolicLinks: false,
};
-
const cwd = process.cwd();
/** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */
const entries = [];
for (const pattern of context.filePatterns) {
- const absolutePath = path.resolve(cwd, pattern);
+ const absolutePath = path.resolve(pattern);
- if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) {
+ if (directoryIgnorer.shouldIgnore(absolutePath)) {
continue;
}
@@ -147,18 +149,6 @@ const errorMessages = {
},
};
-/**
- * @param {string} absolutePath
- * @param {string} cwd
- * @param {string[]} ignoredDirectories
- */
-function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) {
- return path
- .relative(cwd, absolutePath)
- .split(path.sep)
- .some((dir) => ignoredDirectories.includes(dir));
-}
-
/**
* @param {string[]} paths
*/
| diff --git a/src/cli/directory-ignorer.js b/src/cli/directory-ignorer.js
new file mode 100644
index 000000000000..89ce3a63e3d7
--- /dev/null
+++ b/src/cli/directory-ignorer.js
@@ -0,0 +1,42 @@
+import path from "node:path";
+// Ignores files in version control systems directories and `node_modules`
+const alwaysIgnoredDirectories = [".git", ".sl", ".svn", ".hg", ".jj"];
+const withNodeModules = [...alwaysIgnoredDirectories, "node_modules"];
+const cwd = process.cwd();
+class DirectoryIgnorer {
+ ignorePatterns;
+ constructor(shouldIgnoreNodeModules) {
+ const directories = shouldIgnoreNodeModules
+ ? withNodeModules
+ : alwaysIgnoredDirectories;
+ const patterns = directories.map((directory) => `**/${directory}`);
+ this.ignorePatterns = patterns;
+ /**
+ * @param {string} absolutePathOrPattern
+ */
+ shouldIgnore(absolutePathOrPattern) {
+ const directoryNames = path
+ .relative(cwd, absolutePathOrPattern)
+ .split(path.sep);
+ return directoryNames.some((directoryName) =>
+ this.#directories.has(directoryName),
+ );
+}
+const directoryIgnorerWithNodeModules = new DirectoryIgnorer(
+ /* shouldIgnoreNodeModules */ true,
+const directoryIgnorerWithoutNodeModules = new DirectoryIgnorer(
+ /* shouldIgnoreNodeModules */ false,
+export { directoryIgnorerWithNodeModules, directoryIgnorerWithoutNodeModules };
diff --git a/src/cli/expand-patterns.js b/src/cli/expand-patterns.js
index ffc6f8cdc0b0..6e75e585ed68 100644
--- a/src/cli/expand-patterns.js
+++ b/src/cli/expand-patterns.js
@@ -1,4 +1,8 @@
import path from "node:path";
+import {
+ directoryIgnorerWithNodeModules,
+ directoryIgnorerWithoutNodeModules,
+} from "./directory-ignorer.js";
import { fastGlob } from "./prettier-internal.js";
import { lstatSafe, normalizeToPosix } from "./utils.js";
@@ -43,26 +47,24 @@ async function* expandPatterns(context) {
* @param {Context} context
async function* expandPatternsInternal(context) {
- // Ignores files in version control systems directories and `node_modules`
- const silentlyIgnoredDirs = [".git", ".sl", ".svn", ".hg", ".jj"];
- if (context.argv.withNodeModules !== true) {
- silentlyIgnoredDirs.push("node_modules");
- }
+ const directoryIgnorer =
+ context.argv.withNodeModules === true
+ ? directoryIgnorerWithoutNodeModules
+ : directoryIgnorerWithNodeModules;
const globOptions = {
dot: true,
- ignore: silentlyIgnoredDirs.map((dir) => "**/" + dir),
+ ignore: [...directoryIgnorer.ignorePatterns],
followSymbolicLinks: false,
};
const cwd = process.cwd();
/** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */
const entries = [];
for (const pattern of context.filePatterns) {
- const absolutePath = path.resolve(cwd, pattern);
+ const absolutePath = path.resolve(pattern);
- if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) {
+ if (directoryIgnorer.shouldIgnore(absolutePath)) {
continue;
}
@@ -147,18 +149,6 @@ const errorMessages = {
},
};
-/**
- * @param {string} absolutePath
- * @param {string} cwd
- * @param {string[]} ignoredDirectories
- */
-function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) {
- return path
- .relative(cwd, absolutePath)
- .split(path.sep)
- .some((dir) => ignoredDirectories.includes(dir));
-}
/**
* @param {string[]} paths | [
"+ #directories;",
"+ this.#directories = new Set(directories);"
] | [
14,
23
] | {
"additions": 53,
"author": "fisker",
"deletions": 21,
"html_url": "https://github.com/prettier/prettier/pull/17345",
"issue_id": 17345,
"merged_at": "2025-04-14T00:15:16Z",
"omission_probability": 0.1,
"pr_number": 17345,
"repo": "prettier/prettier",
"title": "Minor improvement to `expandPatterns`",
"total_changes": 74
} |
179 | diff --git a/src/utils/infer-parser.js b/src/utils/infer-parser.js
index 0b1b4a0131c6..f8d42af10bf4 100644
--- a/src/utils/infer-parser.js
+++ b/src/utils/infer-parser.js
@@ -1,4 +1,5 @@
import getInterpreter from "./get-interpreter.js";
+import isNonEmptyArray from "./is-non-empty-array.js";
/** @import {Options} from "../index.js" */
@@ -44,14 +45,23 @@ function getLanguageByInterpreter(languages, file) {
return;
}
+ const languagesWithInterpreters = languages.filter(({ interpreters }) =>
+ isNonEmptyArray(interpreters),
+ );
+
+ /* c8 ignore next 3 */
+ if (languagesWithInterpreters.length === 0) {
+ return;
+ }
+
const interpreter = getInterpreter(file);
if (!interpreter) {
return;
}
- return languages.find(({ interpreters }) =>
- interpreters?.includes(interpreter),
+ return languagesWithInterpreters.find(({ interpreters }) =>
+ interpreters.includes(interpreter),
);
}
| diff --git a/src/utils/infer-parser.js b/src/utils/infer-parser.js
index 0b1b4a0131c6..f8d42af10bf4 100644
--- a/src/utils/infer-parser.js
+++ b/src/utils/infer-parser.js
@@ -1,4 +1,5 @@
import getInterpreter from "./get-interpreter.js";
+import isNonEmptyArray from "./is-non-empty-array.js";
/** @import {Options} from "../index.js" */
@@ -44,14 +45,23 @@ function getLanguageByInterpreter(languages, file) {
+ const languagesWithInterpreters = languages.filter(({ interpreters }) =>
+ isNonEmptyArray(interpreters),
+ );
+ /* c8 ignore next 3 */
+ if (languagesWithInterpreters.length === 0) {
+ return;
+ }
const interpreter = getInterpreter(file);
if (!interpreter) {
- return languages.find(({ interpreters }) =>
- interpreters?.includes(interpreter),
+ return languagesWithInterpreters.find(({ interpreters }) =>
+ interpreters.includes(interpreter),
);
} | [] | [] | {
"additions": 12,
"author": "fisker",
"deletions": 2,
"html_url": "https://github.com/prettier/prettier/pull/17328",
"issue_id": 17328,
"merged_at": "2025-04-14T00:13:32Z",
"omission_probability": 0.1,
"pr_number": 17328,
"repo": "prettier/prettier",
"title": "Minor improvement to `inferParser`",
"total_changes": 14
} |
180 | diff --git a/changelog_unreleased/api/17339.md b/changelog_unreleased/api/17339.md
new file mode 100644
index 000000000000..529ee232f70d
--- /dev/null
+++ b/changelog_unreleased/api/17339.md
@@ -0,0 +1,3 @@
+#### Add `mjml` parser (#17339 by @fisker)
+
+We already support [MJML](https://mjml.io/) in previous version with `html` parser, in order to distinguish MJML-specific a new `mjml` parser added.
diff --git a/changelog_unreleased/mjml/.gitkeep b/changelog_unreleased/mjml/.gitkeep
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/docs/options.md b/docs/options.md
index 113648163028..157110b60075 100644
--- a/docs/options.md
+++ b/docs/options.md
@@ -325,6 +325,7 @@ Valid options:
- `"vue"` (same parser as `"html"`, but also formats vue-specific syntax) _First available in 1.10.0_
- `"angular"` (same parser as `"html"`, but also formats angular-specific syntax via [angular-estree-parser](https://github.com/ikatyang/angular-estree-parser)) _First available in 1.15.0_
- `"lwc"` (same parser as `"html"`, but also formats LWC-specific syntax for unquoted template attributes) _First available in 1.17.0_
+- `"mjml"` (same parser as `"html"`, but also formats MJML-specific syntax) _First available in 3.6.0_
- `"yaml"` (via [yaml](https://github.com/eemeli/yaml) and [yaml-unist-parser](https://github.com/ikatyang/yaml-unist-parser)) _First available in 1.14.0_
| Default | CLI Override | API Override |
diff --git a/scripts/generate-changelog.js b/scripts/generate-changelog.js
index 9a699e66a7fc..ac58cacd3c52 100755
--- a/scripts/generate-changelog.js
+++ b/scripts/generate-changelog.js
@@ -134,6 +134,7 @@ function getSyntaxFromCategory(category) {
case "angular":
case "html":
case "lwc":
+ case "mjml":
return "html";
case "cli":
return "sh";
diff --git a/scripts/utils/changelog-categories.js b/scripts/utils/changelog-categories.js
index a5b25175bfb5..da74b1d411f6 100644
--- a/scripts/utils/changelog-categories.js
+++ b/scripts/utils/changelog-categories.js
@@ -11,6 +11,7 @@ export const CHANGELOG_CATEGORIES = [
"json",
"less",
"lwc",
+ "mjml",
"markdown",
"mdx",
"scss",
diff --git a/scripts/utils/changelog.js b/scripts/utils/changelog.js
index 39008cbf84ff..70ff104b558f 100644
--- a/scripts/utils/changelog.js
+++ b/scripts/utils/changelog.js
@@ -22,6 +22,7 @@ export const categories = [
{ dir: "vue", title: "Vue" },
{ dir: "angular", title: "Angular" },
{ dir: "lwc", title: "LWC" },
+ { dir: "mjml", title: "MJML" },
{ dir: "handlebars", title: "Ember / Handlebars" },
{ dir: "graphql", title: "GraphQL" },
{ dir: "markdown", title: "Markdown" },
diff --git a/src/index.d.ts b/src/index.d.ts
index 7a7841ec834d..8680e32b7497 100644
--- a/src/index.d.ts
+++ b/src/index.d.ts
@@ -296,6 +296,7 @@ export type BuiltInParserName =
| "markdown"
| "mdx"
| "meriyah"
+ | "mjml"
| "scss"
| "typescript"
| "vue"
diff --git a/src/language-html/languages.evaluate.js b/src/language-html/languages.evaluate.js
index 130f2743e3c1..2dca2b7f73fd 100644
--- a/src/language-html/languages.evaluate.js
+++ b/src/language-html/languages.evaluate.js
@@ -9,13 +9,9 @@ const languages = [
extensions: [".component.html"],
filenames: [],
})),
- createLanguage(linguistLanguages.HTML, (data) => ({
+ createLanguage(linguistLanguages.HTML, () => ({
parsers: ["html"],
vscodeLanguageIds: ["html"],
- extensions: [
- ...data.extensions,
- ".mjml", // MJML is considered XML in Linguist but it should be formatted as HTML
- ],
})),
createLanguage(linguistLanguages.HTML, () => ({
name: "Lightning Web Components",
@@ -24,6 +20,17 @@ const languages = [
extensions: [],
filenames: [],
})),
+ createLanguage(linguistLanguages.HTML, () => ({
+ name: "MJML",
+ parsers: ["mjml"],
+ extensions: [".mjml"],
+ filenames: [],
+ // https://github.com/mjmlio/vscode-mjml/blob/477f030d400fe838d29495f4a432fba57f2198b7/package.json#L226-L238
+ vscodeLanguageIds: ["mjml"],
+ aliases: ["MJML", "mjml"],
+ // https://github.com/mjmlio/vscode-mjml/blob/477f030d400fe838d29495f4a432fba57f2198b7/package.json#L242
+ tmScope: "text.mjml.basic",
+ })),
createLanguage(linguistLanguages.Vue, () => ({
parsers: ["vue"],
vscodeLanguageIds: ["vue"],
diff --git a/src/language-html/parser-html.js b/src/language-html/parser-html.js
index a88ffbb42333..57af1d01f4d1 100644
--- a/src/language-html/parser-html.js
+++ b/src/language-html/parser-html.js
@@ -28,7 +28,7 @@ import isUnknownNamespace from "./utils/is-unknown-namespace.js";
/**
* @typedef {AngularHtmlParserParseOptions & {
- * name: 'html' | 'angular' | 'vue' | 'lwc';
+ * name: 'html' | 'angular' | 'vue' | 'lwc' | 'mjml';
* normalizeTagName?: boolean;
* normalizeAttributeName?: boolean;
* shouldParseAsRawText?: (tagName: string, prefix: string, hasParent: boolean, attrs: Array<{
@@ -444,6 +444,8 @@ const HTML_PARSE_OPTIONS = {
// HTML
export const html = createParser(HTML_PARSE_OPTIONS);
+// MJML https://mjml.io/
+export const mjml = createParser({ ...HTML_PARSE_OPTIONS, name: "mjml" });
// Angular
export const angular = createParser({ name: "angular" });
// Vue
diff --git a/src/main/core-options.evaluate.js b/src/main/core-options.evaluate.js
index b1b8ae5e7fe0..921b5c5490cf 100644
--- a/src/main/core-options.evaluate.js
+++ b/src/main/core-options.evaluate.js
@@ -128,6 +128,7 @@ const options = {
{ value: "html", description: "HTML" },
{ value: "angular", description: "Angular" },
{ value: "lwc", description: "Lightning Web Components" },
+ { value: "mjml", description: "MJML" },
],
},
plugins: {
diff --git a/src/plugins/builtin-plugins-proxy.js b/src/plugins/builtin-plugins-proxy.js
index 75d30e5b826a..8a47a5754449 100644
--- a/src/plugins/builtin-plugins-proxy.js
+++ b/src/plugins/builtin-plugins-proxy.js
@@ -117,7 +117,7 @@ export const { parsers, printers } = createParsersAndPrinters([
},
{
importPlugin: () => import("./html.js"),
- parsers: ["html", "angular", "vue", "lwc"],
+ parsers: ["html", "angular", "vue", "lwc", "mjml"],
printers: ["html"],
},
{
diff --git a/tests/config/utils/check-parsers.js b/tests/config/utils/check-parsers.js
index 238898b84a39..02f3717fd514 100644
--- a/tests/config/utils/check-parsers.js
+++ b/tests/config/utils/check-parsers.js
@@ -50,7 +50,7 @@ const categoryParsers = new Map([
"html",
{ parsers: ["html"], verifyParsers: [], extensions: [".html", ".svg"] },
],
- ["mjml", { parsers: ["html"], verifyParsers: [], extensions: [".mjml"] }],
+ ["mjml", { parsers: ["mjml"], verifyParsers: [], extensions: [".mjml"] }],
[
"js",
{
diff --git a/tests/dts/unit/cases/parsers.ts b/tests/dts/unit/cases/parsers.ts
index 6157ab57739c..e3a90b22af2a 100644
--- a/tests/dts/unit/cases/parsers.ts
+++ b/tests/dts/unit/cases/parsers.ts
@@ -82,6 +82,7 @@ prettierPluginGlimmer.parsers.glimmer.parse("code", options);
prettierPluginHtml.parsers.html.parse("code", options);
prettierPluginHtml.parsers.vue.parse("code", options);
prettierPluginHtml.parsers.lwc.parse("code", options);
+prettierPluginHtml.parsers.mjml.parse("code", options);
prettierPluginHtml.parsers.angular.parse("code", options);
prettierPluginYaml.parsers.yaml.parse("code", options);
diff --git a/tests/format/mjml/mjml/__snapshots__/format.test.js.snap b/tests/format/mjml/mjml/__snapshots__/format.test.js.snap
index 297ff67b0e76..eb7bd37603d7 100644
--- a/tests/format/mjml/mjml/__snapshots__/format.test.js.snap
+++ b/tests/format/mjml/mjml/__snapshots__/format.test.js.snap
@@ -2,7 +2,7 @@
exports[`empty.mjml format 1`] = `
====================================options=====================================
-parsers: ["html"]
+parsers: ["mjml"]
printWidth: 80
| printWidth
=====================================input======================================
@@ -15,7 +15,7 @@ printWidth: 80
exports[`head.mjml format 1`] = `
====================================options=====================================
-parsers: ["html"]
+parsers: ["mjml"]
printWidth: 80
| printWidth
=====================================input======================================
diff --git a/tests/format/mjml/mjml/format.test.js b/tests/format/mjml/mjml/format.test.js
index 88a427864598..5af041ec4149 100644
--- a/tests/format/mjml/mjml/format.test.js
+++ b/tests/format/mjml/mjml/format.test.js
@@ -1 +1 @@
-runFormatTest(import.meta, ["html"]);
+runFormatTest(import.meta, ["mjml"]);
diff --git a/tests/integration/__tests__/__snapshots__/early-exit.js.snap b/tests/integration/__tests__/__snapshots__/early-exit.js.snap
index df4b673437a0..081db39890bc 100644
--- a/tests/integration/__tests__/__snapshots__/early-exit.js.snap
+++ b/tests/integration/__tests__/__snapshots__/early-exit.js.snap
@@ -66,7 +66,7 @@ Format options:
--object-wrap <preserve|collapse>
How to wrap object literals.
Defaults to preserve.
- --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc>
+ --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml>
Which parser to use.
--print-width <int> The line length where Prettier will try wrap.
Defaults to 80.
@@ -161,7 +161,7 @@ exports[`show version with --version (write) 1`] = `[]`;
exports[`show warning with --help not-found (typo) (stderr) 1`] = `"[warn] Unknown flag "parserr", did you mean "parser"?"`;
exports[`show warning with --help not-found (typo) (stdout) 1`] = `
-"--parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc>
+"--parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml>
Which parser to use.
@@ -190,7 +190,8 @@ Valid options:
glimmer Ember / Handlebars
html HTML
angular Angular
- lwc Lightning Web Components"
+ lwc Lightning Web Components
+ mjml MJML"
`;
exports[`show warning with --help not-found (typo) (write) 1`] = `[]`;
@@ -237,7 +238,7 @@ Format options:
--object-wrap <preserve|collapse>
How to wrap object literals.
Defaults to preserve.
- --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc>
+ --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml>
Which parser to use.
--print-width <int> The line length where Prettier will try wrap.
Defaults to 80.
diff --git a/tests/integration/__tests__/__snapshots__/help-options.js.snap b/tests/integration/__tests__/__snapshots__/help-options.js.snap
index f977b7e65e15..7181ae90044a 100644
--- a/tests/integration/__tests__/__snapshots__/help-options.js.snap
+++ b/tests/integration/__tests__/__snapshots__/help-options.js.snap
@@ -438,7 +438,7 @@ exports[`show detailed usage with --help object-wrap (write) 1`] = `[]`;
exports[`show detailed usage with --help parser (stderr) 1`] = `""`;
exports[`show detailed usage with --help parser (stdout) 1`] = `
-"--parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc>
+"--parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml>
Which parser to use.
@@ -467,7 +467,8 @@ Valid options:
glimmer Ember / Handlebars
html HTML
angular Angular
- lwc Lightning Web Components"
+ lwc Lightning Web Components
+ mjml MJML"
`;
exports[`show detailed usage with --help parser (write) 1`] = `[]`;
diff --git a/tests/integration/__tests__/__snapshots__/plugin-options-string.js.snap b/tests/integration/__tests__/__snapshots__/plugin-options-string.js.snap
index 592c8260798a..ab661da8b15f 100644
--- a/tests/integration/__tests__/__snapshots__/plugin-options-string.js.snap
+++ b/tests/integration/__tests__/__snapshots__/plugin-options-string.js.snap
@@ -33,8 +33,8 @@ exports[`show external options with \`--help\` 1`] = `
--object-wrap <preserve|collapse>
How to wrap object literals.
Defaults to preserve.
-- --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc>
-+ --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|foo-parser>
+- --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml>
++ --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml|foo-parser>
Which parser to use.
--print-width <int> The line length where Prettier will try wrap.
Defaults to 80.
diff --git a/tests/integration/__tests__/__snapshots__/plugin-options.js.snap b/tests/integration/__tests__/__snapshots__/plugin-options.js.snap
index 3f2e8148adb7..7fcf3673590a 100644
--- a/tests/integration/__tests__/__snapshots__/plugin-options.js.snap
+++ b/tests/integration/__tests__/__snapshots__/plugin-options.js.snap
@@ -3,7 +3,7 @@
exports[`include plugin's parsers to the values of the \`parser\` option\` (stderr) 1`] = `""`;
exports[`include plugin's parsers to the values of the \`parser\` option\` (stdout) 1`] = `
-"--parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|foo-parser>
+"--parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml|foo-parser>
Which parser to use.
@@ -33,6 +33,7 @@ Valid options:
html HTML
angular Angular
lwc Lightning Web Components
+ mjml MJML
foo-parser foo (plugin: ./plugin.cjs)"
`;
@@ -76,8 +77,8 @@ exports[`show external options with \`--help\` 1`] = `
--object-wrap <preserve|collapse>
How to wrap object literals.
Defaults to preserve.
-- --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc>
-+ --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|foo-parser>
+- --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml>
++ --parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml|foo-parser>
Which parser to use.
--print-width <int> The line length where Prettier will try wrap.
Defaults to 80.
diff --git a/tests/integration/__tests__/__snapshots__/schema.js.snap b/tests/integration/__tests__/__snapshots__/schema.js.snap
index ca0815883bda..a1b8700b6057 100644
--- a/tests/integration/__tests__/__snapshots__/schema.js.snap
+++ b/tests/integration/__tests__/__snapshots__/schema.js.snap
@@ -315,6 +315,12 @@ exports[`schema 1`] = `
"lwc",
],
},
+ {
+ "description": "MJML",
+ "enum": [
+ "mjml",
+ ],
+ },
{
"description": "Custom parser",
"type": "string",
diff --git a/tests/integration/__tests__/__snapshots__/support-info.js.snap b/tests/integration/__tests__/__snapshots__/support-info.js.snap
index 1055f28c3755..3b27103b484d 100644
--- a/tests/integration/__tests__/__snapshots__/support-info.js.snap
+++ b/tests/integration/__tests__/__snapshots__/support-info.js.snap
@@ -62,6 +62,9 @@ exports[`API getSupportInfo() 1`] = `
"MDX": [
"mdx",
],
+ "MJML": [
+ "mjml",
+ ],
"Markdown": [
"markdown",
],
@@ -197,6 +200,7 @@ exports[`API getSupportInfo() 1`] = `
"html",
"angular",
"lwc",
+ "mjml",
],
"default": undefined,
"type": "choice",
@@ -392,8 +396,7 @@ exports[`CLI --support-info (stdout) 1`] = `
".html.hl",
".inc",
".xht",
- ".xhtml",
- ".mjml"
+ ".xhtml"
],
"linguistLanguageId": 146,
"name": "HTML",
@@ -680,6 +683,21 @@ exports[`CLI --support-info (stdout) 1`] = `
"vscodeLanguageIds": ["mdx"],
"wrap": true
},
+ {
+ "aceMode": "html",
+ "aliases": ["MJML", "mjml"],
+ "codemirrorMimeType": "text/html",
+ "codemirrorMode": "htmlmixed",
+ "color": "#e34c26",
+ "extensions": [".mjml"],
+ "filenames": [],
+ "linguistLanguageId": 146,
+ "name": "MJML",
+ "parsers": ["mjml"],
+ "tmScope": "text.mjml.basic",
+ "type": "markup",
+ "vscodeLanguageIds": ["mjml"]
+ },
{
"aceMode": "text",
"color": "#dc3a0c",
@@ -994,7 +1012,8 @@ exports[`CLI --support-info (stdout) 1`] = `
{ "description": "Ember / Handlebars", "value": "glimmer" },
{ "description": "HTML", "value": "html" },
{ "description": "Angular", "value": "angular" },
- { "description": "Lightning Web Components", "value": "lwc" }
+ { "description": "Lightning Web Components", "value": "lwc" },
+ { "description": "MJML", "value": "mjml" }
],
"description": "Which parser to use.",
"name": "parser",
diff --git a/tests/unit/builtin-plugins.js b/tests/unit/builtin-plugins.js
index dfe3ad5ed213..31a11629d31b 100644
--- a/tests/unit/builtin-plugins.js
+++ b/tests/unit/builtin-plugins.js
@@ -39,6 +39,7 @@ test("builtin parsers", async () => {
"markdown",
"mdx",
"meriyah",
+ "mjml",
"remark",
"scss",
"typescript",
diff --git a/website/playground/codeSamples.mjs b/website/playground/codeSamples.mjs
index 865474ac5a63..662c6ce420d7 100644
--- a/website/playground/codeSamples.mjs
+++ b/website/playground/codeSamples.mjs
@@ -309,6 +309,18 @@ export default function getCodeSamples(parser) {
" </body>",
"</HTML>",
].join("\n");
+ case "mjml":
+ return [
+ "<mjml> <mj-body>",
+ " <mj-section>",
+ " <mj-column>",
+ "<mj-text> Hello World!",
+ " </mj-text>",
+ " </mj-column>",
+ " </mj-section>",
+ " </mj-body>",
+ " </mjml>",
+ ].join("\n");
case "doc-explorer":
return [
"group([",
diff --git a/website/playground/markdown.js b/website/playground/markdown.js
index f7cd649af503..a9ba759f30d1 100644
--- a/website/playground/markdown.js
+++ b/website/playground/markdown.js
@@ -56,6 +56,7 @@ function getMarkdownSyntax(options) {
return "hbs";
case "angular":
case "lwc":
+ case "mjml":
return "html";
default:
return options.parser;
diff --git a/website/playground/util.js b/website/playground/util.js
index a836b6695dfe..663444414310 100644
--- a/website/playground/util.js
+++ b/website/playground/util.js
@@ -84,6 +84,7 @@ export function getAstAutoFold(parser) {
case "angular":
case "vue":
case "lwc":
+ case "mjml":
return astAutoFold.html;
case "markdown":
case "mdx":
| diff --git a/changelog_unreleased/api/17339.md b/changelog_unreleased/api/17339.md
index 000000000000..529ee232f70d
--- /dev/null
+++ b/changelog_unreleased/api/17339.md
@@ -0,0 +1,3 @@
+#### Add `mjml` parser (#17339 by @fisker)
+
diff --git a/changelog_unreleased/mjml/.gitkeep b/changelog_unreleased/mjml/.gitkeep
index 000000000000..e69de29bb2d1
diff --git a/docs/options.md b/docs/options.md
index 113648163028..157110b60075 100644
--- a/docs/options.md
+++ b/docs/options.md
@@ -325,6 +325,7 @@ Valid options:
- `"vue"` (same parser as `"html"`, but also formats vue-specific syntax) _First available in 1.10.0_
- `"angular"` (same parser as `"html"`, but also formats angular-specific syntax via [angular-estree-parser](https://github.com/ikatyang/angular-estree-parser)) _First available in 1.15.0_
- `"lwc"` (same parser as `"html"`, but also formats LWC-specific syntax for unquoted template attributes) _First available in 1.17.0_
+- `"mjml"` (same parser as `"html"`, but also formats MJML-specific syntax) _First available in 3.6.0_
- `"yaml"` (via [yaml](https://github.com/eemeli/yaml) and [yaml-unist-parser](https://github.com/ikatyang/yaml-unist-parser)) _First available in 1.14.0_
| Default | CLI Override | API Override |
diff --git a/scripts/generate-changelog.js b/scripts/generate-changelog.js
index 9a699e66a7fc..ac58cacd3c52 100755
--- a/scripts/generate-changelog.js
+++ b/scripts/generate-changelog.js
@@ -134,6 +134,7 @@ function getSyntaxFromCategory(category) {
case "html":
case "cli":
return "sh";
diff --git a/scripts/utils/changelog-categories.js b/scripts/utils/changelog-categories.js
index a5b25175bfb5..da74b1d411f6 100644
--- a/scripts/utils/changelog-categories.js
+++ b/scripts/utils/changelog-categories.js
@@ -11,6 +11,7 @@ export const CHANGELOG_CATEGORIES = [
"json",
"less",
"lwc",
+ "mjml",
"markdown",
"mdx",
"scss",
diff --git a/scripts/utils/changelog.js b/scripts/utils/changelog.js
index 39008cbf84ff..70ff104b558f 100644
--- a/scripts/utils/changelog.js
+++ b/scripts/utils/changelog.js
@@ -22,6 +22,7 @@ export const categories = [
{ dir: "vue", title: "Vue" },
{ dir: "angular", title: "Angular" },
{ dir: "lwc", title: "LWC" },
+ { dir: "mjml", title: "MJML" },
{ dir: "handlebars", title: "Ember / Handlebars" },
{ dir: "graphql", title: "GraphQL" },
{ dir: "markdown", title: "Markdown" },
diff --git a/src/index.d.ts b/src/index.d.ts
index 7a7841ec834d..8680e32b7497 100644
--- a/src/index.d.ts
+++ b/src/index.d.ts
@@ -296,6 +296,7 @@ export type BuiltInParserName =
| "markdown"
| "mdx"
| "meriyah"
+ | "mjml"
| "scss"
| "typescript"
| "vue"
diff --git a/src/language-html/languages.evaluate.js b/src/language-html/languages.evaluate.js
index 130f2743e3c1..2dca2b7f73fd 100644
--- a/src/language-html/languages.evaluate.js
+++ b/src/language-html/languages.evaluate.js
@@ -9,13 +9,9 @@ const languages = [
extensions: [".component.html"],
- createLanguage(linguistLanguages.HTML, (data) => ({
parsers: ["html"],
vscodeLanguageIds: ["html"],
- extensions: [
- ...data.extensions,
- ".mjml", // MJML is considered XML in Linguist but it should be formatted as HTML
- ],
createLanguage(linguistLanguages.HTML, () => ({
name: "Lightning Web Components",
@@ -24,6 +20,17 @@ const languages = [
extensions: [],
+ parsers: ["mjml"],
+ extensions: [".mjml"],
+ filenames: [],
+ vscodeLanguageIds: ["mjml"],
+ aliases: ["MJML", "mjml"],
+ // https://github.com/mjmlio/vscode-mjml/blob/477f030d400fe838d29495f4a432fba57f2198b7/package.json#L242
+ tmScope: "text.mjml.basic",
+ })),
createLanguage(linguistLanguages.Vue, () => ({
parsers: ["vue"],
vscodeLanguageIds: ["vue"],
diff --git a/src/language-html/parser-html.js b/src/language-html/parser-html.js
index a88ffbb42333..57af1d01f4d1 100644
--- a/src/language-html/parser-html.js
+++ b/src/language-html/parser-html.js
@@ -28,7 +28,7 @@ import isUnknownNamespace from "./utils/is-unknown-namespace.js";
/**
* @typedef {AngularHtmlParserParseOptions & {
- * name: 'html' | 'angular' | 'vue' | 'lwc';
+ * name: 'html' | 'angular' | 'vue' | 'lwc' | 'mjml';
* normalizeTagName?: boolean;
* normalizeAttributeName?: boolean;
* shouldParseAsRawText?: (tagName: string, prefix: string, hasParent: boolean, attrs: Array<{
@@ -444,6 +444,8 @@ const HTML_PARSE_OPTIONS = {
// HTML
export const html = createParser(HTML_PARSE_OPTIONS);
+// MJML https://mjml.io/
+export const mjml = createParser({ ...HTML_PARSE_OPTIONS, name: "mjml" });
// Angular
export const angular = createParser({ name: "angular" });
// Vue
diff --git a/src/main/core-options.evaluate.js b/src/main/core-options.evaluate.js
index b1b8ae5e7fe0..921b5c5490cf 100644
--- a/src/main/core-options.evaluate.js
+++ b/src/main/core-options.evaluate.js
@@ -128,6 +128,7 @@ const options = {
{ value: "html", description: "HTML" },
{ value: "angular", description: "Angular" },
{ value: "lwc", description: "Lightning Web Components" },
+ { value: "mjml", description: "MJML" },
plugins: {
diff --git a/src/plugins/builtin-plugins-proxy.js b/src/plugins/builtin-plugins-proxy.js
index 75d30e5b826a..8a47a5754449 100644
--- a/src/plugins/builtin-plugins-proxy.js
+++ b/src/plugins/builtin-plugins-proxy.js
@@ -117,7 +117,7 @@ export const { parsers, printers } = createParsersAndPrinters([
importPlugin: () => import("./html.js"),
- parsers: ["html", "angular", "vue", "lwc"],
printers: ["html"],
diff --git a/tests/config/utils/check-parsers.js b/tests/config/utils/check-parsers.js
index 238898b84a39..02f3717fd514 100644
--- a/tests/config/utils/check-parsers.js
+++ b/tests/config/utils/check-parsers.js
@@ -50,7 +50,7 @@ const categoryParsers = new Map([
"html",
{ parsers: ["html"], verifyParsers: [], extensions: [".html", ".svg"] },
],
- ["mjml", { parsers: ["html"], verifyParsers: [], extensions: [".mjml"] }],
+ ["mjml", { parsers: ["mjml"], verifyParsers: [], extensions: [".mjml"] }],
[
"js",
diff --git a/tests/dts/unit/cases/parsers.ts b/tests/dts/unit/cases/parsers.ts
index 6157ab57739c..e3a90b22af2a 100644
--- a/tests/dts/unit/cases/parsers.ts
+++ b/tests/dts/unit/cases/parsers.ts
@@ -82,6 +82,7 @@ prettierPluginGlimmer.parsers.glimmer.parse("code", options);
prettierPluginHtml.parsers.html.parse("code", options);
prettierPluginHtml.parsers.vue.parse("code", options);
prettierPluginHtml.parsers.lwc.parse("code", options);
+prettierPluginHtml.parsers.mjml.parse("code", options);
prettierPluginHtml.parsers.angular.parse("code", options);
prettierPluginYaml.parsers.yaml.parse("code", options);
diff --git a/tests/format/mjml/mjml/__snapshots__/format.test.js.snap b/tests/format/mjml/mjml/__snapshots__/format.test.js.snap
index 297ff67b0e76..eb7bd37603d7 100644
--- a/tests/format/mjml/mjml/__snapshots__/format.test.js.snap
+++ b/tests/format/mjml/mjml/__snapshots__/format.test.js.snap
@@ -2,7 +2,7 @@
exports[`empty.mjml format 1`] = `
@@ -15,7 +15,7 @@ printWidth: 80
exports[`head.mjml format 1`] = `
diff --git a/tests/format/mjml/mjml/format.test.js b/tests/format/mjml/mjml/format.test.js
index 88a427864598..5af041ec4149 100644
--- a/tests/format/mjml/mjml/format.test.js
+++ b/tests/format/mjml/mjml/format.test.js
@@ -1 +1 @@
+runFormatTest(import.meta, ["mjml"]);
diff --git a/tests/integration/__tests__/__snapshots__/early-exit.js.snap b/tests/integration/__tests__/__snapshots__/early-exit.js.snap
index df4b673437a0..081db39890bc 100644
--- a/tests/integration/__tests__/__snapshots__/early-exit.js.snap
+++ b/tests/integration/__tests__/__snapshots__/early-exit.js.snap
@@ -66,7 +66,7 @@ Format options:
@@ -161,7 +161,7 @@ exports[`show version with --version (write) 1`] = `[]`;
exports[`show warning with --help not-found (typo) (stderr) 1`] = `"[warn] Unknown flag "parserr", did you mean "parser"?"`;
exports[`show warning with --help not-found (typo) (stdout) 1`] = `
@@ -190,7 +190,8 @@ Valid options:
exports[`show warning with --help not-found (typo) (write) 1`] = `[]`;
@@ -237,7 +238,7 @@ Format options:
diff --git a/tests/integration/__tests__/__snapshots__/help-options.js.snap b/tests/integration/__tests__/__snapshots__/help-options.js.snap
index f977b7e65e15..7181ae90044a 100644
--- a/tests/integration/__tests__/__snapshots__/help-options.js.snap
+++ b/tests/integration/__tests__/__snapshots__/help-options.js.snap
@@ -438,7 +438,7 @@ exports[`show detailed usage with --help object-wrap (write) 1`] = `[]`;
exports[`show detailed usage with --help parser (stderr) 1`] = `""`;
exports[`show detailed usage with --help parser (stdout) 1`] = `
@@ -467,7 +467,8 @@ Valid options:
exports[`show detailed usage with --help parser (write) 1`] = `[]`;
diff --git a/tests/integration/__tests__/__snapshots__/plugin-options-string.js.snap b/tests/integration/__tests__/__snapshots__/plugin-options-string.js.snap
index 592c8260798a..ab661da8b15f 100644
--- a/tests/integration/__tests__/__snapshots__/plugin-options-string.js.snap
+++ b/tests/integration/__tests__/__snapshots__/plugin-options-string.js.snap
@@ -33,8 +33,8 @@ exports[`show external options with \`--help\` 1`] = `
diff --git a/tests/integration/__tests__/__snapshots__/plugin-options.js.snap b/tests/integration/__tests__/__snapshots__/plugin-options.js.snap
index 3f2e8148adb7..7fcf3673590a 100644
--- a/tests/integration/__tests__/__snapshots__/plugin-options.js.snap
+++ b/tests/integration/__tests__/__snapshots__/plugin-options.js.snap
@@ -3,7 +3,7 @@
exports[`include plugin's parsers to the values of the \`parser\` option\` (stderr) 1`] = `""`;
exports[`include plugin's parsers to the values of the \`parser\` option\` (stdout) 1`] = `
+"--parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|mjml|foo-parser>
@@ -33,6 +33,7 @@ Valid options:
lwc Lightning Web Components
+ mjml MJML
foo-parser foo (plugin: ./plugin.cjs)"
@@ -76,8 +77,8 @@ exports[`show external options with \`--help\` 1`] = `
diff --git a/tests/integration/__tests__/__snapshots__/schema.js.snap b/tests/integration/__tests__/__snapshots__/schema.js.snap
index ca0815883bda..a1b8700b6057 100644
--- a/tests/integration/__tests__/__snapshots__/schema.js.snap
+++ b/tests/integration/__tests__/__snapshots__/schema.js.snap
@@ -315,6 +315,12 @@ exports[`schema 1`] = `
"lwc",
],
},
+ {
+ "description": "MJML",
+ "enum": [
+ "mjml",
+ ],
+ },
{
"description": "Custom parser",
"type": "string",
diff --git a/tests/integration/__tests__/__snapshots__/support-info.js.snap b/tests/integration/__tests__/__snapshots__/support-info.js.snap
index 1055f28c3755..3b27103b484d 100644
--- a/tests/integration/__tests__/__snapshots__/support-info.js.snap
+++ b/tests/integration/__tests__/__snapshots__/support-info.js.snap
@@ -62,6 +62,9 @@ exports[`API getSupportInfo() 1`] = `
"MDX": [
+ "MJML": [
+ ],
"Markdown": [
@@ -197,6 +200,7 @@ exports[`API getSupportInfo() 1`] = `
"html",
"angular",
"lwc",
+ "mjml",
"default": undefined,
"type": "choice",
@@ -392,8 +396,7 @@ exports[`CLI --support-info (stdout) 1`] = `
".html.hl",
".inc",
".xht",
- ".xhtml",
- ".mjml"
"linguistLanguageId": 146,
"name": "HTML",
@@ -680,6 +683,21 @@ exports[`CLI --support-info (stdout) 1`] = `
"vscodeLanguageIds": ["mdx"],
"wrap": true
},
+ {
+ "aceMode": "html",
+ "aliases": ["MJML", "mjml"],
+ "codemirrorMimeType": "text/html",
+ "codemirrorMode": "htmlmixed",
+ "color": "#e34c26",
+ "extensions": [".mjml"],
+ "filenames": [],
+ "linguistLanguageId": 146,
+ "name": "MJML",
+ "parsers": ["mjml"],
+ "tmScope": "text.mjml.basic",
+ "type": "markup",
+ "vscodeLanguageIds": ["mjml"]
+ },
"aceMode": "text",
"color": "#dc3a0c",
@@ -994,7 +1012,8 @@ exports[`CLI --support-info (stdout) 1`] = `
{ "description": "Ember / Handlebars", "value": "glimmer" },
{ "description": "HTML", "value": "html" },
{ "description": "Angular", "value": "angular" },
- { "description": "Lightning Web Components", "value": "lwc" }
+ { "description": "Lightning Web Components", "value": "lwc" },
+ { "description": "MJML", "value": "mjml" }
"description": "Which parser to use.",
"name": "parser",
diff --git a/tests/unit/builtin-plugins.js b/tests/unit/builtin-plugins.js
index dfe3ad5ed213..31a11629d31b 100644
--- a/tests/unit/builtin-plugins.js
+++ b/tests/unit/builtin-plugins.js
@@ -39,6 +39,7 @@ test("builtin parsers", async () => {
"meriyah",
"remark",
"scss",
"typescript",
diff --git a/website/playground/codeSamples.mjs b/website/playground/codeSamples.mjs
index 865474ac5a63..662c6ce420d7 100644
--- a/website/playground/codeSamples.mjs
+++ b/website/playground/codeSamples.mjs
@@ -309,6 +309,18 @@ export default function getCodeSamples(parser) {
" </body>",
"</HTML>",
].join("\n");
+ return [
+ "<mjml> <mj-body>",
+ " <mj-column>",
+ " </mj-text>",
+ " </mj-column>",
+ " </mj-section>",
+ " </mj-body>",
+ " </mjml>",
+ ].join("\n");
case "doc-explorer":
return [
"group([",
diff --git a/website/playground/markdown.js b/website/playground/markdown.js
index f7cd649af503..a9ba759f30d1 100644
--- a/website/playground/markdown.js
+++ b/website/playground/markdown.js
@@ -56,6 +56,7 @@ function getMarkdownSyntax(options) {
return "hbs";
default:
return options.parser;
diff --git a/website/playground/util.js b/website/playground/util.js
index a836b6695dfe..663444414310 100644
--- a/website/playground/util.js
+++ b/website/playground/util.js
@@ -84,6 +84,7 @@ export function getAstAutoFold(parser) {
case "vue":
return astAutoFold.html;
case "markdown":
case "mdx": | [
"+We already support [MJML](https://mjml.io/) in previous version with `html` parser, in order to distinguish MJML-specific a new `mjml` parser added.",
"+ name: \"MJML\",",
"+ // https://github.com/mjmlio/vscode-mjml/blob/477f030d400fe838d29495f4a432fba57f2198b7/package.json#L226-L238",
"+ parsers: [\"html\", \"angular\", \"vue\", \"lwc\", \"mjml\"],",
"-runFormatTest(import.meta, [\"html\"]);",
"-\"--parser <flow|babel|babel-flow|babel-ts|typescript|acorn|espree|meriyah|css|less|scss|json|json5|jsonc|json-stringify|graphql|markdown|mdx|vue|yaml|glimmer|html|angular|lwc|foo-parser>",
"+ \".xhtml\"",
"+ \" <mj-section>\",",
"+ \"<mj-text> Hello World!\","
] | [
8,
96,
100,
152,
208,
297,
366,
425,
427
] | {
"additions": 87,
"author": "fisker",
"deletions": 25,
"html_url": "https://github.com/prettier/prettier/pull/17339",
"issue_id": 17339,
"merged_at": "2025-04-14T00:12:53Z",
"omission_probability": 0.1,
"pr_number": 17339,
"repo": "prettier/prettier",
"title": "Add `mjml` parser",
"total_changes": 112
} |
181 | diff --git a/src/config/prettier-config/loaders.js b/src/config/prettier-config/loaders.js
index 10c15fb62521..22f165bda0dd 100644
--- a/src/config/prettier-config/loaders.js
+++ b/src/config/prettier-config/loaders.js
@@ -20,7 +20,7 @@ async function importModuleDefault(file) {
return module.default;
}
-async function readPackageJson(file) {
+async function readBunPackageJson(file) {
try {
return await readJson(file);
} catch (error) {
@@ -28,22 +28,25 @@ async function readPackageJson(file) {
// Bun supports comments and trialing comma in `package.json`
// And it can load via `import()`
// https://bun.sh/blog/bun-v1.2#jsonc-support-in-package-json
- if (process.versions.bun) {
- try {
- return await importModuleDefault(file);
- } catch {
- // No op
- }
+ try {
+ return await importModuleDefault(file);
+ } catch {
+ // No op
}
throw error;
}
}
-async function loadConfigFromPackageJson(file) {
- const { prettier } = await readPackageJson(file);
- return prettier;
-}
+const loadConfigFromPackageJson = process.versions.bun
+ ? async function loadConfigFromBunPackageJson(file) {
+ const { prettier } = await readBunPackageJson(file);
+ return prettier;
+ }
+ : async function loadConfigFromPackageJson(file) {
+ const { prettier } = await readJson(file);
+ return prettier;
+ };
async function loadConfigFromPackageYaml(file) {
const { prettier } = await loadYaml(file);
@@ -60,25 +63,29 @@ async function loadYaml(file) {
}
}
+async function loadToml(file) {
+ const content = await readFile(file);
+ try {
+ return parseToml(content);
+ } catch (/** @type {any} */ error) {
+ error.message = `TOML Error in ${file}:\n${error.message}`;
+ throw error;
+ }
+}
+
+async function loadJson5(file) {
+ const content = await readFile(file);
+ try {
+ return json5.parse(content);
+ } catch (/** @type {any} */ error) {
+ error.message = `JSON5 Error in ${file}:\n${error.message}`;
+ throw error;
+ }
+}
+
const loaders = {
- async ".toml"(file) {
- const content = await readFile(file);
- try {
- return parseToml(content);
- } catch (/** @type {any} */ error) {
- error.message = `TOML Error in ${file}:\n${error.message}`;
- throw error;
- }
- },
- async ".json5"(file) {
- const content = await readFile(file);
- try {
- return json5.parse(content);
- } catch (/** @type {any} */ error) {
- error.message = `JSON5 Error in ${file}:\n${error.message}`;
- throw error;
- }
- },
+ ".toml": loadToml,
+ ".json5": loadJson5,
".json": readJson,
".js": importModuleDefault,
".mjs": importModuleDefault,
| diff --git a/src/config/prettier-config/loaders.js b/src/config/prettier-config/loaders.js
index 10c15fb62521..22f165bda0dd 100644
--- a/src/config/prettier-config/loaders.js
+++ b/src/config/prettier-config/loaders.js
@@ -20,7 +20,7 @@ async function importModuleDefault(file) {
return module.default;
-async function readPackageJson(file) {
+async function readBunPackageJson(file) {
try {
return await readJson(file);
} catch (error) {
@@ -28,22 +28,25 @@ async function readPackageJson(file) {
// Bun supports comments and trialing comma in `package.json`
// And it can load via `import()`
// https://bun.sh/blog/bun-v1.2#jsonc-support-in-package-json
- if (process.versions.bun) {
- try {
- } catch {
- // No op
- }
+ try {
+ return await importModuleDefault(file);
+ } catch {
+ // No op
}
throw error;
-async function loadConfigFromPackageJson(file) {
- const { prettier } = await readPackageJson(file);
- return prettier;
-}
+const loadConfigFromPackageJson = process.versions.bun
+ const { prettier } = await readBunPackageJson(file);
+ }
+ const { prettier } = await readJson(file);
+ };
async function loadConfigFromPackageYaml(file) {
const { prettier } = await loadYaml(file);
@@ -60,25 +63,29 @@ async function loadYaml(file) {
+async function loadToml(file) {
+ error.message = `TOML Error in ${file}:\n${error.message}`;
+async function loadJson5(file) {
+ return json5.parse(content);
+ error.message = `JSON5 Error in ${file}:\n${error.message}`;
const loaders = {
- async ".toml"(file) {
- return parseToml(content);
- error.message = `TOML Error in ${file}:\n${error.message}`;
- async ".json5"(file) {
- return json5.parse(content);
+ ".toml": loadToml,
+ ".json5": loadJson5,
".json": readJson,
".js": importModuleDefault,
".mjs": importModuleDefault, | [
"- return await importModuleDefault(file);",
"+ ? async function loadConfigFromBunPackageJson(file) {",
"+ : async function loadConfigFromPackageJson(file) {",
"+ return parseToml(content);",
"- error.message = `JSON5 Error in ${file}:\\n${error.message}`;"
] | [
19,
38,
42,
56,
88
] | {
"additions": 36,
"author": "fisker",
"deletions": 29,
"html_url": "https://github.com/prettier/prettier/pull/17343",
"issue_id": 17343,
"merged_at": "2025-04-14T00:11:11Z",
"omission_probability": 0.1,
"pr_number": 17343,
"repo": "prettier/prettier",
"title": "Minor improvement to config loader",
"total_changes": 65
} |
182 | diff --git a/changelog_unreleased/angular/17280.md b/changelog_unreleased/angular/17280.md
new file mode 100644
index 000000000000..567e92c8deb5
--- /dev/null
+++ b/changelog_unreleased/angular/17280.md
@@ -0,0 +1,13 @@
+#### Remove extra colon after `track` in angular `@for` control-flow (#17280 by @claudio-herger)
+
+<!-- prettier-ignore -->
+```angular
+// Input
+@for (item of items; let i = $index; let count = $count; track block) {}
+
+// Prettier stable
+@for (item of items; let i = $index; let count = $count; track: block) {}
+
+// Prettier main
+@for (item of items; let i = $index; let count = $count; track block) {}
+```
diff --git a/src/language-js/print/angular.js b/src/language-js/print/angular.js
index cc730d05468c..923373c877e2 100644
--- a/src/language-js/print/angular.js
+++ b/src/language-js/print/angular.js
@@ -62,11 +62,12 @@ function printAngular(path, options, print) {
// https://github.com/prettier/angular-estree-parser/issues/267
const shouldNotPrintColon =
isNgForOf(path) ||
+ isNgForOfTrack(path) ||
(((index === 1 &&
(node.key.name === "then" ||
node.key.name === "else" ||
node.key.name === "as")) ||
- ((index === 2 || index === 3) &&
+ (index === 2 &&
((node.key.name === "else" &&
parent.body[index - 1].type === "NGMicrosyntaxKeyedExpression" &&
parent.body[index - 1].key.name === "then") ||
@@ -100,6 +101,16 @@ function isNgForOf({ node, index }) {
);
}
+function isNgForOfTrack(path) {
+ const { node } = path;
+ return (
+ path.parent.body[1].key.name === "of" &&
+ node.type === "NGMicrosyntaxKeyedExpression" &&
+ node.key.name === "track" &&
+ node.key.type === "NGMicrosyntaxKey"
+ );
+}
+
const hasSideEffect = createTypeCheckFunction([
"CallExpression",
"OptionalCallExpression",
diff --git a/tests/format/angular/control-flow/__snapshots__/format.test.js.snap b/tests/format/angular/control-flow/__snapshots__/format.test.js.snap
index 9aff6695fbc9..a8a352bcdd5c 100644
--- a/tests/format/angular/control-flow/__snapshots__/format.test.js.snap
+++ b/tests/format/angular/control-flow/__snapshots__/format.test.js.snap
@@ -291,6 +291,12 @@ item of
<div *ngFor="item of items; let i = $index; track block"></div>
</div>
+<div>
+ @for (item of items; let i = $index; let count = $count; track block) {}
+
+ <div *ngFor="item of items; let i = $index; let count = $count; track block"></div>
+</div>
+
=====================================output=====================================
<ul>
@for (let item of items; index as i; trackBy: trackByFn) {
@@ -344,6 +350,14 @@ item of
<div *ngFor="item of items; let i = $index; track block"></div>
</div>
+<div>
+ @for (item of items; let i = $index; let count = $count; track block) {}
+
+ <div
+ *ngFor="item of items; let i = $index; let count = $count; track block"
+ ></div>
+</div>
+
================================================================================
`;
diff --git a/tests/format/angular/control-flow/for.html b/tests/format/angular/control-flow/for.html
index 5d4bb036283e..62f7c1b590ef 100644
--- a/tests/format/angular/control-flow/for.html
+++ b/tests/format/angular/control-flow/for.html
@@ -58,3 +58,9 @@
<div *ngFor="item of items; let i = $index; track block"></div>
</div>
+
+<div>
+ @for (item of items; let i = $index; let count = $count; track block) {}
+
+ <div *ngFor="item of items; let i = $index; let count = $count; track block"></div>
+</div>
| diff --git a/changelog_unreleased/angular/17280.md b/changelog_unreleased/angular/17280.md
new file mode 100644
index 000000000000..567e92c8deb5
--- /dev/null
+++ b/changelog_unreleased/angular/17280.md
@@ -0,0 +1,13 @@
+#### Remove extra colon after `track` in angular `@for` control-flow (#17280 by @claudio-herger)
+<!-- prettier-ignore -->
+```angular
+// Input
+// Prettier stable
+@for (item of items; let i = $index; let count = $count; track: block) {}
+// Prettier main
+```
diff --git a/src/language-js/print/angular.js b/src/language-js/print/angular.js
index cc730d05468c..923373c877e2 100644
--- a/src/language-js/print/angular.js
+++ b/src/language-js/print/angular.js
@@ -62,11 +62,12 @@ function printAngular(path, options, print) {
// https://github.com/prettier/angular-estree-parser/issues/267
const shouldNotPrintColon =
isNgForOf(path) ||
+ isNgForOfTrack(path) ||
(((index === 1 &&
(node.key.name === "then" ||
node.key.name === "else" ||
node.key.name === "as")) ||
- ((index === 2 || index === 3) &&
((node.key.name === "else" &&
parent.body[index - 1].type === "NGMicrosyntaxKeyedExpression" &&
parent.body[index - 1].key.name === "then") ||
@@ -100,6 +101,16 @@ function isNgForOf({ node, index }) {
);
}
+function isNgForOfTrack(path) {
+ const { node } = path;
+ return (
+ path.parent.body[1].key.name === "of" &&
+ node.type === "NGMicrosyntaxKeyedExpression" &&
+ node.key.name === "track" &&
+ node.key.type === "NGMicrosyntaxKey"
+ );
+}
const hasSideEffect = createTypeCheckFunction([
"CallExpression",
"OptionalCallExpression",
diff --git a/tests/format/angular/control-flow/__snapshots__/format.test.js.snap b/tests/format/angular/control-flow/__snapshots__/format.test.js.snap
index 9aff6695fbc9..a8a352bcdd5c 100644
--- a/tests/format/angular/control-flow/__snapshots__/format.test.js.snap
+++ b/tests/format/angular/control-flow/__snapshots__/format.test.js.snap
@@ -291,6 +291,12 @@ item of
=====================================output=====================================
<ul>
@for (let item of items; index as i; trackBy: trackByFn) {
@@ -344,6 +350,14 @@ item of
+ <div
+ *ngFor="item of items; let i = $index; let count = $count; track block"
================================================================================
`;
diff --git a/tests/format/angular/control-flow/for.html b/tests/format/angular/control-flow/for.html
index 5d4bb036283e..62f7c1b590ef 100644
--- a/tests/format/angular/control-flow/for.html
+++ b/tests/format/angular/control-flow/for.html
@@ -58,3 +58,9 @@ | [
"+ (index === 2 &&",
"+ ></div>"
] | [
33,
80
] | {
"additions": 45,
"author": "claudio-herger",
"deletions": 1,
"html_url": "https://github.com/prettier/prettier/pull/17280",
"issue_id": 17280,
"merged_at": "2025-04-14T00:10:04Z",
"omission_probability": 0.1,
"pr_number": 17280,
"repo": "prettier/prettier",
"title": "Remove extra colon after `track` in angular `@for` control-flow",
"total_changes": 46
} |
183 | diff --git a/src/language-graphql/pragma.js b/src/language-graphql/pragma.js
index d00614299f5f..449d93781925 100644
--- a/src/language-graphql/pragma.js
+++ b/src/language-graphql/pragma.js
@@ -1,9 +1,14 @@
+import {
+ FORMAT_PRAGMA_TO_INSERT,
+ GRAPHQL_HAS_PRAGMA_REGEXP,
+} from "../utils/pragma/pragma.evaluate.js";
+
function hasPragma(text) {
- return /^\s*#[^\S\n]*@(?:format|prettier)\s*(?:\n|$)/u.test(text);
+ return GRAPHQL_HAS_PRAGMA_REGEXP.test(text);
}
function insertPragma(text) {
- return "# @format\n\n" + text;
+ return `# @${FORMAT_PRAGMA_TO_INSERT}\n\n${text}`;
}
export { hasPragma, insertPragma };
diff --git a/src/language-html/pragma.js b/src/language-html/pragma.js
index dafdf472ad9d..198c92e5e02d 100644
--- a/src/language-html/pragma.js
+++ b/src/language-html/pragma.js
@@ -1,9 +1,15 @@
+import {
+ FORMAT_PRAGMA_TO_INSERT,
+ HTML_HAS_PRAGMA_REGEXP,
+} from "../utils/pragma/pragma.evaluate.js";
+
function hasPragma(text) {
- return /^\s*<!--\s*@(?:format|prettier)\s*-->/u.test(text);
+ // FIXME
+ return HTML_HAS_PRAGMA_REGEXP.test(text);
}
function insertPragma(text) {
- return "<!-- @format -->\n\n" + text;
+ return `<!-- @${FORMAT_PRAGMA_TO_INSERT} -->\n\n${text}`;
}
export { hasPragma, insertPragma };
diff --git a/src/language-js/pragma.js b/src/language-js/pragma.js
index c10f707fc52d..62b669526968 100644
--- a/src/language-js/pragma.js
+++ b/src/language-js/pragma.js
@@ -1,5 +1,9 @@
import { extract, parseWithComments, print, strip } from "jest-docblock";
import { normalizeEndOfLine } from "../common/end-of-line.js";
+import {
+ FORMAT_PRAGMA_TO_INSERT,
+ FORMAT_PRAGMAS,
+} from "../utils/pragma/pragma.evaluate.js";
import getShebang from "./utils/get-shebang.js";
function parseDocBlock(text) {
@@ -16,7 +20,7 @@ function parseDocBlock(text) {
function hasPragma(text) {
const { pragmas } = parseDocBlock(text);
- return Object.hasOwn(pragmas, "prettier") || Object.hasOwn(pragmas, "format");
+ return FORMAT_PRAGMAS.some((pragma) => Object.hasOwn(pragmas, pragma));
}
function insertPragma(originalText) {
@@ -25,7 +29,7 @@ function insertPragma(originalText) {
let docBlock = print({
pragmas: {
- format: "",
+ [FORMAT_PRAGMA_TO_INSERT]: "",
...pragmas,
},
comments: comments.trimStart(),
diff --git a/src/language-yaml/pragma.js b/src/language-yaml/pragma.js
index a8d33105d46b..e868d3089a00 100644
--- a/src/language-yaml/pragma.js
+++ b/src/language-yaml/pragma.js
@@ -1,13 +1,21 @@
+import {
+ FORMAT_PRAGMA_TO_INSERT,
+ YAML_HAS_PRAGMA_REGEXP,
+ YAML_IS_PRAGMA_REGEXP,
+} from "../utils/pragma/pragma.evaluate.js";
+
function isPragma(text) {
- return /^\s*@(?:prettier|format)\s*$/u.test(text);
+ // FIXME
+ return YAML_IS_PRAGMA_REGEXP.test(text);
}
function hasPragma(text) {
- return /^\s*#[^\S\n]*@(?:prettier|format)\s*?(?:\n|$)/u.test(text);
+ // FIXME
+ return YAML_HAS_PRAGMA_REGEXP.test(text);
}
function insertPragma(text) {
- return `# @format\n\n${text}`;
+ return `# @${FORMAT_PRAGMA_TO_INSERT}\n\n${text}`;
}
export { hasPragma, insertPragma, isPragma };
diff --git a/src/utils/pragma/pragma.evaluate.js b/src/utils/pragma/pragma.evaluate.js
new file mode 100644
index 000000000000..9e7150f8ba99
--- /dev/null
+++ b/src/utils/pragma/pragma.evaluate.js
@@ -0,0 +1,44 @@
+import assert from "node:assert";
+
+export const FORMAT_PRAGMAS = ["format", "prettier"];
+export const FORMAT_PRAGMA_TO_INSERT = FORMAT_PRAGMAS[0];
+
+// Regular expressions put in this file so they can be evaluate
+
+// This exists because the regexp was rewrite from existing, feel free to remove when updating them
+const assertRegexpEqual = (regexpA, regexpB) => {
+ assert.ok(regexpA.source, regexpB.source);
+};
+
+export const YAML_IS_PRAGMA_REGEXP = new RegExp(
+ String.raw`^\s*@(?:${FORMAT_PRAGMAS.join("|")})\s*$`,
+ "u",
+);
+assertRegexpEqual(YAML_IS_PRAGMA_REGEXP, /^\s*@(?:prettier|format)\s*$/u);
+
+export const YAML_HAS_PRAGMA_REGEXP = new RegExp(
+ String.raw`^\s*#[^\S\n]*@(?:${FORMAT_PRAGMAS.join("|")})\s*?(?:\n|$)`,
+ "u",
+);
+assertRegexpEqual(
+ YAML_HAS_PRAGMA_REGEXP,
+ /^\s*#[^\S\n]*@(?:prettier|format)\s*?(?:\n|$)/u,
+);
+
+export const GRAPHQL_HAS_PRAGMA_REGEXP = new RegExp(
+ String.raw`^\s*#[^\S\n]*@(?:${FORMAT_PRAGMAS.join("|")})\s*(?:\n|$)`,
+ "u",
+);
+assertRegexpEqual(
+ GRAPHQL_HAS_PRAGMA_REGEXP,
+ /^\s*#[^\S\n]*@(?:format|prettier)\s*(?:\n|$)/u,
+);
+
+export const HTML_HAS_PRAGMA_REGEXP = new RegExp(
+ String.raw`^\s*<!--\s*@(?:${FORMAT_PRAGMAS.join("|")})\s*-->`,
+ "u",
+);
+assertRegexpEqual(
+ HTML_HAS_PRAGMA_REGEXP,
+ /^\s*<!--\s*@(?:format|prettier)\s*-->/u,
+);
| diff --git a/src/language-graphql/pragma.js b/src/language-graphql/pragma.js
index d00614299f5f..449d93781925 100644
--- a/src/language-graphql/pragma.js
+++ b/src/language-graphql/pragma.js
@@ -1,9 +1,14 @@
- return /^\s*#[^\S\n]*@(?:format|prettier)\s*(?:\n|$)/u.test(text);
+ return GRAPHQL_HAS_PRAGMA_REGEXP.test(text);
- return "# @format\n\n" + text;
diff --git a/src/language-html/pragma.js b/src/language-html/pragma.js
index dafdf472ad9d..198c92e5e02d 100644
--- a/src/language-html/pragma.js
+++ b/src/language-html/pragma.js
@@ -1,9 +1,15 @@
+ return HTML_HAS_PRAGMA_REGEXP.test(text);
- return "<!-- @format -->\n\n" + text;
+ return `<!-- @${FORMAT_PRAGMA_TO_INSERT} -->\n\n${text}`;
diff --git a/src/language-js/pragma.js b/src/language-js/pragma.js
index c10f707fc52d..62b669526968 100644
--- a/src/language-js/pragma.js
+++ b/src/language-js/pragma.js
@@ -1,5 +1,9 @@
import { extract, parseWithComments, print, strip } from "jest-docblock";
import { normalizeEndOfLine } from "../common/end-of-line.js";
+ FORMAT_PRAGMAS,
import getShebang from "./utils/get-shebang.js";
function parseDocBlock(text) {
@@ -16,7 +20,7 @@ function parseDocBlock(text) {
const { pragmas } = parseDocBlock(text);
- return Object.hasOwn(pragmas, "prettier") || Object.hasOwn(pragmas, "format");
+ return FORMAT_PRAGMAS.some((pragma) => Object.hasOwn(pragmas, pragma));
function insertPragma(originalText) {
@@ -25,7 +29,7 @@ function insertPragma(originalText) {
let docBlock = print({
pragmas: {
- format: "",
+ [FORMAT_PRAGMA_TO_INSERT]: "",
...pragmas,
},
comments: comments.trimStart(),
diff --git a/src/language-yaml/pragma.js b/src/language-yaml/pragma.js
index a8d33105d46b..e868d3089a00 100644
--- a/src/language-yaml/pragma.js
+++ b/src/language-yaml/pragma.js
@@ -1,13 +1,21 @@
+ YAML_IS_PRAGMA_REGEXP,
function isPragma(text) {
+ return YAML_IS_PRAGMA_REGEXP.test(text);
- return /^\s*#[^\S\n]*@(?:prettier|format)\s*?(?:\n|$)/u.test(text);
+ return YAML_HAS_PRAGMA_REGEXP.test(text);
- return `# @format\n\n${text}`;
export { hasPragma, insertPragma, isPragma };
diff --git a/src/utils/pragma/pragma.evaluate.js b/src/utils/pragma/pragma.evaluate.js
new file mode 100644
index 000000000000..9e7150f8ba99
--- /dev/null
+++ b/src/utils/pragma/pragma.evaluate.js
@@ -0,0 +1,44 @@
+import assert from "node:assert";
+export const FORMAT_PRAGMAS = ["format", "prettier"];
+export const FORMAT_PRAGMA_TO_INSERT = FORMAT_PRAGMAS[0];
+// Regular expressions put in this file so they can be evaluate
+// This exists because the regexp was rewrite from existing, feel free to remove when updating them
+const assertRegexpEqual = (regexpA, regexpB) => {
+ assert.ok(regexpA.source, regexpB.source);
+};
+export const YAML_IS_PRAGMA_REGEXP = new RegExp(
+ String.raw`^\s*@(?:${FORMAT_PRAGMAS.join("|")})\s*$`,
+assertRegexpEqual(YAML_IS_PRAGMA_REGEXP, /^\s*@(?:prettier|format)\s*$/u);
+export const YAML_HAS_PRAGMA_REGEXP = new RegExp(
+ /^\s*#[^\S\n]*@(?:prettier|format)\s*?(?:\n|$)/u,
+export const GRAPHQL_HAS_PRAGMA_REGEXP = new RegExp(
+ String.raw`^\s*#[^\S\n]*@(?:${FORMAT_PRAGMAS.join("|")})\s*(?:\n|$)`,
+ /^\s*#[^\S\n]*@(?:format|prettier)\s*(?:\n|$)/u,
+export const HTML_HAS_PRAGMA_REGEXP = new RegExp(
+ String.raw`^\s*<!--\s*@(?:${FORMAT_PRAGMAS.join("|")})\s*-->`,
+ /^\s*<!--\s*@(?:format|prettier)\s*-->/u, | [
"- return /^\\s*<!--\\s*@(?:format|prettier)\\s*-->/u.test(text);",
"- return /^\\s*@(?:prettier|format)\\s*$/u.test(text);",
"+ String.raw`^\\s*#[^\\S\\n]*@(?:${FORMAT_PRAGMAS.join(\"|\")})\\s*?(?:\\n|$)`,"
] | [
32,
87,
129
] | {
"additions": 76,
"author": "fisker",
"deletions": 9,
"html_url": "https://github.com/prettier/prettier/pull/17346",
"issue_id": 17346,
"merged_at": "2025-04-12T18:44:26Z",
"omission_probability": 0.1,
"pr_number": 17346,
"repo": "prettier/prettier",
"title": "Put pragma related code together",
"total_changes": 85
} |
184 | diff --git a/website/package.json b/website/package.json
index 76ed524cf894..a5777e2e141d 100644
--- a/website/package.json
+++ b/website/package.json
@@ -35,7 +35,7 @@
"@vitejs/plugin-react": "4.3.4",
"concurrently": "9.1.2",
"js-yaml": "4.1.0",
- "vite": "6.2.5"
+ "vite": "6.2.6"
},
"browserslist": {
"production": [
diff --git a/website/yarn.lock b/website/yarn.lock
index 6ee9785240c0..e7f28b1aaf28 100644
--- a/website/yarn.lock
+++ b/website/yarn.lock
@@ -12311,7 +12311,7 @@ __metadata:
react-dom: "npm:18.3.1"
react-markdown: "npm:10.1.0"
react-tweet: "npm:3.2.2"
- vite: "npm:6.2.5"
+ vite: "npm:6.2.6"
languageName: unknown
linkType: soft
@@ -13628,9 +13628,9 @@ __metadata:
languageName: node
linkType: hard
-"vite@npm:6.2.5":
- version: 6.2.5
- resolution: "vite@npm:6.2.5"
+"vite@npm:6.2.6":
+ version: 6.2.6
+ resolution: "vite@npm:6.2.6"
dependencies:
esbuild: "npm:^0.25.0"
fsevents: "npm:~2.3.3"
@@ -13676,7 +13676,7 @@ __metadata:
optional: true
bin:
vite: bin/vite.js
- checksum: 10/354023589439e7e2bcb77af79d24cd06ce20cfc48b409e663c44e515b373b89eb8f29362223eac16a3ff080d3114e40bc5df158372279d92ad03eb270f9e9762
+ checksum: 10/d8fb01a190e31fcf2189e028aed444d68255b5397d5e2c52fa73f8a0de0b052b06fbbe3793c88e7992f4297832336a23cf8bec14c88b9c2ef8aa0bce98219e50
languageName: node
linkType: hard
| diff --git a/website/package.json b/website/package.json
index 76ed524cf894..a5777e2e141d 100644
--- a/website/package.json
+++ b/website/package.json
@@ -35,7 +35,7 @@
"@vitejs/plugin-react": "4.3.4",
"concurrently": "9.1.2",
"js-yaml": "4.1.0",
- "vite": "6.2.5"
+ "vite": "6.2.6"
},
"browserslist": {
"production": [
diff --git a/website/yarn.lock b/website/yarn.lock
index 6ee9785240c0..e7f28b1aaf28 100644
--- a/website/yarn.lock
+++ b/website/yarn.lock
@@ -12311,7 +12311,7 @@ __metadata:
react-dom: "npm:18.3.1"
react-markdown: "npm:10.1.0"
react-tweet: "npm:3.2.2"
- vite: "npm:6.2.5"
+ vite: "npm:6.2.6"
languageName: unknown
linkType: soft
@@ -13628,9 +13628,9 @@ __metadata:
-"vite@npm:6.2.5":
- version: 6.2.5
- resolution: "vite@npm:6.2.5"
+"vite@npm:6.2.6":
+ version: 6.2.6
+ resolution: "vite@npm:6.2.6"
dependencies:
esbuild: "npm:^0.25.0"
fsevents: "npm:~2.3.3"
@@ -13676,7 +13676,7 @@ __metadata:
optional: true
bin:
vite: bin/vite.js
- checksum: 10/354023589439e7e2bcb77af79d24cd06ce20cfc48b409e663c44e515b373b89eb8f29362223eac16a3ff080d3114e40bc5df158372279d92ad03eb270f9e9762
+ checksum: 10/d8fb01a190e31fcf2189e028aed444d68255b5397d5e2c52fa73f8a0de0b052b06fbbe3793c88e7992f4297832336a23cf8bec14c88b9c2ef8aa0bce98219e50 | [] | [] | {
"additions": 6,
"author": "renovate[bot]",
"deletions": 6,
"html_url": "https://github.com/prettier/prettier/pull/17342",
"issue_id": 17342,
"merged_at": "2025-04-11T15:55:46Z",
"omission_probability": 0.1,
"pr_number": 17342,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency vite to v6.2.6 [security]",
"total_changes": 12
} |
185 | diff --git a/cspell.json b/cspell.json
index 0eb0a1b52219..65802f9be8d2 100644
--- a/cspell.json
+++ b/cspell.json
@@ -240,6 +240,7 @@
"refmt",
"reviewdog",
"rhengles",
+ "rspack",
"Rubocop",
"ruleset",
"rulesets",
diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js
index 03b12116eaaf..30d627db51de 100644
--- a/website/docusaurus.config.js
+++ b/website/docusaurus.config.js
@@ -259,7 +259,18 @@ const config = {
},
},
- future: { experimental_faster: true },
+ future: {
+ experimental_faster: {
+ swcJsLoader: true,
+ swcHtmlMinimizer: true,
+ lightningCssMinimizer: true,
+ mdxCrossCompilerCache: true,
+
+ // https://github.com/facebook/docusaurus/issues/11047
+ swcJsMinimizer: false,
+ rspackBundler: false,
+ },
+ },
};
export default config;
| diff --git a/cspell.json b/cspell.json
index 0eb0a1b52219..65802f9be8d2 100644
--- a/cspell.json
+++ b/cspell.json
@@ -240,6 +240,7 @@
"refmt",
"reviewdog",
"rhengles",
+ "rspack",
"Rubocop",
"ruleset",
"rulesets",
diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js
index 03b12116eaaf..30d627db51de 100644
--- a/website/docusaurus.config.js
+++ b/website/docusaurus.config.js
@@ -259,7 +259,18 @@ const config = {
},
},
- future: { experimental_faster: true },
+ future: {
+ experimental_faster: {
+ swcJsLoader: true,
+ swcHtmlMinimizer: true,
+ lightningCssMinimizer: true,
+ mdxCrossCompilerCache: true,
+
+ // https://github.com/facebook/docusaurus/issues/11047
+ swcJsMinimizer: false,
+ rspackBundler: false,
+ },
+ },
};
export default config; | [] | [] | {
"additions": 13,
"author": "Lehoczky",
"deletions": 1,
"html_url": "https://github.com/prettier/prettier/pull/17308",
"issue_id": 17308,
"merged_at": "2025-04-07T07:08:51Z",
"omission_probability": 0.1,
"pr_number": 17308,
"repo": "prettier/prettier",
"title": "Docs: fix emoji rendering on \"Rationale\" page",
"total_changes": 14
} |
186 | diff --git a/package.json b/package.json
index f69847bf9155..6e1504ed2f00 100644
--- a/package.json
+++ b/package.json
@@ -79,7 +79,7 @@
"minimist": "1.2.8",
"n-readlines": "1.0.1",
"outdent": "0.8.0",
- "parse-json": "8.2.0",
+ "parse-json": "8.3.0",
"picocolors": "1.1.1",
"please-upgrade-node": "3.2.0",
"postcss": "8.5.3",
diff --git a/yarn.lock b/yarn.lock
index 79ffd6061cd7..cbd6e72461a8 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4798,7 +4798,7 @@ __metadata:
languageName: node
linkType: hard
-"index-to-position@npm:1.1.0, index-to-position@npm:^1.0.0":
+"index-to-position@npm:1.1.0, index-to-position@npm:^1.1.0":
version: 1.1.0
resolution: "index-to-position@npm:1.1.0"
checksum: 10/16703893c732a025786098fe77cb7e83109afe4b72633dd6feea1595c54f8406623fa7a0a2263a8e08adee7f639fbb1c4731982cd30b4bc30d787bf803f5f3d8
@@ -6606,14 +6606,14 @@ __metadata:
languageName: node
linkType: hard
-"parse-json@npm:8.2.0, parse-json@npm:^8.0.0":
- version: 8.2.0
- resolution: "parse-json@npm:8.2.0"
+"parse-json@npm:8.3.0, parse-json@npm:^8.0.0":
+ version: 8.3.0
+ resolution: "parse-json@npm:8.3.0"
dependencies:
"@babel/code-frame": "npm:^7.26.2"
- index-to-position: "npm:^1.0.0"
- type-fest: "npm:^4.37.0"
- checksum: 10/7238fe443668b4e0c278b53d80863062c84a0ed326a79f40f2cdf6ba98a3f43f452ce4bae470cb8a859069daf457b2ae30f4e7560b61742442959157e22b5813
+ index-to-position: "npm:^1.1.0"
+ type-fest: "npm:^4.39.1"
+ checksum: 10/23812dd66a8ceedfeb0fd8a92c96b88b18bc1030cf1f07cd29146b711a208ef91ac995cf14517422f908fa930f84324086bf22fdcc1013029776cc01d589bae4
languageName: node
linkType: hard
@@ -6927,7 +6927,7 @@ __metadata:
node-style-text: "npm:0.0.7"
npm-run-all2: "npm:7.0.2"
outdent: "npm:0.8.0"
- parse-json: "npm:8.2.0"
+ parse-json: "npm:8.3.0"
picocolors: "npm:1.1.1"
please-upgrade-node: "npm:3.2.0"
postcss: "npm:8.5.3"
@@ -8017,10 +8017,10 @@ __metadata:
languageName: node
linkType: hard
-"type-fest@npm:^4.35.0, type-fest@npm:^4.37.0, type-fest@npm:^4.6.0":
- version: 4.37.0
- resolution: "type-fest@npm:4.37.0"
- checksum: 10/882cf05374d7c635cbbbc50cb89863dad3d27a77c426d062144ba32b23a44087193213c5bbd64f3ab8be04215005c950286567be06fecca9d09c66abd290ef01
+"type-fest@npm:^4.35.0, type-fest@npm:^4.39.1, type-fest@npm:^4.6.0":
+ version: 4.39.1
+ resolution: "type-fest@npm:4.39.1"
+ checksum: 10/8f3fc947cb072effd9ba240425397b4d3c08901b344409bc12a0aabf43fd309f87fa214d7ee0b600f6e2335b435f40992cd22c0ce4bc7ab8dc5a987200f83bcc
languageName: node
linkType: hard
| diff --git a/package.json b/package.json
index f69847bf9155..6e1504ed2f00 100644
--- a/package.json
+++ b/package.json
@@ -79,7 +79,7 @@
"minimist": "1.2.8",
"n-readlines": "1.0.1",
"outdent": "0.8.0",
- "parse-json": "8.2.0",
+ "parse-json": "8.3.0",
"picocolors": "1.1.1",
"please-upgrade-node": "3.2.0",
"postcss": "8.5.3",
diff --git a/yarn.lock b/yarn.lock
index 79ffd6061cd7..cbd6e72461a8 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4798,7 +4798,7 @@ __metadata:
-"index-to-position@npm:1.1.0, index-to-position@npm:^1.0.0":
+"index-to-position@npm:1.1.0, index-to-position@npm:^1.1.0":
version: 1.1.0
resolution: "index-to-position@npm:1.1.0"
checksum: 10/16703893c732a025786098fe77cb7e83109afe4b72633dd6feea1595c54f8406623fa7a0a2263a8e08adee7f639fbb1c4731982cd30b4bc30d787bf803f5f3d8
@@ -6606,14 +6606,14 @@ __metadata:
-"parse-json@npm:8.2.0, parse-json@npm:^8.0.0":
- resolution: "parse-json@npm:8.2.0"
+ version: 8.3.0
+ resolution: "parse-json@npm:8.3.0"
dependencies:
"@babel/code-frame": "npm:^7.26.2"
- index-to-position: "npm:^1.0.0"
- type-fest: "npm:^4.37.0"
- checksum: 10/7238fe443668b4e0c278b53d80863062c84a0ed326a79f40f2cdf6ba98a3f43f452ce4bae470cb8a859069daf457b2ae30f4e7560b61742442959157e22b5813
+ index-to-position: "npm:^1.1.0"
+ type-fest: "npm:^4.39.1"
+ checksum: 10/23812dd66a8ceedfeb0fd8a92c96b88b18bc1030cf1f07cd29146b711a208ef91ac995cf14517422f908fa930f84324086bf22fdcc1013029776cc01d589bae4
@@ -6927,7 +6927,7 @@ __metadata:
node-style-text: "npm:0.0.7"
npm-run-all2: "npm:7.0.2"
outdent: "npm:0.8.0"
+ parse-json: "npm:8.3.0"
picocolors: "npm:1.1.1"
please-upgrade-node: "npm:3.2.0"
postcss: "npm:8.5.3"
@@ -8017,10 +8017,10 @@ __metadata:
-"type-fest@npm:^4.35.0, type-fest@npm:^4.37.0, type-fest@npm:^4.6.0":
- version: 4.37.0
- resolution: "type-fest@npm:4.37.0"
- checksum: 10/882cf05374d7c635cbbbc50cb89863dad3d27a77c426d062144ba32b23a44087193213c5bbd64f3ab8be04215005c950286567be06fecca9d09c66abd290ef01
+ version: 4.39.1
+ resolution: "type-fest@npm:4.39.1"
+ checksum: 10/8f3fc947cb072effd9ba240425397b4d3c08901b344409bc12a0aabf43fd309f87fa214d7ee0b600f6e2335b435f40992cd22c0ce4bc7ab8dc5a987200f83bcc | [
"- version: 8.2.0",
"+\"parse-json@npm:8.3.0, parse-json@npm:^8.0.0\":",
"- parse-json: \"npm:8.2.0\"",
"+\"type-fest@npm:^4.35.0, type-fest@npm:^4.39.1, type-fest@npm:^4.6.0\":"
] | [
31,
33,
51,
64
] | {
"additions": 13,
"author": "renovate[bot]",
"deletions": 13,
"html_url": "https://github.com/prettier/prettier/pull/17335",
"issue_id": 17335,
"merged_at": "2025-04-09T13:51:25Z",
"omission_probability": 0.1,
"pr_number": 17335,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency parse-json to v8.3.0",
"total_changes": 26
} |
187 | diff --git a/src/cli/file-info.js b/src/cli/file-info.js
index 91d8381f186d..a84bf7ea02c3 100644
--- a/src/cli/file-info.js
+++ b/src/cli/file-info.js
@@ -18,7 +18,9 @@ async function logFileInfoOrDie(context) {
resolveConfig: config !== false,
});
- printToScreen(await format(stringify(fileInfo), { parser: "json" }));
+ const result = await format(stringify(fileInfo), { parser: "json" });
+
+ printToScreen(result.trim());
}
export default logFileInfoOrDie;
diff --git a/src/cli/print-support-info.js b/src/cli/print-support-info.js
index cf4672c297fa..5dc91d7662d4 100644
--- a/src/cli/print-support-info.js
+++ b/src/cli/print-support-info.js
@@ -14,7 +14,9 @@ async function printSupportInfo() {
),
};
- printToScreen(await format(stringify(supportInfo), { parser: "json" }));
+ const result = await format(stringify(supportInfo), { parser: "json" });
+
+ printToScreen(result.trim());
}
export default printSupportInfo;
diff --git a/tests/integration/__tests__/__snapshots__/file-info.js.snap b/tests/integration/__tests__/__snapshots__/file-info.js.snap
index 12a9e3537b12..998a69e31a87 100644
--- a/tests/integration/__tests__/__snapshots__/file-info.js.snap
+++ b/tests/integration/__tests__/__snapshots__/file-info.js.snap
@@ -2,113 +2,74 @@
exports[`extracts file-info for a file in not_node_modules (stderr) 1`] = `""`;
-exports[`extracts file-info for a file in not_node_modules (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "babel" }
-"
-`;
+exports[`extracts file-info for a file in not_node_modules (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`extracts file-info for a file in not_node_modules (write) 1`] = `[]`;
exports[`extracts file-info for a js file (stderr) 1`] = `""`;
-exports[`extracts file-info for a js file (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "babel" }
-"
-`;
+exports[`extracts file-info for a js file (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`extracts file-info for a js file (write) 1`] = `[]`;
exports[`extracts file-info for a known markdown file with no extension (stderr) 1`] = `""`;
-exports[`extracts file-info for a known markdown file with no extension (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "markdown" }
-"
-`;
+exports[`extracts file-info for a known markdown file with no extension (stdout) 1`] = `"{ "ignored": false, "inferredParser": "markdown" }"`;
exports[`extracts file-info for a known markdown file with no extension (write) 1`] = `[]`;
exports[`extracts file-info for a markdown file (stderr) 1`] = `""`;
-exports[`extracts file-info for a markdown file (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "markdown" }
-"
-`;
+exports[`extracts file-info for a markdown file (stdout) 1`] = `"{ "ignored": false, "inferredParser": "markdown" }"`;
exports[`extracts file-info for a markdown file (write) 1`] = `[]`;
exports[`extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided (stderr) 1`] = `""`;
-exports[`extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "babel" }
-"
-`;
+exports[`extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided (write) 1`] = `[]`;
exports[`extracts file-info with ignored=true for a file in .prettierignore (stderr) 1`] = `""`;
-exports[`extracts file-info with ignored=true for a file in .prettierignore (stdout) 1`] = `
-"{ "ignored": true, "inferredParser": null }
-"
-`;
+exports[`extracts file-info with ignored=true for a file in .prettierignore (stdout) 1`] = `"{ "ignored": true, "inferredParser": null }"`;
exports[`extracts file-info with ignored=true for a file in .prettierignore (write) 1`] = `[]`;
exports[`extracts file-info with ignored=true for a file in a hand-picked ignore file (stderr) 1`] = `""`;
-exports[`extracts file-info with ignored=true for a file in a hand-picked ignore file (stdout) 1`] = `
-"{ "ignored": true, "inferredParser": null }
-"
-`;
+exports[`extracts file-info with ignored=true for a file in a hand-picked ignore file (stdout) 1`] = `"{ "ignored": true, "inferredParser": null }"`;
exports[`extracts file-info with ignored=true for a file in a hand-picked ignore file (write) 1`] = `[]`;
exports[`extracts file-info with inferredParser=foo when a plugin is hand-picked (stderr) 1`] = `""`;
-exports[`extracts file-info with inferredParser=foo when a plugin is hand-picked (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "foo" }
-"
-`;
+exports[`extracts file-info with inferredParser=foo when a plugin is hand-picked (stdout) 1`] = `"{ "ignored": false, "inferredParser": "foo" }"`;
exports[`extracts file-info with inferredParser=foo when a plugin is hand-picked (write) 1`] = `[]`;
exports[`extracts file-info with inferredParser=null for file.foo (stderr) 1`] = `""`;
-exports[`extracts file-info with inferredParser=null for file.foo (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": null }
-"
-`;
+exports[`extracts file-info with inferredParser=null for file.foo (stdout) 1`] = `"{ "ignored": false, "inferredParser": null }"`;
exports[`extracts file-info with inferredParser=null for file.foo (write) 1`] = `[]`;
exports[`extracts file-info with with ignored=true for a file in node_modules (stderr) 1`] = `""`;
-exports[`extracts file-info with with ignored=true for a file in node_modules (stdout) 1`] = `
-"{ "ignored": true, "inferredParser": null }
-"
-`;
+exports[`extracts file-info with with ignored=true for a file in node_modules (stdout) 1`] = `"{ "ignored": true, "inferredParser": null }"`;
exports[`extracts file-info with with ignored=true for a file in node_modules (write) 1`] = `[]`;
-exports[`file-info should not try resolve config with --no-config (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "babel" }
-"
-`;
+exports[`file-info should not try resolve config with --no-config (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`file-info should try resolve config (stderr) 1`] = `""`;
-exports[`file-info should try resolve config (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "override-js-parser" }
-"
-`;
+exports[`file-info should try resolve config (stdout) 1`] = `"{ "ignored": false, "inferredParser": "override-js-parser" }"`;
exports[`file-info should try resolve config (write) 1`] = `[]`;
exports[`non-exists ignore path (stderr) 1`] = `""`;
-exports[`non-exists ignore path (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "babel" }
-"
-`;
+exports[`non-exists ignore path (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`non-exists ignore path (write) 1`] = `[]`;
diff --git a/tests/integration/__tests__/__snapshots__/infer-parser.js.snap b/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
index 08d876da4132..84a12db4719e 100644
--- a/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
+++ b/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
@@ -76,10 +76,7 @@ exports[`--write with unknown path and no parser multiple files (write) 1`] = `
exports[`--write with unknown path and no parser specific file (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/FOO"."`;
-exports[`Interpreters (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "babel" }
-"
-`;
+exports[`Interpreters (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`Known/Unknown (stdout) 1`] = `"known.js"`;
diff --git a/tests/integration/__tests__/__snapshots__/support-info.js.snap b/tests/integration/__tests__/__snapshots__/support-info.js.snap
index 6531893d26b7..1055f28c3755 100644
--- a/tests/integration/__tests__/__snapshots__/support-info.js.snap
+++ b/tests/integration/__tests__/__snapshots__/support-info.js.snap
@@ -1153,8 +1153,7 @@ exports[`CLI --support-info (stdout) 1`] = `
"type": "boolean"
}
]
-}
-"
+}"
`;
exports[`CLI --support-info (write) 1`] = `[]`;
| diff --git a/src/cli/file-info.js b/src/cli/file-info.js
index 91d8381f186d..a84bf7ea02c3 100644
--- a/src/cli/file-info.js
+++ b/src/cli/file-info.js
@@ -18,7 +18,9 @@ async function logFileInfoOrDie(context) {
resolveConfig: config !== false,
});
- printToScreen(await format(stringify(fileInfo), { parser: "json" }));
+ const result = await format(stringify(fileInfo), { parser: "json" });
export default logFileInfoOrDie;
diff --git a/src/cli/print-support-info.js b/src/cli/print-support-info.js
index cf4672c297fa..5dc91d7662d4 100644
--- a/src/cli/print-support-info.js
+++ b/src/cli/print-support-info.js
@@ -14,7 +14,9 @@ async function printSupportInfo() {
),
};
- printToScreen(await format(stringify(supportInfo), { parser: "json" }));
+ const result = await format(stringify(supportInfo), { parser: "json" });
export default printSupportInfo;
diff --git a/tests/integration/__tests__/__snapshots__/file-info.js.snap b/tests/integration/__tests__/__snapshots__/file-info.js.snap
index 12a9e3537b12..998a69e31a87 100644
--- a/tests/integration/__tests__/__snapshots__/file-info.js.snap
+++ b/tests/integration/__tests__/__snapshots__/file-info.js.snap
@@ -2,113 +2,74 @@
exports[`extracts file-info for a file in not_node_modules (stderr) 1`] = `""`;
-exports[`extracts file-info for a file in not_node_modules (stdout) 1`] = `
exports[`extracts file-info for a file in not_node_modules (write) 1`] = `[]`;
exports[`extracts file-info for a js file (stderr) 1`] = `""`;
-exports[`extracts file-info for a js file (stdout) 1`] = `
+exports[`extracts file-info for a js file (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`extracts file-info for a js file (write) 1`] = `[]`;
exports[`extracts file-info for a known markdown file with no extension (stderr) 1`] = `""`;
-exports[`extracts file-info for a known markdown file with no extension (stdout) 1`] = `
+exports[`extracts file-info for a known markdown file with no extension (stdout) 1`] = `"{ "ignored": false, "inferredParser": "markdown" }"`;
exports[`extracts file-info for a known markdown file with no extension (write) 1`] = `[]`;
exports[`extracts file-info for a markdown file (stderr) 1`] = `""`;
-exports[`extracts file-info for a markdown file (stdout) 1`] = `
+exports[`extracts file-info for a markdown file (stdout) 1`] = `"{ "ignored": false, "inferredParser": "markdown" }"`;
exports[`extracts file-info for a markdown file (write) 1`] = `[]`;
exports[`extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided (stderr) 1`] = `""`;
-exports[`extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided (stdout) 1`] = `
+exports[`extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided (write) 1`] = `[]`;
exports[`extracts file-info with ignored=true for a file in .prettierignore (stderr) 1`] = `""`;
-exports[`extracts file-info with ignored=true for a file in .prettierignore (stdout) 1`] = `
+exports[`extracts file-info with ignored=true for a file in .prettierignore (stdout) 1`] = `"{ "ignored": true, "inferredParser": null }"`;
exports[`extracts file-info with ignored=true for a file in .prettierignore (write) 1`] = `[]`;
exports[`extracts file-info with ignored=true for a file in a hand-picked ignore file (stderr) 1`] = `""`;
-exports[`extracts file-info with ignored=true for a file in a hand-picked ignore file (stdout) 1`] = `
+exports[`extracts file-info with ignored=true for a file in a hand-picked ignore file (stdout) 1`] = `"{ "ignored": true, "inferredParser": null }"`;
exports[`extracts file-info with ignored=true for a file in a hand-picked ignore file (write) 1`] = `[]`;
exports[`extracts file-info with inferredParser=foo when a plugin is hand-picked (stderr) 1`] = `""`;
-exports[`extracts file-info with inferredParser=foo when a plugin is hand-picked (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "foo" }
+exports[`extracts file-info with inferredParser=foo when a plugin is hand-picked (stdout) 1`] = `"{ "ignored": false, "inferredParser": "foo" }"`;
exports[`extracts file-info with inferredParser=foo when a plugin is hand-picked (write) 1`] = `[]`;
exports[`extracts file-info with inferredParser=null for file.foo (stderr) 1`] = `""`;
-exports[`extracts file-info with inferredParser=null for file.foo (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": null }
+exports[`extracts file-info with inferredParser=null for file.foo (stdout) 1`] = `"{ "ignored": false, "inferredParser": null }"`;
exports[`extracts file-info with inferredParser=null for file.foo (write) 1`] = `[]`;
exports[`extracts file-info with with ignored=true for a file in node_modules (stderr) 1`] = `""`;
-exports[`extracts file-info with with ignored=true for a file in node_modules (stdout) 1`] = `
+exports[`extracts file-info with with ignored=true for a file in node_modules (stdout) 1`] = `"{ "ignored": true, "inferredParser": null }"`;
exports[`extracts file-info with with ignored=true for a file in node_modules (write) 1`] = `[]`;
-exports[`file-info should not try resolve config with --no-config (stdout) 1`] = `
+exports[`file-info should not try resolve config with --no-config (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`file-info should try resolve config (stderr) 1`] = `""`;
-exports[`file-info should try resolve config (stdout) 1`] = `
-"{ "ignored": false, "inferredParser": "override-js-parser" }
+exports[`file-info should try resolve config (stdout) 1`] = `"{ "ignored": false, "inferredParser": "override-js-parser" }"`;
exports[`file-info should try resolve config (write) 1`] = `[]`;
exports[`non-exists ignore path (stderr) 1`] = `""`;
+exports[`non-exists ignore path (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`non-exists ignore path (write) 1`] = `[]`;
diff --git a/tests/integration/__tests__/__snapshots__/infer-parser.js.snap b/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
index 08d876da4132..84a12db4719e 100644
--- a/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
+++ b/tests/integration/__tests__/__snapshots__/infer-parser.js.snap
@@ -76,10 +76,7 @@ exports[`--write with unknown path and no parser multiple files (write) 1`] = `
exports[`--write with unknown path and no parser specific file (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/infer-parser/FOO"."`;
-exports[`Interpreters (stdout) 1`] = `
+exports[`Interpreters (stdout) 1`] = `"{ "ignored": false, "inferredParser": "babel" }"`;
exports[`Known/Unknown (stdout) 1`] = `"known.js"`;
diff --git a/tests/integration/__tests__/__snapshots__/support-info.js.snap b/tests/integration/__tests__/__snapshots__/support-info.js.snap
index 6531893d26b7..1055f28c3755 100644
--- a/tests/integration/__tests__/__snapshots__/support-info.js.snap
+++ b/tests/integration/__tests__/__snapshots__/support-info.js.snap
@@ -1153,8 +1153,7 @@ exports[`CLI --support-info (stdout) 1`] = `
"type": "boolean"
}
]
+}"
`;
exports[`CLI --support-info (write) 1`] = `[]`; | [
"+exports[`extracts file-info for a file in not_node_modules (stdout) 1`] = `\"{ \"ignored\": false, \"inferredParser\": \"babel\" }\"`;",
"-exports[`non-exists ignore path (stdout) 1`] = `",
"-}"
] | [
42,
154,
185
] | {
"additions": 21,
"author": "fisker",
"deletions": 60,
"html_url": "https://github.com/prettier/prettier/pull/17332",
"issue_id": 17332,
"merged_at": "2025-04-09T07:23:50Z",
"omission_probability": 0.1,
"pr_number": 17332,
"repo": "prettier/prettier",
"title": "Remove extra lines in `--file-info` and `--support-info`",
"total_changes": 81
} |
188 | diff --git a/eslint.config.js b/eslint.config.js
index 42d13a33b4cd..8a22cc627165 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -29,8 +29,8 @@ coverage/
dist*/
**/node_modules/**
website/build/
-website/static/playground.js
website/static/lib/
+website/static/playground/
website/.docusaurus
scripts/benchmark/*/
**/.yarn/**
@@ -413,6 +413,7 @@ export default [
files: ["src/language-*/**/*.js"],
rules: {
"prettier-internal-rules/directly-loc-start-end": "error",
+ "prettier-internal-rules/print-function-parameter-order": "error",
},
},
{
diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/print-function-parameter-order.js b/scripts/tools/eslint-plugin-prettier-internal-rules/print-function-parameter-order.js
new file mode 100644
index 000000000000..14033b75b48e
--- /dev/null
+++ b/scripts/tools/eslint-plugin-prettier-internal-rules/print-function-parameter-order.js
@@ -0,0 +1,55 @@
+const messageId = "print-function-parameter-order";
+const expectedParameters = ["path", "options", "print"];
+
+export default {
+ meta: {
+ type: "suggestion",
+ messages: {
+ [messageId]:
+ "`{{functionName}}` function parameters should in order of `path`, `options` and `print`.",
+ },
+ },
+ create(context) {
+ const sourceCode = context.getSourceCode();
+
+ return {
+ ":function[params.length>=3]"(node) {
+ const parameterNames = node.params.map((node) =>
+ node.type === "Identifier" ? node.name : "",
+ );
+
+ // `embed` function order is `textToDoc, print, path, options`
+ if (parameterNames.includes("textToDoc")) {
+ return;
+ }
+
+ // Only if all three parameters exists
+ if (expectedParameters.some((name) => !parameterNames.includes(name))) {
+ return;
+ }
+
+ // In correct order
+ if (
+ expectedParameters.every(
+ (name, index) => name === parameterNames[index],
+ )
+ ) {
+ return;
+ }
+
+ const firstToken = sourceCode.getFirstToken(node);
+ const tokenBeforeBody = sourceCode.getTokenBefore(node.body);
+ const functionName = node.id ? node.id.name : "print*";
+ context.report({
+ node,
+ loc: {
+ start: firstToken.loc.start,
+ end: tokenBeforeBody.loc.end,
+ },
+ messageId,
+ data: { functionName },
+ });
+ },
+ };
+ },
+};
diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/test.js b/scripts/tools/eslint-plugin-prettier-internal-rules/test.js
index 340b967a9989..5878aa80127a 100644
--- a/scripts/tools/eslint-plugin-prettier-internal-rules/test.js
+++ b/scripts/tools/eslint-plugin-prettier-internal-rules/test.js
@@ -640,6 +640,31 @@ test("prefer-is-non-empty-array", {
],
});
+test("print-function-parameter-order", {
+ valid: [
+ "function printFoo(path, options, print) {}",
+ "function printFoo(path, opts, print) {}",
+ "function printFoo(path, options, printPath) {}",
+ "function printFoo() {}",
+ "function printFoo(path, print) {}",
+ "function printFoo(path, options) {}",
+ "function printFoo(print, options) {}",
+ "function embed(path, print, textToDoc, options) {}",
+ ],
+ invalid: [
+ "function printFoo(path, print, options) {}",
+ "function printFoo(path, print, options, args) {}",
+ "function printFoo(options, print, path) {}",
+ "const printFoo = function (path, print, options) {}",
+ "const printFoo = function printFoo(path, print, options) {}",
+ "const printFoo = (path, print, options) => {}",
+ ].map((code) => ({
+ code,
+ output: null,
+ errors: 1,
+ })),
+});
+
test("no-empty-flat-contents-for-if-break", {
valid: [
"ifBreak('foo', 'bar')",
diff --git a/src/language-handlebars/printer-glimmer.js b/src/language-handlebars/printer-glimmer.js
index c360d2312e2b..44ed0f83bf46 100644
--- a/src/language-handlebars/printer-glimmer.js
+++ b/src/language-handlebars/printer-glimmer.js
@@ -79,17 +79,17 @@ function print(path, options, print) {
if (isElseIfLike(path)) {
return [
printElseIfLikeBlock(path, print),
- printProgram(path, print, options),
- printInverse(path, print, options),
+ printProgram(path, options, print),
+ printInverse(path, options, print),
];
}
return [
printOpenBlock(path, print),
group([
- printProgram(path, print, options),
- printInverse(path, print, options),
- printCloseBlock(path, print, options),
+ printProgram(path, options, print),
+ printInverse(path, options, print),
+ printCloseBlock(path, options, print),
]),
];
@@ -573,7 +573,7 @@ function printElseIfLikeBlock(path, print) {
]);
}
-function printCloseBlock(path, print, options) {
+function printCloseBlock(path, options, print) {
const { node } = path;
if (options.htmlWhitespaceSensitivity === "ignore") {
@@ -616,7 +616,7 @@ function blockStatementHasElse(node) {
return node.type === "BlockStatement" && node.inverse;
}
-function printProgram(path, print, options) {
+function printProgram(path, options, print) {
const { node } = path;
if (blockStatementHasOnlyWhitespaceInProgram(node)) {
@@ -632,7 +632,7 @@ function printProgram(path, print, options) {
return indent(program);
}
-function printInverse(path, print, options) {
+function printInverse(path, options, print) {
const { node } = path;
const inverse = print("inverse");
diff --git a/src/language-js/print/array.js b/src/language-js/print/array.js
index dc2625423dd1..fa6c453403dc 100644
--- a/src/language-js/print/array.js
+++ b/src/language-js/print/array.js
@@ -135,9 +135,9 @@ function printArray(path, options, print) {
printArrayElements(
path,
options,
+ print,
elementsProperty,
node.inexact,
- print,
),
trailingComma,
],
@@ -192,7 +192,7 @@ function isLineAfterElementEmpty({ node }, { originalText: text }) {
return isNextLineEmptyAfterIndex(text, skipToComma(locEnd(node)));
}
-function printArrayElements(path, options, elementsProperty, inexact, print) {
+function printArrayElements(path, options, print, elementsProperty, inexact) {
const parts = [];
path.each(({ node, isLast }) => {
diff --git a/src/language-js/print/arrow-function.js b/src/language-js/print/arrow-function.js
index 05586c322f9d..27fde82936af 100644
--- a/src/language-js/print/arrow-function.js
+++ b/src/language-js/print/arrow-function.js
@@ -189,8 +189,8 @@ function printArrowFunctionSignature(path, options, print, args) {
group([
printFunctionParameters(
path,
- print,
options,
+ print,
expandArg,
/* printTypeParams */ true,
),
diff --git a/src/language-js/print/binaryish.js b/src/language-js/print/binaryish.js
index 92a838db097f..4cd85975f64a 100644
--- a/src/language-js/print/binaryish.js
+++ b/src/language-js/print/binaryish.js
@@ -51,8 +51,8 @@ function printBinaryishExpression(path, options, print) {
const parts = printBinaryishExpressions(
path,
- print,
options,
+ print,
/* isNested */ false,
isInsideParenthesis,
);
@@ -193,8 +193,8 @@ function printBinaryishExpression(path, options, print) {
// broken before `+`.
function printBinaryishExpressions(
path,
- print,
options,
+ print,
isNested,
isInsideParenthesis,
) {
@@ -225,8 +225,8 @@ function printBinaryishExpressions(
(left) =>
printBinaryishExpressions(
left,
- print,
options,
+ print,
/* isNested */ true,
isInsideParenthesis,
),
@@ -283,8 +283,8 @@ function printBinaryishExpressions(
(left) =>
printBinaryishExpressions(
left,
- print,
options,
+ print,
/* isNested */ true,
isInsideParenthesis,
),
diff --git a/src/language-js/print/component.js b/src/language-js/print/component.js
index 777de08f98d9..cb6597396d95 100644
--- a/src/language-js/print/component.js
+++ b/src/language-js/print/component.js
@@ -32,7 +32,7 @@ function printComponent(path, options, print) {
parts.push(print("typeParameters"));
- const parametersDoc = printComponentParameters(path, print, options);
+ const parametersDoc = printComponentParameters(path, options, print);
if (node.rendersType) {
parts.push(group([parametersDoc, " ", print("rendersType")]));
} else {
@@ -50,7 +50,7 @@ function printComponent(path, options, print) {
return parts;
}
-function printComponentParameters(path, print, options) {
+function printComponentParameters(path, options, print) {
const { node: componentNode } = path;
let parameters = componentNode.params;
if (componentNode.rest) {
diff --git a/src/language-js/print/enum.js b/src/language-js/print/enum.js
index 9e1f6d38037a..acb1bd832d24 100644
--- a/src/language-js/print/enum.js
+++ b/src/language-js/print/enum.js
@@ -1,9 +1,5 @@
import { printDeclareToken } from "./misc.js";
-import { printObject } from "./object.js";
-
-function printEnumMembers(path, print, options) {
- return printObject(path, options, print);
-}
+import { printObject as printEnumMembers } from "./object.js";
/*
- `EnumBooleanMember`(flow)
@@ -48,7 +44,7 @@ function printEnumMember(path, print) {
- `EnumStringBody`(flow)
- `EnumSymbolBody`(flow)
*/
-function printEnumBody(path, print, options) {
+function printEnumBody(path, options, print) {
const { node } = path;
let type;
@@ -72,7 +68,7 @@ function printEnumBody(path, print, options) {
}
}
- return [type ? `of ${type} ` : "", printEnumMembers(path, print, options)];
+ return [type ? `of ${type} ` : "", printEnumMembers(path, options, print)];
}
/*
@@ -80,7 +76,7 @@ function printEnumBody(path, print, options) {
- `EnumDeclaration`(flow)
- `TSEnumDeclaration`(TypeScript)
*/
-function printEnumDeclaration(path, print, options) {
+function printEnumDeclaration(path, options, print) {
const { node } = path;
return [
printDeclareToken(path),
@@ -89,7 +85,7 @@ function printEnumDeclaration(path, print, options) {
print("id"),
" ",
node.type === "TSEnumDeclaration"
- ? printEnumMembers(path, print, options)
+ ? printEnumMembers(path, options, print)
: print("body"),
];
}
diff --git a/src/language-js/print/estree.js b/src/language-js/print/estree.js
index 3e5c93882681..7f0adfe188e7 100644
--- a/src/language-js/print/estree.js
+++ b/src/language-js/print/estree.js
@@ -173,7 +173,7 @@ function printEstree(path, options, print, args) {
return printRestSpread(path, print);
case "FunctionDeclaration":
case "FunctionExpression":
- return printFunction(path, print, options, args);
+ return printFunction(path, options, print, args);
case "ArrowFunctionExpression":
return printArrowFunction(path, options, print, args);
case "YieldExpression":
@@ -632,7 +632,7 @@ function printEstree(path, options, print, args) {
case "TemplateElement":
return replaceEndOfLine(node.value.raw);
case "TemplateLiteral":
- return printTemplateLiteral(path, print, options);
+ return printTemplateLiteral(path, options, print);
case "TaggedTemplateExpression":
return printTaggedTemplateLiteral(path, print);
case "PrivateIdentifier":
diff --git a/src/language-js/print/flow.js b/src/language-js/print/flow.js
index dd9057977778..0005631cd220 100644
--- a/src/language-js/print/flow.js
+++ b/src/language-js/print/flow.js
@@ -159,14 +159,14 @@ function printFlow(path, options, print) {
case "DeclareEnum":
case "EnumDeclaration":
- return printEnumDeclaration(path, print, options);
+ return printEnumDeclaration(path, options, print);
case "EnumBooleanBody":
case "EnumNumberBody":
case "EnumBigIntBody":
case "EnumStringBody":
case "EnumSymbolBody":
- return printEnumBody(path, print, options);
+ return printEnumBody(path, options, print);
case "EnumBooleanMember":
case "EnumNumberMember":
diff --git a/src/language-js/print/function-parameters.js b/src/language-js/print/function-parameters.js
index a8e7773db8e4..8c8273dbd0b1 100644
--- a/src/language-js/print/function-parameters.js
+++ b/src/language-js/print/function-parameters.js
@@ -33,8 +33,8 @@ import { printFunctionTypeParameters } from "./misc.js";
function printFunctionParameters(
path,
- print,
options,
+ print,
expandArg,
printTypeParams,
) {
diff --git a/src/language-js/print/function.js b/src/language-js/print/function.js
index 28743fc31a5e..0c71e4b1cd92 100644
--- a/src/language-js/print/function.js
+++ b/src/language-js/print/function.js
@@ -52,7 +52,7 @@ const isMethodValue = ({ node, key, parent }) =>
- "FunctionExpression"
- `TSDeclareFunction`(TypeScript)
*/
-function printFunction(path, print, options, args) {
+function printFunction(path, options, print, args) {
if (isMethodValue(path)) {
return printMethodValue(path, options, print);
}
@@ -86,8 +86,8 @@ function printFunction(path, print, options, args) {
const parametersDoc = printFunctionParameters(
path,
- print,
options,
+ print,
expandArg,
);
const returnTypeDoc = printReturnType(path, print);
@@ -155,7 +155,7 @@ function printMethod(path, options, print) {
function printMethodValue(path, options, print) {
const { node } = path;
- const parametersDoc = printFunctionParameters(path, print, options);
+ const parametersDoc = printFunctionParameters(path, options, print);
const returnTypeDoc = printReturnType(path, print);
const shouldBreakParameters = shouldBreakFunctionParameters(node);
const shouldGroupParameters = shouldGroupFunctionParameters(
diff --git a/src/language-js/print/hook.js b/src/language-js/print/hook.js
index 9da7de100a99..8f23a342e95e 100644
--- a/src/language-js/print/hook.js
+++ b/src/language-js/print/hook.js
@@ -25,8 +25,8 @@ function printHook(path, options, print) {
const parametersDoc = printFunctionParameters(
path,
- print,
options,
+ print,
false,
true,
);
@@ -90,8 +90,8 @@ function printHookTypeAnnotation(path, options, print) {
let parametersDoc = printFunctionParameters(
path,
- print,
options,
+ print,
/* expandArg */ false,
/* printTypeParams */ true,
);
diff --git a/src/language-js/print/template-literal.js b/src/language-js/print/template-literal.js
index a2baf1f3f98a..db81d5a9d157 100644
--- a/src/language-js/print/template-literal.js
+++ b/src/language-js/print/template-literal.js
@@ -22,7 +22,7 @@ import {
isMemberExpression,
} from "../utils/index.js";
-function printTemplateLiteral(path, print, options) {
+function printTemplateLiteral(path, options, print) {
const { node } = path;
const isTemplateLiteral = node.type === "TemplateLiteral";
diff --git a/src/language-js/print/type-annotation.js b/src/language-js/print/type-annotation.js
index 3b736a7a72a6..f53943c6ee69 100644
--- a/src/language-js/print/type-annotation.js
+++ b/src/language-js/print/type-annotation.js
@@ -298,8 +298,8 @@ function printFunctionType(path, options, print) {
let parametersDoc = printFunctionParameters(
path,
- print,
options,
+ print,
/* expandArg */ false,
/* printTypeParams */ true,
);
diff --git a/src/language-js/print/typescript.js b/src/language-js/print/typescript.js
index abd4a51b1447..50ca6583cca0 100644
--- a/src/language-js/print/typescript.js
+++ b/src/language-js/print/typescript.js
@@ -103,7 +103,7 @@ function printTypescript(path, options, print) {
return group([castGroup, print("expression")]);
}
case "TSDeclareFunction":
- return printFunction(path, print, options);
+ return printFunction(path, options, print);
case "TSExportAssignment":
return ["export = ", print("expression"), semi];
case "TSModuleBlock":
@@ -133,7 +133,7 @@ function printTypescript(path, options, print) {
),
];
case "TSTemplateLiteralType":
- return printTemplateLiteral(path, print, options);
+ return printTemplateLiteral(path, options, print);
case "TSNamedTupleMember":
return printNamedTupleMember(path, options, print);
case "TSRestType":
@@ -245,8 +245,8 @@ function printTypescript(path, options, print) {
const parametersDoc = printFunctionParameters(
path,
- print,
options,
+ print,
/* expandArg */ false,
/* printTypeParams */ true,
);
@@ -274,7 +274,7 @@ function printTypescript(path, options, print) {
case "TSNamespaceExportDeclaration":
return ["export as namespace ", print("id"), options.semi ? ";" : ""];
case "TSEnumDeclaration":
- return printEnumDeclaration(path, print, options);
+ return printEnumDeclaration(path, options, print);
case "TSEnumMember":
return printEnumMember(path, print);
diff --git a/src/language-yaml/print/block.js b/src/language-yaml/print/block.js
index 7bd988004754..564bd18745ad 100644
--- a/src/language-yaml/print/block.js
+++ b/src/language-yaml/print/block.js
@@ -17,7 +17,7 @@ import {
} from "../utils.js";
import { alignWithSpaces } from "./misc.js";
-function printBlock(path, print, options) {
+function printBlock(path, options, print) {
const { node } = path;
const parentIndent = path.ancestors.filter(
(node) => node.type === "sequence" || node.type === "mapping",
diff --git a/src/language-yaml/print/flow-mapping-sequence.js b/src/language-yaml/print/flow-mapping-sequence.js
index 36c0dc7f7acc..4a964743bdf5 100644
--- a/src/language-yaml/print/flow-mapping-sequence.js
+++ b/src/language-yaml/print/flow-mapping-sequence.js
@@ -8,7 +8,7 @@ import {
import { hasEndComments, isEmptyNode } from "../utils.js";
import { alignWithSpaces, printNextEmptyLine } from "./misc.js";
-function printFlowMapping(path, print, options) {
+function printFlowMapping(path, options, print) {
const { node } = path;
const isMapping = node.type === "flowMapping";
const openMarker = isMapping ? "{" : "[";
@@ -29,7 +29,7 @@ function printFlowMapping(path, print, options) {
openMarker,
alignWithSpaces(options.tabWidth, [
bracketSpacing,
- printChildren(path, print, options),
+ printChildren(path, options, print),
options.trailingComma === "none" ? "" : ifBreak(","),
hasEndComments(node)
? [hardline, join(hardline, path.map(print, "endComments"))]
@@ -40,7 +40,7 @@ function printFlowMapping(path, print, options) {
];
}
-function printChildren(path, print, options) {
+function printChildren(path, options, print) {
return path.map(
({ isLast, node, next }) => [
print(),
diff --git a/src/language-yaml/print/mapping-item.js b/src/language-yaml/print/mapping-item.js
index c9c4b408fbde..b04c88d7aa92 100644
--- a/src/language-yaml/print/mapping-item.js
+++ b/src/language-yaml/print/mapping-item.js
@@ -18,7 +18,7 @@ import {
} from "../utils.js";
import { alignWithSpaces } from "./misc.js";
-function printMappingItem(path, print, options) {
+function printMappingItem(path, options, print) {
const { node, parent } = path;
const { key, value } = node;
diff --git a/src/language-yaml/printer-yaml.js b/src/language-yaml/printer-yaml.js
index 4f71218abdde..b1f447c0e0d4 100644
--- a/src/language-yaml/printer-yaml.js
+++ b/src/language-yaml/printer-yaml.js
@@ -305,7 +305,7 @@ function printNode(path, options, print) {
}
case "blockFolded":
case "blockLiteral":
- return printBlock(path, print, options);
+ return printBlock(path, options, print);
case "mapping":
case "sequence":
@@ -317,12 +317,12 @@ function printNode(path, options, print) {
return !node.content ? "" : print("content");
case "mappingItem":
case "flowMappingItem":
- return printMappingItem(path, print, options);
+ return printMappingItem(path, options, print);
case "flowMapping":
- return printFlowMapping(path, print, options);
+ return printFlowMapping(path, options, print);
case "flowSequence":
- return printFlowSequence(path, print, options);
+ return printFlowSequence(path, options, print);
case "flowSequenceItem":
return print("content");
default:
| diff --git a/eslint.config.js b/eslint.config.js
index 42d13a33b4cd..8a22cc627165 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -29,8 +29,8 @@ coverage/
dist*/
**/node_modules/**
website/build/
-website/static/playground.js
website/static/lib/
+website/static/playground/
website/.docusaurus
scripts/benchmark/*/
**/.yarn/**
@@ -413,6 +413,7 @@ export default [
files: ["src/language-*/**/*.js"],
rules: {
"prettier-internal-rules/directly-loc-start-end": "error",
+ "prettier-internal-rules/print-function-parameter-order": "error",
},
},
{
diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/print-function-parameter-order.js b/scripts/tools/eslint-plugin-prettier-internal-rules/print-function-parameter-order.js
new file mode 100644
index 000000000000..14033b75b48e
--- /dev/null
+++ b/scripts/tools/eslint-plugin-prettier-internal-rules/print-function-parameter-order.js
@@ -0,0 +1,55 @@
+const messageId = "print-function-parameter-order";
+const expectedParameters = ["path", "options", "print"];
+export default {
+ meta: {
+ type: "suggestion",
+ messages: {
+ [messageId]:
+ "`{{functionName}}` function parameters should in order of `path`, `options` and `print`.",
+ },
+ create(context) {
+ const sourceCode = context.getSourceCode();
+ return {
+ ":function[params.length>=3]"(node) {
+ const parameterNames = node.params.map((node) =>
+ node.type === "Identifier" ? node.name : "",
+ );
+ if (parameterNames.includes("textToDoc")) {
+ // Only if all three parameters exists
+ if (expectedParameters.some((name) => !parameterNames.includes(name))) {
+ // In correct order
+ if (
+ expectedParameters.every(
+ (name, index) => name === parameterNames[index],
+ )
+ ) {
+ const firstToken = sourceCode.getFirstToken(node);
+ const tokenBeforeBody = sourceCode.getTokenBefore(node.body);
+ const functionName = node.id ? node.id.name : "print*";
+ context.report({
+ node,
+ loc: {
+ start: firstToken.loc.start,
+ end: tokenBeforeBody.loc.end,
+ },
+ messageId,
+ data: { functionName },
+ });
+ },
+ };
+};
diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/test.js b/scripts/tools/eslint-plugin-prettier-internal-rules/test.js
index 340b967a9989..5878aa80127a 100644
--- a/scripts/tools/eslint-plugin-prettier-internal-rules/test.js
+++ b/scripts/tools/eslint-plugin-prettier-internal-rules/test.js
@@ -640,6 +640,31 @@ test("prefer-is-non-empty-array", {
],
});
+test("print-function-parameter-order", {
+ valid: [
+ "function printFoo(path, options, print) {}",
+ "function printFoo(path, opts, print) {}",
+ "function printFoo(path, options, printPath) {}",
+ "function printFoo() {}",
+ "function printFoo(path, print) {}",
+ "function printFoo(path, options) {}",
+ "function printFoo(print, options) {}",
+ "function embed(path, print, textToDoc, options) {}",
+ ],
+ invalid: [
+ "function printFoo(path, print, options) {}",
+ "function printFoo(path, print, options, args) {}",
+ "function printFoo(options, print, path) {}",
+ "const printFoo = function (path, print, options) {}",
+ "const printFoo = function printFoo(path, print, options) {}",
+ "const printFoo = (path, print, options) => {}",
+ ].map((code) => ({
+ code,
+ errors: 1,
+});
test("no-empty-flat-contents-for-if-break", {
valid: [
"ifBreak('foo', 'bar')",
diff --git a/src/language-handlebars/printer-glimmer.js b/src/language-handlebars/printer-glimmer.js
index c360d2312e2b..44ed0f83bf46 100644
--- a/src/language-handlebars/printer-glimmer.js
+++ b/src/language-handlebars/printer-glimmer.js
@@ -79,17 +79,17 @@ function print(path, options, print) {
if (isElseIfLike(path)) {
return [
printElseIfLikeBlock(path, print),
];
}
return [
printOpenBlock(path, print),
group([
- printCloseBlock(path, print, options),
+ printCloseBlock(path, options, print),
]),
@@ -573,7 +573,7 @@ function printElseIfLikeBlock(path, print) {
]);
-function printCloseBlock(path, print, options) {
+function printCloseBlock(path, options, print) {
if (options.htmlWhitespaceSensitivity === "ignore") {
@@ -616,7 +616,7 @@ function blockStatementHasElse(node) {
return node.type === "BlockStatement" && node.inverse;
-function printProgram(path, print, options) {
+function printProgram(path, options, print) {
if (blockStatementHasOnlyWhitespaceInProgram(node)) {
@@ -632,7 +632,7 @@ function printProgram(path, print, options) {
return indent(program);
-function printInverse(path, print, options) {
+function printInverse(path, options, print) {
const inverse = print("inverse");
diff --git a/src/language-js/print/array.js b/src/language-js/print/array.js
index dc2625423dd1..fa6c453403dc 100644
--- a/src/language-js/print/array.js
+++ b/src/language-js/print/array.js
@@ -135,9 +135,9 @@ function printArray(path, options, print) {
printArrayElements(
path,
options,
+ print,
elementsProperty,
node.inexact,
),
trailingComma,
],
@@ -192,7 +192,7 @@ function isLineAfterElementEmpty({ node }, { originalText: text }) {
return isNextLineEmptyAfterIndex(text, skipToComma(locEnd(node)));
-function printArrayElements(path, options, elementsProperty, inexact, print) {
+function printArrayElements(path, options, print, elementsProperty, inexact) {
const parts = [];
path.each(({ node, isLast }) => {
diff --git a/src/language-js/print/arrow-function.js b/src/language-js/print/arrow-function.js
index 05586c322f9d..27fde82936af 100644
--- a/src/language-js/print/arrow-function.js
+++ b/src/language-js/print/arrow-function.js
@@ -189,8 +189,8 @@ function printArrowFunctionSignature(path, options, print, args) {
group([
printFunctionParameters(
path,
expandArg,
/* printTypeParams */ true,
diff --git a/src/language-js/print/binaryish.js b/src/language-js/print/binaryish.js
index 92a838db097f..4cd85975f64a 100644
--- a/src/language-js/print/binaryish.js
+++ b/src/language-js/print/binaryish.js
@@ -51,8 +51,8 @@ function printBinaryishExpression(path, options, print) {
const parts = printBinaryishExpressions(
/* isNested */ false,
isInsideParenthesis,
@@ -193,8 +193,8 @@ function printBinaryishExpression(path, options, print) {
// broken before `+`.
function printBinaryishExpressions(
isNested,
isInsideParenthesis,
@@ -225,8 +225,8 @@ function printBinaryishExpressions(
(left) =>
printBinaryishExpressions(
left,
/* isNested */ true,
isInsideParenthesis,
@@ -283,8 +283,8 @@ function printBinaryishExpressions(
(left) =>
printBinaryishExpressions(
left,
- print,
options,
+ print,
/* isNested */ true,
isInsideParenthesis,
),
diff --git a/src/language-js/print/component.js b/src/language-js/print/component.js
index 777de08f98d9..cb6597396d95 100644
--- a/src/language-js/print/component.js
+++ b/src/language-js/print/component.js
@@ -32,7 +32,7 @@ function printComponent(path, options, print) {
parts.push(print("typeParameters"));
- const parametersDoc = printComponentParameters(path, print, options);
if (node.rendersType) {
parts.push(group([parametersDoc, " ", print("rendersType")]));
} else {
@@ -50,7 +50,7 @@ function printComponent(path, options, print) {
return parts;
-function printComponentParameters(path, print, options) {
+function printComponentParameters(path, options, print) {
const { node: componentNode } = path;
let parameters = componentNode.params;
if (componentNode.rest) {
diff --git a/src/language-js/print/enum.js b/src/language-js/print/enum.js
index 9e1f6d38037a..acb1bd832d24 100644
--- a/src/language-js/print/enum.js
+++ b/src/language-js/print/enum.js
@@ -1,9 +1,5 @@
import { printDeclareToken } from "./misc.js";
-import { printObject } from "./object.js";
-
-function printEnumMembers(path, print, options) {
- return printObject(path, options, print);
-}
+import { printObject as printEnumMembers } from "./object.js";
- `EnumBooleanMember`(flow)
@@ -48,7 +44,7 @@ function printEnumMember(path, print) {
- `EnumStringBody`(flow)
- `EnumSymbolBody`(flow)
-function printEnumBody(path, print, options) {
+function printEnumBody(path, options, print) {
let type;
@@ -72,7 +68,7 @@ function printEnumBody(path, print, options) {
- return [type ? `of ${type} ` : "", printEnumMembers(path, print, options)];
+ return [type ? `of ${type} ` : "", printEnumMembers(path, options, print)];
@@ -80,7 +76,7 @@ function printEnumBody(path, print, options) {
- `EnumDeclaration`(flow)
- `TSEnumDeclaration`(TypeScript)
-function printEnumDeclaration(path, print, options) {
+function printEnumDeclaration(path, options, print) {
return [
printDeclareToken(path),
@@ -89,7 +85,7 @@ function printEnumDeclaration(path, print, options) {
print("id"),
" ",
node.type === "TSEnumDeclaration"
- ? printEnumMembers(path, print, options)
: print("body"),
diff --git a/src/language-js/print/estree.js b/src/language-js/print/estree.js
index 3e5c93882681..7f0adfe188e7 100644
--- a/src/language-js/print/estree.js
+++ b/src/language-js/print/estree.js
@@ -173,7 +173,7 @@ function printEstree(path, options, print, args) {
return printRestSpread(path, print);
case "FunctionDeclaration":
case "FunctionExpression":
- return printFunction(path, print, options, args);
+ return printFunction(path, options, print, args);
case "ArrowFunctionExpression":
return printArrowFunction(path, options, print, args);
case "YieldExpression":
@@ -632,7 +632,7 @@ function printEstree(path, options, print, args) {
case "TemplateElement":
return replaceEndOfLine(node.value.raw);
case "TemplateLiteral":
case "TaggedTemplateExpression":
return printTaggedTemplateLiteral(path, print);
case "PrivateIdentifier":
diff --git a/src/language-js/print/flow.js b/src/language-js/print/flow.js
index dd9057977778..0005631cd220 100644
--- a/src/language-js/print/flow.js
+++ b/src/language-js/print/flow.js
@@ -159,14 +159,14 @@ function printFlow(path, options, print) {
case "DeclareEnum":
case "EnumDeclaration":
case "EnumBooleanBody":
case "EnumNumberBody":
case "EnumBigIntBody":
case "EnumStringBody":
case "EnumSymbolBody":
+ return printEnumBody(path, options, print);
case "EnumBooleanMember":
case "EnumNumberMember":
diff --git a/src/language-js/print/function-parameters.js b/src/language-js/print/function-parameters.js
index a8e7773db8e4..8c8273dbd0b1 100644
--- a/src/language-js/print/function-parameters.js
+++ b/src/language-js/print/function-parameters.js
@@ -33,8 +33,8 @@ import { printFunctionTypeParameters } from "./misc.js";
function printFunctionParameters(
expandArg,
printTypeParams,
diff --git a/src/language-js/print/function.js b/src/language-js/print/function.js
index 28743fc31a5e..0c71e4b1cd92 100644
--- a/src/language-js/print/function.js
+++ b/src/language-js/print/function.js
@@ -52,7 +52,7 @@ const isMethodValue = ({ node, key, parent }) =>
- "FunctionExpression"
- `TSDeclareFunction`(TypeScript)
-function printFunction(path, print, options, args) {
+function printFunction(path, options, print, args) {
if (isMethodValue(path)) {
return printMethodValue(path, options, print);
@@ -86,8 +86,8 @@ function printFunction(path, print, options, args) {
expandArg,
@@ -155,7 +155,7 @@ function printMethod(path, options, print) {
function printMethodValue(path, options, print) {
- const parametersDoc = printFunctionParameters(path, print, options);
+ const parametersDoc = printFunctionParameters(path, options, print);
const shouldBreakParameters = shouldBreakFunctionParameters(node);
const shouldGroupParameters = shouldGroupFunctionParameters(
diff --git a/src/language-js/print/hook.js b/src/language-js/print/hook.js
index 9da7de100a99..8f23a342e95e 100644
--- a/src/language-js/print/hook.js
+++ b/src/language-js/print/hook.js
@@ -25,8 +25,8 @@ function printHook(path, options, print) {
false,
true,
@@ -90,8 +90,8 @@ function printHookTypeAnnotation(path, options, print) {
diff --git a/src/language-js/print/template-literal.js b/src/language-js/print/template-literal.js
index a2baf1f3f98a..db81d5a9d157 100644
--- a/src/language-js/print/template-literal.js
+++ b/src/language-js/print/template-literal.js
@@ -22,7 +22,7 @@ import {
isMemberExpression,
} from "../utils/index.js";
-function printTemplateLiteral(path, print, options) {
const isTemplateLiteral = node.type === "TemplateLiteral";
diff --git a/src/language-js/print/type-annotation.js b/src/language-js/print/type-annotation.js
index 3b736a7a72a6..f53943c6ee69 100644
--- a/src/language-js/print/type-annotation.js
+++ b/src/language-js/print/type-annotation.js
@@ -298,8 +298,8 @@ function printFunctionType(path, options, print) {
diff --git a/src/language-js/print/typescript.js b/src/language-js/print/typescript.js
index abd4a51b1447..50ca6583cca0 100644
--- a/src/language-js/print/typescript.js
+++ b/src/language-js/print/typescript.js
@@ -103,7 +103,7 @@ function printTypescript(path, options, print) {
return group([castGroup, print("expression")]);
case "TSDeclareFunction":
- return printFunction(path, print, options);
+ return printFunction(path, options, print);
case "TSExportAssignment":
return ["export = ", print("expression"), semi];
case "TSModuleBlock":
@@ -133,7 +133,7 @@ function printTypescript(path, options, print) {
case "TSTemplateLiteralType":
case "TSNamedTupleMember":
return printNamedTupleMember(path, options, print);
case "TSRestType":
@@ -245,8 +245,8 @@ function printTypescript(path, options, print) {
const parametersDoc = printFunctionParameters(
path,
options,
+ print,
/* expandArg */ false,
/* printTypeParams */ true,
);
@@ -274,7 +274,7 @@ function printTypescript(path, options, print) {
case "TSNamespaceExportDeclaration":
return ["export as namespace ", print("id"), options.semi ? ";" : ""];
case "TSEnumDeclaration":
case "TSEnumMember":
return printEnumMember(path, print);
diff --git a/src/language-yaml/print/block.js b/src/language-yaml/print/block.js
index 7bd988004754..564bd18745ad 100644
--- a/src/language-yaml/print/block.js
+++ b/src/language-yaml/print/block.js
@@ -17,7 +17,7 @@ import {
-function printBlock(path, print, options) {
+function printBlock(path, options, print) {
const parentIndent = path.ancestors.filter(
(node) => node.type === "sequence" || node.type === "mapping",
diff --git a/src/language-yaml/print/flow-mapping-sequence.js b/src/language-yaml/print/flow-mapping-sequence.js
index 36c0dc7f7acc..4a964743bdf5 100644
--- a/src/language-yaml/print/flow-mapping-sequence.js
+++ b/src/language-yaml/print/flow-mapping-sequence.js
@@ -8,7 +8,7 @@ import {
import { hasEndComments, isEmptyNode } from "../utils.js";
import { alignWithSpaces, printNextEmptyLine } from "./misc.js";
-function printFlowMapping(path, print, options) {
+function printFlowMapping(path, options, print) {
const isMapping = node.type === "flowMapping";
const openMarker = isMapping ? "{" : "[";
@@ -29,7 +29,7 @@ function printFlowMapping(path, print, options) {
openMarker,
alignWithSpaces(options.tabWidth, [
bracketSpacing,
- printChildren(path, print, options),
+ printChildren(path, options, print),
options.trailingComma === "none" ? "" : ifBreak(","),
hasEndComments(node)
? [hardline, join(hardline, path.map(print, "endComments"))]
@@ -40,7 +40,7 @@ function printFlowMapping(path, print, options) {
-function printChildren(path, print, options) {
return path.map(
({ isLast, node, next }) => [
print(),
diff --git a/src/language-yaml/print/mapping-item.js b/src/language-yaml/print/mapping-item.js
index c9c4b408fbde..b04c88d7aa92 100644
--- a/src/language-yaml/print/mapping-item.js
+++ b/src/language-yaml/print/mapping-item.js
@@ -18,7 +18,7 @@ import {
+function printMappingItem(path, options, print) {
const { node, parent } = path;
const { key, value } = node;
diff --git a/src/language-yaml/printer-yaml.js b/src/language-yaml/printer-yaml.js
index 4f71218abdde..b1f447c0e0d4 100644
--- a/src/language-yaml/printer-yaml.js
+++ b/src/language-yaml/printer-yaml.js
@@ -305,7 +305,7 @@ function printNode(path, options, print) {
case "blockFolded":
case "blockLiteral":
- return printBlock(path, print, options);
+ return printBlock(path, options, print);
case "mapping":
case "sequence":
@@ -317,12 +317,12 @@ function printNode(path, options, print) {
return !node.content ? "" : print("content");
case "mappingItem":
case "flowMappingItem":
- return printMappingItem(path, print, options);
+ return printMappingItem(path, options, print);
case "flowMapping":
+ return printFlowMapping(path, options, print);
case "flowSequence":
- return printFlowSequence(path, print, options);
+ return printFlowSequence(path, options, print);
case "flowSequenceItem":
return print("content");
default: | [
"+ // `embed` function order is `textToDoc, print, path, options`",
"+ output: null,",
"+ })),",
"- print,",
"+ const parametersDoc = printComponentParameters(path, options, print);",
"+ ? printEnumMembers(path, options, print)",
"- return printEnumBody(path, print, options);",
"+function printTemplateLiteral(path, options, print) {",
"- print,",
"+function printChildren(path, options, print) {",
"-function printMappingItem(path, print, options) {",
"- return printFlowMapping(path, print, options);"
] | [
48,
111,
113,
184,
264,
324,
366,
450,
494,
549,
561,
587
] | {
"additions": 129,
"author": "fisker",
"deletions": 52,
"html_url": "https://github.com/prettier/prettier/pull/10402",
"issue_id": 10402,
"merged_at": "2025-04-09T03:07:46Z",
"omission_probability": 0.1,
"pr_number": 10402,
"repo": "prettier/prettier",
"title": "Consistent `print*` function parameters order",
"total_changes": 181
} |
189 | diff --git a/.github/workflows/prod-test.yml b/.github/workflows/prod-test.yml
index 5df852db8372..4a12cf2d204a 100644
--- a/.github/workflows/prod-test.yml
+++ b/.github/workflows/prod-test.yml
@@ -152,7 +152,7 @@ jobs:
run: node -v | grep "v0.10.48" || exit 1
- name: Run CLI on Node.js v0.10.48
- run: node dist/bin/prettier.cjs --version 2>&1 >/dev/null | grep "prettier requires at least version 14 of Node, please upgrade" || exit 1
+ run: node dist/prettier/bin/prettier.cjs --version 2>&1 >/dev/null | grep "prettier requires at least version 14 of Node, please upgrade" || exit 1
preview:
if: github.event_name == 'pull_request' && github.repository == 'prettier/prettier'
@@ -178,4 +178,4 @@ jobs:
- name: Release
run: |
npx pkg-pr-new publish --compact
- working-directory: dist
+ working-directory: dist/prettier
diff --git a/jest.config.js b/jest.config.js
index 21080c5ff6f4..acce11cf91e4 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -13,7 +13,7 @@ const SKIP_PRODUCTION_INSTALL = Boolean(process.env.SKIP_PRODUCTION_INSTALL);
const SKIP_TESTS_WITH_NEW_SYNTAX = process.versions.node.startsWith("14.");
let PRETTIER_DIR = isProduction
- ? path.join(PROJECT_ROOT, "dist")
+ ? path.join(PROJECT_ROOT, "dist/prettier")
: PROJECT_ROOT;
let PRETTIER_INSTALLED_DIR = "";
if (
diff --git a/package.json b/package.json
index 284c9e35acde..f69847bf9155 100644
--- a/package.json
+++ b/package.json
@@ -162,9 +162,9 @@
"test:dev-package": "cross-env INSTALL_PACKAGE=1 yarn test",
"test:dist": "cross-env NODE_ENV=production yarn test",
"test:dist-standalone": "cross-env TEST_STANDALONE=1 yarn test:dist",
- "test:dist-lint": "eslint dist --config=./scripts/bundle-eslint-config.js --quiet",
- "perf": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin/prettier.cjs",
- "perf:inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin/prettier.cjs",
+ "test:dist-lint": "eslint dist/prettier --config=./scripts/bundle-eslint-config.js --quiet --format friendly",
+ "perf": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/prettier/bin/prettier.cjs",
+ "perf:inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/prettier/bin/prettier.cjs",
"perf:benchmark": "yarn perf --debug-benchmark",
"perf:compare": "./scripts/benchmark/compare.sh",
"lint": "run-p --continue-on-error \"lint:*\"",
diff --git a/scripts/build-website.js b/scripts/build-website.js
index 7a9bd7066e81..95d913f6040a 100644
--- a/scripts/build-website.js
+++ b/scripts/build-website.js
@@ -20,7 +20,7 @@ const runYarn = (command, args, options) =>
spawn("yarn", [command, ...args], { stdio: "inherit", ...options });
const IS_PULL_REQUEST = process.env.PULL_REQUEST === "true";
const PRETTIER_DIR = IS_PULL_REQUEST
- ? DIST_DIR
+ ? path.join(DIST_DIR, "prettier")
: url.fileURLToPath(new URL("../node_modules/prettier", import.meta.url));
const PLAYGROUND_PRETTIER_DIR = path.join(WEBSITE_DIR, "static/lib");
diff --git a/scripts/build/build-dependencies-license.js b/scripts/build/build-dependencies-license.js
index e3039d9754a6..a1d5bd69fcdb 100644
--- a/scripts/build/build-dependencies-license.js
+++ b/scripts/build/build-dependencies-license.js
@@ -2,7 +2,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { outdent } from "outdent";
import rollupPluginLicense from "rollup-plugin-license";
-import { DIST_DIR, PROJECT_ROOT } from "../utils/index.js";
+import { PROJECT_ROOT } from "../utils/index.js";
const separator = `\n${"-".repeat(40)}\n\n`;
@@ -120,7 +120,14 @@ function getLicenseText(dependencies) {
return [head, content].join("\n\n");
}
-async function buildDependenciesLicense({ file, files, results, cliOptions }) {
+async function buildDependenciesLicense({
+ packageConfig,
+ file,
+ results,
+ cliOptions,
+}) {
+ const { distDirectory, files } = packageConfig;
+
const fileName = file.output.file;
if (files.at(-1) !== file) {
@@ -144,7 +151,7 @@ async function buildDependenciesLicense({ file, files, results, cliOptions }) {
const text = getLicenseText(dependencies);
- await fs.writeFile(path.join(DIST_DIR, fileName), text);
+ await fs.writeFile(path.join(distDirectory, fileName), text);
}
export default buildDependenciesLicense;
diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js
index 49ba81294628..876dec206ab0 100644
--- a/scripts/build/build-javascript-module.js
+++ b/scripts/build/build-javascript-module.js
@@ -4,7 +4,7 @@ import browserslistToEsbuild from "browserslist-to-esbuild";
import esbuild from "esbuild";
import { nodeModulesPolyfillPlugin as esbuildPluginNodeModulePolyfills } from "esbuild-plugins-node-modules-polyfill";
import createEsmUtils from "esm-utils";
-import { DIST_DIR, PROJECT_ROOT } from "../utils/index.js";
+import { PROJECT_ROOT } from "../utils/index.js";
import esbuildPluginAddDefaultExport from "./esbuild-plugins/add-default-export.js";
import esbuildPluginEvaluate from "./esbuild-plugins/evaluate.js";
import esbuildPluginPrimitiveDefine from "./esbuild-plugins/primitive-define.js";
@@ -35,7 +35,9 @@ const getRelativePath = (from, to) => {
return relativePath;
};
-function getEsbuildOptions({ file, files, cliOptions }) {
+function getEsbuildOptions({ packageConfig, file, cliOptions }) {
+ const { distDirectory, files } = packageConfig;
+
// Save dependencies to file
file.dependencies = [];
@@ -232,7 +234,7 @@ function getEsbuildOptions({ file, files, cliOptions }) {
target: [...(buildOptions.target ?? ["node14"])],
logLevel: "error",
format: file.output.format,
- outfile: path.join(DIST_DIR, cliOptions.saveAs ?? file.output.file),
+ outfile: path.join(distDirectory, cliOptions.saveAs ?? file.output.file),
// https://esbuild.github.io/api/#main-fields
mainFields: file.platform === "node" ? ["module", "main"] : undefined,
supported: {
diff --git a/scripts/build/build-package-json.js b/scripts/build/build-package-json.js
index bc8e1376cb86..10561ad77d21 100644
--- a/scripts/build/build-package-json.js
+++ b/scripts/build/build-package-json.js
@@ -1,5 +1,5 @@
import path from "node:path";
-import { DIST_DIR, PROJECT_ROOT, readJson, writeJson } from "../utils/index.js";
+import { PROJECT_ROOT, readJson, writeJson } from "../utils/index.js";
const keysToKeep = [
"name",
@@ -20,7 +20,8 @@ const keysToKeep = [
"preferUnplugged",
];
-async function buildPackageJson({ file, files }) {
+async function buildPackageJson({ packageConfig, file }) {
+ const { distDirectory, files } = packageConfig;
const packageJson = await readJson(path.join(PROJECT_ROOT, file.input));
const bin = files.find(
@@ -102,7 +103,7 @@ async function buildPackageJson({ file, files }) {
};
await writeJson(
- path.join(DIST_DIR, file.output.file),
+ path.join(distDirectory, file.output.file),
Object.assign(pick(packageJson, keysToKeep), overrides),
);
}
diff --git a/scripts/build/build-types.js b/scripts/build/build-types.js
index 6e6d96991ec4..1e65175c0861 100644
--- a/scripts/build/build-types.js
+++ b/scripts/build/build-types.js
@@ -3,9 +3,9 @@ import path from "node:path";
import url from "node:url";
import { isValidIdentifier } from "@babel/types";
import { outdent } from "outdent";
-import { DIST_DIR, PROJECT_ROOT, writeFile } from "../utils/index.js";
+import { PROJECT_ROOT, writeFile } from "../utils/index.js";
-async function typesFileBuilder({ file }) {
+async function typesFileBuilder({ packageConfig, file }) {
/**
* @typedef {{ from: string, to: string }} ImportPathReplacement
* @typedef {{ [input: string]: Array<ImportPathReplacement> }} ReplacementMap
@@ -20,14 +20,17 @@ async function typesFileBuilder({ file }) {
for (const { from, to } of replacements) {
text = text.replaceAll(` from "${from}";`, ` from "${to}";`);
}
- await writeFile(path.join(DIST_DIR, file.output.file), text);
+ await writeFile(
+ path.join(packageConfig.distDirectory, file.output.file),
+ text,
+ );
}
function toPropertyKey(name) {
return isValidIdentifier(name) ? name : JSON.stringify(name);
}
-async function buildPluginTypes({ file: { input, output } }) {
+async function buildPluginTypes({ packageConfig, file: { input, output } }) {
const pluginModule = await import(
url.pathToFileURL(path.join(PROJECT_ROOT, input))
);
@@ -52,7 +55,10 @@ async function buildPluginTypes({ file: { input, output } }) {
};
`;
- await writeFile(path.join(DIST_DIR, output.file), `${code}\n`);
+ await writeFile(
+ path.join(packageConfig.distDirectory, output.file),
+ `${code}\n`,
+ );
}
function buildTypes(options) {
diff --git a/scripts/build/build.js b/scripts/build/build.js
index 44994148fb8e..61a93aaef06a 100644
--- a/scripts/build/build.js
+++ b/scripts/build/build.js
@@ -7,7 +7,7 @@ import createEsmUtils from "esm-utils";
import styleText from "node-style-text";
import prettyBytes from "pretty-bytes";
import { DIST_DIR } from "../utils/index.js";
-import files from "./config.js";
+import packageConfig from "./config.js";
import parseArguments from "./parse-arguments.js";
const { require } = createEsmUtils(import.meta);
@@ -44,7 +44,8 @@ const clear = () => {
readline.cursorTo(process.stdout, 0, null);
};
-async function buildFile({ file, files, cliOptions, results }) {
+async function buildFile({ packageConfig, file, cliOptions, results }) {
+ const { distDirectory } = packageConfig;
let displayName = file.output.file;
if (
(file.platform === "universal" && file.output.format !== "esm") ||
@@ -69,7 +70,7 @@ async function buildFile({ file, files, cliOptions, results }) {
let result;
try {
- result = await file.build({ file, files, cliOptions, results });
+ result = await file.build({ packageConfig, file, cliOptions, results });
} catch (error) {
console.log(status.FAIL + "\n");
console.error(error);
@@ -87,7 +88,7 @@ async function buildFile({ file, files, cliOptions, results }) {
const sizeMessages = [];
if (cliOptions.printSize) {
- const { size } = await fs.stat(path.join(DIST_DIR, outputFile));
+ const { size } = await fs.stat(path.join(distDirectory, outputFile));
sizeMessages.push(prettyBytes(size));
}
@@ -103,7 +104,7 @@ async function buildFile({ file, files, cliOptions, results }) {
}
if (stableSize) {
- const { size } = await fs.stat(path.join(DIST_DIR, outputFile));
+ const { size } = await fs.stat(path.join(distDirectory, outputFile));
const sizeDiff = size - stableSize;
const message = styleText[sizeDiff > 0 ? "yellow" : "green"](
prettyBytes(sizeDiff),
@@ -151,8 +152,13 @@ async function run() {
console.log(styleText.inverse(" Building packages "));
const results = [];
- for (const file of files) {
- const result = await buildFile({ file, files, cliOptions, results });
+ for (const file of packageConfig.files) {
+ const result = await buildFile({
+ packageConfig,
+ file,
+ cliOptions,
+ results,
+ });
results.push(result);
}
}
diff --git a/scripts/build/config.js b/scripts/build/config.js
index 0035636b50ef..91212ad3582b 100644
--- a/scripts/build/config.js
+++ b/scripts/build/config.js
@@ -19,10 +19,10 @@ const {
} = createEsmUtils(import.meta);
const resolveEsmModulePath = (specifier) =>
url.fileURLToPath(importMetaResolve(specifier));
-const copyFileBuilder = ({ file }) =>
+const copyFileBuilder = ({ packageConfig, file }) =>
copyFile(
path.join(PROJECT_ROOT, file.input),
- path.join(DIST_DIR, file.output.file),
+ path.join(packageConfig.distDirectory, file.output.file),
);
function getTypesFileConfig({ input: jsFileInput, outputBaseName, isPlugin }) {
@@ -38,7 +38,7 @@ function getTypesFileConfig({ input: jsFileInput, outputBaseName, isPlugin }) {
return {
input,
output: {
- file: outputBaseName + ".d.ts",
+ file: `${outputBaseName}.d.ts`,
},
kind: "types",
isPlugin,
@@ -867,4 +867,8 @@ const metaFiles = [
/** @type {Files[]} */
const files = [...nodejsFiles, ...universalFiles, ...metaFiles].filter(Boolean);
-export default files;
+export default {
+ packageName: "prettier",
+ distDirectory: path.join(DIST_DIR, "prettier"),
+ files,
+};
diff --git a/scripts/build/parse-arguments.js b/scripts/build/parse-arguments.js
index 5c84e16acf8b..b6e39d7909df 100644
--- a/scripts/build/parse-arguments.js
+++ b/scripts/build/parse-arguments.js
@@ -39,7 +39,9 @@ function parseArguments() {
);
}
- if (!path.join(DIST_DIR, result.saveAs).startsWith(DIST_DIR)) {
+ // TODO: Support package name
+ const distDirectory = path.join(DIST_DIR, "prettier");
+ if (!path.join(distDirectory, result.saveAs).startsWith(distDirectory)) {
throw new Error("'--save-as' can only relative path");
}
}
diff --git a/scripts/release/steps/generate-bundles.js b/scripts/release/steps/generate-bundles.js
index 7d38c24eb89f..ba5a4eb9112e 100644
--- a/scripts/release/steps/generate-bundles.js
+++ b/scripts/release/steps/generate-bundles.js
@@ -11,10 +11,10 @@ export default async function generateBundles({ dry, version, manual }) {
runYarn(["build", "--clean", "--print-size", "--compare-size"]),
);
- const builtPkg = await readJson("dist/package.json");
+ const builtPkg = await readJson("dist/prettier/package.json");
if (!dry && builtPkg.version !== version) {
throw new Error(
- `Expected ${version} in dist/package.json but found ${builtPkg.version}`,
+ `Expected ${version} in dist/prettier/package.json but found ${builtPkg.version}`,
);
}
diff --git a/scripts/release/steps/publish-to-npm.js b/scripts/release/steps/publish-to-npm.js
index 6f9473f8440e..ec6c4ca2320b 100644
--- a/scripts/release/steps/publish-to-npm.js
+++ b/scripts/release/steps/publish-to-npm.js
@@ -24,7 +24,7 @@ export default async function publishToNpm({ dry }) {
args.push("--otp", otp);
}
- await spawn("npm", args, { cwd: "./dist" });
+ await spawn("npm", args, { cwd: "./dist/prettier" });
};
/**
diff --git a/scripts/tools/bundle-test/index.js b/scripts/tools/bundle-test/index.js
index fdab387f51e1..5badfc60e3ec 100644
--- a/scripts/tools/bundle-test/index.js
+++ b/scripts/tools/bundle-test/index.js
@@ -2,8 +2,7 @@ import { createRequire } from "node:module";
import path from "node:path";
import url from "node:url";
import webpack from "webpack";
-import files from "../../build/config.js";
-import { DIST_DIR } from "../../utils/index.js";
+import packageConfig from "../../build/config.js";
function runWebpack(config) {
return new Promise((resolve, reject) => {
@@ -30,6 +29,7 @@ const TEMPORARY_DIRECTORY = url.fileURLToPath(
new URL("./.tmp", import.meta.url),
);
+const { distDirectory, files } = packageConfig;
/* `require` in `parser-typescript.js`, #12338 */
for (const file of files) {
if (file.platform !== "universal") {
@@ -39,7 +39,7 @@ for (const file of files) {
const stats = await runWebpack({
mode: "production",
- entry: path.join(DIST_DIR, file.output.file),
+ entry: path.join(distDirectory, file.output.file),
output: {
path: TEMPORARY_DIRECTORY,
filename: `${file.output.file}.[contenthash:7].${
diff --git a/tests/dts/unit/cases/parsers.ts b/tests/dts/unit/cases/parsers.ts
index 94990a6fa907..6157ab57739c 100644
--- a/tests/dts/unit/cases/parsers.ts
+++ b/tests/dts/unit/cases/parsers.ts
@@ -1,18 +1,18 @@
-import * as prettier from "../../../../dist/index.js";
+import * as prettier from "../../../../dist/prettier/index.js";
-import * as prettierPluginEstree from "../../../../dist/plugins/estree.js";
-import * as prettierPluginBabel from "../../../../dist/plugins/babel.js";
-import * as prettierPluginFlow from "../../../../dist/plugins/flow.js";
-import * as prettierPluginTypeScript from "../../../../dist/plugins/typescript.js";
-import * as prettierPluginAcorn from "../../../../dist/plugins/acorn.js";
-import * as prettierPluginMeriyah from "../../../../dist/plugins/meriyah.js";
-import * as prettierPluginAngular from "../../../../dist/plugins/angular.js";
-import * as prettierPluginPostcss from "../../../../dist/plugins/postcss.js";
-import * as prettierPluginGraphql from "../../../../dist/plugins/graphql.js";
-import * as prettierPluginMarkdown from "../../../../dist/plugins/markdown.js";
-import * as prettierPluginGlimmer from "../../../../dist/plugins/glimmer.js";
-import * as prettierPluginHtml from "../../../../dist/plugins/html.js";
-import * as prettierPluginYaml from "../../../../dist/plugins/yaml.js";
+import * as prettierPluginEstree from "../../../../dist/prettier/plugins/estree.js";
+import * as prettierPluginBabel from "../../../../dist/prettier/plugins/babel.js";
+import * as prettierPluginFlow from "../../../../dist/prettier/plugins/flow.js";
+import * as prettierPluginTypeScript from "../../../../dist/prettier/plugins/typescript.js";
+import * as prettierPluginAcorn from "../../../../dist/prettier/plugins/acorn.js";
+import * as prettierPluginMeriyah from "../../../../dist/prettier/plugins/meriyah.js";
+import * as prettierPluginAngular from "../../../../dist/prettier/plugins/angular.js";
+import * as prettierPluginPostcss from "../../../../dist/prettier/plugins/postcss.js";
+import * as prettierPluginGraphql from "../../../../dist/prettier/plugins/graphql.js";
+import * as prettierPluginMarkdown from "../../../../dist/prettier/plugins/markdown.js";
+import * as prettierPluginGlimmer from "../../../../dist/prettier/plugins/glimmer.js";
+import * as prettierPluginHtml from "../../../../dist/prettier/plugins/html.js";
+import * as prettierPluginYaml from "../../../../dist/prettier/plugins/yaml.js";
const options: prettier.ParserOptions = {
filepath: "/home/mark/prettier/bin/prettier.js",
diff --git a/tests/integration/__tests__/bundle.js b/tests/integration/__tests__/bundle.js
index f10cca8a256e..9e60e8708b52 100644
--- a/tests/integration/__tests__/bundle.js
+++ b/tests/integration/__tests__/bundle.js
@@ -11,7 +11,7 @@ import { projectRoot } from "../env.js";
const { require, importModule } = createEsmUtils(import.meta);
const parserNames = coreOptions.parser.choices.map(({ value }) => value);
-const distDirectory = path.join(projectRoot, "dist");
+const distDirectory = path.join(projectRoot, "dist/prettier");
// Files including U+FFEE can't load in Chrome Extension
// `prettier-chrome-extension` https://github.com/prettier/prettier-chrome-extension
| diff --git a/.github/workflows/prod-test.yml b/.github/workflows/prod-test.yml
index 5df852db8372..4a12cf2d204a 100644
--- a/.github/workflows/prod-test.yml
+++ b/.github/workflows/prod-test.yml
@@ -152,7 +152,7 @@ jobs:
run: node -v | grep "v0.10.48" || exit 1
- name: Run CLI on Node.js v0.10.48
- run: node dist/bin/prettier.cjs --version 2>&1 >/dev/null | grep "prettier requires at least version 14 of Node, please upgrade" || exit 1
+ run: node dist/prettier/bin/prettier.cjs --version 2>&1 >/dev/null | grep "prettier requires at least version 14 of Node, please upgrade" || exit 1
preview:
if: github.event_name == 'pull_request' && github.repository == 'prettier/prettier'
@@ -178,4 +178,4 @@ jobs:
- name: Release
run: |
npx pkg-pr-new publish --compact
- working-directory: dist
+ working-directory: dist/prettier
diff --git a/jest.config.js b/jest.config.js
index 21080c5ff6f4..acce11cf91e4 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -13,7 +13,7 @@ const SKIP_PRODUCTION_INSTALL = Boolean(process.env.SKIP_PRODUCTION_INSTALL);
const SKIP_TESTS_WITH_NEW_SYNTAX = process.versions.node.startsWith("14.");
let PRETTIER_DIR = isProduction
+ ? path.join(PROJECT_ROOT, "dist/prettier")
: PROJECT_ROOT;
let PRETTIER_INSTALLED_DIR = "";
if (
diff --git a/package.json b/package.json
index 284c9e35acde..f69847bf9155 100644
--- a/package.json
+++ b/package.json
@@ -162,9 +162,9 @@
"test:dev-package": "cross-env INSTALL_PACKAGE=1 yarn test",
"test:dist": "cross-env NODE_ENV=production yarn test",
"test:dist-standalone": "cross-env TEST_STANDALONE=1 yarn test:dist",
- "test:dist-lint": "eslint dist --config=./scripts/bundle-eslint-config.js --quiet",
- "perf": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin/prettier.cjs",
- "perf:inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin/prettier.cjs",
+ "test:dist-lint": "eslint dist/prettier --config=./scripts/bundle-eslint-config.js --quiet --format friendly",
+ "perf": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/prettier/bin/prettier.cjs",
+ "perf:inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/prettier/bin/prettier.cjs",
"perf:benchmark": "yarn perf --debug-benchmark",
"perf:compare": "./scripts/benchmark/compare.sh",
"lint": "run-p --continue-on-error \"lint:*\"",
diff --git a/scripts/build-website.js b/scripts/build-website.js
index 7a9bd7066e81..95d913f6040a 100644
--- a/scripts/build-website.js
+++ b/scripts/build-website.js
@@ -20,7 +20,7 @@ const runYarn = (command, args, options) =>
spawn("yarn", [command, ...args], { stdio: "inherit", ...options });
const IS_PULL_REQUEST = process.env.PULL_REQUEST === "true";
const PRETTIER_DIR = IS_PULL_REQUEST
- ? DIST_DIR
+ ? path.join(DIST_DIR, "prettier")
: url.fileURLToPath(new URL("../node_modules/prettier", import.meta.url));
const PLAYGROUND_PRETTIER_DIR = path.join(WEBSITE_DIR, "static/lib");
diff --git a/scripts/build/build-dependencies-license.js b/scripts/build/build-dependencies-license.js
index e3039d9754a6..a1d5bd69fcdb 100644
--- a/scripts/build/build-dependencies-license.js
+++ b/scripts/build/build-dependencies-license.js
@@ -2,7 +2,7 @@ import fs from "node:fs/promises";
import rollupPluginLicense from "rollup-plugin-license";
const separator = `\n${"-".repeat(40)}\n\n`;
@@ -120,7 +120,14 @@ function getLicenseText(dependencies) {
return [head, content].join("\n\n");
-async function buildDependenciesLicense({ file, files, results, cliOptions }) {
+async function buildDependenciesLicense({
+ packageConfig,
+ file,
+ results,
+ cliOptions,
+}) {
const fileName = file.output.file;
if (files.at(-1) !== file) {
@@ -144,7 +151,7 @@ async function buildDependenciesLicense({ file, files, results, cliOptions }) {
const text = getLicenseText(dependencies);
- await fs.writeFile(path.join(DIST_DIR, fileName), text);
+ await fs.writeFile(path.join(distDirectory, fileName), text);
export default buildDependenciesLicense;
diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js
index 49ba81294628..876dec206ab0 100644
--- a/scripts/build/build-javascript-module.js
+++ b/scripts/build/build-javascript-module.js
@@ -4,7 +4,7 @@ import browserslistToEsbuild from "browserslist-to-esbuild";
import esbuild from "esbuild";
import { nodeModulesPolyfillPlugin as esbuildPluginNodeModulePolyfills } from "esbuild-plugins-node-modules-polyfill";
import createEsmUtils from "esm-utils";
import esbuildPluginAddDefaultExport from "./esbuild-plugins/add-default-export.js";
import esbuildPluginEvaluate from "./esbuild-plugins/evaluate.js";
import esbuildPluginPrimitiveDefine from "./esbuild-plugins/primitive-define.js";
@@ -35,7 +35,9 @@ const getRelativePath = (from, to) => {
return relativePath;
-function getEsbuildOptions({ file, files, cliOptions }) {
+function getEsbuildOptions({ packageConfig, file, cliOptions }) {
// Save dependencies to file
file.dependencies = [];
@@ -232,7 +234,7 @@ function getEsbuildOptions({ file, files, cliOptions }) {
target: [...(buildOptions.target ?? ["node14"])],
logLevel: "error",
format: file.output.format,
- outfile: path.join(DIST_DIR, cliOptions.saveAs ?? file.output.file),
+ outfile: path.join(distDirectory, cliOptions.saveAs ?? file.output.file),
// https://esbuild.github.io/api/#main-fields
mainFields: file.platform === "node" ? ["module", "main"] : undefined,
supported: {
diff --git a/scripts/build/build-package-json.js b/scripts/build/build-package-json.js
index bc8e1376cb86..10561ad77d21 100644
--- a/scripts/build/build-package-json.js
+++ b/scripts/build/build-package-json.js
@@ -1,5 +1,5 @@
-import { DIST_DIR, PROJECT_ROOT, readJson, writeJson } from "../utils/index.js";
+import { PROJECT_ROOT, readJson, writeJson } from "../utils/index.js";
const keysToKeep = [
"name",
@@ -20,7 +20,8 @@ const keysToKeep = [
"preferUnplugged",
];
-async function buildPackageJson({ file, files }) {
+async function buildPackageJson({ packageConfig, file }) {
const packageJson = await readJson(path.join(PROJECT_ROOT, file.input));
const bin = files.find(
@@ -102,7 +103,7 @@ async function buildPackageJson({ file, files }) {
await writeJson(
+ path.join(distDirectory, file.output.file),
Object.assign(pick(packageJson, keysToKeep), overrides),
diff --git a/scripts/build/build-types.js b/scripts/build/build-types.js
index 6e6d96991ec4..1e65175c0861 100644
--- a/scripts/build/build-types.js
+++ b/scripts/build/build-types.js
@@ -3,9 +3,9 @@ import path from "node:path";
import { isValidIdentifier } from "@babel/types";
-import { DIST_DIR, PROJECT_ROOT, writeFile } from "../utils/index.js";
-async function typesFileBuilder({ file }) {
+async function typesFileBuilder({ packageConfig, file }) {
* @typedef {{ from: string, to: string }} ImportPathReplacement
* @typedef {{ [input: string]: Array<ImportPathReplacement> }} ReplacementMap
@@ -20,14 +20,17 @@ async function typesFileBuilder({ file }) {
for (const { from, to } of replacements) {
text = text.replaceAll(` from "${from}";`, ` from "${to}";`);
- await writeFile(path.join(DIST_DIR, file.output.file), text);
+ text,
function toPropertyKey(name) {
return isValidIdentifier(name) ? name : JSON.stringify(name);
-async function buildPluginTypes({ file: { input, output } }) {
+async function buildPluginTypes({ packageConfig, file: { input, output } }) {
const pluginModule = await import(
url.pathToFileURL(path.join(PROJECT_ROOT, input))
@@ -52,7 +55,10 @@ async function buildPluginTypes({ file: { input, output } }) {
};
`;
- await writeFile(path.join(DIST_DIR, output.file), `${code}\n`);
+ path.join(packageConfig.distDirectory, output.file),
function buildTypes(options) {
diff --git a/scripts/build/build.js b/scripts/build/build.js
index 44994148fb8e..61a93aaef06a 100644
--- a/scripts/build/build.js
+++ b/scripts/build/build.js
@@ -7,7 +7,7 @@ import createEsmUtils from "esm-utils";
import styleText from "node-style-text";
import prettyBytes from "pretty-bytes";
import { DIST_DIR } from "../utils/index.js";
-import files from "./config.js";
+import packageConfig from "./config.js";
import parseArguments from "./parse-arguments.js";
const { require } = createEsmUtils(import.meta);
@@ -44,7 +44,8 @@ const clear = () => {
readline.cursorTo(process.stdout, 0, null);
-async function buildFile({ file, files, cliOptions, results }) {
+async function buildFile({ packageConfig, file, cliOptions, results }) {
+ const { distDirectory } = packageConfig;
let displayName = file.output.file;
if (
(file.platform === "universal" && file.output.format !== "esm") ||
@@ -69,7 +70,7 @@ async function buildFile({ file, files, cliOptions, results }) {
let result;
try {
- result = await file.build({ file, files, cliOptions, results });
+ result = await file.build({ packageConfig, file, cliOptions, results });
} catch (error) {
console.log(status.FAIL + "\n");
console.error(error);
@@ -87,7 +88,7 @@ async function buildFile({ file, files, cliOptions, results }) {
const sizeMessages = [];
if (cliOptions.printSize) {
- const { size } = await fs.stat(path.join(DIST_DIR, outputFile));
+ const { size } = await fs.stat(path.join(distDirectory, outputFile));
sizeMessages.push(prettyBytes(size));
@@ -103,7 +104,7 @@ async function buildFile({ file, files, cliOptions, results }) {
if (stableSize) {
- const { size } = await fs.stat(path.join(DIST_DIR, outputFile));
+ const { size } = await fs.stat(path.join(distDirectory, outputFile));
const sizeDiff = size - stableSize;
const message = styleText[sizeDiff > 0 ? "yellow" : "green"](
prettyBytes(sizeDiff),
@@ -151,8 +152,13 @@ async function run() {
console.log(styleText.inverse(" Building packages "));
const results = [];
- for (const file of files) {
- const result = await buildFile({ file, files, cliOptions, results });
+ for (const file of packageConfig.files) {
+ const result = await buildFile({
+ packageConfig,
+ file,
+ cliOptions,
+ });
results.push(result);
diff --git a/scripts/build/config.js b/scripts/build/config.js
index 0035636b50ef..91212ad3582b 100644
--- a/scripts/build/config.js
+++ b/scripts/build/config.js
@@ -19,10 +19,10 @@ const {
} = createEsmUtils(import.meta);
const resolveEsmModulePath = (specifier) =>
url.fileURLToPath(importMetaResolve(specifier));
-const copyFileBuilder = ({ file }) =>
+const copyFileBuilder = ({ packageConfig, file }) =>
copyFile(
path.join(PROJECT_ROOT, file.input),
function getTypesFileConfig({ input: jsFileInput, outputBaseName, isPlugin }) {
@@ -38,7 +38,7 @@ function getTypesFileConfig({ input: jsFileInput, outputBaseName, isPlugin }) {
return {
input,
- file: outputBaseName + ".d.ts",
+ file: `${outputBaseName}.d.ts`,
},
kind: "types",
isPlugin,
@@ -867,4 +867,8 @@ const metaFiles = [
/** @type {Files[]} */
const files = [...nodejsFiles, ...universalFiles, ...metaFiles].filter(Boolean);
+export default {
+ packageName: "prettier",
+ files,
+};
diff --git a/scripts/build/parse-arguments.js b/scripts/build/parse-arguments.js
index 5c84e16acf8b..b6e39d7909df 100644
--- a/scripts/build/parse-arguments.js
+++ b/scripts/build/parse-arguments.js
@@ -39,7 +39,9 @@ function parseArguments() {
);
- if (!path.join(DIST_DIR, result.saveAs).startsWith(DIST_DIR)) {
+ // TODO: Support package name
+ const distDirectory = path.join(DIST_DIR, "prettier");
+ if (!path.join(distDirectory, result.saveAs).startsWith(distDirectory)) {
throw new Error("'--save-as' can only relative path");
diff --git a/scripts/release/steps/generate-bundles.js b/scripts/release/steps/generate-bundles.js
index 7d38c24eb89f..ba5a4eb9112e 100644
--- a/scripts/release/steps/generate-bundles.js
+++ b/scripts/release/steps/generate-bundles.js
@@ -11,10 +11,10 @@ export default async function generateBundles({ dry, version, manual }) {
runYarn(["build", "--clean", "--print-size", "--compare-size"]),
- const builtPkg = await readJson("dist/package.json");
+ const builtPkg = await readJson("dist/prettier/package.json");
if (!dry && builtPkg.version !== version) {
throw new Error(
- `Expected ${version} in dist/package.json but found ${builtPkg.version}`,
+ `Expected ${version} in dist/prettier/package.json but found ${builtPkg.version}`,
);
diff --git a/scripts/release/steps/publish-to-npm.js b/scripts/release/steps/publish-to-npm.js
index 6f9473f8440e..ec6c4ca2320b 100644
--- a/scripts/release/steps/publish-to-npm.js
+++ b/scripts/release/steps/publish-to-npm.js
@@ -24,7 +24,7 @@ export default async function publishToNpm({ dry }) {
args.push("--otp", otp);
- await spawn("npm", args, { cwd: "./dist" });
+ await spawn("npm", args, { cwd: "./dist/prettier" });
diff --git a/scripts/tools/bundle-test/index.js b/scripts/tools/bundle-test/index.js
index fdab387f51e1..5badfc60e3ec 100644
--- a/scripts/tools/bundle-test/index.js
+++ b/scripts/tools/bundle-test/index.js
@@ -2,8 +2,7 @@ import { createRequire } from "node:module";
import webpack from "webpack";
-import files from "../../build/config.js";
-import { DIST_DIR } from "../../utils/index.js";
+import packageConfig from "../../build/config.js";
function runWebpack(config) {
return new Promise((resolve, reject) => {
@@ -30,6 +29,7 @@ const TEMPORARY_DIRECTORY = url.fileURLToPath(
new URL("./.tmp", import.meta.url),
);
+const { distDirectory, files } = packageConfig;
/* `require` in `parser-typescript.js`, #12338 */
for (const file of files) {
if (file.platform !== "universal") {
@@ -39,7 +39,7 @@ for (const file of files) {
const stats = await runWebpack({
mode: "production",
- entry: path.join(DIST_DIR, file.output.file),
+ entry: path.join(distDirectory, file.output.file),
path: TEMPORARY_DIRECTORY,
filename: `${file.output.file}.[contenthash:7].${
diff --git a/tests/dts/unit/cases/parsers.ts b/tests/dts/unit/cases/parsers.ts
index 94990a6fa907..6157ab57739c 100644
--- a/tests/dts/unit/cases/parsers.ts
+++ b/tests/dts/unit/cases/parsers.ts
@@ -1,18 +1,18 @@
-import * as prettier from "../../../../dist/index.js";
+import * as prettier from "../../../../dist/prettier/index.js";
-import * as prettierPluginEstree from "../../../../dist/plugins/estree.js";
-import * as prettierPluginBabel from "../../../../dist/plugins/babel.js";
-import * as prettierPluginFlow from "../../../../dist/plugins/flow.js";
-import * as prettierPluginMeriyah from "../../../../dist/plugins/meriyah.js";
-import * as prettierPluginAngular from "../../../../dist/plugins/angular.js";
-import * as prettierPluginPostcss from "../../../../dist/plugins/postcss.js";
-import * as prettierPluginGraphql from "../../../../dist/plugins/graphql.js";
-import * as prettierPluginMarkdown from "../../../../dist/plugins/markdown.js";
-import * as prettierPluginGlimmer from "../../../../dist/plugins/glimmer.js";
+import * as prettierPluginEstree from "../../../../dist/prettier/plugins/estree.js";
+import * as prettierPluginBabel from "../../../../dist/prettier/plugins/babel.js";
+import * as prettierPluginFlow from "../../../../dist/prettier/plugins/flow.js";
+import * as prettierPluginTypeScript from "../../../../dist/prettier/plugins/typescript.js";
+import * as prettierPluginAcorn from "../../../../dist/prettier/plugins/acorn.js";
+import * as prettierPluginMeriyah from "../../../../dist/prettier/plugins/meriyah.js";
+import * as prettierPluginAngular from "../../../../dist/prettier/plugins/angular.js";
+import * as prettierPluginPostcss from "../../../../dist/prettier/plugins/postcss.js";
+import * as prettierPluginGraphql from "../../../../dist/prettier/plugins/graphql.js";
+import * as prettierPluginMarkdown from "../../../../dist/prettier/plugins/markdown.js";
+import * as prettierPluginHtml from "../../../../dist/prettier/plugins/html.js";
+import * as prettierPluginYaml from "../../../../dist/prettier/plugins/yaml.js";
const options: prettier.ParserOptions = {
filepath: "/home/mark/prettier/bin/prettier.js",
diff --git a/tests/integration/__tests__/bundle.js b/tests/integration/__tests__/bundle.js
index f10cca8a256e..9e60e8708b52 100644
--- a/tests/integration/__tests__/bundle.js
+++ b/tests/integration/__tests__/bundle.js
@@ -11,7 +11,7 @@ import { projectRoot } from "../env.js";
const { require, importModule } = createEsmUtils(import.meta);
const parserNames = coreOptions.parser.choices.map(({ value }) => value);
-const distDirectory = path.join(projectRoot, "dist");
+const distDirectory = path.join(projectRoot, "dist/prettier");
// Files including U+FFEE can't load in Chrome Extension
// `prettier-chrome-extension` https://github.com/prettier/prettier-chrome-extension | [
"- ? path.join(PROJECT_ROOT, \"dist\")",
"+import { PROJECT_ROOT, writeFile } from \"../utils/index.js\";",
"+ `${code}\\n`,",
"+ results,",
"-export default files;",
"+ distDirectory: path.join(DIST_DIR, \"prettier\"),",
"-import * as prettierPluginTypeScript from \"../../../../dist/plugins/typescript.js\";",
"-import * as prettierPluginAcorn from \"../../../../dist/plugins/acorn.js\";",
"-import * as prettierPluginHtml from \"../../../../dist/plugins/html.js\";",
"-import * as prettierPluginYaml from \"../../../../dist/plugins/yaml.js\";",
"+import * as prettierPluginGlimmer from \"../../../../dist/prettier/plugins/glimmer.js\";"
] | [
27,
172,
206,
272,
307,
310,
400,
401,
408,
409,
420
] | {
"additions": 82,
"author": "fisker",
"deletions": 54,
"html_url": "https://github.com/prettier/prettier/pull/15825",
"issue_id": 15825,
"merged_at": "2025-04-09T00:38:46Z",
"omission_probability": 0.1,
"pr_number": 15825,
"repo": "prettier/prettier",
"title": "Bundle package into `dist/prettier/`",
"total_changes": 136
} |
190 | diff --git a/package.json b/package.json
index 1ccd5af71126..284c9e35acde 100644
--- a/package.json
+++ b/package.json
@@ -132,13 +132,13 @@
"eslint-plugin-unicorn": "58.0.0",
"esm-utils": "4.3.0",
"globals": "16.0.0",
+ "index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
"jest-light-runner": "0.6.0",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
"knip": "5.47.0",
- "lines-and-columns": "2.0.4",
"magic-string": "0.30.17",
"nano-spawn": "0.2.0",
"node-style-text": "0.0.7",
diff --git a/scripts/lint-changelog.js b/scripts/lint-changelog.js
index 895e6c3dc356..a558d149ed00 100644
--- a/scripts/lint-changelog.js
+++ b/scripts/lint-changelog.js
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import fs from "node:fs";
-import { LinesAndColumns } from "lines-and-columns";
+import indexToPosition from "index-to-position";
import { outdent } from "outdent";
import { CHANGELOG_CATEGORIES } from "./utils/changelog-categories.js";
@@ -142,9 +142,8 @@ for (const category of CHANGELOG_CATEGORIES) {
function getCommentDescription(content, comment) {
const start = content.indexOf(comment);
const end = start + comment.length;
- const linesAndColumns = new LinesAndColumns(content);
const [startLine, endLine] = [start, end].map(
- (index) => linesAndColumns.locationForIndex(index).line + 1,
+ (index) => indexToPosition(content, index, { oneBased: true }).line,
);
if (startLine === endLine) {
diff --git a/tests/config/utils/visualize-range.js b/tests/config/utils/visualize-range.js
index 222bc7a6f79f..220404a1a555 100644
--- a/tests/config/utils/visualize-range.js
+++ b/tests/config/utils/visualize-range.js
@@ -1,5 +1,5 @@
import { codeFrameColumns } from "@babel/code-frame";
-import { LinesAndColumns } from "lines-and-columns";
+import indexToPosition from "index-to-position";
const codeFrameColumnsOptions = {
linesAbove: Number.POSITIVE_INFINITY,
linesBelow: Number.POSITIVE_INFINITY,
@@ -9,15 +9,11 @@ const locationForRange = (text, rangeStart, rangeEnd) => {
if (rangeStart > rangeEnd) {
[rangeStart, rangeEnd] = [rangeEnd, rangeStart];
}
- const lines = new LinesAndColumns(text);
- const start = lines.locationForIndex(rangeStart);
- const end = lines.locationForIndex(rangeEnd);
- start.line += 1;
- start.column += 1;
- end.line += 1;
- if (start.line === end.line) {
- end.column += 1;
+ const start = indexToPosition(text, rangeStart, { oneBased: true });
+ const end = indexToPosition(text, rangeEnd, { oneBased: true });
+ if (start.line !== end.line) {
+ end.column -= 1;
}
return {
diff --git a/yarn.lock b/yarn.lock
index a8149c659b19..79ffd6061cd7 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4798,10 +4798,10 @@ __metadata:
languageName: node
linkType: hard
-"index-to-position@npm:^1.0.0":
- version: 1.0.0
- resolution: "index-to-position@npm:1.0.0"
- checksum: 10/4a24b8f0728da8ec6ffea85556acf809a71317d5291d31148db7c2dececa10432abf3c87a932481a2e326af66221bcf77d8dc1f0abfd11537e7f3cc21432a525
+"index-to-position@npm:1.1.0, index-to-position@npm:^1.0.0":
+ version: 1.1.0
+ resolution: "index-to-position@npm:1.1.0"
+ checksum: 10/16703893c732a025786098fe77cb7e83109afe4b72633dd6feea1595c54f8406623fa7a0a2263a8e08adee7f639fbb1c4731982cd30b4bc30d787bf803f5f3d8
languageName: node
linkType: hard
@@ -5959,13 +5959,6 @@ __metadata:
languageName: node
linkType: hard
-"lines-and-columns@npm:2.0.4":
- version: 2.0.4
- resolution: "lines-and-columns@npm:2.0.4"
- checksum: 10/81ac2f943f5428a46bd4ea2561c74ba674a107d8e6cc70cd317d16892a36ff3ba0dc6e599aca8b6f8668d26c85288394c6edf7a40e985ca843acab3701b80d4c
- languageName: node
- linkType: hard
-
"lines-and-columns@npm:^1.1.6":
version: 1.2.4
resolution: "lines-and-columns@npm:1.2.4"
@@ -6911,6 +6904,7 @@ __metadata:
html-ua-styles: "npm:0.0.8"
ignore: "npm:7.0.3"
import-meta-resolve: "npm:4.1.0"
+ index-to-position: "npm:1.1.0"
is-es5-identifier-name: "npm:1.0.0"
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
@@ -6923,7 +6917,6 @@ __metadata:
json5: "npm:2.2.3"
knip: "npm:5.47.0"
leven: "npm:4.0.0"
- lines-and-columns: "npm:2.0.4"
linguist-languages: "npm:7.29.0"
magic-string: "npm:0.30.17"
meriyah: "npm:6.0.6"
| diff --git a/package.json b/package.json
index 1ccd5af71126..284c9e35acde 100644
--- a/package.json
+++ b/package.json
@@ -132,13 +132,13 @@
"eslint-plugin-unicorn": "58.0.0",
"esm-utils": "4.3.0",
"globals": "16.0.0",
+ "index-to-position": "1.1.0",
"jest": "30.0.0-alpha.7",
"jest-light-runner": "0.6.0",
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
"knip": "5.47.0",
- "lines-and-columns": "2.0.4",
"magic-string": "0.30.17",
"nano-spawn": "0.2.0",
"node-style-text": "0.0.7",
diff --git a/scripts/lint-changelog.js b/scripts/lint-changelog.js
index 895e6c3dc356..a558d149ed00 100644
--- a/scripts/lint-changelog.js
+++ b/scripts/lint-changelog.js
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import fs from "node:fs";
import { outdent } from "outdent";
import { CHANGELOG_CATEGORIES } from "./utils/changelog-categories.js";
@@ -142,9 +142,8 @@ for (const category of CHANGELOG_CATEGORIES) {
function getCommentDescription(content, comment) {
const start = content.indexOf(comment);
const end = start + comment.length;
- const linesAndColumns = new LinesAndColumns(content);
const [startLine, endLine] = [start, end].map(
- (index) => linesAndColumns.locationForIndex(index).line + 1,
);
if (startLine === endLine) {
diff --git a/tests/config/utils/visualize-range.js b/tests/config/utils/visualize-range.js
index 222bc7a6f79f..220404a1a555 100644
--- a/tests/config/utils/visualize-range.js
+++ b/tests/config/utils/visualize-range.js
@@ -1,5 +1,5 @@
import { codeFrameColumns } from "@babel/code-frame";
const codeFrameColumnsOptions = {
linesAbove: Number.POSITIVE_INFINITY,
linesBelow: Number.POSITIVE_INFINITY,
@@ -9,15 +9,11 @@ const locationForRange = (text, rangeStart, rangeEnd) => {
if (rangeStart > rangeEnd) {
[rangeStart, rangeEnd] = [rangeEnd, rangeStart];
- const start = lines.locationForIndex(rangeStart);
- const end = lines.locationForIndex(rangeEnd);
- start.line += 1;
- start.column += 1;
- end.line += 1;
- if (start.line === end.line) {
- end.column += 1;
+ const start = indexToPosition(text, rangeStart, { oneBased: true });
+ const end = indexToPosition(text, rangeEnd, { oneBased: true });
+ if (start.line !== end.line) {
+ end.column -= 1;
return {
diff --git a/yarn.lock b/yarn.lock
index a8149c659b19..79ffd6061cd7 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4798,10 +4798,10 @@ __metadata:
-"index-to-position@npm:^1.0.0":
- version: 1.0.0
- resolution: "index-to-position@npm:1.0.0"
- checksum: 10/4a24b8f0728da8ec6ffea85556acf809a71317d5291d31148db7c2dececa10432abf3c87a932481a2e326af66221bcf77d8dc1f0abfd11537e7f3cc21432a525
+"index-to-position@npm:1.1.0, index-to-position@npm:^1.0.0":
+ version: 1.1.0
+ resolution: "index-to-position@npm:1.1.0"
+ checksum: 10/16703893c732a025786098fe77cb7e83109afe4b72633dd6feea1595c54f8406623fa7a0a2263a8e08adee7f639fbb1c4731982cd30b4bc30d787bf803f5f3d8
@@ -5959,13 +5959,6 @@ __metadata:
-"lines-and-columns@npm:2.0.4":
- version: 2.0.4
- resolution: "lines-and-columns@npm:2.0.4"
- checksum: 10/81ac2f943f5428a46bd4ea2561c74ba674a107d8e6cc70cd317d16892a36ff3ba0dc6e599aca8b6f8668d26c85288394c6edf7a40e985ca843acab3701b80d4c
- languageName: node
- linkType: hard
-
"lines-and-columns@npm:^1.1.6":
version: 1.2.4
resolution: "lines-and-columns@npm:1.2.4"
@@ -6911,6 +6904,7 @@ __metadata:
html-ua-styles: "npm:0.0.8"
ignore: "npm:7.0.3"
import-meta-resolve: "npm:4.1.0"
+ index-to-position: "npm:1.1.0"
is-es5-identifier-name: "npm:1.0.0"
iterate-directory-up: "npm:1.1.1"
jest: "npm:30.0.0-alpha.7"
@@ -6923,7 +6917,6 @@ __metadata:
json5: "npm:2.2.3"
knip: "npm:5.47.0"
leven: "npm:4.0.0"
- lines-and-columns: "npm:2.0.4"
linguist-languages: "npm:7.29.0"
magic-string: "npm:0.30.17"
meriyah: "npm:6.0.6" | [
"+ (index) => indexToPosition(content, index, { oneBased: true }).line,",
"- const lines = new LinesAndColumns(text);"
] | [
39,
58
] | {
"additions": 13,
"author": "fisker",
"deletions": 25,
"html_url": "https://github.com/prettier/prettier/pull/17325",
"issue_id": 17325,
"merged_at": "2025-04-09T00:12:22Z",
"omission_probability": 0.1,
"pr_number": 17325,
"repo": "prettier/prettier",
"title": "Replace `lines-and-columns` with `index-to-position`",
"total_changes": 38
} |
191 | diff --git a/package.json b/package.json
index b17fa88acaca..1ccd5af71126 100644
--- a/package.json
+++ b/package.json
@@ -56,7 +56,7 @@
"fast-glob": "3.3.3",
"fast-json-stable-stringify": "2.1.0",
"file-entry-cache": "10.0.8",
- "find-cache-dir": "5.0.0",
+ "find-cache-directory": "6.0.0",
"flow-parser": "0.266.1",
"get-east-asian-width": "1.3.0",
"get-stdin": "9.0.0",
diff --git a/src/cli/find-cache-file.js b/src/cli/find-cache-file.js
index db1e09af72bf..7e58613d9e09 100644
--- a/src/cli/find-cache-file.js
+++ b/src/cli/find-cache-file.js
@@ -1,15 +1,15 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import findCacheDir from "find-cache-dir";
+import findCacheDirectory from "find-cache-directory";
import { isJson, statSafe } from "./utils.js";
/**
- * Find default cache file (`./node_modules/.cache/prettier/.prettier-cache`) using https://github.com/avajs/find-cache-dir
+ * Find default cache file (`./node_modules/.cache/prettier/.prettier-cache`) using https://github.com/sindresorhus/find-cache-directory
*/
function findDefaultCacheFile() {
const cacheDir =
- findCacheDir({ name: "prettier", create: true }) || os.tmpdir();
+ findCacheDirectory({ name: "prettier", create: true }) || os.tmpdir();
const cacheFilePath = path.join(cacheDir, ".prettier-cache");
return cacheFilePath;
}
diff --git a/yarn.lock b/yarn.lock
index 1ef3e8c7df65..a8149c659b19 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4271,13 +4271,13 @@ __metadata:
languageName: node
linkType: hard
-"find-cache-dir@npm:5.0.0":
- version: 5.0.0
- resolution: "find-cache-dir@npm:5.0.0"
+"find-cache-directory@npm:6.0.0":
+ version: 6.0.0
+ resolution: "find-cache-directory@npm:6.0.0"
dependencies:
common-path-prefix: "npm:^3.0.0"
- pkg-dir: "npm:^7.0.0"
- checksum: 10/1be046a2d6d98698d181352139bdd2f3e45cad4a0b3c9f06a611124ca52d823b0b327f5a629d7c5268b7fad54a202104765e572f8415b89ac35f76818fb3b75e
+ pkg-dir: "npm:^8.0.0"
+ checksum: 10/d0864b74ac556e21b1b4dc09d37f0b85ba8620f8cecc08727e8b2348e94828595d7368095deb79e804234629db56900c0f953beecf3cf2373e615fb809cc2033
languageName: node
linkType: hard
@@ -4308,16 +4308,6 @@ __metadata:
languageName: node
linkType: hard
-"find-up@npm:^6.3.0":
- version: 6.3.0
- resolution: "find-up@npm:6.3.0"
- dependencies:
- locate-path: "npm:^7.1.0"
- path-exists: "npm:^5.0.0"
- checksum: 10/4f3bdc30d41778c647e53f4923e72de5e5fb055157031f34501c5b36c2eb59f77b997edf9cb00165c6060cda7eaa2e3da82cb6be2e61d68ad3e07c4bc4cce67e
- languageName: node
- linkType: hard
-
"flat-cache@npm:^4.0.0":
version: 4.0.1
resolution: "flat-cache@npm:4.0.1"
@@ -6018,15 +6008,6 @@ __metadata:
languageName: node
linkType: hard
-"locate-path@npm:^7.1.0":
- version: 7.2.0
- resolution: "locate-path@npm:7.2.0"
- dependencies:
- p-locate: "npm:^6.0.0"
- checksum: 10/1c6d269d4efec555937081be964e8a9b4a136319c79ca1d45ac6382212a8466113c75bd89e44521ca8ecd1c47fb08523b56eee5c0712bc7d14fec5f729deeb42
- languageName: node
- linkType: hard
-
"lodash.memoize@npm:^4.1.2":
version: 4.1.2
resolution: "lodash.memoize@npm:4.1.2"
@@ -6552,15 +6533,6 @@ __metadata:
languageName: node
linkType: hard
-"p-limit@npm:^4.0.0":
- version: 4.0.0
- resolution: "p-limit@npm:4.0.0"
- dependencies:
- yocto-queue: "npm:^1.0.0"
- checksum: 10/01d9d70695187788f984226e16c903475ec6a947ee7b21948d6f597bed788e3112cc7ec2e171c1d37125057a5f45f3da21d8653e04a3a793589e12e9e80e756b
- languageName: node
- linkType: hard
-
"p-locate@npm:^4.1.0":
version: 4.1.0
resolution: "p-locate@npm:4.1.0"
@@ -6579,15 +6551,6 @@ __metadata:
languageName: node
linkType: hard
-"p-locate@npm:^6.0.0":
- version: 6.0.0
- resolution: "p-locate@npm:6.0.0"
- dependencies:
- p-limit: "npm:^4.0.0"
- checksum: 10/2bfe5234efa5e7a4e74b30a5479a193fdd9236f8f6b4d2f3f69e3d286d9a7d7ab0c118a2a50142efcf4e41625def635bd9332d6cbf9cc65d85eb0718c579ab38
- languageName: node
- linkType: hard
-
"p-map@npm:^4.0.0":
version: 4.0.0
resolution: "p-map@npm:4.0.0"
@@ -6687,13 +6650,6 @@ __metadata:
languageName: node
linkType: hard
-"path-exists@npm:^5.0.0":
- version: 5.0.0
- resolution: "path-exists@npm:5.0.0"
- checksum: 10/8ca842868cab09423994596eb2c5ec2a971c17d1a3cb36dbf060592c730c725cd524b9067d7d2a1e031fef9ba7bd2ac6dc5ec9fb92aa693265f7be3987045254
- languageName: node
- linkType: hard
-
"path-is-absolute@npm:^1.0.0":
version: 1.0.1
resolution: "path-is-absolute@npm:1.0.1"
@@ -6778,12 +6734,12 @@ __metadata:
languageName: node
linkType: hard
-"pkg-dir@npm:^7.0.0":
- version: 7.0.0
- resolution: "pkg-dir@npm:7.0.0"
+"pkg-dir@npm:^8.0.0":
+ version: 8.0.0
+ resolution: "pkg-dir@npm:8.0.0"
dependencies:
- find-up: "npm:^6.3.0"
- checksum: 10/94298b20a446bfbbd66604474de8a0cdd3b8d251225170970f15d9646f633e056c80520dd5b4c1d1050c9fed8f6a9e5054b141c93806439452efe72e57562c03
+ find-up-simple: "npm:^1.0.0"
+ checksum: 10/e589abebd1b76cbc3669a45df64f63cc1b041fd3a6588b45d4c692207df126f2a67478a804e5beeb729e75efea06cd405fb84445c879e7af346ba46a4a30b1ff
languageName: node
linkType: hard
@@ -6943,7 +6899,7 @@ __metadata:
fast-glob: "npm:3.3.3"
fast-json-stable-stringify: "npm:2.1.0"
file-entry-cache: "npm:10.0.8"
- find-cache-dir: "npm:5.0.0"
+ find-cache-directory: "npm:6.0.0"
flow-parser: "npm:0.266.1"
get-east-asian-width: "npm:1.3.0"
get-stdin: "npm:9.0.0"
@@ -8555,13 +8511,6 @@ __metadata:
languageName: node
linkType: hard
-"yocto-queue@npm:^1.0.0":
- version: 1.1.1
- resolution: "yocto-queue@npm:1.1.1"
- checksum: 10/f2e05b767ed3141e6372a80af9caa4715d60969227f38b1a4370d60bffe153c9c5b33a862905609afc9b375ec57cd40999810d20e5e10229a204e8bde7ef255c
- languageName: node
- linkType: hard
-
"zod-validation-error@npm:^3.0.3":
version: 3.4.0
resolution: "zod-validation-error@npm:3.4.0"
| diff --git a/package.json b/package.json
index b17fa88acaca..1ccd5af71126 100644
--- a/package.json
+++ b/package.json
@@ -56,7 +56,7 @@
"fast-glob": "3.3.3",
"fast-json-stable-stringify": "2.1.0",
"file-entry-cache": "10.0.8",
- "find-cache-dir": "5.0.0",
+ "find-cache-directory": "6.0.0",
"flow-parser": "0.266.1",
"get-east-asian-width": "1.3.0",
"get-stdin": "9.0.0",
diff --git a/src/cli/find-cache-file.js b/src/cli/find-cache-file.js
index db1e09af72bf..7e58613d9e09 100644
--- a/src/cli/find-cache-file.js
+++ b/src/cli/find-cache-file.js
@@ -1,15 +1,15 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import findCacheDir from "find-cache-dir";
+import findCacheDirectory from "find-cache-directory";
import { isJson, statSafe } from "./utils.js";
/**
- * Find default cache file (`./node_modules/.cache/prettier/.prettier-cache`) using https://github.com/avajs/find-cache-dir
+ * Find default cache file (`./node_modules/.cache/prettier/.prettier-cache`) using https://github.com/sindresorhus/find-cache-directory
*/
function findDefaultCacheFile() {
const cacheDir =
+ findCacheDirectory({ name: "prettier", create: true }) || os.tmpdir();
const cacheFilePath = path.join(cacheDir, ".prettier-cache");
return cacheFilePath;
}
diff --git a/yarn.lock b/yarn.lock
index 1ef3e8c7df65..a8149c659b19 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4271,13 +4271,13 @@ __metadata:
-"find-cache-dir@npm:5.0.0":
- resolution: "find-cache-dir@npm:5.0.0"
+"find-cache-directory@npm:6.0.0":
+ version: 6.0.0
+ resolution: "find-cache-directory@npm:6.0.0"
common-path-prefix: "npm:^3.0.0"
- pkg-dir: "npm:^7.0.0"
- checksum: 10/1be046a2d6d98698d181352139bdd2f3e45cad4a0b3c9f06a611124ca52d823b0b327f5a629d7c5268b7fad54a202104765e572f8415b89ac35f76818fb3b75e
+ pkg-dir: "npm:^8.0.0"
+ checksum: 10/d0864b74ac556e21b1b4dc09d37f0b85ba8620f8cecc08727e8b2348e94828595d7368095deb79e804234629db56900c0f953beecf3cf2373e615fb809cc2033
@@ -4308,16 +4308,6 @@ __metadata:
-"find-up@npm:^6.3.0":
- version: 6.3.0
- resolution: "find-up@npm:6.3.0"
- path-exists: "npm:^5.0.0"
- checksum: 10/4f3bdc30d41778c647e53f4923e72de5e5fb055157031f34501c5b36c2eb59f77b997edf9cb00165c6060cda7eaa2e3da82cb6be2e61d68ad3e07c4bc4cce67e
"flat-cache@npm:^4.0.0":
version: 4.0.1
resolution: "flat-cache@npm:4.0.1"
@@ -6018,15 +6008,6 @@ __metadata:
-"locate-path@npm:^7.1.0":
- version: 7.2.0
- resolution: "locate-path@npm:7.2.0"
- p-locate: "npm:^6.0.0"
- checksum: 10/1c6d269d4efec555937081be964e8a9b4a136319c79ca1d45ac6382212a8466113c75bd89e44521ca8ecd1c47fb08523b56eee5c0712bc7d14fec5f729deeb42
"lodash.memoize@npm:^4.1.2":
version: 4.1.2
resolution: "lodash.memoize@npm:4.1.2"
@@ -6552,15 +6533,6 @@ __metadata:
-"p-limit@npm:^4.0.0":
- version: 4.0.0
- resolution: "p-limit@npm:4.0.0"
- yocto-queue: "npm:^1.0.0"
- checksum: 10/01d9d70695187788f984226e16c903475ec6a947ee7b21948d6f597bed788e3112cc7ec2e171c1d37125057a5f45f3da21d8653e04a3a793589e12e9e80e756b
"p-locate@npm:^4.1.0":
version: 4.1.0
resolution: "p-locate@npm:4.1.0"
@@ -6579,15 +6551,6 @@ __metadata:
-"p-locate@npm:^6.0.0":
- version: 6.0.0
- resolution: "p-locate@npm:6.0.0"
- p-limit: "npm:^4.0.0"
- checksum: 10/2bfe5234efa5e7a4e74b30a5479a193fdd9236f8f6b4d2f3f69e3d286d9a7d7ab0c118a2a50142efcf4e41625def635bd9332d6cbf9cc65d85eb0718c579ab38
"p-map@npm:^4.0.0":
version: 4.0.0
resolution: "p-map@npm:4.0.0"
@@ -6687,13 +6650,6 @@ __metadata:
- checksum: 10/8ca842868cab09423994596eb2c5ec2a971c17d1a3cb36dbf060592c730c725cd524b9067d7d2a1e031fef9ba7bd2ac6dc5ec9fb92aa693265f7be3987045254
"path-is-absolute@npm:^1.0.0":
version: 1.0.1
resolution: "path-is-absolute@npm:1.0.1"
@@ -6778,12 +6734,12 @@ __metadata:
-"pkg-dir@npm:^7.0.0":
- version: 7.0.0
- resolution: "pkg-dir@npm:7.0.0"
+"pkg-dir@npm:^8.0.0":
+ version: 8.0.0
+ resolution: "pkg-dir@npm:8.0.0"
- find-up: "npm:^6.3.0"
- checksum: 10/94298b20a446bfbbd66604474de8a0cdd3b8d251225170970f15d9646f633e056c80520dd5b4c1d1050c9fed8f6a9e5054b141c93806439452efe72e57562c03
+ find-up-simple: "npm:^1.0.0"
+ checksum: 10/e589abebd1b76cbc3669a45df64f63cc1b041fd3a6588b45d4c692207df126f2a67478a804e5beeb729e75efea06cd405fb84445c879e7af346ba46a4a30b1ff
@@ -6943,7 +6899,7 @@ __metadata:
fast-glob: "npm:3.3.3"
fast-json-stable-stringify: "npm:2.1.0"
file-entry-cache: "npm:10.0.8"
- find-cache-dir: "npm:5.0.0"
+ find-cache-directory: "npm:6.0.0"
flow-parser: "npm:0.266.1"
get-east-asian-width: "npm:1.3.0"
get-stdin: "npm:9.0.0"
@@ -8555,13 +8511,6 @@ __metadata:
-"yocto-queue@npm:^1.0.0":
- version: 1.1.1
- resolution: "yocto-queue@npm:1.1.1"
- checksum: 10/f2e05b767ed3141e6372a80af9caa4715d60969227f38b1a4370d60bffe153c9c5b33a862905609afc9b375ec57cd40999810d20e5e10229a204e8bde7ef255c
"zod-validation-error@npm:^3.0.3":
version: 3.4.0
resolution: "zod-validation-error@npm:3.4.0" | [
"- findCacheDir({ name: \"prettier\", create: true }) || os.tmpdir();",
"- locate-path: \"npm:^7.1.0\"",
"-\"path-exists@npm:^5.0.0\":",
"- resolution: \"path-exists@npm:5.0.0\""
] | [
31,
67,
128,
130
] | {
"additions": 15,
"author": "fisker",
"deletions": 66,
"html_url": "https://github.com/prettier/prettier/pull/17327",
"issue_id": 17327,
"merged_at": "2025-04-08T23:41:12Z",
"omission_probability": 0.1,
"pr_number": 17327,
"repo": "prettier/prettier",
"title": "Update `find-cache-directory` to v6",
"total_changes": 81
} |
192 | diff --git a/scripts/build/parse-arguments.js b/scripts/build/parse-arguments.js
index a515049450ee..5c84e16acf8b 100644
--- a/scripts/build/parse-arguments.js
+++ b/scripts/build/parse-arguments.js
@@ -15,7 +15,6 @@ function parseArguments() {
"save-as": { type: "string" },
report: { type: "string", multiple: true },
},
- strict: true,
});
if (values.minify && values["no-minify"]) {
diff --git a/scripts/changelog-for-patch.js b/scripts/changelog-for-patch.js
index eaa472593f52..bccd256660be 100644
--- a/scripts/changelog-for-patch.js
+++ b/scripts/changelog-for-patch.js
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import path from "node:path";
-import minimist from "minimist";
+import { parseArgs } from "node:util";
import semver from "semver";
import {
categories,
@@ -12,7 +12,7 @@ import {
replaceVersions,
} from "./utils/changelog.js";
-const { previousVersion, newVersion } = parseArgv();
+const { previousVersion, newVersion } = parseArguments();
const entries = changelogUnreleasedDirs.flatMap((dir) => {
const dirPath = path.join(changelogUnreleasedDirPath, dir.name);
@@ -34,10 +34,15 @@ console.log(
),
);
-function parseArgv() {
- const argv = minimist(process.argv.slice(2));
- const previousVersion = argv["prev-version"];
- const newVersion = argv["new-version"];
+function parseArguments() {
+ const {
+ values: { "prev-version": previousVersion, "new-version": newVersion },
+ } = parseArgs({
+ options: {
+ "prev-version": { type: "string" },
+ "new-version": { type: "string" },
+ },
+ });
if (
!previousVersion ||
!newVersion ||
| diff --git a/scripts/build/parse-arguments.js b/scripts/build/parse-arguments.js
index a515049450ee..5c84e16acf8b 100644
--- a/scripts/build/parse-arguments.js
+++ b/scripts/build/parse-arguments.js
@@ -15,7 +15,6 @@ function parseArguments() {
"save-as": { type: "string" },
report: { type: "string", multiple: true },
},
- strict: true,
});
if (values.minify && values["no-minify"]) {
diff --git a/scripts/changelog-for-patch.js b/scripts/changelog-for-patch.js
index eaa472593f52..bccd256660be 100644
--- a/scripts/changelog-for-patch.js
+++ b/scripts/changelog-for-patch.js
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import path from "node:path";
-import minimist from "minimist";
+import { parseArgs } from "node:util";
import semver from "semver";
import {
categories,
@@ -12,7 +12,7 @@ import {
replaceVersions,
} from "./utils/changelog.js";
-const { previousVersion, newVersion } = parseArgv();
+const { previousVersion, newVersion } = parseArguments();
const entries = changelogUnreleasedDirs.flatMap((dir) => {
const dirPath = path.join(changelogUnreleasedDirPath, dir.name);
@@ -34,10 +34,15 @@ console.log(
),
);
-function parseArgv() {
- const argv = minimist(process.argv.slice(2));
- const previousVersion = argv["prev-version"];
- const newVersion = argv["new-version"];
+function parseArguments() {
+ const {
+ values: { "prev-version": previousVersion, "new-version": newVersion },
+ } = parseArgs({
+ options: {
+ "prev-version": { type: "string" },
+ "new-version": { type: "string" },
+ },
+ });
if (
!previousVersion ||
!newVersion || | [] | [] | {
"additions": 11,
"author": "fisker",
"deletions": 7,
"html_url": "https://github.com/prettier/prettier/pull/17324",
"issue_id": 17324,
"merged_at": "2025-04-08T02:11:38Z",
"omission_probability": 0.1,
"pr_number": 17324,
"repo": "prettier/prettier",
"title": "Use `util.parseArgs` in `changelog-for-patch.js` script",
"total_changes": 18
} |
193 | diff --git a/scripts/build/esbuild-plugins/add-default-export.js b/scripts/build/esbuild-plugins/add-default-export.js
index 2b6d80bfd6e2..a2e091875cf3 100644
--- a/scripts/build/esbuild-plugins/add-default-export.js
+++ b/scripts/build/esbuild-plugins/add-default-export.js
@@ -10,31 +10,32 @@ export default function esbuildPluginAddDefaultExport() {
return;
}
- let entry;
-
build.onResolve({ filter: /./, namespace: "file" }, (module) => {
if (module.kind === "entry-point") {
- const relativePath = module.path
- .slice(module.resolveDir.length + 1)
+ const file = module.path;
+ const relativePath = path
+ .relative(module.resolveDir, file)
.replaceAll("\\", "/");
-
- entry = module.path;
- return { path: relativePath, namespace: PLUGIN_NAMESPACE };
+ return {
+ path: relativePath,
+ namespace: PLUGIN_NAMESPACE,
+ pluginData: { file },
+ };
}
});
- build.onLoad({ filter: /./, namespace: PLUGIN_NAMESPACE }, () => {
- const directory = path.dirname(entry);
- const source = `./${path.basename(entry)}`;
+ build.onLoad({ filter: /./, namespace: PLUGIN_NAMESPACE }, (module) => {
+ const { file } = module.pluginData;
+ const source = JSON.stringify(`./${path.basename(file)}`);
return {
contents: /* indent */ `
- import * as namespace from "${source}";
+ import * as namespace from ${source};
- export * from "${source}";
+ export * from ${source};
export default namespace;
`,
- resolveDir: directory,
+ resolveDir: path.dirname(file),
};
});
},
| diff --git a/scripts/build/esbuild-plugins/add-default-export.js b/scripts/build/esbuild-plugins/add-default-export.js
index 2b6d80bfd6e2..a2e091875cf3 100644
--- a/scripts/build/esbuild-plugins/add-default-export.js
+++ b/scripts/build/esbuild-plugins/add-default-export.js
@@ -10,31 +10,32 @@ export default function esbuildPluginAddDefaultExport() {
return;
}
- let entry;
build.onResolve({ filter: /./, namespace: "file" }, (module) => {
if (module.kind === "entry-point") {
- const relativePath = module.path
- .slice(module.resolveDir.length + 1)
+ const file = module.path;
+ const relativePath = path
+ .relative(module.resolveDir, file)
.replaceAll("\\", "/");
- entry = module.path;
- return { path: relativePath, namespace: PLUGIN_NAMESPACE };
+ return {
+ path: relativePath,
+ namespace: PLUGIN_NAMESPACE,
+ pluginData: { file },
+ };
}
- const directory = path.dirname(entry);
- const source = `./${path.basename(entry)}`;
+ build.onLoad({ filter: /./, namespace: PLUGIN_NAMESPACE }, (module) => {
+ const { file } = module.pluginData;
+ const source = JSON.stringify(`./${path.basename(file)}`);
return {
contents: /* indent */ `
- import * as namespace from "${source}";
+ import * as namespace from ${source};
- export * from "${source}";
+ export * from ${source};
export default namespace;
`,
- resolveDir: directory,
+ resolveDir: path.dirname(file),
};
}, | [
"- build.onLoad({ filter: /./, namespace: PLUGIN_NAMESPACE }, () => {"
] | [
29
] | {
"additions": 14,
"author": "fisker",
"deletions": 13,
"html_url": "https://github.com/prettier/prettier/pull/17322",
"issue_id": 17322,
"merged_at": "2025-04-08T01:10:10Z",
"omission_probability": 0.1,
"pr_number": 17322,
"repo": "prettier/prettier",
"title": "Minor tweak to ESBuild `addDefaultExport` plugin",
"total_changes": 27
} |
194 | diff --git a/package.json b/package.json
index caf8fbc2aeff..39aab4bf94e7 100644
--- a/package.json
+++ b/package.json
@@ -129,7 +129,7 @@
"eslint-plugin-n": "17.17.0",
"eslint-plugin-regexp": "2.7.0",
"eslint-plugin-simple-import-sort": "12.1.1",
- "eslint-plugin-unicorn": "57.0.0",
+ "eslint-plugin-unicorn": "58.0.0",
"esm-utils": "4.3.0",
"globals": "16.0.0",
"jest": "30.0.0-alpha.7",
diff --git a/yarn.lock b/yarn.lock
index 1c1541041800..7e7dec431019 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1152,7 +1152,7 @@ __metadata:
languageName: node
linkType: hard
-"@eslint-community/eslint-utils@npm:^4.1.2, @eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.4.0, @eslint-community/eslint-utils@npm:^4.4.1, @eslint-community/eslint-utils@npm:^4.5.0":
+"@eslint-community/eslint-utils@npm:^4.1.2, @eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.4.0, @eslint-community/eslint-utils@npm:^4.5.0, @eslint-community/eslint-utils@npm:^4.5.1":
version: 4.5.1
resolution: "@eslint-community/eslint-utils@npm:4.5.1"
dependencies:
@@ -2640,7 +2640,7 @@ __metadata:
languageName: node
linkType: hard
-"browserslist@npm:4.24.4, browserslist@npm:^4.24.0, browserslist@npm:^4.24.2, browserslist@npm:^4.24.3":
+"browserslist@npm:4.24.4, browserslist@npm:^4.24.0, browserslist@npm:^4.24.2, browserslist@npm:^4.24.4":
version: 4.24.4
resolution: "browserslist@npm:4.24.4"
dependencies:
@@ -2680,10 +2680,10 @@ __metadata:
languageName: node
linkType: hard
-"builtin-modules@npm:^4.0.0":
- version: 4.0.0
- resolution: "builtin-modules@npm:4.0.0"
- checksum: 10/cea28dd8fa3060d39bee0f3e9f141987ac99d2dd7913c2fa15eb34a98372399f3be3b1bf1f849790ecad602d52e57d45a9c54bcde28c0bbf25bfe947ca8ffe55
+"builtin-modules@npm:^5.0.0":
+ version: 5.0.0
+ resolution: "builtin-modules@npm:5.0.0"
+ checksum: 10/85ba92a4cbd794174dae48c867d27f5529a03c9c073ccb029f106e62861eb48e09231f17a7290645e16a0a22d7401ca269ff73b760a6ddb9a3b7d1b9ceba81ac
languageName: node
linkType: hard
@@ -2864,7 +2864,7 @@ __metadata:
languageName: node
linkType: hard
-"ci-info@npm:4.2.0, ci-info@npm:^4.0.0, ci-info@npm:^4.1.0":
+"ci-info@npm:4.2.0, ci-info@npm:^4.0.0, ci-info@npm:^4.2.0":
version: 4.2.0
resolution: "ci-info@npm:4.2.0"
checksum: 10/928d8457f3476ffc4a66dec93b9cdf1944d5e60dba69fbd6a0fc95b652386f6ef64857f6e32372533210ef6d8954634af2c7693d7c07778ee015f3629a5e0dd9
@@ -3075,12 +3075,12 @@ __metadata:
languageName: node
linkType: hard
-"core-js-compat@npm:^3.40.0":
- version: 3.40.0
- resolution: "core-js-compat@npm:3.40.0"
+"core-js-compat@npm:^3.41.0":
+ version: 3.41.0
+ resolution: "core-js-compat@npm:3.41.0"
dependencies:
- browserslist: "npm:^4.24.3"
- checksum: 10/3dd3d717b3d4ae0d9c2930d39c0f2a21ca6f195fcdd5711bda833557996c4d9f90277eab576423478e95689257e2de8d1a2623d6618084416bd224d10d5df9a4
+ browserslist: "npm:^4.24.4"
+ checksum: 10/a59da111fc437cc7ed1a1448dae6883617cabebd7731433d27ad75e0ff77df5f411204979bd8eb5668d2600f99db46eedf6f87e123109b6de728bef489d4229a
languageName: node
linkType: hard
@@ -3941,19 +3941,20 @@ __metadata:
languageName: node
linkType: hard
-"eslint-plugin-unicorn@npm:57.0.0":
- version: 57.0.0
- resolution: "eslint-plugin-unicorn@npm:57.0.0"
+"eslint-plugin-unicorn@npm:58.0.0":
+ version: 58.0.0
+ resolution: "eslint-plugin-unicorn@npm:58.0.0"
dependencies:
"@babel/helper-validator-identifier": "npm:^7.25.9"
- "@eslint-community/eslint-utils": "npm:^4.4.1"
- ci-info: "npm:^4.1.0"
+ "@eslint-community/eslint-utils": "npm:^4.5.1"
+ "@eslint/plugin-kit": "npm:^0.2.7"
+ ci-info: "npm:^4.2.0"
clean-regexp: "npm:^1.0.0"
- core-js-compat: "npm:^3.40.0"
+ core-js-compat: "npm:^3.41.0"
esquery: "npm:^1.6.0"
- globals: "npm:^15.15.0"
+ globals: "npm:^16.0.0"
indent-string: "npm:^5.0.0"
- is-builtin-module: "npm:^4.0.0"
+ is-builtin-module: "npm:^5.0.0"
jsesc: "npm:^3.1.0"
pluralize: "npm:^8.0.0"
read-package-up: "npm:^11.0.0"
@@ -3962,8 +3963,8 @@ __metadata:
semver: "npm:^7.7.1"
strip-indent: "npm:^4.0.0"
peerDependencies:
- eslint: ">=9.20.0"
- checksum: 10/056dcca3ce4f89314bff2d4dcbe4124398e3cb99f315416ea6944c69e5673551f20812d440d5614a11fca0da825d06fb98a870de9a74de2a4f404dcde88d4553
+ eslint: ">=9.22.0"
+ checksum: 10/1e1cea0466be8fe0d41181fc4ca12f1cabb26f97a0f718ecac68f686da29381f69070f4e1f24020b0378a705ef6346294974575ace586c0750aab174d193b2f6
languageName: node
linkType: hard
@@ -4551,7 +4552,7 @@ __metadata:
languageName: node
linkType: hard
-"globals@npm:16.0.0":
+"globals@npm:16.0.0, globals@npm:^16.0.0":
version: 16.0.0
resolution: "globals@npm:16.0.0"
checksum: 10/aa05d569af9c763d9982e6885f3ac6d21c84cd54c9a12eeace55b3334d0631128f189902d34ae2a924694311f92d700dbd3e8e62e8a9e1094a882f9f8897149a
@@ -4572,7 +4573,7 @@ __metadata:
languageName: node
linkType: hard
-"globals@npm:^15.11.0, globals@npm:^15.15.0, globals@npm:^15.7.0":
+"globals@npm:^15.11.0, globals@npm:^15.7.0":
version: 15.15.0
resolution: "globals@npm:15.15.0"
checksum: 10/7f561c87b2fd381b27fc2db7df8a4ea7a9bb378667b8a7193e61fd2ca3a876479174e2a303a74345fbea6e1242e16db48915c1fd3bf35adcf4060a795b425e18
@@ -4892,12 +4893,12 @@ __metadata:
languageName: node
linkType: hard
-"is-builtin-module@npm:^4.0.0":
- version: 4.0.0
- resolution: "is-builtin-module@npm:4.0.0"
+"is-builtin-module@npm:^5.0.0":
+ version: 5.0.0
+ resolution: "is-builtin-module@npm:5.0.0"
dependencies:
- builtin-modules: "npm:^4.0.0"
- checksum: 10/61e31a8730cc0babfc29af52250178220f4a2cefd23c54f614e5256f0e4e37643f0eb709a92ccfd6ad84732e48e8c4d10cd9d3e29a47197598d5ad2c9c19a765
+ builtin-modules: "npm:^5.0.0"
+ checksum: 10/fcb1e458fa08e6d7e8763abaa84bc539ca943b298e15448ba92b79ab8f08c382664b8b1d5e32c59358e87026fed7b1e56e457b955436d7cc860cf0653002e4c6
languageName: node
linkType: hard
@@ -6942,7 +6943,7 @@ __metadata:
eslint-plugin-n: "npm:17.17.0"
eslint-plugin-regexp: "npm:2.7.0"
eslint-plugin-simple-import-sort: "npm:12.1.1"
- eslint-plugin-unicorn: "npm:57.0.0"
+ eslint-plugin-unicorn: "npm:58.0.0"
esm-utils: "npm:4.3.0"
espree: "npm:10.3.0"
fast-glob: "npm:3.3.3"
| diff --git a/package.json b/package.json
index caf8fbc2aeff..39aab4bf94e7 100644
--- a/package.json
+++ b/package.json
@@ -129,7 +129,7 @@
"eslint-plugin-n": "17.17.0",
"eslint-plugin-regexp": "2.7.0",
"eslint-plugin-simple-import-sort": "12.1.1",
- "eslint-plugin-unicorn": "57.0.0",
"esm-utils": "4.3.0",
"globals": "16.0.0",
"jest": "30.0.0-alpha.7",
diff --git a/yarn.lock b/yarn.lock
index 1c1541041800..7e7dec431019 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1152,7 +1152,7 @@ __metadata:
+"@eslint-community/eslint-utils@npm:^4.1.2, @eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.4.0, @eslint-community/eslint-utils@npm:^4.5.0, @eslint-community/eslint-utils@npm:^4.5.1":
version: 4.5.1
resolution: "@eslint-community/eslint-utils@npm:4.5.1"
@@ -2640,7 +2640,7 @@ __metadata:
+"browserslist@npm:4.24.4, browserslist@npm:^4.24.0, browserslist@npm:^4.24.2, browserslist@npm:^4.24.4":
version: 4.24.4
resolution: "browserslist@npm:4.24.4"
@@ -2680,10 +2680,10 @@ __metadata:
-"builtin-modules@npm:^4.0.0":
- resolution: "builtin-modules@npm:4.0.0"
- checksum: 10/cea28dd8fa3060d39bee0f3e9f141987ac99d2dd7913c2fa15eb34a98372399f3be3b1bf1f849790ecad602d52e57d45a9c54bcde28c0bbf25bfe947ca8ffe55
+"builtin-modules@npm:^5.0.0":
+ resolution: "builtin-modules@npm:5.0.0"
+ checksum: 10/85ba92a4cbd794174dae48c867d27f5529a03c9c073ccb029f106e62861eb48e09231f17a7290645e16a0a22d7401ca269ff73b760a6ddb9a3b7d1b9ceba81ac
@@ -2864,7 +2864,7 @@ __metadata:
-"ci-info@npm:4.2.0, ci-info@npm:^4.0.0, ci-info@npm:^4.1.0":
+"ci-info@npm:4.2.0, ci-info@npm:^4.0.0, ci-info@npm:^4.2.0":
version: 4.2.0
resolution: "ci-info@npm:4.2.0"
checksum: 10/928d8457f3476ffc4a66dec93b9cdf1944d5e60dba69fbd6a0fc95b652386f6ef64857f6e32372533210ef6d8954634af2c7693d7c07778ee015f3629a5e0dd9
@@ -3075,12 +3075,12 @@ __metadata:
-"core-js-compat@npm:^3.40.0":
- version: 3.40.0
- resolution: "core-js-compat@npm:3.40.0"
+ version: 3.41.0
+ resolution: "core-js-compat@npm:3.41.0"
- browserslist: "npm:^4.24.3"
- checksum: 10/3dd3d717b3d4ae0d9c2930d39c0f2a21ca6f195fcdd5711bda833557996c4d9f90277eab576423478e95689257e2de8d1a2623d6618084416bd224d10d5df9a4
+ browserslist: "npm:^4.24.4"
+ checksum: 10/a59da111fc437cc7ed1a1448dae6883617cabebd7731433d27ad75e0ff77df5f411204979bd8eb5668d2600f99db46eedf6f87e123109b6de728bef489d4229a
@@ -3941,19 +3941,20 @@ __metadata:
-"eslint-plugin-unicorn@npm:57.0.0":
- version: 57.0.0
- resolution: "eslint-plugin-unicorn@npm:57.0.0"
+"eslint-plugin-unicorn@npm:58.0.0":
+ version: 58.0.0
"@babel/helper-validator-identifier": "npm:^7.25.9"
- "@eslint-community/eslint-utils": "npm:^4.4.1"
- ci-info: "npm:^4.1.0"
+ "@eslint-community/eslint-utils": "npm:^4.5.1"
+ "@eslint/plugin-kit": "npm:^0.2.7"
+ ci-info: "npm:^4.2.0"
clean-regexp: "npm:^1.0.0"
- core-js-compat: "npm:^3.40.0"
+ core-js-compat: "npm:^3.41.0"
esquery: "npm:^1.6.0"
- globals: "npm:^15.15.0"
+ globals: "npm:^16.0.0"
indent-string: "npm:^5.0.0"
- is-builtin-module: "npm:^4.0.0"
+ is-builtin-module: "npm:^5.0.0"
jsesc: "npm:^3.1.0"
pluralize: "npm:^8.0.0"
read-package-up: "npm:^11.0.0"
@@ -3962,8 +3963,8 @@ __metadata:
semver: "npm:^7.7.1"
strip-indent: "npm:^4.0.0"
peerDependencies:
- eslint: ">=9.20.0"
- checksum: 10/056dcca3ce4f89314bff2d4dcbe4124398e3cb99f315416ea6944c69e5673551f20812d440d5614a11fca0da825d06fb98a870de9a74de2a4f404dcde88d4553
+ eslint: ">=9.22.0"
+ checksum: 10/1e1cea0466be8fe0d41181fc4ca12f1cabb26f97a0f718ecac68f686da29381f69070f4e1f24020b0378a705ef6346294974575ace586c0750aab174d193b2f6
@@ -4551,7 +4552,7 @@ __metadata:
-"globals@npm:16.0.0":
+"globals@npm:16.0.0, globals@npm:^16.0.0":
version: 16.0.0
resolution: "globals@npm:16.0.0"
checksum: 10/aa05d569af9c763d9982e6885f3ac6d21c84cd54c9a12eeace55b3334d0631128f189902d34ae2a924694311f92d700dbd3e8e62e8a9e1094a882f9f8897149a
@@ -4572,7 +4573,7 @@ __metadata:
-"globals@npm:^15.11.0, globals@npm:^15.15.0, globals@npm:^15.7.0":
+"globals@npm:^15.11.0, globals@npm:^15.7.0":
version: 15.15.0
resolution: "globals@npm:15.15.0"
checksum: 10/7f561c87b2fd381b27fc2db7df8a4ea7a9bb378667b8a7193e61fd2ca3a876479174e2a303a74345fbea6e1242e16db48915c1fd3bf35adcf4060a795b425e18
@@ -4892,12 +4893,12 @@ __metadata:
- resolution: "is-builtin-module@npm:4.0.0"
+"is-builtin-module@npm:^5.0.0":
+ resolution: "is-builtin-module@npm:5.0.0"
- builtin-modules: "npm:^4.0.0"
- checksum: 10/61e31a8730cc0babfc29af52250178220f4a2cefd23c54f614e5256f0e4e37643f0eb709a92ccfd6ad84732e48e8c4d10cd9d3e29a47197598d5ad2c9c19a765
+ builtin-modules: "npm:^5.0.0"
+ checksum: 10/fcb1e458fa08e6d7e8763abaa84bc539ca943b298e15448ba92b79ab8f08c382664b8b1d5e32c59358e87026fed7b1e56e457b955436d7cc860cf0653002e4c6
@@ -6942,7 +6943,7 @@ __metadata:
eslint-plugin-n: "npm:17.17.0"
eslint-plugin-regexp: "npm:2.7.0"
eslint-plugin-simple-import-sort: "npm:12.1.1"
- eslint-plugin-unicorn: "npm:57.0.0"
+ eslint-plugin-unicorn: "npm:58.0.0"
esm-utils: "npm:4.3.0"
espree: "npm:10.3.0"
fast-glob: "npm:3.3.3" | [
"+ \"eslint-plugin-unicorn\": \"58.0.0\",",
"-\"@eslint-community/eslint-utils@npm:^4.1.2, @eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.4.0, @eslint-community/eslint-utils@npm:^4.4.1, @eslint-community/eslint-utils@npm:^4.5.0\":",
"-\"browserslist@npm:4.24.4, browserslist@npm:^4.24.0, browserslist@npm:^4.24.2, browserslist@npm:^4.24.3\":",
"+\"core-js-compat@npm:^3.41.0\":",
"+ resolution: \"eslint-plugin-unicorn@npm:58.0.0\"",
"-\"is-builtin-module@npm:^4.0.0\":"
] | [
9,
21,
30,
66,
86,
139
] | {
"additions": 32,
"author": "renovate[bot]",
"deletions": 31,
"html_url": "https://github.com/prettier/prettier/pull/17320",
"issue_id": 17320,
"merged_at": "2025-04-07T07:28:38Z",
"omission_probability": 0.1,
"pr_number": 17320,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency eslint-plugin-unicorn to v58",
"total_changes": 63
} |
195 | diff --git a/package.json b/package.json
index caf8fbc2aeff..1b985903ff93 100644
--- a/package.json
+++ b/package.json
@@ -137,7 +137,7 @@
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
- "knip": "5.44.4",
+ "knip": "5.47.0",
"lines-and-columns": "2.0.4",
"magic-string": "0.30.17",
"nano-spawn": "0.2.0",
diff --git a/yarn.lock b/yarn.lock
index 1c1541041800..39b1d53dfe07 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3438,13 +3438,13 @@ __metadata:
languageName: node
linkType: hard
-"enhanced-resolve@npm:^5.17.1, enhanced-resolve@npm:^5.18.0":
- version: 5.18.0
- resolution: "enhanced-resolve@npm:5.18.0"
+"enhanced-resolve@npm:^5.17.1, enhanced-resolve@npm:^5.18.1":
+ version: 5.18.1
+ resolution: "enhanced-resolve@npm:5.18.1"
dependencies:
graceful-fs: "npm:^4.2.4"
tapable: "npm:^2.2.0"
- checksum: 10/e88463ef97b68d40d0da0cd0c572e23f43dba0be622d6d44eae5cafed05f0c5dac43e463a83a86c4f70186d029357f82b56d9e1e47e8fc91dce3d6602f8bd6ce
+ checksum: 10/50e81c7fe2239fba5670ebce78a34709906ed3a79274aa416434f7307b252e0b7824d76a7dd403eca795571dc6afd9a44183fc45a68475e8f2fdfbae6e92fcc3
languageName: node
linkType: hard
@@ -5920,14 +5920,14 @@ __metadata:
languageName: node
linkType: hard
-"knip@npm:5.44.4":
- version: 5.44.4
- resolution: "knip@npm:5.44.4"
+"knip@npm:5.47.0":
+ version: 5.47.0
+ resolution: "knip@npm:5.47.0"
dependencies:
"@nodelib/fs.walk": "npm:3.0.1"
"@snyk/github-codeowners": "npm:1.1.0"
easy-table: "npm:1.2.0"
- enhanced-resolve: "npm:^5.18.0"
+ enhanced-resolve: "npm:^5.18.1"
fast-glob: "npm:^3.3.3"
jiti: "npm:^2.4.2"
js-yaml: "npm:^4.1.0"
@@ -5946,7 +5946,7 @@ __metadata:
bin:
knip: bin/knip.js
knip-bun: bin/knip-bun.js
- checksum: 10/85fbf7e4138681d9d8c66a61fb4117c1c578847113605c9bee1f473ab9098e144feb481d0fd6cb4a603d07d421aff0c93ba7ba2f74dfc221eaf1e183f3327adc
+ checksum: 10/3ce2f98c39cb81a7ac1a3ae78471b219bbebaa4f470153265fbc8fdd5b40f63e314113934cc72adfb5d7ae2e1549d1bb415e49569d0d8a0abe61f32ab078f848
languageName: node
linkType: hard
@@ -6970,7 +6970,7 @@ __metadata:
jest-watch-typeahead: "npm:2.2.2"
js-yaml: "npm:4.1.0"
json5: "npm:2.2.3"
- knip: "npm:5.44.4"
+ knip: "npm:5.47.0"
leven: "npm:4.0.0"
lines-and-columns: "npm:2.0.4"
linguist-languages: "npm:7.29.0"
| diff --git a/package.json b/package.json
index caf8fbc2aeff..1b985903ff93 100644
--- a/package.json
+++ b/package.json
@@ -137,7 +137,7 @@
"jest-snapshot-serializer-ansi": "2.2.1",
"jest-snapshot-serializer-raw": "2.0.0",
"jest-watch-typeahead": "2.2.2",
- "knip": "5.44.4",
+ "knip": "5.47.0",
"lines-and-columns": "2.0.4",
"magic-string": "0.30.17",
"nano-spawn": "0.2.0",
diff --git a/yarn.lock b/yarn.lock
index 1c1541041800..39b1d53dfe07 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3438,13 +3438,13 @@ __metadata:
-"enhanced-resolve@npm:^5.17.1, enhanced-resolve@npm:^5.18.0":
- version: 5.18.0
- resolution: "enhanced-resolve@npm:5.18.0"
+"enhanced-resolve@npm:^5.17.1, enhanced-resolve@npm:^5.18.1":
+ version: 5.18.1
+ resolution: "enhanced-resolve@npm:5.18.1"
graceful-fs: "npm:^4.2.4"
tapable: "npm:^2.2.0"
- checksum: 10/e88463ef97b68d40d0da0cd0c572e23f43dba0be622d6d44eae5cafed05f0c5dac43e463a83a86c4f70186d029357f82b56d9e1e47e8fc91dce3d6602f8bd6ce
+ checksum: 10/50e81c7fe2239fba5670ebce78a34709906ed3a79274aa416434f7307b252e0b7824d76a7dd403eca795571dc6afd9a44183fc45a68475e8f2fdfbae6e92fcc3
@@ -5920,14 +5920,14 @@ __metadata:
-"knip@npm:5.44.4":
- resolution: "knip@npm:5.44.4"
+"knip@npm:5.47.0":
+ version: 5.47.0
+ resolution: "knip@npm:5.47.0"
"@nodelib/fs.walk": "npm:3.0.1"
"@snyk/github-codeowners": "npm:1.1.0"
easy-table: "npm:1.2.0"
- enhanced-resolve: "npm:^5.18.0"
+ enhanced-resolve: "npm:^5.18.1"
fast-glob: "npm:^3.3.3"
jiti: "npm:^2.4.2"
js-yaml: "npm:^4.1.0"
@@ -5946,7 +5946,7 @@ __metadata:
bin:
knip: bin/knip.js
knip-bun: bin/knip-bun.js
@@ -6970,7 +6970,7 @@ __metadata:
jest-watch-typeahead: "npm:2.2.2"
js-yaml: "npm:4.1.0"
json5: "npm:2.2.3"
- knip: "npm:5.44.4"
+ knip: "npm:5.47.0"
leven: "npm:4.0.0"
lines-and-columns: "npm:2.0.4"
linguist-languages: "npm:7.29.0" | [
"- version: 5.44.4",
"- checksum: 10/85fbf7e4138681d9d8c66a61fb4117c1c578847113605c9bee1f473ab9098e144feb481d0fd6cb4a603d07d421aff0c93ba7ba2f74dfc221eaf1e183f3327adc",
"+ checksum: 10/3ce2f98c39cb81a7ac1a3ae78471b219bbebaa4f470153265fbc8fdd5b40f63e314113934cc72adfb5d7ae2e1549d1bb415e49569d0d8a0abe61f32ab078f848"
] | [
40,
58,
59
] | {
"additions": 11,
"author": "renovate[bot]",
"deletions": 11,
"html_url": "https://github.com/prettier/prettier/pull/17319",
"issue_id": 17319,
"merged_at": "2025-04-07T07:28:10Z",
"omission_probability": 0.1,
"pr_number": 17319,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency knip to v5.47.0",
"total_changes": 22
} |
196 | diff --git a/package.json b/package.json
index 64d80b045a24..02dd0a11140f 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"bin"
],
"dependencies": {
- "@angular/compiler": "19.2.2",
+ "@angular/compiler": "19.2.5",
"@babel/code-frame": "7.26.2",
"@babel/parser": "7.27.0",
"@babel/types": "7.27.0",
diff --git a/yarn.lock b/yarn.lock
index 1c1541041800..02355daa817b 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -15,17 +15,12 @@ __metadata:
languageName: node
linkType: hard
-"@angular/compiler@npm:19.2.2":
- version: 19.2.2
- resolution: "@angular/compiler@npm:19.2.2"
+"@angular/compiler@npm:19.2.5":
+ version: 19.2.5
+ resolution: "@angular/compiler@npm:19.2.5"
dependencies:
tslib: "npm:^2.3.0"
- peerDependencies:
- "@angular/core": 19.2.2
- peerDependenciesMeta:
- "@angular/core":
- optional: true
- checksum: 10/2c427e4e4696f8ce357e432a517d12a0730f9cbdb1306b5be49f9d4f7bd54b76442cfaba8f82579152bc814402e5f666bb5092c994f43c3022bb9a93e8d64db6
+ checksum: 10/3a36f13228a49fe7e4c8630df47a6220ef5164b62a5c3e7d883f811bcffce0319fcdcc1bdf20d358fb37ebf52be6a1b73cebaa0565b86e540eb0f21ac0979e5b
languageName: node
linkType: hard
@@ -6897,7 +6892,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "prettier@workspace:."
dependencies:
- "@angular/compiler": "npm:19.2.2"
+ "@angular/compiler": "npm:19.2.5"
"@babel/code-frame": "npm:7.26.2"
"@babel/generator": "npm:7.27.0"
"@babel/parser": "npm:7.27.0"
| diff --git a/package.json b/package.json
index 64d80b045a24..02dd0a11140f 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"bin"
],
"dependencies": {
- "@angular/compiler": "19.2.2",
+ "@angular/compiler": "19.2.5",
"@babel/code-frame": "7.26.2",
"@babel/parser": "7.27.0",
"@babel/types": "7.27.0",
diff --git a/yarn.lock b/yarn.lock
index 1c1541041800..02355daa817b 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -15,17 +15,12 @@ __metadata:
-"@angular/compiler@npm:19.2.2":
- version: 19.2.2
- resolution: "@angular/compiler@npm:19.2.2"
+"@angular/compiler@npm:19.2.5":
+ version: 19.2.5
+ resolution: "@angular/compiler@npm:19.2.5"
tslib: "npm:^2.3.0"
- peerDependencies:
- "@angular/core": 19.2.2
- peerDependenciesMeta:
- "@angular/core":
- optional: true
- checksum: 10/2c427e4e4696f8ce357e432a517d12a0730f9cbdb1306b5be49f9d4f7bd54b76442cfaba8f82579152bc814402e5f666bb5092c994f43c3022bb9a93e8d64db6
+ checksum: 10/3a36f13228a49fe7e4c8630df47a6220ef5164b62a5c3e7d883f811bcffce0319fcdcc1bdf20d358fb37ebf52be6a1b73cebaa0565b86e540eb0f21ac0979e5b
@@ -6897,7 +6892,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "prettier@workspace:."
- "@angular/compiler": "npm:19.2.2"
+ "@angular/compiler": "npm:19.2.5"
"@babel/code-frame": "npm:7.26.2"
"@babel/generator": "npm:7.27.0"
"@babel/parser": "npm:7.27.0" | [] | [] | {
"additions": 6,
"author": "renovate[bot]",
"deletions": 11,
"html_url": "https://github.com/prettier/prettier/pull/17315",
"issue_id": 17315,
"merged_at": "2025-04-07T07:27:27Z",
"omission_probability": 0.1,
"pr_number": 17315,
"repo": "prettier/prettier",
"title": "chore(deps): update dependency @angular/compiler to v19.2.5",
"total_changes": 17
} |
197 | diff --git a/package.json b/package.json
index 2436632dd694..b9bd36f98fd3 100644
--- a/package.json
+++ b/package.json
@@ -57,11 +57,11 @@
"fast-json-stable-stringify": "2.1.0",
"file-entry-cache": "10.0.8",
"find-cache-dir": "5.0.0",
- "flow-parser": "0.259.1",
+ "flow-parser": "0.266.1",
"get-east-asian-width": "1.3.0",
"get-stdin": "9.0.0",
"graphql": "16.10.0",
- "hermes-parser": "0.26.0",
+ "hermes-parser": "0.27.0",
"html-element-attributes": "3.4.0",
"html-tag-names": "2.1.0",
"html-ua-styles": "0.0.8",
diff --git a/yarn.lock b/yarn.lock
index 154d9317ca31..8bd6561c04bb 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4337,10 +4337,10 @@ __metadata:
languageName: node
linkType: hard
-"flow-parser@npm:0.259.1":
- version: 0.259.1
- resolution: "flow-parser@npm:0.259.1"
- checksum: 10/a92a17cedce15f844b1541a12fba8d6b4cbbdcf583b9dc223d4652d83dcd780e7535d82091cffa28837425f176f41a5242c0f6cf24638d36a5b99790d3318bff
+"flow-parser@npm:0.266.1":
+ version: 0.266.1
+ resolution: "flow-parser@npm:0.266.1"
+ checksum: 10/179d16b296f44e2a076fcef502fcf768b3e59749e715cdbfb192d6cfbe874e9ccd846fb2e171a13432f787185f4541cbbb8a61937e0124b59edb4c4896353a76
languageName: node
linkType: hard
@@ -4608,19 +4608,19 @@ __metadata:
languageName: node
linkType: hard
-"hermes-estree@npm:0.26.0":
- version: 0.26.0
- resolution: "hermes-estree@npm:0.26.0"
- checksum: 10/4a4fe72f2c873ad6f66537e70da4a075ad7eb9758a6c605e103c3232f311f22deba0f59345161b2dede4e7fe74794c7537d88dd4cedcecb0967719404ebc6b4d
+"hermes-estree@npm:0.27.0":
+ version: 0.27.0
+ resolution: "hermes-estree@npm:0.27.0"
+ checksum: 10/bbad6b3f800d38bebcdfba6b5548facb0b7d61d2bdddf3d581563836142a7bf658bdeb6e9c19a9ef0e8bcbeff65c440397ea76fd3c838f6f3df8562493166912
languageName: node
linkType: hard
-"hermes-parser@npm:0.26.0":
- version: 0.26.0
- resolution: "hermes-parser@npm:0.26.0"
+"hermes-parser@npm:0.27.0":
+ version: 0.27.0
+ resolution: "hermes-parser@npm:0.27.0"
dependencies:
- hermes-estree: "npm:0.26.0"
- checksum: 10/dc1c80ef2c4835b799025ad83837e34c6f6b898a24714d9086849979dc06805ecfade3065310d9ffde30ed3dfe45afe3c54eee7e79d52e1ecc0a139d6fdc0d89
+ hermes-estree: "npm:0.27.0"
+ checksum: 10/58850d6cd5358a2a5c98f28e4b25b9bfd8b4b5fdf1e0c69a1b45fe597d01b5ae63ac2700e282528b0f521c659505496bc691d0ebe174cb10b328e6b206e5105f
languageName: node
linkType: hard
@@ -6918,12 +6918,12 @@ __metadata:
fast-json-stable-stringify: "npm:2.1.0"
file-entry-cache: "npm:10.0.8"
find-cache-dir: "npm:5.0.0"
- flow-parser: "npm:0.259.1"
+ flow-parser: "npm:0.266.1"
get-east-asian-width: "npm:1.3.0"
get-stdin: "npm:9.0.0"
globals: "npm:16.0.0"
graphql: "npm:16.10.0"
- hermes-parser: "npm:0.26.0"
+ hermes-parser: "npm:0.27.0"
html-element-attributes: "npm:3.4.0"
html-tag-names: "npm:2.1.0"
html-ua-styles: "npm:0.0.8"
| diff --git a/package.json b/package.json
index 2436632dd694..b9bd36f98fd3 100644
--- a/package.json
+++ b/package.json
@@ -57,11 +57,11 @@
"fast-json-stable-stringify": "2.1.0",
"file-entry-cache": "10.0.8",
"find-cache-dir": "5.0.0",
- "flow-parser": "0.259.1",
+ "flow-parser": "0.266.1",
"get-east-asian-width": "1.3.0",
"get-stdin": "9.0.0",
"graphql": "16.10.0",
- "hermes-parser": "0.26.0",
+ "hermes-parser": "0.27.0",
"html-element-attributes": "3.4.0",
"html-tag-names": "2.1.0",
"html-ua-styles": "0.0.8",
diff --git a/yarn.lock b/yarn.lock
index 154d9317ca31..8bd6561c04bb 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4337,10 +4337,10 @@ __metadata:
-"flow-parser@npm:0.259.1":
- version: 0.259.1
- resolution: "flow-parser@npm:0.259.1"
- checksum: 10/a92a17cedce15f844b1541a12fba8d6b4cbbdcf583b9dc223d4652d83dcd780e7535d82091cffa28837425f176f41a5242c0f6cf24638d36a5b99790d3318bff
+"flow-parser@npm:0.266.1":
+ resolution: "flow-parser@npm:0.266.1"
+ checksum: 10/179d16b296f44e2a076fcef502fcf768b3e59749e715cdbfb192d6cfbe874e9ccd846fb2e171a13432f787185f4541cbbb8a61937e0124b59edb4c4896353a76
@@ -4608,19 +4608,19 @@ __metadata:
-"hermes-estree@npm:0.26.0":
- resolution: "hermes-estree@npm:0.26.0"
- checksum: 10/4a4fe72f2c873ad6f66537e70da4a075ad7eb9758a6c605e103c3232f311f22deba0f59345161b2dede4e7fe74794c7537d88dd4cedcecb0967719404ebc6b4d
+"hermes-estree@npm:0.27.0":
+ resolution: "hermes-estree@npm:0.27.0"
+ checksum: 10/bbad6b3f800d38bebcdfba6b5548facb0b7d61d2bdddf3d581563836142a7bf658bdeb6e9c19a9ef0e8bcbeff65c440397ea76fd3c838f6f3df8562493166912
-"hermes-parser@npm:0.26.0":
- resolution: "hermes-parser@npm:0.26.0"
+"hermes-parser@npm:0.27.0":
+ resolution: "hermes-parser@npm:0.27.0"
dependencies:
- hermes-estree: "npm:0.26.0"
- checksum: 10/dc1c80ef2c4835b799025ad83837e34c6f6b898a24714d9086849979dc06805ecfade3065310d9ffde30ed3dfe45afe3c54eee7e79d52e1ecc0a139d6fdc0d89
+ hermes-estree: "npm:0.27.0"
+ checksum: 10/58850d6cd5358a2a5c98f28e4b25b9bfd8b4b5fdf1e0c69a1b45fe597d01b5ae63ac2700e282528b0f521c659505496bc691d0ebe174cb10b328e6b206e5105f
@@ -6918,12 +6918,12 @@ __metadata:
fast-json-stable-stringify: "npm:2.1.0"
file-entry-cache: "npm:10.0.8"
find-cache-dir: "npm:5.0.0"
- flow-parser: "npm:0.259.1"
get-east-asian-width: "npm:1.3.0"
get-stdin: "npm:9.0.0"
globals: "npm:16.0.0"
graphql: "npm:16.10.0"
- hermes-parser: "npm:0.26.0"
+ hermes-parser: "npm:0.27.0"
html-element-attributes: "npm:3.4.0"
html-tag-names: "npm:2.1.0"
html-ua-styles: "npm:0.0.8" | [
"+ version: 0.266.1",
"+ flow-parser: \"npm:0.266.1\""
] | [
31,
71
] | {
"additions": 17,
"author": "renovate[bot]",
"deletions": 17,
"html_url": "https://github.com/prettier/prettier/pull/17313",
"issue_id": 17313,
"merged_at": "2025-04-07T07:05:24Z",
"omission_probability": 0.1,
"pr_number": 17313,
"repo": "prettier/prettier",
"title": "chore(deps): update flow-parser",
"total_changes": 34
} |
198 | diff --git a/package.json b/package.json
index 2436632dd694..b3b082dd82c5 100644
--- a/package.json
+++ b/package.json
@@ -36,8 +36,8 @@
"@babel/types": "7.27.0",
"@glimmer/syntax": "0.94.9",
"@prettier/parse-srcset": "3.1.0",
- "@typescript-eslint/typescript-estree": "8.25.0",
- "@typescript-eslint/visitor-keys": "8.25.0",
+ "@typescript-eslint/typescript-estree": "8.29.0",
+ "@typescript-eslint/visitor-keys": "8.29.0",
"acorn": "8.14.1",
"acorn-jsx": "5.3.2",
"angular-estree-parser": "11.1.1",
@@ -111,7 +111,7 @@
"@eslint/js": "9.21.0",
"@stylistic/eslint-plugin-js": "4.0.1",
"@types/estree": "1.0.7",
- "@typescript-eslint/eslint-plugin": "8.25.0",
+ "@typescript-eslint/eslint-plugin": "8.29.0",
"browserslist": "4.24.4",
"browserslist-to-esbuild": "2.1.1",
"c8": "10.1.3",
diff --git a/yarn.lock b/yarn.lock
index 154d9317ca31..ba9e7c9a17bb 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2157,15 +2157,15 @@ __metadata:
languageName: node
linkType: hard
-"@typescript-eslint/eslint-plugin@npm:8.25.0":
- version: 8.25.0
- resolution: "@typescript-eslint/eslint-plugin@npm:8.25.0"
+"@typescript-eslint/eslint-plugin@npm:8.29.0":
+ version: 8.29.0
+ resolution: "@typescript-eslint/eslint-plugin@npm:8.29.0"
dependencies:
"@eslint-community/regexpp": "npm:^4.10.0"
- "@typescript-eslint/scope-manager": "npm:8.25.0"
- "@typescript-eslint/type-utils": "npm:8.25.0"
- "@typescript-eslint/utils": "npm:8.25.0"
- "@typescript-eslint/visitor-keys": "npm:8.25.0"
+ "@typescript-eslint/scope-manager": "npm:8.29.0"
+ "@typescript-eslint/type-utils": "npm:8.29.0"
+ "@typescript-eslint/utils": "npm:8.29.0"
+ "@typescript-eslint/visitor-keys": "npm:8.29.0"
graphemer: "npm:^1.4.0"
ignore: "npm:^5.3.1"
natural-compare: "npm:^1.4.0"
@@ -2173,49 +2173,49 @@ __metadata:
peerDependencies:
"@typescript-eslint/parser": ^8.0.0 || ^8.0.0-alpha.0
eslint: ^8.57.0 || ^9.0.0
- typescript: ">=4.8.4 <5.8.0"
- checksum: 10/605d65c8e2917fe88d6c1f9de2acddb4e46a79a86816354896c024fde4e2294d4e16f492bf8e46a8c28e49b3b33069b81f50615a8ad90e266d0d15915b821d84
+ typescript: ">=4.8.4 <5.9.0"
+ checksum: 10/1df4b43c209e40a00ec77e572b575760a9ac93967b6ebcc13f36587bf2881fc891c158f62cf25e8c2b8ca1ecd05b3eb583b30869ba6c2fa558435f0574773df8
languageName: node
linkType: hard
-"@typescript-eslint/scope-manager@npm:8.25.0, @typescript-eslint/scope-manager@npm:^8.24.1":
- version: 8.25.0
- resolution: "@typescript-eslint/scope-manager@npm:8.25.0"
+"@typescript-eslint/scope-manager@npm:8.29.0, @typescript-eslint/scope-manager@npm:^8.24.1":
+ version: 8.29.0
+ resolution: "@typescript-eslint/scope-manager@npm:8.29.0"
dependencies:
- "@typescript-eslint/types": "npm:8.25.0"
- "@typescript-eslint/visitor-keys": "npm:8.25.0"
- checksum: 10/474cbb29119dd6976a65228ad0d25dbbf4f2973954e2a446d7f37fa0aaa3be8665bfdb5f6359d1645e1506c579a04c34c9fe0c30cf118808bcaa2f9afaa2d881
+ "@typescript-eslint/types": "npm:8.29.0"
+ "@typescript-eslint/visitor-keys": "npm:8.29.0"
+ checksum: 10/23ce9962d57607f91a8a4a9bc43e64bd91cd933b53e61765924704614e52f39e8ccb28276b60b7472fb6dffe52fa681f114b73e4561fb4dcb74910a4e6a3629f
languageName: node
linkType: hard
-"@typescript-eslint/type-utils@npm:8.25.0, @typescript-eslint/type-utils@npm:^8.0.0, @typescript-eslint/type-utils@npm:^8.24.1":
- version: 8.25.0
- resolution: "@typescript-eslint/type-utils@npm:8.25.0"
+"@typescript-eslint/type-utils@npm:8.29.0, @typescript-eslint/type-utils@npm:^8.0.0, @typescript-eslint/type-utils@npm:^8.24.1":
+ version: 8.29.0
+ resolution: "@typescript-eslint/type-utils@npm:8.29.0"
dependencies:
- "@typescript-eslint/typescript-estree": "npm:8.25.0"
- "@typescript-eslint/utils": "npm:8.25.0"
+ "@typescript-eslint/typescript-estree": "npm:8.29.0"
+ "@typescript-eslint/utils": "npm:8.29.0"
debug: "npm:^4.3.4"
ts-api-utils: "npm:^2.0.1"
peerDependencies:
eslint: ^8.57.0 || ^9.0.0
- typescript: ">=4.8.4 <5.8.0"
- checksum: 10/7f4f7afeca3fd96340b5c87a32484d963c26de621c8fc77c770428150b8d2ccc8f30c6ac9e3b85f521ad47223a2d1438446c0faeaef1a3fb118cc45098cf5788
+ typescript: ">=4.8.4 <5.9.0"
+ checksum: 10/3b18caf6d3d16461d462b8960e1fa7fdb94f0eb2aa8afb9c95e2e458af32ffc82b14f1d26bb635b5e751bd0a7ff5c10fa1754377fff0dea760d1a96848705f88
languageName: node
linkType: hard
-"@typescript-eslint/types@npm:8.25.0, @typescript-eslint/types@npm:^8.24.1":
- version: 8.25.0
- resolution: "@typescript-eslint/types@npm:8.25.0"
- checksum: 10/f560a0a9b00d38eca43204e7e8cdd4896900163a9ca3bf8007b259fd4a1551a914012cccddd0c263d1f091e321acd54640502b9f3238d4c7f9eb712d409c3a22
+"@typescript-eslint/types@npm:8.29.0, @typescript-eslint/types@npm:^8.24.1":
+ version: 8.29.0
+ resolution: "@typescript-eslint/types@npm:8.29.0"
+ checksum: 10/d65b9f2f6d87a3744788b09d9112c4a0298f1215138d8677240aae3bfa37ddc24a59315536cd9aab63c7608909ae2c5f436924c889b98986b78003b6028b5c35
languageName: node
linkType: hard
-"@typescript-eslint/typescript-estree@npm:8.25.0, @typescript-eslint/typescript-estree@npm:^8.24.1":
- version: 8.25.0
- resolution: "@typescript-eslint/typescript-estree@npm:8.25.0"
+"@typescript-eslint/typescript-estree@npm:8.29.0, @typescript-eslint/typescript-estree@npm:^8.24.1":
+ version: 8.29.0
+ resolution: "@typescript-eslint/typescript-estree@npm:8.29.0"
dependencies:
- "@typescript-eslint/types": "npm:8.25.0"
- "@typescript-eslint/visitor-keys": "npm:8.25.0"
+ "@typescript-eslint/types": "npm:8.29.0"
+ "@typescript-eslint/visitor-keys": "npm:8.29.0"
debug: "npm:^4.3.4"
fast-glob: "npm:^3.3.2"
is-glob: "npm:^4.0.3"
@@ -2223,33 +2223,33 @@ __metadata:
semver: "npm:^7.6.0"
ts-api-utils: "npm:^2.0.1"
peerDependencies:
- typescript: ">=4.8.4 <5.8.0"
- checksum: 10/7378415eddf0cac90f6ef0f919da9a6050b14fdfa320b16e68212dcd67cce65f0fc3e9e0266d10b4cb2ff9a3de23ac6e992de2eef7b858019381ebf2cb211e43
+ typescript: ">=4.8.4 <5.9.0"
+ checksum: 10/276e6ea97857ef0fd940578d4b8f1677fd68d2bb62603c85d7aa97fcf86c1f66c5da962393254b605c7025f0cda74395904053891088cbe405b899afc1180e9c
languageName: node
linkType: hard
-"@typescript-eslint/utils@npm:8.25.0, @typescript-eslint/utils@npm:^6.0.0 || ^7.0.0 || ^8.0.0, @typescript-eslint/utils@npm:^8.24.1":
- version: 8.25.0
- resolution: "@typescript-eslint/utils@npm:8.25.0"
+"@typescript-eslint/utils@npm:8.29.0, @typescript-eslint/utils@npm:^6.0.0 || ^7.0.0 || ^8.0.0, @typescript-eslint/utils@npm:^8.24.1":
+ version: 8.29.0
+ resolution: "@typescript-eslint/utils@npm:8.29.0"
dependencies:
"@eslint-community/eslint-utils": "npm:^4.4.0"
- "@typescript-eslint/scope-manager": "npm:8.25.0"
- "@typescript-eslint/types": "npm:8.25.0"
- "@typescript-eslint/typescript-estree": "npm:8.25.0"
+ "@typescript-eslint/scope-manager": "npm:8.29.0"
+ "@typescript-eslint/types": "npm:8.29.0"
+ "@typescript-eslint/typescript-estree": "npm:8.29.0"
peerDependencies:
eslint: ^8.57.0 || ^9.0.0
- typescript: ">=4.8.4 <5.8.0"
- checksum: 10/9e54ad9551401eb52780cef2d08d3a0b9de5b378af529fe149f48230c2378da6b28c9f9b1b8fa88b04c6455bd59154b23d78d5c4775868d330d724ae6038a8b6
+ typescript: ">=4.8.4 <5.9.0"
+ checksum: 10/1fd17a28b8b57fc73c0455dea43a8185d3a4421f4a21ece01009b5e6a2974c8d4113f90d27993f668fa97077891b4464588d380c25116d351eb12ad7ef0d468d
languageName: node
linkType: hard
-"@typescript-eslint/visitor-keys@npm:8.25.0":
- version: 8.25.0
- resolution: "@typescript-eslint/visitor-keys@npm:8.25.0"
+"@typescript-eslint/visitor-keys@npm:8.29.0":
+ version: 8.29.0
+ resolution: "@typescript-eslint/visitor-keys@npm:8.29.0"
dependencies:
- "@typescript-eslint/types": "npm:8.25.0"
+ "@typescript-eslint/types": "npm:8.29.0"
eslint-visitor-keys: "npm:^4.2.0"
- checksum: 10/9fd236d22f146f07536a55507ab8db7bbe37b127c2ab4b29f7b3d86de001356216ecd5cd505f82deb32d3f52316d8b7d549c24275ea96cbf1d72871eac998f1b
+ checksum: 10/02e0e86ab112849a31b7d06c767be0ca7802385bf953d3b75f4ba6d06741d9492773325bc69d4c2a1c191b08f1c4c4b33f8e062d6d5d9f0f4f78f1b8b3cc2d41
languageName: node
linkType: hard
@@ -6877,9 +6877,9 @@ __metadata:
"@prettier/parse-srcset": "npm:3.1.0"
"@stylistic/eslint-plugin-js": "npm:4.0.1"
"@types/estree": "npm:1.0.7"
- "@typescript-eslint/eslint-plugin": "npm:8.25.0"
- "@typescript-eslint/typescript-estree": "npm:8.25.0"
- "@typescript-eslint/visitor-keys": "npm:8.25.0"
+ "@typescript-eslint/eslint-plugin": "npm:8.29.0"
+ "@typescript-eslint/typescript-estree": "npm:8.29.0"
+ "@typescript-eslint/visitor-keys": "npm:8.29.0"
acorn: "npm:8.14.1"
acorn-jsx: "npm:5.3.2"
angular-estree-parser: "npm:11.1.1"
| diff --git a/package.json b/package.json
index 2436632dd694..b3b082dd82c5 100644
--- a/package.json
+++ b/package.json
@@ -36,8 +36,8 @@
"@babel/types": "7.27.0",
"@glimmer/syntax": "0.94.9",
"@prettier/parse-srcset": "3.1.0",
- "@typescript-eslint/typescript-estree": "8.25.0",
- "@typescript-eslint/visitor-keys": "8.25.0",
+ "@typescript-eslint/typescript-estree": "8.29.0",
+ "@typescript-eslint/visitor-keys": "8.29.0",
"acorn": "8.14.1",
"acorn-jsx": "5.3.2",
"angular-estree-parser": "11.1.1",
@@ -111,7 +111,7 @@
"@eslint/js": "9.21.0",
"@stylistic/eslint-plugin-js": "4.0.1",
"@types/estree": "1.0.7",
- "@typescript-eslint/eslint-plugin": "8.25.0",
+ "@typescript-eslint/eslint-plugin": "8.29.0",
"browserslist": "4.24.4",
"browserslist-to-esbuild": "2.1.1",
"c8": "10.1.3",
diff --git a/yarn.lock b/yarn.lock
index 154d9317ca31..ba9e7c9a17bb 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2157,15 +2157,15 @@ __metadata:
-"@typescript-eslint/eslint-plugin@npm:8.25.0":
+"@typescript-eslint/eslint-plugin@npm:8.29.0":
+ resolution: "@typescript-eslint/eslint-plugin@npm:8.29.0"
"@eslint-community/regexpp": "npm:^4.10.0"
+ "@typescript-eslint/type-utils": "npm:8.29.0"
graphemer: "npm:^1.4.0"
ignore: "npm:^5.3.1"
natural-compare: "npm:^1.4.0"
@@ -2173,49 +2173,49 @@ __metadata:
"@typescript-eslint/parser": ^8.0.0 || ^8.0.0-alpha.0
- checksum: 10/605d65c8e2917fe88d6c1f9de2acddb4e46a79a86816354896c024fde4e2294d4e16f492bf8e46a8c28e49b3b33069b81f50615a8ad90e266d0d15915b821d84
+ checksum: 10/1df4b43c209e40a00ec77e572b575760a9ac93967b6ebcc13f36587bf2881fc891c158f62cf25e8c2b8ca1ecd05b3eb583b30869ba6c2fa558435f0574773df8
-"@typescript-eslint/scope-manager@npm:8.25.0, @typescript-eslint/scope-manager@npm:^8.24.1":
- resolution: "@typescript-eslint/scope-manager@npm:8.25.0"
+"@typescript-eslint/scope-manager@npm:8.29.0, @typescript-eslint/scope-manager@npm:^8.24.1":
+ resolution: "@typescript-eslint/scope-manager@npm:8.29.0"
- checksum: 10/474cbb29119dd6976a65228ad0d25dbbf4f2973954e2a446d7f37fa0aaa3be8665bfdb5f6359d1645e1506c579a04c34c9fe0c30cf118808bcaa2f9afaa2d881
+ checksum: 10/23ce9962d57607f91a8a4a9bc43e64bd91cd933b53e61765924704614e52f39e8ccb28276b60b7472fb6dffe52fa681f114b73e4561fb4dcb74910a4e6a3629f
-"@typescript-eslint/type-utils@npm:8.25.0, @typescript-eslint/type-utils@npm:^8.0.0, @typescript-eslint/type-utils@npm:^8.24.1":
- resolution: "@typescript-eslint/type-utils@npm:8.25.0"
+"@typescript-eslint/type-utils@npm:8.29.0, @typescript-eslint/type-utils@npm:^8.0.0, @typescript-eslint/type-utils@npm:^8.24.1":
+ resolution: "@typescript-eslint/type-utils@npm:8.29.0"
- checksum: 10/7f4f7afeca3fd96340b5c87a32484d963c26de621c8fc77c770428150b8d2ccc8f30c6ac9e3b85f521ad47223a2d1438446c0faeaef1a3fb118cc45098cf5788
+ checksum: 10/3b18caf6d3d16461d462b8960e1fa7fdb94f0eb2aa8afb9c95e2e458af32ffc82b14f1d26bb635b5e751bd0a7ff5c10fa1754377fff0dea760d1a96848705f88
-"@typescript-eslint/types@npm:8.25.0, @typescript-eslint/types@npm:^8.24.1":
- resolution: "@typescript-eslint/types@npm:8.25.0"
- checksum: 10/f560a0a9b00d38eca43204e7e8cdd4896900163a9ca3bf8007b259fd4a1551a914012cccddd0c263d1f091e321acd54640502b9f3238d4c7f9eb712d409c3a22
+"@typescript-eslint/types@npm:8.29.0, @typescript-eslint/types@npm:^8.24.1":
+ resolution: "@typescript-eslint/types@npm:8.29.0"
+ checksum: 10/d65b9f2f6d87a3744788b09d9112c4a0298f1215138d8677240aae3bfa37ddc24a59315536cd9aab63c7608909ae2c5f436924c889b98986b78003b6028b5c35
-"@typescript-eslint/typescript-estree@npm:8.25.0, @typescript-eslint/typescript-estree@npm:^8.24.1":
- resolution: "@typescript-eslint/typescript-estree@npm:8.25.0"
+"@typescript-eslint/typescript-estree@npm:8.29.0, @typescript-eslint/typescript-estree@npm:^8.24.1":
+ resolution: "@typescript-eslint/typescript-estree@npm:8.29.0"
fast-glob: "npm:^3.3.2"
is-glob: "npm:^4.0.3"
@@ -2223,33 +2223,33 @@ __metadata:
semver: "npm:^7.6.0"
- checksum: 10/7378415eddf0cac90f6ef0f919da9a6050b14fdfa320b16e68212dcd67cce65f0fc3e9e0266d10b4cb2ff9a3de23ac6e992de2eef7b858019381ebf2cb211e43
-"@typescript-eslint/utils@npm:8.25.0, @typescript-eslint/utils@npm:^6.0.0 || ^7.0.0 || ^8.0.0, @typescript-eslint/utils@npm:^8.24.1":
- resolution: "@typescript-eslint/utils@npm:8.25.0"
+"@typescript-eslint/utils@npm:8.29.0, @typescript-eslint/utils@npm:^6.0.0 || ^7.0.0 || ^8.0.0, @typescript-eslint/utils@npm:^8.24.1":
+ resolution: "@typescript-eslint/utils@npm:8.29.0"
"@eslint-community/eslint-utils": "npm:^4.4.0"
- checksum: 10/9e54ad9551401eb52780cef2d08d3a0b9de5b378af529fe149f48230c2378da6b28c9f9b1b8fa88b04c6455bd59154b23d78d5c4775868d330d724ae6038a8b6
+ checksum: 10/1fd17a28b8b57fc73c0455dea43a8185d3a4421f4a21ece01009b5e6a2974c8d4113f90d27993f668fa97077891b4464588d380c25116d351eb12ad7ef0d468d
-"@typescript-eslint/visitor-keys@npm:8.25.0":
- resolution: "@typescript-eslint/visitor-keys@npm:8.25.0"
+"@typescript-eslint/visitor-keys@npm:8.29.0":
+ resolution: "@typescript-eslint/visitor-keys@npm:8.29.0"
eslint-visitor-keys: "npm:^4.2.0"
- checksum: 10/9fd236d22f146f07536a55507ab8db7bbe37b127c2ab4b29f7b3d86de001356216ecd5cd505f82deb32d3f52316d8b7d549c24275ea96cbf1d72871eac998f1b
+ checksum: 10/02e0e86ab112849a31b7d06c767be0ca7802385bf953d3b75f4ba6d06741d9492773325bc69d4c2a1c191b08f1c4c4b33f8e062d6d5d9f0f4f78f1b8b3cc2d41
@@ -6877,9 +6877,9 @@ __metadata:
"@prettier/parse-srcset": "npm:3.1.0"
"@stylistic/eslint-plugin-js": "npm:4.0.1"
"@types/estree": "npm:1.0.7"
+ "@typescript-eslint/eslint-plugin": "npm:8.29.0"
acorn: "npm:8.14.1"
acorn-jsx: "npm:5.3.2"
angular-estree-parser: "npm:11.1.1" | [
"- resolution: \"@typescript-eslint/eslint-plugin@npm:8.25.0\"",
"- \"@typescript-eslint/type-utils\": \"npm:8.25.0\"",
"+ checksum: 10/276e6ea97857ef0fd940578d4b8f1677fd68d2bb62603c85d7aa97fcf86c1f66c5da962393254b605c7025f0cda74395904053891088cbe405b899afc1180e9c",
"- \"@typescript-eslint/eslint-plugin\": \"npm:8.25.0\""
] | [
34,
41,
132,
178
] | {
"additions": 52,
"author": "renovate[bot]",
"deletions": 52,
"html_url": "https://github.com/prettier/prettier/pull/17314",
"issue_id": 17314,
"merged_at": "2025-04-07T07:04:36Z",
"omission_probability": 0.1,
"pr_number": 17314,
"repo": "prettier/prettier",
"title": "chore(deps): update typescript-eslint to v8.29.0",
"total_changes": 104
} |
199 | diff --git a/packages/react-reconciler/src/ReactFiberCommitWork.js b/packages/react-reconciler/src/ReactFiberCommitWork.js
index 8065432370add..61cc176f72b19 100644
--- a/packages/react-reconciler/src/ReactFiberCommitWork.js
+++ b/packages/react-reconciler/src/ReactFiberCommitWork.js
@@ -1042,9 +1042,9 @@ function commitTransitionProgress(offscreenFiber: Fiber) {
if (
parent !== null &&
parent.tag === SuspenseComponent &&
- parent.memoizedProps.unstable_name
+ parent.memoizedProps.name
) {
- name = parent.memoizedProps.unstable_name;
+ name = parent.memoizedProps.name;
}
if (!wasHidden && isHidden) {
@@ -4816,7 +4816,7 @@ function commitPassiveUnmountInsideDeletedTreeOnFiber(
if (transitions !== null) {
const abortReason = {
reason: 'suspense',
- name: current.memoizedProps.unstable_name || null,
+ name: current.memoizedProps.name || null,
};
if (
current.memoizedState === null ||
diff --git a/packages/react-reconciler/src/__tests__/ReactTransitionTracing-test.js b/packages/react-reconciler/src/__tests__/ReactTransitionTracing-test.js
index 64d51a1ff3cd9..772eb987100aa 100644
--- a/packages/react-reconciler/src/__tests__/ReactTransitionTracing-test.js
+++ b/packages/react-reconciler/src/__tests__/ReactTransitionTracing-test.js
@@ -412,7 +412,7 @@ describe('ReactInteractionTracing', () => {
{navigate ? (
<Suspense
fallback={<Text text="Loading..." />}
- unstable_name="suspense page">
+ name="suspense page">
<AsyncText text="Page Two" />
</Suspense>
) : (
@@ -498,14 +498,14 @@ describe('ReactInteractionTracing', () => {
<>
{showText ? (
<Suspense
- unstable_name="show text"
+ name="show text"
fallback={<Text text="Show Text Loading..." />}>
<AsyncText text="Show Text" />
</Suspense>
) : null}
<Suspense
fallback={<Text text="Loading..." />}
- unstable_name="suspense page">
+ name="suspense page">
<AsyncText text="Page Two" />
</Suspense>
</>
@@ -605,14 +605,14 @@ describe('ReactInteractionTracing', () => {
<>
{showText ? (
<Suspense
- unstable_name="show text"
+ name="show text"
fallback={<Text text="Show Text Loading..." />}>
<AsyncText text="Show Text" />
</Suspense>
) : null}
<Suspense
fallback={<Text text="Loading..." />}
- unstable_name="suspense page">
+ name="suspense page">
<AsyncText text="Page Two" />
</Suspense>
</>
@@ -719,16 +719,16 @@ describe('ReactInteractionTracing', () => {
<>
<Suspense
fallback={<Text text="Loading..." />}
- unstable_name="suspense page">
+ name="suspense page">
<AsyncText text="Page Two" />
<Suspense
- unstable_name="show text one"
+ name="show text one"
fallback={<Text text="Show Text One Loading..." />}>
<AsyncText text="Show Text One" />
</Suspense>
<div>
<Suspense
- unstable_name="show text two"
+ name="show text two"
fallback={<Text text="Show Text Two Loading..." />}>
<AsyncText text="Show Text Two" />
</Suspense>
@@ -848,12 +848,12 @@ describe('ReactInteractionTracing', () => {
<>
<Suspense
fallback={<Text text="Loading..." />}
- unstable_name="suspense page">
+ name="suspense page">
<AsyncText text="Page Two" />
{/* showTextOne is entangled with navigate */}
{showTextOne ? (
<Suspense
- unstable_name="show text one"
+ name="show text one"
fallback={<Text text="Show Text One Loading..." />}>
<AsyncText text="Show Text One" />
</Suspense>
@@ -865,7 +865,7 @@ describe('ReactInteractionTracing', () => {
from completing */}
{showTextTwo ? (
<Suspense
- unstable_name="show text two"
+ name="show text two"
fallback={<Text text="Show Text Two Loading..." />}>
<AsyncText text="Show Text Two" />
</Suspense>
@@ -1115,13 +1115,13 @@ describe('ReactInteractionTracing', () => {
{navigate ? (
<Suspense
fallback={<Text text="Loading..." />}
- unstable_name="suspense page">
+ name="suspense page">
<AsyncText text="Page Two" />
<React.unstable_TracingMarker name="sync marker" />
<React.unstable_TracingMarker name="async marker">
<Suspense
fallback={<Text text="Loading..." />}
- unstable_name="marker suspense">
+ name="marker suspense">
<AsyncText text="Marker Text" />
</Suspense>
</React.unstable_TracingMarker>
@@ -1226,20 +1226,18 @@ describe('ReactInteractionTracing', () => {
<div>
{navigate ? (
<React.unstable_TracingMarker name="outer marker">
- <Suspense
- fallback={<Text text="Outer..." />}
- unstable_name="outer">
+ <Suspense fallback={<Text text="Outer..." />} name="outer">
<AsyncText text="Outer Text" />
<Suspense
fallback={<Text text="Inner One..." />}
- unstable_name="inner one">
+ name="inner one">
<React.unstable_TracingMarker name="marker one">
<AsyncText text="Inner Text One" />
</React.unstable_TracingMarker>
</Suspense>
<Suspense
fallback={<Text text="Inner Two..." />}
- unstable_name="inner two">
+ name="inner two">
<React.unstable_TracingMarker name="marker two">
<AsyncText text="Inner Text Two" />
</React.unstable_TracingMarker>
@@ -1488,21 +1486,21 @@ describe('ReactInteractionTracing', () => {
{showMarker ? (
<React.unstable_TracingMarker name="marker one">
<Suspense
- unstable_name="suspense page"
+ name="suspense page"
fallback={<Text text="Loading..." />}>
<AsyncText text="Page Two" />
</Suspense>
</React.unstable_TracingMarker>
) : (
<Suspense
- unstable_name="suspense page"
+ name="suspense page"
fallback={<Text text="Loading..." />}>
<AsyncText text="Page Two" />
</Suspense>
)}
<React.unstable_TracingMarker name="sibling">
<Suspense
- unstable_name="suspense sibling"
+ name="suspense sibling"
fallback={<Text text="Sibling Loading..." />}>
<AsyncText text="Sibling Text" />
</Suspense>
@@ -1652,7 +1650,7 @@ describe('ReactInteractionTracing', () => {
<div>
<React.unstable_TracingMarker name="one">
<Suspense
- unstable_name="suspense one"
+ name="suspense one"
fallback={<Text text="Loading One..." />}>
<AsyncText text="Page One" />
</Suspense>
@@ -1661,7 +1659,7 @@ describe('ReactInteractionTracing', () => {
) : null}
<React.unstable_TracingMarker name="two">
<Suspense
- unstable_name="suspense two"
+ name="suspense two"
fallback={<Text text="Loading Two..." />}>
<AsyncText text="Page Two" />
</Suspense>
@@ -1788,12 +1786,12 @@ describe('ReactInteractionTracing', () => {
<React.unstable_TracingMarker name="one">
{!deleteOne ? (
<Suspense
- unstable_name="suspense one"
+ name="suspense one"
fallback={<Text text="Loading One..." />}>
<AsyncText text="Page One" />
<React.unstable_TracingMarker name="page one" />
<Suspense
- unstable_name="suspense child"
+ name="suspense child"
fallback={<Text text="Loading Child..." />}>
<React.unstable_TracingMarker name="child" />
<AsyncText text="Child" />
@@ -1803,7 +1801,7 @@ describe('ReactInteractionTracing', () => {
</React.unstable_TracingMarker>
<React.unstable_TracingMarker name="two">
<Suspense
- unstable_name="suspense two"
+ name="suspense two"
fallback={<Text text="Loading Two..." />}>
<AsyncText text="Page Two" />
</Suspense>
@@ -1948,11 +1946,11 @@ describe('ReactInteractionTracing', () => {
return (
<React.unstable_TracingMarker name="parent">
{show ? (
- <Suspense unstable_name="appended child">
+ <Suspense name="appended child">
<AsyncText text="Appended child" />
</Suspense>
) : null}
- <Suspense unstable_name="child">
+ <Suspense name="child">
<AsyncText text="Child" />
</Suspense>
</React.unstable_TracingMarker>
@@ -2068,13 +2066,13 @@ describe('ReactInteractionTracing', () => {
{show ? (
<React.unstable_TracingMarker name="appended child">
{showSuspense ? (
- <Suspense unstable_name="appended child">
+ <Suspense name="appended child">
<AsyncText text="Appended child" />
</Suspense>
) : null}
</React.unstable_TracingMarker>
) : null}
- <Suspense unstable_name="child">
+ <Suspense name="child">
<AsyncText text="Child" />
</Suspense>
</React.unstable_TracingMarker>
@@ -2349,9 +2347,7 @@ describe('ReactInteractionTracing', () => {
function App() {
return (
- <Suspense
- fallback={<Text text="Loading..." />}
- unstable_name="suspense page">
+ <Suspense fallback={<Text text="Loading..." />} name="suspense page">
<AsyncText text="Page Two" />
</Suspense>
);
@@ -2416,12 +2412,10 @@ describe('ReactInteractionTracing', () => {
});
return (
<>
- <Suspense unstable_name="one" fallback={<Text text="Loading..." />}>
+ <Suspense name="one" fallback={<Text text="Loading..." />}>
<AsyncText text="Text" />
</Suspense>
- <Suspense
- unstable_name="two"
- fallback={<Text text="Loading Two..." />}>
+ <Suspense name="two" fallback={<Text text="Loading Two..." />}>
<AsyncText text="Text Two" />
</Suspense>
</>
@@ -2490,9 +2484,7 @@ describe('ReactInteractionTracing', () => {
function App({name}) {
return (
<>
- <Suspense
- unstable_name={name}
- fallback={<Text text={`Loading ${name}...`} />}>
+ <Suspense name={name} fallback={<Text text={`Loading ${name}...`} />}>
<AsyncText text={`Text ${name}`} />
</Suspense>
</>
diff --git a/packages/shared/ReactTypes.js b/packages/shared/ReactTypes.js
index c439f1fb4ad9e..e199fa9e7b0b7 100644
--- a/packages/shared/ReactTypes.js
+++ b/packages/shared/ReactTypes.js
@@ -278,7 +278,7 @@ export type SuspenseProps = {
unstable_avoidThisFallback?: boolean,
unstable_expectedLoadTime?: number,
- unstable_name?: string,
+ name?: string,
};
export type TracingMarkerProps = {
| diff --git a/packages/react-reconciler/src/ReactFiberCommitWork.js b/packages/react-reconciler/src/ReactFiberCommitWork.js
index 8065432370add..61cc176f72b19 100644
--- a/packages/react-reconciler/src/ReactFiberCommitWork.js
+++ b/packages/react-reconciler/src/ReactFiberCommitWork.js
@@ -1042,9 +1042,9 @@ function commitTransitionProgress(offscreenFiber: Fiber) {
if (
parent !== null &&
parent.tag === SuspenseComponent &&
- parent.memoizedProps.unstable_name
+ parent.memoizedProps.name
) {
+ name = parent.memoizedProps.name;
}
if (!wasHidden && isHidden) {
@@ -4816,7 +4816,7 @@ function commitPassiveUnmountInsideDeletedTreeOnFiber(
if (transitions !== null) {
const abortReason = {
reason: 'suspense',
- name: current.memoizedProps.unstable_name || null,
+ name: current.memoizedProps.name || null,
};
if (
current.memoizedState === null ||
diff --git a/packages/react-reconciler/src/__tests__/ReactTransitionTracing-test.js b/packages/react-reconciler/src/__tests__/ReactTransitionTracing-test.js
index 64d51a1ff3cd9..772eb987100aa 100644
--- a/packages/react-reconciler/src/__tests__/ReactTransitionTracing-test.js
+++ b/packages/react-reconciler/src/__tests__/ReactTransitionTracing-test.js
@@ -412,7 +412,7 @@ describe('ReactInteractionTracing', () => {
) : (
@@ -498,14 +498,14 @@ describe('ReactInteractionTracing', () => {
@@ -605,14 +605,14 @@ describe('ReactInteractionTracing', () => {
@@ -719,16 +719,16 @@ describe('ReactInteractionTracing', () => {
- unstable_name="show text one"
+ name="show text one"
fallback={<Text text="Show Text One Loading..." />}>
<AsyncText text="Show Text One" />
@@ -848,12 +848,12 @@ describe('ReactInteractionTracing', () => {
{/* showTextOne is entangled with navigate */}
{showTextOne ? (
- unstable_name="show text one"
+ name="show text one"
fallback={<Text text="Show Text One Loading..." />}>
<AsyncText text="Show Text One" />
@@ -865,7 +865,7 @@ describe('ReactInteractionTracing', () => {
from completing */}
{showTextTwo ? (
@@ -1115,13 +1115,13 @@ describe('ReactInteractionTracing', () => {
<React.unstable_TracingMarker name="sync marker" />
<React.unstable_TracingMarker name="async marker">
fallback={<Text text="Loading..." />}
- unstable_name="marker suspense">
+ name="marker suspense">
<AsyncText text="Marker Text" />
@@ -1226,20 +1226,18 @@ describe('ReactInteractionTracing', () => {
<div>
<React.unstable_TracingMarker name="outer marker">
- <Suspense
- fallback={<Text text="Outer..." />}
- unstable_name="outer">
+ <Suspense fallback={<Text text="Outer..." />} name="outer">
<AsyncText text="Outer Text" />
fallback={<Text text="Inner One..." />}
- unstable_name="inner one">
+ name="inner one">
<React.unstable_TracingMarker name="marker one">
<AsyncText text="Inner Text One" />
fallback={<Text text="Inner Two..." />}
- unstable_name="inner two">
<React.unstable_TracingMarker name="marker two">
<AsyncText text="Inner Text Two" />
@@ -1488,21 +1486,21 @@ describe('ReactInteractionTracing', () => {
{showMarker ? (
<React.unstable_TracingMarker name="marker one">
- unstable_name="suspense page"
+ name="suspense page"
fallback={<Text text="Loading..." />}>
<AsyncText text="Page Two" />
</React.unstable_TracingMarker>
) : (
- unstable_name="suspense page"
+ name="suspense page"
fallback={<Text text="Loading..." />}>
)}
<React.unstable_TracingMarker name="sibling">
- unstable_name="suspense sibling"
+ name="suspense sibling"
fallback={<Text text="Sibling Loading..." />}>
<AsyncText text="Sibling Text" />
@@ -1652,7 +1650,7 @@ describe('ReactInteractionTracing', () => {
<React.unstable_TracingMarker name="one">
- unstable_name="suspense one"
+ name="suspense one"
fallback={<Text text="Loading One..." />}>
<AsyncText text="Page One" />
</Suspense>
@@ -1661,7 +1659,7 @@ describe('ReactInteractionTracing', () => {
@@ -1788,12 +1786,12 @@ describe('ReactInteractionTracing', () => {
<React.unstable_TracingMarker name="one">
{!deleteOne ? (
- unstable_name="suspense one"
+ name="suspense one"
fallback={<Text text="Loading One..." />}>
<AsyncText text="Page One" />
<React.unstable_TracingMarker name="page one" />
- unstable_name="suspense child"
+ name="suspense child"
fallback={<Text text="Loading Child..." />}>
<React.unstable_TracingMarker name="child" />
<AsyncText text="Child" />
@@ -1803,7 +1801,7 @@ describe('ReactInteractionTracing', () => {
@@ -1948,11 +1946,11 @@ describe('ReactInteractionTracing', () => {
<React.unstable_TracingMarker name="parent">
- <Suspense unstable_name="appended child">
+ <Suspense name="appended child">
<AsyncText text="Appended child" />
@@ -2068,13 +2066,13 @@ describe('ReactInteractionTracing', () => {
<React.unstable_TracingMarker name="appended child">
{showSuspense ? (
- <Suspense unstable_name="appended child">
+ <Suspense name="appended child">
<AsyncText text="Appended child" />
</React.unstable_TracingMarker>
@@ -2349,9 +2347,7 @@ describe('ReactInteractionTracing', () => {
function App() {
- <Suspense
- fallback={<Text text="Loading..." />}
- unstable_name="suspense page">
+ <Suspense fallback={<Text text="Loading..." />} name="suspense page">
<AsyncText text="Page Two" />
</Suspense>
);
@@ -2416,12 +2412,10 @@ describe('ReactInteractionTracing', () => {
});
- <Suspense unstable_name="one" fallback={<Text text="Loading..." />}>
+ <Suspense name="one" fallback={<Text text="Loading..." />}>
<AsyncText text="Text" />
- unstable_name="two"
- fallback={<Text text="Loading Two..." />}>
+ <Suspense name="two" fallback={<Text text="Loading Two..." />}>
<AsyncText text="Text Two" />
@@ -2490,9 +2484,7 @@ describe('ReactInteractionTracing', () => {
function App({name}) {
- unstable_name={name}
- fallback={<Text text={`Loading ${name}...`} />}>
+ <Suspense name={name} fallback={<Text text={`Loading ${name}...`} />}>
<AsyncText text={`Text ${name}`} />
diff --git a/packages/shared/ReactTypes.js b/packages/shared/ReactTypes.js
index c439f1fb4ad9e..e199fa9e7b0b7 100644
--- a/packages/shared/ReactTypes.js
+++ b/packages/shared/ReactTypes.js
@@ -278,7 +278,7 @@ export type SuspenseProps = {
unstable_avoidThisFallback?: boolean,
unstable_expectedLoadTime?: number,
- unstable_name?: string,
+ name?: string,
};
export type TracingMarkerProps = { | [
"- name = parent.memoizedProps.unstable_name;",
"+ name=\"inner two\">"
] | [
11,
152
] | {
"additions": 36,
"author": "sebmarkbage",
"deletions": 44,
"html_url": "https://github.com/facebook/react/pull/33014",
"issue_id": 33014,
"merged_at": "2025-04-24T20:53:34Z",
"omission_probability": 0.1,
"pr_number": 33014,
"repo": "facebook/react",
"title": "Rename Suspense unstable_name to name",
"total_changes": 80
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.