diff --git a/Cargo.toml b/Cargo.toml index 970b13eab35..d282766e00b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,14 +2,13 @@ name = "rustfmt-nightly" version = "1.4.37" -authors = ["Nicholas Cameron ", "The Rustfmt developers"] description = "Tool to find and fix Rust formatting issues" repository = "https://github.com/rust-lang/rustfmt" readme = "README.md" license = "Apache-2.0/MIT" build = "build.rs" categories = ["development-tools"] -edition = "2018" +edition = "2021" [[bin]] name = "rustfmt" diff --git a/config_proc_macro/Cargo.toml b/config_proc_macro/Cargo.toml index cc995571602..a41b3a5e6bf 100644 --- a/config_proc_macro/Cargo.toml +++ b/config_proc_macro/Cargo.toml @@ -1,7 +1,6 @@ [package] name = "rustfmt-config_proc_macro" version = "0.2.0" -authors = ["topecongiro "] edition = "2018" description = "A collection of procedural macros for rustfmt" license = "Apache-2.0/MIT" diff --git a/rust-toolchain b/rust-toolchain index b0cd4464df8..b19ecbdb07c 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2021-07-23" +channel = "nightly-2021-10-20" components = ["rustc-dev"] diff --git a/src/closures.rs b/src/closures.rs index c9d46aef294..34d73a77fd3 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -160,6 +160,7 @@ 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/expr.rs b/src/expr.rs index f40f80e4253..7f1dd363f93 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -616,7 +616,7 @@ struct ControlFlow<'a> { fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) { match expr.kind { - ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond), + ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond), _ => (None, expr), } } diff --git a/src/items.rs b/src/items.rs index 471a365e470..1cb1a2701c3 100644 --- a/src/items.rs +++ b/src/items.rs @@ -6,7 +6,7 @@ use std::cmp::{max, min, Ordering}; use regex::Regex; use rustc_ast::visit; use rustc_ast::{ast, ptr}; -use rustc_span::{symbol, BytePos, Span}; +use rustc_span::{symbol, BytePos, Span, DUMMY_SP}; use crate::attr::filter_inline_attrs; use crate::comment::{ @@ -31,7 +31,12 @@ use crate::stmt::Stmt; use crate::utils::*; use crate::vertical::rewrite_with_alignment; use crate::visitor::FmtVisitor; -use crate::DEFAULT_VISIBILITY; + +const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility { + kind: ast::VisibilityKind::Inherited, + span: DUMMY_SP, + tokens: None, +}; fn type_annotation_separator(config: &Config) -> &str { colon_spaces(config) @@ -48,7 +53,7 @@ impl Rewrite for ast::Local { skip_out_of_file_lines_range!(context, self.span); - if contains_skip(&self.attrs) { + if contains_skip(&self.attrs) || matches!(self.kind, ast::LocalKind::InitElse(..)) { return None; } @@ -97,7 +102,7 @@ impl Rewrite for ast::Local { infix.push_str(&rewrite); } - if self.init.is_some() { + if self.kind.init().is_some() { infix.push_str(" ="); } @@ -106,11 +111,12 @@ impl Rewrite for ast::Local { result.push_str(&infix); - if let Some(ref ex) = self.init { + if let Some((init, _els)) = self.kind.init_else_opt() { // 1 = trailing semicolon; let nested_shape = shape.sub_width(1)?; - result = rewrite_assign_rhs(context, result, &**ex, nested_shape)?; + result = rewrite_assign_rhs(context, result, init, nested_shape)?; + // todo else } result.push(';'); @@ -972,7 +978,7 @@ impl<'a> StructParts<'a> { format_header(context, self.prefix, self.ident, self.vis, offset) } - pub(crate) fn from_variant(variant: &'a ast::Variant) -> Self { + fn from_variant(variant: &'a ast::Variant) -> Self { StructParts { prefix: "", ident: variant.ident, diff --git a/src/lib.rs b/src/lib.rs index 206d2f78290..47a7b9d4dbe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use std::path::PathBuf; use std::rc::Rc; use rustc_ast::ast; -use rustc_span::{symbol, DUMMY_SP}; +use rustc_span::symbol; use thiserror::Error; use crate::comment::LineClasses; @@ -96,11 +96,6 @@ mod types; mod vertical; pub(crate) mod visitor; -const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility { - kind: ast::VisibilityKind::Inherited, - span: DUMMY_SP, - tokens: None, -}; /// The various errors that can occur during formatting. Note that not all of /// these can currently be propagated to clients. #[derive(Error, Debug)] diff --git a/src/macros.rs b/src/macros.rs index 6c5e32716c0..927187dfd8a 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -401,7 +401,7 @@ fn rewrite_macro_inner( handle_vec_semi(context, shape, arg_vec, macro_name, style) } else { // If we are rewriting `vec!` macro or other special macros, - // then we can rewrite this as an usual array literal. + // then we can rewrite this as a usual array literal. // Otherwise, we must preserve the original existence of trailing comma. let macro_name = ¯o_name.as_str(); let mut force_trailing_comma = if trailing_comma { @@ -762,7 +762,6 @@ impl MacroArgKind { #[derive(Debug, Clone)] struct ParsedMacroArg { kind: MacroArgKind, - span: Span, } impl ParsedMacroArg { @@ -780,14 +779,10 @@ impl ParsedMacroArg { struct MacroArgParser { /// Either a name of the next metavariable, a separator, or junk. buf: String, - /// The start position on the current buffer. - lo: BytePos, /// The first token of the current buffer. start_tok: Token, /// `true` if we are parsing a metavariable or a repeat. is_meta_var: bool, - /// The position of the last token. - hi: BytePos, /// The last token parsed. last_tok: Token, /// Holds the parsed arguments. @@ -807,8 +802,6 @@ fn last_tok(tt: &TokenTree) -> Token { impl MacroArgParser { fn new() -> MacroArgParser { MacroArgParser { - lo: BytePos(0), - hi: BytePos(0), buf: String::new(), is_meta_var: false, last_tok: Token { @@ -824,7 +817,6 @@ impl MacroArgParser { } fn set_last_tok(&mut self, tok: &TokenTree) { - self.hi = tok.span().hi(); self.last_tok = last_tok(tok); } @@ -836,7 +828,6 @@ impl MacroArgParser { }; self.result.push(ParsedMacroArg { kind: MacroArgKind::Separator(self.buf.clone(), prefix), - span: mk_sp(self.lo, self.hi), }); self.buf.clear(); } @@ -849,7 +840,6 @@ impl MacroArgParser { }; self.result.push(ParsedMacroArg { kind: MacroArgKind::Other(self.buf.clone(), prefix), - span: mk_sp(self.lo, self.hi), }); self.buf.clear(); } @@ -858,11 +848,10 @@ impl MacroArgParser { match iter.next() { Some(TokenTree::Token(Token { kind: TokenKind::Ident(name, _), - span, + .. })) => { self.result.push(ParsedMacroArg { kind: MacroArgKind::MetaVariable(name, self.buf.clone()), - span: mk_sp(self.lo, span.hi()), }); self.buf.clear(); @@ -873,10 +862,9 @@ impl MacroArgParser { } } - fn add_delimited(&mut self, inner: Vec, delim: DelimToken, span: Span) { + fn add_delimited(&mut self, inner: Vec, delim: DelimToken) { self.result.push(ParsedMacroArg { kind: MacroArgKind::Delimited(delim, inner), - span, }); } @@ -886,19 +874,15 @@ impl MacroArgParser { inner: Vec, delim: DelimToken, iter: &mut Cursor, - span: Span, ) -> Option<()> { let mut buffer = String::new(); let mut first = true; - let mut lo = span.lo(); - let mut hi = span.hi(); // Parse '*', '+' or '?. for tok in iter { self.set_last_tok(&tok); if first { first = false; - lo = tok.span().lo(); } match tok { @@ -918,7 +902,6 @@ impl MacroArgParser { } TokenTree::Token(ref t) => { buffer.push_str(&pprust::token_to_string(&t)); - hi = t.span.hi(); } _ => return None, } @@ -930,20 +913,17 @@ impl MacroArgParser { } else { Some(Box::new(ParsedMacroArg { kind: MacroArgKind::Other(buffer, "".to_owned()), - span: mk_sp(lo, hi), })) }; self.result.push(ParsedMacroArg { kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()), - span: mk_sp(self.lo, self.hi), }); Some(()) } fn update_buffer(&mut self, t: &Token) { if self.buf.is_empty() { - self.lo = t.span.lo(); self.start_tok = t.clone(); } else { let needs_space = match next_space(&self.last_tok.kind) { @@ -999,7 +979,6 @@ impl MacroArgParser { // Start keeping the name of this metavariable in the buffer. self.is_meta_var = true; - self.lo = span.lo(); self.start_tok = Token { kind: TokenKind::Dollar, span, @@ -1012,7 +991,7 @@ impl MacroArgParser { self.add_meta_variable(&mut iter)?; } TokenTree::Token(ref t) => self.update_buffer(t), - TokenTree::Delimited(delimited_span, delimited, ref tts) => { + TokenTree::Delimited(_delimited_span, delimited, ref tts) => { if !self.buf.is_empty() { if next_space(&self.last_tok.kind) == SpaceState::Always { self.add_separator(); @@ -1022,16 +1001,14 @@ impl MacroArgParser { } // Parse the stuff inside delimiters. - let mut parser = MacroArgParser::new(); - parser.lo = delimited_span.open.lo(); + let parser = MacroArgParser::new(); let delimited_arg = parser.parse(tts.clone())?; - let span = delimited_span.entire(); if self.is_meta_var { - self.add_repeat(delimited_arg, delimited, &mut iter, span)?; + self.add_repeat(delimited_arg, delimited, &mut iter)?; self.is_meta_var = false; } else { - self.add_delimited(delimited_arg, delimited, span); + self.add_delimited(delimited_arg, delimited); } } } @@ -1270,7 +1247,12 @@ impl MacroParser { let data = delimited_span.entire().data(); ( data.hi, - Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt), + Span::new( + data.lo + BytePos(1), + data.hi - BytePos(1), + data.ctxt, + data.parent, + ), delimited_span.entire(), ) } @@ -1417,7 +1399,7 @@ impl MacroBranch { } } -/// Format `lazy_static!` from https://crates.io/crates/lazy_static. +/// Format `lazy_static!` from . /// /// # Expected syntax /// diff --git a/src/modules.rs b/src/modules.rs index 5de0575b5cd..ded34d9032f 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -27,7 +27,6 @@ type FileModMap<'ast> = BTreeMap>; pub(crate) struct Module<'a> { ast_mod_kind: Option>, pub(crate) items: Cow<'a, Vec>>, - attrs: Cow<'a, Vec>, inner_attr: Vec, pub(crate) span: Span, } @@ -46,7 +45,6 @@ impl<'a> Module<'a> { .collect(); Module { items: mod_items, - attrs: mod_attrs, inner_attr, span: mod_span, ast_mod_kind, diff --git a/src/patterns.rs b/src/patterns.rs index 34987b1d59e..ba8d8024a97 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -23,11 +23,11 @@ use crate::utils::{format_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: /// -/// [small, ntp]: +/// `[small, ntp]`: /// - single token /// - `&[single-line, ntp]` /// -/// [small]: +/// `[small]`: /// - `[small, ntp]` /// - unary tuple constructor `([small, ntp])` /// - `&[small]` diff --git a/src/string.rs b/src/string.rs index 0cb9d817ca2..64ae15672df 100644 --- a/src/string.rs +++ b/src/string.rs @@ -153,7 +153,7 @@ pub(crate) fn rewrite_string<'a>( wrap_str(result, fmt.config.max_width(), fmt.shape) } -/// Returns the index to the end of the URL if the split at index of the given string includes an +/// Returns the index to the end of the URL if the split at index of the given string includes a /// URL or alike. Otherwise, returns `None`. fn detect_url(s: &[&str], index: usize) -> Option { let start = match s[..=index].iter().rposition(|g| is_whitespace(g)) { diff --git a/src/syntux/session.rs b/src/syntux/session.rs index 94257e1ce7f..946c076d9f2 100644 --- a/src/syntux/session.rs +++ b/src/syntux/session.rs @@ -317,6 +317,7 @@ mod tests { suggestions: vec![], span: span.unwrap_or_else(MultiSpan::new), sort_span: DUMMY_SP, + is_lint: false, } } diff --git a/src/types.rs b/src/types.rs index 9a0d31e51df..62c05ba078c 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,15 +1,15 @@ use std::iter::ExactSizeIterator; use std::ops::Deref; -use rustc_ast::ast::{self, AttrVec, FnRetTy, Mutability}; -use rustc_span::{symbol::kw, symbol::Ident, BytePos, Pos, Span}; +use rustc_ast::ast::{self, FnRetTy, Mutability}; +use rustc_span::{symbol::kw, BytePos, Pos, Span}; +use crate::comment::{combine_strs_with_missing_comments, contains_comment}; use crate::config::lists::*; use crate::config::{IndentStyle, TypeDensity, Version}; use crate::expr::{ format_expr, rewrite_assign_rhs, rewrite_call, rewrite_tuple, rewrite_unary_prefix, ExprType, }; -use crate::items::StructParts; use crate::lists::{ definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator, }; @@ -24,11 +24,6 @@ use crate::utils::{ colon_spaces, extra_offset, first_line_width, format_extern, format_mutability, last_line_extendable, last_line_width, mk_sp, rewrite_ident, }; -use crate::DEFAULT_VISIBILITY; -use crate::{ - comment::{combine_strs_with_missing_comments, contains_comment}, - items::format_struct_struct, -}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum PathContext { @@ -548,10 +543,10 @@ impl Rewrite for ast::GenericBound { .map(|s| format!("?{}", s)), ast::TraitBoundModifier::MaybeConst => poly_trait_ref .rewrite(context, shape.offset_left(7)?) - .map(|s| format!("?const {}", s)), + .map(|s| format!("~const {}", s)), ast::TraitBoundModifier::MaybeConstMaybe => poly_trait_ref .rewrite(context, shape.offset_left(8)?) - .map(|s| format!("?const ?{}", s)), + .map(|s| format!("~const ?{}", s)), }; rewrite.map(|s| if has_paren { format!("({})", s) } else { s }) } @@ -790,54 +785,6 @@ impl Rewrite for ast::Ty { ast::TyKind::Tup(ref items) => { rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1) } - ast::TyKind::AnonymousStruct(ref fields, recovered) => { - let ident = Ident::new( - kw::Struct, - mk_sp(self.span.lo(), self.span.lo() + BytePos(6)), - ); - let data = ast::VariantData::Struct(fields.clone(), recovered); - let variant = ast::Variant { - attrs: AttrVec::new(), - id: self.id, - span: self.span, - vis: DEFAULT_VISIBILITY, - ident, - data, - disr_expr: None, - is_placeholder: false, - }; - format_struct_struct( - &context, - &StructParts::from_variant(&variant), - fields, - shape.indent, - None, - ) - } - ast::TyKind::AnonymousUnion(ref fields, recovered) => { - let ident = Ident::new( - kw::Union, - mk_sp(self.span.lo(), self.span.lo() + BytePos(5)), - ); - let data = ast::VariantData::Struct(fields.clone(), recovered); - let variant = ast::Variant { - attrs: AttrVec::new(), - id: self.id, - span: self.span, - vis: DEFAULT_VISIBILITY, - ident, - data, - disr_expr: None, - is_placeholder: false, - }; - format_struct_struct( - &context, - &StructParts::from_variant(&variant), - fields, - shape.indent, - None, - ) - } ast::TyKind::Path(ref q_self, ref path) => { rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape) } diff --git a/src/utils.rs b/src/utils.rs index 06159a1b26e..29e1e070d41 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -356,11 +356,11 @@ macro_rules! source { } pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span { - Span::new(lo, hi, SyntaxContext::root()) + Span::new(lo, hi, SyntaxContext::root(), None) } pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span { - Span::new(lo, lo + BytePos(1), SyntaxContext::root()) + Span::new(lo, lo + BytePos(1), SyntaxContext::root(), None) } // Returns `true` if the given span does not intersect with file lines. diff --git a/src/visitor.rs b/src/visitor.rs index c67ebe793fd..d854d90b40b 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -36,7 +36,7 @@ pub(crate) struct SnippetProvider { big_snippet: Lrc, /// A position of the start of `big_snippet`, used as an offset. start_pos: usize, - /// A end position of the file that this snippet lives. + /// An end position of the file that this snippet lives. end_pos: usize, } diff --git a/tests/source/cfg_if/detect/arch/x86.rs b/tests/source/cfg_if/detect/arch/x86.rs index 50d5cfa87c4..4c71a2c6ab9 100644 --- a/tests/source/cfg_if/detect/arch/x86.rs +++ b/tests/source/cfg_if/detect/arch/x86.rs @@ -2,7 +2,7 @@ //! //! The features are detected using the `detect_features` function below. //! This function uses the CPUID instruction to read the feature flags from the -//! CPU and encodes them in an `usize` where each bit position represents +//! CPU and encodes them in a `usize` where each bit position represents //! whether a feature is available (bit is set) or unavaiable (bit is cleared). //! //! The enum `Feature` is used to map bit positions to feature names, and the diff --git a/tests/source/let_else.rs b/tests/source/let_else.rs new file mode 100644 index 00000000000..a6e816fb524 --- /dev/null +++ b/tests/source/let_else.rs @@ -0,0 +1,3 @@ +fn main() { + let Some(1) = Some(1) else { return }; +} diff --git a/tests/source/type.rs b/tests/source/type.rs index 57f31dc901e..61ef73a3cab 100644 --- a/tests/source/type.rs +++ b/tests/source/type.rs @@ -140,29 +140,23 @@ fn foo(a: SomeLongComplexType, b: SomeOtherLongComplexType) -> Box Box>; -// Const opt-out +// Const bound -trait T: ? const Super {} +trait T: ~ const Super {} -const fn maybe_const() -> i32 { ::CONST } +const fn not_quite_const() -> i32 { ::CONST } -struct S(std::marker::PhantomData); +struct S(std::marker::PhantomData); -impl ? const T {} +impl ~ const T {} -fn trait_object() -> &'static dyn ? const T { &S } +fn apit(_: impl ~ const T) {} -fn i(_: impl IntoIterator>) {} - -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 { - // not calling methods on `t`, so we opt out of requiring - // `` to have const methods via `?const` Self(t) } } @@ -171,4 +165,4 @@ impl Foo { type T = typeof( 1); impl T for .. { -} \ No newline at end of file +} diff --git a/tests/target/cfg_if/detect/arch/x86.rs b/tests/target/cfg_if/detect/arch/x86.rs index 9219a4a577f..b985dd8caa1 100644 --- a/tests/target/cfg_if/detect/arch/x86.rs +++ b/tests/target/cfg_if/detect/arch/x86.rs @@ -2,7 +2,7 @@ //! //! The features are detected using the `detect_features` function below. //! This function uses the CPUID instruction to read the feature flags from the -//! CPU and encodes them in an `usize` where each bit position represents +//! CPU and encodes them in a `usize` where each bit position represents //! whether a feature is available (bit is set) or unavaiable (bit is cleared). //! //! The enum `Feature` is used to map bit positions to feature names, and the diff --git a/tests/target/let_else.rs b/tests/target/let_else.rs new file mode 100644 index 00000000000..a6e816fb524 --- /dev/null +++ b/tests/target/let_else.rs @@ -0,0 +1,3 @@ +fn main() { + let Some(1) = Some(1) else { return }; +} diff --git a/tests/target/type.rs b/tests/target/type.rs index e7761251688..38cf909c258 100644 --- a/tests/target/type.rs +++ b/tests/target/type.rs @@ -145,35 +145,27 @@ type MyFn = fn( b: SomeOtherLongComplexType, ) -> Box>; -// Const opt-out +// Const bound -trait T: ?const Super {} +trait T: ~const Super {} -const fn maybe_const() -> i32 { +const fn not_quite_const() -> i32 { ::CONST } -struct S(std::marker::PhantomData); +struct S(std::marker::PhantomData); -impl ?const T {} +impl ~const T {} -fn trait_object() -> &'static dyn ?const T { - &S -} +fn apit(_: impl ~const T) {} -fn i(_: impl IntoIterator>) {} - -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 { - // not calling methods on `t`, so we opt out of requiring - // `` to have const methods via `?const` Self(t) } }