From d67f1a48efbcdc689c69b6218ec55b541ebf8c7a Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Sun, 2 May 2021 16:56:25 -0400 Subject: [PATCH 01/44] 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/44] 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/44] 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/44] 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/44] 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 a26237e634be7f94dbd40cc1204514f2b4c380d2 Mon Sep 17 00:00:00 2001 From: Christiaan Dirkx Date: Fri, 18 Jun 2021 18:02:56 +0200 Subject: [PATCH 06/44] Remove `Ipv4Addr::is_ietf_protocol_assignment` --- library/std/src/net/ip.rs | 40 +++------------------------------ library/std/src/net/ip/tests.rs | 17 +++----------- 2 files changed, 6 insertions(+), 51 deletions(-) diff --git a/library/std/src/net/ip.rs b/library/std/src/net/ip.rs index baf1c5aa2b941..d31d8c573d356 100644 --- a/library/std/src/net/ip.rs +++ b/library/std/src/net/ip.rs @@ -486,8 +486,7 @@ impl Ipv4Addr { /// - addresses used for documentation (see [`Ipv4Addr::is_documentation()`]) /// - the unspecified address (see [`Ipv4Addr::is_unspecified()`]), and the whole /// `0.0.0.0/8` block - /// - addresses reserved for future protocols (see - /// [`Ipv4Addr::is_ietf_protocol_assignment()`], except + /// - addresses reserved for future protocols, except /// `192.0.0.9/32` and `192.0.0.10/32` which are globally routable /// - addresses reserved for future use (see [`Ipv4Addr::is_reserved()`] /// - addresses reserved for networking devices benchmarking (see @@ -560,7 +559,8 @@ impl Ipv4Addr { && !self.is_broadcast() && !self.is_documentation() && !self.is_shared() - && !self.is_ietf_protocol_assignment() + // addresses reserved for future protocols (`192.0.0.0/24`) + && !(self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0) && !self.is_reserved() && !self.is_benchmarking() // Make sure the address is not in 0.0.0.0/8 @@ -589,40 +589,6 @@ impl Ipv4Addr { self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000) } - /// Returns [`true`] if this address is part of `192.0.0.0/24`, which is reserved to - /// IANA for IETF protocol assignments, as documented in [IETF RFC 6890]. - /// - /// Note that parts of this block are in use: - /// - /// - `192.0.0.8/32` is the "IPv4 dummy address" (see [IETF RFC 7600]) - /// - `192.0.0.9/32` is the "Port Control Protocol Anycast" (see [IETF RFC 7723]) - /// - `192.0.0.10/32` is used for NAT traversal (see [IETF RFC 8155]) - /// - /// [IETF RFC 6890]: https://tools.ietf.org/html/rfc6890 - /// [IETF RFC 7600]: https://tools.ietf.org/html/rfc7600 - /// [IETF RFC 7723]: https://tools.ietf.org/html/rfc7723 - /// [IETF RFC 8155]: https://tools.ietf.org/html/rfc8155 - /// - /// # Examples - /// - /// ``` - /// #![feature(ip)] - /// use std::net::Ipv4Addr; - /// - /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_ietf_protocol_assignment(), true); - /// assert_eq!(Ipv4Addr::new(192, 0, 0, 8).is_ietf_protocol_assignment(), true); - /// assert_eq!(Ipv4Addr::new(192, 0, 0, 9).is_ietf_protocol_assignment(), true); - /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_ietf_protocol_assignment(), true); - /// assert_eq!(Ipv4Addr::new(192, 0, 1, 0).is_ietf_protocol_assignment(), false); - /// assert_eq!(Ipv4Addr::new(191, 255, 255, 255).is_ietf_protocol_assignment(), false); - /// ``` - #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")] - #[unstable(feature = "ip", issue = "27709")] - #[inline] - pub const fn is_ietf_protocol_assignment(&self) -> bool { - self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0 - } - /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0` /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`. diff --git a/library/std/src/net/ip/tests.rs b/library/std/src/net/ip/tests.rs index 2109980ad058d..dbfab9dde404e 100644 --- a/library/std/src/net/ip/tests.rs +++ b/library/std/src/net/ip/tests.rs @@ -339,7 +339,6 @@ fn ipv4_properties() { let broadcast: u16 = 1 << 6; let documentation: u16 = 1 << 7; let benchmarking: u16 = 1 << 8; - let ietf_protocol_assignment: u16 = 1 << 9; let reserved: u16 = 1 << 10; let shared: u16 = 1 << 11; @@ -397,12 +396,6 @@ fn ipv4_properties() { assert!(!ip!($s).is_benchmarking()); } - if ($mask & ietf_protocol_assignment) == ietf_protocol_assignment { - assert!(ip!($s).is_ietf_protocol_assignment()); - } else { - assert!(!ip!($s).is_ietf_protocol_assignment()); - } - if ($mask & reserved) == reserved { assert!(ip!($s).is_reserved()); } else { @@ -426,7 +419,6 @@ fn ipv4_properties() { let broadcast: u16 = 1 << 6; let documentation: u16 = 1 << 7; let benchmarking: u16 = 1 << 8; - let ietf_protocol_assignment: u16 = 1 << 9; let reserved: u16 = 1 << 10; let shared: u16 = 1 << 11; @@ -449,9 +441,9 @@ fn ipv4_properties() { check!("198.18.0.0", benchmarking); check!("198.18.54.2", benchmarking); check!("198.19.255.255", benchmarking); - check!("192.0.0.0", ietf_protocol_assignment); - check!("192.0.0.255", ietf_protocol_assignment); - check!("192.0.0.100", ietf_protocol_assignment); + check!("192.0.0.0"); + check!("192.0.0.255"); + check!("192.0.0.100"); check!("240.0.0.0", reserved); check!("251.54.1.76", reserved); check!("254.255.255.255", reserved); @@ -823,9 +815,6 @@ fn ipv4_const() { const IS_SHARED: bool = IP_ADDRESS.is_shared(); assert!(!IS_SHARED); - const IS_IETF_PROTOCOL_ASSIGNMENT: bool = IP_ADDRESS.is_ietf_protocol_assignment(); - assert!(!IS_IETF_PROTOCOL_ASSIGNMENT); - const IS_BENCHMARKING: bool = IP_ADDRESS.is_benchmarking(); assert!(!IS_BENCHMARKING); From 71f01d197411fc7a9b3509cbf566720eabdf8d92 Mon Sep 17 00:00:00 2001 From: Alexander Melentyev Date: Mon, 21 Jun 2021 12:11:37 +0300 Subject: [PATCH 07/44] 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 5d851309958735e875dbd4361e97a1996cc83d4d Mon Sep 17 00:00:00 2001 From: Jacob Pratt Date: Thu, 24 Jun 2021 05:16:45 -0400 Subject: [PATCH 08/44] Partially stabilize `const_slice_first_last` --- library/core/src/slice/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 27cb70d9c8e5c..06ef9fcbdea87 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -140,7 +140,7 @@ impl [T] { /// assert_eq!(None, w.first()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] + #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.55.0")] #[inline] pub const fn first(&self) -> Option<&T> { if let [first, ..] = self { Some(first) } else { None } @@ -178,7 +178,7 @@ impl [T] { /// } /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] - #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] + #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.55.0")] #[inline] pub const fn split_first(&self) -> Option<(&T, &[T])> { if let [first, tail @ ..] = self { Some((first, tail)) } else { None } @@ -218,7 +218,7 @@ impl [T] { /// } /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] - #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] + #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.55.0")] #[inline] pub const fn split_last(&self) -> Option<(&T, &[T])> { if let [init @ .., last] = self { Some((last, init)) } else { None } @@ -257,7 +257,7 @@ impl [T] { /// assert_eq!(None, w.last()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] + #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.55.0")] #[inline] pub const fn last(&self) -> Option<&T> { if let [.., last] = self { Some(last) } else { None } From 33acc960f78cfde092a4e720c01896fbff86cdc8 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Wed, 30 Jun 2021 00:13:34 -0400 Subject: [PATCH 09/44] 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 c93cb40b90b5f862bf448136cbe608f43ae0f62f Mon Sep 17 00:00:00 2001 From: Christiaan Dirkx Date: Mon, 21 Jun 2021 11:44:59 +0200 Subject: [PATCH 10/44] Move `os_str_bytes` to `sys::unix` and reuse it on other platforms. --- library/std/src/sys/hermit/mod.rs | 3 ++- library/std/src/sys/sgx/mod.rs | 4 ++-- library/std/src/sys/unix/mod.rs | 3 +-- .../src/{sys_common/os_str_bytes.rs => sys/unix/os_str.rs} | 1 + .../src/{sys_common/os_str_bytes => sys/unix/os_str}/tests.rs | 0 library/std/src/sys/unsupported/common.rs | 2 -- library/std/src/sys/unsupported/mod.rs | 2 ++ library/std/src/sys/wasi/mod.rs | 3 ++- library/std/src/sys/wasm/mod.rs | 4 ++-- library/std/src/sys_common/mod.rs | 4 ---- 10 files changed, 12 insertions(+), 14 deletions(-) rename library/std/src/{sys_common/os_str_bytes.rs => sys/unix/os_str.rs} (99%) rename library/std/src/{sys_common/os_str_bytes => sys/unix/os_str}/tests.rs (100%) diff --git a/library/std/src/sys/hermit/mod.rs b/library/std/src/sys/hermit/mod.rs index 10c19424953d2..185b68c0a7803 100644 --- a/library/std/src/sys/hermit/mod.rs +++ b/library/std/src/sys/hermit/mod.rs @@ -32,6 +32,8 @@ pub mod memchr; pub mod mutex; pub mod net; pub mod os; +#[path = "../unix/os_str.rs"] +pub mod os_str; #[path = "../unix/path.rs"] pub mod path; #[path = "../unsupported/pipe.rs"] @@ -47,7 +49,6 @@ pub mod thread_local_key; pub mod time; use crate::io::ErrorKind; -pub use crate::sys_common::os_str_bytes as os_str; #[allow(unused_extern_crates)] pub extern crate hermit_abi as abi; diff --git a/library/std/src/sys/sgx/mod.rs b/library/std/src/sys/sgx/mod.rs index fce6b4207328b..a2a763c2b4e0f 100644 --- a/library/std/src/sys/sgx/mod.rs +++ b/library/std/src/sys/sgx/mod.rs @@ -26,6 +26,8 @@ pub mod memchr; pub mod mutex; pub mod net; pub mod os; +#[path = "../unix/os_str.rs"] +pub mod os_str; pub mod path; #[path = "../unsupported/pipe.rs"] pub mod pipe; @@ -37,8 +39,6 @@ pub mod thread; pub mod thread_local_key; pub mod time; -pub use crate::sys_common::os_str_bytes as os_str; - // SAFETY: must be called only once during runtime initialization. // NOTE: this is not guaranteed to run, for example when Rust code is called externally. pub unsafe fn init(argc: isize, argv: *const *const u8) { diff --git a/library/std/src/sys/unix/mod.rs b/library/std/src/sys/unix/mod.rs index 8eebdf9f5488e..44bb5ffd35d38 100644 --- a/library/std/src/sys/unix/mod.rs +++ b/library/std/src/sys/unix/mod.rs @@ -30,6 +30,7 @@ pub mod net; #[cfg(target_os = "l4re")] pub use self::l4re::net; pub mod os; +pub mod os_str; pub mod path; pub mod pipe; pub mod process; @@ -42,8 +43,6 @@ pub mod thread_local_dtor; pub mod thread_local_key; pub mod time; -pub use crate::sys_common::os_str_bytes as os_str; - // SAFETY: must be called only once during runtime initialization. // NOTE: this is not guaranteed to run, for example when Rust code is called externally. pub unsafe fn init(argc: isize, argv: *const *const u8) { diff --git a/library/std/src/sys_common/os_str_bytes.rs b/library/std/src/sys/unix/os_str.rs similarity index 99% rename from library/std/src/sys_common/os_str_bytes.rs rename to library/std/src/sys/unix/os_str.rs index 569600470db77..ae96d6b4df44e 100644 --- a/library/std/src/sys_common/os_str_bytes.rs +++ b/library/std/src/sys/unix/os_str.rs @@ -13,6 +13,7 @@ use crate::sys_common::{AsInner, IntoInner}; use core::str::lossy::{Utf8Lossy, Utf8LossyChunk}; #[cfg(test)] +#[path = "../unix/os_str/tests.rs"] mod tests; #[derive(Hash)] diff --git a/library/std/src/sys_common/os_str_bytes/tests.rs b/library/std/src/sys/unix/os_str/tests.rs similarity index 100% rename from library/std/src/sys_common/os_str_bytes/tests.rs rename to library/std/src/sys/unix/os_str/tests.rs diff --git a/library/std/src/sys/unsupported/common.rs b/library/std/src/sys/unsupported/common.rs index 4e6c301d29f54..a06b44e96a923 100644 --- a/library/std/src/sys/unsupported/common.rs +++ b/library/std/src/sys/unsupported/common.rs @@ -4,8 +4,6 @@ pub mod memchr { pub use core::slice::memchr::{memchr, memrchr}; } -pub use crate::sys_common::os_str_bytes as os_str; - // This is not necessarily correct. May want to consider making it part of the // spec definition? use crate::os::raw::c_char; diff --git a/library/std/src/sys/unsupported/mod.rs b/library/std/src/sys/unsupported/mod.rs index 3ef4c6b8a8f22..a1276193bda37 100644 --- a/library/std/src/sys/unsupported/mod.rs +++ b/library/std/src/sys/unsupported/mod.rs @@ -11,6 +11,8 @@ pub mod io; pub mod mutex; pub mod net; pub mod os; +#[path = "../unix/os_str.rs"] +pub mod os_str; #[path = "../unix/path.rs"] pub mod path; pub mod pipe; diff --git a/library/std/src/sys/wasi/mod.rs b/library/std/src/sys/wasi/mod.rs index 4af99bfa46478..8d62335aae5eb 100644 --- a/library/std/src/sys/wasi/mod.rs +++ b/library/std/src/sys/wasi/mod.rs @@ -32,7 +32,8 @@ pub mod io; pub mod mutex; pub mod net; pub mod os; -pub use crate::sys_common::os_str_bytes as os_str; +#[path = "../unix/os_str.rs"] +pub mod os_str; #[path = "../unix/path.rs"] pub mod path; #[path = "../unsupported/pipe.rs"] diff --git a/library/std/src/sys/wasm/mod.rs b/library/std/src/sys/wasm/mod.rs index cd701a333f84c..c81d653a5e38f 100644 --- a/library/std/src/sys/wasm/mod.rs +++ b/library/std/src/sys/wasm/mod.rs @@ -30,6 +30,8 @@ pub mod io; pub mod net; #[path = "../unsupported/os.rs"] pub mod os; +#[path = "../unix/os_str.rs"] +pub mod os_str; #[path = "../unix/path.rs"] pub mod path; #[path = "../unsupported/pipe.rs"] @@ -45,8 +47,6 @@ pub mod thread_local_key; #[path = "../unsupported/time.rs"] pub mod time; -pub use crate::sys_common::os_str_bytes as os_str; - cfg_if::cfg_if! { if #[cfg(target_feature = "atomics")] { #[path = "atomics/condvar.rs"] diff --git a/library/std/src/sys_common/mod.rs b/library/std/src/sys_common/mod.rs index db83bad60d84c..894440564b738 100644 --- a/library/std/src/sys_common/mod.rs +++ b/library/std/src/sys_common/mod.rs @@ -26,10 +26,6 @@ pub mod fs; pub mod io; pub mod memchr; pub mod mutex; -// `doc` is required because `sys/mod.rs` imports `unix/ext/mod.rs` on Windows -// when generating documentation. -#[cfg(any(doc, not(windows)))] -pub mod os_str_bytes; pub mod process; pub mod remutex; #[macro_use] From f2c0f29248fa6f6d2c8d71fdfa2dfb86088dc4c7 Mon Sep 17 00:00:00 2001 From: Aris Merchant <22333129+inquisitivecrystal@users.noreply.github.com> Date: Wed, 9 Jun 2021 00:40:31 -0700 Subject: [PATCH 11/44] Change env var getters to error recoverably Before this, `std`'s env var getter functions would panic on receiving certain invalid inputs. This commit makes them return a `None` or `Err` instead. --- library/std/src/env.rs | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 64f88c1aba68e..c0f9cc1f64e9f 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -188,12 +188,8 @@ impl fmt::Debug for VarsOs { /// Errors if the environment variable is not present. /// Errors if the environment variable is not valid Unicode. If this is not desired, consider using /// [`var_os`]. -/// -/// # Panics -/// -/// This function may panic if `key` is empty, contains an ASCII equals sign -/// `'='` or the NUL character `'\0'`, or when the value contains the NUL -/// character. +/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`. +/// May error when the value contains the NUL character. /// /// # Examples /// @@ -219,18 +215,18 @@ fn _var(key: &OsStr) -> Result { } /// Fetches the environment variable `key` from the current process, returning -/// [`None`] if the variable isn't set. -/// -/// # Panics -/// -/// This function may panic if `key` is empty, contains an ASCII equals sign -/// `'='` or the NUL character `'\0'`, or when the value contains the NUL -/// character. +/// [`None`] if the variable isn't set or there's another error. /// /// Note that the method will not check if the environment variable /// is valid Unicode. If you want to have an error on invalid UTF-8, /// use the [`var`] function instead. /// +/// # Errors +/// +/// Errors if the variable isn't set. +/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`. +/// May error when the value contains the NUL character. +/// /// # Examples /// /// ``` @@ -248,8 +244,7 @@ pub fn var_os>(key: K) -> Option { } fn _var_os(key: &OsStr) -> Option { - os_imp::getenv(key) - .unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e)) + os_imp::getenv(key).ok()? } /// The error type for operations interacting with environment variables. From d26e01e9df416304f7d0cc425bd0290560e12fae Mon Sep 17 00:00:00 2001 From: Aris Merchant <22333129+inquisitivecrystal@users.noreply.github.com> Date: Wed, 9 Jun 2021 01:44:06 -0700 Subject: [PATCH 12/44] Add test to prevent regression --- .../ui/macros/issue-86082-option-env-invalid-char.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 src/test/ui/macros/issue-86082-option-env-invalid-char.rs diff --git a/src/test/ui/macros/issue-86082-option-env-invalid-char.rs b/src/test/ui/macros/issue-86082-option-env-invalid-char.rs new file mode 100644 index 0000000000000..b556b24d6aa6a --- /dev/null +++ b/src/test/ui/macros/issue-86082-option-env-invalid-char.rs @@ -0,0 +1,10 @@ +// check-pass +// +// Regression test for issue #86082 +// +// Checks that option_env! does not panic on receiving an invalid +// environment variable name. + +fn main() { + option_env!("\0="); +} From a12107afaaa634cd7352d3828caef89a975299bb Mon Sep 17 00:00:00 2001 From: Aris Merchant <22333129+inquisitivecrystal@users.noreply.github.com> Date: Thu, 24 Jun 2021 16:04:24 -0700 Subject: [PATCH 13/44] Make `getenv` return an Option instead of a Result --- library/std/src/env.rs | 2 +- library/std/src/sys/hermit/os.rs | 9 ++------- library/std/src/sys/sgx/os.rs | 4 ++-- library/std/src/sys/unix/os.rs | 9 ++++----- library/std/src/sys/unsupported/os.rs | 4 ++-- library/std/src/sys/wasi/os.rs | 9 ++++----- library/std/src/sys/windows/os.rs | 19 +++++-------------- 7 files changed, 20 insertions(+), 36 deletions(-) diff --git a/library/std/src/env.rs b/library/std/src/env.rs index c0f9cc1f64e9f..a7b2748681114 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -244,7 +244,7 @@ pub fn var_os>(key: K) -> Option { } fn _var_os(key: &OsStr) -> Option { - os_imp::getenv(key).ok()? + os_imp::getenv(key) } /// The error type for operations interacting with environment variables. diff --git a/library/std/src/sys/hermit/os.rs b/library/std/src/sys/hermit/os.rs index eeb30a578c05b..8f927df85be5d 100644 --- a/library/std/src/sys/hermit/os.rs +++ b/library/std/src/sys/hermit/os.rs @@ -140,13 +140,8 @@ pub fn env() -> Env { } } -pub fn getenv(k: &OsStr) -> io::Result> { - unsafe { - match ENV.as_ref().unwrap().lock().unwrap().get_mut(k) { - Some(value) => Ok(Some(value.clone())), - None => Ok(None), - } - } +pub fn getenv(k: &OsStr) -> Option { + unsafe { ENV.as_ref().unwrap().lock().unwrap().get_mut(k).cloned() } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { diff --git a/library/std/src/sys/sgx/os.rs b/library/std/src/sys/sgx/os.rs index 144248d60c9cf..5f8b8def7c670 100644 --- a/library/std/src/sys/sgx/os.rs +++ b/library/std/src/sys/sgx/os.rs @@ -106,8 +106,8 @@ pub fn env() -> Env { get_env_store().map(|env| clone_to_vec(&env.lock().unwrap())).unwrap_or_default().into_iter() } -pub fn getenv(k: &OsStr) -> io::Result> { - Ok(get_env_store().and_then(|s| s.lock().unwrap().get(k).cloned())) +pub fn getenv(k: &OsStr) -> Option { + get_env_store().and_then(|s| s.lock().unwrap().get(k).cloned()) } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { diff --git a/library/std/src/sys/unix/os.rs b/library/std/src/sys/unix/os.rs index 71fec79347a87..1694656114a10 100644 --- a/library/std/src/sys/unix/os.rs +++ b/library/std/src/sys/unix/os.rs @@ -532,19 +532,18 @@ pub fn env() -> Env { } } -pub fn getenv(k: &OsStr) -> io::Result> { +pub fn getenv(k: &OsStr) -> Option { // environment variables with a nul byte can't be set, so their value is // always None as well - let k = CString::new(k.as_bytes())?; + let k = CString::new(k.as_bytes()).ok()?; unsafe { let _guard = env_read_lock(); let s = libc::getenv(k.as_ptr()) as *const libc::c_char; - let ret = if s.is_null() { + if s.is_null() { None } else { Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec())) - }; - Ok(ret) + } } } diff --git a/library/std/src/sys/unsupported/os.rs b/library/std/src/sys/unsupported/os.rs index e30395a0b1d92..2886ec1180e54 100644 --- a/library/std/src/sys/unsupported/os.rs +++ b/library/std/src/sys/unsupported/os.rs @@ -76,8 +76,8 @@ pub fn env() -> Env { panic!("not supported on this platform") } -pub fn getenv(_: &OsStr) -> io::Result> { - Ok(None) +pub fn getenv(_: &OsStr) -> Option { + None } pub fn setenv(_: &OsStr, _: &OsStr) -> io::Result<()> { diff --git a/library/std/src/sys/wasi/os.rs b/library/std/src/sys/wasi/os.rs index f129ee55a8391..c5229a188342a 100644 --- a/library/std/src/sys/wasi/os.rs +++ b/library/std/src/sys/wasi/os.rs @@ -175,17 +175,16 @@ pub fn env() -> Env { } } -pub fn getenv(k: &OsStr) -> io::Result> { - let k = CString::new(k.as_bytes())?; +pub fn getenv(k: &OsStr) -> Option { + let k = CString::new(k.as_bytes()).ok()?; unsafe { let _guard = env_lock(); let s = libc::getenv(k.as_ptr()) as *const libc::c_char; - let ret = if s.is_null() { + if s.is_null() { None } else { Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec())) - }; - Ok(ret) + } } } diff --git a/library/std/src/sys/windows/os.rs b/library/std/src/sys/windows/os.rs index 77c378a66afd7..8db97ba50a81f 100644 --- a/library/std/src/sys/windows/os.rs +++ b/library/std/src/sys/windows/os.rs @@ -253,22 +253,13 @@ pub fn chdir(p: &path::Path) -> io::Result<()> { cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(drop) } -pub fn getenv(k: &OsStr) -> io::Result> { - let k = to_u16s(k)?; - let res = super::fill_utf16_buf( +pub fn getenv(k: &OsStr) -> Option { + let k = to_u16s(k).ok()?; + super::fill_utf16_buf( |buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, |buf| OsStringExt::from_wide(buf), - ); - match res { - Ok(value) => Ok(Some(value)), - Err(e) => { - if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) { - Ok(None) - } else { - Err(e) - } - } - } + ) + .ok() } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { From d9752c7d843f3f93ed7f570b072aec8eb5127a96 Mon Sep 17 00:00:00 2001 From: Aris Merchant <22333129+inquisitivecrystal@users.noreply.github.com> Date: Mon, 5 Jul 2021 22:12:48 -0700 Subject: [PATCH 14/44] Improve env var getter docs --- library/std/src/env.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/library/std/src/env.rs b/library/std/src/env.rs index a7b2748681114..a359ad3b55889 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -185,11 +185,9 @@ impl fmt::Debug for VarsOs { /// /// # Errors /// -/// Errors if the environment variable is not present. -/// Errors if the environment variable is not valid Unicode. If this is not desired, consider using -/// [`var_os`]. -/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`. -/// May error when the value contains the NUL character. +/// Returns `[None]` if the environment variable isn't set. +/// Returns `[None]` if the environment variable is not valid Unicode. If this is not +/// desired, consider using [`var_os`]. /// /// # Examples /// @@ -223,9 +221,8 @@ fn _var(key: &OsStr) -> Result { /// /// # Errors /// -/// Errors if the variable isn't set. -/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`. -/// May error when the value contains the NUL character. +/// Returns `[None]` if the variable isn't set. +/// May return `[None]` if the variable value contains the NUL character. /// /// # Examples /// From a674ae6f7640c6e04a983022c778b0827798ac3d Mon Sep 17 00:00:00 2001 From: Christiaan Dirkx Date: Wed, 7 Jul 2021 14:41:06 +0200 Subject: [PATCH 15/44] Add documentation for `Ipv6MulticastScope` --- library/std/src/net/ip.rs | 44 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/library/std/src/net/ip.rs b/library/std/src/net/ip.rs index 4b6d60d121e13..5ec4b90aa8f01 100644 --- a/library/std/src/net/ip.rs +++ b/library/std/src/net/ip.rs @@ -116,16 +116,58 @@ pub struct Ipv6Addr { inner: c::in6_addr, } -#[allow(missing_docs)] +/// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2]. +/// +/// # Stability Guarantees +/// +/// Not all possible values for a multicast scope have been assigned. +/// Future RFCs may introduce new scopes, which will be added as variants to this enum; +/// because of this the enum is marked as `#[non_exhaustive]`. +/// +/// # Examples +/// ``` +/// #![feature(ip)] +/// +/// use std::net::Ipv6Addr; +/// use std::net::Ipv6MulticastScope::*; +/// +/// // An IPv6 multicast address with global scope (`ff0e::`). +/// let address = Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0); +/// +/// // Will print "Global scope". +/// match address.multicast_scope() { +/// Some(InterfaceLocal) => println!("Interface-Local scope"), +/// Some(LinkLocal) => println!("Link-Local scope"), +/// Some(RealmLocal) => println!("Realm-Local scope"), +/// Some(AdminLocal) => println!("Admin-Local scope"), +/// Some(SiteLocal) => println!("Site-Local scope"), +/// Some(OrganizationLocal) => println!("Organization-Local scope"), +/// Some(Global) => println!("Global scope"), +/// Some(_) => println!("Unknown scope"), +/// None => println!("Not a multicast address!") +/// } +/// +/// ``` +/// +/// [IPv6 multicast address]: Ipv6Addr +/// [IETF RFC 7346 section 2]: https://tools.ietf.org/html/rfc7346#section-2 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)] #[unstable(feature = "ip", issue = "27709")] +#[non_exhaustive] pub enum Ipv6MulticastScope { + /// Interface-Local scope. InterfaceLocal, + /// Link-Local scope. LinkLocal, + /// Realm-Local scope. RealmLocal, + /// Admin-Local scope. AdminLocal, + /// Site-Local scope. SiteLocal, + /// Organization-Local scope. OrganizationLocal, + /// Global scope. Global, } From abf449ffa657ab10c274595c1d3ec7a69bf801c3 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 5 May 2021 21:31:25 +0200 Subject: [PATCH 16/44] 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 17/44] 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 8f3844ff07449ebd045ba8fd9adcac62e957cfe8 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Mon, 19 Jul 2021 12:25:29 +0200 Subject: [PATCH 18/44] refactor adding rustc and std into extended builds --- src/bootstrap/dist.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 92853378e5881..1d7dbeddee981 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -1345,7 +1345,15 @@ impl Step for Extended { builder.info(&format!("Dist extended stage{} ({})", compiler.stage, target)); - let rustc_installer = builder.ensure(Rustc { compiler: builder.compiler(stage, target) }); + let mut tarballs = Vec::new(); + + // When rust-std package split from rustc, we needed to ensure that during + // upgrades rustc was upgraded before rust-std. To avoid rustc clobbering + // the std files during uninstall. To do this ensure that rustc comes + // before rust-std in the list below. + tarballs.push(builder.ensure(Rustc { compiler: builder.compiler(stage, target) })); + tarballs.push(builder.ensure(Std { compiler, target }).expect("missing std")); + let cargo_installer = builder.ensure(Cargo { compiler, target }); let rustfmt_installer = builder.ensure(Rustfmt { compiler, target }); let rust_demangler_installer = builder.ensure(RustDemangler { compiler, target }); @@ -1358,7 +1366,6 @@ impl Step for Extended { let analysis_installer = builder.ensure(Analysis { compiler, target }); let docs_installer = builder.ensure(Docs { host: target }); - let std_installer = builder.ensure(Std { compiler, target }); let etc = builder.src.join("src/etc/installer"); @@ -1367,12 +1374,6 @@ impl Step for Extended { return; } - // When rust-std package split from rustc, we needed to ensure that during - // upgrades rustc was upgraded before rust-std. To avoid rustc clobbering - // the std files during uninstall. To do this ensure that rustc comes - // before rust-std in the list below. - let mut tarballs = Vec::new(); - tarballs.push(rustc_installer); tarballs.push(cargo_installer); tarballs.push(clippy_installer); tarballs.extend(rust_demangler_installer.clone()); @@ -1384,7 +1385,6 @@ impl Step for Extended { if let Some(analysis_installer) = analysis_installer { tarballs.push(analysis_installer); } - tarballs.push(std_installer.expect("missing std")); if let Some(docs_installer) = docs_installer { tarballs.push(docs_installer); } From 0c8baa729dc3bb61713fdc198062e721c1ffa7c1 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Mon, 19 Jul 2021 13:06:24 +0200 Subject: [PATCH 19/44] refactor gating of dist docs --- src/bootstrap/dist.rs | 21 +++++++++------------ src/bootstrap/install.rs | 8 ++------ 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 1d7dbeddee981..b0764791907b3 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -51,11 +51,12 @@ pub struct Docs { } impl Step for Docs { - type Output = Option; + type Output = GeneratedTarball; const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("src/doc") + let default = run.builder.config.docs; + run.path("src/doc").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -63,11 +64,8 @@ impl Step for Docs { } /// Builds the `rust-docs` installer component. - fn run(self, builder: &Builder<'_>) -> Option { + fn run(self, builder: &Builder<'_>) -> GeneratedTarball { let host = self.host; - if !builder.config.docs { - return None; - } builder.default_doc(&[]); let dest = "share/doc/rust/html"; @@ -76,7 +74,7 @@ impl Step for Docs { tarball.set_product_name("Rust Documentation"); tarball.add_bulk_dir(&builder.doc_out(host), dest); tarball.add_file(&builder.src.join("src/doc/robots.txt"), dest, 0o644); - Some(tarball.generate()) + tarball.generate() } } @@ -1354,6 +1352,10 @@ impl Step for Extended { tarballs.push(builder.ensure(Rustc { compiler: builder.compiler(stage, target) })); tarballs.push(builder.ensure(Std { compiler, target }).expect("missing std")); + if builder.config.docs { + tarballs.push(builder.ensure(Docs { host: target })); + } + let cargo_installer = builder.ensure(Cargo { compiler, target }); let rustfmt_installer = builder.ensure(Rustfmt { compiler, target }); let rust_demangler_installer = builder.ensure(RustDemangler { compiler, target }); @@ -1365,8 +1367,6 @@ impl Step for Extended { let mingw_installer = builder.ensure(Mingw { host: target }); let analysis_installer = builder.ensure(Analysis { compiler, target }); - let docs_installer = builder.ensure(Docs { host: target }); - let etc = builder.src.join("src/etc/installer"); // Avoid producing tarballs during a dry run. @@ -1385,9 +1385,6 @@ impl Step for Extended { if let Some(analysis_installer) = analysis_installer { tarballs.push(analysis_installer); } - if let Some(docs_installer) = docs_installer { - tarballs.push(docs_installer); - } if target.contains("pc-windows-gnu") { tarballs.push(mingw_installer.unwrap()); } diff --git a/src/bootstrap/install.rs b/src/bootstrap/install.rs index 8a1b6df0dafe3..1eb516fb77125 100644 --- a/src/bootstrap/install.rs +++ b/src/bootstrap/install.rs @@ -139,12 +139,8 @@ macro_rules! install { install!((self, builder, _config), Docs, "src/doc", _config.docs, only_hosts: false, { - if let Some(tarball) = builder.ensure(dist::Docs { host: self.target }) { - install_sh(builder, "docs", self.compiler.stage, Some(self.target), &tarball); - } else { - panic!("docs are not available to install, \ - check that `build.docs` is true in `config.toml`"); - } + let tarball = builder.ensure(dist::Docs { host: self.target }); + install_sh(builder, "docs", self.compiler.stage, Some(self.target), &tarball); }; Std, "library/std", true, only_hosts: false, { for target in &builder.targets { From 7167f8b83f8dc441541a5bfeb087c5b25f787a84 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Mon, 19 Jul 2021 13:42:54 +0200 Subject: [PATCH 20/44] change output of dist cargo and clippy to be consistent with other tools --- src/bootstrap/dist.rs | 16 ++++++++-------- src/bootstrap/install.rs | 8 ++++++-- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index b0764791907b3..62ca8bff405af 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -951,7 +951,7 @@ pub struct Cargo { } impl Step for Cargo { - type Output = GeneratedTarball; + type Output = Option; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -969,7 +969,7 @@ impl Step for Cargo { }); } - fn run(self, builder: &Builder<'_>) -> GeneratedTarball { + fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; @@ -994,7 +994,7 @@ impl Step for Cargo { } } - tarball.generate() + Some(tarball.generate()) } } @@ -1106,7 +1106,7 @@ pub struct Clippy { } impl Step for Clippy { - type Output = GeneratedTarball; + type Output = Option; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -1124,7 +1124,7 @@ impl Step for Clippy { }); } - fn run(self, builder: &Builder<'_>) -> GeneratedTarball { + fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; assert!(builder.config.extended); @@ -1145,7 +1145,7 @@ impl Step for Clippy { tarball.add_file(clippy, "bin", 0o755); tarball.add_file(cargoclippy, "bin", 0o755); tarball.add_legal_and_readme_to("share/doc/clippy"); - tarball.generate() + Some(tarball.generate()) } } @@ -1374,8 +1374,8 @@ impl Step for Extended { return; } - tarballs.push(cargo_installer); - tarballs.push(clippy_installer); + tarballs.extend(cargo_installer); + tarballs.extend(clippy_installer); tarballs.extend(rust_demangler_installer.clone()); tarballs.extend(rls_installer.clone()); tarballs.extend(rust_analyzer_installer.clone()); diff --git a/src/bootstrap/install.rs b/src/bootstrap/install.rs index 1eb516fb77125..72a9ff2d5a794 100644 --- a/src/bootstrap/install.rs +++ b/src/bootstrap/install.rs @@ -154,7 +154,9 @@ install!((self, builder, _config), } }; Cargo, "cargo", Self::should_build(_config), only_hosts: true, { - let tarball = builder.ensure(dist::Cargo { compiler: self.compiler, target: self.target }); + let tarball = builder + .ensure(dist::Cargo { compiler: self.compiler, target: self.target }) + .expect("missing cargo"); install_sh(builder, "cargo", self.compiler.stage, Some(self.target), &tarball); }; Rls, "rls", Self::should_build(_config), only_hosts: true, { @@ -178,7 +180,9 @@ install!((self, builder, _config), } }; Clippy, "clippy", Self::should_build(_config), only_hosts: true, { - let tarball = builder.ensure(dist::Clippy { compiler: self.compiler, target: self.target }); + let tarball = builder + .ensure(dist::Clippy { compiler: self.compiler, target: self.target }) + .expect("missing clippy"); install_sh(builder, "clippy", self.compiler.stage, Some(self.target), &tarball); }; Miri, "miri", Self::should_build(_config), only_hosts: true, { From e60b348b0d0122d9522df0d84f47c64ebea2e4c1 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Mon, 19 Jul 2021 15:09:30 +0200 Subject: [PATCH 21/44] refactor gating of tools --- src/bootstrap/dist.rs | 149 +++++++++++++++++++++--------------------- 1 file changed, 75 insertions(+), 74 deletions(-) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 62ca8bff405af..2237f5e3e0cb5 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -8,6 +8,7 @@ //! out to `rust-installer` still. This may one day be replaced with bits and //! pieces of `rustup.rs`! +use std::collections::HashSet; use std::env; use std::fs; use std::path::{Path, PathBuf}; @@ -45,6 +46,18 @@ fn missing_tool(tool_name: &str, skip: bool) { } } +fn should_build_extended_tool(builder: &Builder<'_>, tool: &str) -> bool { + if !builder.config.extended { + return false; + } + + if let Some(tools) = &builder.config.tools { + tools.is_empty() || tools.contains(tool) + } else { + true + } +} + #[derive(Debug, PartialOrd, Ord, Copy, Clone, Hash, PartialEq, Eq)] pub struct Docs { pub host: TargetSelection, @@ -671,11 +684,10 @@ pub struct Analysis { impl Step for Analysis { type Output = Option; - const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - let builder = run.builder; - run.path("analysis").default_condition(builder.config.extended) + let default = should_build_extended_tool(&run.builder, "analysis"); + run.path("analysis").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -696,7 +708,6 @@ impl Step for Analysis { fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; - assert!(builder.config.extended); if compiler.host != builder.config.build { return None; } @@ -955,7 +966,8 @@ impl Step for Cargo { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("cargo") + let default = should_build_extended_tool(&run.builder, "cargo"); + run.path("cargo").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -1009,7 +1021,8 @@ impl Step for Rls { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("rls") + let default = should_build_extended_tool(&run.builder, "rls"); + run.path("rls").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -1026,7 +1039,6 @@ impl Step for Rls { fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; - assert!(builder.config.extended); let rls = builder .ensure(tool::Rls { compiler, target, extra_features: Vec::new() }) @@ -1055,7 +1067,8 @@ impl Step for RustAnalyzer { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("rust-analyzer") + let default = should_build_extended_tool(&run.builder, "rust-analyzer"); + run.path("rust-analyzer").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -1078,7 +1091,6 @@ impl Step for RustAnalyzer { } let compiler = self.compiler; let target = self.target; - assert!(builder.config.extended); if target.contains("riscv64") { // riscv64 currently has an LLVM bug that makes rust-analyzer unable @@ -1110,7 +1122,8 @@ impl Step for Clippy { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("clippy") + let default = should_build_extended_tool(&run.builder, "clippy"); + run.path("clippy").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -1127,7 +1140,6 @@ impl Step for Clippy { fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; - assert!(builder.config.extended); // Prepare the image directory // We expect clippy to build, because we've exited this step above if tool @@ -1160,7 +1172,8 @@ impl Step for Miri { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("miri") + let default = should_build_extended_tool(&run.builder, "miri"); + run.path("miri").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -1183,7 +1196,6 @@ impl Step for Miri { } let compiler = self.compiler; let target = self.target; - assert!(builder.config.extended); let miri = builder .ensure(tool::Miri { compiler, target, extra_features: Vec::new() }) @@ -1219,7 +1231,8 @@ impl Step for Rustfmt { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("rustfmt") + let default = should_build_extended_tool(&run.builder, "rustfmt"); + run.path("rustfmt").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -1344,6 +1357,17 @@ impl Step for Extended { builder.info(&format!("Dist extended stage{} ({})", compiler.stage, target)); let mut tarballs = Vec::new(); + let mut built_tools = HashSet::new(); + macro_rules! add_tool { + ($name:expr => $step:expr) => { + if should_build_extended_tool(builder, $name) { + if let Some(tarball) = builder.ensure($step) { + tarballs.push(tarball); + built_tools.insert($name); + } + } + }; + } // When rust-std package split from rustc, we needed to ensure that during // upgrades rustc was upgraded before rust-std. To avoid rustc clobbering @@ -1356,16 +1380,17 @@ impl Step for Extended { tarballs.push(builder.ensure(Docs { host: target })); } - let cargo_installer = builder.ensure(Cargo { compiler, target }); - let rustfmt_installer = builder.ensure(Rustfmt { compiler, target }); + add_tool!("cargo" => Cargo { compiler, target }); + add_tool!("rustfmt" => Rustfmt { compiler, target }); + add_tool!("rls" => Rls { compiler, target }); + add_tool!("rust-analyzer" => RustAnalyzer { compiler, target }); + add_tool!("llvm-tools" => LlvmTools { target }); + add_tool!("clippy" => Clippy { compiler, target }); + add_tool!("miri" => Miri { compiler, target }); + add_tool!("analysis" => Analysis { compiler, target }); + let rust_demangler_installer = builder.ensure(RustDemangler { compiler, target }); - let rls_installer = builder.ensure(Rls { compiler, target }); - let rust_analyzer_installer = builder.ensure(RustAnalyzer { compiler, target }); - let llvm_tools_installer = builder.ensure(LlvmTools { target }); - let clippy_installer = builder.ensure(Clippy { compiler, target }); - let miri_installer = builder.ensure(Miri { compiler, target }); let mingw_installer = builder.ensure(Mingw { host: target }); - let analysis_installer = builder.ensure(Analysis { compiler, target }); let etc = builder.src.join("src/etc/installer"); @@ -1374,17 +1399,8 @@ impl Step for Extended { return; } - tarballs.extend(cargo_installer); - tarballs.extend(clippy_installer); tarballs.extend(rust_demangler_installer.clone()); - tarballs.extend(rls_installer.clone()); - tarballs.extend(rust_analyzer_installer.clone()); - tarballs.extend(miri_installer.clone()); - tarballs.extend(rustfmt_installer.clone()); - tarballs.extend(llvm_tools_installer); - if let Some(analysis_installer) = analysis_installer { - tarballs.push(analysis_installer); - } + if target.contains("pc-windows-gnu") { tarballs.push(mingw_installer.unwrap()); } @@ -1434,17 +1450,11 @@ impl Step for Extended { if rust_demangler_installer.is_none() { contents = filter(&contents, "rust-demangler"); } - if rls_installer.is_none() { - contents = filter(&contents, "rls"); - } - if rust_analyzer_installer.is_none() { - contents = filter(&contents, "rust-analyzer"); - } - if miri_installer.is_none() { - contents = filter(&contents, "miri"); - } - if rustfmt_installer.is_none() { - contents = filter(&contents, "rustfmt"); + + for tool in &["rls", "rust-analyzer", "miri", "rustfmt"] { + if !built_tools.contains(tool) { + contents = filter(&contents, tool); + } } let ret = tmp.join(p.file_name().unwrap()); t!(fs::write(&ret, &contents)); @@ -1485,16 +1495,11 @@ impl Step for Extended { if rust_demangler_installer.is_some() { prepare("rust-demangler"); } - if rls_installer.is_some() { - prepare("rls"); - } - if rust_analyzer_installer.is_some() { - prepare("rust-analyzer"); - } - if miri_installer.is_some() { - prepare("miri"); + for tool in &["rls", "rust-analyzer", "miri"] { + if built_tools.contains(tool) { + prepare(tool); + } } - // create an 'uninstall' package builder.install(&etc.join("pkg/postinstall"), &pkg.join("uninstall"), 0o755); pkgbuild("uninstall"); @@ -1554,14 +1559,10 @@ impl Step for Extended { if rust_demangler_installer.is_some() { prepare("rust-demangler"); } - if rls_installer.is_some() { - prepare("rls"); - } - if rust_analyzer_installer.is_some() { - prepare("rust-analyzer"); - } - if miri_installer.is_some() { - prepare("miri"); + for tool in &["rls", "rust-analyzer", "miri"] { + if built_tools.contains(tool) { + prepare(tool); + } } if target.contains("windows-gnu") { prepare("rust-mingw"); @@ -1640,7 +1641,7 @@ impl Step for Extended { .arg("-out") .arg(exe.join("StdGroup.wxs")), ); - if rls_installer.is_some() { + if built_tools.contains("rls") { builder.run( Command::new(&heat) .current_dir(&exe) @@ -1659,7 +1660,7 @@ impl Step for Extended { .arg(etc.join("msi/remove-duplicates.xsl")), ); } - if rust_analyzer_installer.is_some() { + if built_tools.contains("rust-analyzer") { builder.run( Command::new(&heat) .current_dir(&exe) @@ -1714,7 +1715,7 @@ impl Step for Extended { .arg(etc.join("msi/remove-duplicates.xsl")), ); } - if miri_installer.is_some() { + if built_tools.contains("miri") { builder.run( Command::new(&heat) .current_dir(&exe) @@ -1790,13 +1791,13 @@ impl Step for Extended { if rust_demangler_installer.is_some() { cmd.arg("-dRustDemanglerDir=rust-demangler"); } - if rls_installer.is_some() { + if built_tools.contains("rls") { cmd.arg("-dRlsDir=rls"); } - if rust_analyzer_installer.is_some() { + if built_tools.contains("rust-analyzer") { cmd.arg("-dRustAnalyzerDir=rust-analyzer"); } - if miri_installer.is_some() { + if built_tools.contains("miri") { cmd.arg("-dMiriDir=miri"); } if target.contains("windows-gnu") { @@ -1815,13 +1816,13 @@ impl Step for Extended { if rust_demangler_installer.is_some() { candle("RustDemanglerGroup.wxs".as_ref()); } - if rls_installer.is_some() { + if built_tools.contains("rls") { candle("RlsGroup.wxs".as_ref()); } - if rust_analyzer_installer.is_some() { + if built_tools.contains("rust-analyzer") { candle("RustAnalyzerGroup.wxs".as_ref()); } - if miri_installer.is_some() { + if built_tools.contains("miri") { candle("MiriGroup.wxs".as_ref()); } candle("AnalysisGroup.wxs".as_ref()); @@ -1855,16 +1856,16 @@ impl Step for Extended { .arg("ClippyGroup.wixobj") .current_dir(&exe); - if rls_installer.is_some() { + if built_tools.contains("rls") { cmd.arg("RlsGroup.wixobj"); } - if rust_analyzer_installer.is_some() { + if built_tools.contains("rust-analyzer") { cmd.arg("RustAnalyzerGroup.wixobj"); } if rust_demangler_installer.is_some() { cmd.arg("RustDemanglerGroup.wixobj"); } - if miri_installer.is_some() { + if built_tools.contains("miri") { cmd.arg("MiriGroup.wixobj"); } @@ -1994,7 +1995,8 @@ impl Step for LlvmTools { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("llvm-tools") + let default = should_build_extended_tool(&run.builder, "llvm-tools"); + run.path("llvm-tools").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -2003,7 +2005,6 @@ impl Step for LlvmTools { fn run(self, builder: &Builder<'_>) -> Option { let target = self.target; - assert!(builder.config.extended); /* run only if llvm-config isn't used */ if let Some(config) = builder.config.target_config.get(&target) { From 82faa9caffd766b626c216f895f083f874f2440f Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Mon, 19 Jul 2021 15:22:19 +0200 Subject: [PATCH 22/44] refactor gating of demangler --- src/bootstrap/dist.rs | 50 ++++++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 2237f5e3e0cb5..3b4940e59f4c5 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -1284,7 +1284,13 @@ impl Step for RustDemangler { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("rust-demangler") + // While other tools use `should_build_extended_tool` to decide whether to be run by + // default or not, `rust-demangler` must be build when *either* it's enabled as a tool like + // the other ones or if `profiler = true`. Because we don't know the target at this stage + // we run the step by default when only `extended = true`, and decide whether to actually + // run it or not later. + let default = run.builder.config.extended; + run.path("rust-demangler").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -1301,11 +1307,11 @@ impl Step for RustDemangler { fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; - assert!(builder.config.extended); // Only build this extended tool if explicitly included in `tools`, or if `profiler = true` - let profiler = builder.config.profiler_enabled(target); - if !builder.config.tools.as_ref().map_or(profiler, |t| t.contains("rust-demangler")) { + let condition = should_build_extended_tool(builder, "rust-demangler") + || builder.config.profiler_enabled(target); + if builder.config.extended && !condition { return None; } @@ -1380,6 +1386,15 @@ impl Step for Extended { tarballs.push(builder.ensure(Docs { host: target })); } + if builder.config.profiler_enabled(target) + || should_build_extended_tool(builder, "rust-demangler") + { + if let Some(tarball) = builder.ensure(RustDemangler { compiler, target }) { + tarballs.push(tarball); + built_tools.insert("rust-demangler"); + } + } + add_tool!("cargo" => Cargo { compiler, target }); add_tool!("rustfmt" => Rustfmt { compiler, target }); add_tool!("rls" => Rls { compiler, target }); @@ -1389,7 +1404,6 @@ impl Step for Extended { add_tool!("miri" => Miri { compiler, target }); add_tool!("analysis" => Analysis { compiler, target }); - let rust_demangler_installer = builder.ensure(RustDemangler { compiler, target }); let mingw_installer = builder.ensure(Mingw { host: target }); let etc = builder.src.join("src/etc/installer"); @@ -1399,8 +1413,6 @@ impl Step for Extended { return; } - tarballs.extend(rust_demangler_installer.clone()); - if target.contains("pc-windows-gnu") { tarballs.push(mingw_installer.unwrap()); } @@ -1447,11 +1459,7 @@ impl Step for Extended { let xform = |p: &Path| { let mut contents = t!(fs::read_to_string(p)); - if rust_demangler_installer.is_none() { - contents = filter(&contents, "rust-demangler"); - } - - for tool in &["rls", "rust-analyzer", "miri", "rustfmt"] { + for tool in &["rust-demangler", "rls", "rust-analyzer", "miri", "rustfmt"] { if !built_tools.contains(tool) { contents = filter(&contents, tool); } @@ -1492,10 +1500,7 @@ impl Step for Extended { prepare("rust-std"); prepare("rust-analysis"); prepare("clippy"); - if rust_demangler_installer.is_some() { - prepare("rust-demangler"); - } - for tool in &["rls", "rust-analyzer", "miri"] { + for tool in &["rust-demangler", "rls", "rust-analyzer", "miri"] { if built_tools.contains(tool) { prepare(tool); } @@ -1556,10 +1561,7 @@ impl Step for Extended { prepare("rust-docs"); prepare("rust-std"); prepare("clippy"); - if rust_demangler_installer.is_some() { - prepare("rust-demangler"); - } - for tool in &["rls", "rust-analyzer", "miri"] { + for tool in &["rust-demangler", "rls", "rust-analyzer", "miri"] { if built_tools.contains(tool) { prepare(tool); } @@ -1696,7 +1698,7 @@ impl Step for Extended { .arg("-t") .arg(etc.join("msi/remove-duplicates.xsl")), ); - if rust_demangler_installer.is_some() { + if built_tools.contains("rust-demangler") { builder.run( Command::new(&heat) .current_dir(&exe) @@ -1788,7 +1790,7 @@ impl Step for Extended { .arg(&input); add_env(builder, &mut cmd, target); - if rust_demangler_installer.is_some() { + if built_tools.contains("rust-demangler") { cmd.arg("-dRustDemanglerDir=rust-demangler"); } if built_tools.contains("rls") { @@ -1813,7 +1815,7 @@ impl Step for Extended { candle("CargoGroup.wxs".as_ref()); candle("StdGroup.wxs".as_ref()); candle("ClippyGroup.wxs".as_ref()); - if rust_demangler_installer.is_some() { + if built_tools.contains("rust-demangler") { candle("RustDemanglerGroup.wxs".as_ref()); } if built_tools.contains("rls") { @@ -1862,7 +1864,7 @@ impl Step for Extended { if built_tools.contains("rust-analyzer") { cmd.arg("RustAnalyzerGroup.wixobj"); } - if rust_demangler_installer.is_some() { + if built_tools.contains("rust-demangler") { cmd.arg("RustDemanglerGroup.wixobj"); } if built_tools.contains("miri") { From f4c6d8f77c23aef7fc7a2128e99f8801b8176a09 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Mon, 19 Jul 2021 15:26:47 +0200 Subject: [PATCH 23/44] refactor gating of mingw --- src/bootstrap/dist.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 3b4940e59f4c5..9776b097bec07 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -1386,6 +1386,10 @@ impl Step for Extended { tarballs.push(builder.ensure(Docs { host: target })); } + if target.contains("windows-gnu") { + tarballs.push(builder.ensure(Mingw { host: target }).expect("missing mingw")); + } + if builder.config.profiler_enabled(target) || should_build_extended_tool(builder, "rust-demangler") { @@ -1404,8 +1408,6 @@ impl Step for Extended { add_tool!("miri" => Miri { compiler, target }); add_tool!("analysis" => Analysis { compiler, target }); - let mingw_installer = builder.ensure(Mingw { host: target }); - let etc = builder.src.join("src/etc/installer"); // Avoid producing tarballs during a dry run. @@ -1413,10 +1415,6 @@ impl Step for Extended { return; } - if target.contains("pc-windows-gnu") { - tarballs.push(mingw_installer.unwrap()); - } - let tarball = Tarball::new(builder, "rust", &target.triple); let generated = tarball.combine(&tarballs); From 2cfac3f04599ab50f1a7b6e21bb98c02b53bba75 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 23 Jul 2021 15:02:12 +0200 Subject: [PATCH 24/44] don't build extra tools if build.tools is explicitly an empty list --- src/bootstrap/dist.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 9776b097bec07..5290e8453e7be 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -50,12 +50,7 @@ fn should_build_extended_tool(builder: &Builder<'_>, tool: &str) -> bool { if !builder.config.extended { return false; } - - if let Some(tools) = &builder.config.tools { - tools.is_empty() || tools.contains(tool) - } else { - true - } + builder.config.tools.as_ref().map_or(true, |tools| tools.contains(tool)) } #[derive(Debug, PartialOrd, Ord, Copy, Clone, Hash, PartialEq, Eq)] From c15e2480908868024f41ac4de92eabf435f5e911 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 23 Jul 2021 16:51:43 +0200 Subject: [PATCH 25/44] refactor extended tarball generaton to use the new ensure_if_default --- src/bootstrap/builder.rs | 44 +++++++++++++++++++++++++++++++------ src/bootstrap/dist.rs | 47 +++++++++++++++------------------------- src/bootstrap/install.rs | 2 +- 3 files changed, 55 insertions(+), 38 deletions(-) diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index 56ecc6e68a98c..f2d841cb335ab 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -163,14 +163,8 @@ impl StepDescription { } fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) { - if builder.config.exclude.iter().any(|e| pathset.has(e)) { - eprintln!("Skipping {:?} because it is excluded", pathset); + if self.is_excluded(builder, pathset) { return; - } else if !builder.config.exclude.is_empty() { - eprintln!( - "{:?} not skipped for {:?} -- not in {:?}", - pathset, self.name, builder.config.exclude - ); } // Determine the targets participating in this rule. @@ -182,6 +176,21 @@ impl StepDescription { } } + fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool { + if builder.config.exclude.iter().any(|e| pathset.has(e)) { + eprintln!("Skipping {:?} because it is excluded", pathset); + return true; + } + + if !builder.config.exclude.is_empty() { + eprintln!( + "{:?} not skipped for {:?} -- not in {:?}", + pathset, self.name, builder.config.exclude + ); + } + false + } + fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) { let should_runs = v.iter().map(|desc| (desc.should_run)(ShouldRun::new(builder))).collect::>(); @@ -1579,6 +1588,27 @@ impl<'a> Builder<'a> { self.cache.put(step, out.clone()); out } + + /// Ensure that a given step is built *only if it's supposed to be built by default*, returning + /// its output. This will cache the step, so it's safe (and good!) to call this as often as + /// needed to ensure that all dependencies are build. + pub(crate) fn ensure_if_default>>( + &'a self, + step: S, + ) -> S::Output { + let desc = StepDescription::from::(); + let should_run = (desc.should_run)(ShouldRun::new(self)); + + // Avoid running steps contained in --exclude + for pathset in &should_run.paths { + if desc.is_excluded(self, pathset) { + return None; + } + } + + // Only execute if it's supposed to run as default + if desc.default && should_run.is_really_default() { self.ensure(step) } else { None } + } } #[cfg(test)] diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 5290e8453e7be..730bc51acbe1a 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -59,7 +59,7 @@ pub struct Docs { } impl Step for Docs { - type Output = GeneratedTarball; + type Output = Option; const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -72,7 +72,7 @@ impl Step for Docs { } /// Builds the `rust-docs` installer component. - fn run(self, builder: &Builder<'_>) -> GeneratedTarball { + fn run(self, builder: &Builder<'_>) -> Option { let host = self.host; builder.default_doc(&[]); @@ -82,7 +82,7 @@ impl Step for Docs { tarball.set_product_name("Rust Documentation"); tarball.add_bulk_dir(&builder.doc_out(host), dest); tarball.add_file(&builder.src.join("src/doc/robots.txt"), dest, 0o644); - tarball.generate() + Some(tarball.generate()) } } @@ -1359,13 +1359,11 @@ impl Step for Extended { let mut tarballs = Vec::new(); let mut built_tools = HashSet::new(); - macro_rules! add_tool { + macro_rules! add_component { ($name:expr => $step:expr) => { - if should_build_extended_tool(builder, $name) { - if let Some(tarball) = builder.ensure($step) { - tarballs.push(tarball); - built_tools.insert($name); - } + if let Some(tarball) = builder.ensure_if_default($step) { + tarballs.push(tarball); + built_tools.insert($name); } }; } @@ -1377,31 +1375,20 @@ impl Step for Extended { tarballs.push(builder.ensure(Rustc { compiler: builder.compiler(stage, target) })); tarballs.push(builder.ensure(Std { compiler, target }).expect("missing std")); - if builder.config.docs { - tarballs.push(builder.ensure(Docs { host: target })); - } - if target.contains("windows-gnu") { tarballs.push(builder.ensure(Mingw { host: target }).expect("missing mingw")); } - if builder.config.profiler_enabled(target) - || should_build_extended_tool(builder, "rust-demangler") - { - if let Some(tarball) = builder.ensure(RustDemangler { compiler, target }) { - tarballs.push(tarball); - built_tools.insert("rust-demangler"); - } - } - - add_tool!("cargo" => Cargo { compiler, target }); - add_tool!("rustfmt" => Rustfmt { compiler, target }); - add_tool!("rls" => Rls { compiler, target }); - add_tool!("rust-analyzer" => RustAnalyzer { compiler, target }); - add_tool!("llvm-tools" => LlvmTools { target }); - add_tool!("clippy" => Clippy { compiler, target }); - add_tool!("miri" => Miri { compiler, target }); - add_tool!("analysis" => Analysis { compiler, target }); + add_component!("rust-docs" => Docs { host: target }); + add_component!("rust-demangler"=> RustDemangler { compiler, target }); + add_component!("cargo" => Cargo { compiler, target }); + add_component!("rustfmt" => Rustfmt { compiler, target }); + add_component!("rls" => Rls { compiler, target }); + add_component!("rust-analyzer" => RustAnalyzer { compiler, target }); + add_component!("llvm-components" => LlvmTools { target }); + add_component!("clippy" => Clippy { compiler, target }); + add_component!("miri" => Miri { compiler, target }); + add_component!("analysis" => Analysis { compiler, target }); let etc = builder.src.join("src/etc/installer"); diff --git a/src/bootstrap/install.rs b/src/bootstrap/install.rs index 72a9ff2d5a794..06acf1a9a0083 100644 --- a/src/bootstrap/install.rs +++ b/src/bootstrap/install.rs @@ -139,7 +139,7 @@ macro_rules! install { install!((self, builder, _config), Docs, "src/doc", _config.docs, only_hosts: false, { - let tarball = builder.ensure(dist::Docs { host: self.target }); + let tarball = builder.ensure(dist::Docs { host: self.target }).expect("missing docs"); install_sh(builder, "docs", self.compiler.stage, Some(self.target), &tarball); }; Std, "library/std", true, only_hosts: false, { From 75765f656ebae28dbbc6f93d36a1e851473aeec9 Mon Sep 17 00:00:00 2001 From: Ruby Lazuli Date: Sat, 22 May 2021 08:22:42 -0500 Subject: [PATCH 26/44] 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 27/44] 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 28/44] 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 29/44] 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 30/44] 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 31/44] 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 32/44] 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 33/44] 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 34/44] 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 35/44] 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 36/44] 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"] From 661f46148d34dc8258dad8312fcb1206d37e45df Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Mon, 26 Jul 2021 21:50:25 -0700 Subject: [PATCH 37/44] Update mdbook. --- Cargo.lock | 8 ++++---- src/tools/rustbook/Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 553d9d05e57ba..d6fd85ba43913 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1495,9 +1495,9 @@ dependencies = [ [[package]] name = "handlebars" -version = "3.4.0" +version = "4.1.0" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "5deefd4816fb852b1ff3cb48f6c41da67be2d0e1d20b26a7a3b076da11f064b1" +checksum = "72a0ffab8c36d0436114310c7e10b59b3307e650ddfabf6d006028e29a70c6e6" dependencies = [ "log", "pest", @@ -2100,9 +2100,9 @@ dependencies = [ [[package]] name = "mdbook" -version = "0.4.7" +version = "0.4.11" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "28f6a882f3880ec68e96f60d6b543c34941e2f307ad10e2992e4db9acfe96529" +checksum = "4ee73932975c44c485e541416d7c30abb31a053af7e49682f6e856f1e4d6ab2a" dependencies = [ "ammonia", "anyhow", diff --git a/src/tools/rustbook/Cargo.toml b/src/tools/rustbook/Cargo.toml index 26a66fb021e4d..d03d1190d3458 100644 --- a/src/tools/rustbook/Cargo.toml +++ b/src/tools/rustbook/Cargo.toml @@ -10,6 +10,6 @@ clap = "2.25.0" env_logger = "0.7.1" [dependencies.mdbook] -version = "0.4.6" +version = "0.4.11" default-features = false features = ["search"] From 69f712c088b16fa88672efa2d49fe2d6ea4ca06e Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Wed, 28 Jul 2021 16:57:25 +0200 Subject: [PATCH 38/44] set all of the optional tools as DEFAULT = true The default is then overridden by `should_run`. --- src/bootstrap/dist.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 730bc51acbe1a..f5ddc07ebb2d5 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -679,6 +679,7 @@ pub struct Analysis { impl Step for Analysis { type Output = Option; + const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let default = should_build_extended_tool(&run.builder, "analysis"); @@ -958,6 +959,7 @@ pub struct Cargo { impl Step for Cargo { type Output = Option; + const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -1014,6 +1016,7 @@ pub struct Rls { impl Step for Rls { type Output = Option; const ONLY_HOSTS: bool = true; + const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let default = should_build_extended_tool(&run.builder, "rls"); @@ -1059,6 +1062,7 @@ pub struct RustAnalyzer { impl Step for RustAnalyzer { type Output = Option; + const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -1114,6 +1118,7 @@ pub struct Clippy { impl Step for Clippy { type Output = Option; + const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -1164,6 +1169,7 @@ pub struct Miri { impl Step for Miri { type Output = Option; + const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -1223,6 +1229,7 @@ pub struct Rustfmt { impl Step for Rustfmt { type Output = Option; + const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -1276,6 +1283,7 @@ pub struct RustDemangler { impl Step for RustDemangler { type Output = Option; + const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -1975,6 +1983,7 @@ pub struct LlvmTools { impl Step for LlvmTools { type Output = Option; const ONLY_HOSTS: bool = true; + const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let default = should_build_extended_tool(&run.builder, "llvm-tools"); From 377b4ce2b96dadb4083e39f4a6b2221e402ba515 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Thu, 29 Jul 2021 16:56:50 -0500 Subject: [PATCH 39/44] Remove unused field `Session.system_library_path` --- compiler/rustc_session/src/session.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 369af437c4384..9ab6dbb1ea906 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -198,10 +198,6 @@ pub struct Session { /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`. pub confused_type_with_std_module: Lock>, - /// Path for libraries that will take preference over libraries shipped by Rust. - /// Used by windows-gnu targets to priortize system mingw-w64 libraries. - pub system_library_path: OneThread>>>, - /// Tracks the current behavior of the CTFE engine when an error occurs. /// Options range from returning the error without a backtrace to returning an error /// and immediately printing the backtrace to stderr. @@ -1375,7 +1371,6 @@ pub fn build_session( driver_lint_caps, trait_methods_not_found: Lock::new(Default::default()), confused_type_with_std_module: Lock::new(Default::default()), - system_library_path: OneThread::new(RefCell::new(Default::default())), ctfe_backtrace, miri_unleashed_features: Lock::new(Default::default()), asm_arch, From 8d2bb9389adbd224bdf2c35f33097b8cab304636 Mon Sep 17 00:00:00 2001 From: Frank Steffahn Date: Fri, 30 Jul 2021 17:02:26 +0200 Subject: [PATCH 40/44] Consistent spelling of "adapter" in the standard library Change all occurrences of "(A|a)daptor" to "(A|a)dapter". --- library/core/src/alloc/mod.rs | 4 ++-- library/core/src/iter/traits/iterator.rs | 6 +++--- library/core/tests/iter/adapters/mod.rs | 2 +- library/std/src/io/mod.rs | 24 ++++++++++++------------ 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 06a761531b676..1f1033b0437f8 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -338,9 +338,9 @@ pub unsafe trait Allocator { Ok(new_ptr) } - /// Creates a "by reference" adaptor for this instance of `Allocator`. + /// Creates a "by reference" adapter for this instance of `Allocator`. /// - /// The returned adaptor also implements `Allocator` and will simply borrow this. + /// The returned adapter also implements `Allocator` and will simply borrow this. #[inline(always)] fn by_ref(&self) -> &Self where diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index f34adb878c45f..537e42f66de1b 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -694,7 +694,7 @@ pub trait Iterator { /// more idiomatic to use a `for` loop, but `for_each` may be more legible /// when processing items at the end of longer iterator chains. In some /// cases `for_each` may also be faster than a loop, because it will use - /// internal iteration on adaptors like `Chain`. + /// internal iteration on adapters like `Chain`. /// /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for /// @@ -1293,7 +1293,7 @@ pub trait Iterator { Take::new(self, n) } - /// An iterator adaptor similar to [`fold`] that holds internal state and + /// An iterator adapter similar to [`fold`] that holds internal state and /// produces a new iterator. /// /// [`fold`]: Iterator::fold @@ -1604,7 +1604,7 @@ pub trait Iterator { /// Borrows an iterator, rather than consuming it. /// - /// This is useful to allow applying iterator adaptors while still + /// This is useful to allow applying iterator adapters while still /// retaining ownership of the original iterator. /// /// # Examples diff --git a/library/core/tests/iter/adapters/mod.rs b/library/core/tests/iter/adapters/mod.rs index 96a53be1eaa50..567d9fe49cade 100644 --- a/library/core/tests/iter/adapters/mod.rs +++ b/library/core/tests/iter/adapters/mod.rs @@ -24,7 +24,7 @@ use core::cell::Cell; /// An iterator that panics whenever `next` or next_back` is called /// after `None` has already been returned. This does not violate -/// `Iterator`'s contract. Used to test that iterator adaptors don't +/// `Iterator`'s contract. Used to test that iterator adapters don't /// poll their inner iterators after exhausting them. pub struct NonFused { iter: I, diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index b336b65ad7d24..fa073d080c6ed 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -810,9 +810,9 @@ pub trait Read { default_read_exact(self, buf) } - /// Creates a "by reference" adaptor for this instance of `Read`. + /// Creates a "by reference" adapter for this instance of `Read`. /// - /// The returned adaptor also implements `Read` and will simply borrow this + /// The returned adapter also implements `Read` and will simply borrow this /// current reader. /// /// # Examples @@ -889,7 +889,7 @@ pub trait Read { Bytes { inner: self } } - /// Creates an adaptor which will chain this stream with another. + /// Creates an adapter which will chain this stream with another. /// /// The returned `Read` instance will first read all bytes from this object /// until EOF is encountered. Afterwards the output is equivalent to the @@ -927,7 +927,7 @@ pub trait Read { Chain { first: self, second: next, done_first: false } } - /// Creates an adaptor which will read at most `limit` bytes from it. + /// Creates an adapter which will read at most `limit` bytes from it. /// /// This function returns a new instance of `Read` which will read at most /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any @@ -1326,7 +1326,7 @@ impl Initializer { /// * The [`write`] method will attempt to write some data into the object, /// returning how many bytes were successfully written. /// -/// * The [`flush`] method is useful for adaptors and explicit buffers +/// * The [`flush`] method is useful for adapters and explicit buffers /// themselves for ensuring that all buffered data has been pushed out to the /// 'true sink'. /// @@ -1646,12 +1646,12 @@ pub trait Write { fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> { // Create a shim which translates a Write to a fmt::Write and saves // off I/O errors. instead of discarding them - struct Adaptor<'a, T: ?Sized + 'a> { + struct Adapter<'a, T: ?Sized + 'a> { inner: &'a mut T, error: Result<()>, } - impl fmt::Write for Adaptor<'_, T> { + impl fmt::Write for Adapter<'_, T> { fn write_str(&mut self, s: &str) -> fmt::Result { match self.inner.write_all(s.as_bytes()) { Ok(()) => Ok(()), @@ -1663,7 +1663,7 @@ pub trait Write { } } - let mut output = Adaptor { inner: self, error: Ok(()) }; + let mut output = Adapter { inner: self, error: Ok(()) }; match fmt::write(&mut output, fmt) { Ok(()) => Ok(()), Err(..) => { @@ -1677,9 +1677,9 @@ pub trait Write { } } - /// Creates a "by reference" adaptor for this instance of `Write`. + /// Creates a "by reference" adapter for this instance of `Write`. /// - /// The returned adaptor also implements `Write` and will simply borrow this + /// The returned adapter also implements `Write` and will simply borrow this /// current writer. /// /// # Examples @@ -2263,7 +2263,7 @@ pub trait BufRead: Read { } } -/// Adaptor to chain together two readers. +/// Adapter to chain together two readers. /// /// This struct is generally created by calling [`chain`] on a reader. /// Please see the documentation of [`chain`] for more details. @@ -2414,7 +2414,7 @@ impl SizeHint for Chain { } } -/// Reader adaptor which limits the bytes read from an underlying reader. +/// Reader adapter which limits the bytes read from an underlying reader. /// /// This struct is generally created by calling [`take`] on a reader. /// Please see the documentation of [`take`] for more details. From 12017f9e2b958aded7aead4ead25995caf2db7f9 Mon Sep 17 00:00:00 2001 From: Amanieu d'Antras Date: Fri, 30 Jul 2021 18:56:48 +0200 Subject: [PATCH 41/44] Update compiler_builtins to fix i128 shift/mul on thumbv6m Fixes #86063 --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b7c180012e08a..8a6bfe690e71b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -646,9 +646,9 @@ dependencies = [ [[package]] name = "compiler_builtins" -version = "0.1.47" +version = "0.1.49" source = "registry+/~https://github.com/rust-lang/crates.io-index" -checksum = "fd4ed89e0a5c3e50b15c0045fbe1ff8567b703bc07544faf935ddff0aaa7b65f" +checksum = "20b1438ef42c655665a8ab2c1c6d605a305f031d38d9be689ddfef41a20f3aa2" dependencies = [ "cc", "rustc-std-workspace-core", From 9a2e3f3a8e032ae7b39c33bc7cc8f25ebbef8a8e Mon Sep 17 00:00:00 2001 From: Flying-Toast <38232168+Flying-Toast@users.noreply.github.com> Date: Fri, 30 Jul 2021 16:01:49 -0400 Subject: [PATCH 42/44] Recommend `swap_remove` in `Vec::remove` docs --- library/alloc/src/vec/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 06a7c335bf05d..61e018285ce66 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -1360,6 +1360,12 @@ impl Vec { /// Removes and returns the element at position `index` within the vector, /// shifting all elements after it to the left. /// + /// Note: Because this shifts over the remaining elements, it has a + /// worst-case performance of O(n). If you don't need the order of elements + /// to be preserved, use [`swap_remove`] instead. + /// + /// [`swap_remove`]: Vec::swap_remove + /// /// # Panics /// /// Panics if `index` is out of bounds. From 6aaa8327f9f47033f4958dbf634413ff0cd98a3e Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 31 Jul 2021 11:37:48 +0200 Subject: [PATCH 43/44] mark a UB doctest as no_run --- library/core/src/ptr/non_null.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index 032df7f5a80ad..87c8674af0dc5 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -173,8 +173,14 @@ impl NonNull { /// /// let mut x = 0u32; /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) }; + /// ``` + /// + /// *Incorrect* usage of this function: + /// + /// ```rust,no_run + /// use std::ptr::NonNull; /// - /// // NEVER DO THAT!!! + /// // NEVER DO THAT!!! This is undefined behavior. ⚠️ /// let ptr = unsafe { NonNull::::new_unchecked(std::ptr::null_mut()) }; /// ``` #[stable(feature = "nonnull", since = "1.25.0")] From 9854d30543b34443a17537acfd1caff64b8a2697 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Sun, 1 Aug 2021 17:25:19 +0200 Subject: [PATCH 44/44] Update const_slice_first_last_not_mut stable version. --- library/core/src/slice/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 06ef9fcbdea87..e7cc34c30b1b6 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -140,7 +140,7 @@ impl [T] { /// assert_eq!(None, w.first()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.55.0")] + #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] #[inline] pub const fn first(&self) -> Option<&T> { if let [first, ..] = self { Some(first) } else { None } @@ -178,7 +178,7 @@ impl [T] { /// } /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] - #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.55.0")] + #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] #[inline] pub const fn split_first(&self) -> Option<(&T, &[T])> { if let [first, tail @ ..] = self { Some((first, tail)) } else { None } @@ -218,7 +218,7 @@ impl [T] { /// } /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] - #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.55.0")] + #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] #[inline] pub const fn split_last(&self) -> Option<(&T, &[T])> { if let [init @ .., last] = self { Some((last, init)) } else { None } @@ -257,7 +257,7 @@ impl [T] { /// assert_eq!(None, w.last()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.55.0")] + #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] #[inline] pub const fn last(&self) -> Option<&T> { if let [.., last] = self { Some(last) } else { None }