diff --git a/Cargo.lock b/Cargo.lock index 981107b19fd..dbc62287baa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -75,12 +75,6 @@ version = "1.0.56" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4361135be9122e0870de935d7c439aef945b9f9ddd4199a553b5270b49c82a27" -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - [[package]] name = "bitflags" version = "2.9.4" @@ -98,9 +92,9 @@ dependencies = [ [[package]] name = "bytecount" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce89b21cab1437276d2650d57e971f9d548a2d9037cc231abdc0562b97498ce" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" [[package]] name = "camino" @@ -131,7 +125,7 @@ dependencies = [ "semver", "serde", "serde_json", - "thiserror", + "thiserror 1.0.40", ] [[package]] @@ -214,23 +208,23 @@ checksum = "0e25ea47919b1560c4e3b7fe0aaab9becf5b84a10325ddf7db0f0ba5e1026499" [[package]] name = "dirs" -version = "5.0.1" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ "dirs-sys", ] [[package]] name = "dirs-sys" -version = "0.4.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.48.0", + "windows-sys 0.60.2", ] [[package]] @@ -379,6 +373,16 @@ version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" +[[package]] +name = "libredox" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" +dependencies = [ + "bitflags", + "libc", +] + [[package]] name = "linux-raw-sys" version = "0.11.0" @@ -445,9 +449,9 @@ checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" [[package]] name = "proc-macro2" -version = "1.0.78" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ "unicode-ident", ] @@ -467,24 +471,15 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "redox_users" -version = "0.4.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.6", - "redox_syscall", - "thiserror", + "libredox", + "thiserror 2.0.18", ] [[package]] @@ -544,7 +539,7 @@ dependencies = [ "serde_json", "tempfile", "term", - "thiserror", + "thiserror 1.0.40", "toml", "tracing", "tracing-subscriber", @@ -559,7 +554,7 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" dependencies = [ - "bitflags 2.9.4", + "bitflags", "errno", "libc", "linux-raw-sys", @@ -653,9 +648,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "syn" -version = "2.0.48" +version = "2.0.116" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" +checksum = "3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb" dependencies = [ "proc-macro2", "quote", @@ -690,7 +685,16 @@ version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.40", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", ] [[package]] @@ -704,6 +708,17 @@ dependencies = [ "syn", ] +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "thread_local" version = "1.1.4" diff --git a/Cargo.toml b/Cargo.toml index 2b693b19c0f..65ece1e7b99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,17 +30,20 @@ path = "src/git-rustfmt/main.rs" default = ["cargo-fmt", "rustfmt-format-diff"] cargo-fmt = [] rustfmt-format-diff = [] -generic-simd = ["bytecount/generic-simd"] +# FIXME(ytmimi) re-enable "bytecount/generic-simd" to the `generic-simd` features +# once bytecount releases a fix. rustfmt's `generic-simd` features is breaking CI +# and interfering with the next subtree-sync +generic-simd = [] [dependencies] annotate-snippets = { version = "0.11" } anyhow = "1.0" -bytecount = "0.6.8" +bytecount = "0.6.9" cargo_metadata = "0.18" clap = { version = "4.4.2", features = ["derive"] } clap-cargo = "0.12.0" diff = "0.1" -dirs = "5.0" +dirs = "6.0" getopts = "0.2" ignore = "0.4" itertools = "0.12" diff --git a/rust-toolchain b/rust-toolchain index 80851788276..cad47379b5d 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2025-04-02" +channel = "nightly-2026-02-19" components = ["llvm-tools", "rustc-dev"] diff --git a/src/attr.rs b/src/attr.rs index e2104617fdc..ac9ce2e8796 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -333,8 +333,8 @@ impl Rewrite for ast::Attribute { rewrite_doc_comment(snippet, shape.comment(context.config), context.config) } else { let should_skip = self - .ident() - .map(|s| context.skip_context.attributes.skip(s.name.as_str())) + .name() + .map(|s| context.skip_context.attributes.skip(s.as_str())) .unwrap_or(false); let prefix = attr_prefix(self); diff --git a/src/chains.rs b/src/chains.rs index 9ab20b355fb..90adb67ad43 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -58,7 +58,7 @@ use std::borrow::Cow; use std::cmp::min; -use rustc_ast::{ast, ptr}; +use rustc_ast::ast; use rustc_span::{BytePos, Span, symbol}; use tracing::debug; @@ -190,7 +190,7 @@ enum ChainItemKind { MethodCall( ast::PathSegment, Vec, - ThinVec>, + ThinVec>, ), StructField(symbol::Ident), TupleField(symbol::Ident, bool), @@ -351,7 +351,7 @@ impl ChainItem { fn rewrite_method_call( method_name: symbol::Ident, types: &[ast::GenericArg], - args: &[ptr::P], + args: &[Box], span: Span, context: &RewriteContext<'_>, shape: Shape, diff --git a/src/closures.rs b/src/closures.rs index 1ab1a80f863..19cd0d9792c 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -1,4 +1,4 @@ -use rustc_ast::{Label, ast, ptr}; +use rustc_ast::{Label, ast}; use rustc_span::Span; use thin_vec::thin_vec; use tracing::debug; @@ -169,7 +169,7 @@ fn rewrite_closure_with_block( let block = ast::Block { stmts: thin_vec![ast::Stmt { id: ast::NodeId::root(), - kind: ast::StmtKind::Expr(ptr::P(body.clone())), + kind: ast::StmtKind::Expr(Box::new(body.clone())), span: body.span, }], id: ast::NodeId::root(), diff --git a/src/config/file_lines.rs b/src/config/file_lines.rs index 91f822db0fc..85e91251307 100644 --- a/src/config/file_lines.rs +++ b/src/config/file_lines.rs @@ -28,7 +28,15 @@ pub enum FileName { impl From for FileName { fn from(name: rustc_span::FileName) -> FileName { match name { - rustc_span::FileName::Real(rustc_span::RealFileName::LocalPath(p)) => FileName::Real(p), + rustc_span::FileName::Real(real) => { + if let Some(p) = real.into_local_path() { + FileName::Real(p) + } else { + // rustfmt does not remap filenames; the local path should always + // remain accessible. + unreachable!() + } + } rustc_span::FileName::Custom(ref f) if f == "stdin" => FileName::Stdin, _ => unreachable!(), } diff --git a/src/config/mod.rs b/src/config/mod.rs index 008d296b6a8..8abb7439257 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -558,7 +558,6 @@ mod test { #[allow(dead_code)] mod mock { use super::super::*; - use crate::config_option_with_style_edition_default; use rustfmt_config_proc_macro::config_type; #[config_type] diff --git a/src/expr.rs b/src/expr.rs index f043eb0449c..b79137c4442 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -3,7 +3,7 @@ use std::cmp::min; use itertools::Itertools; use rustc_ast::token::{Delimiter, Lit, LitKind}; -use rustc_ast::{ForLoopKind, MatchKind, ast, ptr, token}; +use rustc_ast::{ForLoopKind, MatchKind, ast, token}; use rustc_span::{BytePos, Span}; use tracing::debug; @@ -392,12 +392,13 @@ pub(crate) fn format_expr( // Style Guide RFC for InlineAsm variant pending // https://github.com/rust-dev-tools/fmt-rfcs/issues/152 ast::ExprKind::InlineAsm(..) => Ok(context.snippet(expr.span).to_owned()), - ast::ExprKind::TryBlock(ref block) => { + ast::ExprKind::TryBlock(ref block, None) => { if let rw @ Ok(_) = rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape) { rw } else { + // FIXME: 9 sounds like `"do catch ".len()`, so may predate the rename // 9 = `try ` let budget = shape.width.saturating_sub(9); Ok(format!( @@ -413,6 +414,33 @@ pub(crate) fn format_expr( )) } } + ast::ExprKind::TryBlock(ref block, Some(ref ty)) => { + let keyword = "try bikeshed "; + // 2 = " {".len() + let ty_shape = shape + .shrink_left(keyword.len(), expr.span) + .and_then(|shape| shape.sub_width(2, expr.span))?; + + let ty_str = ty.rewrite_result(context, ty_shape)?; + let prefix = format!("{keyword}{ty_str} "); + if let rw @ Ok(_) = + rewrite_single_line_block(context, &prefix, block, Some(&expr.attrs), None, shape) + { + rw + } else { + let budget = shape.width.saturating_sub(prefix.len()); + Ok(format!( + "{prefix}{}", + rewrite_block( + block, + Some(&expr.attrs), + None, + context, + Shape::legacy(budget, shape.indent) + )? + )) + } + } ast::ExprKind::Gen(capture_by, ref block, ref kind, _) => { let mover = if matches!(capture_by, ast::CaptureBy::Value { .. }) { "move " @@ -1469,7 +1497,7 @@ fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option, callee: &str, - args: &[ptr::P], + args: &[Box], span: Span, shape: Shape, ) -> RewriteResult { @@ -1732,7 +1760,7 @@ fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool fn rewrite_struct_lit<'a>( context: &RewriteContext<'_>, path: &ast::Path, - qself: &Option>, + qself: &Option>, fields: &'a [ast::ExprField], struct_rest: &ast::StructRest, attrs: &[ast::Attribute], @@ -2135,7 +2163,7 @@ fn rewrite_assignment( context: &RewriteContext<'_>, lhs: &ast::Expr, rhs: &ast::Expr, - op: Option<&ast::BinOp>, + op: Option<&ast::AssignOp>, shape: Shape, ) -> RewriteResult { let operator_str = match op { @@ -2365,8 +2393,10 @@ fn rewrite_expr_addrof( ) -> RewriteResult { let operator_str = match (mutability, borrow_kind) { (ast::Mutability::Not, ast::BorrowKind::Ref) => "&", + (ast::Mutability::Not, ast::BorrowKind::Pin) => "&pin const ", (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ", (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ", + (ast::Mutability::Mut, ast::BorrowKind::Pin) => "&pin mut ", (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ", }; rewrite_unary_prefix(context, operator_str, expr, shape) diff --git a/src/imports.rs b/src/imports.rs index 2a1cc0cfd7c..2f26791639a 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -191,7 +191,7 @@ impl UseSegment { modsep: bool, ) -> Option { let name = rewrite_ident(context, path_seg.ident); - if name.is_empty() || name == "{{root}}" { + if name.is_empty() { return None; } let kind = match name { diff --git a/src/items.rs b/src/items.rs index b8ad789a884..2c5fcf09c9f 100644 --- a/src/items.rs +++ b/src/items.rs @@ -4,8 +4,8 @@ use std::borrow::Cow; use std::cmp::{Ordering, max, min}; use regex::Regex; +use rustc_ast::ast; use rustc_ast::visit; -use rustc_ast::{ast, ptr}; use rustc_span::{BytePos, DUMMY_SP, Ident, Span, symbol}; use tracing::debug; @@ -65,6 +65,11 @@ impl Rewrite for ast::Local { return Err(RewriteError::SkipFormatting); } + // FIXME(super_let): Implement formatting + if self.super_.is_some() { + return Err(RewriteError::SkipFormatting); + } + let attrs_str = self.attrs.rewrite_result(context, shape)?; let mut result = if attrs_str.is_empty() { "let ".to_owned() @@ -308,12 +313,13 @@ impl<'a> FnSig<'a> { method_sig: &'a ast::FnSig, generics: &'a ast::Generics, visibility: &'a ast::Visibility, + defaultness: ast::Defaultness, ) -> FnSig<'a> { FnSig { safety: method_sig.header.safety, coroutine_kind: Cow::Borrowed(&method_sig.header.coroutine_kind), constness: method_sig.header.constness, - defaultness: ast::Defaultness::Final, + defaultness, ext: method_sig.header.ext, decl: &*method_sig.decl, generics, @@ -328,9 +334,7 @@ impl<'a> FnSig<'a> { ) -> FnSig<'a> { match *fn_kind { 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 + FnSig::from_method_sig(sig, generics, vis, defaultness) } visit::FnKind::Fn(_, vis, ast::Fn { sig, generics, .. }) => FnSig { decl, @@ -448,6 +452,7 @@ impl<'a> FmtVisitor<'a> { sig: &ast::FnSig, vis: &ast::Visibility, generics: &ast::Generics, + defaultness: ast::Defaultness, span: Span, ) -> RewriteResult { // Drop semicolon or it will be interpreted as comment. @@ -458,7 +463,7 @@ impl<'a> FmtVisitor<'a> { &context, indent, ident, - &FnSig::from_method_sig(sig, generics, vis), + &FnSig::from_method_sig(sig, generics, vis, defaultness), span, FnBraceStyle::None, )?; @@ -714,9 +719,9 @@ impl<'a> FmtVisitor<'a> { .ok() } - fn visit_impl_items(&mut self, items: &[ptr::P]) { + fn visit_impl_items(&mut self, items: &[Box]) { if self.get_context().config.reorder_impl_items() { - type TyOpt = Option>; + type TyOpt = Option>; use crate::ast::AssocItemKind::*; let is_type = |ty: &TyOpt| opaque_ty(ty).is_none(); let is_opaque = |ty: &TyOpt| opaque_ty(ty).is_some(); @@ -825,8 +830,7 @@ pub(crate) fn format_impl( let where_span_end = context.snippet_provider.opt_span_before(missing_span, "{"); let where_clause_str = rewrite_where_clause( context, - &generics.where_clause.predicates, - generics.where_clause.span, + &generics.where_clause, context.config.brace_style(), Shape::legacy(where_budget, offset.block_only()), false, @@ -922,7 +926,7 @@ pub(crate) fn format_impl( fn is_impl_single_line( context: &RewriteContext<'_>, - items: &[ptr::P], + items: &[Box], result: &str, where_clause_str: &str, item: &ast::Item, @@ -944,20 +948,22 @@ fn format_impl_ref_and_type( offset: Indent, ) -> RewriteResult { let ast::Impl { - safety, - polarity, - defaultness, + generics, + of_trait, + self_ty, + items: _, constness, - ref generics, - of_trait: ref trait_ref, - ref self_ty, - .. - } = *iimpl; + } = iimpl; let mut result = String::with_capacity(128); result.push_str(&format_visibility(context, &item.vis)); - result.push_str(format_defaultness(defaultness)); - result.push_str(format_safety(safety)); + + if let Some(of_trait) = of_trait.as_deref() { + result.push_str(format_defaultness(of_trait.defaultness)); + result.push_str(format_safety(of_trait.safety)); + } else { + result.push_str(format_constness(*constness)); + } let shape = if context.config.style_edition() >= StyleEdition::Edition2024 { Shape::indented(offset + last_line_width(&result), context.config) @@ -971,28 +977,24 @@ fn format_impl_ref_and_type( }; let generics_str = rewrite_generics(context, "impl", generics, shape)?; result.push_str(&generics_str); - result.push_str(format_constness_right(constness)); - - let polarity_str = match polarity { - ast::ImplPolarity::Negative(_) => "!", - ast::ImplPolarity::Positive => "", - }; - let polarity_overhead; let trait_ref_overhead; - if let Some(ref trait_ref) = *trait_ref { + if let Some(of_trait) = of_trait.as_deref() { + result.push_str(format_constness_right(*constness)); + let polarity_str = match of_trait.polarity { + ast::ImplPolarity::Negative(_) => "!", + ast::ImplPolarity::Positive => "", + }; let result_len = last_line_width(&result); result.push_str(&rewrite_trait_ref( context, - trait_ref, + &of_trait.trait_ref, offset, polarity_str, result_len, )?); - polarity_overhead = 0; // already written trait_ref_overhead = " for".len(); } else { - polarity_overhead = polarity_str.len(); trait_ref_overhead = 0; } @@ -1007,17 +1009,15 @@ fn format_impl_ref_and_type( } else { 0 }; - let used_space = - last_line_width(&result) + polarity_overhead + trait_ref_overhead + curly_brace_overhead; + let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead; // 1 = space before the type. let budget = context.budget(used_space + 1); if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) { if !self_ty_str.contains('\n') { - if trait_ref.is_some() { + if of_trait.is_some() { result.push_str(" for "); } else { result.push(' '); - result.push_str(polarity_str); } result.push_str(&self_ty_str); return Ok(result); @@ -1029,12 +1029,10 @@ fn format_impl_ref_and_type( // Add indentation of one additional tab. let new_line_offset = offset.block_indent(context.config); result.push_str(&new_line_offset.to_string(context.config)); - if trait_ref.is_some() { + if of_trait.is_some() { result.push_str("for "); - } else { - result.push_str(polarity_str); } - let budget = context.budget(last_line_width(&result) + polarity_overhead); + let budget = context.budget(last_line_width(&result)); let type_offset = match context.config.indent_style() { IndentStyle::Visual => new_line_offset + trait_ref_overhead, IndentStyle::Block => new_line_offset, @@ -1097,10 +1095,10 @@ impl<'a> StructParts<'a> { pub(crate) fn from_item(item: &'a ast::Item) -> Self { let (prefix, def, ident, generics) = match item.kind { - ast::ItemKind::Struct(ident, ref def, ref generics) => { + ast::ItemKind::Struct(ident, ref generics, ref def) => { ("struct ", def, ident, generics) } - ast::ItemKind::Union(ident, ref def, ref generics) => ("union ", def, ident, generics), + ast::ItemKind::Union(ident, ref generics, ref def) => ("union ", def, ident, generics), _ => unreachable!(), }; StructParts { @@ -1157,6 +1155,7 @@ pub(crate) fn format_trait( offset: Indent, ) -> RewriteResult { let ast::Trait { + constness, is_auto, safety, ident, @@ -1167,8 +1166,9 @@ pub(crate) fn format_trait( let mut result = String::with_capacity(128); let header = format!( - "{}{}{}trait ", + "{}{}{}{}trait ", format_visibility(context, &item.vis), + format_constness(constness), format_safety(safety), format_auto(is_auto), ); @@ -1214,8 +1214,7 @@ pub(crate) fn format_trait( let option = WhereClauseOption::snuggled(&generics_str); let where_clause_str = rewrite_where_clause( context, - &generics.where_clause.predicates, - generics.where_clause.span, + &generics.where_clause, context.config.brace_style(), Shape::legacy(where_budget, offset.block_only()), where_on_new_line, @@ -1340,8 +1339,7 @@ impl<'a> Rewrite for TraitAliasBounds<'a> { let where_str = rewrite_where_clause( context, - &self.generics.where_clause.predicates, - self.generics.where_clause.span, + &self.generics.where_clause, context.config.brace_style(), shape, false, @@ -1368,30 +1366,29 @@ impl<'a> Rewrite for TraitAliasBounds<'a> { pub(crate) fn format_trait_alias( context: &RewriteContext<'_>, - ident: Ident, - item: &ast::Item, - generics: &ast::Generics, - generic_bounds: &ast::GenericBounds, + ta: &ast::TraitAlias, + vis: &ast::Visibility, + span: Span, shape: Shape, ) -> RewriteResult { - let ast::Item { ref vis, span, .. } = *item; - let alias = rewrite_ident(context, ident); + let alias = rewrite_ident(context, ta.ident); // 6 = "trait ", 2 = " =" let g_shape = shape.offset_left(6, span)?.sub_width(2, span)?; - let generics_str = rewrite_generics(context, alias, generics, g_shape)?; + let generics_str = rewrite_generics(context, alias, &ta.generics, g_shape)?; let vis_str = format_visibility(context, vis); - let lhs = format!("{vis_str}trait {generics_str} ="); + let constness = format_constness(ta.constness); + let lhs = format!("{vis_str}{constness}trait {generics_str} ="); // 1 = ";" let trait_alias_bounds = TraitAliasBounds { - generic_bounds, - generics, + generic_bounds: &ta.bounds, + generics: &ta.generics, }; let result = rewrite_assign_rhs( context, lhs, &trait_alias_bounds, &RhsAssignKind::Bounds, - shape.sub_width(1, generics.span)?, + shape.sub_width(1, ta.generics.span)?, )?; Ok(result + ";") } @@ -1611,8 +1608,7 @@ fn format_tuple_struct( let option = WhereClauseOption::new(true, WhereClauseSpace::Newline); rewrite_where_clause( context, - &generics.where_clause.predicates, - generics.where_clause.span, + &generics.where_clause, context.config.brace_style(), Shape::legacy(where_budget, offset.block_only()), false, @@ -1681,7 +1677,7 @@ struct TyAliasRewriteInfo<'c, 'g>( &'c RewriteContext<'c>, Indent, &'g ast::Generics, - ast::TyAliasWhereClauses, + &'g ast::WhereClause, symbol::Ident, Span, ); @@ -1702,13 +1698,13 @@ pub(crate) fn rewrite_type_alias<'a>( ref generics, ref bounds, ref ty, - where_clauses, + ref after_where_clause, } = *ty_alias_kind; let ty_opt = ty.as_ref(); let rhs_hi = ty .as_ref() - .map_or(where_clauses.before.span.hi(), |ty| ty.span.hi()); - let rw_info = &TyAliasRewriteInfo(context, indent, generics, where_clauses, ident, span); + .map_or(generics.where_clause.span.hi(), |ty| ty.span.hi()); + let rw_info = &TyAliasRewriteInfo(context, indent, generics, after_where_clause, ident, span); let op_ty = opaque_ty(ty); // Type Aliases are formatted slightly differently depending on the context // in which they appear, whether they are opaque, and whether they are associated. @@ -1752,11 +1748,7 @@ fn rewrite_ty( vis: &ast::Visibility, ) -> RewriteResult { let mut result = String::with_capacity(128); - let TyAliasRewriteInfo(context, indent, generics, where_clauses, ident, span) = *rw_info; - let (before_where_predicates, after_where_predicates) = generics - .where_clause - .predicates - .split_at(where_clauses.split); + let TyAliasRewriteInfo(context, indent, generics, after_where_clause, ident, span) = *rw_info; result.push_str(&format!("{}type ", format_visibility(context, vis))); let ident_str = rewrite_ident(context, ident); @@ -1791,8 +1783,7 @@ fn rewrite_ty( } let before_where_clause_str = rewrite_where_clause( context, - before_where_predicates, - where_clauses.before.span, + &generics.where_clause, context.config.brace_style(), Shape::legacy(where_budget, indent), false, @@ -1807,9 +1798,9 @@ fn rewrite_ty( // If there are any where clauses, add a newline before the assignment. // If there is a before where clause, do not indent, but if there is // only an after where clause, additionally indent the type. - if !before_where_predicates.is_empty() { + if !generics.where_clause.predicates.is_empty() { result.push_str(&indent.to_string_with_newline(context.config)); - } else if !after_where_predicates.is_empty() { + } else if !after_where_clause.predicates.is_empty() { result.push_str( &indent .block_indent(context.config) @@ -1822,7 +1813,7 @@ fn rewrite_ty( let comment_span = context .snippet_provider .opt_span_before(span, "=") - .map(|op_lo| mk_sp(where_clauses.before.span.hi(), op_lo)); + .map(|op_lo| mk_sp(generics.where_clause.span.hi(), op_lo)); let lhs = match comment_span { Some(comment_span) @@ -1833,7 +1824,7 @@ fn rewrite_ty( .unknown_error()?, ) => { - let comment_shape = if !before_where_predicates.is_empty() { + let comment_shape = if !generics.where_clause.predicates.is_empty() { Shape::indented(indent, context.config) } else { let shape = Shape::indented(indent, context.config); @@ -1854,7 +1845,7 @@ fn rewrite_ty( // 1 = `;` unless there's a trailing where clause let shape = Shape::indented(indent, context.config); - let shape = if after_where_predicates.is_empty() { + let shape = if after_where_clause.predicates.is_empty() { Shape::indented(indent, context.config).sub_width(1, span)? } else { shape @@ -1864,12 +1855,11 @@ fn rewrite_ty( result }; - if !after_where_predicates.is_empty() { + if !after_where_clause.predicates.is_empty() { let option = WhereClauseOption::new(true, WhereClauseSpace::Newline); let after_where_clause_str = rewrite_where_clause( context, - after_where_predicates, - where_clauses.after.span, + &after_where_clause, context.config.brace_style(), Shape::indented(indent, context.config), false, @@ -1998,37 +1988,41 @@ pub(crate) struct StaticParts<'a> { generics: Option<&'a ast::Generics>, ty: &'a ast::Ty, mutability: ast::Mutability, - expr_opt: Option<&'a ptr::P>, + expr_opt: Option<&'a ast::Expr>, defaultness: Option, span: Span, } impl<'a> StaticParts<'a> { pub(crate) fn from_item(item: &'a ast::Item) -> Self { - let (defaultness, prefix, safety, ident, ty, mutability, expr, generics) = match &item.kind - { - ast::ItemKind::Static(s) => ( - None, - "static", - s.safety, - s.ident, - &s.ty, - s.mutability, - &s.expr, - None, - ), - ast::ItemKind::Const(c) => ( - Some(c.defaultness), - "const", - ast::Safety::Default, - c.ident, - &c.ty, - ast::Mutability::Not, - &c.expr, - Some(&c.generics), - ), - _ => unreachable!(), - }; + let (defaultness, prefix, safety, ident, ty, mutability, expr_opt, generics) = + match &item.kind { + ast::ItemKind::Static(s) => ( + None, + "static", + s.safety, + s.ident, + &s.ty, + s.mutability, + s.expr.as_deref(), + None, + ), + ast::ItemKind::Const(c) => ( + Some(c.defaultness), + if c.rhs_kind.is_type_const() { + "type const" + } else { + "const" + }, + ast::Safety::Default, + c.ident, + &c.ty, + ast::Mutability::Not, + c.rhs_kind.expr(), + Some(&c.generics), + ), + _ => unreachable!(), + }; StaticParts { prefix, safety, @@ -2037,45 +2031,71 @@ impl<'a> StaticParts<'a> { generics, ty, mutability, - expr_opt: expr.as_ref(), + expr_opt, defaultness, span: item.span, } } pub(crate) fn from_trait_item(ti: &'a ast::AssocItem, ident: Ident) -> Self { - let (defaultness, ty, expr_opt, generics) = match &ti.kind { - ast::AssocItemKind::Const(c) => (c.defaultness, &c.ty, &c.expr, Some(&c.generics)), + let (defaultness, ty, expr_opt, generics, prefix) = match &ti.kind { + ast::AssocItemKind::Const(c) => { + let prefix = if c.rhs_kind.is_type_const() { + "type const" + } else { + "const" + }; + ( + c.defaultness, + &c.ty, + c.rhs_kind.expr(), + Some(&c.generics), + prefix, + ) + } _ => unreachable!(), }; StaticParts { - prefix: "const", + prefix, safety: ast::Safety::Default, vis: &ti.vis, ident, generics, ty, mutability: ast::Mutability::Not, - expr_opt: expr_opt.as_ref(), + expr_opt, defaultness: Some(defaultness), span: ti.span, } } pub(crate) fn from_impl_item(ii: &'a ast::AssocItem, ident: Ident) -> Self { - let (defaultness, ty, expr, generics) = match &ii.kind { - ast::AssocItemKind::Const(c) => (c.defaultness, &c.ty, &c.expr, Some(&c.generics)), + let (defaultness, ty, expr_opt, generics, prefix) = match &ii.kind { + ast::AssocItemKind::Const(c) => { + let prefix = if c.rhs_kind.is_type_const() { + "type const" + } else { + "const" + }; + ( + c.defaultness, + &c.ty, + c.rhs_kind.expr(), + Some(&c.generics), + prefix, + ) + } _ => unreachable!(), }; StaticParts { - prefix: "const", + prefix, safety: ast::Safety::Default, vis: &ii.vis, ident, generics, ty, mutability: ast::Mutability::Not, - expr_opt: expr.as_ref(), + expr_opt, defaultness: Some(defaultness), span: ii.span, } @@ -2138,7 +2158,7 @@ fn rewrite_static( rewrite_assign_rhs_with_comments( context, &lhs, - &**expr, + expr, Shape::legacy(remaining_width, offset.block_only()), &RhsAssignKind::Expr(&expr.kind, expr.span), RhsTactics::Default, @@ -2421,11 +2441,7 @@ pub(crate) fn span_hi_for_param(context: &RewriteContext<'_>, param: &ast::Param } pub(crate) fn is_named_param(param: &ast::Param) -> bool { - if let ast::PatKind::Ident(_, ident, _) = param.pat.kind { - ident.name != symbol::kw::Empty - } else { - true - } + !matches!(param.pat.kind, ast::PatKind::Missing) } #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -2713,8 +2729,7 @@ fn rewrite_fn_base( } let where_clause_str = rewrite_where_clause( context, - &where_clause.predicates, - where_clause.span, + &where_clause, context.config.brace_style(), Shape::indented(indent, context.config), true, @@ -3146,8 +3161,7 @@ fn rewrite_bounds_on_where_clause( fn rewrite_where_clause( context: &RewriteContext<'_>, - predicates: &[ast::WherePredicate], - where_span: Span, + where_clause: &ast::WhereClause, brace_style: BraceStyle, shape: Shape, on_new_line: bool, @@ -3156,6 +3170,12 @@ fn rewrite_where_clause( span_end_before_where: BytePos, where_clause_option: WhereClauseOption, ) -> RewriteResult { + let ast::WhereClause { + ref predicates, + span: where_span, + has_where_token: _, + } = *where_clause; + if predicates.is_empty() { return Ok(String::new()); } @@ -3342,8 +3362,7 @@ fn format_generics( } let where_clause_str = rewrite_where_clause( context, - &generics.where_clause.predicates, - generics.where_clause.span, + &generics.where_clause, brace_style, Shape::legacy(budget, offset.block_only()), true, @@ -3458,7 +3477,7 @@ impl Rewrite for ast::ForeignItem { context, shape.indent, ident, - &FnSig::from_method_sig(sig, generics, &self.vis), + &FnSig::from_method_sig(sig, generics, &self.vis, defaultness), span, FnBraceStyle::None, ) @@ -3585,7 +3604,7 @@ pub(crate) fn rewrite_extern_crate( pub(crate) fn is_mod_decl(item: &ast::Item) -> bool { !matches!( item.kind, - ast::ItemKind::Mod(_, _, ast::ModKind::Loaded(_, ast::Inline::Yes, _, _)) + ast::ItemKind::Mod(_, _, ast::ModKind::Loaded(_, ast::Inline::Yes, _)) ) } diff --git a/src/macros.rs b/src/macros.rs index 3b58d28bfb0..1c5d804c6d4 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -12,9 +12,9 @@ use std::collections::HashMap; use std::panic::{AssertUnwindSafe, catch_unwind}; +use rustc_ast::ast; use rustc_ast::token::{Delimiter, Token, TokenKind}; use rustc_ast::tokenstream::{TokenStream, TokenStreamIter, TokenTree}; -use rustc_ast::{ast, ptr}; use rustc_ast_pretty::pprust; use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol}; use tracing::debug; @@ -53,10 +53,10 @@ pub(crate) enum MacroPosition { #[derive(Debug)] pub(crate) enum MacroArg { - Expr(ptr::P), - Ty(ptr::P), - Pat(ptr::P), - Item(ptr::P), + Expr(Box), + Ty(Box), + Pat(Box), + Item(Box), Keyword(Ident, Span), } @@ -724,7 +724,7 @@ fn last_tok(tt: &TokenTree) -> Token { match *tt { TokenTree::Token(ref t, _) => t.clone(), TokenTree::Delimited(delim_span, _, delim, _) => Token { - kind: TokenKind::CloseDelim(delim), + kind: delim.as_open_token_kind(), span: delim_span.close, }, } @@ -860,18 +860,18 @@ impl MacroArgParser { }; self.result.push(ParsedMacroArg { - kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()), + kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok), }); Some(()) } - fn update_buffer(&mut self, t: &Token) { + fn update_buffer(&mut self, t: Token) { if self.buf.is_empty() { - self.start_tok = t.clone(); + self.start_tok = t; } else { let needs_space = match next_space(&self.last_tok.kind) { - SpaceState::Ident => ident_like(t), - SpaceState::Punctuation => !ident_like(t), + SpaceState::Ident => ident_like(&t), + SpaceState::Punctuation => !ident_like(&t), SpaceState::Always => true, SpaceState::Never => false, }; @@ -880,7 +880,7 @@ impl MacroArgParser { } } - self.buf.push_str(&pprust::token_to_string(t)); + self.buf.push_str(&pprust::token_to_string(&t)); } fn need_space_prefix(&self) -> bool { @@ -939,7 +939,7 @@ impl MacroArgParser { ) if self.is_meta_var => { self.add_meta_variable(&mut iter)?; } - TokenTree::Token(ref t, _) => self.update_buffer(t), + &TokenTree::Token(t, _) => self.update_buffer(t), &TokenTree::Delimited(_dspan, _spacing, delimited, ref tts) => { if !self.buf.is_empty() { if next_space(&self.last_tok.kind) == SpaceState::Always { @@ -1126,8 +1126,14 @@ fn next_space(tok: &TokenKind) -> SpaceState { TokenKind::PathSep | TokenKind::Pound | TokenKind::Dollar - | TokenKind::OpenDelim(_) - | TokenKind::CloseDelim(_) => SpaceState::Never, + | TokenKind::OpenParen + | TokenKind::CloseParen + | TokenKind::OpenBrace + | TokenKind::CloseBrace + | TokenKind::OpenBracket + | TokenKind::CloseBracket + | TokenKind::OpenInvisible(_) + | TokenKind::CloseInvisible(_) => SpaceState::Never, TokenKind::Literal(..) | TokenKind::Ident(..) | TokenKind::Lifetime(..) => { SpaceState::Ident diff --git a/src/matches.rs b/src/matches.rs index 1727a9de868..4741abbe465 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -2,7 +2,7 @@ use std::iter::repeat; -use rustc_ast::{MatchKind, ast, ptr}; +use rustc_ast::{MatchKind, ast}; use rustc_span::{BytePos, Span}; use tracing::debug; @@ -396,7 +396,7 @@ fn flatten_arm_body<'a>( fn rewrite_match_body( context: &RewriteContext<'_>, - body: &ptr::P, + body: &Box, pats_str: &str, shape: Shape, has_guard: bool, @@ -571,7 +571,7 @@ fn rewrite_match_body( // The `if ...` guard on a match arm. fn rewrite_guard( context: &RewriteContext<'_>, - guard: &Option>, + guard: &Option>, shape: Shape, // The amount of space used up on this line for the pattern in // the arm (excludes offset). diff --git a/src/modules.rs b/src/modules.rs index a8b686855a9..099a6442821 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -26,7 +26,7 @@ type FileModMap<'ast> = BTreeMap>; #[derive(Debug, Clone)] pub(crate) struct Module<'a> { ast_mod_kind: Option>, - pub(crate) items: Cow<'a, ThinVec>>, + pub(crate) items: Cow<'a, ThinVec>>, inner_attr: ast::AttrVec, pub(crate) span: Span, } @@ -35,7 +35,7 @@ impl<'a> Module<'a> { pub(crate) fn new( mod_span: Span, ast_mod_kind: Option>, - mod_items: Cow<'a, ThinVec>>, + mod_items: Cow<'a, ThinVec>>, mod_attrs: Cow<'a, ast::AttrVec>, ) -> Self { let inner_attr = mod_attrs @@ -189,16 +189,16 @@ impl<'ast, 'psess, 'c> ModResolver<'ast, 'psess> { /// Visit modules defined inside macro calls. fn visit_mod_outside_ast( &mut self, - items: ThinVec>, + items: ThinVec>, ) -> Result<(), ModuleResolutionError> { for item in items { if is_cfg_if(&item) { - self.visit_cfg_if(Cow::Owned(item.into_inner()))?; + self.visit_cfg_if(Cow::Owned(*item))?; continue; } if is_cfg_match(&item) { - self.visit_cfg_match(Cow::Owned(item.into_inner()))?; + self.visit_cfg_match(Cow::Owned(*item))?; continue; } @@ -221,7 +221,7 @@ impl<'ast, 'psess, 'c> ModResolver<'ast, 'psess> { /// Visit modules from AST. fn visit_mod_from_ast( &mut self, - items: &'ast [rustc_ast::ptr::P], + items: &'ast [Box], ) -> Result<(), ModuleResolutionError> { for item in items { if is_cfg_if(item) { @@ -344,11 +344,12 @@ impl<'ast, 'psess, 'c> ModResolver<'ast, 'psess> { self.directory = directory; } match (sub_mod.ast_mod_kind, sub_mod.items) { - (Some(Cow::Borrowed(ast::ModKind::Loaded(items, _, _, _))), _) => { + (Some(Cow::Borrowed(ast::ModKind::Loaded(items, _, _))), _) => { self.visit_mod_from_ast(items) } - (Some(Cow::Owned(ast::ModKind::Loaded(items, _, _, _))), _) - | (_, Cow::Owned(items)) => self.visit_mod_outside_ast(items), + (Some(Cow::Owned(ast::ModKind::Loaded(items, _, _))), _) | (_, Cow::Owned(items)) => { + self.visit_mod_outside_ast(items) + } (_, _) => Ok(()), } } diff --git a/src/overflow.rs b/src/overflow.rs index 19f7b06f8a3..4230c89b57b 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -3,8 +3,8 @@ use std::cmp::min; use itertools::Itertools; +use rustc_ast::ast; use rustc_ast::token::Delimiter; -use rustc_ast::{ast, ptr}; use rustc_span::Span; use tracing::debug; @@ -219,7 +219,7 @@ pub(crate) trait IntoOverflowableItem<'a>: Rewrite + Spanned { fn into_overflowable_item(&'a self) -> OverflowableItem<'a>; } -impl<'a, T: 'a + IntoOverflowableItem<'a>> IntoOverflowableItem<'a> for ptr::P { +impl<'a, T: 'a + IntoOverflowableItem<'a>> IntoOverflowableItem<'a> for Box { fn into_overflowable_item(&'a self) -> OverflowableItem<'a> { (**self).into_overflowable_item() } diff --git a/src/parse/macros/asm.rs b/src/parse/macros/asm.rs new file mode 100644 index 00000000000..bfa9c6300c4 --- /dev/null +++ b/src/parse/macros/asm.rs @@ -0,0 +1,11 @@ +use rustc_ast::ast; +use rustc_parse::parser::asm::{AsmArg, parse_asm_args}; + +use crate::rewrite::RewriteContext; + +#[allow(dead_code)] +pub(crate) fn parse_asm(context: &RewriteContext<'_>, mac: &ast::MacCall) -> Option> { + let ts = mac.args.tokens.clone(); + let mut parser = super::build_parser(context, ts); + parse_asm_args(&mut parser, mac.span(), ast::AsmMacro::Asm).ok() +} diff --git a/src/parse/macros/cfg_if.rs b/src/parse/macros/cfg_if.rs index 0b7b6c4d361..495f12c8f5d 100644 --- a/src/parse/macros/cfg_if.rs +++ b/src/parse/macros/cfg_if.rs @@ -1,9 +1,9 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use rustc_ast::ast; -use rustc_ast::token::{Delimiter, TokenKind}; +use rustc_ast::token::TokenKind; use rustc_parse::exp; -use rustc_parse::parser::ForceCollect; +use rustc_parse::parser::{AllowConstBlockItems, ForceCollect}; use rustc_span::symbol::kw; use crate::parse::macros::build_stream_parser; @@ -60,11 +60,9 @@ fn parse_cfg_if_inner<'a>( return Err("Expected an opening brace"); } - while parser.token != TokenKind::CloseDelim(Delimiter::Brace) - && parser.token.kind != TokenKind::Eof - { - let item = match parser.parse_item(ForceCollect::No) { - Ok(Some(item_ptr)) => item_ptr.into_inner(), + while parser.token != TokenKind::CloseBrace && parser.token.kind != TokenKind::Eof { + let item = match parser.parse_item(ForceCollect::No, AllowConstBlockItems::Yes) { + Ok(Some(item_ptr)) => *item_ptr, Ok(None) => continue, Err(err) => { err.cancel(); diff --git a/src/parse/macros/cfg_match.rs b/src/parse/macros/cfg_match.rs index 87071db2749..476289b08b7 100644 --- a/src/parse/macros/cfg_match.rs +++ b/src/parse/macros/cfg_match.rs @@ -1,9 +1,9 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use rustc_ast::ast; -use rustc_ast::token::{Delimiter, TokenKind}; +use rustc_ast::token::TokenKind; use rustc_parse::exp; -use rustc_parse::parser::ForceCollect; +use rustc_parse::parser::{AllowConstBlockItems, ForceCollect}; use crate::parse::macros::build_stream_parser; use crate::parse::session::ParseSess; @@ -26,7 +26,7 @@ fn parse_cfg_match_inner<'a>( let ts = mac.args.tokens.clone(); let mut parser = build_stream_parser(psess.inner(), ts); - if parser.token == TokenKind::OpenDelim(Delimiter::Brace) { + if parser.token == TokenKind::OpenBrace { return Err("Expression position cfg_match! not yet supported"); } @@ -48,11 +48,11 @@ fn parse_cfg_match_inner<'a>( return Err("Expected an opening brace"); } - while parser.token != TokenKind::CloseDelim(Delimiter::Brace) - && parser.token.kind != TokenKind::Eof - { - let item = match parser.parse_item(ForceCollect::No) { - Ok(Some(item_ptr)) => item_ptr.into_inner(), + while parser.token != TokenKind::CloseBrace && parser.token.kind != TokenKind::Eof { + let item = match parser + .parse_item(ForceCollect::No, AllowConstBlockItems::DoesNotMatter) + { + Ok(Some(item_ptr)) => *item_ptr, Ok(None) => continue, Err(err) => { err.cancel(); diff --git a/src/parse/macros/lazy_static.rs b/src/parse/macros/lazy_static.rs index cbe81004e22..8611615d123 100644 --- a/src/parse/macros/lazy_static.rs +++ b/src/parse/macros/lazy_static.rs @@ -1,5 +1,4 @@ use rustc_ast::ast; -use rustc_ast::ptr::P; use rustc_ast::token; use rustc_ast::tokenstream::TokenStream; use rustc_parse::exp; @@ -10,7 +9,7 @@ use crate::rewrite::RewriteContext; pub(crate) fn parse_lazy_static( context: &RewriteContext<'_>, ts: TokenStream, -) -> Option, P)>> { +) -> Option, Box)>> { let mut result = vec![]; let mut parser = super::build_parser(context, ts); macro_rules! parse_or { diff --git a/src/parse/macros/mod.rs b/src/parse/macros/mod.rs index 16313ce65f4..00e0f6f58bd 100644 --- a/src/parse/macros/mod.rs +++ b/src/parse/macros/mod.rs @@ -1,8 +1,8 @@ +use rustc_ast::ast; use rustc_ast::token::{Delimiter, NonterminalKind, NtExprKind::*, NtPatKind::*, TokenKind}; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{ast, ptr}; use rustc_parse::MACRO_ARGUMENTS; -use rustc_parse::parser::{ForceCollect, Parser, Recovery}; +use rustc_parse::parser::{AllowConstBlockItems, ForceCollect, Parser, Recovery}; use rustc_session::parse::ParseSess; use rustc_span::symbol; @@ -49,26 +49,26 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { Expr, NonterminalKind::Expr(Expr), |parser: &mut Parser<'b>| parser.parse_expr(), - |x: ptr::P| Some(x) + |x: Box| Some(x) ); parse_macro_arg!( Ty, NonterminalKind::Ty, |parser: &mut Parser<'b>| parser.parse_ty(), - |x: ptr::P| Some(x) + |x: Box| Some(x) ); parse_macro_arg!( Pat, NonterminalKind::Pat(PatParam { inferred: false }), |parser: &mut Parser<'b>| parser.parse_pat_no_top_alt(None, None), - |x: ptr::P| Some(x) + |x: ast::Pat| Some(Box::new(x)) ); - // `parse_item` returns `Option>`. + // `parse_item` returns `Option>`. parse_macro_arg!( Item, NonterminalKind::Item, - |parser: &mut Parser<'b>| parser.parse_item(ForceCollect::No), - |x: Option>| x + |parser: &mut Parser<'b>| parser.parse_item(ForceCollect::No, AllowConstBlockItems::Yes), + |x: Option>| x ); None @@ -164,7 +164,7 @@ pub(crate) fn parse_macro_args( pub(crate) fn parse_expr( context: &RewriteContext<'_>, tokens: TokenStream, -) -> Option> { +) -> Option> { let mut parser = build_parser(context, tokens); parser.parse_expr().ok() } diff --git a/src/parse/parser.rs b/src/parse/parser.rs index f357aed66c2..63c6c8c99d0 100644 --- a/src/parse/parser.rs +++ b/src/parse/parser.rs @@ -1,8 +1,9 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use std::path::{Path, PathBuf}; -use rustc_ast::{ast, attr, ptr}; +use rustc_ast::{ast, attr}; use rustc_errors::Diag; +use rustc_parse::lexer::StripTokens; use rustc_parse::parser::Parser as RawParser; use rustc_parse::{exp, new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal}; use rustc_span::{Span, sym}; @@ -64,11 +65,14 @@ impl<'a> ParserBuilder<'a> { input: Input, ) -> Result, Vec>> { match input { - Input::File(ref file) => new_parser_from_file(psess, file, None), + Input::File(ref file) => { + new_parser_from_file(psess, file, StripTokens::ShebangAndFrontmatter, None) + } Input::Text(text) => new_parser_from_source_str( psess, rustc_span::FileName::Custom("stdin".to_owned()), text, + StripTokens::ShebangAndFrontmatter, ), } } @@ -102,10 +106,14 @@ impl<'a> Parser<'a> { psess: &'a ParseSess, path: &Path, span: Span, - ) -> Result<(ast::AttrVec, ThinVec>, Span), ParserError> { + ) -> Result<(ast::AttrVec, ThinVec>, Span), ParserError> { let result = catch_unwind(AssertUnwindSafe(|| { - let mut parser = - unwrap_or_emit_fatal(new_parser_from_file(psess.inner(), path, Some(span))); + let mut parser = unwrap_or_emit_fatal(new_parser_from_file( + psess.inner(), + path, + StripTokens::ShebangAndFrontmatter, + Some(span), + )); match parser.parse_mod(exp!(Eof)) { Ok((a, i, spans)) => Some((a, i, spans.inner_span)), Err(e) => { diff --git a/src/parse/session.rs b/src/parse/session.rs index afd847f9515..2a5c8f77642 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -3,9 +3,9 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; 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; +use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter; +use rustc_errors::emitter::{DynEmitter, Emitter, SilentEmitter, stderr_destination}; +use rustc_errors::translation::Translator; use rustc_errors::{ColorConfig, Diag, DiagCtxt, DiagInner, Level as DiagnosticLevel}; use rustc_session::parse::ParseSess as RawParseSess; use rustc_span::{ @@ -40,20 +40,10 @@ struct SilentOnIgnoredFilesEmitter { } impl SilentOnIgnoredFilesEmitter { - fn handle_non_ignoreable_error(&mut self, diag: DiagInner, registry: &Registry) { + fn handle_non_ignoreable_error(&mut self, diag: DiagInner) { self.has_non_ignorable_parser_errors = true; self.can_reset.store(false, Ordering::Release); - self.emitter.emit_diagnostic(diag, registry); - } -} - -impl Translate for SilentOnIgnoredFilesEmitter { - fn fluent_bundle(&self) -> Option<&rustc_errors::FluentBundle> { - self.emitter.fluent_bundle() - } - - fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { - self.emitter.fallback_fluent_bundle() + self.emitter.emit_diagnostic(diag); } } @@ -62,27 +52,31 @@ impl Emitter for SilentOnIgnoredFilesEmitter { None } - fn emit_diagnostic(&mut self, diag: DiagInner, registry: &Registry) { + fn emit_diagnostic(&mut self, diag: DiagInner) { if diag.level() == DiagnosticLevel::Fatal { - return self.handle_non_ignoreable_error(diag, registry); + return self.handle_non_ignoreable_error(diag); } if let Some(primary_span) = &diag.span.primary_span() { let file_name = self.source_map.span_to_filename(*primary_span); - if let rustc_span::FileName::Real(rustc_span::RealFileName::LocalPath(ref path)) = - file_name - { - if self - .ignore_path_set - .is_match(&FileName::Real(path.to_path_buf())) - { - if !self.has_non_ignorable_parser_errors { - self.can_reset.store(true, Ordering::Release); + if let rustc_span::FileName::Real(real) = file_name { + if let Some(path) = real.local_path() { + if self + .ignore_path_set + .is_match(&FileName::Real(path.to_path_buf())) + { + if !self.has_non_ignorable_parser_errors { + self.can_reset.store(true, Ordering::Release); + } + return; } - return; } - }; + } } - self.handle_non_ignoreable_error(diag, registry); + self.handle_non_ignoreable_error(diag); + } + + fn translator(&self) -> &Translator { + self.emitter.translator() } } @@ -110,23 +104,15 @@ fn default_dcx( ColorConfig::Never }; - let fallback_bundle = rustc_errors::fallback_fluent_bundle( - rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(), - false, - ); - let emitter = Box::new( - HumanEmitter::new(stderr_destination(emit_color), fallback_bundle) - .sm(Some(source_map.clone())), - ); - - let emitter: Box = if !show_parse_errors { - Box::new(SilentEmitter { - fatal_emitter: emitter, - fatal_note: None, - emit_fatal_diagnostic: false, - }) + let translator = rustc_driver::default_translator(); + + let emitter: Box = if show_parse_errors { + Box::new( + AnnotateSnippetEmitter::new(stderr_destination(emit_color), translator) + .sm(Some(source_map.clone())), + ) } else { - emitter + Box::new(SilentEmitter { translator }) }; DiagCtxt::new(Box::new(SilentOnIgnoredFilesEmitter { has_non_ignorable_parser_errors: false, @@ -195,7 +181,10 @@ impl ParseSess { self.raw_psess .source_map() .get_source_file(&rustc_span::FileName::Real( - rustc_span::RealFileName::LocalPath(path.to_path_buf()), + self.raw_psess + .source_map() + .path_mapping() + .to_real_filename(self.raw_psess.source_map().working_dir(), path), )) .is_some() } @@ -205,7 +194,7 @@ impl ParseSess { } pub(crate) fn set_silent_emitter(&mut self) { - self.raw_psess.dcx().make_silent(None, false); + self.raw_psess.dcx().make_silent(); } pub(crate) fn span_to_filename(&self, span: Span) -> FileName { @@ -260,10 +249,20 @@ impl ParseSess { ) } - pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option> { + pub(crate) fn get_original_snippet(&self, filename: &FileName) -> Option> { + let rustc_filename = match filename { + FileName::Real(path) => rustc_span::FileName::Real( + self.raw_psess + .source_map() + .path_mapping() + .to_real_filename(self.raw_psess.source_map().working_dir(), path), + ), + FileName::Stdin => rustc_span::FileName::Custom("stdin".to_owned()), + }; + self.raw_psess .source_map() - .get_source_file(&file_name.into()) + .get_source_file(&rustc_filename) .and_then(|source_file| source_file.src.clone()) } } @@ -327,7 +326,7 @@ mod tests { use crate::config::IgnoreList; use crate::utils::mk_sp; use rustc_errors::MultiSpan; - use rustc_span::{FileName as SourceMapFileName, RealFileName}; + use rustc_span::FileName as SourceMapFileName; use std::path::PathBuf; use std::sync::atomic::AtomicU32; @@ -335,28 +334,21 @@ mod tests { num_emitted_errors: Arc, } - impl Translate for TestEmitter { - fn fluent_bundle(&self) -> Option<&rustc_errors::FluentBundle> { - None - } - - fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { - panic!("test emitter attempted to translate a diagnostic"); - } - } - impl Emitter for TestEmitter { fn source_map(&self) -> Option<&SourceMap> { None } - fn emit_diagnostic(&mut self, _diag: DiagInner, _registry: &Registry) { + fn emit_diagnostic(&mut self, _diag: DiagInner) { self.num_emitted_errors.fetch_add(1, Ordering::Release); } + + fn translator(&self) -> &Translator { + panic!("test emitter attempted to translate a diagnostic"); + } } fn build_diagnostic(level: DiagnosticLevel, span: Option) -> DiagInner { - #[allow(rustc::untranslatable_diagnostic)] // no translation needed for empty string let mut diag = DiagInner::new(level, ""); diag.messages.clear(); if let Some(span) = span { @@ -392,6 +384,13 @@ mod tests { .ignore() } + fn filename(sm: &SourceMap, path: &str) -> SourceMapFileName { + SourceMapFileName::Real( + sm.path_mapping() + .to_real_filename(sm.working_dir(), PathBuf::from(path)), + ) + } + #[test] fn handles_fatal_parse_error_in_ignored_file() { let num_emitted_errors = Arc::new(AtomicU32::new(0)); @@ -400,11 +399,7 @@ mod tests { 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( - SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))), - source, - ); - let registry = Registry::new(&[]); + source_map.new_source_file(filename(&source_map, "foo.rs"), source); let mut emitter = build_emitter( Arc::clone(&num_emitted_errors), Arc::clone(&can_reset_errors), @@ -413,7 +408,7 @@ mod tests { ); let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1))); let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, Some(span)); - emitter.emit_diagnostic(fatal_diagnostic, ®istry); + emitter.emit_diagnostic(fatal_diagnostic); assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1); assert_eq!(can_reset_errors.load(Ordering::Acquire), false); } @@ -426,11 +421,7 @@ mod tests { let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#); 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"))), - source, - ); - let registry = Registry::new(&[]); + source_map.new_source_file(filename(&source_map, "foo.rs"), source); let mut emitter = build_emitter( Arc::clone(&num_emitted_errors), Arc::clone(&can_reset_errors), @@ -439,7 +430,7 @@ mod tests { ); let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1))); let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(span)); - emitter.emit_diagnostic(non_fatal_diagnostic, ®istry); + emitter.emit_diagnostic(non_fatal_diagnostic); assert_eq!(num_emitted_errors.load(Ordering::Acquire), 0); assert_eq!(can_reset_errors.load(Ordering::Acquire), true); } @@ -451,11 +442,7 @@ mod tests { 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"))), - source, - ); - let registry = Registry::new(&[]); + source_map.new_source_file(filename(&source_map, "foo.rs"), source); let mut emitter = build_emitter( Arc::clone(&num_emitted_errors), Arc::clone(&can_reset_errors), @@ -464,7 +451,7 @@ mod tests { ); let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1))); let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(span)); - emitter.emit_diagnostic(non_fatal_diagnostic, ®istry); + emitter.emit_diagnostic(non_fatal_diagnostic); assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1); assert_eq!(can_reset_errors.load(Ordering::Acquire), false); } @@ -480,19 +467,9 @@ mod tests { let foo_source = String::from(r#"pub fn foo() { 1x; }"#); let fatal_source = String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#); - source_map.new_source_file( - SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("bar.rs"))), - bar_source, - ); - source_map.new_source_file( - SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))), - foo_source, - ); - source_map.new_source_file( - SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("fatal.rs"))), - fatal_source, - ); - let registry = Registry::new(&[]); + source_map.new_source_file(filename(&source_map, "bar.rs"), bar_source); + source_map.new_source_file(filename(&source_map, "foo.rs"), foo_source); + source_map.new_source_file(filename(&source_map, "fatal.rs"), fatal_source); let mut emitter = build_emitter( Arc::clone(&num_emitted_errors), Arc::clone(&can_reset_errors), @@ -504,9 +481,9 @@ mod tests { let bar_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(bar_span)); let foo_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(foo_span)); let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, None); - emitter.emit_diagnostic(bar_diagnostic, ®istry); - emitter.emit_diagnostic(foo_diagnostic, ®istry); - emitter.emit_diagnostic(fatal_diagnostic, ®istry); + emitter.emit_diagnostic(bar_diagnostic); + emitter.emit_diagnostic(foo_diagnostic); + emitter.emit_diagnostic(fatal_diagnostic); assert_eq!(num_emitted_errors.load(Ordering::Acquire), 2); assert_eq!(can_reset_errors.load(Ordering::Acquire), false); } diff --git a/src/patterns.rs b/src/patterns.rs index 80daad75fec..df2a8dc5c6f 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -1,5 +1,4 @@ use rustc_ast::ast::{self, BindingMode, ByRef, Pat, PatField, PatKind, RangeEnd, RangeSyntax}; -use rustc_ast::ptr; use rustc_span::{BytePos, Span}; use crate::comment::{FindUncommented, combine_strs_with_missing_comments}; @@ -18,7 +17,9 @@ use crate::shape::Shape; use crate::source_map::SpanUtils; use crate::spanned::Spanned; use crate::types::{PathContext, rewrite_path}; -use crate::utils::{format_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident}; +use crate::utils::{ + format_mutability, format_pinnedness_and_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident, +}; /// Returns `true` if the given pattern is "short". /// A short pattern is defined by the following grammar: @@ -42,6 +43,7 @@ pub(crate) fn is_short_pattern( fn is_short_pattern_inner(context: &RewriteContext<'_>, pat: &ast::Pat) -> bool { match &pat.kind { + ast::PatKind::Missing => unreachable!(), ast::PatKind::Rest | ast::PatKind::Never | ast::PatKind::Wild | ast::PatKind::Err(_) => { true } @@ -69,14 +71,14 @@ fn is_short_pattern_inner(context: &RewriteContext<'_>, pat: &ast::Pat) -> bool } ast::PatKind::Box(ref p) | PatKind::Deref(ref p) - | ast::PatKind::Ref(ref p, _) + | ast::PatKind::Ref(ref 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)), } } pub(crate) struct RangeOperand<'a, T> { - pub operand: &'a Option>, + pub operand: &'a Option>, pub span: Span, } @@ -100,6 +102,7 @@ impl Rewrite for Pat { fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { match self.kind { + PatKind::Missing => unreachable!(), PatKind::Or(ref pats) => { let pat_strs = pats .iter() @@ -132,9 +135,13 @@ impl Rewrite for Pat { PatKind::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => { let mut_prefix = format_mutability(mutability).trim(); - let (ref_kw, mut_infix) = match by_ref { - ByRef::Yes(rmutbl) => ("ref", format_mutability(rmutbl).trim()), - ByRef::No => ("", ""), + let (ref_kw, pin_infix, mut_infix) = match by_ref { + ByRef::Yes(pinnedness, rmutbl) => { + let (pin_infix, mut_infix) = + format_pinnedness_and_mutability(pinnedness, rmutbl); + ("ref", pin_infix.trim(), mut_infix.trim()) + } + ByRef::No => ("", "", ""), }; let id_str = rewrite_ident(context, ident); let sub_pat = match *sub_pat { @@ -145,6 +152,7 @@ impl Rewrite for Pat { .checked_sub( mut_prefix.len() + ref_kw.len() + + pin_infix.len() + mut_infix.len() + id_str.len() + 2, @@ -191,18 +199,17 @@ impl Rewrite for Pat { (true, true) => (self.span.lo(), "".to_owned()), }; - // combine result of above and mut - let (second_lo, second) = match (first.is_empty(), mut_infix.is_empty()) { + // combine result of above and pin + let (second_lo, second) = match (first.is_empty(), pin_infix.is_empty()) { (false, false) => { let lo = context.snippet_provider.span_after(self.span, "ref"); - let end_span = mk_sp(first_lo, self.span.hi()); - let hi = context.snippet_provider.span_before(end_span, "mut"); + let hi = context.snippet_provider.span_before(self.span, "pin"); ( - context.snippet_provider.span_after(end_span, "mut"), + context.snippet_provider.span_after(self.span, "pin"), combine_strs_with_missing_comments( context, &first, - mut_infix, + pin_infix, mk_sp(lo, hi), shape, true, @@ -210,7 +217,33 @@ impl Rewrite for Pat { ) } (false, true) => (first_lo, first), - (true, false) => unreachable!("mut_infix necessarily follows a ref"), + (true, false) => unreachable!("pin_infix necessarily follows a ref"), + (true, true) => (self.span.lo(), "".to_owned()), + }; + + // combine result of above and const|mut + let (third_lo, third) = match (second.is_empty(), mut_infix.is_empty()) { + (false, false) => { + let lo = context.snippet_provider.span_after( + self.span, + if pin_infix.is_empty() { "ref" } else { "pin" }, + ); + let end_span = mk_sp(second_lo, self.span.hi()); + let hi = context.snippet_provider.span_before(end_span, mut_infix); + ( + context.snippet_provider.span_after(end_span, mut_infix), + combine_strs_with_missing_comments( + context, + &second, + mut_infix, + mk_sp(lo, hi), + shape, + true, + )?, + ) + } + (false, true) => (second_lo, second), + (true, false) => unreachable!("mut_infix necessarily follows a pin or ref"), (true, true) => (self.span.lo(), "".to_owned()), }; @@ -230,9 +263,9 @@ impl Rewrite for Pat { combine_strs_with_missing_comments( context, - &second, + &third, &next, - mk_sp(second_lo, ident.span.lo()), + mk_sp(third_lo, ident.span.lo()), shape, true, ) @@ -261,8 +294,10 @@ impl Rewrite for Pat { PatKind::Range(ref lhs, ref rhs, ref end_kind) => { rewrite_range_pat(context, shape, lhs, rhs, end_kind, self.span) } - PatKind::Ref(ref pat, mutability) => { - let prefix = format!("&{}", format_mutability(mutability)); + PatKind::Ref(ref pat, pinnedness, mutability) => { + let (pin_prefix, mut_prefix) = + format_pinnedness_and_mutability(pinnedness, mutability); + let prefix = format!("&{}{}", pin_prefix, mut_prefix); rewrite_unary_prefix(context, &prefix, &**pat, shape) } PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape), @@ -302,7 +337,7 @@ impl Rewrite for Pat { qself, path, fields, - rest == ast::PatFieldsRest::Rest, + matches!(rest, ast::PatFieldsRest::Rest(_)), self.span, context, shape, @@ -324,8 +359,8 @@ impl Rewrite for Pat { pub(crate) fn rewrite_range_pat( context: &RewriteContext<'_>, shape: Shape, - lhs: &Option>, - rhs: &Option>, + lhs: &Option>, + rhs: &Option>, end_kind: &rustc_span::source_map::Spanned, span: Span, ) -> RewriteResult { @@ -366,7 +401,7 @@ pub(crate) fn rewrite_range_pat( } fn rewrite_struct_pat( - qself: &Option>, + qself: &Option>, path: &ast::Path, fields: &[ast::PatField], ellipsis: bool, @@ -504,7 +539,7 @@ impl Rewrite for PatField { #[derive(Debug)] pub(crate) enum TuplePatField<'a> { - Pat(&'a ptr::P), + Pat(&'a ast::Pat), Dotdot(Span), } @@ -550,7 +585,7 @@ pub(crate) fn can_be_overflowed_pat( | ast::PatKind::Tuple(..) | ast::PatKind::Struct(..) | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1, - ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => { + ast::PatKind::Ref(ref p, _, _) | ast::PatKind::Box(ref p) => { can_be_overflowed_pat(context, &TuplePatField::Pat(p), len) } ast::PatKind::Expr(ref expr) => can_be_overflowed_expr(context, expr, len), @@ -561,7 +596,7 @@ pub(crate) fn can_be_overflowed_pat( } fn rewrite_tuple_pat( - pats: &[ptr::P], + pats: &[ast::Pat], path_str: Option, span: Span, context: &RewriteContext<'_>, diff --git a/src/rewrite.rs b/src/rewrite.rs index dbe1cb44d6c..96dc4d449c9 100644 --- a/src/rewrite.rs +++ b/src/rewrite.rs @@ -3,7 +3,6 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; -use rustc_ast::ptr; use rustc_span::Span; use thiserror::Error; @@ -24,7 +23,7 @@ pub(crate) trait Rewrite { } } -impl Rewrite for ptr::P { +impl Rewrite for Box { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { (**self).rewrite(context, shape) } diff --git a/src/source_file.rs b/src/source_file.rs index e942058a0a8..b0ec24f3db6 100644 --- a/src/source_file.rs +++ b/src/source_file.rs @@ -65,18 +65,6 @@ where } } - #[allow(non_local_definitions)] - impl From<&FileName> for rustc_span::FileName { - fn from(filename: &FileName) -> rustc_span::FileName { - match filename { - FileName::Real(path) => { - rustc_span::FileName::Real(rustc_span::RealFileName::LocalPath(path.to_owned())) - } - FileName::Stdin => rustc_span::FileName::Custom("stdin".to_owned()), - } - } - } - // SourceFile's in the SourceMap will always have Unix-style line endings // See: https://github.com/rust-lang/rustfmt/issues/3850 // So if the user has explicitly overridden the rustfmt `newline_style` diff --git a/src/spanned.rs b/src/spanned.rs index 507647566d4..020651e2daa 100644 --- a/src/spanned.rs +++ b/src/spanned.rs @@ -1,6 +1,6 @@ use std::cmp::max; -use rustc_ast::{ast, ptr}; +use rustc_ast::ast; use rustc_span::{Span, source_map}; use crate::macros::MacroArg; @@ -12,7 +12,7 @@ pub(crate) trait Spanned { fn span(&self) -> Span; } -impl Spanned for ptr::P { +impl Spanned for Box { fn span(&self) -> Span { (**self).span() } @@ -122,7 +122,7 @@ impl Spanned for ast::GenericParam { fn span(&self) -> Span { let lo = match self.kind { _ if !self.attrs.is_empty() => self.attrs[0].span.lo(), - ast::GenericParamKind::Const { kw_span, .. } => kw_span.lo(), + ast::GenericParamKind::Const { span, .. } => span.lo(), _ => self.ident.span.lo(), }; let hi = if self.bounds.is_empty() { diff --git a/src/types.rs b/src/types.rs index 713066f20b0..94ed42c6ea5 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,7 +1,6 @@ use std::ops::Deref; use rustc_ast::ast::{self, FnRetTy, Mutability, Term}; -use rustc_ast::ptr; use rustc_span::{BytePos, Pos, Span, symbol::kw}; use tracing::debug; @@ -9,8 +8,7 @@ use crate::comment::{combine_strs_with_missing_comments, contains_comment}; use crate::config::lists::*; use crate::config::{IndentStyle, StyleEdition, TypeDensity}; use crate::expr::{ - ExprType, RhsAssignKind, format_expr, rewrite_assign_rhs, rewrite_call, rewrite_tuple, - rewrite_unary_prefix, + ExprType, RhsAssignKind, format_expr, rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix, }; use crate::lists::{ ListFormatting, ListItem, Separator, definitive_tactic, itemize_list, write_list, @@ -39,7 +37,7 @@ pub(crate) enum PathContext { pub(crate) fn rewrite_path( context: &RewriteContext<'_>, path_context: PathContext, - qself: &Option>, + qself: &Option>, path: &ast::Path, shape: Shape, ) -> RewriteResult { @@ -685,7 +683,7 @@ impl Rewrite for ast::GenericParam { let param_start = if let ast::GenericParamKind::Const { ref ty, - kw_span, + span, default, } = &self.kind { @@ -707,7 +705,7 @@ impl Rewrite for ast::GenericParam { default.rewrite_result(context, Shape::legacy(budget, shape.indent))?; param.push_str(&rewrite); } - kw_span.lo() + span.lo() } else { param.push_str(rewrite_ident(context, self.ident)); self.ident.span.lo() @@ -825,10 +823,6 @@ impl Rewrite for ast::Ty { let shape = shape.offset_left(4, self.span())?; (shape, "dyn ") } - ast::TraitObjectSyntax::DynStar => { - let shape = shape.offset_left(5, self.span())?; - (shape, "dyn* ") - } ast::TraitObjectSyntax::None => (shape, ""), }; let mut res = bounds.rewrite_result(context, shape)?; @@ -1003,7 +997,7 @@ impl Rewrite for ast::Ty { }) } } - ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape), + ast::TyKind::FnPtr(ref fn_ptr) => rewrite_fn_ptr(fn_ptr, self.span, context, shape), ast::TyKind::Never => Ok(String::from("!")), ast::TyKind::MacCall(ref mac) => { rewrite_macro(mac, context, shape, MacroPosition::Expression) @@ -1031,13 +1025,6 @@ impl Rewrite for ast::Ty { } ast::TyKind::CVarArgs => Ok("...".to_owned()), ast::TyKind::Dummy | ast::TyKind::Err(_) => Ok(context.snippet(self.span).to_owned()), - ast::TyKind::Typeof(ref anon_const) => rewrite_call( - context, - "typeof", - &[anon_const.value.clone()], - self.span, - shape, - ), ast::TyKind::Pat(ref ty, ref pat) => { let ty = ty.rewrite_result(context, shape)?; let pat = pat.rewrite_result(context, shape)?; @@ -1083,13 +1070,26 @@ impl Rewrite for ast::TyPat { 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), + ast::TyPatKind::Or(ref variants) => { + let mut first = true; + let mut s = String::new(); + for variant in variants { + if first { + first = false + } else { + s.push_str(" | "); + } + s.push_str(&variant.rewrite_result(context, shape)?); + } + Ok(s) + } + ast::TyPatKind::NotNull | ast::TyPatKind::Err(_) => Err(RewriteError::Unknown), } } } -fn rewrite_bare_fn( - bare_fn: &ast::BareFnTy, +fn rewrite_fn_ptr( + fn_ptr: &ast::FnPtrTy, span: Span, context: &RewriteContext<'_>, shape: Shape, @@ -1098,7 +1098,7 @@ fn rewrite_bare_fn( let mut result = String::with_capacity(128); - if let Some(ref lifetime_str) = rewrite_bound_params(context, shape, &bare_fn.generic_params) { + if let Some(ref lifetime_str) = rewrite_bound_params(context, shape, &fn_ptr.generic_params) { result.push_str("for<"); // 6 = "for<> ".len(), 4 = "for<". // This doesn't work out so nicely for multiline situation with lots of @@ -1107,10 +1107,10 @@ fn rewrite_bare_fn( result.push_str("> "); } - result.push_str(crate::utils::format_safety(bare_fn.safety)); + result.push_str(crate::utils::format_safety(fn_ptr.safety)); result.push_str(&format_extern( - bare_fn.ext, + fn_ptr.ext, context.config.force_explicit_abi(), )); @@ -1125,9 +1125,9 @@ fn rewrite_bare_fn( }; let rewrite = format_function_type( - bare_fn.decl.inputs.iter(), - &bare_fn.decl.output, - bare_fn.decl.c_variadic(), + fn_ptr.decl.inputs.iter(), + &fn_ptr.decl.output, + fn_ptr.decl.c_variadic(), span, context, func_ty_shape, @@ -1320,7 +1320,7 @@ fn join_bounds_inner( } } -pub(crate) fn opaque_ty(ty: &Option>) -> Option<&ast::GenericBounds> { +pub(crate) fn opaque_ty(ty: &Option>) -> Option<&ast::GenericBounds> { ty.as_ref().and_then(|t| match &t.kind { ast::TyKind::ImplTrait(_, bounds) => Some(bounds), _ => None, diff --git a/src/utils.rs b/src/utils.rs index fcd475b1784..b676803379f 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,10 +1,10 @@ use std::borrow::Cow; +use rustc_ast::YieldKind; use rustc_ast::ast::{ self, Attribute, MetaItem, MetaItemInner, MetaItemKind, NodeId, Path, Visibility, VisibilityKind, }; -use rustc_ast::{YieldKind, ptr}; use rustc_ast_pretty::pprust; use rustc_span::{BytePos, LocalExpnId, Span, Symbol, SyntaxContext, sym, symbol}; use unicode_width::UnicodeWidthStr; @@ -102,8 +102,9 @@ pub(crate) fn format_constness_right(constness: ast::Const) -> &'static str { #[inline] pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str { match defaultness { + ast::Defaultness::Implicit => "", ast::Defaultness::Default(..) => "default ", - ast::Defaultness::Final => "", + ast::Defaultness::Final(..) => "final ", } } @@ -132,6 +133,19 @@ pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str { } } +#[inline] +pub(crate) fn format_pinnedness_and_mutability( + pinnedness: ast::Pinnedness, + mutability: ast::Mutability, +) -> (&'static str, &'static str) { + match (pinnedness, mutability) { + (ast::Pinnedness::Pinned, ast::Mutability::Mut) => ("pin ", "mut "), + (ast::Pinnedness::Pinned, ast::Mutability::Not) => ("pin ", "const "), + (ast::Pinnedness::Not, ast::Mutability::Mut) => ("", "mut "), + (ast::Pinnedness::Not, ast::Mutability::Not) => ("", ""), + } +} + #[inline] pub(crate) fn format_extern(ext: ast::Extern, explicit_abi: bool) -> Cow<'static, str> { match ext { @@ -149,8 +163,8 @@ pub(crate) fn format_extern(ext: ast::Extern, explicit_abi: bool) -> Cow<'static } #[inline] -// Transform `Vec>` into `Vec<&T>` -pub(crate) fn ptr_vec_to_ref_vec(vec: &[ptr::P]) -> Vec<&T> { +// Transform `Vec>` into `Vec<&T>` +pub(crate) fn ptr_vec_to_ref_vec(vec: &[Box]) -> Vec<&T> { vec.iter().map(|x| &**x).collect::>() } diff --git a/src/visitor.rs b/src/visitor.rs index 79a231bfe11..6048084c8da 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -6,7 +6,10 @@ use rustc_ast::{ast, token::Delimiter, visit}; use rustc_span::{BytePos, Ident, Pos, Span, symbol}; use tracing::debug; -use crate::comment::{CodeCharKind, CommentCodeSlices, contains_comment, rewrite_comment}; +use crate::attr::*; +use crate::comment::{ + CodeCharKind, CommentCodeSlices, contains_comment, recover_comment_removed, rewrite_comment, +}; use crate::config::{BraceStyle, Config, MacroSelector, StyleEdition}; use crate::coverage::transform_missing_snippet; use crate::items::{ @@ -26,8 +29,7 @@ use crate::utils::{ self, contains_skip, count_newlines, depr_skip_annotation, format_safety, inner_attributes, last_line_width, mk_sp, ptr_vec_to_ref_vec, rewrite_ident, starts_with_newline, }; -use crate::{Edition, attr::*}; -use crate::{ErrorKind, FormatReport, FormattingError}; +use crate::{Edition, ErrorKind, FormatReport, FormattingError}; /// Creates a string slice corresponding to the specified span. pub(crate) struct SnippetProvider { @@ -497,16 +499,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.with_context(|ctx| format_trait(ctx, item, trait_kind, block_indent)); self.push_rewrite(item.span, rw.ok()); } - ast::ItemKind::TraitAlias(ident, ref generics, ref generic_bounds) => { + ast::ItemKind::TraitAlias(ref ta) => { let shape = Shape::indented(self.block_indent, self.config); - let rw = format_trait_alias( - &self.get_context(), - ident, - item, - generics, - generic_bounds, - shape, - ); + let rw = + format_trait_alias(&self.get_context(), ta, &item.vis, item.span, shape); self.push_rewrite(item.span, rw.ok()); } ast::ItemKind::ExternCrate(..) => { @@ -521,7 +517,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => { self.visit_struct(&StructParts::from_item(item)); } - ast::ItemKind::Enum(ident, ref def, ref generics) => { + ast::ItemKind::Enum(ident, ref generics, ref def) => { self.format_missing_with_indent(source!(self, item.span).lo()); self.visit_enum(ident, &item.vis, def, generics, item.span); self.last_pos = source!(self, item.span).hi(); @@ -540,6 +536,28 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => { self.visit_static(&StaticParts::from_item(item)); } + ast::ItemKind::ConstBlock(ast::ConstBlockItem { + id: _, + span, + ref block, + }) => { + let context = &self.get_context(); + let offset = self.block_indent; + self.push_rewrite( + item.span, + block + .rewrite( + context, + Shape::legacy( + context.budget(offset.block_indent), + offset.block_only(), + ), + ) + .map(|rhs| { + recover_comment_removed(format!("const {rhs}"), span, context) + }), + ); + } ast::ItemKind::Fn(ref fn_kind) => { let ast::Fn { defaultness, @@ -566,7 +584,15 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } else { let indent = self.block_indent; let rewrite = self - .rewrite_required_fn(indent, ident, sig, &item.vis, generics, item.span) + .rewrite_required_fn( + indent, + ident, + sig, + &item.vis, + generics, + defaultness, + item.span, + ) .ok(); self.push_rewrite(item.span, rewrite); } @@ -669,7 +695,15 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } else { let indent = self.block_indent; let rewrite = self - .rewrite_required_fn(indent, fn_kind.ident, sig, &ai.vis, generics, ai.span) + .rewrite_required_fn( + indent, + fn_kind.ident, + sig, + &ai.vis, + generics, + defaultness, + ai.span, + ) .ok(); self.push_rewrite(ai.span, rewrite); } @@ -875,7 +909,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { !is_skip_attr(segments) } - fn walk_mod_items(&mut self, items: &[rustc_ast::ptr::P]) { + fn walk_mod_items(&mut self, items: &[Box]) { self.visit_items_with_reordering(&ptr_vec_to_ref_vec(items)); } @@ -943,7 +977,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let ident_str = rewrite_ident(&self.get_context(), ident).to_owned(); self.push_str(&ident_str); - if let ast::ModKind::Loaded(ref items, ast::Inline::Yes, ref spans, _) = mod_kind { + if let ast::ModKind::Loaded(ref items, ast::Inline::Yes, ref spans) = mod_kind { let ast::ModSpans { inner_span, inject_use_span: _, diff --git a/tests/rustfmt/main.rs b/tests/rustfmt/main.rs index 3653166f3a9..4008c8d1435 100644 --- a/tests/rustfmt/main.rs +++ b/tests/rustfmt/main.rs @@ -195,10 +195,11 @@ fn dont_emit_ICE() { "tests/target/issue-6105.rs", ]; + let panic_re = regex::Regex::new("thread.*panicked").unwrap(); for file in files { let args = [file]; let (_stdout, stderr) = rustfmt(&args); - assert!(!stderr.contains("thread 'main' panicked")); + assert!(!panic_re.is_match(&stderr)); } } diff --git a/tests/source/cfg_if/detect/os/x86.rs b/tests/source/cfg_if/detect/os/x86.rs index b9adc67221a..8b45a5bbd26 100644 --- a/tests/source/cfg_if/detect/os/x86.rs +++ b/tests/source/cfg_if/detect/os/x86.rs @@ -66,13 +66,13 @@ fn detect_features() -> cache::Initializer { ecx: proc_info_ecx, edx: proc_info_edx, .. - } = unsafe { __cpuid(0x0000_0001_u32) }; + } = __cpuid(0x0000_0001_u32); // EAX = 7, ECX = 0: Queries "Extended Features"; // Contains information about bmi,bmi2, and avx2 support. let (extended_features_ebx, extended_features_ecx) = if max_basic_leaf >= 7 { - let CpuidResult { ebx, ecx, .. } = unsafe { __cpuid(0x0000_0007_u32) }; + let CpuidResult { ebx, ecx, .. } = __cpuid(0x0000_0007_u32); (ebx, ecx) } else { (0, 0) // CPUID does not support "Extended Features" @@ -84,12 +84,12 @@ fn detect_features() -> cache::Initializer { let CpuidResult { eax: extended_max_basic_leaf, .. - } = unsafe { __cpuid(0x8000_0000_u32) }; + } = __cpuid(0x8000_0000_u32); // EAX = 0x8000_0001, ECX=0: Queries "Extended Processor Info and Feature // Bits" let extended_proc_info_ecx = if extended_max_basic_leaf >= 1 { - let CpuidResult { ecx, .. } = unsafe { __cpuid(0x8000_0001_u32) }; + let CpuidResult { ecx, .. } = __cpuid(0x8000_0001_u32); ecx } else { 0 @@ -182,7 +182,7 @@ fn detect_features() -> cache::Initializer { let CpuidResult { eax: proc_extended_state1_eax, .. - } = unsafe { __cpuid_count(0xd_u32, 1) }; + } = __cpuid_count(0xd_u32, 1); enable(proc_extended_state1_eax, 0, Feature::xsaveopt); enable(proc_extended_state1_eax, 1, Feature::xsavec); enable(proc_extended_state1_eax, 3, Feature::xsaves); diff --git a/tests/source/const-block-items.rs b/tests/source/const-block-items.rs new file mode 100644 index 00000000000..f30f0fe256a --- /dev/null +++ b/tests/source/const-block-items.rs @@ -0,0 +1,24 @@ +#![feature(const_block_items)] + + const { + + + assert!(true) + } + + #[cfg(false)] const { assert!(false) } + + + #[cfg(false)] +// foo + const + + { + // bar + assert!(false) + // baz + } // 123 + + + #[expect(unused)] +pub const { let a = 1; assert!(true); } diff --git a/tests/source/const_trait.rs b/tests/source/const_trait.rs new file mode 100644 index 00000000000..99414a74f25 --- /dev/null +++ b/tests/source/const_trait.rs @@ -0,0 +1,14 @@ +#![feature(trait_alias, const_trait_impl)] + +const trait Bar {} + +const trait Foo = Bar; + +impl const Bar for () {} + +// const impl gets reformatted to impl const.. for now +const impl Bar for u8 {} + +struct X; + +const impl X {} diff --git a/tests/source/frontmatter_compact.rs b/tests/source/frontmatter_compact.rs new file mode 100644 index 00000000000..21d4c6f4b61 --- /dev/null +++ b/tests/source/frontmatter_compact.rs @@ -0,0 +1,8 @@ +#!/usr/bin/env cargo +---identifier +[dependencies] +regex = "1" +--- +#![feature(frontmatter)] + +fn main() {} diff --git a/tests/source/frontmatter_escaped.rs b/tests/source/frontmatter_escaped.rs new file mode 100644 index 00000000000..0d026377566 --- /dev/null +++ b/tests/source/frontmatter_escaped.rs @@ -0,0 +1,13 @@ +#!/usr/bin/env cargo +------------ +package.description = """ +Header +----- + +Body +""" +------------ + +#![feature(frontmatter)] + +fn main() {} diff --git a/tests/source/frontmatter_spaced.rs b/tests/source/frontmatter_spaced.rs new file mode 100644 index 00000000000..ee0bb81705c --- /dev/null +++ b/tests/source/frontmatter_spaced.rs @@ -0,0 +1,16 @@ +#!/usr/bin/env cargo + + +--- identifier +[dependencies] +regex = "1" + +--- + + + + + +#![feature(frontmatter)] + +fn main() {} diff --git a/tests/source/issue-6788.rs b/tests/source/issue-6788.rs new file mode 100644 index 00000000000..0e63ab53a1a --- /dev/null +++ b/tests/source/issue-6788.rs @@ -0,0 +1,7 @@ +fn foo() { + let a = [(); const { let x = 1; x }]; +} + +fn foo() { + let x = [(); const { 1 }]; +} diff --git a/tests/source/let_chains.rs b/tests/source/let_chains.rs index 0c4d8aa85ea..fc2a9310569 100644 --- a/tests/source/let_chains.rs +++ b/tests/source/let_chains.rs @@ -1,3 +1,5 @@ +// rustfmt-edition: 2024 + fn main() { if let x = x && x {} diff --git a/tests/source/negative-impl.rs b/tests/source/negative-impl.rs index da242d4f3dc..e8f9508e656 100644 --- a/tests/source/negative-impl.rs +++ b/tests/source/negative-impl.rs @@ -1,7 +1,3 @@ impl ! Display for JoinHandle { } -impl ! Box < JoinHandle > { } - impl ! std :: fmt :: Display for JoinHandle < T : std :: future :: Future + std :: marker :: Send + std :: marker :: Sync > { } - -impl ! JoinHandle < T : std :: future :: Future < Output > + std :: marker :: Send + std :: marker :: Sync + 'static > + 'static { } diff --git a/tests/source/pin_sugar.rs b/tests/source/pin_sugar.rs index 370dfbc196a..5f52e244926 100644 --- a/tests/source/pin_sugar.rs +++ b/tests/source/pin_sugar.rs @@ -18,3 +18,32 @@ impl Foo { mut self) {} fn i(&pin mut self) {} } + +fn borrows() { + let mut foo = 0_i32; + let x: Pin<&mut _> = & pin + mut foo; + + let x: Pin<&_> = & + pin const + foo; +} + +fn patterns<'a>( + &pin mut x: &pin + mut + i32, + & + pin + const + y: & + 'a pin + const + i32, + ref pin mut z: i32, + mut + ref + pin + const + w: i32, +) {} diff --git a/tests/source/trait.rs b/tests/source/trait.rs index b6db9e1590d..1970646f777 100644 --- a/tests/source/trait.rs +++ b/tests/source/trait.rs @@ -181,3 +181,5 @@ trait Visible { pub fn f(); pub fn g() {} } + +const trait Foomp = Hash; \ No newline at end of file diff --git a/tests/source/try_block.rs b/tests/source/try_block.rs index 2e8d61f7e66..e324a133175 100644 --- a/tests/source/try_block.rs +++ b/tests/source/try_block.rs @@ -1,4 +1,5 @@ // rustfmt-edition: 2018 +#![feature(try_blocks)] fn main() -> Result<(), !> { let _x: Option<_> = try { diff --git a/tests/source/try_blocks_heterogeneous.rs b/tests/source/try_blocks_heterogeneous.rs new file mode 100644 index 00000000000..7a1135cfbc7 --- /dev/null +++ b/tests/source/try_blocks_heterogeneous.rs @@ -0,0 +1,39 @@ +// rustfmt-edition: 2018 +#![feature(try_blocks_heterogeneous)] + +fn main() -> Result<(), !> { + let _x = try bikeshed Option<_> { + 4 + }; + + try bikeshed Result<_, _> {} +} + +fn baz() -> Option { + if (1 == 1) { + return try bikeshed Option { + 5 + }; + } + + // test + let x = try bikeshed Option<()> { + // try blocks are great + }; + + let y = try bikeshed Option { + 6 + }; // comment + + let x = try /* Invisible comment */ bikeshed Option<()> {}; + let x = try bikeshed /* Invisible comment */ Option<()> {}; + let x = try bikeshed Option<()> /* Invisible comment */ {}; + + let x = try bikeshed Option { baz()?; baz()?; baz()?; 7 }; + + let x = try bikeshed Foo { 1 + 1 + 1 }; + + let x = try bikeshed Foo {}; + + return None; +} diff --git a/tests/source/type.rs b/tests/source/type.rs index 7a232f85198..09ec22cf8d1 100644 --- a/tests/source/type.rs +++ b/tests/source/type.rs @@ -142,25 +142,19 @@ type MyFn = fn(a: SomeLongComplexType, b: SomeOtherLongComplexType,) -> Box() -> i32 { ::CONST } +const fn not_quite_const() -> i32 { ::CONST } -impl ~ const T {} +impl const T for U {} -fn apit(_: impl ~ const T) {} +fn apit(_: impl [ const ] T) {} -fn rpit() -> impl ~ const T { S } +fn rpit() -> impl [ const] T { S } pub struct Foo(T); -impl Foo { +impl Foo { fn new(t: T) -> Self { Self(t) } } - -// #4357 -type T = typeof( -1); -impl T for .. { -} diff --git a/tests/target/cfg_if/detect/os/x86.rs b/tests/target/cfg_if/detect/os/x86.rs index 944b51615f8..fb7136d8391 100644 --- a/tests/target/cfg_if/detect/os/x86.rs +++ b/tests/target/cfg_if/detect/os/x86.rs @@ -66,12 +66,12 @@ fn detect_features() -> cache::Initializer { ecx: proc_info_ecx, edx: proc_info_edx, .. - } = unsafe { __cpuid(0x0000_0001_u32) }; + } = __cpuid(0x0000_0001_u32); // EAX = 7, ECX = 0: Queries "Extended Features"; // Contains information about bmi,bmi2, and avx2 support. let (extended_features_ebx, extended_features_ecx) = if max_basic_leaf >= 7 { - let CpuidResult { ebx, ecx, .. } = unsafe { __cpuid(0x0000_0007_u32) }; + let CpuidResult { ebx, ecx, .. } = __cpuid(0x0000_0007_u32); (ebx, ecx) } else { (0, 0) // CPUID does not support "Extended Features" @@ -83,12 +83,12 @@ fn detect_features() -> cache::Initializer { let CpuidResult { eax: extended_max_basic_leaf, .. - } = unsafe { __cpuid(0x8000_0000_u32) }; + } = __cpuid(0x8000_0000_u32); // EAX = 0x8000_0001, ECX=0: Queries "Extended Processor Info and Feature // Bits" let extended_proc_info_ecx = if extended_max_basic_leaf >= 1 { - let CpuidResult { ecx, .. } = unsafe { __cpuid(0x8000_0001_u32) }; + let CpuidResult { ecx, .. } = __cpuid(0x8000_0001_u32); ecx } else { 0 @@ -181,7 +181,7 @@ fn detect_features() -> cache::Initializer { let CpuidResult { eax: proc_extended_state1_eax, .. - } = unsafe { __cpuid_count(0xd_u32, 1) }; + } = __cpuid_count(0xd_u32, 1); enable(proc_extended_state1_eax, 0, Feature::xsaveopt); enable(proc_extended_state1_eax, 1, Feature::xsavec); enable(proc_extended_state1_eax, 3, Feature::xsaves); diff --git a/tests/target/const-block-items.rs b/tests/target/const-block-items.rs new file mode 100644 index 00000000000..bbf6dbf481c --- /dev/null +++ b/tests/target/const-block-items.rs @@ -0,0 +1,20 @@ +#![feature(const_block_items)] + +const { assert!(true) } + +#[cfg(false)] +const { assert!(false) } + +#[cfg(false)] +// foo +const { + // bar + assert!(false) + // baz +} // 123 + +#[expect(unused)] +const { + let a = 1; + assert!(true); +} diff --git a/tests/target/const_trait.rs b/tests/target/const_trait.rs new file mode 100644 index 00000000000..337a4cf4140 --- /dev/null +++ b/tests/target/const_trait.rs @@ -0,0 +1,14 @@ +#![feature(trait_alias, const_trait_impl)] + +const trait Bar {} + +const trait Foo = Bar; + +impl const Bar for () {} + +// const impl gets reformatted to impl const.. for now +impl const Bar for u8 {} + +struct X; + +const impl X {} diff --git a/tests/target/final-kw.rs b/tests/target/final-kw.rs new file mode 100644 index 00000000000..d68b6908d76 --- /dev/null +++ b/tests/target/final-kw.rs @@ -0,0 +1,5 @@ +trait Foo { + final fn final_() {} + + fn not_final() {} +} diff --git a/tests/target/frontmatter_compact.rs b/tests/target/frontmatter_compact.rs new file mode 100644 index 00000000000..21d4c6f4b61 --- /dev/null +++ b/tests/target/frontmatter_compact.rs @@ -0,0 +1,8 @@ +#!/usr/bin/env cargo +---identifier +[dependencies] +regex = "1" +--- +#![feature(frontmatter)] + +fn main() {} diff --git a/tests/target/frontmatter_escaped.rs b/tests/target/frontmatter_escaped.rs new file mode 100644 index 00000000000..0d026377566 --- /dev/null +++ b/tests/target/frontmatter_escaped.rs @@ -0,0 +1,13 @@ +#!/usr/bin/env cargo +------------ +package.description = """ +Header +----- + +Body +""" +------------ + +#![feature(frontmatter)] + +fn main() {} diff --git a/tests/target/frontmatter_spaced.rs b/tests/target/frontmatter_spaced.rs new file mode 100644 index 00000000000..ee0bb81705c --- /dev/null +++ b/tests/target/frontmatter_spaced.rs @@ -0,0 +1,16 @@ +#!/usr/bin/env cargo + + +--- identifier +[dependencies] +regex = "1" + +--- + + + + + +#![feature(frontmatter)] + +fn main() {} diff --git a/tests/target/issue-6788.rs b/tests/target/issue-6788.rs new file mode 100644 index 00000000000..c559438b2d5 --- /dev/null +++ b/tests/target/issue-6788.rs @@ -0,0 +1,10 @@ +fn foo() { + let a = [(); const { + let x = 1; + x + }]; +} + +fn foo() { + let x = [(); const { 1 }]; +} diff --git a/tests/target/issue_5542.rs b/tests/target/issue_5542.rs deleted file mode 100644 index 730bb7b681a..00000000000 --- a/tests/target/issue_5542.rs +++ /dev/null @@ -1,10 +0,0 @@ -#![feature(dyn_star)] -#![allow(incomplete_features)] - -use core::fmt::Debug; - -fn main() { - let i = 42; - let dyn_i = i as dyn* Debug; - dbg!(dyn_i); -} diff --git a/tests/target/let_chains.rs b/tests/target/let_chains.rs index 204937b4cac..4fd6048d914 100644 --- a/tests/target/let_chains.rs +++ b/tests/target/let_chains.rs @@ -1,3 +1,5 @@ +// rustfmt-edition: 2024 + fn main() { if let x = x && x diff --git a/tests/target/negative-impl.rs b/tests/target/negative-impl.rs index 16ce7e26a99..bb53048dbc6 100644 --- a/tests/target/negative-impl.rs +++ b/tests/target/negative-impl.rs @@ -1,14 +1,6 @@ impl !Display for JoinHandle {} -impl !Box {} - impl !std::fmt::Display for JoinHandle { } - -impl - !JoinHandle + std::marker::Send + std::marker::Sync + 'static> - + 'static -{ -} diff --git a/tests/target/pin_sugar.rs b/tests/target/pin_sugar.rs index 7d04efb1b32..f366ab4da95 100644 --- a/tests/target/pin_sugar.rs +++ b/tests/target/pin_sugar.rs @@ -16,3 +16,18 @@ impl Foo { fn h<'a>(&'a pin mut self) {} fn i(&pin mut self) {} } + +fn borrows() { + let mut foo = 0_i32; + let x: Pin<&mut _> = &pin mut foo; + + let x: Pin<&_> = &pin const foo; +} + +fn patterns<'a>( + &pin mut x: &pin mut i32, + &pin const y: &'a pin const i32, + ref pin mut z: i32, + mut ref pin const w: i32, +) { +} diff --git a/tests/target/trait.rs b/tests/target/trait.rs index 7f067991b26..7a65b13d629 100644 --- a/tests/target/trait.rs +++ b/tests/target/trait.rs @@ -218,3 +218,5 @@ trait Visible { pub fn f(); pub fn g() {} } + +const trait Foomp = Hash; diff --git a/tests/target/try_block.rs b/tests/target/try_block.rs index 19a3f3e1487..61da123b735 100644 --- a/tests/target/try_block.rs +++ b/tests/target/try_block.rs @@ -1,4 +1,5 @@ // rustfmt-edition: 2018 +#![feature(try_blocks)] fn main() -> Result<(), !> { let _x: Option<_> = try { 4 }; diff --git a/tests/target/try_blocks_heterogeneous.rs b/tests/target/try_blocks_heterogeneous.rs new file mode 100644 index 00000000000..018d53ed35e --- /dev/null +++ b/tests/target/try_blocks_heterogeneous.rs @@ -0,0 +1,41 @@ +// rustfmt-edition: 2018 +#![feature(try_blocks_heterogeneous)] + +fn main() -> Result<(), !> { + let _x = try bikeshed Option<_> { 4 }; + + try bikeshed Result<_, _> {} +} + +fn baz() -> Option { + if (1 == 1) { + return try bikeshed Option { 5 }; + } + + // test + let x = try bikeshed Option<()> { + // try blocks are great + }; + + let y = try bikeshed Option { 6 }; // comment + + let x = try /* Invisible comment */ bikeshed Option<()> {}; + let x = try bikeshed /* Invisible comment */ Option<()> {}; + let x = try bikeshed Option<()> /* Invisible comment */ {}; + + let x = try bikeshed Option { + baz()?; + baz()?; + baz()?; + 7 + }; + + let x = try bikeshed Foo { + 1 + 1 + 1 + }; + + let x = + try bikeshed Foo {}; + + return None; +} diff --git a/tests/target/type.rs b/tests/target/type.rs index 325adb52f3f..623192b72b8 100644 --- a/tests/target/type.rs +++ b/tests/target/type.rs @@ -147,27 +147,23 @@ type MyFn = fn( // Const bound -trait T: ~const Super {} +trait T: [const] Super {} -const fn not_quite_const() -> i32 { +const fn not_quite_const() -> i32 { ::CONST } -impl ~const T {} +impl const T for U {} -fn apit(_: impl ~const T) {} +fn apit(_: impl [const] T) {} -fn rpit() -> impl ~const T { +fn rpit() -> impl [const] T { S } pub struct Foo(T); -impl Foo { +impl Foo { fn new(t: T) -> Self { Self(t) } } - -// #4357 -type T = typeof(1); -impl T for .. {}