From d67f1a48efbcdc689c69b6218ec55b541ebf8c7a Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Sun, 2 May 2021 16:56:25 -0400 Subject: [PATCH 01/20] Update log to 0.4.14 This avoids the following warning: ``` warning: trailing semicolon in macro used in expression position --> /home/joshua/.local/lib/cargo/registry/src/github.com-1ecc6299db9ec823/log-0.4.11/src/macros.rs:152:45 | 147 | / macro_rules! debug { 148 | | (target: $target:expr, $($arg:tt)+) => ( 149 | | log!(target: $target, $crate::Level::Debug, $($arg)+); 150 | | ); 151 | | ($($arg:tt)+) => ( 152 | | log!($crate::Level::Debug, $($arg)+); | | ^ 153 | | ) 154 | | } | |_- in this expansion of `debug!` | ::: src/tools/rustfmt/src/modules/visitor.rs:36:23 | 36 | Err(e) => debug!("{}", e), | --------------- in this macro invocation | = note: requested on the command line with `-W semicolon-in-expressions-from-macros` = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 ``` --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 24b3b79343b05..3a04fb28f7cbf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,7 +42,7 @@ unicode-segmentation = "1.0.0" regex = "1.0" term = "0.6" diff = "0.1" -log = "0.4" +log = "0.4.14" env_logger = "0.6" getopts = "0.2" derive-new = "0.5" From e243be6adad16ad65c3349e476d528d1f416ed59 Mon Sep 17 00:00:00 2001 From: jedel1043 Date: Sun, 16 May 2021 22:13:38 -0500 Subject: [PATCH 02/20] Allow formatting `Anonymous{Struct, Union}` declarations --- src/items.rs | 11 +++------- src/lib.rs | 7 ++++++- src/types.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 64 insertions(+), 11 deletions(-) diff --git a/src/items.rs b/src/items.rs index ecbd0bd12ec6e..420484c0ba11e 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, DUMMY_SP}; +use rustc_span::{symbol, BytePos, Span}; use crate::attr::filter_inline_attrs; use crate::comment::{ @@ -31,12 +31,7 @@ use crate::stmt::Stmt; use crate::utils::*; use crate::vertical::rewrite_with_alignment; use crate::visitor::FmtVisitor; - -const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility { - kind: ast::VisibilityKind::Inherited, - span: DUMMY_SP, - tokens: None, -}; +use crate::DEFAULT_VISIBILITY; fn type_annotation_separator(config: &Config) -> &str { colon_spaces(config) @@ -976,7 +971,7 @@ impl<'a> StructParts<'a> { format_header(context, self.prefix, self.ident, self.vis, offset) } - fn from_variant(variant: &'a ast::Variant) -> Self { + pub(crate) fn from_variant(variant: &'a ast::Variant) -> Self { StructParts { prefix: "", ident: variant.ident, diff --git a/src/lib.rs b/src/lib.rs index 8a798777e0e80..cde5d390cf259 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,7 +31,7 @@ use std::rc::Rc; use ignore; use rustc_ast::ast; -use rustc_span::symbol; +use rustc_span::{symbol, DUMMY_SP}; use thiserror::Error; use crate::comment::LineClasses; @@ -95,6 +95,11 @@ 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/types.rs b/src/types.rs index cda17e13eebb0..5597af9ee320c 100644 --- a/src/types.rs +++ b/src/types.rs @@ -2,14 +2,14 @@ use std::iter::ExactSizeIterator; use std::ops::Deref; use rustc_ast::ast::{self, FnRetTy, Mutability}; -use rustc_span::{symbol::kw, BytePos, Pos, Span}; +use rustc_span::{symbol::kw, symbol::Ident, 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,6 +24,11 @@ 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 { @@ -764,6 +769,54 @@ 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: vec![], + 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: vec![], + 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) } From 58c63cf8dec2b7d97667932c17248f774dd6e1ab Mon Sep 17 00:00:00 2001 From: Ryan Levick Date: Thu, 10 Dec 2020 13:20:07 +0100 Subject: [PATCH 03/20] Add support for using qualified paths with structs in expression and pattern position. --- src/expr.rs | 4 +++- src/patterns.rs | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/expr.rs b/src/expr.rs index ced382c4915a1..bca9f77f959e3 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -107,7 +107,9 @@ pub(crate) fn format_expr( } ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape), ast::ExprKind::Struct(ref struct_expr) => { - let ast::StructExpr { fields, path, rest } = &**struct_expr; + let ast::StructExpr { + fields, path, rest, .. + } = &**struct_expr; rewrite_struct_lit(context, path, fields, rest, &expr.attrs, expr.span, shape) } ast::ExprKind::Tup(ref items) => { diff --git a/src/patterns.rs b/src/patterns.rs index 6824fc661ba72..fa0ef260991d7 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -45,7 +45,7 @@ fn is_short_pattern_inner(pat: &ast::Pat) -> bool { | ast::PatKind::Path(..) | ast::PatKind::Range(..) => false, ast::PatKind::Tuple(ref subpats) => subpats.len() <= 1, - ast::PatKind::TupleStruct(ref path, ref subpats) => { + ast::PatKind::TupleStruct(_, ref path, ref subpats) => { path.segments.len() <= 1 && subpats.len() <= 1 } ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => { @@ -226,7 +226,7 @@ impl Rewrite for Pat { PatKind::Path(ref q_self, ref path) => { rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape) } - PatKind::TupleStruct(ref path, ref pat_vec) => { + PatKind::TupleStruct(_, ref path, ref pat_vec) => { let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?; rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape) } @@ -244,7 +244,7 @@ impl Rewrite for Pat { .collect(); Some(format!("[{}]", rw.join(", "))) } - PatKind::Struct(ref path, ref fields, ellipsis) => { + PatKind::Struct(_, ref path, ref fields, ellipsis) => { rewrite_struct_pat(path, fields, ellipsis, self.span, context, shape) } PatKind::MacCall(ref mac) => { From 1e2258ffa949bf4d273259e78d326857c0b2bb3d Mon Sep 17 00:00:00 2001 From: Yuki Okushi Date: Thu, 17 Jun 2021 07:11:13 +0900 Subject: [PATCH 04/20] Use `AttrVec` for `Arm`, `FieldDef`, and `Variant` --- src/types.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/types.rs b/src/types.rs index 5597af9ee320c..974c0c5990c7d 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,7 +1,7 @@ use std::iter::ExactSizeIterator; use std::ops::Deref; -use rustc_ast::ast::{self, FnRetTy, Mutability}; +use rustc_ast::ast::{self, AttrVec, FnRetTy, Mutability}; use rustc_span::{symbol::kw, symbol::Ident, BytePos, Pos, Span}; use crate::config::lists::*; @@ -776,7 +776,7 @@ impl Rewrite for ast::Ty { ); let data = ast::VariantData::Struct(fields.clone(), recovered); let variant = ast::Variant { - attrs: vec![], + attrs: AttrVec::new(), id: self.id, span: self.span, vis: DEFAULT_VISIBILITY, @@ -800,7 +800,7 @@ impl Rewrite for ast::Ty { ); let data = ast::VariantData::Struct(fields.clone(), recovered); let variant = ast::Variant { - attrs: vec![], + attrs: AttrVec::new(), id: self.id, span: self.span, vis: DEFAULT_VISIBILITY, From 2608f2c63bbc565cffd02514c997511ac31f74aa Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Thu, 17 Jun 2021 22:35:19 -0500 Subject: [PATCH 05/20] fix(rustfmt): load nested out-of-line mods correctly --- src/modules.rs | 2 +- src/test/mod.rs | 1 + src/test/mod_resolver.rs | 25 ++++++++++++++++++++++++ tests/mod-resolver/issue-4874/bar/baz.rs | 5 +++++ tests/mod-resolver/issue-4874/foo.rs | 1 + tests/mod-resolver/issue-4874/foo/qux.rs | 5 +++++ tests/mod-resolver/issue-4874/main.rs | 8 ++++++++ 7 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/test/mod_resolver.rs create mode 100644 tests/mod-resolver/issue-4874/bar/baz.rs create mode 100644 tests/mod-resolver/issue-4874/foo.rs create mode 100644 tests/mod-resolver/issue-4874/foo/qux.rs create mode 100644 tests/mod-resolver/issue-4874/main.rs diff --git a/src/modules.rs b/src/modules.rs index c3f4406860135..5de0575b5cd66 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -318,7 +318,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { self.directory = directory; } match (sub_mod.ast_mod_kind, sub_mod.items) { - (Some(Cow::Borrowed(ast::ModKind::Loaded(items, ast::Inline::No, _))), _) => { + (Some(Cow::Borrowed(ast::ModKind::Loaded(items, _, _))), _) => { self.visit_mod_from_ast(&items) } (Some(Cow::Owned(..)), Cow::Owned(items)) => self.visit_mod_outside_ast(items), diff --git a/src/test/mod.rs b/src/test/mod.rs index ce56a223f2b04..cb52346a13a41 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -16,6 +16,7 @@ use crate::source_file; use crate::{is_nightly_channel, FormatReport, FormatReportFormatterBuilder, Input, Session}; mod configuration_snippet; +mod mod_resolver; mod parser; const DIFF_CONTEXT_SIZE: usize = 3; diff --git a/src/test/mod_resolver.rs b/src/test/mod_resolver.rs new file mode 100644 index 0000000000000..e0b55e3efb2c4 --- /dev/null +++ b/src/test/mod_resolver.rs @@ -0,0 +1,25 @@ +use std::io; +use std::path::PathBuf; + +use super::read_config; + +use crate::{FileName, Input, Session}; + +#[test] +fn nested_out_of_line_mods_loaded() { + // See also https://github.com/rust-lang/rustfmt/issues/4874 + let filename = "tests/mod-resolver/issue-4874/main.rs"; + let input_file = PathBuf::from(filename); + let config = read_config(&input_file); + let mut session = Session::::new(config, None); + let report = session + .format(Input::File(filename.into())) + .expect("Should not have had any execution errors"); + let errors_by_file = &report.internal.borrow().0; + assert!(errors_by_file.contains_key(&FileName::Real(PathBuf::from( + "tests/mod-resolver/issue-4874/bar/baz.rs", + )))); + assert!(errors_by_file.contains_key(&FileName::Real(PathBuf::from( + "tests/mod-resolver/issue-4874/foo/qux.rs", + )))); +} diff --git a/tests/mod-resolver/issue-4874/bar/baz.rs b/tests/mod-resolver/issue-4874/bar/baz.rs new file mode 100644 index 0000000000000..d31b675ea260d --- /dev/null +++ b/tests/mod-resolver/issue-4874/bar/baz.rs @@ -0,0 +1,5 @@ +fn + fail_fmt_check + ( + + ) {} \ No newline at end of file diff --git a/tests/mod-resolver/issue-4874/foo.rs b/tests/mod-resolver/issue-4874/foo.rs new file mode 100644 index 0000000000000..246d847869a12 --- /dev/null +++ b/tests/mod-resolver/issue-4874/foo.rs @@ -0,0 +1 @@ +mod qux; \ No newline at end of file diff --git a/tests/mod-resolver/issue-4874/foo/qux.rs b/tests/mod-resolver/issue-4874/foo/qux.rs new file mode 100644 index 0000000000000..d8bb610a64db1 --- /dev/null +++ b/tests/mod-resolver/issue-4874/foo/qux.rs @@ -0,0 +1,5 @@ + fn + badly_formatted + ( + + ) {} \ No newline at end of file diff --git a/tests/mod-resolver/issue-4874/main.rs b/tests/mod-resolver/issue-4874/main.rs new file mode 100644 index 0000000000000..3609415b1468b --- /dev/null +++ b/tests/mod-resolver/issue-4874/main.rs @@ -0,0 +1,8 @@ +fn main() { + println!("Hello, world!"); +} + +mod foo; +mod bar { + mod baz; +} \ No newline at end of file From 71f01d197411fc7a9b3509cbf566720eabdf8d92 Mon Sep 17 00:00:00 2001 From: Alexander Melentyev Date: Mon, 21 Jun 2021 12:11:37 +0300 Subject: [PATCH 06/20] Delete spaces --- CHANGELOG.md | 10 +++++----- Configurations.md | 32 ++++++++++++++++---------------- Contributing.md | 2 +- Design.md | 4 ++-- README.md | 4 ++-- ci/integration.sh | 2 +- docs/index.html | 8 ++++---- 7 files changed, 31 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f23663d6c2f9..68354b6ceaf25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -176,7 +176,7 @@ https://rust-lang.github.io/rustfmt/?version=v1.4.33&search=#imports_granularity ### Changed -- Original comment indentation for trailing comments within an `if` is now taken into account when determining the indentation level to use for the trailing comment in formatted code. This does not modify any existing code formatted with rustfmt; it simply gives the programmer discretion to specify whether the comment is associated to the `else` block, or if the trailing comment is just a member of the `if` block. ([#1575](https://github.com/rust-lang/rustfmt/issues/1575), [#4120](https://github.com/rust-lang/rustfmt/issues/4120), [#4506](https://github.com/rust-lang/rustfmt/issues/4506)) +- Original comment indentation for trailing comments within an `if` is now taken into account when determining the indentation level to use for the trailing comment in formatted code. This does not modify any existing code formatted with rustfmt; it simply gives the programmer discretion to specify whether the comment is associated to the `else` block, or if the trailing comment is just a member of the `if` block. ([#1575](https://github.com/rust-lang/rustfmt/issues/1575), [#4120](https://github.com/rust-lang/rustfmt/issues/4120), [#4506](https://github.com/rust-lang/rustfmt/issues/4506)) In this example the `// else comment` refers to the `else`: ```rust @@ -213,7 +213,7 @@ if toks.eat_token(Token::Word("modify"))? && toks.eat_token(Token::Word("labels" ### Fixed - Formatting of empty blocks with attributes which only contained comments is no longer butchered.([#4475](https://github.com/rust-lang/rustfmt/issues/4475), [#4467](https://github.com/rust-lang/rustfmt/issues/4467), [#4452](https://github.com/rust-lang/rustfmt/issues/4452#issuecomment-705886282), [#4522](https://github.com/rust-lang/rustfmt/issues/4522)) -- Indentation of trailing comments in non-empty extern blocks is now correct. ([#4120](https://github.com/rust-lang/rustfmt/issues/4120#issuecomment-696491872)) +- Indentation of trailing comments in non-empty extern blocks is now correct. ([#4120](https://github.com/rust-lang/rustfmt/issues/4120#issuecomment-696491872)) ### Install/Download Options - **crates.io package** - *pending* @@ -297,7 +297,7 @@ if toks.eat_token(Token::Word("modify"))? && toks.eat_token(Token::Word("labels" - Fix aligning comments of different group - Fix flattening imports with a single `self`. - Fix removing attributes on function parameters. -- Fix removing `impl` keyword from opaque type. +- Fix removing `impl` keyword from opaque type. ## [1.4.8] 2019-09-08 @@ -329,7 +329,7 @@ if toks.eat_token(Token::Word("modify"))? && toks.eat_token(Token::Word("labels" - Add `--message-format` command line option to `cargo-fmt`. - Add `-l,--files-with-diff` command line option to `rustfmt`. -- Add `json` emit mode. +- Add `json` emit mode. ### Fixed @@ -380,7 +380,7 @@ if toks.eat_token(Token::Word("modify"))? && toks.eat_token(Token::Word("labels" ### Added -- Add new attribute `rustfmt::skip::attributes` to prevent rustfmt +- Add new attribute `rustfmt::skip::attributes` to prevent rustfmt from formatting an attribute #3665 ### Changed diff --git a/Configurations.md b/Configurations.md index 37cb7474130c8..9daa706537976 100644 --- a/Configurations.md +++ b/Configurations.md @@ -17,7 +17,7 @@ To enable unstable options, set `unstable_features = true` in `rustfmt.toml` or Below you find a detailed visual guide on all the supported configuration options of rustfmt: -## `array_width` +## `array_width` Maximum width of an array literal before falling back to vertical formatting. @@ -25,11 +25,11 @@ Maximum width of an array literal before falling back to vertical formatting. - **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) - **Stable**: Yes -By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `array_width` will take precedence. +By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `array_width` will take precedence. See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics) -## `attr_fn_like_width` +## `attr_fn_like_width` Maximum width of the args of a function-like attributes before falling back to vertical formatting. @@ -37,7 +37,7 @@ Maximum width of the args of a function-like attributes before falling back to v - **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) - **Stable**: Yes -By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `attr_fn_like_width` will take precedence. +By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `attr_fn_like_width` will take precedence. See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics) @@ -295,7 +295,7 @@ where } ``` -## `chain_width` +## `chain_width` Maximum width of a chain to fit on one line. @@ -303,7 +303,7 @@ Maximum width of a chain to fit on one line. - **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) - **Stable**: Yes -By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `chain_width` will take precedence. +By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `chain_width` will take precedence. See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics) @@ -751,7 +751,7 @@ trait Lorem { } ``` -## `fn_call_width` +## `fn_call_width` Maximum width of the args of a function call before falling back to vertical formatting. @@ -759,7 +759,7 @@ Maximum width of the args of a function call before falling back to vertical for - **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) - **Stable**: Yes -By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `fn_call_width` will take precedence. +By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `fn_call_width` will take precedence. See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics) @@ -2124,7 +2124,7 @@ Don't reformat out of line modules - **Possible values**: `true`, `false` - **Stable**: No (tracking issue: #3389) -## `single_line_if_else_max_width` +## `single_line_if_else_max_width` Maximum line length for single line if-else expressions. A value of `0` (zero) results in if-else expressions always being broken into multiple lines. Note this occurs when `use_small_heuristics` is set to `Off`. @@ -2132,7 +2132,7 @@ Maximum line length for single line if-else expressions. A value of `0` (zero) r - **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) - **Stable**: Yes -By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `single_line_if_else_max_width` will take precedence. +By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `single_line_if_else_max_width` will take precedence. See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics) @@ -2313,7 +2313,7 @@ fn main() { See also: [`indent_style`](#indent_style). -## `struct_lit_width` +## `struct_lit_width` Maximum width in the body of a struct literal before falling back to vertical formatting. A value of `0` (zero) results in struct literals always being broken into multiple lines. Note this occurs when `use_small_heuristics` is set to `Off`. @@ -2321,11 +2321,11 @@ Maximum width in the body of a struct literal before falling back to vertical fo - **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) - **Stable**: Yes -By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `struct_lit_width` will take precedence. +By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `struct_lit_width` will take precedence. See also [`max_width`](#max_width), [`use_small_heuristics`](#use_small_heuristics), and [`struct_lit_single_line`](#struct_lit_single_line) -## `struct_variant_width` +## `struct_variant_width` Maximum width in the body of a struct variant before falling back to vertical formatting. A value of `0` (zero) results in struct literals always being broken into multiple lines. Note this occurs when `use_small_heuristics` is set to `Off`. @@ -2333,7 +2333,7 @@ Maximum width in the body of a struct variant before falling back to vertical fo - **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) - **Stable**: Yes -By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `struct_variant_width` will take precedence. +By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `struct_variant_width` will take precedence. See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics) @@ -2530,7 +2530,7 @@ fn main() { This option can be used to simplify the management and bulk updates of the granular width configuration settings ([`fn_call_width`](#fn_call_width), [`attr_fn_like_width`](#attr_fn_like_width), [`struct_lit_width`](#struct_lit_width), [`struct_variant_width`](#struct_variant_width), [`array_width`](#array_width), [`chain_width`](#chain_width), [`single_line_if_else_max_width`](#single_line_if_else_max_width)), that respectively control when formatted constructs are multi-lined/vertical based on width. -Note that explicitly provided values for the width configuration settings take precedence and override the calculated values determined by `use_small_heuristics`. +Note that explicitly provided values for the width configuration settings take precedence and override the calculated values determined by `use_small_heuristics`. - **Default value**: `"Default"` - **Possible values**: `"Default"`, `"Off"`, `"Max"` @@ -2595,7 +2595,7 @@ fn main() { ``` #### `Off`: -When `use_small_heuristics` is set to `Off`, the granular width settings are functionally disabled and ignored. See the documentation for the respective width config options for specifics. +When `use_small_heuristics` is set to `Off`, the granular width settings are functionally disabled and ignored. See the documentation for the respective width config options for specifics. ```rust enum Lorem { diff --git a/Contributing.md b/Contributing.md index 131f38dd06a2b..1b77dad11f0fe 100644 --- a/Contributing.md +++ b/Contributing.md @@ -38,7 +38,7 @@ colourised diff will be printed so that the offending line(s) can quickly be identified. Without explicit settings, the tests will be run using rustfmt's default -configuration. It is possible to run a test using non-default settings in several +configuration. It is possible to run a test using non-default settings in several ways. Firstly, you can include configuration parameters in comments at the top of the file. For example: to use 3 spaces per tab, start your test with `// rustfmt-tab_spaces: 3`. Just remember that the comment is part of the input, diff --git a/Design.md b/Design.md index 00a7652aee0dc..7a4dcf8773b61 100644 --- a/Design.md +++ b/Design.md @@ -150,8 +150,8 @@ for its configuration. Our visitor keeps track of the desired current indent due to blocks ( `block_indent`). Each `visit_*` method reformats code according to this indent, -`config.comment_width()` and `config.max_width()`. Most reformatting that is done -in the `visit_*` methods is a bit hacky and is meant to be temporary until it can +`config.comment_width()` and `config.max_width()`. Most reformatting that is done +in the `visit_*` methods is a bit hacky and is meant to be temporary until it can be done properly. There are a bunch of methods called `rewrite_*`. They do the bulk of the diff --git a/README.md b/README.md index 7a97d31bab9c7..500a9f9a37c8c 100644 --- a/README.md +++ b/README.md @@ -180,13 +180,13 @@ needs to be specified in `rustfmt.toml`, e.g., with `edition = "2018"`. * For things you do not want rustfmt to mangle, use `#[rustfmt::skip]` * To prevent rustfmt from formatting a macro or an attribute, - use `#[rustfmt::skip::macros(target_macro_name)]` or + use `#[rustfmt::skip::macros(target_macro_name)]` or `#[rustfmt::skip::attributes(target_attribute_name)]` Example: ```rust - #![rustfmt::skip::attributes(custom_attribute)] + #![rustfmt::skip::attributes(custom_attribute)] #[custom_attribute(formatting , here , should , be , Skipped)] #[rustfmt::skip::macros(html)] diff --git a/ci/integration.sh b/ci/integration.sh index 13a3ecaa1961c..0269e3ee4af93 100755 --- a/ci/integration.sh +++ b/ci/integration.sh @@ -15,7 +15,7 @@ set -ex # it again. # #which cargo-fmt || cargo install --force -CFG_RELEASE=nightly CFG_RELEASE_CHANNEL=nightly cargo install --path . --force +CFG_RELEASE=nightly CFG_RELEASE_CHANNEL=nightly cargo install --path . --force echo "Integration tests for: ${INTEGRATION}" cargo fmt -- --version diff --git a/docs/index.html b/docs/index.html index 2a12da3881f05..56d1917e2b61b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -85,7 +85,7 @@ outputHtml() { const ast = this.configurationDescriptions .filter(({ head, text, stable }) => { - + if ( text.includes(this.searchCondition) === false && head.includes(this.searchCondition) === false @@ -105,7 +105,7 @@ }, created: async function() { const res = await axios.get(ConfigurationMdUrl); - const { + const { about, configurationAbout, configurationDescriptions @@ -144,7 +144,7 @@ const lastIndex = stack.length - 1; stack[lastIndex].push(next); return stack; - }, + }, [[]]); }); } @@ -179,7 +179,7 @@ configurationAbout, ...configurationDescriptions ] = configurations; configurationAbout.value.links = {}; - + return { about, configurationAbout: configurationAbout.value, From 33acc960f78cfde092a4e720c01896fbff86cdc8 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Wed, 30 Jun 2021 00:13:34 -0400 Subject: [PATCH 07/20] Document rustfmt on nightly-rustc The recursion_limit attribute avoids the following error: ``` error[E0275]: overflow evaluating the requirement `std::ptr::Unique: std::marker::Send` | = help: consider adding a `#![recursion_limit="256"]` attribute to your crate (`rustfmt_nightly`) ``` --- src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib.rs b/src/lib.rs index cde5d390cf259..ce8a45eea6531 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ #![feature(rustc_private)] #![deny(rust_2018_idioms)] #![warn(unreachable_pub)] +#![recursion_limit = "256"] #[macro_use] extern crate derive_new; From abf449ffa657ab10c274595c1d3ec7a69bf801c3 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 5 May 2021 21:31:25 +0200 Subject: [PATCH 08/20] Rework SESSION_GLOBALS API to prevent overwriting it --- src/formatting.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/formatting.rs b/src/formatting.rs index b69ecdc5cb8ae..e0403574eebc1 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -34,7 +34,7 @@ impl<'b, T: Write + 'b> Session<'b, T> { return Err(ErrorKind::VersionMismatch); } - rustc_span::with_session_globals(self.config.edition().into(), || { + rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| { if self.config.disable_all_formatting() { // When the input is from stdin, echo back the input. if let Input::Text(ref buf) = input { From 277feac1f97324dffea0bfc3816ef8d3f73026f3 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 25 Jun 2021 20:43:04 +0200 Subject: [PATCH 09/20] Use LocalExpnId where possible. --- src/utils.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils.rs b/src/utils.rs index d3c349fb701e1..614cda5f911c2 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -6,7 +6,7 @@ use rustc_ast::ast::{ }; use rustc_ast::ptr; use rustc_ast_pretty::pprust; -use rustc_span::{sym, symbol, BytePos, ExpnId, Span, Symbol, SyntaxContext}; +use rustc_span::{sym, symbol, BytePos, LocalExpnId, Span, Symbol, SyntaxContext}; use unicode_width::UnicodeWidthStr; use crate::comment::{filter_normal_code, CharClasses, FullCodeCharKind, LineClasses}; @@ -675,7 +675,7 @@ pub(crate) trait NodeIdExt { impl NodeIdExt for NodeId { fn root() -> NodeId { - NodeId::placeholder_from_expn_id(ExpnId::root()) + NodeId::placeholder_from_expn_id(LocalExpnId::ROOT) } } From 75765f656ebae28dbbc6f93d36a1e851473aeec9 Mon Sep 17 00:00:00 2001 From: Ruby Lazuli Date: Sat, 22 May 2021 08:22:42 -0500 Subject: [PATCH 10/20] Allow `--edition 2021` to be passed to rustfmt This was added to Configurations.md in #4618, but the option wasn't actually made available. This should let people who are using Rust 2021 on nightly rustc run `cargo fmt` again. --- src/bin/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bin/main.rs b/src/bin/main.rs index 56b07222212f8..92fe8b9c51439 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -689,6 +689,7 @@ fn edition_from_edition_str(edition_str: &str) -> Result { match edition_str { "2015" => Ok(Edition::Edition2015), "2018" => Ok(Edition::Edition2018), + "2021" => Ok(Edition::Edition2021), _ => Err(format_err!("Invalid value for `--edition`")), } } From 1ca3798d2c961c43b02e312e8aa0e4bfa3f1b37e Mon Sep 17 00:00:00 2001 From: Casey Rodarmor Date: Sun, 9 May 2021 20:01:24 -0700 Subject: [PATCH 11/20] Improve pasta copyability of `merge_imports` deprecation message Add double quotes around `Crate` so that it can be copied directly into a `Cargo.toml` file --- src/config/config_type.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 2f567b2552106..7fc4486ddcd3d 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -409,7 +409,7 @@ macro_rules! create_config { if self.was_set().merge_imports() { eprintln!( "Warning: the `merge_imports` option is deprecated. \ - Use `imports_granularity=Crate` instead" + Use `imports_granularity=\"Crate\"` instead" ); if !self.was_set().imports_granularity() { self.imports_granularity.2 = if self.merge_imports() { From 486e774fbfbbe2be98cdd2ebdbfc3e8b92fc2a95 Mon Sep 17 00:00:00 2001 From: Michael Murphy Date: Fri, 11 Jun 2021 02:39:28 +0100 Subject: [PATCH 12/20] Adjusting help message (#4865) On stable, running with `--help|-h` shows information about `file-lines` which is a nightly-only option. This commit removes all mention of `file-lines` from the help message on stable. There is room for improvement here; perhaps a new struct called, e.g., `StableOptions` could be added to complement the existing `GetOptsOptions` struct. `StableOptions` could have a field for each field in `GetOptsOptions`, with each field's value being a `bool` that specifies whether or not the option exists on stable. Or is this adding too much complexity? --- src/bin/main.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/bin/main.rs b/src/bin/main.rs index 92fe8b9c51439..4b4aa42d93596 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -178,12 +178,15 @@ fn make_opts() -> Options { opts.optflag("v", "verbose", "Print verbose output"); opts.optflag("q", "quiet", "Print less output"); opts.optflag("V", "version", "Show version information"); - opts.optflagopt( - "h", - "help", - "Show this message or help about a specific topic: `config` or `file-lines`", - "=TOPIC", - ); + let help_topics = if is_nightly { + "`config` or `file-lines`" + } else { + "`config`" + }; + let mut help_topic_msg = "Show this message or help about a specific topic: ".to_owned(); + help_topic_msg.push_str(help_topics); + + opts.optflagopt("h", "help", &help_topic_msg, "=TOPIC"); opts } @@ -437,7 +440,7 @@ fn determine_operation(matches: &Matches) -> Result { return Ok(Operation::Help(HelpOp::None)); } else if topic == Some("config".to_owned()) { return Ok(Operation::Help(HelpOp::Config)); - } else if topic == Some("file-lines".to_owned()) { + } else if topic == Some("file-lines".to_owned()) && is_nightly() { return Ok(Operation::Help(HelpOp::FileLines)); } else { return Err(OperationError::UnknownHelpTopic(topic.unwrap())); From e634a6f9a8ad9435f2d9f6bbfb6a8eb018ee8e3f Mon Sep 17 00:00:00 2001 From: Michael Murphy Date: Wed, 16 Jun 2021 04:33:34 +0100 Subject: [PATCH 13/20] Updating outdated links (#4869) * Updating outdated links Updating the links to the docs and source code for `ast.rs`. Seems like it was moved to a new crate at some point. * Updating more outdated links This time, the links to the `fmt-rfcs` repository, which is now owned by `rust-dev-tools` (although GitHub was redirecting anyway). * Update Contributing.md Co-authored-by: Caleb Cartwright Co-authored-by: Caleb Cartwright --- Contributing.md | 4 ++-- README.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Contributing.md b/Contributing.md index 1b77dad11f0fe..a108195beb9a6 100644 --- a/Contributing.md +++ b/Contributing.md @@ -138,8 +138,8 @@ format. There are different nodes for every kind of item and expression in Rust. For more details see the source code in the compiler - -[ast.rs](https://dxr.mozilla.org/rust/source/src/libsyntax/ast.rs) - and/or the -[docs](https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/index.html). +[ast.rs](https://github.com/rust-lang/rust/blob/master/compiler/rustc_ast/src/ast.rs) - and/or the +[docs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/ast/index.html). Many nodes in the AST (but not all, annoyingly) have a `Span`. A `Span` is a range in the source code, it can easily be converted to a snippet of source diff --git a/README.md b/README.md index 500a9f9a37c8c..9c7a1c4bc341b 100644 --- a/README.md +++ b/README.md @@ -230,5 +230,5 @@ Apache License (Version 2.0). See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT) for details. [rust]: https://github.com/rust-lang/rust -[fmt rfcs]: https://github.com/rust-lang-nursery/fmt-rfcs -[style guide]: https://github.com/rust-lang-nursery/fmt-rfcs/blob/master/guide/guide.md +[fmt rfcs]: https://github.com/rust-dev-tools/fmt-rfcs +[style guide]: https://github.com/rust-dev-tools/fmt-rfcs/blob/master/guide/guide.md From b305d62e5b9e08c6f4540de0a349fbf6da3dc0e4 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Thu, 24 Jun 2021 18:22:28 -0500 Subject: [PATCH 14/20] fix: correct arm leading pipe check (#4880) In the event a pattern starts with a leading pipe the pattern span will contain, and begin with, the pipe. This updates the process to see if a match arm contains a leading pipe by leveraging this recent(ish) change to the patterns in the AST, and avoids an indexing bug that occurs when a pattern starts with a non-ascii char in the old implementation. --- src/matches.rs | 7 ++++--- .../configs/match_arm_leading_pipes/preserve.rs | 8 ++++++++ .../configs/match_arm_leading_pipes/preserve.rs | 8 ++++++++ tests/target/issue_4868.rs | 17 +++++++++++++++++ 4 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 tests/target/issue_4868.rs diff --git a/src/matches.rs b/src/matches.rs index f33fedce92da5..140ec226c02e5 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -19,7 +19,7 @@ use crate::source_map::SpanUtils; use crate::spanned::Spanned; use crate::utils::{ contains_skip, extra_offset, first_line_width, inner_attributes, last_line_extendable, mk_sp, - mk_sp_lo_plus_one, semicolon_for_expr, trimmed_last_line_width, unicode_str_width, + semicolon_for_expr, trimmed_last_line_width, unicode_str_width, }; /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`. @@ -167,8 +167,9 @@ fn collect_beginning_verts( arms.iter() .map(|a| { context - .snippet_provider - .opt_span_before(mk_sp_lo_plus_one(a.pat.span.lo()), "|") + .snippet(a.pat.span) + .starts_with("|") + .then(|| a.pat.span().lo()) }) .collect() } diff --git a/tests/source/configs/match_arm_leading_pipes/preserve.rs b/tests/source/configs/match_arm_leading_pipes/preserve.rs index ea303e857def5..5486877bde190 100644 --- a/tests/source/configs/match_arm_leading_pipes/preserve.rs +++ b/tests/source/configs/match_arm_leading_pipes/preserve.rs @@ -26,3 +26,11 @@ fn bar() { _ => {} } } + +fn f(x: NonAscii) -> bool { + match x { + // foo + | Éfgh => true, + _ => false, + } +} \ No newline at end of file diff --git a/tests/target/configs/match_arm_leading_pipes/preserve.rs b/tests/target/configs/match_arm_leading_pipes/preserve.rs index 2beb1f5d8133d..4775575842ab9 100644 --- a/tests/target/configs/match_arm_leading_pipes/preserve.rs +++ b/tests/target/configs/match_arm_leading_pipes/preserve.rs @@ -25,3 +25,11 @@ fn bar() { _ => {} } } + +fn f(x: NonAscii) -> bool { + match x { + // foo + | Éfgh => true, + _ => false, + } +} diff --git a/tests/target/issue_4868.rs b/tests/target/issue_4868.rs new file mode 100644 index 0000000000000..763a82c3231f1 --- /dev/null +++ b/tests/target/issue_4868.rs @@ -0,0 +1,17 @@ +enum NonAscii { + Abcd, + Éfgh, +} + +use NonAscii::*; + +fn f(x: NonAscii) -> bool { + match x { + Éfgh => true, + _ => false, + } +} + +fn main() { + dbg!(f(Abcd)); +} From 19733f19f18e2f2a1510667c078c7fc7739b3c54 Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Fri, 25 Jun 2021 16:17:43 +0200 Subject: [PATCH 15/20] Change line endings from CRLF to LF --- appveyor.yml | 110 +++++++++++++++++++++++++-------------------------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 7bfe696009fac..5ac99fd71f8f8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,55 +1,55 @@ -# This is based on https://github.com/japaric/rust-everywhere/blob/master/appveyor.yml -# and modified (mainly removal of deployment) to suit rustfmt. - -environment: - global: - PROJECT_NAME: rustfmt - matrix: - # Stable channel - # - TARGET: i686-pc-windows-gnu - # CHANNEL: stable - # - TARGET: i686-pc-windows-msvc - # CHANNEL: stable - # - TARGET: x86_64-pc-windows-gnu - # CHANNEL: stable - # - TARGET: x86_64-pc-windows-msvc - # CHANNEL: stable - # Beta channel - # - TARGET: i686-pc-windows-gnu - # CHANNEL: beta - # - TARGET: i686-pc-windows-msvc - # CHANNEL: beta - # - TARGET: x86_64-pc-windows-gnu - # CHANNEL: beta - # - TARGET: x86_64-pc-windows-msvc - # CHANNEL: beta - # Nightly channel - - TARGET: i686-pc-windows-gnu - CHANNEL: nightly - - TARGET: i686-pc-windows-msvc - CHANNEL: nightly - - TARGET: x86_64-pc-windows-gnu - CHANNEL: nightly - - TARGET: x86_64-pc-windows-msvc - CHANNEL: nightly - -# Install Rust and Cargo -# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml) -install: - - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - if "%TARGET%" == "i686-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw32\bin - - if "%TARGET%" == "x86_64-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw64\bin - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - rustup-init.exe --default-host %TARGET% --default-toolchain %CHANNEL% -y - - rustc -Vv - - cargo -V - -# ??? -build: false - -test_script: - - set CFG_RELEASE_CHANNEL=nightly - - set CFG_RELEASE=nightly - - cargo build --verbose - - cargo test - - cargo test -- --ignored +# This is based on https://github.com/japaric/rust-everywhere/blob/master/appveyor.yml +# and modified (mainly removal of deployment) to suit rustfmt. + +environment: + global: + PROJECT_NAME: rustfmt + matrix: + # Stable channel + # - TARGET: i686-pc-windows-gnu + # CHANNEL: stable + # - TARGET: i686-pc-windows-msvc + # CHANNEL: stable + # - TARGET: x86_64-pc-windows-gnu + # CHANNEL: stable + # - TARGET: x86_64-pc-windows-msvc + # CHANNEL: stable + # Beta channel + # - TARGET: i686-pc-windows-gnu + # CHANNEL: beta + # - TARGET: i686-pc-windows-msvc + # CHANNEL: beta + # - TARGET: x86_64-pc-windows-gnu + # CHANNEL: beta + # - TARGET: x86_64-pc-windows-msvc + # CHANNEL: beta + # Nightly channel + - TARGET: i686-pc-windows-gnu + CHANNEL: nightly + - TARGET: i686-pc-windows-msvc + CHANNEL: nightly + - TARGET: x86_64-pc-windows-gnu + CHANNEL: nightly + - TARGET: x86_64-pc-windows-msvc + CHANNEL: nightly + +# Install Rust and Cargo +# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml) +install: + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - if "%TARGET%" == "i686-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw32\bin + - if "%TARGET%" == "x86_64-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw64\bin + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - rustup-init.exe --default-host %TARGET% --default-toolchain %CHANNEL% -y + - rustc -Vv + - cargo -V + +# ??? +build: false + +test_script: + - set CFG_RELEASE_CHANNEL=nightly + - set CFG_RELEASE=nightly + - cargo build --verbose + - cargo test + - cargo test -- --ignored From 2cf280ed1ba84001aa4e14152ae37cea18ebcb1c Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 4 Jul 2021 22:26:08 -0500 Subject: [PATCH 16/20] docs: clarify match_arm_blocks config documentation --- Configurations.md | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/Configurations.md b/Configurations.md index 9daa706537976..d2e5613eba964 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1475,7 +1475,9 @@ Copyright 2018 The Rust Project Developers.`, etc.: ## `match_arm_blocks` -Wrap the body of arms in blocks when it does not fit on the same line with the pattern of arms +Controls whether arm bodies are wrapped in cases where the first line of the body cannot fit on the same line as the `=>` operator. + +The Style Guide requires that bodies are block wrapped by default if a line break is required after the `=>`, but this option can be used to disable that behavior to prevent wrapping arm bodies in that event, so long as the body does not contain multiple statements nor line comments. - **Default value**: `true` - **Possible values**: `true`, `false` @@ -1486,10 +1488,16 @@ Wrap the body of arms in blocks when it does not fit on the same line with the p ```rust fn main() { match lorem { - true => { + ipsum => { foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(x) } - false => println!("{}", sit), + dolor => println!("{}", sit), + sit => foo( + "foooooooooooooooooooooooo", + "baaaaaaaaaaaaaaaaaaaaaaaarr", + "baaaaaaaaaaaaaaaaaaaazzzzzzzzzzzzz", + "qqqqqqqqquuuuuuuuuuuuuuuuuuuuuuuuuuxxx", + ), } } ``` @@ -1499,9 +1507,15 @@ fn main() { ```rust fn main() { match lorem { - true => + lorem => foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(x), - false => println!("{}", sit), + ipsum => println!("{}", sit), + sit => foo( + "foooooooooooooooooooooooo", + "baaaaaaaaaaaaaaaaaaaaaaaarr", + "baaaaaaaaaaaaaaaaaaaazzzzzzzzzzzzz", + "qqqqqqqqquuuuuuuuuuuuuuuuuuuuuuuuuuxxx", + ), } } ``` From 4c2959fb12a6bd083003ec4371126211402e265d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sun, 18 Jul 2021 10:44:39 +0200 Subject: [PATCH 17/20] fix a bunch of clippy warnings clippy::bind_instead_of_map clippy::branches_sharing_code clippy::collapsible_match clippy::inconsistent_struct_constructor clippy::int_plus_one clippy::iter_count clippy::iter_nth_zero clippy::manual_range_contains clippy::match_like_matches_macro clippy::needless::collect clippy::needless_question_mark clippy::needless_return clippy::op_ref clippy::option_as_ref_deref clippy::ptr_arg clippy::redundant_clone clippy::redundant_closure clippy::redundant_static_lifetimes clippy::search_is_some clippy::#single_char_add_str clippy::single_char_pattern clippy::single_component_path_imports clippy::single_match clippy::skip_while_next clippy::unnecessary_lazy_evaluations clippy::unnecessary_unwrap clippy::useless_conversion clippy::useless_format --- src/attr.rs | 2 +- src/cargo-fmt/main.rs | 4 ++-- src/chains.rs | 5 +---- src/closures.rs | 15 +++++-------- src/comment.rs | 21 ++++++++---------- src/config/file_lines.rs | 4 ++-- src/config/license.rs | 1 - src/emitter/diff.rs | 2 +- src/expr.rs | 30 +++++++++---------------- src/formatting/newline_style.rs | 2 +- src/imports.rs | 30 ++++++++++--------------- src/issues.rs | 14 +++--------- src/items.rs | 26 +++++++++------------- src/lib.rs | 6 +---- src/lists.rs | 11 ++++------ src/macros.rs | 39 +++++++++++++++------------------ src/missed_spans.rs | 8 +++---- src/overflow.rs | 28 ++++++++++------------- src/patterns.rs | 25 ++++++++++----------- src/rustfmt_diff.rs | 7 ++---- src/skip.rs | 6 ++--- src/source_file.rs | 2 +- src/string.rs | 4 ++-- src/syntux/parser.rs | 5 ++--- src/types.rs | 15 ++++--------- src/utils.rs | 5 ++--- src/visitor.rs | 18 +++++++-------- 27 files changed, 130 insertions(+), 205 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index c5ffb074ba554..315eb10a9dbc0 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -183,7 +183,7 @@ fn format_derive( } else if let SeparatorTactic::Always = context.config.trailing_comma() { // Retain the trailing comma. result.push_str(&item_str); - } else if item_str.ends_with(",") { + } else if item_str.ends_with(',') { // Remove the trailing comma. result.push_str(&item_str[..item_str.len() - 1]); } else { diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 9062a2952ec1a..ba693e852ffa6 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -405,8 +405,8 @@ fn get_targets_recursive( .packages .iter() .find(|p| p.name == dependency.name && p.source.is_none()); - let manifest_path = if dependency_package.is_some() { - PathBuf::from(&dependency_package.unwrap().manifest_path) + let manifest_path = if let Some(dep_pkg) = dependency_package { + PathBuf::from(&dep_pkg.manifest_path) } else { let mut package_manifest_path = PathBuf::from(&package.manifest_path); package_manifest_path.pop(); diff --git a/src/chains.rs b/src/chains.rs index 8053f0e8fecc1..614638ea2abfb 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -231,10 +231,7 @@ impl ChainItem { } fn is_comment(&self) -> bool { - match self.kind { - ChainItemKind::Comment(..) => true, - _ => false, - } + matches!(self.kind, ChainItemKind::Comment(..)) } fn rewrite_method_call( diff --git a/src/closures.rs b/src/closures.rs index 3d65077ddc209..c9d46aef294a0 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -336,7 +336,7 @@ pub(crate) fn rewrite_last_closure( // We force to use block for the body of the closure for certain kinds of expressions. if is_block_closure_forced(context, body) { - return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then( + return rewrite_closure_with_block(body, &prefix, context, body_shape).map( |body_str| { match fn_decl.output { ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => { @@ -344,15 +344,15 @@ pub(crate) fn rewrite_last_closure( // closure. However, if the closure has a return type, then we must // keep the blocks. match rewrite_closure_expr(body, &prefix, context, shape) { - Some(ref single_line_body_str) + Some(single_line_body_str) if !single_line_body_str.contains('\n') => { - Some(single_line_body_str.clone()) + single_line_body_str } - _ => Some(body_str), + _ => body_str, } } - _ => Some(body_str), + _ => body_str, } }, ); @@ -377,10 +377,7 @@ pub(crate) fn rewrite_last_closure( pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool { args.iter() .filter_map(OverflowableItem::to_expr) - .filter(|expr| match expr.kind { - ast::ExprKind::Closure(..) => true, - _ => false, - }) + .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..))) .count() > 1 } diff --git a/src/comment.rs b/src/comment.rs index c71302fdd182b..0f8118a408ec0 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -67,10 +67,7 @@ impl<'a> CommentStyle<'a> { /// Returns `true` if the commenting style is for documentation. pub(crate) fn is_doc_comment(&self) -> bool { - match *self { - CommentStyle::TripleSlash | CommentStyle::Doc => true, - _ => false, - } + matches!(*self, CommentStyle::TripleSlash | CommentStyle::Doc) } pub(crate) fn opener(&self) -> &'a str { @@ -689,8 +686,8 @@ impl<'a> CommentRewrite<'a> { self.code_block_attr = None; self.item_block = None; - if line.starts_with("```") { - self.code_block_attr = Some(CodeBlockAttribute::new(&line[3..])) + if let Some(stripped) = line.strip_prefix("```") { + self.code_block_attr = Some(CodeBlockAttribute::new(stripped)) } else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(&line) { let ib = ItemizedBlock::new(&line); self.item_block = Some(ib); @@ -948,8 +945,8 @@ fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a s { (&line[4..], true) } else if let CommentStyle::Custom(opener) = *style { - if line.starts_with(opener) { - (&line[opener.len()..], true) + if let Some(ref stripped) = line.strip_prefix(opener) { + (stripped, true) } else { (&line[opener.trim_end().len()..], false) } @@ -968,8 +965,8 @@ fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a s || line.starts_with("**") { (&line[2..], line.chars().nth(1).unwrap() == ' ') - } else if line.starts_with('*') { - (&line[1..], false) + } else if let Some(stripped) = line.strip_prefix('*') { + (stripped, false) } else { (line, line.starts_with(' ')) } @@ -1682,8 +1679,8 @@ impl<'a> Iterator for CommentReducer<'a> { fn remove_comment_header(comment: &str) -> &str { if comment.starts_with("///") || comment.starts_with("//!") { &comment[3..] - } else if comment.starts_with("//") { - &comment[2..] + } else if let Some(ref stripped) = comment.strip_prefix("//") { + stripped } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) || comment.starts_with("/*!") { diff --git a/src/config/file_lines.rs b/src/config/file_lines.rs index 22dd091cb5101..4b799780d85d9 100644 --- a/src/config/file_lines.rs +++ b/src/config/file_lines.rs @@ -305,7 +305,7 @@ impl str::FromStr for FileLines { let mut m = HashMap::new(); for js in v { let (s, r) = JsonSpan::into_tuple(js)?; - m.entry(s).or_insert_with(|| vec![]).push(r); + m.entry(s).or_insert_with(Vec::new).push(r); } Ok(FileLines::from_ranges(m)) } @@ -322,7 +322,7 @@ impl JsonSpan { fn into_tuple(self) -> Result<(FileName, Range), FileLinesError> { let (lo, hi) = self.range; let canonical = canonicalize_path_string(&self.file) - .ok_or_else(|| FileLinesError::CannotCanonicalize(self.file))?; + .ok_or(FileLinesError::CannotCanonicalize(self.file))?; Ok((canonical, Range::new(lo, hi))) } } diff --git a/src/config/license.rs b/src/config/license.rs index 121a1b1c151f4..c7feb502ea91e 100644 --- a/src/config/license.rs +++ b/src/config/license.rs @@ -3,7 +3,6 @@ use std::fs::File; use std::io; use std::io::Read; -use regex; use regex::Regex; #[derive(Debug)] diff --git a/src/emitter/diff.rs b/src/emitter/diff.rs index 9be4fb28f993f..2fbbfedb566d1 100644 --- a/src/emitter/diff.rs +++ b/src/emitter/diff.rs @@ -45,7 +45,7 @@ impl Emitter for DiffEmitter { return Ok(EmitterResult { has_diff: true }); } - return Ok(EmitterResult { has_diff }); + Ok(EmitterResult { has_diff }) } } diff --git a/src/expr.rs b/src/expr.rs index bca9f77f959e3..6cfeb9977a966 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -263,15 +263,12 @@ pub(crate) fn format_expr( } fn needs_space_after_range(rhs: &ast::Expr) -> bool { - match rhs.kind { - // Don't format `.. ..` into `....`, which is invalid. - // - // This check is unnecessary for `lhs`, because a range - // starting from another range needs parentheses as `(x ..) ..` - // (`x .. ..` is a range from `x` to `..`). - ast::ExprKind::Range(None, _, _) => true, - _ => false, - } + // Don't format `.. ..` into `....`, which is invalid. + // + // This check is unnecessary for `lhs`, because a range + // starting from another range needs parentheses as `(x ..) ..` + // (`x .. ..` is a range from `x` to `..`). + matches!(rhs.kind, ast::ExprKind::Range(None, _, _)) } let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| { @@ -531,7 +528,7 @@ pub(crate) fn rewrite_block_with_visitor( let inner_attrs = attrs.map(inner_attributes); let label_str = rewrite_label(label); - visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces); + visitor.visit_block(block, inner_attrs.as_deref(), has_braces); let visitor_context = visitor.get_context(); context .skipped_range @@ -595,7 +592,7 @@ pub(crate) fn rewrite_cond( String::from("\n") + &shape.indent.block_only().to_string(context.config); control_flow .rewrite_cond(context, shape, &alt_block_sep) - .and_then(|rw| Some(rw.0)) + .map(|rw| rw.0) }), } } @@ -1157,18 +1154,11 @@ pub(crate) fn is_empty_block( } pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool { - match stmt.kind { - ast::StmtKind::Expr(..) => true, - _ => false, - } + matches!(stmt.kind, ast::StmtKind::Expr(..)) } pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool { - if let ast::BlockCheckMode::Unsafe(..) = block.rules { - true - } else { - false - } + matches!(block.rules, ast::BlockCheckMode::Unsafe(..)) } pub(crate) fn rewrite_literal( diff --git a/src/formatting/newline_style.rs b/src/formatting/newline_style.rs index ac62009490001..97c4fc16d6f5d 100644 --- a/src/formatting/newline_style.rs +++ b/src/formatting/newline_style.rs @@ -77,7 +77,7 @@ fn convert_to_windows_newlines(formatted_text: &String) -> String { transformed } -fn convert_to_unix_newlines(formatted_text: &String) -> String { +fn convert_to_unix_newlines(formatted_text: &str) -> String { formatted_text.replace(WINDOWS_NEWLINE, UNIX_NEWLINE) } diff --git a/src/imports.rs b/src/imports.rs index 0f635fe1ccb35..64d78605f0c5f 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -374,7 +374,7 @@ impl UseTree { UseTreeKind::Nested(ref list) => { // Extract comments between nested use items. // This needs to be done before sorting use items. - let items: Vec<_> = itemize_list( + let items = itemize_list( context.snippet_provider, list.iter().map(|(tree, _)| tree), "}", @@ -385,8 +385,8 @@ impl UseTree { context.snippet_provider.span_after(a.span, "{"), a.span.hi(), false, - ) - .collect(); + ); + // in case of a global path and the nested list starts at the root, // e.g., "::{foo, bar}" if a.prefix.segments.len() == 1 && leading_modsep { @@ -394,7 +394,7 @@ impl UseTree { } result.path.push(UseSegment::List( list.iter() - .zip(items.into_iter()) + .zip(items) .map(|(t, list_item)| { Self::from_ast(context, &t.0, Some(list_item), None, None, None) }) @@ -466,11 +466,8 @@ impl UseTree { // Normalise foo::self as bar -> foo as bar. if let UseSegment::Slf(_) = last { - match self.path.last() { - Some(UseSegment::Ident(_, None)) => { - aliased_self = true; - } - _ => {} + if let Some(UseSegment::Ident(_, None)) = self.path.last() { + aliased_self = true; } } @@ -572,9 +569,8 @@ impl UseTree { match self.path.clone().last().unwrap() { UseSegment::List(list) => { if list.len() == 1 && list[0].path.len() == 1 { - match list[0].path[0] { - UseSegment::Slf(..) => return vec![self], - _ => (), + if let UseSegment::Slf(..) = list[0].path[0] { + return vec![self]; }; } let prefix = &self.path[..self.path.len() - 1]; @@ -790,13 +786,9 @@ fn rewrite_nested_use_tree( } } let has_nested_list = use_tree_list.iter().any(|use_segment| { - use_segment - .path - .last() - .map_or(false, |last_segment| match last_segment { - UseSegment::List(..) => true, - _ => false, - }) + use_segment.path.last().map_or(false, |last_segment| { + matches!(last_segment, UseSegment::List(..)) + }) }); let remaining_width = if has_nested_list { diff --git a/src/issues.rs b/src/issues.rs index d369b75541ef9..33fb5522aeae5 100644 --- a/src/issues.rs +++ b/src/issues.rs @@ -126,11 +126,7 @@ impl BadIssueSeeker { return Seeking::Number { issue: Issue { issue_type: IssueType::Todo, - missing_number: if let ReportTactic::Unnumbered = self.report_todo { - true - } else { - false - }, + missing_number: matches!(self.report_todo, ReportTactic::Unnumbered), }, part: NumberPart::OpenParen, }; @@ -144,11 +140,7 @@ impl BadIssueSeeker { return Seeking::Number { issue: Issue { issue_type: IssueType::Fixme, - missing_number: if let ReportTactic::Unnumbered = self.report_fixme { - true - } else { - false - }, + missing_number: matches!(self.report_fixme, ReportTactic::Unnumbered), }, part: NumberPart::OpenParen, }; @@ -196,7 +188,7 @@ impl BadIssueSeeker { } } NumberPart::Number => { - if c >= '0' && c <= '9' { + if ('0'..='9').contains(&c) { part = NumberPart::CloseParen; } else { return IssueClassification::Bad(issue); diff --git a/src/items.rs b/src/items.rs index 420484c0ba11e..0542358c6e7c5 100644 --- a/src/items.rs +++ b/src/items.rs @@ -741,7 +741,7 @@ pub(crate) fn format_impl( // there is only one where-clause predicate // recover the suppressed comma in single line where_clause formatting if generics.where_clause.predicates.len() == 1 { - result.push_str(","); + result.push(','); } result.push_str(&format!("{}{{{}}}", sep, sep)); } else { @@ -1207,7 +1207,7 @@ impl<'a> Rewrite for TraitAliasBounds<'a> { let fits_single_line = !generic_bounds_str.contains('\n') && !where_str.contains('\n') - && generic_bounds_str.len() + where_str.len() + 1 <= shape.width; + && generic_bounds_str.len() + where_str.len() < shape.width; let space = if generic_bounds_str.is_empty() || where_str.is_empty() { Cow::from("") } else if fits_single_line { @@ -1236,8 +1236,8 @@ pub(crate) fn format_trait_alias( let lhs = format!("{}trait {} =", vis_str, generics_str); // 1 = ";" let trait_alias_bounds = TraitAliasBounds { - generics, generic_bounds, + generics, }; rewrite_assign_rhs(context, lhs, &trait_alias_bounds, shape.sub_width(1)?).map(|s| s + ";") } @@ -1993,7 +1993,7 @@ impl Rewrite for ast::Param { let num_attrs = self.attrs.len(); ( mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()), - param_attrs_result.contains("\n"), + param_attrs_result.contains('\n'), ) } else { (mk_sp(self.span.lo(), self.span.lo()), false) @@ -3265,22 +3265,16 @@ pub(crate) fn rewrite_extern_crate( /// Returns `true` for `mod foo;`, false for `mod foo { .. }`. pub(crate) fn is_mod_decl(item: &ast::Item) -> bool { - match item.kind { - ast::ItemKind::Mod(_, ast::ModKind::Loaded(_, ast::Inline::Yes, _)) => false, - _ => true, - } + !matches!( + item.kind, + ast::ItemKind::Mod(_, ast::ModKind::Loaded(_, ast::Inline::Yes, _)) + ) } pub(crate) fn is_use_item(item: &ast::Item) -> bool { - match item.kind { - ast::ItemKind::Use(_) => true, - _ => false, - } + matches!(item.kind, ast::ItemKind::Use(_)) } pub(crate) fn is_extern_crate(item: &ast::Item) -> bool { - match item.kind { - ast::ItemKind::ExternCrate(..) => true, - _ => false, - } + matches!(item.kind, ast::ItemKind::ExternCrate(..)) } diff --git a/src/lib.rs b/src/lib.rs index ce8a45eea6531..eb314e63de368 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,7 +30,6 @@ use std::panic; use std::path::PathBuf; use std::rc::Rc; -use ignore; use rustc_ast::ast; use rustc_span::{symbol, DUMMY_SP}; use thiserror::Error; @@ -149,10 +148,7 @@ pub enum ErrorKind { impl ErrorKind { fn is_comment(&self) -> bool { - match self { - ErrorKind::LostComment => true, - _ => false, - } + matches!(self, ErrorKind::LostComment) } } diff --git a/src/lists.rs b/src/lists.rs index ccf8f784c0454..73e886c55637e 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -194,10 +194,7 @@ impl ListItem { // Returns `true` if the item causes something to be written. fn is_substantial(&self) -> bool { fn empty(s: &Option) -> bool { - match *s { - Some(ref s) if !s.is_empty() => false, - _ => true, - } + !matches!(*s, Some(ref s) if !s.is_empty()) } !(empty(&self.pre_comment) && empty(&self.item) && empty(&self.post_comment)) @@ -618,8 +615,8 @@ pub(crate) fn extract_post_comment( let post_snippet = post_snippet[..comment_end].trim(); let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') { post_snippet[1..].trim_matches(white_space) - } else if post_snippet.starts_with(separator) { - post_snippet[separator.len()..].trim_matches(white_space) + } else if let Some(stripped) = post_snippet.strip_prefix(separator) { + stripped.trim_matches(white_space) } // not comment or over two lines else if post_snippet.ends_with(',') @@ -823,7 +820,7 @@ where pub(crate) fn total_item_width(item: &ListItem) -> usize { comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) - + &item.item.as_ref().map_or(0, |s| unicode_str_width(&s)) + + item.item.as_ref().map_or(0, |s| unicode_str_width(&s)) } fn comment_len(comment: Option<&str>) -> usize { diff --git a/src/macros.rs b/src/macros.rs index bf4769b34aa84..6c5e32716c017 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -179,10 +179,10 @@ fn return_macro_parse_failure_fallback( .lines() .last() .map(|closing_line| { - closing_line.trim().chars().all(|ch| match ch { - '}' | ')' | ']' => true, - _ => false, - }) + closing_line + .trim() + .chars() + .all(|ch| matches!(ch, '}' | ')' | ']')) }) .unwrap_or(false); if is_like_block_indent_style { @@ -690,25 +690,22 @@ fn delim_token_to_str( impl MacroArgKind { fn starts_with_brace(&self) -> bool { - match *self { + matches!( + *self, MacroArgKind::Repeat(DelimToken::Brace, _, _, _) - | MacroArgKind::Delimited(DelimToken::Brace, _) => true, - _ => false, - } + | MacroArgKind::Delimited(DelimToken::Brace, _) + ) } fn starts_with_dollar(&self) -> bool { - match *self { - MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true, - _ => false, - } + matches!( + *self, + MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) + ) } fn ends_with_space(&self) -> bool { - match *self { - MacroArgKind::Separator(..) => true, - _ => false, - } + matches!(*self, MacroArgKind::Separator(..)) } fn has_meta_var(&self) -> bool { @@ -1162,10 +1159,10 @@ fn force_space_before(tok: &TokenKind) -> bool { } fn ident_like(tok: &Token) -> bool { - match tok.kind { - TokenKind::Ident(..) | TokenKind::Literal(..) | TokenKind::Lifetime(_) => true, - _ => false, - } + matches!( + tok.kind, + TokenKind::Ident(..) | TokenKind::Literal(..) | TokenKind::Lifetime(_) + ) } fn next_space(tok: &TokenKind) -> SpaceState { @@ -1399,7 +1396,7 @@ impl MacroBranch { // Undo our replacement of macro variables. // FIXME: this could be *much* more efficient. for (old, new) in &substs { - if old_body.find(new).is_some() { + if old_body.contains(new) { debug!("rewrite_macro_def: bailing matching variable: `{}`", new); return None; } diff --git a/src/missed_spans.rs b/src/missed_spans.rs index 17b11ed6cf49c..263d840785a29 100644 --- a/src/missed_spans.rs +++ b/src/missed_spans.rs @@ -230,8 +230,7 @@ impl<'a> FmtVisitor<'a> { let last_char = big_snippet .chars() .rev() - .skip_while(|rev_c| [' ', '\t'].contains(rev_c)) - .next(); + .find(|rev_c| ![' ', '\t'].contains(rev_c)); let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c)); let mut on_same_line = false; @@ -262,7 +261,7 @@ impl<'a> FmtVisitor<'a> { let comment_shape = Shape::legacy(comment_width, comment_indent); if on_same_line { - match subslice.find("\n") { + match subslice.find('\n') { None => { self.push_str(subslice); } @@ -299,8 +298,7 @@ impl<'a> FmtVisitor<'a> { match snippet[status.line_start..] .chars() // skip trailing whitespaces - .skip_while(|c| *c == ' ' || *c == '\t') - .next() + .find(|c| !(*c == ' ' || *c == '\t')) { Some('\n') | Some('\r') => { if !is_last_comment_block(subslice) { diff --git a/src/overflow.rs b/src/overflow.rs index d670b0a41e818..e32213467a51f 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -126,21 +126,19 @@ impl<'a> OverflowableItem<'a> { OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr), OverflowableItem::NestedMetaItem(nested_meta_item) => match nested_meta_item { ast::NestedMetaItem::Literal(..) => true, - ast::NestedMetaItem::MetaItem(ref meta_item) => match meta_item.kind { - ast::MetaItemKind::Word => true, - _ => false, - }, + ast::NestedMetaItem::MetaItem(ref meta_item) => { + matches!(meta_item.kind, ast::MetaItemKind::Word) + } }, _ => false, } } pub(crate) fn is_expr(&self) -> bool { - match self { - OverflowableItem::Expr(..) => true, - OverflowableItem::MacroArg(MacroArg::Expr(..)) => true, - _ => false, - } + matches!( + self, + OverflowableItem::Expr(..) | OverflowableItem::MacroArg(MacroArg::Expr(..)) + ) } pub(crate) fn is_nested_call(&self) -> bool { @@ -154,10 +152,7 @@ impl<'a> OverflowableItem<'a> { pub(crate) fn to_expr(&self) -> Option<&'a ast::Expr> { match self { OverflowableItem::Expr(expr) => Some(expr), - OverflowableItem::MacroArg(macro_arg) => match macro_arg { - MacroArg::Expr(ref expr) => Some(expr), - _ => None, - }, + OverflowableItem::MacroArg(MacroArg::Expr(ref expr)) => Some(expr), _ => None, } } @@ -178,10 +173,9 @@ impl<'a> OverflowableItem<'a> { ast::NestedMetaItem::MetaItem(..) => true, } } - OverflowableItem::SegmentParam(seg) => match seg { - SegmentParam::Type(ty) => can_be_overflowed_type(context, ty, len), - _ => false, - }, + OverflowableItem::SegmentParam(SegmentParam::Type(ty)) => { + can_be_overflowed_type(context, ty, len) + } OverflowableItem::TuplePatField(pat) => can_be_overflowed_pat(context, pat, len), OverflowableItem::Ty(ty) => can_be_overflowed_type(context, ty, len), _ => false, diff --git a/src/patterns.rs b/src/patterns.rs index fa0ef260991d7..062e9cef9bbd3 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -238,7 +238,7 @@ impl Rewrite for Pat { if let Some(rw) = p.rewrite(context, shape) { rw } else { - format!("{}", context.snippet(p.span)) + context.snippet(p.span).to_string() } }) .collect(); @@ -310,23 +310,22 @@ fn rewrite_struct_pat( if fields_str.contains('\n') || fields_str.len() > one_line_width { // Add a missing trailing comma. if context.config.trailing_comma() == SeparatorTactic::Never { - fields_str.push_str(","); + fields_str.push(','); } - fields_str.push_str("\n"); + fields_str.push('\n'); fields_str.push_str(&nested_shape.indent.to_string(context.config)); - fields_str.push_str(".."); } else { if !fields_str.is_empty() { // there are preceding struct fields being matched on if tactic == DefinitiveListTactic::Vertical { // if the tactic is Vertical, write_list already added a trailing , - fields_str.push_str(" "); + fields_str.push(' '); } else { fields_str.push_str(", "); } } - fields_str.push_str(".."); } + fields_str.push_str(".."); } // ast::Pat doesn't have attrs so use &[] @@ -411,10 +410,7 @@ impl<'a> Spanned for TuplePatField<'a> { impl<'a> TuplePatField<'a> { fn is_dotdot(&self) -> bool { match self { - TuplePatField::Pat(pat) => match pat.kind { - ast::PatKind::Rest => true, - _ => false, - }, + TuplePatField::Pat(pat) => matches!(pat.kind, ast::PatKind::Rest), TuplePatField::Dotdot(_) => true, } } @@ -510,10 +506,11 @@ fn count_wildcard_suffix_len( ) .collect(); - for item in items.iter().rev().take_while(|i| match i.item { - Some(ref internal_string) if internal_string == "_" => true, - _ => false, - }) { + for item in items + .iter() + .rev() + .take_while(|i| matches!(i.item, Some(ref internal_string) if internal_string == "_")) + { suffix_len += 1; if item.has_comment() { diff --git a/src/rustfmt_diff.rs b/src/rustfmt_diff.rs index fc2c7d06e264e..a394ce07398ef 100644 --- a/src/rustfmt_diff.rs +++ b/src/rustfmt_diff.rs @@ -56,10 +56,7 @@ impl From> for ModifiedLines { let chunks = mismatches.into_iter().map(|mismatch| { let lines = mismatch.lines.iter(); let num_removed = lines - .filter(|line| match line { - DiffLine::Resulting(_) => true, - _ => false, - }) + .filter(|line| matches!(line, DiffLine::Resulting(_))) .count(); let new_lines = mismatch.lines.into_iter().filter_map(|line| match line { @@ -94,7 +91,7 @@ impl fmt::Display for ModifiedLines { "{} {} {}", chunk.line_number_orig, chunk.lines_removed, - chunk.lines.iter().count() + chunk.lines.len() )?; for line in &chunk.lines { diff --git a/src/skip.rs b/src/skip.rs index 6c500635a9551..0fdc097efc23f 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -32,8 +32,8 @@ impl SkipContext { } } -static RUSTFMT: &'static str = "rustfmt"; -static SKIP: &'static str = "skip"; +static RUSTFMT: &str = "rustfmt"; +static SKIP: &str = "skip"; /// Say if you're playing with `rustfmt`'s skip attribute pub(crate) fn is_skip_attr(segments: &[ast::PathSegment]) -> bool { @@ -46,7 +46,7 @@ pub(crate) fn is_skip_attr(segments: &[ast::PathSegment]) -> bool { segments[1].ident.to_string() == SKIP && ["macros", "attributes"] .iter() - .any(|&n| n == &pprust::path_segment_to_string(&segments[2])) + .any(|&n| n == pprust::path_segment_to_string(&segments[2])) } _ => false, } diff --git a/src/source_file.rs b/src/source_file.rs index 5a9a2cbd80c7e..853336004d8b1 100644 --- a/src/source_file.rs +++ b/src/source_file.rs @@ -18,7 +18,7 @@ use rustc_data_structures::sync::Lrc; // Append a newline to the end of each file. pub(crate) fn append_newline(s: &mut String) { - s.push_str("\n"); + s.push('\n'); } #[cfg(test)] diff --git a/src/string.rs b/src/string.rs index 080c4f1778823..0cb9d817ca2d3 100644 --- a/src/string.rs +++ b/src/string.rs @@ -57,7 +57,7 @@ impl<'a> StringFormat<'a> { /// This allows to fit more graphemes from the string on a line when /// SnippetState::EndWithLineFeed. fn max_width_without_indent(&self) -> Option { - Some(self.config.max_width().checked_sub(self.line_end.len())?) + self.config.max_width().checked_sub(self.line_end.len()) } } @@ -99,7 +99,7 @@ pub(crate) fn rewrite_string<'a>( if is_new_line(grapheme) { // take care of blank lines result = trim_end_but_line_feed(fmt.trim_end, result); - result.push_str("\n"); + result.push('\n'); if !is_bareline_ok && cur_start + i + 1 < graphemes.len() { result.push_str(&indent_without_newline); result.push_str(fmt.line_start); diff --git a/src/syntux/parser.rs b/src/syntux/parser.rs index 0b94749f3c6f4..b5fe4335dd33d 100644 --- a/src/syntux/parser.rs +++ b/src/syntux/parser.rs @@ -79,7 +79,7 @@ impl<'a> ParserBuilder<'a> { rustc_span::FileName::Custom("stdin".to_owned()), text, ) - .map_err(|db| Some(db)), + .map_err(Some), } } } @@ -196,8 +196,7 @@ impl<'a> Parser<'a> { mac: &'a ast::MacCall, ) -> Result, &'static str> { let token_stream = mac.args.inner_tokens(); - let mut parser = - rustc_parse::stream_to_parser(sess.inner(), token_stream.clone(), Some("")); + let mut parser = rustc_parse::stream_to_parser(sess.inner(), token_stream, Some("")); let mut items = vec![]; let mut process_if_cfg = true; diff --git a/src/types.rs b/src/types.rs index 974c0c5990c7d..c6f89c310650c 100644 --- a/src/types.rs +++ b/src/types.rs @@ -662,7 +662,7 @@ impl Rewrite for ast::Ty { let mut_str = format_mutability(mt.mutbl); let mut_len = mut_str.len(); let mut result = String::with_capacity(128); - result.push_str("&"); + result.push('&'); let ref_hi = context.snippet_provider.span_after(self.span(), "&"); let mut cmnt_lo = ref_hi; @@ -685,7 +685,7 @@ impl Rewrite for ast::Ty { } else { result.push_str(<_str); } - result.push_str(" "); + result.push(' '); cmnt_lo = lifetime.ident.span.hi(); } @@ -1048,11 +1048,7 @@ fn join_bounds_inner( true, ) .map(|v| (v, trailing_span, extendable)), - _ => Some(( - String::from(strs) + &trailing_str, - trailing_span, - extendable, - )), + _ => Some((strs + &trailing_str, trailing_span, extendable)), } }, )?; @@ -1089,10 +1085,7 @@ fn rewrite_lifetime_param( ) -> Option { let result = generic_params .iter() - .filter(|p| match p.kind { - ast::GenericParamKind::Lifetime => true, - _ => false, - }) + .filter(|p| matches!(p.kind, ast::GenericParamKind::Lifetime)) .map(|lt| lt.rewrite(context, shape)) .collect::>>()? .join(", "); diff --git a/src/utils.rs b/src/utils.rs index 614cda5f911c2..06159a1b26e86 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -191,7 +191,7 @@ pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec #[inline] pub(crate) fn is_single_line(s: &str) -> bool { - s.chars().find(|&c| c == '\n').is_none() + !s.chars().any(|c| c == '\n') } #[inline] @@ -260,8 +260,7 @@ fn is_skip(meta_item: &MetaItem) -> bool { match meta_item.kind { MetaItemKind::Word => { let path_str = pprust::path_to_string(&meta_item.path); - path_str == &*skip_annotation().as_str() - || path_str == &*depr_skip_annotation().as_str() + path_str == *skip_annotation().as_str() || path_str == *depr_skip_annotation().as_str() } MetaItemKind::List(ref l) => { meta_item.has_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1]) diff --git a/src/visitor.rs b/src/visitor.rs index 079568630cf52..3f251bf7c16b3 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -198,7 +198,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let missing_span = self.next_span(hi); let snippet = self.snippet(missing_span); let len = CommentCodeSlices::new(snippet) - .nth(0) + .next() .and_then(|(kind, _, s)| { if kind == CodeCharKind::Normal { s.rfind('\n') @@ -293,7 +293,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } let span_in_between = mk_sp(last_hi, span.lo() + BytePos::from_usize(offset)); let snippet_in_between = self.snippet(span_in_between); - let mut comment_on_same_line = !snippet_in_between.contains("\n"); + let mut comment_on_same_line = !snippet_in_between.contains('\n'); let mut comment_shape = Shape::indented(self.block_indent, config).comment(config); @@ -301,7 +301,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.push_str(" "); // put the first line of the comment on the same line as the // block's last line - match sub_slice.find("\n") { + match sub_slice.find('\n') { None => { self.push_str(&sub_slice); } @@ -764,7 +764,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let hi = self.snippet_provider.span_before(search_span, ";"); let target_span = mk_sp(mac.span().lo(), hi + BytePos(1)); let rewrite = rewrite.map(|rw| { - if !rw.ends_with(";") { + if !rw.ends_with(';') { format!("{};", rw) } else { rw @@ -921,7 +921,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { !is_skip_attr(segments) } - fn walk_mod_items(&mut self, items: &Vec>) { + fn walk_mod_items(&mut self, items: &[rustc_ast::ptr::P]) { self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&items)); } @@ -953,10 +953,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { // break the Stability Guarantee // N.B. This could be updated to utilize the version gates. let include_next_empty = if stmts.len() > 1 { - match (&stmts[0].as_ast_node().kind, &stmts[1].as_ast_node().kind) { - (ast::StmtKind::Item(_), ast::StmtKind::Empty) => true, - _ => false, - } + matches!( + (&stmts[0].as_ast_node().kind, &stmts[1].as_ast_node().kind), + (ast::StmtKind::Item(_), ast::StmtKind::Empty) + ) } else { false }; From d42be80bf772688089b90a7f2c8651adc366a3c4 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 18 Jul 2021 12:14:23 -0500 Subject: [PATCH 18/20] chore: disable clippy::matches_like_macro lint --- Cargo.lock | 24 +++++++++++++++--------- src/cargo-fmt/main.rs | 1 + src/lib.rs | 1 + 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0e12e81904c91..03bb5598007ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,7 +73,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "924c76597f0d9ca25d762c25a4d369d51267536465dc5064bdf0eb073ed477ea" dependencies = [ "backtrace-sys", - "cfg-if", + "cfg-if 0.1.10", "libc", "rustc-demangle", ] @@ -162,6 +162,12 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + [[package]] name = "clap" version = "2.33.0" @@ -207,7 +213,7 @@ version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "lazy_static", ] @@ -218,7 +224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce446db02cdc3165b94ae73111e570793400d0794e46125cc4056c81cbb039f4" dependencies = [ "autocfg", - "cfg-if", + "cfg-if 0.1.10", "lazy_static", ] @@ -245,7 +251,7 @@ version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13aea89a5c93364a98e9b37b2fa237effbb694d5cfe01c5b70941f7eb087d5e3" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "dirs-sys", ] @@ -255,7 +261,7 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "afa0b23de8fd801745c471deffa6e12d248f962c9fd4b4c33787b055599bde7b" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "libc", "redox_users", "winapi", @@ -401,11 +407,11 @@ checksum = "f2f96b10ec2560088a8e76961b00d47107b3a625fecb76dedb29ee7ccbf98235" [[package]] name = "log" -version = "0.4.8" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" +checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -426,7 +432,7 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a85ea9fc0d4ac0deb6fe7911d38786b32fc11119afd9e9d38b84ff691ce64220" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", ] [[package]] diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index ba693e852ffa6..90ffad927e2c4 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -1,6 +1,7 @@ // Inspired by Paul Woolcock's cargo-fmt (https://github.com/pwoolcoc/cargo-fmt/). #![deny(warnings)] +#![allow(clippy::match_like_matches_macro)] use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet}; diff --git a/src/lib.rs b/src/lib.rs index eb314e63de368..206d2f782909c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ #![deny(rust_2018_idioms)] #![warn(unreachable_pub)] #![recursion_limit = "256"] +#![allow(clippy::match_like_matches_macro)] #[macro_use] extern crate derive_new; From 0832137b9e72cf639d46f42d4801db8bc6d798e0 Mon Sep 17 00:00:00 2001 From: Elliot Bobrow <77182873+ebobrow@users.noreply.github.com> Date: Mon, 19 Jul 2021 14:50:05 -0700 Subject: [PATCH 19/20] fix link in Contributing.md --- Contributing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Contributing.md b/Contributing.md index a108195beb9a6..e6dc6a220376d 100644 --- a/Contributing.md +++ b/Contributing.md @@ -65,7 +65,7 @@ and get a better grasp on the execution flow. ## Hack! -Here are some [good starting issues](https://github.com/rust-lang/rustfmt/issues?q=is%3Aopen+is%3Aissue+label%3Agood-first-issue). +Here are some [good starting issues](https://github.com/rust-lang/rustfmt/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22). If you've found areas which need polish and don't have issues, please submit a PR, don't feel there needs to be an issue. From 4236289b75ee55c78538c749512cdbeea5e1c332 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 25 Jul 2021 22:27:33 -0500 Subject: [PATCH 20/20] chore: bump toolchain --- rust-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain b/rust-toolchain index 7c9d02d933d08..b0cd4464df8e5 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2021-05-13" +channel = "nightly-2021-07-23" components = ["rustc-dev"]