From 840eb96e1614182cc6fad779c49d5311791debfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E6=9D=B0=E5=8F=8B=20Jieyou=20Xu=20=28Joe=29?= <39484203+jieyouxu@users.noreply.github.com> Date: Tue, 7 Jan 2025 20:49:29 +0800 Subject: [PATCH 01/26] rustfmt: drop nightly-gating of the `--style-edition` flag registration --- src/bin/main.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/bin/main.rs b/src/bin/main.rs index 4078484ff10..34984798ae6 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -161,6 +161,12 @@ fn make_opts() -> Options { "Set options from command line. These settings take priority over .rustfmt.toml", "[key1=val1,key2=val2...]", ); + opts.optopt( + "", + "style-edition", + "The edition of the Style Guide.", + "[2015|2018|2021|2024]", + ); if is_nightly { opts.optflag( @@ -186,12 +192,6 @@ fn make_opts() -> Options { "skip-children", "Don't reformat child modules (unstable).", ); - opts.optopt( - "", - "style-edition", - "The edition of the Style Guide (unstable).", - "[2015|2018|2021|2024]", - ); } opts.optflag("v", "verbose", "Print verbose output"); From 06ff325556767d881cf04d53100669c9971130c3 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 7 Jan 2025 08:56:23 +0000 Subject: [PATCH 02/26] Rename PatKind::Lit to Expr --- src/patterns.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/patterns.rs b/src/patterns.rs index 7b4730eadc8..b55469f332a 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -42,7 +42,7 @@ fn is_short_pattern_inner(pat: &ast::Pat) -> bool { | ast::PatKind::Never | ast::PatKind::Wild | ast::PatKind::Err(_) - | ast::PatKind::Lit(_) => true, + | ast::PatKind::Expr(_) => true, ast::PatKind::Ident(_, _, ref pat) => pat.is_none(), ast::PatKind::Struct(..) | ast::PatKind::MacCall(..) @@ -293,7 +293,7 @@ impl Rewrite for Pat { let path_str = rewrite_path(context, PathContext::Expr, q_self, path, shape)?; rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape) } - PatKind::Lit(ref expr) => expr.rewrite_result(context, shape), + PatKind::Expr(ref expr) => expr.rewrite_result(context, shape), PatKind::Slice(ref slice_pat) if context.config.style_edition() <= StyleEdition::Edition2021 => { @@ -530,7 +530,7 @@ pub(crate) fn can_be_overflowed_pat( ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => { can_be_overflowed_pat(context, &TuplePatField::Pat(p), len) } - ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len), + ast::PatKind::Expr(ref expr) => can_be_overflowed_expr(context, expr, len), _ => false, }, TuplePatField::Dotdot(..) => false, From ad8b776a979d7f1ea80ead6843c52fd2188c4786 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Wed, 8 Jan 2025 08:53:10 +0000 Subject: [PATCH 03/26] Only treat plain literal patterns as short --- src/patterns.rs | 37 +++++++++++++++++++++++++------------ tests/source/pattern.rs | 10 ++++++++++ tests/target/pattern.rs | 8 ++++++++ 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/src/patterns.rs b/src/patterns.rs index b55469f332a..1d88726d945 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -31,18 +31,31 @@ use crate::utils::{format_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident}; /// - `[small, ntp]` /// - unary tuple constructor `([small, ntp])` /// - `&[small]` -pub(crate) fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool { +pub(crate) fn is_short_pattern( + context: &RewriteContext<'_>, + pat: &ast::Pat, + pat_str: &str, +) -> bool { // We also require that the pattern is reasonably 'small' with its literal width. - pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat) + pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(context, pat) } -fn is_short_pattern_inner(pat: &ast::Pat) -> bool { - match pat.kind { - ast::PatKind::Rest - | ast::PatKind::Never - | ast::PatKind::Wild - | ast::PatKind::Err(_) - | ast::PatKind::Expr(_) => true, +fn is_short_pattern_inner(context: &RewriteContext<'_>, pat: &ast::Pat) -> bool { + match &pat.kind { + ast::PatKind::Rest | ast::PatKind::Never | ast::PatKind::Wild | ast::PatKind::Err(_) => { + true + } + ast::PatKind::Expr(expr) => match &expr.kind { + ast::ExprKind::Lit(_) => true, + ast::ExprKind::Unary(ast::UnOp::Neg, expr) => match &expr.kind { + ast::ExprKind::Lit(_) => true, + _ => unreachable!(), + }, + ast::ExprKind::ConstBlock(_) | ast::ExprKind::Path(..) => { + context.config.style_edition() <= StyleEdition::Edition2024 + } + _ => unreachable!(), + }, ast::PatKind::Ident(_, _, ref pat) => pat.is_none(), ast::PatKind::Struct(..) | ast::PatKind::MacCall(..) @@ -57,8 +70,8 @@ fn is_short_pattern_inner(pat: &ast::Pat) -> bool { ast::PatKind::Box(ref p) | PatKind::Deref(ref p) | ast::PatKind::Ref(ref p, _) - | ast::PatKind::Paren(ref p) => is_short_pattern_inner(&*p), - PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(p)), + | ast::PatKind::Paren(ref p) => is_short_pattern_inner(context, &*p), + PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(context, p)), } } @@ -96,7 +109,7 @@ impl Rewrite for Pat { let use_mixed_layout = pats .iter() .zip(pat_strs.iter()) - .all(|(pat, pat_str)| is_short_pattern(pat, pat_str)); + .all(|(pat, pat_str)| is_short_pattern(context, pat, pat_str)); let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect(); let tactic = if use_mixed_layout { DefinitiveListTactic::Mixed diff --git a/tests/source/pattern.rs b/tests/source/pattern.rs index f06d03cadf2..ed6ad690fa9 100644 --- a/tests/source/pattern.rs +++ b/tests/source/pattern.rs @@ -88,3 +88,13 @@ fn issue3728() { | c; foo((1,)); } + +fn literals() { + match 42 { + const { 1 + 2 } | 4 + | 6 => {} + 10 | 11 | 12 + | 13 | 14 => {} + _ => {} + } +} \ No newline at end of file diff --git a/tests/target/pattern.rs b/tests/target/pattern.rs index 576018ac623..e867f65929d 100644 --- a/tests/target/pattern.rs +++ b/tests/target/pattern.rs @@ -96,3 +96,11 @@ fn issue3728() { let foo = |(c,)| c; foo((1,)); } + +fn literals() { + match 42 { + const { 1 + 2 } | 4 | 6 => {} + 10 | 11 | 12 | 13 | 14 => {} + _ => {} + } +} From 31a9a27db753a815c1d812e2d3839d243250488b Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Wed, 8 Jan 2025 08:53:10 +0000 Subject: [PATCH 04/26] Only treat plain literal patterns as short --- src/patterns.rs | 37 +++++++++++++++++++++++++------------ tests/source/pattern.rs | 10 ++++++++++ tests/target/pattern.rs | 8 ++++++++ 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/src/patterns.rs b/src/patterns.rs index b55469f332a..1d88726d945 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -31,18 +31,31 @@ use crate::utils::{format_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident}; /// - `[small, ntp]` /// - unary tuple constructor `([small, ntp])` /// - `&[small]` -pub(crate) fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool { +pub(crate) fn is_short_pattern( + context: &RewriteContext<'_>, + pat: &ast::Pat, + pat_str: &str, +) -> bool { // We also require that the pattern is reasonably 'small' with its literal width. - pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat) + pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(context, pat) } -fn is_short_pattern_inner(pat: &ast::Pat) -> bool { - match pat.kind { - ast::PatKind::Rest - | ast::PatKind::Never - | ast::PatKind::Wild - | ast::PatKind::Err(_) - | ast::PatKind::Expr(_) => true, +fn is_short_pattern_inner(context: &RewriteContext<'_>, pat: &ast::Pat) -> bool { + match &pat.kind { + ast::PatKind::Rest | ast::PatKind::Never | ast::PatKind::Wild | ast::PatKind::Err(_) => { + true + } + ast::PatKind::Expr(expr) => match &expr.kind { + ast::ExprKind::Lit(_) => true, + ast::ExprKind::Unary(ast::UnOp::Neg, expr) => match &expr.kind { + ast::ExprKind::Lit(_) => true, + _ => unreachable!(), + }, + ast::ExprKind::ConstBlock(_) | ast::ExprKind::Path(..) => { + context.config.style_edition() <= StyleEdition::Edition2024 + } + _ => unreachable!(), + }, ast::PatKind::Ident(_, _, ref pat) => pat.is_none(), ast::PatKind::Struct(..) | ast::PatKind::MacCall(..) @@ -57,8 +70,8 @@ fn is_short_pattern_inner(pat: &ast::Pat) -> bool { ast::PatKind::Box(ref p) | PatKind::Deref(ref p) | ast::PatKind::Ref(ref p, _) - | ast::PatKind::Paren(ref p) => is_short_pattern_inner(&*p), - PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(p)), + | ast::PatKind::Paren(ref p) => is_short_pattern_inner(context, &*p), + PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(context, p)), } } @@ -96,7 +109,7 @@ impl Rewrite for Pat { let use_mixed_layout = pats .iter() .zip(pat_strs.iter()) - .all(|(pat, pat_str)| is_short_pattern(pat, pat_str)); + .all(|(pat, pat_str)| is_short_pattern(context, pat, pat_str)); let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect(); let tactic = if use_mixed_layout { DefinitiveListTactic::Mixed diff --git a/tests/source/pattern.rs b/tests/source/pattern.rs index f06d03cadf2..ed6ad690fa9 100644 --- a/tests/source/pattern.rs +++ b/tests/source/pattern.rs @@ -88,3 +88,13 @@ fn issue3728() { | c; foo((1,)); } + +fn literals() { + match 42 { + const { 1 + 2 } | 4 + | 6 => {} + 10 | 11 | 12 + | 13 | 14 => {} + _ => {} + } +} \ No newline at end of file diff --git a/tests/target/pattern.rs b/tests/target/pattern.rs index 576018ac623..e867f65929d 100644 --- a/tests/target/pattern.rs +++ b/tests/target/pattern.rs @@ -96,3 +96,11 @@ fn issue3728() { let foo = |(c,)| c; foo((1,)); } + +fn literals() { + match 42 { + const { 1 + 2 } | 4 | 6 => {} + 10 | 11 | 12 | 13 | 14 => {} + _ => {} + } +} From f19e82658619b53f7f1350354981830c95ea2880 Mon Sep 17 00:00:00 2001 From: "Celina G. Val" Date: Mon, 27 Jan 2025 16:30:02 -0800 Subject: [PATCH 05/26] Refactor FnKind variant to hold &Fn --- src/items.rs | 17 +++++++++-------- src/visitor.rs | 15 ++++++++++++--- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/items.rs b/src/items.rs index e7d0fba048b..457d0afe3b5 100644 --- a/src/items.rs +++ b/src/items.rs @@ -333,19 +333,19 @@ impl<'a> FnSig<'a> { defaultness: ast::Defaultness, ) -> FnSig<'a> { match *fn_kind { - visit::FnKind::Fn(visit::FnCtxt::Assoc(..), _, fn_sig, vis, generics, _) => { - let mut fn_sig = FnSig::from_method_sig(fn_sig, generics, vis); + visit::FnKind::Fn(visit::FnCtxt::Assoc(..), _, vis, ast::Fn { sig, generics, .. }) => { + let mut fn_sig = FnSig::from_method_sig(sig, generics, vis); fn_sig.defaultness = defaultness; fn_sig } - visit::FnKind::Fn(_, _, fn_sig, vis, generics, _) => FnSig { + visit::FnKind::Fn(_, _, vis, ast::Fn { sig, generics, .. }) => FnSig { decl, generics, - ext: fn_sig.header.ext, - constness: fn_sig.header.constness, - coroutine_kind: Cow::Borrowed(&fn_sig.header.coroutine_kind), + ext: sig.header.ext, + constness: sig.header.constness, + coroutine_kind: Cow::Borrowed(&sig.header.coroutine_kind), defaultness, - safety: fn_sig.header.safety, + safety: sig.header.safety, visibility: vis, }, _ => unreachable!(), @@ -3453,6 +3453,7 @@ impl Rewrite for ast::ForeignItem { ref sig, ref generics, ref body, + .. } = **fn_kind; if body.is_some() { let mut visitor = FmtVisitor::from_context(context); @@ -3461,7 +3462,7 @@ impl Rewrite for ast::ForeignItem { let inner_attrs = inner_attributes(&self.attrs); let fn_ctxt = visit::FnCtxt::Foreign; visitor.visit_fn( - visit::FnKind::Fn(fn_ctxt, &self.ident, sig, &self.vis, generics, body), + visit::FnKind::Fn(fn_ctxt, &self.ident, &self.vis, fn_kind), &sig.decl, self.span, defaultness, diff --git a/src/visitor.rs b/src/visitor.rs index 805e13b7803..bdcb619153d 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -386,7 +386,14 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let indent = self.block_indent; let block; let rewrite = match fk { - visit::FnKind::Fn(_, ident, _, _, _, Some(ref b)) => { + visit::FnKind::Fn( + _, + ident, + _, + ast::Fn { + body: Some(ref b), .. + }, + ) => { block = b; self.rewrite_fn_before_block( indent, @@ -539,6 +546,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ref sig, ref generics, ref body, + .. } = **fn_kind; if body.is_some() { let inner_attrs = inner_attributes(&item.attrs); @@ -547,7 +555,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { _ => visit::FnCtxt::Foreign, }; self.visit_fn( - visit::FnKind::Fn(fn_ctxt, &item.ident, sig, &item.vis, generics, body), + visit::FnKind::Fn(fn_ctxt, &item.ident, &item.vis, fn_kind), &sig.decl, item.span, defaultness, @@ -640,12 +648,13 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ref sig, ref generics, ref body, + .. } = **fn_kind; if body.is_some() { let inner_attrs = inner_attributes(&ai.attrs); let fn_ctxt = visit::FnCtxt::Assoc(assoc_ctxt); self.visit_fn( - visit::FnKind::Fn(fn_ctxt, &ai.ident, sig, &ai.vis, generics, body), + visit::FnKind::Fn(fn_ctxt, &ai.ident, &ai.vis, fn_kind), &sig.decl, ai.span, defaultness, From 7de0ca8b71cfeae822b4a644f41d70e184eff2b2 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 30 Jan 2025 18:24:02 +0000 Subject: [PATCH 06/26] Disable overflow_delimited_expr in edition 2024 --- src/bin/main.rs | 9 +-- src/config/mod.rs | 2 +- src/config/options.rs | 4 +- .../style_edition/overflow_delim_expr_2024.rs | 73 +++++++++++-------- 4 files changed, 51 insertions(+), 37 deletions(-) diff --git a/src/bin/main.rs b/src/bin/main.rs index 34984798ae6..28df49b9304 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -817,7 +817,6 @@ mod test { options.inline_config = HashMap::from([("version".to_owned(), "Two".to_owned())]); let config = get_config(None, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), true); } #[nightly_only_test] @@ -827,7 +826,6 @@ mod test { let config_file = Some(Path::new("tests/config/style-edition/just-version")); let config = get_config(config_file, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), true); } #[nightly_only_test] @@ -872,7 +870,6 @@ mod test { ]); let config = get_config(None, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), true); } #[nightly_only_test] @@ -938,7 +935,6 @@ mod test { options.style_edition = Some(StyleEdition::Edition2024); let config = get_config(None, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), true); } #[nightly_only_test] @@ -948,6 +944,8 @@ mod test { let config_file = Some(Path::new("tests/config/style-edition/overrides")); let config = get_config(config_file, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); + // FIXME: this test doesn't really exercise anything, since + // `overflow_delimited_expr` is disabled by default in edition 2024. assert_eq!(config.overflow_delimited_expr(), false); } @@ -959,7 +957,8 @@ mod test { options.inline_config = HashMap::from([("overflow_delimited_expr".to_owned(), "false".to_owned())]); let config = get_config(config_file, Some(options)); - assert_eq!(config.style_edition(), StyleEdition::Edition2024); + // FIXME: this test doesn't really exercise anything, since + // `overflow_delimited_expr` is disabled by default in edition 2024. assert_eq!(config.overflow_delimited_expr(), false); } } diff --git a/src/config/mod.rs b/src/config/mod.rs index 7355adc9f9d..6b63108c037 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -848,7 +848,7 @@ binop_separator = "Front" remove_nested_parens = true combine_control_expr = true short_array_element_width_threshold = 10 -overflow_delimited_expr = true +overflow_delimited_expr = false struct_field_align_threshold = 0 enum_discrim_align_threshold = 0 match_arm_blocks = true diff --git a/src/config/options.rs b/src/config/options.rs index bbc99a2dced..71865ec75ce 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -627,7 +627,7 @@ config_option_with_style_edition_default!( RemoveNestedParens, bool, _ => true; CombineControlExpr, bool, _ => true; ShortArrayElementWidthThreshold, usize, _ => 10; - OverflowDelimitedExpr, bool, Edition2024 => true, _ => false; + OverflowDelimitedExpr, bool, _ => false; StructFieldAlignThreshold, usize, _ => 0; EnumDiscrimAlignThreshold, usize, _ => 0; MatchArmBlocks, bool, _ => true; @@ -644,7 +644,7 @@ config_option_with_style_edition_default!( BlankLinesLowerBound, usize, _ => 0; EditionConfig, Edition, _ => Edition::Edition2015; StyleEditionConfig, StyleEdition, - Edition2024 => StyleEdition::Edition2024, _ => StyleEdition::Edition2015; + Edition2024 => StyleEdition::Edition2024, _ => StyleEdition::Edition2015; VersionConfig, Version, Edition2024 => Version::Two, _ => Version::One; InlineAttributeWidth, usize, _ => 0; FormatGeneratedFiles, bool, _ => true; diff --git a/tests/target/configs/style_edition/overflow_delim_expr_2024.rs b/tests/target/configs/style_edition/overflow_delim_expr_2024.rs index ecd2e8ca797..1b2d12ce320 100644 --- a/tests/target/configs/style_edition/overflow_delim_expr_2024.rs +++ b/tests/target/configs/style_edition/overflow_delim_expr_2024.rs @@ -25,10 +25,13 @@ fn combine_blocklike() { y: value2, }); - do_thing(x, Bar { - x: value, - y: value2, - }); + do_thing( + x, + Bar { + x: value, + y: value2, + }, + ); do_thing( x, @@ -46,12 +49,15 @@ fn combine_blocklike() { value4_with_longer_name, ]); - do_thing(x, &[ - value_with_longer_name, - value2_with_longer_name, - value3_with_longer_name, - value4_with_longer_name, - ]); + do_thing( + x, + &[ + value_with_longer_name, + value2_with_longer_name, + value3_with_longer_name, + value4_with_longer_name, + ], + ); do_thing( x, @@ -71,12 +77,15 @@ fn combine_blocklike() { value4_with_longer_name, ]); - do_thing(x, vec![ - value_with_longer_name, - value2_with_longer_name, - value3_with_longer_name, - value4_with_longer_name, - ]); + do_thing( + x, + vec![ + value_with_longer_name, + value2_with_longer_name, + value3_with_longer_name, + value4_with_longer_name, + ], + ); do_thing( x, @@ -99,22 +108,28 @@ fn combine_blocklike() { } fn combine_struct_sample() { - let identity = verify(&ctx, VerifyLogin { - type_: LoginType::Username, - username: args.username.clone(), - password: Some(args.password.clone()), - domain: None, - })?; + let identity = verify( + &ctx, + VerifyLogin { + type_: LoginType::Username, + username: args.username.clone(), + password: Some(args.password.clone()), + domain: None, + }, + )?; } fn combine_macro_sample() { rocket::ignite() - .mount("/", routes![ - http::auth::login, - http::auth::logout, - http::cors::options, - http::action::dance, - http::action::sleep, - ]) + .mount( + "/", + routes![ + http::auth::login, + http::auth::logout, + http::cors::options, + http::action::dance, + http::action::sleep, + ], + ) .launch(); } From 5e0549320e0cf4358f8ab3406a99d8b5fa953f8a Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sun, 2 Feb 2025 15:12:33 +0000 Subject: [PATCH 07/26] Slightly simplify DiagCtxt::make_silent --- src/parse/session.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parse/session.rs b/src/parse/session.rs index 63cc8794cea..d1a2974a617 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -121,7 +121,7 @@ fn default_dcx( let emitter: Box = if !show_parse_errors { Box::new(SilentEmitter { fallback_bundle, - fatal_dcx: DiagCtxt::new(emitter), + fatal_emitter: emitter, fatal_note: None, emit_fatal_diagnostic: false, }) From 0eadd9965197aee7f22201e92efed78c9096cf6b Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sun, 2 Feb 2025 15:36:28 +0000 Subject: [PATCH 08/26] Use fallback fluent bundle from inner emitter in SilentEmitter --- src/parse/session.rs | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/parse/session.rs b/src/parse/session.rs index d1a2974a617..34077c5f866 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -114,13 +114,12 @@ fn default_dcx( false, ); let emitter = Box::new( - HumanEmitter::new(stderr_destination(emit_color), fallback_bundle.clone()) + HumanEmitter::new(stderr_destination(emit_color), fallback_bundle) .sm(Some(source_map.clone())), ); let emitter: Box = if !show_parse_errors { Box::new(SilentEmitter { - fallback_bundle, fatal_emitter: emitter, fatal_note: None, emit_fatal_diagnostic: false, @@ -205,16 +204,7 @@ impl ParseSess { } pub(crate) fn set_silent_emitter(&mut self) { - // Ideally this invocation wouldn't be necessary and the fallback bundle in - // `self.parse_sess.dcx` could be used, but the lock in `DiagCtxt` prevents this. - // See `::fallback_fluent_bundle`. - let fallback_bundle = rustc_errors::fallback_fluent_bundle( - rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(), - false, - ); - self.raw_psess - .dcx() - .make_silent(fallback_bundle, None, false); + self.raw_psess.dcx().make_silent(None, false); } pub(crate) fn span_to_filename(&self, span: Span) -> FileName { From 58ba3608a471e4c33165c2ed18e85b014afcb1fc Mon Sep 17 00:00:00 2001 From: Askar Safin Date: Mon, 3 Feb 2025 06:44:41 +0300 Subject: [PATCH 09/26] tree-wide: parallel: Fully removed all `Lrc`, replaced with `Arc` --- src/config/file_lines.rs | 4 +- src/parse/session.rs | 97 ++++++++++++++++++++-------------------- src/source_file.rs | 7 ++- src/visitor.rs | 6 +-- 4 files changed, 57 insertions(+), 57 deletions(-) diff --git a/src/config/file_lines.rs b/src/config/file_lines.rs index c53ec6371e9..2f2a6c8d552 100644 --- a/src/config/file_lines.rs +++ b/src/config/file_lines.rs @@ -3,9 +3,9 @@ use itertools::Itertools; use std::collections::HashMap; use std::path::PathBuf; +use std::sync::Arc; use std::{cmp, fmt, iter, str}; -use rustc_data_structures::sync::Lrc; use rustc_span::SourceFile; use serde::{Deserialize, Deserializer, Serialize, Serializer, ser}; use serde_json as json; @@ -13,7 +13,7 @@ use thiserror::Error; /// A range of lines in a file, inclusive of both ends. pub struct LineRange { - pub(crate) file: Lrc, + pub(crate) file: Arc, pub(crate) lo: usize, pub(crate) hi: usize, } diff --git a/src/parse/session.rs b/src/parse/session.rs index 34077c5f866..afd847f9515 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -1,7 +1,8 @@ use std::path::Path; +use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; +use rustc_data_structures::sync::IntoDynSyncSend; use rustc_errors::emitter::{DynEmitter, Emitter, HumanEmitter, SilentEmitter, stderr_destination}; use rustc_errors::registry::Registry; use rustc_errors::translation::Translate; @@ -25,17 +26,17 @@ use crate::{Config, ErrorKind, FileName}; /// ParseSess holds structs necessary for constructing a parser. pub(crate) struct ParseSess { raw_psess: RawParseSess, - ignore_path_set: Lrc, - can_reset_errors: Lrc, + ignore_path_set: Arc, + can_reset_errors: Arc, } /// Emit errors against every files expect ones specified in the `ignore_path_set`. struct SilentOnIgnoredFilesEmitter { - ignore_path_set: IntoDynSyncSend>, - source_map: Lrc, + ignore_path_set: IntoDynSyncSend>, + source_map: Arc, emitter: Box, has_non_ignorable_parser_errors: bool, - can_reset: Lrc, + can_reset: Arc, } impl SilentOnIgnoredFilesEmitter { @@ -96,9 +97,9 @@ impl From for ColorConfig { } fn default_dcx( - source_map: Lrc, - ignore_path_set: Lrc, - can_reset: Lrc, + source_map: Arc, + ignore_path_set: Arc, + can_reset: Arc, show_parse_errors: bool, color: Color, ) -> DiagCtxt { @@ -139,16 +140,16 @@ fn default_dcx( impl ParseSess { pub(crate) fn new(config: &Config) -> Result { let ignore_path_set = match IgnorePathSet::from_ignore_list(&config.ignore()) { - Ok(ignore_path_set) => Lrc::new(ignore_path_set), + Ok(ignore_path_set) => Arc::new(ignore_path_set), Err(e) => return Err(ErrorKind::InvalidGlobPattern(e)), }; - let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let can_reset_errors = Lrc::new(AtomicBool::new(false)); + let source_map = Arc::new(SourceMap::new(FilePathMapping::empty())); + let can_reset_errors = Arc::new(AtomicBool::new(false)); let dcx = default_dcx( - Lrc::clone(&source_map), - Lrc::clone(&ignore_path_set), - Lrc::clone(&can_reset_errors), + Arc::clone(&source_map), + Arc::clone(&ignore_path_set), + Arc::clone(&can_reset_errors), config.show_parse_errors(), config.color(), ); @@ -211,7 +212,7 @@ impl ParseSess { self.raw_psess.source_map().span_to_filename(span).into() } - pub(crate) fn span_to_file_contents(&self, span: Span) -> Lrc { + pub(crate) fn span_to_file_contents(&self, span: Span) -> Arc { self.raw_psess .source_map() .lookup_source_file(span.data().lo) @@ -255,11 +256,11 @@ impl ParseSess { SnippetProvider::new( source_file.start_pos, source_file.end_position(), - Lrc::clone(source_file.src.as_ref().unwrap()), + Arc::clone(source_file.src.as_ref().unwrap()), ) } - pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option> { + pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option> { self.raw_psess .source_map() .get_source_file(&file_name.into()) @@ -331,7 +332,7 @@ mod tests { use std::sync::atomic::AtomicU32; struct TestEmitter { - num_emitted_errors: Lrc, + num_emitted_errors: Arc, } impl Translate for TestEmitter { @@ -365,15 +366,15 @@ mod tests { } fn build_emitter( - num_emitted_errors: Lrc, - can_reset: Lrc, - source_map: Option>, + num_emitted_errors: Arc, + can_reset: Arc, + source_map: Option>, ignore_list: Option, ) -> SilentOnIgnoredFilesEmitter { let emitter_writer = TestEmitter { num_emitted_errors }; let source_map = - source_map.unwrap_or_else(|| Lrc::new(SourceMap::new(FilePathMapping::empty()))); - let ignore_path_set = Lrc::new( + source_map.unwrap_or_else(|| Arc::new(SourceMap::new(FilePathMapping::empty()))); + let ignore_path_set = Arc::new( IgnorePathSet::from_ignore_list(&ignore_list.unwrap_or_default()).unwrap(), ); SilentOnIgnoredFilesEmitter { @@ -393,10 +394,10 @@ mod tests { #[test] fn handles_fatal_parse_error_in_ignored_file() { - let num_emitted_errors = Lrc::new(AtomicU32::new(0)); - let can_reset_errors = Lrc::new(AtomicBool::new(false)); + let num_emitted_errors = Arc::new(AtomicU32::new(0)); + let can_reset_errors = Arc::new(AtomicBool::new(false)); let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#); - let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); + let source_map = Arc::new(SourceMap::new(FilePathMapping::empty())); let source = String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#); source_map.new_source_file( @@ -405,9 +406,9 @@ mod tests { ); let registry = Registry::new(&[]); let mut emitter = build_emitter( - Lrc::clone(&num_emitted_errors), - Lrc::clone(&can_reset_errors), - Some(Lrc::clone(&source_map)), + Arc::clone(&num_emitted_errors), + Arc::clone(&can_reset_errors), + Some(Arc::clone(&source_map)), Some(ignore_list), ); let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1))); @@ -420,10 +421,10 @@ mod tests { #[nightly_only_test] #[test] fn handles_recoverable_parse_error_in_ignored_file() { - let num_emitted_errors = Lrc::new(AtomicU32::new(0)); - let can_reset_errors = Lrc::new(AtomicBool::new(false)); + let num_emitted_errors = Arc::new(AtomicU32::new(0)); + let can_reset_errors = Arc::new(AtomicBool::new(false)); let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#); - let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); + let source_map = Arc::new(SourceMap::new(FilePathMapping::empty())); let source = String::from(r#"pub fn bar() { 1x; }"#); source_map.new_source_file( SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))), @@ -431,9 +432,9 @@ mod tests { ); let registry = Registry::new(&[]); let mut emitter = build_emitter( - Lrc::clone(&num_emitted_errors), - Lrc::clone(&can_reset_errors), - Some(Lrc::clone(&source_map)), + Arc::clone(&num_emitted_errors), + Arc::clone(&can_reset_errors), + Some(Arc::clone(&source_map)), Some(ignore_list), ); let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1))); @@ -446,9 +447,9 @@ mod tests { #[nightly_only_test] #[test] fn handles_recoverable_parse_error_in_non_ignored_file() { - let num_emitted_errors = Lrc::new(AtomicU32::new(0)); - let can_reset_errors = Lrc::new(AtomicBool::new(false)); - let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); + let num_emitted_errors = Arc::new(AtomicU32::new(0)); + let can_reset_errors = Arc::new(AtomicBool::new(false)); + let source_map = Arc::new(SourceMap::new(FilePathMapping::empty())); let source = String::from(r#"pub fn bar() { 1x; }"#); source_map.new_source_file( SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))), @@ -456,9 +457,9 @@ mod tests { ); let registry = Registry::new(&[]); let mut emitter = build_emitter( - Lrc::clone(&num_emitted_errors), - Lrc::clone(&can_reset_errors), - Some(Lrc::clone(&source_map)), + Arc::clone(&num_emitted_errors), + Arc::clone(&can_reset_errors), + Some(Arc::clone(&source_map)), None, ); let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1))); @@ -471,9 +472,9 @@ mod tests { #[nightly_only_test] #[test] fn handles_mix_of_recoverable_parse_error() { - let num_emitted_errors = Lrc::new(AtomicU32::new(0)); - let can_reset_errors = Lrc::new(AtomicBool::new(false)); - let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); + let num_emitted_errors = Arc::new(AtomicU32::new(0)); + let can_reset_errors = Arc::new(AtomicBool::new(false)); + let source_map = Arc::new(SourceMap::new(FilePathMapping::empty())); let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#); let bar_source = String::from(r#"pub fn bar() { 1x; }"#); let foo_source = String::from(r#"pub fn foo() { 1x; }"#); @@ -493,9 +494,9 @@ mod tests { ); let registry = Registry::new(&[]); let mut emitter = build_emitter( - Lrc::clone(&num_emitted_errors), - Lrc::clone(&can_reset_errors), - Some(Lrc::clone(&source_map)), + Arc::clone(&num_emitted_errors), + Arc::clone(&can_reset_errors), + Some(Arc::clone(&source_map)), Some(ignore_list), ); let bar_span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1))); diff --git a/src/source_file.rs b/src/source_file.rs index 73f8ecb5529..e942058a0a8 100644 --- a/src/source_file.rs +++ b/src/source_file.rs @@ -1,6 +1,7 @@ use std::fs; use std::io::{self, Write}; use std::path::Path; +use std::sync::Arc; use crate::NewlineStyle; use crate::config::FileName; @@ -14,8 +15,6 @@ use crate::create_emitter; #[cfg(test)] use crate::formatting::FileRecord; -use rustc_data_structures::sync::Lrc; - // Append a newline to the end of each file. pub(crate) fn append_newline(s: &mut String) { s.push('\n'); @@ -88,11 +87,11 @@ where // source map instead of hitting the file system. This also supports getting // original text for `FileName::Stdin`. let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin { - Lrc::new(fs::read_to_string(ensure_real_path(filename))?) + Arc::new(fs::read_to_string(ensure_real_path(filename))?) } else { match psess.and_then(|psess| psess.get_original_snippet(filename)) { Some(ori) => ori, - None => Lrc::new(fs::read_to_string(ensure_real_path(filename))?), + None => Arc::new(fs::read_to_string(ensure_real_path(filename))?), } }; diff --git a/src/visitor.rs b/src/visitor.rs index bdcb619153d..a5cfc542a17 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -1,8 +1,8 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; use rustc_ast::{ast, token::Delimiter, visit}; -use rustc_data_structures::sync::Lrc; use rustc_span::{BytePos, Pos, Span, symbol}; use tracing::debug; @@ -32,7 +32,7 @@ use crate::{ErrorKind, FormatReport, FormattingError}; /// Creates a string slice corresponding to the specified span. pub(crate) struct SnippetProvider { /// A pointer to the content of the file we are formatting. - big_snippet: Lrc, + big_snippet: Arc, /// A position of the start of `big_snippet`, used as an offset. start_pos: usize, /// An end position of the file that this snippet lives. @@ -46,7 +46,7 @@ impl SnippetProvider { Some(&self.big_snippet[start_index..end_index]) } - pub(crate) fn new(start_pos: BytePos, end_pos: BytePos, big_snippet: Lrc) -> Self { + pub(crate) fn new(start_pos: BytePos, end_pos: BytePos, big_snippet: Arc) -> Self { let start_pos = start_pos.to_usize(); let end_pos = end_pos.to_usize(); SnippetProvider { From 35f979905989bc077c5cd1acbd7e80b6ecb6cd92 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Thu, 6 Feb 2025 13:48:12 +0000 Subject: [PATCH 10/26] Add a TyPat in the AST to reuse the generic arg lowering logic --- src/patterns.rs | 87 ++++++++++++++++++++++++++++--------------------- src/spanned.rs | 2 +- src/types.rs | 16 +++++++++ 3 files changed, 66 insertions(+), 39 deletions(-) diff --git a/src/patterns.rs b/src/patterns.rs index 1d88726d945..bafed41e39f 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -75,12 +75,12 @@ fn is_short_pattern_inner(context: &RewriteContext<'_>, pat: &ast::Pat) -> bool } } -pub(crate) struct RangeOperand<'a> { - operand: &'a Option>, - pub(crate) span: Span, +pub(crate) struct RangeOperand<'a, T> { + pub operand: &'a Option>, + pub span: Span, } -impl<'a> Rewrite for RangeOperand<'a> { +impl<'a, T: Rewrite> Rewrite for RangeOperand<'a, T> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.rewrite_result(context, shape).ok() } @@ -259,40 +259,7 @@ impl Rewrite for Pat { } PatKind::Never => Err(RewriteError::Unknown), PatKind::Range(ref lhs, ref rhs, ref end_kind) => { - let infix = match end_kind.node { - RangeEnd::Included(RangeSyntax::DotDotDot) => "...", - RangeEnd::Included(RangeSyntax::DotDotEq) => "..=", - RangeEnd::Excluded => "..", - }; - let infix = if context.config.spaces_around_ranges() { - let lhs_spacing = match lhs { - None => "", - Some(_) => " ", - }; - let rhs_spacing = match rhs { - None => "", - Some(_) => " ", - }; - format!("{lhs_spacing}{infix}{rhs_spacing}") - } else { - infix.to_owned() - }; - let lspan = self.span.with_hi(end_kind.span.lo()); - let rspan = self.span.with_lo(end_kind.span.hi()); - rewrite_pair( - &RangeOperand { - operand: lhs, - span: lspan, - }, - &RangeOperand { - operand: rhs, - span: rspan, - }, - PairParts::infix(&infix), - context, - shape, - SeparatorPlace::Front, - ) + rewrite_range_pat(context, shape, lhs, rhs, end_kind, self.span) } PatKind::Ref(ref pat, mutability) => { let prefix = format!("&{}", format_mutability(mutability)); @@ -359,6 +326,50 @@ impl Rewrite for Pat { } } +pub fn rewrite_range_pat( + context: &RewriteContext<'_>, + shape: Shape, + lhs: &Option>, + rhs: &Option>, + end_kind: &rustc_span::source_map::Spanned, + span: Span, +) -> RewriteResult { + let infix = match end_kind.node { + RangeEnd::Included(RangeSyntax::DotDotDot) => "...", + RangeEnd::Included(RangeSyntax::DotDotEq) => "..=", + RangeEnd::Excluded => "..", + }; + let infix = if context.config.spaces_around_ranges() { + let lhs_spacing = match lhs { + None => "", + Some(_) => " ", + }; + let rhs_spacing = match rhs { + None => "", + Some(_) => " ", + }; + format!("{lhs_spacing}{infix}{rhs_spacing}") + } else { + infix.to_owned() + }; + let lspan = span.with_hi(end_kind.span.lo()); + let rspan = span.with_lo(end_kind.span.hi()); + rewrite_pair( + &RangeOperand { + operand: lhs, + span: lspan, + }, + &RangeOperand { + operand: rhs, + span: rspan, + }, + PairParts::infix(&infix), + context, + shape, + SeparatorPlace::Front, + ) +} + fn rewrite_struct_pat( qself: &Option>, path: &ast::Path, diff --git a/src/spanned.rs b/src/spanned.rs index 6b3e40b9115..e93eb53cd87 100644 --- a/src/spanned.rs +++ b/src/spanned.rs @@ -211,7 +211,7 @@ impl Spanned for ast::PreciseCapturingArg { } } -impl<'a> Spanned for RangeOperand<'a> { +impl<'a, T> Spanned for RangeOperand<'a, T> { fn span(&self) -> Span { self.span } diff --git a/src/types.rs b/src/types.rs index f8b713117f4..0009490e86f 100644 --- a/src/types.rs +++ b/src/types.rs @@ -18,6 +18,7 @@ use crate::lists::{ use crate::macros::{MacroPosition, rewrite_macro}; use crate::overflow; use crate::pairs::{PairParts, rewrite_pair}; +use crate::patterns::rewrite_range_pat; use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult}; use crate::shape::Shape; use crate::source_map::SpanUtils; @@ -1045,6 +1046,21 @@ impl Rewrite for ast::Ty { } } +impl Rewrite for ast::TyPat { + fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { + self.rewrite_result(context, shape).ok() + } + + fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { + match self.kind { + ast::TyPatKind::Range(ref lhs, ref rhs, ref end_kind) => { + rewrite_range_pat(context, shape, lhs, rhs, end_kind, self.span) + } + ast::TyPatKind::Err(_) => Err(RewriteError::Unknown), + } + } +} + fn rewrite_bare_fn( bare_fn: &ast::BareFnTy, span: Span, From 6dcc68f7e2f544fd80a0678dce8e045797b44364 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 28 Feb 2025 02:59:37 +0000 Subject: [PATCH 11/26] Do not yeet unsafe<> from type --- src/types.rs | 6 +++++- tests/source/unsafe-binders.rs | 3 +++ tests/target/unsafe-binders.rs | 2 ++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/types.rs b/src/types.rs index 0009490e86f..7b44b47c719 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1019,7 +1019,11 @@ impl Rewrite for ast::Ty { } ast::TyKind::UnsafeBinder(ref binder) => { let mut result = String::new(); - if let Some(ref lifetime_str) = + if binder.generic_params.is_empty() { + // We always want to write `unsafe<>` since `unsafe<> Ty` + // and `Ty` are distinct types. + result.push_str("unsafe<> ") + } else if let Some(ref lifetime_str) = rewrite_bound_params(context, shape, &binder.generic_params) { result.push_str("unsafe<"); diff --git a/tests/source/unsafe-binders.rs b/tests/source/unsafe-binders.rs index ccf7c8bb9af..2f43af54d20 100644 --- a/tests/source/unsafe-binders.rs +++ b/tests/source/unsafe-binders.rs @@ -9,3 +9,6 @@ struct Foo { struct Bar(unsafe<'a> &'a ()); impl Trait for unsafe<'a> &'a () {} + +fn empty() +-> unsafe<> () {} diff --git a/tests/target/unsafe-binders.rs b/tests/target/unsafe-binders.rs index 9d308f4a894..d52dc559519 100644 --- a/tests/target/unsafe-binders.rs +++ b/tests/target/unsafe-binders.rs @@ -7,3 +7,5 @@ struct Foo { struct Bar(unsafe<'a> &'a ()); impl Trait for unsafe<'a> &'a () {} + +fn empty() -> unsafe<> () {} From 326e3212e6391c6b269c1b76df8e092ff82c0fb5 Mon Sep 17 00:00:00 2001 From: Frank King Date: Wed, 5 Feb 2025 18:58:29 +0800 Subject: [PATCH 12/26] Implment `#[cfg]` and `#[cfg_attr]` in `where` clauses --- src/spanned.rs | 7 +- src/types.rs | 35 +++++++- tests/target/cfg_attribute_in_where.rs | 116 +++++++++++++++++++++++++ 3 files changed, 151 insertions(+), 7 deletions(-) create mode 100644 tests/target/cfg_attribute_in_where.rs diff --git a/src/spanned.rs b/src/spanned.rs index e93eb53cd87..507647566d4 100644 --- a/src/spanned.rs +++ b/src/spanned.rs @@ -58,6 +58,7 @@ implement_spanned!(ast::ExprField); implement_spanned!(ast::ForeignItem); implement_spanned!(ast::Item); implement_spanned!(ast::Local); +implement_spanned!(ast::WherePredicate); impl Spanned for ast::Stmt { fn span(&self) -> Span { @@ -149,12 +150,6 @@ impl Spanned for ast::FieldDef { } } -impl Spanned for ast::WherePredicate { - fn span(&self) -> Span { - self.span - } -} - impl Spanned for ast::FnRetTy { fn span(&self) -> Span { match *self { diff --git a/src/types.rs b/src/types.rs index 0009490e86f..281be957819 100644 --- a/src/types.rs +++ b/src/types.rs @@ -463,8 +463,9 @@ impl Rewrite for ast::WherePredicate { } fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { + let attrs_str = self.attrs.rewrite_result(context, shape)?; // FIXME: dead spans? - let result = match self.kind { + let pred_str = &match self.kind { ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate { ref bound_generic_params, ref bounded_ty, @@ -499,6 +500,38 @@ impl Rewrite for ast::WherePredicate { } }; + let mut result = String::with_capacity(attrs_str.len() + pred_str.len() + 1); + result.push_str(&attrs_str); + let pred_start = self.span.lo(); + let line_len = last_line_width(&attrs_str) + 1 + first_line_width(&pred_str); + if let Some(last_attr) = self.attrs.last().filter(|last_attr| { + contains_comment(context.snippet(mk_sp(last_attr.span.hi(), pred_start))) + }) { + result = combine_strs_with_missing_comments( + context, + &result, + &pred_str, + mk_sp(last_attr.span.hi(), pred_start), + Shape { + width: shape.width.min(context.config.inline_attribute_width()), + ..shape + }, + !last_attr.is_doc_comment(), + )?; + } else { + if !self.attrs.is_empty() { + if context.config.inline_attribute_width() < line_len + || self.attrs.len() > 1 + || self.attrs.last().is_some_and(|a| a.is_doc_comment()) + { + result.push_str(&shape.indent.to_string_with_newline(context.config)); + } else { + result.push(' '); + } + } + result.push_str(&pred_str); + } + Ok(result) } } diff --git a/tests/target/cfg_attribute_in_where.rs b/tests/target/cfg_attribute_in_where.rs new file mode 100644 index 00000000000..11f495b1629 --- /dev/null +++ b/tests/target/cfg_attribute_in_where.rs @@ -0,0 +1,116 @@ +// rustfmt-inline_attribute_width: 40 + +#![crate_type = "lib"] +#![feature(cfg_attribute_in_where)] +use std::marker::PhantomData; + +#[cfg(a)] +trait TraitA {} + +#[cfg(b)] +trait TraitB {} + +trait A +where + #[cfg = a_very_long_attribute_name] + T: TraitA, + #[cfg = another_very_long_attribute_name] + T: TraitB, +{ + type B + where + #[cfg = a] + // line comment after the attribute + U: TraitA, + #[cfg = b] + /* block comment after the attribute */ + U: TraitB, + #[cfg = a] // short + U: TraitA, + #[cfg = b] /* short */ U: TraitB; + + fn foo(&self) + where + /// line doc comment before the attribute + U: TraitA, + /** line doc block comment before the attribute */ + U: TraitB; +} + +impl A for T +where + #[doc = "line doc before the attribute"] + T: TraitA, + /** short doc */ + T: TraitB, +{ + type B + = () + where + #[doc = "short"] U: TraitA, + #[doc = "short"] + #[cfg = a] + U: TraitB; + + fn foo(&self) + where + #[cfg = a] + #[cfg = b] + U: TraitA, + /// line doc + #[cfg = c] + U: TraitB, + { + } +} + +struct C +where + #[cfg = a] T: TraitA, + #[cfg = b] T: TraitB, +{ + _t: PhantomData, +} + +union D +where + #[cfg = a] T: TraitA, + #[cfg = b] T: TraitB, +{ + _t: PhantomData, +} + +enum E +where + #[cfg = a] T: TraitA, + #[cfg = b] T: TraitB, +{ + E(PhantomData), +} + +#[allow(type_alias_bounds)] +type F +where + #[cfg = a] T: TraitA, + #[cfg = b] T: TraitB, += T; + +impl C +where + #[cfg = a] T: TraitA, + #[cfg = b] T: TraitB, +{ + fn new() + where + #[cfg = a] U: TraitA, + #[cfg = b] U: TraitB, + { + } +} + +fn foo() +where + #[cfg = a] T: TraitA, + #[cfg = b] T: TraitB, +{ +} From 7be7efabbb889e4d8937ae2cd8f087f8d4dbd92e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 20 Dec 2024 07:28:16 +1100 Subject: [PATCH 13/26] Replace `ast::TokenKind::BinOp{,Eq}` and remove `BinOpToken`. `BinOpToken` is badly named, because it only covers the assignable binary ops and excludes comparisons and `&&`/`||`. Its use in `ast::TokenKind` does allow a small amount of code sharing, but it's a clumsy factoring. This commit removes `ast::TokenKind::BinOp{,Eq}`, replacing each one with 10 individual variants. This makes `ast::TokenKind` more similar to `rustc_lexer::TokenKind`, which has individual variants for all operators. Although the number of lines of code increases, the number of chars decreases due to the frequent use of shorter names like `token::Plus` instead of `token::BinOp(BinOpToken::Plus)`. --- src/macros.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/macros.rs b/src/macros.rs index ea8ca38cb77..7775db2db6b 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::panic::{AssertUnwindSafe, catch_unwind}; -use rustc_ast::token::{BinOpToken, Delimiter, Token, TokenKind}; +use rustc_ast::token::{Delimiter, Token, TokenKind}; use rustc_ast::tokenstream::{TokenStream, TokenStreamIter, TokenTree}; use rustc_ast::{ast, ptr}; use rustc_ast_pretty::pprust; @@ -841,7 +841,7 @@ impl MacroArgParser { match tok { TokenTree::Token( Token { - kind: TokenKind::BinOp(BinOpToken::Plus), + kind: TokenKind::Plus, .. }, _, @@ -855,7 +855,7 @@ impl MacroArgParser { ) | TokenTree::Token( Token { - kind: TokenKind::BinOp(BinOpToken::Star), + kind: TokenKind::Star, .. }, _, @@ -1090,12 +1090,30 @@ fn force_space_before(tok: &TokenKind) -> bool { | TokenKind::OrOr | TokenKind::Not | TokenKind::Tilde - | TokenKind::BinOpEq(_) + | TokenKind::PlusEq + | TokenKind::MinusEq + | TokenKind::StarEq + | TokenKind::SlashEq + | TokenKind::PercentEq + | TokenKind::CaretEq + | TokenKind::AndEq + | TokenKind::OrEq + | TokenKind::ShlEq + | TokenKind::ShrEq | TokenKind::At | TokenKind::RArrow | TokenKind::LArrow | TokenKind::FatArrow - | TokenKind::BinOp(_) + | TokenKind::Plus + | TokenKind::Minus + | TokenKind::Star + | TokenKind::Slash + | TokenKind::Percent + | TokenKind::Caret + | TokenKind::And + | TokenKind::Or + | TokenKind::Shl + | TokenKind::Shr | TokenKind::Pound | TokenKind::Dollar => true, _ => false, @@ -1114,7 +1132,7 @@ fn next_space(tok: &TokenKind) -> SpaceState { match tok { TokenKind::Not - | TokenKind::BinOp(BinOpToken::And) + | TokenKind::And | TokenKind::Tilde | TokenKind::At | TokenKind::Comma From 88e23c95ddcfc8adc46c747b44e805e4045d32ec Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 20 Dec 2024 14:04:25 +1100 Subject: [PATCH 14/26] Rename `ast::TokenKind::Not` as `ast::TokenKind::Bang`. For consistency with `rustc_lexer::TokenKind::Bang`, and because other `ast::TokenKind` variants generally have syntactic names instead of semantic names (e.g. `Star` and `DotDot` instead of `Mul` and `Range`). --- src/macros.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/macros.rs b/src/macros.rs index 7775db2db6b..664c90b991a 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -1088,7 +1088,7 @@ fn force_space_before(tok: &TokenKind) -> bool { | TokenKind::Gt | TokenKind::AndAnd | TokenKind::OrOr - | TokenKind::Not + | TokenKind::Bang | TokenKind::Tilde | TokenKind::PlusEq | TokenKind::MinusEq @@ -1131,7 +1131,7 @@ fn next_space(tok: &TokenKind) -> SpaceState { debug!("next_space: {:?}", tok); match tok { - TokenKind::Not + TokenKind::Bang | TokenKind::And | TokenKind::Tilde | TokenKind::At From 0ae83402333144cddcbdc27964afe261c42632cf Mon Sep 17 00:00:00 2001 From: Frank King Date: Sun, 19 Jan 2025 23:30:58 +0800 Subject: [PATCH 15/26] Implement `&pin const self` and `&pin mut self` sugars --- src/items.rs | 27 +++++++++++++++++++++++++++ tests/source/pin_sugar.rs | 10 ++++++++++ tests/target/pin_sugar.rs | 9 +++++++++ 3 files changed, 46 insertions(+) diff --git a/src/items.rs b/src/items.rs index 457d0afe3b5..e9e7c4ed8f9 100644 --- a/src/items.rs +++ b/src/items.rs @@ -2395,6 +2395,33 @@ fn rewrite_explicit_self( )?), } } + ast::SelfKind::Pinned(lt, m) => { + let mut_str = m.ptr_str(); + match lt { + Some(ref l) => { + let lifetime_str = l.rewrite_result( + context, + Shape::legacy(context.config.max_width(), Indent::empty()), + )?; + Ok(combine_strs_with_missing_comments( + context, + param_attrs, + &format!("&{lifetime_str} pin {mut_str} self"), + span, + shape, + !has_multiple_attr_lines, + )?) + } + None => Ok(combine_strs_with_missing_comments( + context, + param_attrs, + &format!("&pin {mut_str} self"), + span, + shape, + !has_multiple_attr_lines, + )?), + } + } ast::SelfKind::Explicit(ref ty, mutability) => { let type_str = ty.rewrite_result( context, diff --git a/tests/source/pin_sugar.rs b/tests/source/pin_sugar.rs index 0eb3c0770c4..370dfbc196a 100644 --- a/tests/source/pin_sugar.rs +++ b/tests/source/pin_sugar.rs @@ -8,3 +8,13 @@ fn g<'a>(x: & 'a pin const i32) {} fn h<'a>(x: & 'a pin mut i32) {} fn i(x: &pin mut i32) {} + +struct Foo; + +impl Foo { + fn f(&pin const self) {} + fn g<'a>(& 'a pin const self) {} + fn h<'a>(& 'a pin +mut self) {} + fn i(&pin mut self) {} +} diff --git a/tests/target/pin_sugar.rs b/tests/target/pin_sugar.rs index c9fa883e238..7d04efb1b32 100644 --- a/tests/target/pin_sugar.rs +++ b/tests/target/pin_sugar.rs @@ -7,3 +7,12 @@ fn f(x: &pin const i32) {} fn g<'a>(x: &'a pin const i32) {} fn h<'a>(x: &'a pin mut i32) {} fn i(x: &pin mut i32) {} + +struct Foo; + +impl Foo { + fn f(&pin const self) {} + fn g<'a>(&'a pin const self) {} + fn h<'a>(&'a pin mut self) {} + fn i(&pin mut self) {} +} From facc42a32ec8dee76166d07740c1b75052809661 Mon Sep 17 00:00:00 2001 From: Frank King Date: Wed, 5 Mar 2025 22:35:50 +0800 Subject: [PATCH 16/26] Simplify `rewrite_explicit_self` --- src/items.rs | 98 +++++++++++++++++----------------------------------- 1 file changed, 31 insertions(+), 67 deletions(-) diff --git a/src/items.rs b/src/items.rs index e9e7c4ed8f9..3fb3284e3d7 100644 --- a/src/items.rs +++ b/src/items.rs @@ -2359,6 +2359,21 @@ impl Rewrite for ast::Param { } } +fn rewrite_opt_lifetime( + context: &RewriteContext<'_>, + lifetime: Option, +) -> RewriteResult { + let Some(l) = lifetime else { + return Ok(String::new()); + }; + let mut result = l.rewrite_result( + context, + Shape::legacy(context.config.max_width(), Indent::empty()), + )?; + result.push(' '); + Ok(result) +} + fn rewrite_explicit_self( context: &RewriteContext<'_>, explicit_self: &ast::ExplicitSelf, @@ -2367,85 +2382,34 @@ fn rewrite_explicit_self( shape: Shape, has_multiple_attr_lines: bool, ) -> RewriteResult { - match explicit_self.node { + let self_str = match explicit_self.node { ast::SelfKind::Region(lt, m) => { let mut_str = format_mutability(m); - match lt { - Some(ref l) => { - let lifetime_str = l.rewrite_result( - context, - Shape::legacy(context.config.max_width(), Indent::empty()), - )?; - Ok(combine_strs_with_missing_comments( - context, - param_attrs, - &format!("&{lifetime_str} {mut_str}self"), - span, - shape, - !has_multiple_attr_lines, - )?) - } - None => Ok(combine_strs_with_missing_comments( - context, - param_attrs, - &format!("&{mut_str}self"), - span, - shape, - !has_multiple_attr_lines, - )?), - } + let lifetime_str = rewrite_opt_lifetime(context, lt)?; + format!("&{lifetime_str}{mut_str}self") } ast::SelfKind::Pinned(lt, m) => { let mut_str = m.ptr_str(); - match lt { - Some(ref l) => { - let lifetime_str = l.rewrite_result( - context, - Shape::legacy(context.config.max_width(), Indent::empty()), - )?; - Ok(combine_strs_with_missing_comments( - context, - param_attrs, - &format!("&{lifetime_str} pin {mut_str} self"), - span, - shape, - !has_multiple_attr_lines, - )?) - } - None => Ok(combine_strs_with_missing_comments( - context, - param_attrs, - &format!("&pin {mut_str} self"), - span, - shape, - !has_multiple_attr_lines, - )?), - } + let lifetime_str = rewrite_opt_lifetime(context, lt)?; + format!("&{lifetime_str}pin {mut_str} self") } ast::SelfKind::Explicit(ref ty, mutability) => { let type_str = ty.rewrite_result( context, Shape::legacy(context.config.max_width(), Indent::empty()), )?; - - Ok(combine_strs_with_missing_comments( - context, - param_attrs, - &format!("{}self: {}", format_mutability(mutability), type_str), - span, - shape, - !has_multiple_attr_lines, - )?) + format!("{}self: {}", format_mutability(mutability), type_str) } - ast::SelfKind::Value(mutability) => Ok(combine_strs_with_missing_comments( - context, - param_attrs, - &format!("{}self", format_mutability(mutability)), - span, - shape, - !has_multiple_attr_lines, - )?), - } + ast::SelfKind::Value(mutability) => format!("{}self", format_mutability(mutability)), + }; + Ok(combine_strs_with_missing_comments( + context, + param_attrs, + &self_str, + span, + shape, + !has_multiple_attr_lines, + )?) } pub(crate) fn span_lo_for_param(param: &ast::Param) -> BytePos { From ebd63721cbdff20f235d8d773c1d99f9c3e74f2b Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 27 Dec 2024 01:43:49 -0300 Subject: [PATCH 17/26] Fix rustfmt --- src/expr.rs | 4 ++++ src/utils.rs | 1 + 2 files changed, 5 insertions(+) diff --git a/src/expr.rs b/src/expr.rs index 16b7e7aa709..eff2d2e3ff4 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -137,6 +137,10 @@ pub(crate) fn format_expr( ast::ExprKind::Tup(ref items) => { rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1) } + ast::ExprKind::Use(_, _) => { + // FIXME: properly implement this + Ok(context.snippet(expr.span()).to_owned()) + } ast::ExprKind::Let(ref pat, ref expr, _span, _) => rewrite_let(context, shape, pat, expr), ast::ExprKind::If(..) | ast::ExprKind::ForLoop { .. } diff --git a/src/utils.rs b/src/utils.rs index ba4a4c045f1..fe716c18638 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -513,6 +513,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Become(..) | ast::ExprKind::Yeet(..) | ast::ExprKind::Tup(..) + | ast::ExprKind::Use(..) | ast::ExprKind::Type(..) | ast::ExprKind::Yield(None) | ast::ExprKind::Underscore => false, From d038fb8fe3982b4b9ad02c1b84bce5a6afe27af5 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Wed, 12 Mar 2025 16:27:52 -0700 Subject: [PATCH 18/26] Preserve yield position during pretty printing --- src/utils.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils.rs b/src/utils.rs index fe716c18638..bee39153229 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -485,7 +485,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Index(_, ref expr, _) | ast::ExprKind::Unary(_, ref expr) | ast::ExprKind::Try(ref expr) - | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr), + | ast::ExprKind::Yield(Some(ref expr), _) => is_block_expr(context, expr, repr), ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr), // This can only be a string lit ast::ExprKind::Lit(_) => { @@ -515,7 +515,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Tup(..) | ast::ExprKind::Use(..) | ast::ExprKind::Type(..) - | ast::ExprKind::Yield(None) + | ast::ExprKind::Yield(None, _) | ast::ExprKind::Underscore => false, } } From e3776329ff1f94e2ba3b19a30e0a92e773c224c1 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Thu, 13 Mar 2025 14:36:02 -0700 Subject: [PATCH 19/26] Teach rustfmt to handle postfix yield --- src/expr.rs | 5 +++-- tests/source/postfix-yield.rs | 15 +++++++++++++++ tests/target/postfix-yield.rs | 12 ++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 tests/source/postfix-yield.rs create mode 100644 tests/target/postfix-yield.rs diff --git a/src/expr.rs b/src/expr.rs index eff2d2e3ff4..92c1ffa6076 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -221,7 +221,7 @@ pub(crate) fn format_expr( Ok(format!("break{id_str}")) } } - ast::ExprKind::Yield(ref opt_expr) => { + ast::ExprKind::Yield(ref opt_expr, ast::YieldKind::Prefix) => { if let Some(ref expr) = *opt_expr { rewrite_unary_prefix(context, "yield ", &**expr, shape) } else { @@ -243,7 +243,8 @@ pub(crate) fn format_expr( ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) - | ast::ExprKind::Await(_, _) => rewrite_chain(expr, context, shape), + | ast::ExprKind::Await(_, _) + | ast::ExprKind::Yield(_, ast::YieldKind::Postfix) => rewrite_chain(expr, context, shape), ast::ExprKind::MacCall(ref mac) => { rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|_| { wrap_str( diff --git a/tests/source/postfix-yield.rs b/tests/source/postfix-yield.rs new file mode 100644 index 00000000000..8a8958f3ad4 --- /dev/null +++ b/tests/source/postfix-yield.rs @@ -0,0 +1,15 @@ +// This demonstrates a proposed alternate or additional option of having yield in postfix position. +//@ edition: 2024 + +#![feature(gen_blocks, coroutines, coroutine_trait, yield_expr)] + +use std::ops::{Coroutine, CoroutineState}; +use std::pin::pin; + +fn main() { + let mut coro = + pin!(#[coroutine] |_: i32| { let x = 1.yield; + + + (x + 2).yield; }); +} diff --git a/tests/target/postfix-yield.rs b/tests/target/postfix-yield.rs new file mode 100644 index 00000000000..7e94e1e095a --- /dev/null +++ b/tests/target/postfix-yield.rs @@ -0,0 +1,12 @@ +// This demonstrates a proposed alternate or additional option of having yield in postfix position. +//@ edition: 2024 + +#![feature(gen_blocks, coroutines, coroutine_trait, yield_expr)] + +use std::ops::{Coroutine, CoroutineState}; +use std::pin::pin; + +fn main() { + let mut coro = + pin!(#[coroutine] |_: i32| { let x = 1.yield; (x + 2).yield; }); +} From 96f68d138f307eb763b177bbf83fe90712b0bf60 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Mon, 17 Mar 2025 17:32:11 -0700 Subject: [PATCH 20/26] Teach rustfmt to handle postfix yield This involved fixing the span when parsing .yield --- src/chains.rs | 10 +++++++++- src/utils.rs | 8 +++++--- tests/source/postfix-yield.rs | 15 --------------- tests/target/postfix-yield.rs | 9 +++++++-- 4 files changed, 21 insertions(+), 21 deletions(-) delete mode 100644 tests/source/postfix-yield.rs diff --git a/src/chains.rs b/src/chains.rs index fd2ef9cb1db..fabb4400553 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -192,6 +192,7 @@ enum ChainItemKind { StructField(symbol::Ident), TupleField(symbol::Ident, bool), Await, + Yield, Comment(String, CommentPosition), } @@ -203,6 +204,7 @@ impl ChainItemKind { | ChainItemKind::StructField(..) | ChainItemKind::TupleField(..) | ChainItemKind::Await + | ChainItemKind::Yield | ChainItemKind::Comment(..) => false, } } @@ -257,6 +259,10 @@ impl ChainItemKind { let span = mk_sp(nested.span.hi(), expr.span.hi()); (ChainItemKind::Await, span) } + ast::ExprKind::Yield(Some(ref nested), ast::YieldKind::Postfix) => { + let span = mk_sp(nested.span.hi(), expr.span.hi()); + (ChainItemKind::Yield, span) + } _ => { return ( ChainItemKind::Parent { @@ -306,6 +312,7 @@ impl Rewrite for ChainItem { rewrite_ident(context, ident) ), ChainItemKind::Await => ".await".to_owned(), + ChainItemKind::Yield => ".yield".to_owned(), ChainItemKind::Comment(ref comment, _) => { rewrite_comment(comment, false, shape, context.config)? } @@ -508,7 +515,8 @@ impl Chain { }), ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) - | ast::ExprKind::Await(ref subexpr, _) => Some(SubExpr { + | ast::ExprKind::Await(ref subexpr, _) + | ast::ExprKind::Yield(Some(ref subexpr), ast::YieldKind::Postfix) => Some(SubExpr { expr: Self::convert_try(subexpr, context), is_method_call_receiver: false, }), diff --git a/src/utils.rs b/src/utils.rs index bee39153229..1811752c3c4 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -4,7 +4,7 @@ use rustc_ast::ast::{ self, Attribute, MetaItem, MetaItemInner, MetaItemKind, NodeId, Path, Visibility, VisibilityKind, }; -use rustc_ast::ptr; +use rustc_ast::{YieldKind, ptr}; use rustc_ast_pretty::pprust; use rustc_span::{BytePos, LocalExpnId, Span, Symbol, SyntaxContext, sym, symbol}; use unicode_width::UnicodeWidthStr; @@ -485,7 +485,9 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Index(_, ref expr, _) | ast::ExprKind::Unary(_, ref expr) | ast::ExprKind::Try(ref expr) - | ast::ExprKind::Yield(Some(ref expr), _) => is_block_expr(context, expr, repr), + | ast::ExprKind::Yield(Some(ref expr), YieldKind::Prefix) => { + is_block_expr(context, expr, repr) + } ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr), // This can only be a string lit ast::ExprKind::Lit(_) => { @@ -515,7 +517,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Tup(..) | ast::ExprKind::Use(..) | ast::ExprKind::Type(..) - | ast::ExprKind::Yield(None, _) + | ast::ExprKind::Yield(_, _) | ast::ExprKind::Underscore => false, } } diff --git a/tests/source/postfix-yield.rs b/tests/source/postfix-yield.rs deleted file mode 100644 index 8a8958f3ad4..00000000000 --- a/tests/source/postfix-yield.rs +++ /dev/null @@ -1,15 +0,0 @@ -// This demonstrates a proposed alternate or additional option of having yield in postfix position. -//@ edition: 2024 - -#![feature(gen_blocks, coroutines, coroutine_trait, yield_expr)] - -use std::ops::{Coroutine, CoroutineState}; -use std::pin::pin; - -fn main() { - let mut coro = - pin!(#[coroutine] |_: i32| { let x = 1.yield; - - - (x + 2).yield; }); -} diff --git a/tests/target/postfix-yield.rs b/tests/target/postfix-yield.rs index 7e94e1e095a..8ee34ec4312 100644 --- a/tests/target/postfix-yield.rs +++ b/tests/target/postfix-yield.rs @@ -7,6 +7,11 @@ use std::ops::{Coroutine, CoroutineState}; use std::pin::pin; fn main() { - let mut coro = - pin!(#[coroutine] |_: i32| { let x = 1.yield; (x + 2).yield; }); + let mut coro = pin!( + #[coroutine] + |_: i32| { + let x = 1.yield; + (x + 2).await; + } + ); } From ad0b41cf44176d984ab99d473e962af5da796398 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Tue, 18 Mar 2025 12:19:43 -0700 Subject: [PATCH 21/26] Refactor YieldKind so postfix yield must have an expression --- src/chains.rs | 4 ++-- src/expr.rs | 4 ++-- src/utils.rs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index fabb4400553..034ecde068a 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -259,7 +259,7 @@ impl ChainItemKind { let span = mk_sp(nested.span.hi(), expr.span.hi()); (ChainItemKind::Await, span) } - ast::ExprKind::Yield(Some(ref nested), ast::YieldKind::Postfix) => { + ast::ExprKind::Yield(ast::YieldKind::Postfix(ref nested)) => { let span = mk_sp(nested.span.hi(), expr.span.hi()); (ChainItemKind::Yield, span) } @@ -516,7 +516,7 @@ impl Chain { ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) | ast::ExprKind::Await(ref subexpr, _) - | ast::ExprKind::Yield(Some(ref subexpr), ast::YieldKind::Postfix) => Some(SubExpr { + | ast::ExprKind::Yield(ast::YieldKind::Postfix(ref subexpr)) => Some(SubExpr { expr: Self::convert_try(subexpr, context), is_method_call_receiver: false, }), diff --git a/src/expr.rs b/src/expr.rs index 92c1ffa6076..e866f13efc7 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -221,7 +221,7 @@ pub(crate) fn format_expr( Ok(format!("break{id_str}")) } } - ast::ExprKind::Yield(ref opt_expr, ast::YieldKind::Prefix) => { + ast::ExprKind::Yield(ast::YieldKind::Prefix(ref opt_expr)) => { if let Some(ref expr) = *opt_expr { rewrite_unary_prefix(context, "yield ", &**expr, shape) } else { @@ -244,7 +244,7 @@ pub(crate) fn format_expr( | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Await(_, _) - | ast::ExprKind::Yield(_, ast::YieldKind::Postfix) => rewrite_chain(expr, context, shape), + | ast::ExprKind::Yield(ast::YieldKind::Postfix(_)) => rewrite_chain(expr, context, shape), ast::ExprKind::MacCall(ref mac) => { rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|_| { wrap_str( diff --git a/src/utils.rs b/src/utils.rs index 1811752c3c4..fcd475b1784 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -485,7 +485,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Index(_, ref expr, _) | ast::ExprKind::Unary(_, ref expr) | ast::ExprKind::Try(ref expr) - | ast::ExprKind::Yield(Some(ref expr), YieldKind::Prefix) => { + | ast::ExprKind::Yield(YieldKind::Prefix(Some(ref expr))) => { is_block_expr(context, expr, repr) } ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr), @@ -517,7 +517,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Tup(..) | ast::ExprKind::Use(..) | ast::ExprKind::Type(..) - | ast::ExprKind::Yield(_, _) + | ast::ExprKind::Yield(..) | ast::ExprKind::Underscore => false, } } From b661e49756211e0015ed8ff869ca4e18718dcc47 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 12 Mar 2025 16:14:32 +1100 Subject: [PATCH 22/26] Remove `is_any_keyword` methods. They're dodgy, covering all the keywords, including weak ones, and edition-specific ones without considering the edition. They have a single use in rustfmt. This commit changes that use to `is_reserved_ident`, which is a much more widely used alternative and is good enough, judging by the lack of effect on the test suite. --- src/parse/macros/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parse/macros/mod.rs b/src/parse/macros/mod.rs index 680a35f7e03..d7964484b26 100644 --- a/src/parse/macros/mod.rs +++ b/src/parse/macros/mod.rs @@ -81,7 +81,7 @@ pub(crate) struct ParsedMacroArgs { } fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { - if parser.token.is_any_keyword() + if parser.token.is_reserved_ident() && parser.look_ahead(1, |t| *t == TokenKind::Eof || *t == TokenKind::Comma) { let keyword = parser.token.ident().unwrap().0.name; From de6e2d7e92a0f7f2aeceea4a1b300f04c614480b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sun, 23 Mar 2025 22:00:39 +0100 Subject: [PATCH 23/26] Remove fields that are dead since the removal of type ascription syntax Since `{ ident: ident }` is a parse error, these fields are dead. --- src/closures.rs | 1 - src/macros.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/src/closures.rs b/src/closures.rs index a37b47e3bc9..61e148cdf18 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -176,7 +176,6 @@ fn rewrite_closure_with_block( .first() .map(|attr| attr.span.to(body.span)) .unwrap_or(body.span), - could_be_bare_literal: false, }; let block = crate::expr::rewrite_block_with_visitor( context, diff --git a/src/macros.rs b/src/macros.rs index 664c90b991a..e239ff47c04 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -423,7 +423,6 @@ fn rewrite_empty_macro_def_body( rules: ast::BlockCheckMode::Default, span, tokens: None, - could_be_bare_literal: false, }; block.rewrite_result(context, shape) } From b3b26f4d6d0cf6b81661ef413befb1c4ca62f23a Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 25 Mar 2025 09:00:35 +0000 Subject: [PATCH 24/26] Track whether an assoc item is in a trait impl or an inherent impl --- src/visitor.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/visitor.rs b/src/visitor.rs index a5cfc542a17..5749d8c63fa 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -624,7 +624,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { // TODO(calebcartwright): Not sure the skip spans are correct let (ai, skip_span, assoc_ctxt) = match visitor_kind { AssocTraitItem(ai) => (*ai, ai.span(), visit::AssocCtxt::Trait), - AssocImplItem(ai) => (*ai, ai.span, visit::AssocCtxt::Impl), + // There is no difference between trait and inherent assoc item formatting + AssocImplItem(ai) => (*ai, ai.span, visit::AssocCtxt::Impl { of_trait: false }), _ => unreachable!(), }; skip_out_of_file_lines_range_visitor!(self, ai.span); From 025092fe33077120ac3371bf215fa7072edf2903 Mon Sep 17 00:00:00 2001 From: rustfmt bot Date: Tue, 1 Apr 2025 02:44:40 +0000 Subject: [PATCH 25/26] chore: bump rustfmt toolchain to nightly-2025-04-01 Bumping the toolchain version as part of a git subtree push current toolchain (nightly-2025-01-02): - 1.85.0-nightly (45d11e51b 2025-01-01) latest toolchain (nightly-2025-04-01): - 1.88.0-nightly (0b45675cf 2025-03-31) --- rust-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain b/rust-toolchain index 348664bc168..29e0b6eee5b 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2025-01-02" +channel = "nightly-2025-04-01" components = ["llvm-tools", "rustc-dev"] From 687bdc665dcc79e36f440859b8455f61c7c407cf Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 31 Mar 2025 22:54:56 -0400 Subject: [PATCH 26/26] chore: avoid `unreachable_pub` warning after subtree-push --- src/patterns.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/patterns.rs b/src/patterns.rs index 87bfc66ffa3..dc176b73f89 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -323,7 +323,7 @@ impl Rewrite for Pat { } } -pub fn rewrite_range_pat( +pub(crate) fn rewrite_range_pat( context: &RewriteContext<'_>, shape: Shape, lhs: &Option>,