From e4b8714c0986def4ac895f6e6df0c913f924dbb8 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 25 Jul 2021 22:57:19 -0500 Subject: [PATCH 01/98] Merge commit '4236289b75ee55c78538c749512cdbeea5e1c332' into update-rustfmt --- Cargo.lock | 24 ++-- Configurations.md | 24 +++- Contributing.md | 6 +- README.md | 4 +- appveyor.yml | 110 +++++++++--------- rust-toolchain | 2 +- src/attr.rs | 2 +- src/bin/main.rs | 18 +-- src/cargo-fmt/main.rs | 5 +- src/chains.rs | 5 +- src/closures.rs | 15 +-- src/comment.rs | 21 ++-- src/config/config_type.rs | 2 +- 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 | 7 +- src/lists.rs | 11 +- src/macros.rs | 39 +++---- src/matches.rs | 7 +- 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 +-- .../match_arm_leading_pipes/preserve.rs | 8 ++ .../match_arm_leading_pipes/preserve.rs | 8 ++ tests/target/issue_4868.rs | 17 +++ 39 files changed, 276 insertions(+), 291 deletions(-) create mode 100644 tests/target/issue_4868.rs 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/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", + ), } } ``` diff --git a/Contributing.md b/Contributing.md index 1b77dad11f0fe..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. @@ -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 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 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"] 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/bin/main.rs b/src/bin/main.rs index 56b07222212f8..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())); @@ -689,6 +692,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`")), } } diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 9062a2952ec1a..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}; @@ -405,8 +406,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/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() { 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..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; @@ -30,7 +31,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 +149,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/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/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 }; 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 778f03530f8fba92ae0d87644b8cef71d351a859 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 26 Jul 2021 21:17:15 -0500 Subject: [PATCH 02/98] ci: remove unnecessary cargo-make install on windows jobs --- .github/workflows/windows.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 08cb52eedaea7..c05e8d4896ac7 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -54,9 +54,6 @@ jobs: if: matrix.target == 'x86_64-pc-windows-gnu' && matrix.channel == 'nightly' shell: bash - - name: cargo-make - run: cargo install --force cargo-make - - name: build run: | rustc -Vv From e7fa07036fa3e87f536fa3bedd3daad51dfeaf16 Mon Sep 17 00:00:00 2001 From: Outvi V <19144373+outloudvi@users.noreply.github.com> Date: Thu, 22 Jul 2021 21:24:07 +0800 Subject: [PATCH 03/98] fix: make --edition 2021 visible in --help --- src/bin/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bin/main.rs b/src/bin/main.rs index 4b4aa42d93596..1bcc5c0dada3b 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -121,7 +121,7 @@ fn make_opts() -> Options { found reverts to the input file path", "[Path for the configuration file]", ); - opts.optopt("", "edition", "Rust edition to use", "[2015|2018]"); + opts.optopt("", "edition", "Rust edition to use", "[2015|2018|2021]"); opts.optopt( "", "color", From 0b21ea2161923a87f65932b6abb5e7a94003ec3a Mon Sep 17 00:00:00 2001 From: Ellen Date: Wed, 28 Apr 2021 20:44:40 +0100 Subject: [PATCH 04/98] Unyeet const param defaults --- src/types.rs | 12 +++++++++++- tests/source/issue-4816/lib.rs | 10 ++++++++++ tests/target/issue-4816/lib.rs | 35 ++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 tests/source/issue-4816/lib.rs create mode 100644 tests/target/issue-4816/lib.rs diff --git a/src/types.rs b/src/types.rs index c6f89c310650c..1d3f4669fcd6f 100644 --- a/src/types.rs +++ b/src/types.rs @@ -571,13 +571,23 @@ impl Rewrite for ast::GenericParam { if let ast::GenericParamKind::Const { ref ty, kw_span: _, - default: _, + default, } = &self.kind { result.push_str("const "); result.push_str(rewrite_ident(context, self.ident)); result.push_str(": "); result.push_str(&ty.rewrite(context, shape)?); + if let Some(default) = default { + let eq_str = match context.config.type_punctuation_density() { + TypeDensity::Compressed => "=", + TypeDensity::Wide => " = ", + }; + result.push_str(eq_str); + let budget = shape.width.checked_sub(result.len())?; + let rewrite = default.rewrite(context, Shape::legacy(budget, shape.indent))?; + result.push_str(&rewrite); + } } else { result.push_str(rewrite_ident(context, self.ident)); } diff --git a/tests/source/issue-4816/lib.rs b/tests/source/issue-4816/lib.rs new file mode 100644 index 0000000000000..43d540c4a5d72 --- /dev/null +++ b/tests/source/issue-4816/lib.rs @@ -0,0 +1,10 @@ +#![feature(const_generics_defaults)] +struct Foo; +struct Bar; +struct Lots; +struct NamesRHard; +struct FooBar< + const LessThan100ButClose: usize = {1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1} +>; +struct FooBarrrrrrrr; diff --git a/tests/target/issue-4816/lib.rs b/tests/target/issue-4816/lib.rs new file mode 100644 index 0000000000000..246e775e1febc --- /dev/null +++ b/tests/target/issue-4816/lib.rs @@ -0,0 +1,35 @@ +#![feature(const_generics_defaults)] +struct Foo; +struct Bar; +struct Lots< + const N1BlahFooUwU: usize = { 10 + 28 + 1872 / 10 * 3 }, + const N2SecondParamOhmyyy: usize = { N1BlahFooUwU / 2 + 10 * 2 }, +>; +struct NamesRHard; +struct FooBar< + const LessThan100ButClose: usize = { + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + }, +>; +struct FooBarrrrrrrr< + const N: usize = { + 13478234326456456444323871 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + + 1 + }, +>; From 8c52aae10a099abf3f481a42bef60bc5db3aba47 Mon Sep 17 00:00:00 2001 From: klensy Date: Thu, 3 Jun 2021 05:28:20 +0300 Subject: [PATCH 05/98] Bump deps * dirs-sys v0.3.4 -> v0.3.6 to drop a lot of deps regex v1.3.1 -> v1.4.3 drops thread_local 0.3.6 bytecount v0.6.0 -> v0.6.2 replaces packed_simd with packed_simd_2 ignore v0.4.11 -> v0.4.17 drop crossbeam-channel v0.4.0 * itertools 8.0 -> 9.0 bump `ignore` version in Cargo.toml * cargo_metadata 0.8 -> 0.12 * env_logger 0.6 -> 0.8 --- Cargo.lock | 372 ++++++++++++------------------------------ Cargo.toml | 8 +- src/cargo-fmt/main.rs | 2 +- 3 files changed, 106 insertions(+), 276 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 03bb5598007ce..be134f3e9754c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -35,21 +35,6 @@ version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9267dff192e68f3399525901e709a48c1d3982c9c072fa32f2127a0cb0babf14" -[[package]] -name = "arrayref" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d382e583f07208808f6b1249e60848879ba3543f57c32277bf52d69c2f0f0ee" - -[[package]] -name = "arrayvec" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd9fd44efafa8690358b7408d253adf110036b88f55672a933f01d616ad9b1b9" -dependencies = [ - "nodrop", -] - [[package]] name = "atty" version = "0.2.13" @@ -62,40 +47,9 @@ dependencies = [ [[package]] name = "autocfg" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" - -[[package]] -name = "backtrace" -version = "0.3.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "924c76597f0d9ca25d762c25a4d369d51267536465dc5064bdf0eb073ed477ea" -dependencies = [ - "backtrace-sys", - "cfg-if 0.1.10", - "libc", - "rustc-demangle", -] - -[[package]] -name = "backtrace-sys" -version = "0.1.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6575f128516de27e3ce99689419835fce9643a9b215a14d2b5b685be018491" -dependencies = [ - "cc", - "libc", -] - -[[package]] -name = "base64" -version = "0.10.1" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" -dependencies = [ - "byteorder", -] +checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" [[package]] name = "bitflags" @@ -103,17 +57,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" -[[package]] -name = "blake2b_simd" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5850aeee1552f495dd0250014cf64b82b7c8879a89d83b33bbdace2cc4f63182" -dependencies = [ - "arrayref", - "arrayvec", - "constant_time_eq", -] - [[package]] name = "bstr" version = "0.2.8" @@ -125,37 +68,35 @@ dependencies = [ [[package]] name = "bytecount" -version = "0.6.0" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0017894339f586ccb943b01b9555de56770c11cda818e7e3d8bd93f4ed7f46e" +checksum = "72feb31ffc86498dacdbd0fcebb56138e7177a8cc5cea4516031d15ae85a742e" dependencies = [ - "packed_simd", + "packed_simd_2", ] [[package]] -name = "byteorder" -version = "1.3.2" +name = "cargo-platform" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7c3dd8985a7111efc5c80b44e23ecdd8c007de8ade3b96595387e812b957cf5" +checksum = "0226944a63d1bf35a3b5f948dd7c59e263db83695c9e8bffc4037de02e30f1d7" +dependencies = [ + "serde", +] [[package]] name = "cargo_metadata" -version = "0.8.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "700b3731fd7d357223d0000f4dbf1808401b694609035c3c411fbc0cd375c426" +checksum = "7714a157da7991e23d90686b9524b9e12e0407a108647f52e9328f4b3d51ac7f" dependencies = [ + "cargo-platform", "semver", + "semver-parser", "serde", - "serde_derive", "serde_json", ] -[[package]] -name = "cc" -version = "1.0.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0213d356d3c4ea2c18c40b037c3be23cd639825c18f25ee670ac7813beeef99c" - [[package]] name = "cfg-if" version = "0.1.10" @@ -183,48 +124,14 @@ dependencies = [ "vec_map", ] -[[package]] -name = "cloudabi" -version = "0.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" -dependencies = [ - "bitflags", -] - -[[package]] -name = "constant_time_eq" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995a44c877f9212528ccc74b21a232f66ad69001e40ede5bcee2ac9ef2657120" - -[[package]] -name = "crossbeam-channel" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acec9a3b0b3559f15aee4f90746c4e5e293b701c0f7d3925d24e01645267b68c" -dependencies = [ - "crossbeam-utils 0.7.0", -] - [[package]] name = "crossbeam-utils" -version = "0.6.6" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" -dependencies = [ - "cfg-if 0.1.10", - "lazy_static", -] - -[[package]] -name = "crossbeam-utils" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce446db02cdc3165b94ae73111e570793400d0794e46125cc4056c81cbb039f4" +checksum = "e7e9d99fa91428effe99c5c6d4634cdeba32b8cf784fc428a2a687f61a952c49" dependencies = [ "autocfg", - "cfg-if 0.1.10", + "cfg-if 1.0.0", "lazy_static", ] @@ -257,11 +164,10 @@ dependencies = [ [[package]] name = "dirs-sys" -version = "0.3.4" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa0b23de8fd801745c471deffa6e12d248f962c9fd4b4c33787b055599bde7b" +checksum = "03d86534ed367a67548dc68113a0f5db55432fdfbb6e6f9d77704397d95d5780" dependencies = [ - "cfg-if 0.1.10", "libc", "redox_users", "winapi", @@ -275,9 +181,9 @@ checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" [[package]] name = "env_logger" -version = "0.6.2" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aafcde04e90a5226a6443b7aabdb016ba2f8307c847d524724bd9b346dd1a2d3" +checksum = "54532e3223c5af90a6a757c90b5c5521564b07e5e7a958681bcd2afad421cdcd" dependencies = [ "atty", "humantime", @@ -286,40 +192,12 @@ dependencies = [ "termcolor", ] -[[package]] -name = "failure" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8273f13c977665c5db7eb2b99ae520952fe5ac831ae4cd09d80c4c7042b5ed9" -dependencies = [ - "backtrace", - "failure_derive", -] - -[[package]] -name = "failure_derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - [[package]] name = "fnv" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" -[[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - [[package]] name = "getopts" version = "0.2.21" @@ -329,11 +207,22 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "getrandom" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "wasi", +] + [[package]] name = "globset" -version = "0.4.4" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "925aa2cac82d8834e2b2a4415b6f6879757fb5c0928fc445ae76461a12eed8f2" +checksum = "c152169ef1e421390738366d2f796655fec62621dabbd0fd476f905934061e4a" dependencies = [ "aho-corasick", "bstr", @@ -353,36 +242,33 @@ dependencies = [ [[package]] name = "humantime" -version = "1.3.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" -dependencies = [ - "quick-error", -] +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "ignore" -version = "0.4.11" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "522daefc3b69036f80c7d2990b28ff9e0471c683bad05ca258e0a01dd22c5a1e" +checksum = "b287fb45c60bb826a0dc68ff08742b9d88a2fea13d6e0c286b3172065aaf878c" dependencies = [ - "crossbeam-channel", + "crossbeam-utils", "globset", "lazy_static", "log", "memchr", "regex", "same-file", - "thread_local 1.0.1", + "thread_local", "walkdir", "winapi-util", ] [[package]] name = "itertools" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8467d9c1cebe26feb08c640139247fac215782d35371ade9a2136ed6085358" +checksum = "284f18f85651fe11e8a991b2adb42cb078325c996ed026d994719efcfca1d54b" dependencies = [ "either", ] @@ -405,6 +291,12 @@ version = "0.2.77" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f96b10ec2560088a8e76961b00d47107b3a625fecb76dedb29ee7ccbf98235" +[[package]] +name = "libm" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fc7aa29613bd6a620df431842069224d8bc9011086b1db4c0e0cd47fa03ec9a" + [[package]] name = "log" version = "0.4.14" @@ -421,18 +313,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e" [[package]] -name = "nodrop" -version = "0.1.14" +name = "packed_simd_2" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" +checksum = "3278e0492f961fd4ae70909f56b2723a7e8d01a228427294e19cdfdebda89a17" +dependencies = [ + "cfg-if 0.1.10", + "libm", +] [[package]] -name = "packed_simd" -version = "0.3.3" +name = "pest" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a85ea9fc0d4ac0deb6fe7911d38786b32fc11119afd9e9d38b84ff691ce64220" +checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" dependencies = [ - "cfg-if 0.1.10", + "ucd-trie", ] [[package]] @@ -463,19 +359,13 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.6" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c9e470a8dc4aeae2dee2f335e8f533e2d4b347e1434e5671afc49b054592f27" +checksum = "a152013215dca273577e18d2bf00fa862b89b24169fb78c4c95aeb07992c9cec" dependencies = [ "unicode-xid", ] -[[package]] -name = "quick-error" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0" - [[package]] name = "quote" version = "1.0.6" @@ -486,95 +376,41 @@ dependencies = [ ] [[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - -[[package]] -name = "rand_os" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" -dependencies = [ - "cloudabi", - "fuchsia-cprng", - "libc", - "rand_core 0.4.2", - "rdrand", - "winapi", -] - -[[package]] -name = "rdrand" -version = "0.4.0" +name = "redox_syscall" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" +checksum = "05ec8ca9416c5ea37062b502703cd7fcb207736bc294f6e0cf367ac6fc234570" dependencies = [ - "rand_core 0.3.1", + "bitflags", ] -[[package]] -name = "redox_syscall" -version = "0.1.56" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" - [[package]] name = "redox_users" -version = "0.3.1" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ecedbca3bf205f8d8f5c2b44d83cd0690e39ee84b951ed649e9f1841132b66d" +checksum = "528532f3d801c87aec9def2add9ca802fe569e44a544afe633765267840abe64" dependencies = [ - "failure", - "rand_os", + "getrandom", "redox_syscall", - "rust-argon2", ] [[package]] name = "regex" -version = "1.3.1" +version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc220bd33bdce8f093101afe22a037b8eb0e5af33592e6a9caafff0d4cb81cbd" +checksum = "d9251239e129e16308e70d853559389de218ac275b515068abc96829d05b948a" dependencies = [ "aho-corasick", "memchr", "regex-syntax", - "thread_local 0.3.6", + "thread_local", ] [[package]] name = "regex-syntax" -version = "0.6.12" +version = "0.6.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11a7e20d1cce64ef2fed88b66d347f88bd9babb82845b2b858f3edbf59a4f716" - -[[package]] -name = "rust-argon2" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca4eaef519b494d1f2848fc602d18816fed808a981aedf4f1f00ceb7c9d32cf" -dependencies = [ - "base64", - "blake2b_simd", - "crossbeam-utils 0.6.6", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" +checksum = "b5eb417147ba9860a96cfe72a0b93bf88fee1744b5636ec99ab20c1aa9376581" [[package]] name = "rustc-workspace-hack" @@ -639,9 +475,9 @@ dependencies = [ [[package]] name = "semver" -version = "0.9.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" dependencies = [ "semver-parser", "serde", @@ -649,24 +485,27 @@ dependencies = [ [[package]] name = "semver-parser" -version = "0.7.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] [[package]] name = "serde" -version = "1.0.101" +version = "1.0.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9796c9b7ba2ffe7a9ce53c2287dfc48080f4b2b362fcc245a259b3a7201119dd" +checksum = "ec7505abeacaec74ae4778d9d9328fe5a5d04253220a85c4ee022239fc996d03" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.101" +version = "1.0.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b133a43a1ecd55d4086bd5b4dc6c1751c68b1bfbeba7a5040442022c7e7c02e" +checksum = "963a7dbc9895aeac7ac90e74f34a5d5261828f79df35cbed41e10189d3804d43" dependencies = [ "proc-macro2", "quote", @@ -675,9 +514,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.41" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f72eb2a68a7dc3f9a691bfda9305a1c017a6215e5a4545c258500d2099a37c2" +checksum = "dcac07dbffa1c65e7f816ab9eba78eb142c6d44410f4eeba1e26e4f5dfa56b95" dependencies = [ "itoa", "ryu", @@ -716,9 +555,9 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.11" +version = "1.0.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff0acdb207ae2fe6d5976617f887eb1e35a2ba52c13c7234c790960cdad9238" +checksum = "f3a1d708c221c5a612956ef9f75b37e454e88d1f7b899fbd3a18d4252012d663" dependencies = [ "proc-macro2", "quote", @@ -736,18 +575,6 @@ dependencies = [ "syn", ] -[[package]] -name = "synstructure" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f085a5855930c0441ca1288cf044ea4aecf4f43a91668abdb870b4ba546a203" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - [[package]] name = "term" version = "0.6.1" @@ -796,15 +623,6 @@ dependencies = [ "syn", ] -[[package]] -name = "thread_local" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" -dependencies = [ - "lazy_static", -] - [[package]] name = "thread_local" version = "1.0.1" @@ -823,6 +641,12 @@ dependencies = [ "serde", ] +[[package]] +name = "ucd-trie" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" + [[package]] name = "unicode-segmentation" version = "1.3.0" @@ -870,6 +694,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.10.2+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" + [[package]] name = "winapi" version = "0.3.8" diff --git a/Cargo.toml b/Cargo.toml index 3a04fb28f7cbf..e368f3eb1ec0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,7 @@ rustfmt-format-diff = [] generic-simd = ["bytecount/generic-simd"] [dependencies] -itertools = "0.8" +itertools = "0.9" toml = "0.5" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" @@ -43,15 +43,15 @@ regex = "1.0" term = "0.6" diff = "0.1" log = "0.4.14" -env_logger = "0.6" +env_logger = "0.8" getopts = "0.2" derive-new = "0.5" -cargo_metadata = "0.8" +cargo_metadata = "0.12" bytecount = "0.6" unicode-width = "0.1.5" unicode_categories = "0.1.1" dirs = "2.0.1" -ignore = "0.4.11" +ignore = "0.4.17" annotate-snippets = { version = "0.8", features = ["color"] } structopt = "0.3" rustfmt-config_proc_macro = { version = "0.2", path = "config_proc_macro" } diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 90ffad927e2c4..f8cf698525bab 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -528,7 +528,7 @@ fn get_cargo_metadata( if let Some(manifest_path) = manifest_path { cmd.manifest_path(manifest_path); } - cmd.other_options(&[String::from("--offline")]); + cmd.other_options(vec![String::from("--offline")]); match cmd.exec() { Ok(metadata) => Ok(metadata), From e9038b8842263b99d8a77a9a23339e02a8c3cf79 Mon Sep 17 00:00:00 2001 From: Jade Date: Tue, 27 Jul 2021 16:38:13 -0700 Subject: [PATCH 06/98] rfc3052: Remove authors field from Cargo manifests Since RFC 3052 soft deprecated the authors field anyway, hiding it from crates.io, docs.rs, and making Cargo not add it by default, and it is not generally up to date/useful information, we should remove it from crates in this repo. --- Cargo.toml | 1 - config_proc_macro/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3a04fb28f7cbf..81e3e26e8b000 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,6 @@ name = "rustfmt-nightly" version = "1.4.37" -authors = ["Nicholas Cameron ", "The Rustfmt developers"] description = "Tool to find and fix Rust formatting issues" repository = "https://github.com/rust-lang/rustfmt" readme = "README.md" diff --git a/config_proc_macro/Cargo.toml b/config_proc_macro/Cargo.toml index cc995571602b9..a41b3a5e6bf88 100644 --- a/config_proc_macro/Cargo.toml +++ b/config_proc_macro/Cargo.toml @@ -1,7 +1,6 @@ [package] name = "rustfmt-config_proc_macro" version = "0.2.0" -authors = ["topecongiro "] edition = "2018" description = "A collection of procedural macros for rustfmt" license = "Apache-2.0/MIT" From 8cbee5604a069bf8426f0848fd4fd2c86cfff0fa Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Thu, 29 Jul 2021 21:15:56 -0500 Subject: [PATCH 07/98] ci: functionally delete appveyor --- appveyor.yml | 49 +------------------------------------------------ 1 file changed, 1 insertion(+), 48 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 5ac99fd71f8f8..b3dda091e0a96 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,55 +1,8 @@ -# 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 + - echo Why does no one have access to delete me? From fefb5427a2fb28459f91a776948fca0ab0f2d11c Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Fri, 6 Aug 2021 21:26:27 -0500 Subject: [PATCH 08/98] fix: handle GAT types in impls with self bounds --- src/items.rs | 82 ++++++++++++-------------------------- src/visitor.rs | 49 +++++++++-------------- tests/source/issue_4911.rs | 6 +++ tests/target/issue_4911.rs | 9 +++++ 4 files changed, 59 insertions(+), 87 deletions(-) create mode 100644 tests/source/issue_4911.rs create mode 100644 tests/target/issue_4911.rs diff --git a/src/items.rs b/src/items.rs index 0542358c6e7c5..1a56acc7de1b5 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1497,7 +1497,7 @@ fn format_tuple_struct( Some(result) } -fn rewrite_type( +pub(crate) fn rewrite_type( context: &RewriteContext<'_>, indent: Indent, ident: symbol::Ident, @@ -1841,29 +1841,6 @@ fn rewrite_static( Some(format!("{}{};", prefix, ty_str)) } } - -pub(crate) fn rewrite_type_alias( - ident: symbol::Ident, - ty_opt: Option<&ptr::P>, - generics: &ast::Generics, - generic_bounds_opt: Option<&ast::GenericBounds>, - context: &RewriteContext<'_>, - indent: Indent, - vis: &ast::Visibility, - span: Span, -) -> Option { - rewrite_type( - context, - indent, - ident, - vis, - generics, - generic_bounds_opt, - ty_opt, - span, - ) -} - struct OpaqueType<'a> { bounds: &'a ast::GenericBounds, } @@ -1877,32 +1854,7 @@ impl<'a> Rewrite for OpaqueType<'a> { } } -pub(crate) fn rewrite_opaque_impl_type( - context: &RewriteContext<'_>, - ident: symbol::Ident, - generics: &ast::Generics, - generic_bounds: &ast::GenericBounds, - indent: Indent, -) -> Option { - let ident_str = rewrite_ident(context, ident); - // 5 = "type " - let generics_shape = Shape::indented(indent, context.config).offset_left(5)?; - let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?; - let prefix = format!("type {} =", generics_str); - let rhs = OpaqueType { - bounds: generic_bounds, - }; - - rewrite_assign_rhs( - context, - &prefix, - &rhs, - Shape::indented(indent, context.config).sub_width(1)?, - ) - .map(|s| s + ";") -} - -pub(crate) fn rewrite_associated_impl_type( +pub(crate) fn rewrite_impl_type( ident: symbol::Ident, vis: &ast::Visibility, defaultness: ast::Defaultness, @@ -1912,7 +1864,25 @@ pub(crate) fn rewrite_associated_impl_type( indent: Indent, span: Span, ) -> Option { - let result = rewrite_type_alias(ident, ty_opt, generics, None, context, indent, vis, span)?; + // Opaque type + let result = if let Some(rustc_ast::ast::Ty { + kind: ast::TyKind::ImplTrait(_, ref bounds), + .. + }) = ty_opt.map(|t| &**t) + { + rewrite_type( + context, + indent, + ident, + &DEFAULT_VISIBILITY, + generics, + None, + Some(&OpaqueType { bounds }), + span, + ) + } else { + rewrite_type(context, indent, ident, vis, generics, None, ty_opt, span) + }?; match defaultness { ast::Defaultness::Default(..) => Some(format!("default {}", result)), @@ -3164,14 +3134,14 @@ impl Rewrite for ast::ForeignItem { ast::ForeignItemKind::TyAlias(ref ty_alias_kind) => { let ast::TyAliasKind(_, ref generics, ref generic_bounds, ref type_default) = **ty_alias_kind; - rewrite_type_alias( - self.ident, - type_default.as_ref(), - generics, - Some(generic_bounds), + rewrite_type( &context, shape.indent, + self.ident, &self.vis, + generics, + Some(generic_bounds), + type_default.as_ref(), self.span, ) } diff --git a/src/visitor.rs b/src/visitor.rs index 3f251bf7c16b3..12a3281eda551 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -11,9 +11,9 @@ use crate::config::Version; use crate::config::{BraceStyle, Config}; use crate::coverage::transform_missing_snippet; use crate::items::{ - format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item, - rewrite_associated_impl_type, rewrite_extern_crate, rewrite_opaque_impl_type, - rewrite_opaque_type, rewrite_type_alias, FnBraceStyle, FnSig, StaticParts, StructParts, + format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item, rewrite_extern_crate, + rewrite_impl_type, rewrite_opaque_type, rewrite_type, FnBraceStyle, FnSig, StaticParts, + StructParts, }; use crate::macros::{macro_style, rewrite_macro, rewrite_macro_def, MacroPosition}; use crate::modules::Module; @@ -579,14 +579,14 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { **alias_kind; match ty { Some(ty) => { - let rewrite = rewrite_type_alias( - item.ident, - Some(&*ty), - generics, - Some(generic_bounds), + let rewrite = rewrite_type( &self.get_context(), self.block_indent, + item.ident, &item.vis, + generics, + Some(generic_bounds), + Some(&*ty), item.span, ); self.push_rewrite(item.span, rewrite); @@ -665,14 +665,14 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ast::AssocItemKind::TyAlias(ref ty_alias_kind) => { let ast::TyAliasKind(_, ref generics, ref generic_bounds, ref type_default) = **ty_alias_kind; - let rewrite = rewrite_type_alias( - ti.ident, - type_default.as_ref(), - generics, - Some(generic_bounds), + let rewrite = rewrite_type( &self.get_context(), self.block_indent, + ti.ident, &ti.vis, + generics, + Some(generic_bounds), + type_default.as_ref(), ti.span, ); self.push_rewrite(ti.span, rewrite); @@ -715,8 +715,9 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ast::AssocItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)), ast::AssocItemKind::TyAlias(ref ty_alias_kind) => { let ast::TyAliasKind(defaultness, ref generics, _, ref ty) = **ty_alias_kind; - let rewrite_associated = || { - rewrite_associated_impl_type( + self.push_rewrite( + ii.span, + rewrite_impl_type( ii.ident, &ii.vis, defaultness, @@ -725,22 +726,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { &self.get_context(), self.block_indent, ii.span, - ) - }; - let rewrite = match ty { - None => rewrite_associated(), - Some(ty) => match ty.kind { - ast::TyKind::ImplTrait(_, ref bounds) => rewrite_opaque_impl_type( - &self.get_context(), - ii.ident, - generics, - bounds, - self.block_indent, - ), - _ => rewrite_associated(), - }, - }; - self.push_rewrite(ii.span, rewrite); + ), + ); } ast::AssocItemKind::MacCall(ref mac) => { self.visit_mac(mac, Some(ii.ident), MacroPosition::Item); diff --git a/tests/source/issue_4911.rs b/tests/source/issue_4911.rs new file mode 100644 index 0000000000000..21ef6c6c491ac --- /dev/null +++ b/tests/source/issue_4911.rs @@ -0,0 +1,6 @@ +#![feature(generic_associated_types)] +#![feature(min_type_alias_impl_trait)] + +impl SomeTrait for SomeType { + type SomeGAT<'a> where Self: 'a = impl SomeOtherTrait; +} \ No newline at end of file diff --git a/tests/target/issue_4911.rs b/tests/target/issue_4911.rs new file mode 100644 index 0000000000000..890a62267ce64 --- /dev/null +++ b/tests/target/issue_4911.rs @@ -0,0 +1,9 @@ +#![feature(generic_associated_types)] +#![feature(min_type_alias_impl_trait)] + +impl SomeTrait for SomeType { + type SomeGAT<'a> + where + Self: 'a, + = impl SomeOtherTrait; +} From 5d8eb8d79ce01571e468df9a0dfad8b2730bdf58 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sat, 7 Aug 2021 20:24:14 -0500 Subject: [PATCH 09/98] fix: don't drop drop generic args on assoc ty constraints --- src/types.rs | 123 ++++++++++++++++++++----------------- tests/target/issue_4943.rs | 8 +++ 2 files changed, 75 insertions(+), 56 deletions(-) create mode 100644 tests/target/issue_4943.rs diff --git a/src/types.rs b/src/types.rs index 1d3f4669fcd6f..9a0d31e51dfc4 100644 --- a/src/types.rs +++ b/src/types.rs @@ -174,31 +174,38 @@ impl<'a> Rewrite for SegmentParam<'a> { SegmentParam::Const(const_) => const_.rewrite(context, shape), SegmentParam::LifeTime(lt) => lt.rewrite(context, shape), SegmentParam::Type(ty) => ty.rewrite(context, shape), - SegmentParam::Binding(assoc_ty_constraint) => { - let mut result = match assoc_ty_constraint.kind { - ast::AssocTyConstraintKind::Bound { .. } => { - format!("{}: ", rewrite_ident(context, assoc_ty_constraint.ident)) - } - ast::AssocTyConstraintKind::Equality { .. } => { - match context.config.type_punctuation_density() { - TypeDensity::Wide => { - format!("{} = ", rewrite_ident(context, assoc_ty_constraint.ident)) - } - TypeDensity::Compressed => { - format!("{}=", rewrite_ident(context, assoc_ty_constraint.ident)) - } - } - } - }; + SegmentParam::Binding(atc) => atc.rewrite(context, shape), + } + } +} - let budget = shape.width.checked_sub(result.len())?; - let rewrite = assoc_ty_constraint - .kind - .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?; - result.push_str(&rewrite); - Some(result) - } +impl Rewrite for ast::AssocTyConstraint { + fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { + use ast::AssocTyConstraintKind::{Bound, Equality}; + + let mut result = String::with_capacity(128); + result.push_str(rewrite_ident(context, self.ident)); + + if let Some(ref gen_args) = self.gen_args { + let budget = shape.width.checked_sub(result.len())?; + let shape = Shape::legacy(budget, shape.indent + result.len()); + let gen_str = rewrite_generic_args(gen_args, context, shape, gen_args.span())?; + result.push_str(&gen_str); } + + let infix = match (&self.kind, context.config.type_punctuation_density()) { + (Bound { .. }, _) => ": ", + (Equality { .. }, TypeDensity::Wide) => " = ", + (Equality { .. }, TypeDensity::Compressed) => "=", + }; + result.push_str(infix); + + let budget = shape.width.checked_sub(result.len())?; + let shape = Shape::legacy(budget, shape.indent + result.len()); + let rewrite = self.kind.rewrite(context, shape)?; + result.push_str(&rewrite); + + Some(result) } } @@ -240,21 +247,9 @@ fn rewrite_segment( }; if let Some(ref args) = segment.args { + let generics_str = rewrite_generic_args(args, context, shape, mk_sp(*span_lo, span_hi))?; match **args { ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => { - let param_list = data - .args - .iter() - .map(|x| match x { - ast::AngleBracketedArg::Arg(generic_arg) => { - SegmentParam::from_generic_arg(generic_arg) - } - ast::AngleBracketedArg::Constraint(constraint) => { - SegmentParam::Binding(constraint) - } - }) - .collect::>(); - // HACK: squeeze out the span between the identifier and the parameters. // The hack is requried so that we don't remove the separator inside macro calls. // This does not work in the presence of comment, hoping that people are @@ -270,33 +265,14 @@ fn rewrite_segment( }; result.push_str(separator); - let generics_str = overflow::rewrite_with_angle_brackets( - context, - "", - param_list.iter(), - shape, - mk_sp(*span_lo, span_hi), - )?; - // Update position of last bracket. *span_lo = context .snippet_provider .span_after(mk_sp(*span_lo, span_hi), "<"); - - result.push_str(&generics_str) - } - ast::GenericArgs::Parenthesized(ref data) => { - result.push_str(&format_function_type( - data.inputs.iter().map(|x| &**x), - &data.output, - false, - data.span, - context, - shape, - )?); } _ => (), } + result.push_str(&generics_str) } Some(result) @@ -489,6 +465,41 @@ impl Rewrite for ast::GenericArg { } } +fn rewrite_generic_args( + gen_args: &ast::GenericArgs, + context: &RewriteContext<'_>, + shape: Shape, + span: Span, +) -> Option { + match gen_args { + ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => { + let args = data + .args + .iter() + .map(|x| match x { + ast::AngleBracketedArg::Arg(generic_arg) => { + SegmentParam::from_generic_arg(generic_arg) + } + ast::AngleBracketedArg::Constraint(constraint) => { + SegmentParam::Binding(constraint) + } + }) + .collect::>(); + + overflow::rewrite_with_angle_brackets(context, "", args.iter(), shape, span) + } + ast::GenericArgs::Parenthesized(ref data) => format_function_type( + data.inputs.iter().map(|x| &**x), + &data.output, + false, + data.span, + context, + shape, + ), + _ => Some("".to_owned()), + } +} + fn rewrite_bounded_lifetime( lt: &ast::Lifetime, bounds: &[ast::GenericBound], diff --git a/tests/target/issue_4943.rs b/tests/target/issue_4943.rs new file mode 100644 index 0000000000000..bc8f1a366da29 --- /dev/null +++ b/tests/target/issue_4943.rs @@ -0,0 +1,8 @@ +impl SomeStruct { + fn process(v: T) -> ::R + where + Self: GAT = T>, + { + SomeStruct::do_something(v) + } +} From 1d6002ae3887536578e87b17935a83b94953a8d8 Mon Sep 17 00:00:00 2001 From: Nipunn Koorapati Date: Sat, 7 Aug 2021 18:08:38 -0700 Subject: [PATCH 10/98] Enable triagebot assignment in rustfmt --- triagebot.toml | 1 + 1 file changed, 1 insertion(+) create mode 100644 triagebot.toml diff --git a/triagebot.toml b/triagebot.toml new file mode 100644 index 0000000000000..fa0824ac53c0a --- /dev/null +++ b/triagebot.toml @@ -0,0 +1 @@ +[assign] From 64bf8dfa33f1394fa317f2fa50580fcb13f458f9 Mon Sep 17 00:00:00 2001 From: Caio Date: Sun, 8 Aug 2021 11:49:13 -0300 Subject: [PATCH 11/98] Introduce hir::ExprKind::Let - Take 2 --- src/expr.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/expr.rs b/src/expr.rs index 6cfeb9977a966..975af6c02947a 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -616,7 +616,7 @@ struct ControlFlow<'a> { fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) { match expr.kind { - ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond), + ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond), _ => (None, expr), } } From 7769ed048414dff021720f969372d5063b7dc7ac Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Tue, 13 Jul 2021 21:09:03 -0400 Subject: [PATCH 12/98] Document private items for rustfmt This is possible now that rustdoc allows passing `--document-private-items` more than once. --- src/comment.rs | 2 +- src/macros.rs | 2 +- src/patterns.rs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/comment.rs b/src/comment.rs index 0f8118a408ec0..58a2b5e6aecf3 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -393,7 +393,7 @@ fn identify_comment( } /// Attributes for code blocks in rustdoc. -/// See https://doc.rust-lang.org/rustdoc/print.html#attributes +/// See . enum CodeBlockAttribute { Rust, Ignore, diff --git a/src/macros.rs b/src/macros.rs index 6c5e32716c017..c8ee590b6cc17 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -1417,7 +1417,7 @@ impl MacroBranch { } } -/// Format `lazy_static!` from https://crates.io/crates/lazy_static. +/// Format `lazy_static!` from . /// /// # Expected syntax /// diff --git a/src/patterns.rs b/src/patterns.rs index 062e9cef9bbd3..0501e76d27727 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -22,11 +22,11 @@ use crate::utils::{format_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident}; /// Returns `true` if the given pattern is "short". /// A short pattern is defined by the following grammar: /// -/// [small, ntp]: +/// `[small, ntp]`: /// - single token /// - `&[single-line, ntp]` /// -/// [small]: +/// `[small]`: /// - `[small, ntp]` /// - unary tuple constructor `([small, ntp])` /// - `&[small]` From 667a2da7af0ed32361f1ea195f7a42911a54f1a8 Mon Sep 17 00:00:00 2001 From: Ayaz Hafiz Date: Sun, 31 May 2020 09:23:39 -0700 Subject: [PATCH 13/98] Fix stable toggle on gh pages configuration site A demonstration of the fix is included in the PR associated with this commit. --- docs/index.html | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/index.html b/docs/index.html index 56d1917e2b61b..1af4351039854 100644 --- a/docs/index.html +++ b/docs/index.html @@ -155,7 +155,9 @@ head: val[0].text, value: val, stable: val.some((elem) => { - return !!elem.text && elem.text.includes("**Stable**: Yes") + return elem.type === "list" && + !!elem.raw && + elem.raw.includes("**Stable**: Yes"); }), text: val.reduce((result, next) => { return next.text != null @@ -188,4 +190,4 @@ } - \ No newline at end of file + From 6959d03a3aab11515acb5ca2f0e3e5940b451dee Mon Sep 17 00:00:00 2001 From: Ayaz Hafiz Date: Sun, 31 May 2020 17:12:09 -0700 Subject: [PATCH 14/98] Show configs from different versions on github pages See https://gushiermainecoon.htmlpasta.com/ for a demo of this change. Part of #4178 --- docs/index.html | 102 ++++++++++++++++++++++++++++++------------------ 1 file changed, 65 insertions(+), 37 deletions(-) diff --git a/docs/index.html b/docs/index.html index 1af4351039854..49435e6ab3683 100644 --- a/docs/index.html +++ b/docs/index.html @@ -5,6 +5,7 @@ + @@ -137,12 +146,27 @@ }, []); ast.links = {}; + queryParams.set('version', this.version); + queryParams.set('search', this.searchCondition); + const curUrl = window.location.pathname + + '?' + queryParams.toString() + window.location.hash; + history.pushState(null, '', curUrl); + + const renderer = new marked.Renderer(); + renderer.heading = function(text, level) { + const id = htmlToId(text); + return ` + ${text} + `; + }; + return marked.parser(ast, { highlight(code, lang) { return hljs.highlight(lang ? lang : 'rust', code).value; }, headerIds: true, - headerPrefix: '' + headerPrefix: '', + renderer, }); } }, @@ -156,13 +180,10 @@ }, mounted() { if (UrlHash === '') return; - const interval = setInterval(() => { - const target = document.querySelector(`#${UrlHash}`); - if (target != null) { - target.scrollIntoView(true); - clearInterval(interval); - } - }, 100); + const target = document.querySelector(`#${UrlHash}`); + if (target != null) { + target.scrollIntoView(true); + } } }); const extractDepthOnes = (ast) => { @@ -228,6 +249,11 @@ configurationDescriptions }; } + function htmlToId(text) { + const tmpl = document.createElement('template'); + tmpl.innerHTML = text.trim(); + return encodeURIComponent(CSS.escape(tmpl.content.textContent)); + } From bf47fc17a3bbcf93f665ec2b19fbe794ead555af Mon Sep 17 00:00:00 2001 From: Ayaz Hafiz Date: Wed, 15 Jul 2020 17:50:43 -0700 Subject: [PATCH 20/98] Ensure that doc url hash IDs are scrolled to on page load I broke this a few weeks ago so I'll fix it Demo: https://5f0fa445faca4aff5f580029--naughty-borg-09b903.netlify.app/?version=master&search=#brace_style --- docs/index.html | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/index.html b/docs/index.html index 40fafd44428bb..1f299b9182055 100644 --- a/docs/index.html +++ b/docs/index.html @@ -108,7 +108,8 @@ shouldStable: false, version: versionNumber, oldVersion: undefined, - versionOptions: ['master'] + versionOptions: ['master'], + scrolledOnce: false, }, asyncComputed: { async outputHtml() { @@ -156,11 +157,11 @@ renderer.heading = function(text, level) { const id = htmlToId(text); return ` - ${text} + ${text} `; }; - return marked.parser(ast, { + const html = marked.parser(ast, { highlight(code, lang) { return hljs.highlight(lang ? lang : 'rust', code).value; }, @@ -168,6 +169,8 @@ headerPrefix: '', renderer, }); + document.dispatchEvent(new Event('htmlbuilt')); + return html; } }, created: async function() { @@ -178,12 +181,15 @@ .filter(tag => tag.startsWith('v')); this.versionOptions = this.versionOptions.concat(tagOptions); }, - mounted() { + updated: function() { if (UrlHash === '') return; - const target = document.querySelector(`#${UrlHash}`); - if (target != null) { - target.scrollIntoView(true); - } + this.$nextTick(() => { + const target = document.querySelector(`#${UrlHash}`); + if (target != null && !this.scrolledOnce) { + target.scrollIntoView(true); + this.scrolledOnce = true; + } + }); } }); const extractDepthOnes = (ast) => { From f5c782f321572e7eece7d42c51a049c1ae825b5a Mon Sep 17 00:00:00 2001 From: Ayaz Hafiz Date: Wed, 15 Jul 2020 17:52:52 -0700 Subject: [PATCH 21/98] fixup! Ensure that doc url hash IDs are scrolled to on page load --- docs/index.html | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/index.html b/docs/index.html index 1f299b9182055..3cc0c45a7591f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -161,7 +161,7 @@ `; }; - const html = marked.parser(ast, { + return marked.parser(ast, { highlight(code, lang) { return hljs.highlight(lang ? lang : 'rust', code).value; }, @@ -169,8 +169,6 @@ headerPrefix: '', renderer, }); - document.dispatchEvent(new Event('htmlbuilt')); - return html; } }, created: async function() { @@ -181,7 +179,7 @@ .filter(tag => tag.startsWith('v')); this.versionOptions = this.versionOptions.concat(tagOptions); }, - updated: function() { + updated() { if (UrlHash === '') return; this.$nextTick(() => { const target = document.querySelector(`#${UrlHash}`); From 5c7ac69393a20e18bcc07f0d69383bc6254d1b40 Mon Sep 17 00:00:00 2001 From: Ayaz Hafiz Date: Wed, 15 Jul 2020 18:27:19 -0700 Subject: [PATCH 22/98] Warn when rate limit is on docs page Demo: https://5f0fad2f06c62143ac519413--festive-golick-afb5e0.netlify.app --- docs/index.html | 58 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/docs/index.html b/docs/index.html index 3cc0c45a7591f..eb5ded4ac30eb 100644 --- a/docs/index.html +++ b/docs/index.html @@ -116,20 +116,22 @@ if (this.version !== this.oldVersion) { const ConfigurationMdUrl = `https://raw.githubusercontent.com/rust-lang/rustfmt/${this.version}/Configurations.md`; + let res; try { - const res = await axios.get(ConfigurationMdUrl); - const { - about, - configurationAbout, - configurationDescriptions - } = parseMarkdownAst(res.data); - this.aboutHtml = marked.parser(about); - this.configurationAboutHtml = marked.parser(configurationAbout); - this.configurationDescriptions = configurationDescriptions; - this.oldVersion = this.version; - } catch(error) { - this.aboutHtml = "

Failed to get configuration options for this version, please select the version from the dropdown above.

"; + res = await axios.get(ConfigurationMdUrl).catch(e => { throw e }); + } catch(e) { + this.handleReqFailure(e); + return; } + const { + about, + configurationAbout, + configurationDescriptions + } = parseMarkdownAst(res.data); + this.aboutHtml = marked.parser(about); + this.configurationAboutHtml = marked.parser(configurationAbout); + this.configurationDescriptions = configurationDescriptions; + this.oldVersion = this.version; } const ast = this.configurationDescriptions @@ -172,7 +174,13 @@ } }, created: async function() { - const {data: tags} = await axios.get(RusfmtTagsUrl); + let tags; + try { + tags = (await axios.get(RusfmtTagsUrl)).data; + } catch(e) { + this.handleReqFailure(e); + return; + } const reMajorVersion = /v(\d+)/; const tagOptions = tags .map(tag => tag.name) @@ -188,6 +196,30 @@ this.scrolledOnce = true; } }); + }, + methods: { + handleReqFailure(e) { + if (e.response.status === 404) { + this.aboutHtml = + "

Failed to get configuration options for this version, please select the version from the dropdown above.

"; + } else if ( + e.response.status === 403 && + e.response.headers["X-RateLimit-Remaining"] === 0 + ) { + const resetDate = new Date( + e.response.headers['X-RateLimit-Reset'] * 1000 + ).toLocaleString(); + this.aboutHtml = + `

You have hit the GitHub API rate limit; documentation cannot be updated.` + + `

The rate limit will be reset at ${resetDate}.

`; + } else { + this.aboutHtml = + `

Ecountered an error when fetching documentation data:

` + + `
${e.response.data}
` + + `

We would appreciate a bug report.` + + `

Try refreshing the page.

`; + } + } } }); const extractDepthOnes = (ast) => { From 3c36a0c0b74c2e5cb4c27a53e596b5729a5b3c65 Mon Sep 17 00:00:00 2001 From: jdollar Date: Sat, 3 Oct 2020 19:05:31 -0400 Subject: [PATCH 23/98] Exluding v0.8.1 and v0.7 from the config dropdown Older tags of the repo don't have the configuration.md file that the docs/index.html file uses to display configuration options. Removing them from the list since they don't apply to the use case of the documentation page. --- docs/index.html | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/index.html b/docs/index.html index eb5ded4ac30eb..bab4d2ec63bbf 100644 --- a/docs/index.html +++ b/docs/index.html @@ -181,10 +181,12 @@ this.handleReqFailure(e); return; } - const reMajorVersion = /v(\d+)/; + + const excludedTagVersions = new Set(['v0.7', 'v0.8.1']); + const tagOptions = tags .map(tag => tag.name) - .filter(tag => tag.startsWith('v')); + .filter(tag => tag.startsWith('v') && !excludedTagVersions.has(tag)); this.versionOptions = this.versionOptions.concat(tagOptions); }, updated() { From 042c2ec369a61d52cef935cbb67ae9b81da03d0f Mon Sep 17 00:00:00 2001 From: gunadhya <6939749+gunadhya@users.noreply.github.com> Date: Sat, 16 Jan 2021 01:34:11 +0530 Subject: [PATCH 24/98] Added Updated default version to Rustfmt docs config --- docs/index.html | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/index.html b/docs/index.html index bab4d2ec63bbf..f31c695f7ca0b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -87,6 +87,7 @@ From d19f69cd7106d8e84d4e92dad4d94249128a9d35 Mon Sep 17 00:00:00 2001 From: Eric Date: Mon, 30 Aug 2021 20:59:45 +1200 Subject: [PATCH 38/98] test: add missing source for #4943 --- tests/source/issue_4943.rs | 9 +++++++++ tests/target/issue_4943.rs | 2 ++ 2 files changed, 11 insertions(+) create mode 100644 tests/source/issue_4943.rs diff --git a/tests/source/issue_4943.rs b/tests/source/issue_4943.rs new file mode 100644 index 0000000000000..0793b7b4fe1cc --- /dev/null +++ b/tests/source/issue_4943.rs @@ -0,0 +1,9 @@ +#![feature(generic_associated_types)] + +impl SomeStruct { + fn process(v: T) -> ::R + where Self: GAT = T> + { + SomeStruct::do_something(v) + } +} diff --git a/tests/target/issue_4943.rs b/tests/target/issue_4943.rs index bc8f1a366da29..318f7ebed6e06 100644 --- a/tests/target/issue_4943.rs +++ b/tests/target/issue_4943.rs @@ -1,3 +1,5 @@ +#![feature(generic_associated_types)] + impl SomeStruct { fn process(v: T) -> ::R where From 33d1368674be78b5f058e1fb83d08e0d381ed2d6 Mon Sep 17 00:00:00 2001 From: Eric Date: Mon, 30 Aug 2021 21:09:21 +1200 Subject: [PATCH 39/98] test: add test for #4257 --- tests/source/issue_4257.rs | 13 +++++++++++++ tests/target/issue_4257.rs | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/source/issue_4257.rs create mode 100644 tests/target/issue_4257.rs diff --git a/tests/source/issue_4257.rs b/tests/source/issue_4257.rs new file mode 100644 index 0000000000000..2b887fadb621c --- /dev/null +++ b/tests/source/issue_4257.rs @@ -0,0 +1,13 @@ +#![feature(generic_associated_types)] +#![allow(incomplete_features)] + +trait Trait { + type Type<'a> where T: 'a; + fn foo(x: &T) -> Self::Type<'_>; +} +impl Trait for () { + type Type<'a> where T: 'a = &'a T; + fn foo(x: &T) -> Self::Type<'_> { + x + } +} diff --git a/tests/target/issue_4257.rs b/tests/target/issue_4257.rs new file mode 100644 index 0000000000000..1ebaaf2b60018 --- /dev/null +++ b/tests/target/issue_4257.rs @@ -0,0 +1,18 @@ +#![feature(generic_associated_types)] +#![allow(incomplete_features)] + +trait Trait { + type Type<'a> + where + T: 'a; + fn foo(x: &T) -> Self::Type<'_>; +} +impl Trait for () { + type Type<'a> + where + T: 'a, + = &'a T; + fn foo(x: &T) -> Self::Type<'_> { + x + } +} From bfc60466bdbab90d578c6912083fe2e238e29166 Mon Sep 17 00:00:00 2001 From: Eric Date: Mon, 30 Aug 2021 21:13:42 +1200 Subject: [PATCH 40/98] test: add test for #4954 --- tests/source/issue_4954.rs | 5 +++++ tests/target/issue_4954.rs | 7 +++++++ 2 files changed, 12 insertions(+) create mode 100644 tests/source/issue_4954.rs create mode 100644 tests/target/issue_4954.rs diff --git a/tests/source/issue_4954.rs b/tests/source/issue_4954.rs new file mode 100644 index 0000000000000..8011c601b654f --- /dev/null +++ b/tests/source/issue_4954.rs @@ -0,0 +1,5 @@ +trait Foo { + type Arg<'a>; +} + +struct Bar(T) where for<'a> T: Foo = ()>; diff --git a/tests/target/issue_4954.rs b/tests/target/issue_4954.rs new file mode 100644 index 0000000000000..aa5e79befe9c8 --- /dev/null +++ b/tests/target/issue_4954.rs @@ -0,0 +1,7 @@ +trait Foo { + type Arg<'a>; +} + +struct Bar(T) +where + for<'a> T: Foo = ()>; From ae5696a7c4c2edf642c37f06c526eb6bdf78c23b Mon Sep 17 00:00:00 2001 From: Eric Date: Mon, 30 Aug 2021 21:17:43 +1200 Subject: [PATCH 41/98] test: add test for #4322 --- tests/source/issue_4322.rs | 3 +++ tests/target/issue_4322.rs | 5 +++++ 2 files changed, 8 insertions(+) create mode 100644 tests/source/issue_4322.rs create mode 100644 tests/target/issue_4322.rs diff --git a/tests/source/issue_4322.rs b/tests/source/issue_4322.rs new file mode 100644 index 0000000000000..b28cc7cdd12fe --- /dev/null +++ b/tests/source/issue_4322.rs @@ -0,0 +1,3 @@ +trait Bar { + type X<'a> where Self: 'a; +} diff --git a/tests/target/issue_4322.rs b/tests/target/issue_4322.rs new file mode 100644 index 0000000000000..0ec0547119f47 --- /dev/null +++ b/tests/target/issue_4322.rs @@ -0,0 +1,5 @@ +trait Bar { + type X<'a> + where + Self: 'a; +} From 48b8e4577a6fefc032b97712872eff5a87b27fd7 Mon Sep 17 00:00:00 2001 From: Esteban Kuber Date: Thu, 2 Sep 2021 18:34:03 +0000 Subject: [PATCH 42/98] Detect bare blocks with type ascription that were meant to be a `struct` literal Address part of #34255. Potential improvement: silence the other knock down errors in `issue-34255-1.rs`. --- src/closures.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/closures.rs b/src/closures.rs index c9d46aef294a0..34d73a77fd3d4 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -160,6 +160,7 @@ fn rewrite_closure_with_block( .first() .map(|attr| attr.span.to(body.span)) .unwrap_or(body.span), + could_be_bare_literal: false, }; let block = crate::expr::rewrite_block_with_visitor( context, From 1674eea8ad84ec0b6a6aa60dae103e28f0347bed Mon Sep 17 00:00:00 2001 From: yukang Date: Sat, 4 Sep 2021 19:26:25 +0800 Subject: [PATCH 43/98] Fix #88256, remove duplicated diagnostic --- src/syntux/session.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/syntux/session.rs b/src/syntux/session.rs index 870f0acfe395c..2965b0928aada 100644 --- a/src/syntux/session.rs +++ b/src/syntux/session.rs @@ -311,6 +311,7 @@ mod tests { suggestions: vec![], span: span.unwrap_or_else(MultiSpan::new), sort_span: DUMMY_SP, + is_lint: false, } } From 59063e8b407acf2d187ba12616f9f36d041eff8c Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Thu, 16 Apr 2020 07:52:47 -0500 Subject: [PATCH 44/98] fix: newline width calc in combine w/ comments (#4123) --- src/comment.rs | 2 +- tests/target/issue_4031.rs | 21 +++++++++++++++ tests/target/issue_4110.rs | 55 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 tests/target/issue_4031.rs create mode 100644 tests/target/issue_4110.rs diff --git a/src/comment.rs b/src/comment.rs index 0f8118a408ec0..62b624acd4954 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -184,7 +184,7 @@ pub(crate) fn combine_strs_with_missing_comments( let missing_comment = rewrite_missing_comment(span, shape, context)?; if missing_comment.is_empty() { - if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width { + if allow_extend && one_line_width <= shape.width { result.push_str(first_sep); } else if !prev_str.is_empty() { result.push_str(&indent.to_string_with_newline(config)) diff --git a/tests/target/issue_4031.rs b/tests/target/issue_4031.rs new file mode 100644 index 0000000000000..065d5395c7e73 --- /dev/null +++ b/tests/target/issue_4031.rs @@ -0,0 +1,21 @@ +fn foo() { + with_woff2_glyf_table("tests/fonts/woff2/SFNT-TTF-Composite.woff2", |glyf| { + let actual = glyf + .records + .iter() + .map(|glyph| match glyph { + GlyfRecord::Parsed( + found @ Glyph { + data: GlyphData::Composite { .. }, + .. + }, + ) => Some(found), + _ => None, + }) + .find(|candidate| candidate.is_some()) + .unwrap() + .unwrap(); + + assert_eq!(*actual, expected) + }); +} diff --git a/tests/target/issue_4110.rs b/tests/target/issue_4110.rs new file mode 100644 index 0000000000000..4a58c3946e12d --- /dev/null +++ b/tests/target/issue_4110.rs @@ -0,0 +1,55 @@ +fn bindings() { + let err = match (place_desc, explanation) { + ( + Some(ref name), + BorrowExplanation::MustBeValidFor { + category: + category @ (ConstraintCategory::Return + | ConstraintCategory::CallArgument + | ConstraintCategory::OpaqueType), + from_closure: false, + ref region_name, + span, + .. + }, + ) if borrow_spans.for_generator() | borrow_spans.for_closure() => self + .report_escaping_closure_capture( + borrow_spans, + borrow_span, + region_name, + category, + span, + &format!("`{}`", name), + ), + ( + ref name, + BorrowExplanation::MustBeValidFor { + category: ConstraintCategory::Assignment, + from_closure: false, + region_name: + RegionName { + source: RegionNameSource::AnonRegionFromUpvar(upvar_span, ref upvar_name), + .. + }, + span, + .. + }, + ) => self.report_escaping_data(borrow_span, name, upvar_span, upvar_name, span), + (Some(name), explanation) => self.report_local_value_does_not_live_long_enough( + location, + &name, + &borrow, + drop_span, + borrow_spans, + explanation, + ), + (None, explanation) => self.report_temporary_value_does_not_live_long_enough( + location, + &borrow, + drop_span, + borrow_spans, + proper_span, + explanation, + ), + }; +} From a59cac29f4dcfd6e9aba03db07b33767809fcea0 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 6 Sep 2021 15:35:25 -0500 Subject: [PATCH 45/98] fix: use correct spans for params with attrs --- src/spanned.rs | 2 +- tests/source/issue_4032.rs | 4 ++++ tests/target/issue_4032.rs | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 tests/source/issue_4032.rs create mode 100644 tests/target/issue_4032.rs diff --git a/src/spanned.rs b/src/spanned.rs index 7e3786b7cd94c..8e6c75a3744ac 100644 --- a/src/spanned.rs +++ b/src/spanned.rs @@ -104,7 +104,7 @@ impl Spanned for ast::Arm { impl Spanned for ast::Param { fn span(&self) -> Span { if crate::items::is_named_param(self) { - mk_sp(self.pat.span.lo(), self.ty.span.hi()) + mk_sp(crate::items::span_lo_for_param(self), self.ty.span.hi()) } else { self.ty.span } diff --git a/tests/source/issue_4032.rs b/tests/source/issue_4032.rs new file mode 100644 index 0000000000000..11ded074c3455 --- /dev/null +++ b/tests/source/issue_4032.rs @@ -0,0 +1,4 @@ +fn a1(#[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] a: u8) {} +fn b1(#[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] bb: u8) {} +fn a2(#[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] a: u8) {} +fn b2(#[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] bb: u8) {} diff --git a/tests/target/issue_4032.rs b/tests/target/issue_4032.rs new file mode 100644 index 0000000000000..2e7e624ca6e6d --- /dev/null +++ b/tests/target/issue_4032.rs @@ -0,0 +1,18 @@ +fn a1( + #[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] + a: u8, +) { +} +fn b1( + #[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] + bb: u8, +) { +} +fn a2( + #[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] a: u8, +) { +} +fn b2( + #[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] bb: u8, +) { +} From c2f0e99d854d399880d05f546953659c2d170d54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Campinas?= Date: Tue, 6 Oct 2020 03:44:48 +0200 Subject: [PATCH 46/98] try to write the parameter on a new line in case the attribute/parameter together are over max_width --- src/comment.rs | 14 ++++++++------ src/items.rs | 33 +++++++++++++++++++++++++++------ 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/src/comment.rs b/src/comment.rs index 62b624acd4954..42449d1060f7d 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -10,7 +10,8 @@ use crate::rewrite::RewriteContext; use crate::shape::{Indent, Shape}; use crate::string::{rewrite_string, StringFormat}; use crate::utils::{ - count_newlines, first_line_width, last_line_width, trim_left_preserve_layout, unicode_str_width, + count_newlines, first_line_width, last_line_width, trim_left_preserve_layout, + trimmed_last_line_width, unicode_str_width, }; use crate::{ErrorKind, FormattingError}; @@ -171,11 +172,12 @@ pub(crate) fn combine_strs_with_missing_comments( String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128); result.push_str(prev_str); let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n'); - let first_sep = if prev_str.is_empty() || next_str.is_empty() { - "" - } else { - " " - }; + let first_sep = + if prev_str.is_empty() || next_str.is_empty() || trimmed_last_line_width(prev_str) == 0 { + "" + } else { + " " + }; let mut one_line_width = last_line_width(prev_str) + first_line_width(next_str) + first_sep.len(); diff --git a/src/items.rs b/src/items.rs index 4fa7190c138d9..6ba83b577ae2f 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1980,12 +1980,13 @@ impl Rewrite for ast::Param { has_multiple_attr_lines, ) } else if is_named_param(self) { + let param_name = &self + .pat + .rewrite(context, Shape::legacy(shape.width, shape.indent))?; let mut result = combine_strs_with_missing_comments( context, ¶m_attrs_result, - &self - .pat - .rewrite(context, Shape::legacy(shape.width, shape.indent))?, + param_name, span, shape, !has_multiple_attr_lines, @@ -1999,10 +2000,30 @@ impl Rewrite for ast::Param { result.push_str(&after_comment); let overhead = last_line_width(&result); let max_width = shape.width.checked_sub(overhead)?; - let ty_str = self + if let Some(ty_str) = self .ty - .rewrite(context, Shape::legacy(max_width, shape.indent))?; - result.push_str(&ty_str); + .rewrite(context, Shape::legacy(max_width, shape.indent)) + { + result.push_str(&ty_str); + } else { + result = combine_strs_with_missing_comments( + context, + &(param_attrs_result + &shape.to_string_with_newline(context.config)), + param_name, + span, + shape, + !has_multiple_attr_lines, + )?; + result.push_str(&before_comment); + result.push_str(colon_spaces(context.config)); + result.push_str(&after_comment); + let overhead = last_line_width(&result); + let max_width = shape.width.checked_sub(overhead)?; + let ty_str = self + .ty + .rewrite(context, Shape::legacy(max_width, shape.indent))?; + result.push_str(&ty_str); + } } Some(result) From 3d8cd57c2f166cb92204e95a5f4c73ab20fed4f2 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 6 Sep 2021 17:30:16 -0500 Subject: [PATCH 47/98] tests: add files for issue 4579 --- tests/source/issue_4579.rs | 15 +++++++++++++++ tests/target/issue_4579.rs | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/source/issue_4579.rs create mode 100644 tests/target/issue_4579.rs diff --git a/tests/source/issue_4579.rs b/tests/source/issue_4579.rs new file mode 100644 index 0000000000000..73f345233ba77 --- /dev/null +++ b/tests/source/issue_4579.rs @@ -0,0 +1,15 @@ +// rustfmt-hard_tabs: true + +#[macro_export] +macro_rules! main { + () => { + #[spirv(fragment)] + pub fn main_fs( + mut out_color: ::spirv_std::storage_class::Output, + #[spirv(descriptor_set = 1)]iChannelResolution: ::spirv_std::storage_class::UniformConstant< + [::spirv_std::glam::Vec3A; 4], + >, + ) { + } + }; +} diff --git a/tests/target/issue_4579.rs b/tests/target/issue_4579.rs new file mode 100644 index 0000000000000..7b0a5f3a62e49 --- /dev/null +++ b/tests/target/issue_4579.rs @@ -0,0 +1,16 @@ +// rustfmt-hard_tabs: true + +#[macro_export] +macro_rules! main { + () => { + #[spirv(fragment)] + pub fn main_fs( + mut out_color: ::spirv_std::storage_class::Output, + #[spirv(descriptor_set = 1)] + iChannelResolution: ::spirv_std::storage_class::UniformConstant< + [::spirv_std::glam::Vec3A; 4], + >, + ) { + } + }; +} From 57548aa096f31d90b9606f882f5815a93b2570b3 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Tue, 7 Sep 2021 19:49:56 -0500 Subject: [PATCH 48/98] fix: resolve idempotency issue in extern body elements --- src/missed_spans.rs | 20 ++++++++++++-------- tests/source/issue_4963.rs | 5 +++++ tests/target/issue_4963.rs | 9 +++++++++ 3 files changed, 26 insertions(+), 8 deletions(-) create mode 100644 tests/source/issue_4963.rs create mode 100644 tests/target/issue_4963.rs diff --git a/src/missed_spans.rs b/src/missed_spans.rs index 263d840785a29..28edcb784b40e 100644 --- a/src/missed_spans.rs +++ b/src/missed_spans.rs @@ -51,6 +51,14 @@ impl<'a> FmtVisitor<'a> { } pub(crate) fn format_missing_with_indent(&mut self, end: BytePos) { + self.format_missing_indent(end, true) + } + + pub(crate) fn format_missing_no_indent(&mut self, end: BytePos) { + self.format_missing_indent(end, false) + } + + fn format_missing_indent(&mut self, end: BytePos, should_indent: bool) { let config = self.config; self.format_missing_inner(end, |this, last_snippet, snippet| { this.push_str(last_snippet.trim_end()); @@ -58,14 +66,10 @@ impl<'a> FmtVisitor<'a> { // No new lines in the snippet. this.push_str("\n"); } - let indent = this.block_indent.to_string(config); - this.push_str(&indent); - }) - } - - pub(crate) fn format_missing_no_indent(&mut self, end: BytePos) { - self.format_missing_inner(end, |this, last_snippet, _| { - this.push_str(last_snippet.trim_end()); + if should_indent { + let indent = this.block_indent.to_string(config); + this.push_str(&indent); + } }) } diff --git a/tests/source/issue_4963.rs b/tests/source/issue_4963.rs new file mode 100644 index 0000000000000..32e1f6cd41bf6 --- /dev/null +++ b/tests/source/issue_4963.rs @@ -0,0 +1,5 @@ +mod test { + extern "C" {fn test();} +} + +extern "C" {fn test();} \ No newline at end of file diff --git a/tests/target/issue_4963.rs b/tests/target/issue_4963.rs new file mode 100644 index 0000000000000..0c3c13579c13b --- /dev/null +++ b/tests/target/issue_4963.rs @@ -0,0 +1,9 @@ +mod test { + extern "C" { + fn test(); + } +} + +extern "C" { + fn test(); +} From a80688329c7bf696245b5ed6f3eeda6a80ab3721 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 8 Sep 2021 18:59:49 -0500 Subject: [PATCH 49/98] fix: handle param doc comments for macro scenarios --- src/items.rs | 9 ++++++--- tests/target/issue_4936.rs | 10 ++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 tests/target/issue_4936.rs diff --git a/src/items.rs b/src/items.rs index 6ba83b577ae2f..e8eb1c5dfbb55 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1960,14 +1960,17 @@ impl Rewrite for ast::Param { let param_attrs_result = self .attrs .rewrite(context, Shape::legacy(shape.width, shape.indent))?; - let (span, has_multiple_attr_lines) = if !self.attrs.is_empty() { + // N.B. Doc comments aren't typically valid syntax, but could appear + // in the presence of certain macros - https://github.com/rust-lang/rustfmt/issues/4936 + let (span, has_multiple_attr_lines, has_doc_comments) = if !self.attrs.is_empty() { let num_attrs = self.attrs.len(); ( mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()), param_attrs_result.contains('\n'), + self.attrs.iter().any(|a| a.is_doc_comment()), ) } else { - (mk_sp(self.span.lo(), self.span.lo()), false) + (mk_sp(self.span.lo(), self.span.lo()), false, false) }; if let Some(ref explicit_self) = self.to_self() { @@ -1989,7 +1992,7 @@ impl Rewrite for ast::Param { param_name, span, shape, - !has_multiple_attr_lines, + !has_multiple_attr_lines && !has_doc_comments, )?; if !is_empty_infer(&*self.ty, self.pat.span) { diff --git a/tests/target/issue_4936.rs b/tests/target/issue_4936.rs new file mode 100644 index 0000000000000..c19e505fd03ad --- /dev/null +++ b/tests/target/issue_4936.rs @@ -0,0 +1,10 @@ +#[discard_params_doc] +trait Trait { + fn foo( + &self, + /// some docs + bar: String, + /// another docs + baz: i32, + ); +} From b10ab51fed62f54010a786e3f7d018700464b786 Mon Sep 17 00:00:00 2001 From: Nipunn Koorapati Date: Sat, 7 Aug 2021 18:00:51 -0700 Subject: [PATCH 50/98] rustfmt doc code blocks with multiple comma-separated attributes Added test covering this. Chose to treat the code block as rust if and only if all of the comma-separated attributes are rust-valid. Chose to allow/preserve whitespace around commas Fixes #3158 --- src/comment.rs | 52 ++++++++++++--------------- tests/source/issue-3158.rs | 74 ++++++++++++++++++++++++++++++++++++++ tests/target/issue-3158.rs | 74 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 171 insertions(+), 29 deletions(-) create mode 100644 tests/source/issue-3158.rs create mode 100644 tests/target/issue-3158.rs diff --git a/src/comment.rs b/src/comment.rs index 42449d1060f7d..6082542485856 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -394,28 +394,26 @@ fn identify_comment( } } -/// Attributes for code blocks in rustdoc. -/// See https://doc.rust-lang.org/rustdoc/print.html#attributes +/// Enum indicating if the code block contains rust based on attributes enum CodeBlockAttribute { Rust, - Ignore, - Text, - ShouldPanic, - NoRun, - CompileFail, + NotRust, } impl CodeBlockAttribute { - fn new(attribute: &str) -> CodeBlockAttribute { - match attribute { - "rust" | "" => CodeBlockAttribute::Rust, - "ignore" => CodeBlockAttribute::Ignore, - "text" => CodeBlockAttribute::Text, - "should_panic" => CodeBlockAttribute::ShouldPanic, - "no_run" => CodeBlockAttribute::NoRun, - "compile_fail" => CodeBlockAttribute::CompileFail, - _ => CodeBlockAttribute::Text, + /// Parse comma separated attributes list. Return rust only if all + /// attributes are valid rust attributes + /// See https://doc.rust-lang.org/rustdoc/print.html#attributes + fn new(attributes: &str) -> CodeBlockAttribute { + for attribute in attributes.split(",") { + match attribute.trim() { + "" | "rust" | "should_panic" | "no_run" | "edition2015" | "edition2018" + | "edition2021" => (), + "ignore" | "compile_fail" | "text" => return CodeBlockAttribute::NotRust, + _ => return CodeBlockAttribute::NotRust, + } } + CodeBlockAttribute::Rust } } @@ -649,25 +647,21 @@ impl<'a> CommentRewrite<'a> { } else if self.code_block_attr.is_some() { if line.starts_with("```") { let code_block = match self.code_block_attr.as_ref().unwrap() { - CodeBlockAttribute::Ignore | CodeBlockAttribute::Text => { - trim_custom_comment_prefix(&self.code_block_buffer) - } - _ if self.code_block_buffer.is_empty() => String::new(), - _ => { + CodeBlockAttribute::Rust + if self.fmt.config.format_code_in_doc_comments() + && !self.code_block_buffer.is_empty() => + { let mut config = self.fmt.config.clone(); config.set().wrap_comments(false); - if config.format_code_in_doc_comments() { - if let Some(s) = - crate::format_code_block(&self.code_block_buffer, &config, false) - { - trim_custom_comment_prefix(&s.snippet) - } else { - trim_custom_comment_prefix(&self.code_block_buffer) - } + if let Some(s) = + crate::format_code_block(&self.code_block_buffer, &config, false) + { + trim_custom_comment_prefix(&s.snippet) } else { trim_custom_comment_prefix(&self.code_block_buffer) } } + _ => trim_custom_comment_prefix(&self.code_block_buffer), }; if !code_block.is_empty() { self.result.push_str(&self.comment_line_separator); diff --git a/tests/source/issue-3158.rs b/tests/source/issue-3158.rs new file mode 100644 index 0000000000000..315073db6af5a --- /dev/null +++ b/tests/source/issue-3158.rs @@ -0,0 +1,74 @@ +// rustfmt-format_code_in_doc_comments: true + +/// Should format +/// ```rust +/// assert!( false ); +/// ``` +/// +/// Should format +/// ```rust,should_panic +/// assert!( false ); +/// ``` +/// +/// Should format +/// ```rust,should_panic,edition2018 +/// assert!( false ); +/// ``` +/// +/// Should format +/// ```rust , should_panic , edition2018 +/// assert!( false ); +/// ``` +/// +/// Should not format +/// ```ignore +/// assert!( false ); +/// ``` +/// +/// Should not format (not all are rust) +/// ```rust,ignore +/// assert!( false ); +/// ``` +/// +/// Should not format (rust compile_fail) +/// ```compile_fail +/// assert!( false ); +/// ``` +/// +/// Should not format (rust compile_fail) +/// ```rust,compile_fail +/// assert!( false ); +/// ``` +/// +/// Various unspecified ones that should format +/// ``` +/// assert!( false ); +/// ``` +/// +/// ```, +/// assert!( false ); +/// ``` +/// +/// ```,,,,, +/// assert!( false ); +/// ``` +/// +/// ```,,, rust ,, +/// assert!( false ); +/// ``` +/// +/// Should not format +/// ```,,, rust , ignore, +/// assert!( false ); +/// ``` +/// +/// Few empty ones +/// ``` +/// ``` +/// +/// ```rust +/// ``` +/// +/// ```ignore +/// ``` +fn foo() {} diff --git a/tests/target/issue-3158.rs b/tests/target/issue-3158.rs new file mode 100644 index 0000000000000..4bbbdc1d03922 --- /dev/null +++ b/tests/target/issue-3158.rs @@ -0,0 +1,74 @@ +// rustfmt-format_code_in_doc_comments: true + +/// Should format +/// ```rust +/// assert!(false); +/// ``` +/// +/// Should format +/// ```rust,should_panic +/// assert!(false); +/// ``` +/// +/// Should format +/// ```rust,should_panic,edition2018 +/// assert!(false); +/// ``` +/// +/// Should format +/// ```rust , should_panic , edition2018 +/// assert!(false); +/// ``` +/// +/// Should not format +/// ```ignore +/// assert!( false ); +/// ``` +/// +/// Should not format (not all are rust) +/// ```rust,ignore +/// assert!( false ); +/// ``` +/// +/// Should not format (rust compile_fail) +/// ```compile_fail +/// assert!( false ); +/// ``` +/// +/// Should not format (rust compile_fail) +/// ```rust,compile_fail +/// assert!( false ); +/// ``` +/// +/// Various unspecified ones that should format +/// ``` +/// assert!(false); +/// ``` +/// +/// ```, +/// assert!(false); +/// ``` +/// +/// ```,,,,, +/// assert!(false); +/// ``` +/// +/// ```,,, rust ,, +/// assert!(false); +/// ``` +/// +/// Should not format +/// ```,,, rust , ignore, +/// assert!( false ); +/// ``` +/// +/// Few empty ones +/// ``` +/// ``` +/// +/// ```rust +/// ``` +/// +/// ```ignore +/// ``` +fn foo() {} From d647ebfb4a41f05301548e8613a2d7d403da79d5 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Wed, 8 Sep 2021 13:40:32 -0400 Subject: [PATCH 51/98] Revert "Allow formatting `Anonymous{Struct, Union}` declarations" This reverts commit 64acb7d92135ae722dfce89f0ca9d7cf6576de66. --- src/items.rs | 11 +++++++--- src/lib.rs | 7 +------ src/types.rs | 59 +++------------------------------------------------- 3 files changed, 12 insertions(+), 65 deletions(-) diff --git a/src/items.rs b/src/items.rs index 2483d0570d9ea..14041539b9dfd 100644 --- a/src/items.rs +++ b/src/items.rs @@ -6,7 +6,7 @@ use std::cmp::{max, min, Ordering}; use regex::Regex; use rustc_ast::visit; use rustc_ast::{ast, ptr}; -use rustc_span::{symbol, BytePos, Span}; +use rustc_span::{symbol, BytePos, Span, DUMMY_SP}; use crate::attr::filter_inline_attrs; use crate::comment::{ @@ -31,7 +31,12 @@ use crate::stmt::Stmt; use crate::utils::*; use crate::vertical::rewrite_with_alignment; use crate::visitor::FmtVisitor; -use crate::DEFAULT_VISIBILITY; + +const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility { + kind: ast::VisibilityKind::Inherited, + span: DUMMY_SP, + tokens: None, +}; fn type_annotation_separator(config: &Config) -> &str { colon_spaces(config) @@ -972,7 +977,7 @@ impl<'a> StructParts<'a> { format_header(context, self.prefix, self.ident, self.vis, offset) } - pub(crate) fn from_variant(variant: &'a ast::Variant) -> Self { + fn from_variant(variant: &'a ast::Variant) -> Self { StructParts { prefix: "", ident: variant.ident, diff --git a/src/lib.rs b/src/lib.rs index 206d2f782909c..47a7b9d4dbe3c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use std::path::PathBuf; use std::rc::Rc; use rustc_ast::ast; -use rustc_span::{symbol, DUMMY_SP}; +use rustc_span::symbol; use thiserror::Error; use crate::comment::LineClasses; @@ -96,11 +96,6 @@ mod types; mod vertical; pub(crate) mod visitor; -const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility { - kind: ast::VisibilityKind::Inherited, - span: DUMMY_SP, - tokens: None, -}; /// The various errors that can occur during formatting. Note that not all of /// these can currently be propagated to clients. #[derive(Error, Debug)] diff --git a/src/types.rs b/src/types.rs index 640d127e86098..76bf58e875b1f 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,15 +1,15 @@ use std::iter::ExactSizeIterator; use std::ops::Deref; -use rustc_ast::ast::{self, AttrVec, FnRetTy, Mutability}; -use rustc_span::{symbol::kw, symbol::Ident, BytePos, Pos, Span}; +use rustc_ast::ast::{self, FnRetTy, Mutability}; +use rustc_span::{symbol::kw, BytePos, Pos, Span}; +use crate::comment::{combine_strs_with_missing_comments, contains_comment}; use crate::config::lists::*; use crate::config::{IndentStyle, TypeDensity, Version}; use crate::expr::{ format_expr, rewrite_assign_rhs, rewrite_call, rewrite_tuple, rewrite_unary_prefix, ExprType, }; -use crate::items::StructParts; use crate::lists::{ definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator, }; @@ -24,11 +24,6 @@ use crate::utils::{ colon_spaces, extra_offset, first_line_width, format_extern, format_mutability, last_line_extendable, last_line_width, mk_sp, rewrite_ident, }; -use crate::DEFAULT_VISIBILITY; -use crate::{ - comment::{combine_strs_with_missing_comments, contains_comment}, - items::format_struct_struct, -}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum PathContext { @@ -769,54 +764,6 @@ impl Rewrite for ast::Ty { ast::TyKind::Tup(ref items) => { rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1) } - ast::TyKind::AnonymousStruct(ref fields, recovered) => { - let ident = Ident::new( - kw::Struct, - mk_sp(self.span.lo(), self.span.lo() + BytePos(6)), - ); - let data = ast::VariantData::Struct(fields.clone(), recovered); - let variant = ast::Variant { - attrs: AttrVec::new(), - id: self.id, - span: self.span, - vis: DEFAULT_VISIBILITY, - ident, - data, - disr_expr: None, - is_placeholder: false, - }; - format_struct_struct( - &context, - &StructParts::from_variant(&variant), - fields, - shape.indent, - None, - ) - } - ast::TyKind::AnonymousUnion(ref fields, recovered) => { - let ident = Ident::new( - kw::Union, - mk_sp(self.span.lo(), self.span.lo() + BytePos(5)), - ); - let data = ast::VariantData::Struct(fields.clone(), recovered); - let variant = ast::Variant { - attrs: AttrVec::new(), - id: self.id, - span: self.span, - vis: DEFAULT_VISIBILITY, - ident, - data, - disr_expr: None, - is_placeholder: false, - }; - format_struct_struct( - &context, - &StructParts::from_variant(&variant), - fields, - shape.indent, - None, - ) - } ast::TyKind::Path(ref q_self, ref path) => { rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape) } From e014277b07049f0638662f4040c2af7b119cc8a4 Mon Sep 17 00:00:00 2001 From: Fabian Wolff Date: Fri, 21 May 2021 19:35:49 +0200 Subject: [PATCH 52/98] Ignore automatically derived impls of `Clone` and `Debug` in dead code analysis --- src/macros.rs | 35 ++++++----------------------------- src/modules.rs | 2 -- 2 files changed, 6 insertions(+), 31 deletions(-) diff --git a/src/macros.rs b/src/macros.rs index a9bc89544d820..779a1149f413e 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -762,7 +762,6 @@ impl MacroArgKind { #[derive(Debug, Clone)] struct ParsedMacroArg { kind: MacroArgKind, - span: Span, } impl ParsedMacroArg { @@ -780,14 +779,10 @@ impl ParsedMacroArg { struct MacroArgParser { /// Either a name of the next metavariable, a separator, or junk. buf: String, - /// The start position on the current buffer. - lo: BytePos, /// The first token of the current buffer. start_tok: Token, /// `true` if we are parsing a metavariable or a repeat. is_meta_var: bool, - /// The position of the last token. - hi: BytePos, /// The last token parsed. last_tok: Token, /// Holds the parsed arguments. @@ -807,8 +802,6 @@ fn last_tok(tt: &TokenTree) -> Token { impl MacroArgParser { fn new() -> MacroArgParser { MacroArgParser { - lo: BytePos(0), - hi: BytePos(0), buf: String::new(), is_meta_var: false, last_tok: Token { @@ -824,7 +817,6 @@ impl MacroArgParser { } fn set_last_tok(&mut self, tok: &TokenTree) { - self.hi = tok.span().hi(); self.last_tok = last_tok(tok); } @@ -836,7 +828,6 @@ impl MacroArgParser { }; self.result.push(ParsedMacroArg { kind: MacroArgKind::Separator(self.buf.clone(), prefix), - span: mk_sp(self.lo, self.hi), }); self.buf.clear(); } @@ -849,7 +840,6 @@ impl MacroArgParser { }; self.result.push(ParsedMacroArg { kind: MacroArgKind::Other(self.buf.clone(), prefix), - span: mk_sp(self.lo, self.hi), }); self.buf.clear(); } @@ -858,11 +848,10 @@ impl MacroArgParser { match iter.next() { Some(TokenTree::Token(Token { kind: TokenKind::Ident(name, _), - span, + .. })) => { self.result.push(ParsedMacroArg { kind: MacroArgKind::MetaVariable(name, self.buf.clone()), - span: mk_sp(self.lo, span.hi()), }); self.buf.clear(); @@ -873,10 +862,9 @@ impl MacroArgParser { } } - fn add_delimited(&mut self, inner: Vec, delim: DelimToken, span: Span) { + fn add_delimited(&mut self, inner: Vec, delim: DelimToken) { self.result.push(ParsedMacroArg { kind: MacroArgKind::Delimited(delim, inner), - span, }); } @@ -886,19 +874,15 @@ impl MacroArgParser { inner: Vec, delim: DelimToken, iter: &mut Cursor, - span: Span, ) -> Option<()> { let mut buffer = String::new(); let mut first = true; - let mut lo = span.lo(); - let mut hi = span.hi(); // Parse '*', '+' or '?. for tok in iter { self.set_last_tok(&tok); if first { first = false; - lo = tok.span().lo(); } match tok { @@ -918,7 +902,6 @@ impl MacroArgParser { } TokenTree::Token(ref t) => { buffer.push_str(&pprust::token_to_string(&t)); - hi = t.span.hi(); } _ => return None, } @@ -930,20 +913,17 @@ impl MacroArgParser { } else { Some(Box::new(ParsedMacroArg { kind: MacroArgKind::Other(buffer, "".to_owned()), - span: mk_sp(lo, hi), })) }; self.result.push(ParsedMacroArg { kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()), - span: mk_sp(self.lo, self.hi), }); Some(()) } fn update_buffer(&mut self, t: &Token) { if self.buf.is_empty() { - self.lo = t.span.lo(); self.start_tok = t.clone(); } else { let needs_space = match next_space(&self.last_tok.kind) { @@ -999,7 +979,6 @@ impl MacroArgParser { // Start keeping the name of this metavariable in the buffer. self.is_meta_var = true; - self.lo = span.lo(); self.start_tok = Token { kind: TokenKind::Dollar, span, @@ -1012,7 +991,7 @@ impl MacroArgParser { self.add_meta_variable(&mut iter)?; } TokenTree::Token(ref t) => self.update_buffer(t), - TokenTree::Delimited(delimited_span, delimited, ref tts) => { + TokenTree::Delimited(_delimited_span, delimited, ref tts) => { if !self.buf.is_empty() { if next_space(&self.last_tok.kind) == SpaceState::Always { self.add_separator(); @@ -1022,16 +1001,14 @@ impl MacroArgParser { } // Parse the stuff inside delimiters. - let mut parser = MacroArgParser::new(); - parser.lo = delimited_span.open.lo(); + let parser = MacroArgParser::new(); let delimited_arg = parser.parse(tts.clone())?; - let span = delimited_span.entire(); if self.is_meta_var { - self.add_repeat(delimited_arg, delimited, &mut iter, span)?; + self.add_repeat(delimited_arg, delimited, &mut iter)?; self.is_meta_var = false; } else { - self.add_delimited(delimited_arg, delimited, span); + self.add_delimited(delimited_arg, delimited); } } } diff --git a/src/modules.rs b/src/modules.rs index 5de0575b5cd66..ded34d9032f91 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -27,7 +27,6 @@ type FileModMap<'ast> = BTreeMap>; pub(crate) struct Module<'a> { ast_mod_kind: Option>, pub(crate) items: Cow<'a, Vec>>, - attrs: Cow<'a, Vec>, inner_attr: Vec, pub(crate) span: Span, } @@ -46,7 +45,6 @@ impl<'a> Module<'a> { .collect(); Module { items: mod_items, - attrs: mod_attrs, inner_attr, span: mod_span, ast_mod_kind, From 127ec9a8c94419669b22079c988e38638b58395f Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 18 Apr 2021 14:27:04 +0200 Subject: [PATCH 53/98] Keep a parent LocalDefId in SpanData. --- src/macros.rs | 7 ++++++- src/utils.rs | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/macros.rs b/src/macros.rs index a9bc89544d820..f483505a53e8a 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -1270,7 +1270,12 @@ impl MacroParser { let data = delimited_span.entire().data(); ( data.hi, - Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt), + Span::new( + data.lo + BytePos(1), + data.hi - BytePos(1), + data.ctxt, + data.parent, + ), delimited_span.entire(), ) } diff --git a/src/utils.rs b/src/utils.rs index 06159a1b26e86..29e1e070d4111 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -356,11 +356,11 @@ macro_rules! source { } pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span { - Span::new(lo, hi, SyntaxContext::root()) + Span::new(lo, hi, SyntaxContext::root(), None) } pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span { - Span::new(lo, lo + BytePos(1), SyntaxContext::root()) + Span::new(lo, lo + BytePos(1), SyntaxContext::root(), None) } // Returns `true` if the given span does not intersect with file lines. From 67a59f6ee35c3cfd75e2aab5a8475608e167840b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Fri, 8 Nov 2019 23:50:18 +0200 Subject: [PATCH 54/98] opts: rephrase wording for --all and -p --- src/cargo-fmt/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index f8cf698525bab..f1125fa0bda13 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -36,7 +36,7 @@ pub struct Opts { #[structopt(long = "version")] version: bool, - /// Specify package to format (only usable in workspaces) + /// Specify package to format #[structopt(short = "p", long = "package", value_name = "package")] packages: Vec, @@ -53,7 +53,7 @@ pub struct Opts { #[structopt(name = "rustfmt_options", raw(true))] rustfmt_options: Vec, - /// Format all packages (only usable in workspaces) + /// Format all packages, and also their local path-based dependencies #[structopt(long = "all")] format_all: bool, } From d4ffd1efa4c83084f05f6e83585ae0a70450bcfd Mon Sep 17 00:00:00 2001 From: Seiichi Uchida Date: Fri, 10 Jul 2020 11:23:12 +0900 Subject: [PATCH 55/98] Support @generated marker to skip code formatting This is a copy of #4296 with these changes: * file is not reopened again to find if the file is generated * first five lines are scanned for `@generated` marker instead of one * no attempt is made to only search for marker in comments `@generated` marker is used by certain tools to understand that the file is generated, so it should be treated differently than a file written by a human: * linters should not be invoked on these files, * diffs in these files are less important, * and these files should not be reformatted. This PR proposes builtin support for `@generated` marker. I have not found a standard for a generated file marker, but: * Facebook [uses `@generated` marker](https://tinyurl.com/fb-generated) * Phabricator tool which was spawned from Facebook internal tool [also understands `@generated` marker](https://git.io/JnVHa) * Cargo inserts `@generated` marker into [generated Cargo.lock files](https://git.io/JnVHP) My personal story is that rust-protobuf project which I maintain was broken twice because of incompatibilities/bugs in rustfmt marker handling: [one](https://github.com/stepancheg/rust-protobuf/issues/493), [two](https://github.com/stepancheg/rust-protobuf/issues/551). (Also, rust-protobuf started generating `@generated` marker [6 years ago](https://git.io/JnV5h)). While rustfmt AST markers are useful to apply to a certain AST elements, disable whole-file-at-once all-tools-at-once text level marker might be easier to use and more reliable for generated code. --- Configurations.md | 9 +++++++++ src/config/mod.rs | 2 ++ src/formatting.rs | 9 ++++++++- src/formatting/generated.rs | 7 +++++++ src/syntux/session.rs | 6 ++++++ src/test/mod.rs | 2 +- tests/source/configs/format_generated_files/false.rs | 8 ++++++++ tests/source/configs/format_generated_files/true.rs | 8 ++++++++ tests/target/configs/format_generated_files/false.rs | 8 ++++++++ tests/target/configs/format_generated_files/true.rs | 6 ++++++ 10 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 src/formatting/generated.rs create mode 100644 tests/source/configs/format_generated_files/false.rs create mode 100644 tests/source/configs/format_generated_files/true.rs create mode 100644 tests/target/configs/format_generated_files/false.rs create mode 100644 tests/target/configs/format_generated_files/true.rs diff --git a/Configurations.md b/Configurations.md index 469deccc56ef3..84e8c3f7db614 100644 --- a/Configurations.md +++ b/Configurations.md @@ -924,6 +924,15 @@ fn add_one(x: i32) -> i32 { } ``` +## `format_generated_files` + +Format generated files. A file is considered generated +if any of the first five lines contains `@generated` marker. + +- **Default value**: `false` +- **Possible values**: `true`, `false` +- **Stable**: No + ## `format_macro_matchers` Format the metavariable matching patterns in macros. diff --git a/src/config/mod.rs b/src/config/mod.rs index 8c04363b1fd4b..3d6e32fdb60f1 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -136,6 +136,7 @@ create_config! { inline_attribute_width: usize, 0, false, "Write an item and its attribute on the same line \ if their combined width is below a threshold"; + format_generated_files: bool, false, false, "Format generated files"; // Options that can change the source code beyond whitespace/blocks (somewhat linty things) merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one"; @@ -604,6 +605,7 @@ blank_lines_lower_bound = 0 edition = "2015" version = "One" inline_attribute_width = 0 +format_generated_files = false merge_derives = true use_try_shorthand = false use_field_init_shorthand = false diff --git a/src/formatting.rs b/src/formatting.rs index e0403574eebc1..9ef47b887cadb 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -10,6 +10,7 @@ use rustc_span::Span; use self::newline_style::apply_newline_style; use crate::comment::{CharClasses, FullCodeCharKind}; use crate::config::{Config, FileName, Verbosity}; +use crate::formatting::generated::is_generated_file; use crate::issues::BadIssueSeeker; use crate::modules::Module; use crate::syntux::parser::{DirectoryOwnership, Parser, ParserError}; @@ -18,6 +19,7 @@ use crate::utils::count_newlines; use crate::visitor::FmtVisitor; use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session}; +mod generated; mod newline_style; // A map of the files of a crate, with their new content @@ -103,7 +105,12 @@ fn format_project( context.parse_session.set_silent_emitter(); for (path, module) in files { - let should_ignore = !input_is_stdin && context.ignore_file(&path); + let source_file = context.parse_session.span_to_file_contents(module.span); + let src = source_file.src.as_ref().expect("SourceFile without src"); + + let should_ignore = (!input_is_stdin && context.ignore_file(&path)) + || (!config.format_generated_files() && is_generated_file(src)); + if (config.skip_children() && path != main_file) || should_ignore { continue; } diff --git a/src/formatting/generated.rs b/src/formatting/generated.rs new file mode 100644 index 0000000000000..58f43f17ee15f --- /dev/null +++ b/src/formatting/generated.rs @@ -0,0 +1,7 @@ +/// Returns `true` if the given span is a part of generated files. +pub(super) fn is_generated_file(original_snippet: &str) -> bool { + original_snippet + .lines() + .take(5) // looking for marker only in the beginning of the file + .any(|line| line.contains("@generated")) +} diff --git a/src/syntux/session.rs b/src/syntux/session.rs index 870f0acfe395c..94257e1ce7f15 100644 --- a/src/syntux/session.rs +++ b/src/syntux/session.rs @@ -175,6 +175,12 @@ impl ParseSess { self.parse_sess.source_map().span_to_filename(span).into() } + pub(crate) fn span_to_file_contents(&self, span: Span) -> Lrc { + self.parse_sess + .source_map() + .lookup_source_file(span.data().lo) + } + pub(crate) fn span_to_first_line_string(&self, span: Span) -> String { let file_lines = self.parse_sess.source_map().span_to_lines(span).ok(); diff --git a/src/test/mod.rs b/src/test/mod.rs index cb52346a13a41..ece1b91bfd7c5 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -694,7 +694,7 @@ fn read_significant_comments(file_name: &Path) -> HashMap { reader .lines() .map(|line| line.expect("failed getting line")) - .take_while(|line| line_regex.is_match(line)) + .filter(|line| line_regex.is_match(line)) .filter_map(|line| { regex.captures_iter(&line).next().map(|capture| { ( diff --git a/tests/source/configs/format_generated_files/false.rs b/tests/source/configs/format_generated_files/false.rs new file mode 100644 index 0000000000000..dec1e00d117b4 --- /dev/null +++ b/tests/source/configs/format_generated_files/false.rs @@ -0,0 +1,8 @@ +// @generated +// rustfmt-format_generated_files: false + +fn main() +{ + println!("hello, world") + ; +} diff --git a/tests/source/configs/format_generated_files/true.rs b/tests/source/configs/format_generated_files/true.rs new file mode 100644 index 0000000000000..a25ddc25a6a44 --- /dev/null +++ b/tests/source/configs/format_generated_files/true.rs @@ -0,0 +1,8 @@ +// @generated +// rustfmt-format_generated_files: true + +fn main() +{ + println!("hello, world") + ; +} diff --git a/tests/target/configs/format_generated_files/false.rs b/tests/target/configs/format_generated_files/false.rs new file mode 100644 index 0000000000000..dec1e00d117b4 --- /dev/null +++ b/tests/target/configs/format_generated_files/false.rs @@ -0,0 +1,8 @@ +// @generated +// rustfmt-format_generated_files: false + +fn main() +{ + println!("hello, world") + ; +} diff --git a/tests/target/configs/format_generated_files/true.rs b/tests/target/configs/format_generated_files/true.rs new file mode 100644 index 0000000000000..5fea7e8b34139 --- /dev/null +++ b/tests/target/configs/format_generated_files/true.rs @@ -0,0 +1,6 @@ +// @generated +// rustfmt-format_generated_files: true + +fn main() { + println!("hello, world"); +} From 9d65b7dcd19557bca9aa4b175efa14a35db6d713 Mon Sep 17 00:00:00 2001 From: Arjen Laarhoven Date: Thu, 15 Jul 2021 19:55:52 +0200 Subject: [PATCH 56/98] feat: upper- or lowercase hexadecimal literals --- Configurations.md | 7 ++++++ src/config/mod.rs | 3 +++ src/config/options.rs | 11 ++++++++++ src/expr.rs | 33 +++++++++++++++++++++++++++- tests/source/hex_literal_lower.rs | 5 +++++ tests/source/hex_literal_upper.rs | 5 +++++ tests/target/hex_literal_lower.rs | 5 +++++ tests/target/hex_literal_preserve.rs | 5 +++++ tests/target/hex_literal_upper.rs | 5 +++++ 9 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 tests/source/hex_literal_lower.rs create mode 100644 tests/source/hex_literal_upper.rs create mode 100644 tests/target/hex_literal_lower.rs create mode 100644 tests/target/hex_literal_preserve.rs create mode 100644 tests/target/hex_literal_upper.rs diff --git a/Configurations.md b/Configurations.md index 84e8c3f7db614..b8f8f3053968f 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1056,6 +1056,13 @@ fn lorem() -> usize { See also: [`tab_spaces`](#tab_spaces). +## `hex_literal_case` + +Control the case of the letters in hexadecimal literal values + +- **Default value**: `Preserve` +- **Possible values**: `Upper`, `Lower` +- **Stable**: No ## `hide_parse_errors` diff --git a/src/config/mod.rs b/src/config/mod.rs index 3d6e32fdb60f1..c6cee8ed22734 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -69,6 +69,8 @@ create_config! { format_macro_matchers: bool, false, false, "Format the metavariable matching patterns in macros"; format_macro_bodies: bool, true, false, "Format the bodies of macros"; + hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false, + "Format hexadecimal integer literals"; // Single line expressions and items empty_item_single_line: bool, true, false, @@ -570,6 +572,7 @@ license_template_path = "" format_strings = false format_macro_matchers = false format_macro_bodies = true +hex_literal_case = "Preserve" empty_item_single_line = true struct_lit_single_line = true fn_single_line = false diff --git a/src/config/options.rs b/src/config/options.rs index db15ee97a40ac..e92f8e8a53152 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -129,6 +129,17 @@ pub enum ImportGranularity { One, } +/// Controls how rustfmt should handle case in hexadecimal literals. +#[config_type] +pub enum HexLiteralCase { + /// Leave the literal as-is + Preserve, + /// Ensure all literals use uppercase lettering + Upper, + /// Ensure all literals use lowercase lettering + Lower, +} + #[config_type] pub enum ReportTactic { Always, diff --git a/src/expr.rs b/src/expr.rs index 6cfeb9977a966..01cc388c186ef 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -13,7 +13,7 @@ use crate::comment::{ rewrite_missing_comment, CharClasses, FindUncommented, }; use crate::config::lists::*; -use crate::config::{Config, ControlBraceStyle, IndentStyle, Version}; +use crate::config::{Config, ControlBraceStyle, HexLiteralCase, IndentStyle, Version}; use crate::lists::{ definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape, struct_lit_tactic, write_list, ListFormatting, Separator, @@ -1168,6 +1168,7 @@ pub(crate) fn rewrite_literal( ) -> Option { match l.kind { ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape), + ast::LitKind::Int(..) => rewrite_int_lit(context, l, shape), _ => wrap_str( context.snippet(l.span).to_owned(), context.config.max_width(), @@ -1202,6 +1203,36 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> ) } +fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option { + let span = lit.span; + let symbol = lit.token.symbol.as_str(); + + if symbol.starts_with("0x") { + let hex_lit = match context.config.hex_literal_case() { + HexLiteralCase::Preserve => None, + HexLiteralCase::Upper => Some(symbol[2..].to_ascii_uppercase()), + HexLiteralCase::Lower => Some(symbol[2..].to_ascii_lowercase()), + }; + if let Some(hex_lit) = hex_lit { + return wrap_str( + format!( + "0x{}{}", + hex_lit, + lit.token.suffix.map_or(String::new(), |s| s.to_string()) + ), + context.config.max_width(), + shape, + ); + } + } + + wrap_str( + context.snippet(span).to_owned(), + context.config.max_width(), + shape, + ) +} + fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option { if context.inside_macro() { if span_ends_with_comma(context, span) { diff --git a/tests/source/hex_literal_lower.rs b/tests/source/hex_literal_lower.rs new file mode 100644 index 0000000000000..ce307b3aa521e --- /dev/null +++ b/tests/source/hex_literal_lower.rs @@ -0,0 +1,5 @@ +// rustfmt-hex_literal_case: Lower +fn main() { + let h1 = 0xCAFE_5EA7; + let h2 = 0xCAFE_F00Du32; +} diff --git a/tests/source/hex_literal_upper.rs b/tests/source/hex_literal_upper.rs new file mode 100644 index 0000000000000..b1092ad71ba13 --- /dev/null +++ b/tests/source/hex_literal_upper.rs @@ -0,0 +1,5 @@ +// rustfmt-hex_literal_case: Upper +fn main() { + let h1 = 0xCaFE_5ea7; + let h2 = 0xCAFE_F00Du32; +} diff --git a/tests/target/hex_literal_lower.rs b/tests/target/hex_literal_lower.rs new file mode 100644 index 0000000000000..5c27fded16743 --- /dev/null +++ b/tests/target/hex_literal_lower.rs @@ -0,0 +1,5 @@ +// rustfmt-hex_literal_case: Lower +fn main() { + let h1 = 0xcafe_5ea7; + let h2 = 0xcafe_f00du32; +} diff --git a/tests/target/hex_literal_preserve.rs b/tests/target/hex_literal_preserve.rs new file mode 100644 index 0000000000000..e8774d0bb24eb --- /dev/null +++ b/tests/target/hex_literal_preserve.rs @@ -0,0 +1,5 @@ +// rustfmt-hex_literal_case: Preserve +fn main() { + let h1 = 0xcAfE_5Ea7; + let h2 = 0xCaFe_F00du32; +} diff --git a/tests/target/hex_literal_upper.rs b/tests/target/hex_literal_upper.rs new file mode 100644 index 0000000000000..48bb93d2c1c08 --- /dev/null +++ b/tests/target/hex_literal_upper.rs @@ -0,0 +1,5 @@ +// rustfmt-hex_literal_case: Upper +fn main() { + let h1 = 0xCAFE_5EA7; + let h2 = 0xCAFE_F00Du32; +} From 17cb2b147e11c9ad274b316026b1001fbd7007d4 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sat, 26 Oct 2019 21:07:04 -0500 Subject: [PATCH 57/98] feat: add --check flag to cargo fmt (#3890) --- src/cargo-fmt/main.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index f1125fa0bda13..89ce454ac4d00 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -56,6 +56,10 @@ pub struct Opts { /// Format all packages, and also their local path-based dependencies #[structopt(long = "all")] format_all: bool, + + /// Run rustfmt in check mode + #[structopt(long = "check")] + check: bool, } fn main() { @@ -104,6 +108,12 @@ fn execute() -> i32 { let strategy = CargoFmtStrategy::from_opts(&opts); let mut rustfmt_args = opts.rustfmt_options; + if opts.check { + let check_flag = String::from("--check"); + if !rustfmt_args.contains(&check_flag) { + rustfmt_args.push(check_flag); + } + } if let Some(message_format) = opts.message_format { if let Err(msg) = convert_message_format_to_rustfmt_args(&message_format, &mut rustfmt_args) { @@ -553,6 +563,7 @@ mod cargo_fmt_tests { assert_eq!(false, o.quiet); assert_eq!(false, o.verbose); assert_eq!(false, o.version); + assert_eq!(false, o.check); assert_eq!(empty, o.packages); assert_eq!(empty, o.rustfmt_options); assert_eq!(false, o.format_all); @@ -571,6 +582,7 @@ mod cargo_fmt_tests { "p2", "--message-format", "short", + "--check", "--", "--edition", "2018", @@ -578,6 +590,7 @@ mod cargo_fmt_tests { assert_eq!(true, o.quiet); assert_eq!(false, o.verbose); assert_eq!(false, o.version); + assert_eq!(true, o.check); assert_eq!(vec!["p1", "p2"], o.packages); assert_eq!(vec!["--edition", "2018"], o.rustfmt_options); assert_eq!(false, o.format_all); @@ -606,12 +619,12 @@ mod cargo_fmt_tests { fn mandatory_separator() { assert!( Opts::clap() - .get_matches_from_safe(&["test", "--check"]) + .get_matches_from_safe(&["test", "--emit"]) .is_err() ); assert!( !Opts::clap() - .get_matches_from_safe(&["test", "--", "--check"]) + .get_matches_from_safe(&["test", "--", "--emit"]) .is_err() ); } From 7aa69e5bc87f32fdcbf037abce2d575335480b9a Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Thu, 16 Sep 2021 21:25:09 -0500 Subject: [PATCH 58/98] refactor: use iter workaround for contains() gap --- src/cargo-fmt/main.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 89ce454ac4d00..147b19d7a48c7 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -109,9 +109,9 @@ fn execute() -> i32 { let strategy = CargoFmtStrategy::from_opts(&opts); let mut rustfmt_args = opts.rustfmt_options; if opts.check { - let check_flag = String::from("--check"); - if !rustfmt_args.contains(&check_flag) { - rustfmt_args.push(check_flag); + let check_flag = "--check"; + if !rustfmt_args.iter().any(|o| o == check_flag) { + rustfmt_args.push(check_flag.to_owned()); } } if let Some(message_format) = opts.message_format { From dd445aba080cd337300644c77137fedcad482623 Mon Sep 17 00:00:00 2001 From: Ulyssa Date: Wed, 15 Sep 2021 08:58:23 -0700 Subject: [PATCH 59/98] Trailing comma on match block goes missing when guard is on its own line --- src/matches.rs | 1 + tests/source/match-block-trailing-comma.rs | 8 ++++++++ tests/target/match-block-trailing-comma.rs | 10 ++++++++++ 3 files changed, 19 insertions(+) diff --git a/src/matches.rs b/src/matches.rs index 140ec226c02e5..5a6ed0ec06e55 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -409,6 +409,7 @@ fn rewrite_match_body( } result.push_str(&nested_indent_str); result.push_str(&body_str); + result.push_str(&comma); return Some(result); } diff --git a/tests/source/match-block-trailing-comma.rs b/tests/source/match-block-trailing-comma.rs index e9daac13bf96f..baa05b79c1617 100644 --- a/tests/source/match-block-trailing-comma.rs +++ b/tests/source/match-block-trailing-comma.rs @@ -8,6 +8,14 @@ fn foo() { "line1"; "line2" } + ThisIsA::Guard if true => { + "line1"; + "line2" + } + ThisIsA::ReallyLongPattern(ThatWillForce::TheGuard, ToWrapOnto::TheFollowingLine) if true => { + "line1"; + "line2" + } b => (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb), } diff --git a/tests/target/match-block-trailing-comma.rs b/tests/target/match-block-trailing-comma.rs index 44d1f289f8e0f..5ab433a2e6cf6 100644 --- a/tests/target/match-block-trailing-comma.rs +++ b/tests/target/match-block-trailing-comma.rs @@ -8,6 +8,16 @@ fn foo() { "line1"; "line2" }, + ThisIsA::Guard if true => { + "line1"; + "line2" + }, + ThisIsA::ReallyLongPattern(ThatWillForce::TheGuard, ToWrapOnto::TheFollowingLine) + if true => + { + "line1"; + "line2" + }, b => ( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, From 9060bc5583f80a37530ee35a6cc2ddf1293d068f Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Sun, 19 Sep 2021 12:49:55 -0400 Subject: [PATCH 60/98] Migrate to 2021 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 81e3e26e8b000..7b4667c17c864 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license = "Apache-2.0/MIT" build = "build.rs" categories = ["development-tools"] -edition = "2018" +edition = "2021" [[bin]] name = "rustfmt" From 74df7b3265702949105161b36aee8b0975907210 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 19 Sep 2021 22:15:50 -0500 Subject: [PATCH 61/98] deps: update cargo_metadata to include 'path' --- Cargo.lock | 44 ++++++++++++++------------------------------ Cargo.toml | 2 +- 2 files changed, 15 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index be134f3e9754c..7263f0474770a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -75,6 +75,15 @@ dependencies = [ "packed_simd_2", ] +[[package]] +name = "camino" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d74260d9bf6944e2208aa46841b4b8f0d7ffc0849a06837b2f510337f86b2b" +dependencies = [ + "serde", +] + [[package]] name = "cargo-platform" version = "0.1.1" @@ -86,13 +95,13 @@ dependencies = [ [[package]] name = "cargo_metadata" -version = "0.12.3" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714a157da7991e23d90686b9524b9e12e0407a108647f52e9328f4b3d51ac7f" +checksum = "c297bd3135f558552f99a0daa180876984ea2c4ffa7470314540dff8c654109a" dependencies = [ + "camino", "cargo-platform", "semver", - "semver-parser", "serde", "serde_json", ] @@ -322,15 +331,6 @@ dependencies = [ "libm", ] -[[package]] -name = "pest" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" -dependencies = [ - "ucd-trie", -] - [[package]] name = "proc-macro-error" version = "0.4.11" @@ -475,23 +475,13 @@ dependencies = [ [[package]] name = "semver" -version = "0.11.0" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +checksum = "568a8e6258aa33c13358f81fd834adb854c6f7c9468520910a9b1e8fac068012" dependencies = [ - "semver-parser", "serde", ] -[[package]] -name = "semver-parser" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" -dependencies = [ - "pest", -] - [[package]] name = "serde" version = "1.0.126" @@ -641,12 +631,6 @@ dependencies = [ "serde", ] -[[package]] -name = "ucd-trie" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" - [[package]] name = "unicode-segmentation" version = "1.3.0" diff --git a/Cargo.toml b/Cargo.toml index e368f3eb1ec0d..970b13eab353b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,7 @@ log = "0.4.14" env_logger = "0.8" getopts = "0.2" derive-new = "0.5" -cargo_metadata = "0.12" +cargo_metadata = "0.14" bytecount = "0.6" unicode-width = "0.1.5" unicode_categories = "0.1.1" From 7f6229b9aada69389be4ead0ecbec8aed5892a24 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 20 Sep 2021 18:58:38 -0500 Subject: [PATCH 62/98] tests: restructure and extend cargo-fmt tests --- .gitignore | 1 + src/cargo-fmt/test/message_format.rs | 80 ++++++++++ src/cargo-fmt/test/mod.rs | 137 ++++++++++++++++++ src/cargo-fmt/test/targets.rs | 134 +++++++++++++++++ .../divergent-crate-dir-names/Cargo.toml | 13 ++ .../dependency-dir-name/Cargo.toml | 10 ++ .../dependency-dir-name/src/lib.rs | 7 + .../subdep-dir-name/Cargo.toml | 7 + .../subdep-dir-name/src/lib.rs | 7 + .../divergent-crate-dir-names/src/main.rs | 3 + .../workspaces/path-dep-above/e/Cargo.toml | 6 + .../workspaces/path-dep-above/e/src/main.rs | 1 + .../workspaces/path-dep-above/ws/Cargo.toml | 5 + .../workspaces/path-dep-above/ws/a/Cargo.toml | 6 + .../path-dep-above/ws/a/d/Cargo.toml | 7 + .../path-dep-above/ws/a/d/f/Cargo.toml | 4 + .../path-dep-above/ws/a/d/f/src/lib.rs | 1 + .../path-dep-above/ws/a/d/src/lib.rs | 1 + .../path-dep-above/ws/a/src/main.rs | 1 + .../workspaces/path-dep-above/ws/b/Cargo.toml | 6 + .../path-dep-above/ws/b/src/main.rs | 1 + .../workspaces/path-dep-above/ws/c/Cargo.toml | 4 + .../workspaces/path-dep-above/ws/c/src/lib.rs | 1 + 23 files changed, 443 insertions(+) create mode 100644 src/cargo-fmt/test/message_format.rs create mode 100644 src/cargo-fmt/test/mod.rs create mode 100644 src/cargo-fmt/test/targets.rs create mode 100644 tests/cargo-fmt/source/divergent-crate-dir-names/Cargo.toml create mode 100644 tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/Cargo.toml create mode 100644 tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/src/lib.rs create mode 100644 tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/subdep-dir-name/Cargo.toml create mode 100644 tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/subdep-dir-name/src/lib.rs create mode 100644 tests/cargo-fmt/source/divergent-crate-dir-names/src/main.rs create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/e/src/main.rs create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/Cargo.toml create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/Cargo.toml create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/Cargo.toml create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/f/Cargo.toml create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/f/src/lib.rs create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/src/lib.rs create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/src/main.rs create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/b/Cargo.toml create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/b/src/main.rs create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/c/Cargo.toml create mode 100644 tests/cargo-fmt/source/workspaces/path-dep-above/ws/c/src/lib.rs diff --git a/.gitignore b/.gitignore index 37adf8751ca8f..71cf88f79e67b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ # Generated by Cargo # will have compiled files and executables /target +tests/cargo-fmt/**/target # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock diff --git a/src/cargo-fmt/test/message_format.rs b/src/cargo-fmt/test/message_format.rs new file mode 100644 index 0000000000000..bf44924f13c31 --- /dev/null +++ b/src/cargo-fmt/test/message_format.rs @@ -0,0 +1,80 @@ +use super::*; + +#[test] +fn invalid_message_format() { + assert_eq!( + convert_message_format_to_rustfmt_args("awesome", &mut vec![]), + Err(String::from( + "invalid --message-format value: awesome. Allowed values are: short|json|human" + )), + ); +} + +#[test] +fn json_message_format_and_check_arg() { + let mut args = vec![String::from("--check")]; + assert_eq!( + convert_message_format_to_rustfmt_args("json", &mut args), + Err(String::from( + "cannot include --check arg when --message-format is set to json" + )), + ); +} + +#[test] +fn json_message_format_and_emit_arg() { + let mut args = vec![String::from("--emit"), String::from("checkstyle")]; + assert_eq!( + convert_message_format_to_rustfmt_args("json", &mut args), + Err(String::from( + "cannot include --emit arg when --message-format is set to json" + )), + ); +} + +#[test] +fn json_message_format() { + let mut args = vec![String::from("--edition"), String::from("2018")]; + assert!(convert_message_format_to_rustfmt_args("json", &mut args).is_ok()); + assert_eq!( + args, + vec![ + String::from("--edition"), + String::from("2018"), + String::from("--emit"), + String::from("json") + ] + ); +} + +#[test] +fn human_message_format() { + let exp_args = vec![String::from("--emit"), String::from("json")]; + let mut act_args = exp_args.clone(); + assert!(convert_message_format_to_rustfmt_args("human", &mut act_args).is_ok()); + assert_eq!(act_args, exp_args); +} + +#[test] +fn short_message_format() { + let mut args = vec![String::from("--check")]; + assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok()); + assert_eq!(args, vec![String::from("--check"), String::from("-l")]); +} + +#[test] +fn short_message_format_included_short_list_files_flag() { + let mut args = vec![String::from("--check"), String::from("-l")]; + assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok()); + assert_eq!(args, vec![String::from("--check"), String::from("-l")]); +} + +#[test] +fn short_message_format_included_long_list_files_flag() { + let mut args = vec![String::from("--check"), String::from("--files-with-diff")]; + assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok()); + assert_eq!( + args, + vec![String::from("--check"), String::from("--files-with-diff")] + ); +} diff --git a/src/cargo-fmt/test/mod.rs b/src/cargo-fmt/test/mod.rs new file mode 100644 index 0000000000000..360503632c7ed --- /dev/null +++ b/src/cargo-fmt/test/mod.rs @@ -0,0 +1,137 @@ +use super::*; + +mod message_format; +mod targets; + +#[test] +fn default_options() { + let empty: Vec = vec![]; + let o = Opts::from_iter(&empty); + assert_eq!(false, o.quiet); + assert_eq!(false, o.verbose); + assert_eq!(false, o.version); + assert_eq!(false, o.check); + assert_eq!(empty, o.packages); + assert_eq!(empty, o.rustfmt_options); + assert_eq!(false, o.format_all); + assert_eq!(None, o.manifest_path); + assert_eq!(None, o.message_format); +} + +#[test] +fn good_options() { + let o = Opts::from_iter(&[ + "test", + "-q", + "-p", + "p1", + "-p", + "p2", + "--message-format", + "short", + "--check", + "--", + "--edition", + "2018", + ]); + assert_eq!(true, o.quiet); + assert_eq!(false, o.verbose); + assert_eq!(false, o.version); + assert_eq!(true, o.check); + assert_eq!(vec!["p1", "p2"], o.packages); + assert_eq!(vec!["--edition", "2018"], o.rustfmt_options); + assert_eq!(false, o.format_all); + assert_eq!(Some(String::from("short")), o.message_format); +} + +#[test] +fn unexpected_option() { + assert!( + Opts::clap() + .get_matches_from_safe(&["test", "unexpected"]) + .is_err() + ); +} + +#[test] +fn unexpected_flag() { + assert!( + Opts::clap() + .get_matches_from_safe(&["test", "--flag"]) + .is_err() + ); +} + +#[test] +fn mandatory_separator() { + assert!( + Opts::clap() + .get_matches_from_safe(&["test", "--emit"]) + .is_err() + ); + assert!( + !Opts::clap() + .get_matches_from_safe(&["test", "--", "--emit"]) + .is_err() + ); +} + +#[test] +fn multiple_packages_one_by_one() { + let o = Opts::from_iter(&[ + "test", + "-p", + "package1", + "--package", + "package2", + "-p", + "package3", + ]); + assert_eq!(3, o.packages.len()); +} + +#[test] +fn multiple_packages_grouped() { + let o = Opts::from_iter(&[ + "test", + "--package", + "package1", + "package2", + "-p", + "package3", + "package4", + ]); + assert_eq!(4, o.packages.len()); +} + +#[test] +fn empty_packages_1() { + assert!(Opts::clap().get_matches_from_safe(&["test", "-p"]).is_err()); +} + +#[test] +fn empty_packages_2() { + assert!( + Opts::clap() + .get_matches_from_safe(&["test", "-p", "--", "--check"]) + .is_err() + ); +} + +#[test] +fn empty_packages_3() { + assert!( + Opts::clap() + .get_matches_from_safe(&["test", "-p", "--verbose"]) + .is_err() + ); +} + +#[test] +fn empty_packages_4() { + assert!( + Opts::clap() + .get_matches_from_safe(&["test", "-p", "--check"]) + .is_err() + ); +} diff --git a/src/cargo-fmt/test/targets.rs b/src/cargo-fmt/test/targets.rs new file mode 100644 index 0000000000000..b7e7fabdf7156 --- /dev/null +++ b/src/cargo-fmt/test/targets.rs @@ -0,0 +1,134 @@ +use super::*; + +struct ExpTarget { + path: &'static str, + edition: &'static str, + kind: &'static str, +} + +mod all_targets { + use super::*; + + fn assert_correct_targets_loaded( + manifest_suffix: &str, + source_root: &str, + exp_targets: &[ExpTarget], + exp_num_targets: usize, + ) { + let root_path = Path::new("tests/cargo-fmt/source").join(source_root); + let get_path = |exp: &str| PathBuf::from(&root_path).join(exp).canonicalize().unwrap(); + let manifest_path = Path::new(&root_path).join(manifest_suffix); + let targets = get_targets(&CargoFmtStrategy::All, Some(manifest_path.as_path())) + .expect("Targets should have been loaded"); + + assert_eq!(targets.len(), exp_num_targets); + + for target in exp_targets { + assert!(targets.contains(&Target { + path: get_path(target.path), + edition: target.edition.to_owned(), + kind: target.kind.to_owned(), + })); + } + } + + mod different_crate_and_dir_names { + use super::*; + + fn assert_correct_targets_loaded(manifest_suffix: &str) { + let exp_targets = vec![ + ExpTarget { + path: "dependency-dir-name/subdep-dir-name/src/lib.rs", + edition: "2018", + kind: "lib", + }, + ExpTarget { + path: "dependency-dir-name/src/lib.rs", + edition: "2018", + kind: "lib", + }, + ExpTarget { + path: "src/main.rs", + edition: "2018", + kind: "main", + }, + ]; + super::assert_correct_targets_loaded( + manifest_suffix, + "divergent-crate-dir-names", + &exp_targets, + 3, + ); + } + + #[test] + fn correct_targets_from_root() { + assert_correct_targets_loaded("Cargo.toml"); + } + + #[test] + fn correct_targets_from_sub_local_dep() { + assert_correct_targets_loaded("dependency-dir-name/Cargo.toml"); + } + } + + mod workspaces { + use super::*; + + fn assert_correct_targets_loaded(manifest_suffix: &str) { + let exp_targets = vec![ + ExpTarget { + path: "ws/a/src/main.rs", + edition: "2018", + kind: "bin", + }, + ExpTarget { + path: "ws/b/src/main.rs", + edition: "2018", + kind: "bin", + }, + ExpTarget { + path: "ws/c/src/lib.rs", + edition: "2018", + kind: "lib", + }, + ExpTarget { + path: "ws/a/d/src/lib.rs", + edition: "2018", + kind: "lib", + }, + ExpTarget { + path: "e/src/main.rs", + edition: "2018", + kind: "main", + }, + ExpTarget { + path: "ws/a/d/f/src/lib.rs", + edition: "2018", + kind: "lib", + }, + ]; + super::assert_correct_targets_loaded( + manifest_suffix, + "workspaces/path-dep-above", + &exp_targets, + 6, + ); + } + + #[test] + fn includes_outside_workspace_deps() { + assert_correct_targets_loaded("ws/Cargo.toml"); + } + + #[test] + fn includes_workspace_from_dep_above() { + assert_correct_targets_loaded("e/Cargo.toml"); + } + + #[test] + fn includes_all_packages_from_workspace_subdir() { + assert_correct_targets_loaded("ws/a/d/f/Cargo.toml"); + } + } +} diff --git a/tests/cargo-fmt/source/divergent-crate-dir-names/Cargo.toml b/tests/cargo-fmt/source/divergent-crate-dir-names/Cargo.toml new file mode 100644 index 0000000000000..315364a64573a --- /dev/null +++ b/tests/cargo-fmt/source/divergent-crate-dir-names/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "cargo-fmt-test" +version = "0.1.0" +authors = ["calebcartwright"] +edition = "2018" + +[dependencies] +indexmap = "1.0.2" + +[workspace] +members = [ + "dependency-dir-name", +] \ No newline at end of file diff --git a/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/Cargo.toml b/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/Cargo.toml new file mode 100644 index 0000000000000..4493882bf40a2 --- /dev/null +++ b/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "dependency-crate-name" +version = "0.1.0" +authors = ["calebcartwright"] +edition = "2018" + +[dependencies] +subdep-crate-name = { path = "subdep-dir-name" } +indexmap = "1.0.2" +rusty-hook = "0.8.4" \ No newline at end of file diff --git a/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/src/lib.rs b/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/src/lib.rs new file mode 100644 index 0000000000000..e93b18d725b9d --- /dev/null +++ b/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/src/lib.rs @@ -0,0 +1,7 @@ +#[cfg(test)] +mod tests { +#[test] +fn it_works() { + assert_eq!(2 + 2, 4); +} +} diff --git a/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/subdep-dir-name/Cargo.toml b/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/subdep-dir-name/Cargo.toml new file mode 100644 index 0000000000000..7dad09f4077b2 --- /dev/null +++ b/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/subdep-dir-name/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "subdep-crate-name" +version = "0.1.0" +authors = ["calebcartwright"] +edition = "2018" + +[dependencies] diff --git a/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/subdep-dir-name/src/lib.rs b/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/subdep-dir-name/src/lib.rs new file mode 100644 index 0000000000000..1c08c1c4fd386 --- /dev/null +++ b/tests/cargo-fmt/source/divergent-crate-dir-names/dependency-dir-name/subdep-dir-name/src/lib.rs @@ -0,0 +1,7 @@ +#[cfg(test)] +mod tests { +#[test] +fn sub_test_that_works() { + assert_eq!(3 + 3, 6); +} + } diff --git a/tests/cargo-fmt/source/divergent-crate-dir-names/src/main.rs b/tests/cargo-fmt/source/divergent-crate-dir-names/src/main.rs new file mode 100644 index 0000000000000..f5c339a8dd141 --- /dev/null +++ b/tests/cargo-fmt/source/divergent-crate-dir-names/src/main.rs @@ -0,0 +1,3 @@ +fn main() { +println!("Hello, world!"); +} diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml b/tests/cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml new file mode 100644 index 0000000000000..df1886c82be31 --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "e" +version = "0.1.0" +edition = "2018" +[dependencies] +c = { path = "../ws/c" } diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/e/src/main.rs b/tests/cargo-fmt/source/workspaces/path-dep-above/e/src/main.rs new file mode 100644 index 0000000000000..1c26a3895f37e --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/e/src/main.rs @@ -0,0 +1 @@ +struct E{ } diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/Cargo.toml b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/Cargo.toml new file mode 100644 index 0000000000000..202739b613b8f --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/Cargo.toml @@ -0,0 +1,5 @@ +[workspace] +members = [ + "a", + "b" +] \ No newline at end of file diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/Cargo.toml b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/Cargo.toml new file mode 100644 index 0000000000000..712a113448fb1 --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "a" +version = "0.1.0" +edition = "2018" +[dependencies] +d = { path = "./d" } diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/Cargo.toml b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/Cargo.toml new file mode 100644 index 0000000000000..fb0f06fe5fce1 --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "d" +version = "0.1.0" +edition = "2018" +[dependencies] +e = { path = "../../../e" } +f = { path = "f" } diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/f/Cargo.toml b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/f/Cargo.toml new file mode 100644 index 0000000000000..5c4fa5617886f --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/f/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "f" +version = "0.1.0" +edition = "2018" diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/f/src/lib.rs b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/f/src/lib.rs new file mode 100644 index 0000000000000..c655c4d5e1a82 --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/f/src/lib.rs @@ -0,0 +1 @@ +struct F{ } \ No newline at end of file diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/src/lib.rs b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/src/lib.rs new file mode 100644 index 0000000000000..04e6e4cb94022 --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/d/src/lib.rs @@ -0,0 +1 @@ +struct D{ } \ No newline at end of file diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/src/main.rs b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/src/main.rs new file mode 100644 index 0000000000000..04e6e4cb94022 --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/a/src/main.rs @@ -0,0 +1 @@ +struct D{ } \ No newline at end of file diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/b/Cargo.toml b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/b/Cargo.toml new file mode 100644 index 0000000000000..47a24ff4f2753 --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "b" +version = "0.1.0" +edition = "2018" +[dependencies] +c = { path = "../c" } diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/b/src/main.rs b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/b/src/main.rs new file mode 100644 index 0000000000000..4833bbc69b48e --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/b/src/main.rs @@ -0,0 +1 @@ +struct B{ } \ No newline at end of file diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/c/Cargo.toml b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/c/Cargo.toml new file mode 100644 index 0000000000000..49fa6c395eb6c --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/c/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "c" +version = "0.1.0" +edition = "2018" diff --git a/tests/cargo-fmt/source/workspaces/path-dep-above/ws/c/src/lib.rs b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/c/src/lib.rs new file mode 100644 index 0000000000000..1245ac91d60a4 --- /dev/null +++ b/tests/cargo-fmt/source/workspaces/path-dep-above/ws/c/src/lib.rs @@ -0,0 +1 @@ +struct C{ } \ No newline at end of file From 4b9d637f5846b92f2c17b98985c47dea795064d2 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 20 Sep 2021 19:09:16 -0500 Subject: [PATCH 63/98] refactor: simplify local dep lookups --- src/cargo-fmt/main.rs | 280 ++++-------------------------------------- 1 file changed, 26 insertions(+), 254 deletions(-) diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 147b19d7a48c7..1d423ac34919b 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -17,6 +17,10 @@ use std::str; use structopt::StructOpt; +#[path = "test/mod.rs"] +#[cfg(test)] +mod cargo_fmt_tests; + #[derive(StructOpt, Debug)] #[structopt( bin_name = "cargo fmt", @@ -356,7 +360,7 @@ fn get_targets_root_only( manifest_path: Option<&Path>, targets: &mut BTreeSet, ) -> Result<(), io::Error> { - let metadata = get_cargo_metadata(manifest_path, false)?; + let metadata = get_cargo_metadata(manifest_path)?; let workspace_root_path = PathBuf::from(&metadata.workspace_root).canonicalize()?; let (in_workspace_root, current_dir_manifest) = if let Some(target_manifest) = manifest_path { ( @@ -400,34 +404,29 @@ fn get_targets_recursive( mut targets: &mut BTreeSet, visited: &mut BTreeSet, ) -> Result<(), io::Error> { - let metadata = get_cargo_metadata(manifest_path, false)?; - let metadata_with_deps = get_cargo_metadata(manifest_path, true)?; - - for package in metadata.packages { + let metadata = get_cargo_metadata(manifest_path)?; + for package in &metadata.packages { add_targets(&package.targets, &mut targets); - // Look for local dependencies. - for dependency in package.dependencies { - if dependency.source.is_some() || visited.contains(&dependency.name) { + // Look for local dependencies using information available since cargo v1.51 + // It's theoretically possible someone could use a newer version of rustfmt with + // a much older version of `cargo`, but we don't try to explicitly support that scenario. + // If someone reports an issue with path-based deps not being formatted, be sure to + // confirm their version of `cargo` (not `cargo-fmt`) is >= v1.51 + // https://github.com/rust-lang/cargo/pull/8994 + for dependency in &package.dependencies { + if dependency.path.is_none() || visited.contains(&dependency.name) { continue; } - let dependency_package = metadata_with_deps - .packages - .iter() - .find(|p| p.name == dependency.name && p.source.is_none()); - 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(); - package_manifest_path.push(&dependency.name); - package_manifest_path.push("Cargo.toml"); - package_manifest_path - }; - - if manifest_path.exists() { - visited.insert(dependency.name); + let manifest_path = PathBuf::from(dependency.path.as_ref().unwrap()).join("Cargo.toml"); + if manifest_path.exists() + && !metadata + .packages + .iter() + .any(|p| p.manifest_path.eq(&manifest_path)) + { + visited.insert(dependency.name.to_owned()); get_targets_recursive(Some(&manifest_path), &mut targets, visited)?; } } @@ -441,8 +440,7 @@ fn get_targets_with_hitlist( hitlist: &[String], targets: &mut BTreeSet, ) -> Result<(), io::Error> { - let metadata = get_cargo_metadata(manifest_path, false)?; - + let metadata = get_cargo_metadata(manifest_path)?; let mut workspace_hitlist: BTreeSet<&String> = BTreeSet::from_iter(hitlist); for package in metadata.packages { @@ -527,14 +525,9 @@ fn run_rustfmt( .unwrap_or(SUCCESS)) } -fn get_cargo_metadata( - manifest_path: Option<&Path>, - include_deps: bool, -) -> Result { +fn get_cargo_metadata(manifest_path: Option<&Path>) -> Result { let mut cmd = cargo_metadata::MetadataCommand::new(); - if !include_deps { - cmd.no_deps(); - } + cmd.no_deps(); if let Some(manifest_path) = manifest_path { cmd.manifest_path(manifest_path); } @@ -551,224 +544,3 @@ fn get_cargo_metadata( } } } - -#[cfg(test)] -mod cargo_fmt_tests { - use super::*; - - #[test] - fn default_options() { - let empty: Vec = vec![]; - let o = Opts::from_iter(&empty); - assert_eq!(false, o.quiet); - assert_eq!(false, o.verbose); - assert_eq!(false, o.version); - assert_eq!(false, o.check); - assert_eq!(empty, o.packages); - assert_eq!(empty, o.rustfmt_options); - assert_eq!(false, o.format_all); - assert_eq!(None, o.manifest_path); - assert_eq!(None, o.message_format); - } - - #[test] - fn good_options() { - let o = Opts::from_iter(&[ - "test", - "-q", - "-p", - "p1", - "-p", - "p2", - "--message-format", - "short", - "--check", - "--", - "--edition", - "2018", - ]); - assert_eq!(true, o.quiet); - assert_eq!(false, o.verbose); - assert_eq!(false, o.version); - assert_eq!(true, o.check); - assert_eq!(vec!["p1", "p2"], o.packages); - assert_eq!(vec!["--edition", "2018"], o.rustfmt_options); - assert_eq!(false, o.format_all); - assert_eq!(Some(String::from("short")), o.message_format); - } - - #[test] - fn unexpected_option() { - assert!( - Opts::clap() - .get_matches_from_safe(&["test", "unexpected"]) - .is_err() - ); - } - - #[test] - fn unexpected_flag() { - assert!( - Opts::clap() - .get_matches_from_safe(&["test", "--flag"]) - .is_err() - ); - } - - #[test] - fn mandatory_separator() { - assert!( - Opts::clap() - .get_matches_from_safe(&["test", "--emit"]) - .is_err() - ); - assert!( - !Opts::clap() - .get_matches_from_safe(&["test", "--", "--emit"]) - .is_err() - ); - } - - #[test] - fn multiple_packages_one_by_one() { - let o = Opts::from_iter(&[ - "test", - "-p", - "package1", - "--package", - "package2", - "-p", - "package3", - ]); - assert_eq!(3, o.packages.len()); - } - - #[test] - fn multiple_packages_grouped() { - let o = Opts::from_iter(&[ - "test", - "--package", - "package1", - "package2", - "-p", - "package3", - "package4", - ]); - assert_eq!(4, o.packages.len()); - } - - #[test] - fn empty_packages_1() { - assert!(Opts::clap().get_matches_from_safe(&["test", "-p"]).is_err()); - } - - #[test] - fn empty_packages_2() { - assert!( - Opts::clap() - .get_matches_from_safe(&["test", "-p", "--", "--check"]) - .is_err() - ); - } - - #[test] - fn empty_packages_3() { - assert!( - Opts::clap() - .get_matches_from_safe(&["test", "-p", "--verbose"]) - .is_err() - ); - } - - #[test] - fn empty_packages_4() { - assert!( - Opts::clap() - .get_matches_from_safe(&["test", "-p", "--check"]) - .is_err() - ); - } - - mod convert_message_format_to_rustfmt_args_tests { - use super::*; - - #[test] - fn invalid_message_format() { - assert_eq!( - convert_message_format_to_rustfmt_args("awesome", &mut vec![]), - Err(String::from( - "invalid --message-format value: awesome. Allowed values are: short|json|human" - )), - ); - } - - #[test] - fn json_message_format_and_check_arg() { - let mut args = vec![String::from("--check")]; - assert_eq!( - convert_message_format_to_rustfmt_args("json", &mut args), - Err(String::from( - "cannot include --check arg when --message-format is set to json" - )), - ); - } - - #[test] - fn json_message_format_and_emit_arg() { - let mut args = vec![String::from("--emit"), String::from("checkstyle")]; - assert_eq!( - convert_message_format_to_rustfmt_args("json", &mut args), - Err(String::from( - "cannot include --emit arg when --message-format is set to json" - )), - ); - } - - #[test] - fn json_message_format() { - let mut args = vec![String::from("--edition"), String::from("2018")]; - assert!(convert_message_format_to_rustfmt_args("json", &mut args).is_ok()); - assert_eq!( - args, - vec![ - String::from("--edition"), - String::from("2018"), - String::from("--emit"), - String::from("json") - ] - ); - } - - #[test] - fn human_message_format() { - let exp_args = vec![String::from("--emit"), String::from("json")]; - let mut act_args = exp_args.clone(); - assert!(convert_message_format_to_rustfmt_args("human", &mut act_args).is_ok()); - assert_eq!(act_args, exp_args); - } - - #[test] - fn short_message_format() { - let mut args = vec![String::from("--check")]; - assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok()); - assert_eq!(args, vec![String::from("--check"), String::from("-l")]); - } - - #[test] - fn short_message_format_included_short_list_files_flag() { - let mut args = vec![String::from("--check"), String::from("-l")]; - assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok()); - assert_eq!(args, vec![String::from("--check"), String::from("-l")]); - } - - #[test] - fn short_message_format_included_long_list_files_flag() { - let mut args = vec![String::from("--check"), String::from("--files-with-diff")]; - assert!(convert_message_format_to_rustfmt_args("short", &mut args).is_ok()); - assert_eq!( - args, - vec![String::from("--check"), String::from("--files-with-diff")] - ); - } - } -} From cb144c35e7d7151bb4b6ccd9b30a4141959166d1 Mon Sep 17 00:00:00 2001 From: Lucas Kent Date: Fri, 10 Sep 2021 17:50:40 +1000 Subject: [PATCH 64/98] In Configurations.md demonstrate both cases for noop selections --- Configurations.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/Configurations.md b/Configurations.md index b8f8f3053968f..ff83f02f87ba5 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1684,6 +1684,9 @@ pub enum Foo {} #### `false`: ```rust +#[derive(Eq, PartialEq, Debug, Copy, Clone)] +pub enum Bar {} + #[derive(Eq, PartialEq)] #[derive(Debug)] #[derive(Copy, Clone)] @@ -1857,6 +1860,9 @@ Convert `#![doc]` and `#[doc]` attributes to `//!` and `///` doc comments. #![doc = "Example documentation"] #[doc = "Example item documentation"] +pub enum Bar {} + +/// Example item documentation pub enum Foo {} ``` @@ -1971,6 +1977,8 @@ fn main() { #### `false`: ```rust fn main() { + (foo()); + ((((foo())))); } ``` @@ -1996,6 +2004,14 @@ impl Iterator for Dummy { type Item = i32; } + +impl Iterator for Dummy { + type Item = i32; + + fn next(&mut self) -> Option { + None + } +} ``` #### `true` @@ -2552,7 +2568,8 @@ fn main() { let x = 1; let y = 2; let z = 3; - let a = Foo { x: x, y: y, z: z }; + let a = Foo { x, y, z }; + let b = Foo { x: x, y: y, z: z }; } ``` @@ -2721,6 +2738,8 @@ Replace uses of the try! macro by the ? shorthand ```rust fn main() { + let lorem = ipsum.map(|dolor| dolor.sit())?; + let lorem = try!(ipsum.map(|dolor| dolor.sit())); } ``` @@ -2792,6 +2811,12 @@ Break comments to fit on the line #### `false` (default): ```rust +// Lorem ipsum dolor sit amet, consectetur adipiscing elit, +// sed do eiusmod tempor incididunt ut labore et dolore +// magna aliqua. Ut enim ad minim veniam, quis nostrud +// exercitation ullamco laboris nisi ut aliquip ex ea +// commodo consequat. + // Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` From a5138b34d5f2644d916e906a3d460856a1b1a42a Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 27 Sep 2021 16:55:23 -0400 Subject: [PATCH 65/98] Prevent removal of qualified path for tuple struct inside macro fixes 5005 This was very similar to 4964 and the fix was to extract and pass along the qself of the ``PatKind::TupleStruct`` --- src/patterns.rs | 5 +++-- tests/target/issue-5005/minimum_example.rs | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 tests/target/issue-5005/minimum_example.rs diff --git a/src/patterns.rs b/src/patterns.rs index 0c6a6f3e81436..4c6a2d5d75b94 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -226,8 +226,9 @@ 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) => { - let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?; + PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => { + let path_str = + rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)?; rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape) } PatKind::Lit(ref expr) => expr.rewrite(context, shape), diff --git a/tests/target/issue-5005/minimum_example.rs b/tests/target/issue-5005/minimum_example.rs new file mode 100644 index 0000000000000..11cc645fa5356 --- /dev/null +++ b/tests/target/issue-5005/minimum_example.rs @@ -0,0 +1,9 @@ +#![feature(more_qualified_paths)] +macro_rules! show { + ($ty:ty, $ex:expr) => { + match $ex { + <$ty>::A(_val) => println!("got a"), // formatting should not remove <$ty>:: + <$ty>::B => println!("got b"), + } + }; +} From e3203ef5e6902e0bbb7b62ebd34b3d53cb5d28b8 Mon Sep 17 00:00:00 2001 From: Ulyssa Date: Mon, 20 Sep 2021 16:29:28 -0700 Subject: [PATCH 66/98] Add tests for binop_separator = Back --- tests/source/binop-separator-back/bitwise.rs | 14 ++++++++ tests/source/binop-separator-back/comp.rs | 23 +++++++++++++ tests/source/binop-separator-back/logic.rs | 7 ++++ tests/source/binop-separator-back/math.rs | 7 ++++ tests/source/binop-separator-back/patterns.rs | 9 +++++ tests/source/binop-separator-back/range.rs | 7 ++++ tests/target/binop-separator-back/bitwise.rs | 18 ++++++++++ tests/target/binop-separator-back/comp.rs | 33 +++++++++++++++++++ tests/target/binop-separator-back/logic.rs | 10 ++++++ tests/target/binop-separator-back/math.rs | 23 +++++++++++++ tests/target/binop-separator-back/patterns.rs | 11 +++++++ tests/target/binop-separator-back/range.rs | 9 +++++ 12 files changed, 171 insertions(+) create mode 100644 tests/source/binop-separator-back/bitwise.rs create mode 100644 tests/source/binop-separator-back/comp.rs create mode 100644 tests/source/binop-separator-back/logic.rs create mode 100644 tests/source/binop-separator-back/math.rs create mode 100644 tests/source/binop-separator-back/patterns.rs create mode 100644 tests/source/binop-separator-back/range.rs create mode 100644 tests/target/binop-separator-back/bitwise.rs create mode 100644 tests/target/binop-separator-back/comp.rs create mode 100644 tests/target/binop-separator-back/logic.rs create mode 100644 tests/target/binop-separator-back/math.rs create mode 100644 tests/target/binop-separator-back/patterns.rs create mode 100644 tests/target/binop-separator-back/range.rs diff --git a/tests/source/binop-separator-back/bitwise.rs b/tests/source/binop-separator-back/bitwise.rs new file mode 100644 index 0000000000000..3804bf3215b19 --- /dev/null +++ b/tests/source/binop-separator-back/bitwise.rs @@ -0,0 +1,14 @@ +// rustfmt-binop_separator: Back + +fn main() { + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ^ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ & abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ << abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ >> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + +} diff --git a/tests/source/binop-separator-back/comp.rs b/tests/source/binop-separator-back/comp.rs new file mode 100644 index 0000000000000..50a27127445df --- /dev/null +++ b/tests/source/binop-separator-back/comp.rs @@ -0,0 +1,23 @@ +// rustfmt-binop_separator: Back + +fn main() { + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ < abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ { + // + } + + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ <= abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ { + // + } + + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ > abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ { + // + } + + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ >= abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ { + // + } + + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ == abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ { + // + } +} diff --git a/tests/source/binop-separator-back/logic.rs b/tests/source/binop-separator-back/logic.rs new file mode 100644 index 0000000000000..8c297e5a67507 --- /dev/null +++ b/tests/source/binop-separator-back/logic.rs @@ -0,0 +1,7 @@ +// rustfmt-binop_separator: Back + +fn main() { + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ && abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ || abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ { + // + } +} diff --git a/tests/source/binop-separator-back/math.rs b/tests/source/binop-separator-back/math.rs new file mode 100644 index 0000000000000..3af4aad16051e --- /dev/null +++ b/tests/source/binop-separator-back/math.rs @@ -0,0 +1,7 @@ +// rustfmt-binop_separator: Back + +fn main() { + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ * abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ - abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ / abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ * abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ * abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ / abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ / abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; +} diff --git a/tests/source/binop-separator-back/patterns.rs b/tests/source/binop-separator-back/patterns.rs new file mode 100644 index 0000000000000..a8c3b5cdd9b16 --- /dev/null +++ b/tests/source/binop-separator-back/patterns.rs @@ -0,0 +1,9 @@ +// rustfmt-binop_separator: Back + +fn main() { + match val { + ThisIsA::ReallyLongPatternNameToHelpOverflowTheNextValueOntoTheNextLine | ThisIsA::SecondValueSeparatedByAPipe | ThisIsA::ThirdValueSeparatedByAPipe => { + // + } + } +} diff --git a/tests/source/binop-separator-back/range.rs b/tests/source/binop-separator-back/range.rs new file mode 100644 index 0000000000000..bdd3de9922b09 --- /dev/null +++ b/tests/source/binop-separator-back/range.rs @@ -0,0 +1,7 @@ +// rustfmt-binop_separator: Back + +fn main() { + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ..abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ..=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; +} diff --git a/tests/target/binop-separator-back/bitwise.rs b/tests/target/binop-separator-back/bitwise.rs new file mode 100644 index 0000000000000..ce32c05ef703f --- /dev/null +++ b/tests/target/binop-separator-back/bitwise.rs @@ -0,0 +1,18 @@ +// rustfmt-binop_separator: Back + +fn main() { + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ^ + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ & + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ | + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ << + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ >> + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; +} diff --git a/tests/target/binop-separator-back/comp.rs b/tests/target/binop-separator-back/comp.rs new file mode 100644 index 0000000000000..efd837bcfe389 --- /dev/null +++ b/tests/target/binop-separator-back/comp.rs @@ -0,0 +1,33 @@ +// rustfmt-binop_separator: Back + +fn main() { + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ < + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + { + // + } + + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ <= + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + { + // + } + + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ > + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + { + // + } + + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ >= + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + { + // + } + + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ == + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + { + // + } +} diff --git a/tests/target/binop-separator-back/logic.rs b/tests/target/binop-separator-back/logic.rs new file mode 100644 index 0000000000000..5f69fd5f55e4a --- /dev/null +++ b/tests/target/binop-separator-back/logic.rs @@ -0,0 +1,10 @@ +// rustfmt-binop_separator: Back + +fn main() { + if abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ && + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ || + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + { + // + } +} diff --git a/tests/target/binop-separator-back/math.rs b/tests/target/binop-separator-back/math.rs new file mode 100644 index 0000000000000..7a3f27e733b2c --- /dev/null +++ b/tests/target/binop-separator-back/math.rs @@ -0,0 +1,23 @@ +// rustfmt-binop_separator: Back + +fn main() { + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ * + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ - + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ / + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ * + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ * + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ / + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ / + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; +} diff --git a/tests/target/binop-separator-back/patterns.rs b/tests/target/binop-separator-back/patterns.rs new file mode 100644 index 0000000000000..2e59713526a02 --- /dev/null +++ b/tests/target/binop-separator-back/patterns.rs @@ -0,0 +1,11 @@ +// rustfmt-binop_separator: Back + +fn main() { + match val { + ThisIsA::ReallyLongPatternNameToHelpOverflowTheNextValueOntoTheNextLine | + ThisIsA::SecondValueSeparatedByAPipe | + ThisIsA::ThirdValueSeparatedByAPipe => { + // + } + } +} diff --git a/tests/target/binop-separator-back/range.rs b/tests/target/binop-separator-back/range.rs new file mode 100644 index 0000000000000..19e5a81cd9cd1 --- /dev/null +++ b/tests/target/binop-separator-back/range.rs @@ -0,0 +1,9 @@ +// rustfmt-binop_separator: Back + +fn main() { + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.. + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; + + let value = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ..= + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ; +} From 041212f8fbb9f52d41167448e4fbc2ce8cc7ee9a Mon Sep 17 00:00:00 2001 From: Fabian Wolff Date: Sat, 2 Oct 2021 19:15:45 +0200 Subject: [PATCH 67/98] Report fatal lexer errors in `--cfg` command line arguments --- compiler/rustc_errors/src/emitter.rs | 21 +++++++++++++++---- compiler/rustc_interface/src/interface.rs | 5 ++++- compiler/rustc_session/src/parse.rs | 9 ++++++-- .../cfg-arg-invalid-7.rs | 5 +++++ .../cfg-arg-invalid-7.stderr | 4 ++++ 5 files changed, 37 insertions(+), 7 deletions(-) create mode 100644 src/test/ui/conditional-compilation/cfg-arg-invalid-7.rs create mode 100644 src/test/ui/conditional-compilation/cfg-arg-invalid-7.stderr diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 29f352ae58559..fa986ce8a7e12 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -15,7 +15,7 @@ use rustc_span::{MultiSpan, SourceFile, Span}; use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString}; use crate::styled_buffer::StyledBuffer; use crate::{ - CodeSuggestion, Diagnostic, DiagnosticId, Level, SubDiagnostic, SubstitutionHighlight, + CodeSuggestion, Diagnostic, DiagnosticId, Handler, Level, SubDiagnostic, SubstitutionHighlight, SuggestionStyle, }; @@ -527,14 +527,27 @@ impl Emitter for EmitterWriter { } } -/// An emitter that does nothing when emitting a diagnostic. -pub struct SilentEmitter; +/// An emitter that does nothing when emitting a non-fatal diagnostic. +/// Fatal diagnostics are forwarded to `fatal_handler` to avoid silent +/// failures of rustc, as witnessed e.g. in issue #89358. +pub struct SilentEmitter { + pub fatal_handler: Handler, + pub fatal_note: Option, +} impl Emitter for SilentEmitter { fn source_map(&self) -> Option<&Lrc> { None } - fn emit_diagnostic(&mut self, _: &Diagnostic) {} + fn emit_diagnostic(&mut self, d: &Diagnostic) { + if d.level == Level::Fatal { + let mut d = d.clone(); + if let Some(ref note) = self.fatal_note { + d.note(note); + } + self.fatal_handler.emit_diagnostic(&d); + } + } } /// Maximum number of lines we will print for a multiline suggestion; arbitrary. diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index 8393826aa1285..3233887169cd1 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -81,7 +81,10 @@ pub fn parse_cfgspecs(cfgspecs: Vec) -> FxHashSet<(String, Option Self { + pub fn with_silent_emitter(fatal_note: Option) -> Self { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let handler = Handler::with_emitter(false, None, Box::new(SilentEmitter)); + let fatal_handler = Handler::with_tty_emitter(ColorConfig::Auto, false, None, None); + let handler = Handler::with_emitter( + false, + None, + Box::new(SilentEmitter { fatal_handler, fatal_note }), + ); ParseSess::with_span_handler(handler, sm) } diff --git a/src/test/ui/conditional-compilation/cfg-arg-invalid-7.rs b/src/test/ui/conditional-compilation/cfg-arg-invalid-7.rs new file mode 100644 index 0000000000000..149142f63ae14 --- /dev/null +++ b/src/test/ui/conditional-compilation/cfg-arg-invalid-7.rs @@ -0,0 +1,5 @@ +// Regression test for issue #89358. + +// compile-flags: --cfg a" +// error-pattern: unterminated double quote string +// error-pattern: this error occurred on the command line diff --git a/src/test/ui/conditional-compilation/cfg-arg-invalid-7.stderr b/src/test/ui/conditional-compilation/cfg-arg-invalid-7.stderr new file mode 100644 index 0000000000000..919709c847019 --- /dev/null +++ b/src/test/ui/conditional-compilation/cfg-arg-invalid-7.stderr @@ -0,0 +1,4 @@ +error[E0765]: unterminated double quote string + | + = note: this error occurred on the command line: `--cfg=a"` + From f0f449d6edda5a40057fc82ea02cc9abeae4d012 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Fri, 17 Sep 2021 18:56:30 -0700 Subject: [PATCH 68/98] Wrap long array and slice patterns. Closes #4530. --- src/overflow.rs | 4 +++- src/patterns.rs | 12 +++++++++++- tests/source/issue-4530.rs | 4 ++++ tests/target/issue-4530.rs | 9 +++++++++ 4 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 tests/source/issue-4530.rs create mode 100644 tests/target/issue-4530.rs diff --git a/src/overflow.rs b/src/overflow.rs index e32213467a51f..ac24181c78052 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -77,6 +77,7 @@ pub(crate) enum OverflowableItem<'a> { FieldDef(&'a ast::FieldDef), TuplePatField(&'a TuplePatField<'a>), Ty(&'a ast::Ty), + Pat(&'a ast::Pat), } impl<'a> Rewrite for OverflowableItem<'a> { @@ -116,6 +117,7 @@ impl<'a> OverflowableItem<'a> { OverflowableItem::FieldDef(sf) => f(*sf), OverflowableItem::TuplePatField(pat) => f(*pat), OverflowableItem::Ty(ty) => f(*ty), + OverflowableItem::Pat(pat) => f(*pat), } } @@ -232,7 +234,7 @@ macro_rules! impl_into_overflowable_item_for_rustfmt_types { } } -impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, NestedMetaItem, FieldDef, Ty); +impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, NestedMetaItem, FieldDef, Ty, Pat); impl_into_overflowable_item_for_rustfmt_types!([MacroArg], [SegmentParam, TuplePatField]); pub(crate) fn into_overflowable_list<'a, T>( diff --git a/src/patterns.rs b/src/patterns.rs index 4c6a2d5d75b94..34987b1d59e4b 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -4,6 +4,7 @@ use rustc_span::{BytePos, Span}; use crate::comment::{combine_strs_with_missing_comments, FindUncommented}; use crate::config::lists::*; +use crate::config::Version; use crate::expr::{can_be_overflowed_expr, rewrite_unary_prefix, wrap_struct_field}; use crate::lists::{ definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape, @@ -232,7 +233,7 @@ impl Rewrite for Pat { rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape) } PatKind::Lit(ref expr) => expr.rewrite(context, shape), - PatKind::Slice(ref slice_pat) => { + PatKind::Slice(ref slice_pat) if context.config.version() == Version::One => { let rw: Vec = slice_pat .iter() .map(|p| { @@ -245,6 +246,15 @@ impl Rewrite for Pat { .collect(); Some(format!("[{}]", rw.join(", "))) } + PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets( + context, + "", + slice_pat.iter(), + shape, + self.span, + None, + None, + ), PatKind::Struct(ref qself, ref path, ref fields, ellipsis) => { rewrite_struct_pat(qself, path, fields, ellipsis, self.span, context, shape) } diff --git a/tests/source/issue-4530.rs b/tests/source/issue-4530.rs new file mode 100644 index 0000000000000..9d2882abb3c1c --- /dev/null +++ b/tests/source/issue-4530.rs @@ -0,0 +1,4 @@ +// rustfmt-version: Two +fn main() { + let [aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, cccccccccccccccccccccccccc, ddddddddddddddddddddddddd] = panic!(); +} diff --git a/tests/target/issue-4530.rs b/tests/target/issue-4530.rs new file mode 100644 index 0000000000000..296dc559a9343 --- /dev/null +++ b/tests/target/issue-4530.rs @@ -0,0 +1,9 @@ +// rustfmt-version: Two +fn main() { + let [ + aaaaaaaaaaaaaaaaaaaaaaaaaa, + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, + cccccccccccccccccccccccccc, + ddddddddddddddddddddddddd, + ] = panic!(); +} From 0866b9627c50a6439e7c40340b10e7d173189534 Mon Sep 17 00:00:00 2001 From: Jane Lusby Date: Tue, 5 Oct 2021 15:33:33 -0700 Subject: [PATCH 69/98] Apply suggestions from code review --- library/std/src/os/unix/process.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/library/std/src/os/unix/process.rs b/library/std/src/os/unix/process.rs index 206425fc6e9d1..c3d9f3030093a 100644 --- a/library/std/src/os/unix/process.rs +++ b/library/std/src/os/unix/process.rs @@ -237,27 +237,27 @@ pub trait ExitStatusExt: Sealed { fn signal(&self) -> Option; /// If the process was terminated by a signal, says whether it dumped core. - #[stable(feature = "unix_process_wait_more", since = "1.56.0")] + #[stable(feature = "unix_process_wait_more", since = "1.57.0")] fn core_dumped(&self) -> bool; /// If the process was stopped by a signal, returns that signal. /// /// In other words, if `WIFSTOPPED`, this returns `WSTOPSIG`. This is only possible if the status came from /// a `wait` system call which was passed `WUNTRACED`, and was then converted into an `ExitStatus`. - #[stable(feature = "unix_process_wait_more", since = "1.56.0")] + #[stable(feature = "unix_process_wait_more", since = "1.57.0")] fn stopped_signal(&self) -> Option; /// Whether the process was continued from a stopped status. /// /// Ie, `WIFCONTINUED`. This is only possible if the status came from a `wait` system call /// which was passed `WCONTINUED`, and was then converted into an `ExitStatus`. - #[stable(feature = "unix_process_wait_more", since = "1.56.0")] + #[stable(feature = "unix_process_wait_more", since = "1.57.0")] fn continued(&self) -> bool; /// Returns the underlying raw `wait` status. /// /// The returned integer is a **wait status, not an exit status**. - #[stable(feature = "unix_process_wait_more", since = "1.56.0")] + #[stable(feature = "unix_process_wait_more", since = "1.57.0")] fn into_raw(self) -> i32; } From 40f4993c67ff54e413da17496769407ab85f3924 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Thu, 23 Sep 2021 22:43:03 -0400 Subject: [PATCH 70/98] Update derive attibute span to start after opening '(' Fixes 4984 When parsing derive attributes we're only concerned about the traits and comments listed between the opening and closing parentheses. Derive attribute spans currently start at the '#'. Span starts here | v #[derive(...)] After this update the derive spans start after the opening '('. Span starts here | V #[derive(...)] --- src/attr.rs | 5 +++- tests/source/issue-4984/minimum_example.rs | 2 ++ tests/source/issue-4984/multi_line_derive.rs | 20 +++++++++++++++ tests/target/issue-4984/minimum_example.rs | 2 ++ tests/target/issue-4984/multi_line_derive.rs | 26 ++++++++++++++++++++ 5 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 tests/source/issue-4984/minimum_example.rs create mode 100644 tests/source/issue-4984/multi_line_derive.rs create mode 100644 tests/target/issue-4984/minimum_example.rs create mode 100644 tests/target/issue-4984/multi_line_derive.rs diff --git a/src/attr.rs b/src/attr.rs index 315eb10a9dbc0..a5982820e3ded 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -13,6 +13,7 @@ use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, use crate::overflow; use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::Shape; +use crate::source_map::SpanUtils; use crate::types::{rewrite_path, PathContext}; use crate::utils::{count_newlines, mk_sp}; @@ -116,7 +117,9 @@ fn format_derive( |span| span.lo(), |span| span.hi(), |span| Some(context.snippet(*span).to_owned()), - attr.span.lo(), + // We update derive attribute spans to start after the opening '(' + // This helps us focus parsing to just what's inside #[derive(...)] + context.snippet_provider.span_after(attr.span, "("), attr.span.hi(), false, ); diff --git a/tests/source/issue-4984/minimum_example.rs b/tests/source/issue-4984/minimum_example.rs new file mode 100644 index 0000000000000..677f873771691 --- /dev/null +++ b/tests/source/issue-4984/minimum_example.rs @@ -0,0 +1,2 @@ +#[derive(/*Debug, */Clone)] +struct Foo; diff --git a/tests/source/issue-4984/multi_line_derive.rs b/tests/source/issue-4984/multi_line_derive.rs new file mode 100644 index 0000000000000..73921dd173547 --- /dev/null +++ b/tests/source/issue-4984/multi_line_derive.rs @@ -0,0 +1,20 @@ +#[derive( +/* ---------- Some really important comment that just had to go inside the derive --------- */ +Debug, Clone, Eq, PartialEq, +)] +struct Foo { + a: i32, + b: T, +} + +#[derive( +/* + Some really important comment that just had to go inside the derive. + Also had to be put over multiple lines +*/ +Debug, Clone, Eq, PartialEq, +)] +struct Bar { + a: i32, + b: T, +} diff --git a/tests/target/issue-4984/minimum_example.rs b/tests/target/issue-4984/minimum_example.rs new file mode 100644 index 0000000000000..f0599c5d694b2 --- /dev/null +++ b/tests/target/issue-4984/minimum_example.rs @@ -0,0 +1,2 @@ +#[derive(/*Debug, */ Clone)] +struct Foo; diff --git a/tests/target/issue-4984/multi_line_derive.rs b/tests/target/issue-4984/multi_line_derive.rs new file mode 100644 index 0000000000000..5fbd9784adc97 --- /dev/null +++ b/tests/target/issue-4984/multi_line_derive.rs @@ -0,0 +1,26 @@ +#[derive( + /* ---------- Some really important comment that just had to go inside the derive --------- */ + Debug, + Clone, + Eq, + PartialEq, +)] +struct Foo { + a: i32, + b: T, +} + +#[derive( + /* + Some really important comment that just had to go inside the derive. + Also had to be put over multiple lines + */ + Debug, + Clone, + Eq, + PartialEq, +)] +struct Bar { + a: i32, + b: T, +} From 365a2f8f6e710f67d6485fe9004bb3f64da977bc Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Wed, 29 Sep 2021 14:18:54 -0400 Subject: [PATCH 71/98] Add additional test cases for issue 4984 --- tests/source/issue-4984/multiple_comments_within.rs | 8 ++++++++ tests/target/issue-4984/multiple_comments_within.rs | 11 +++++++++++ tests/target/issue-4984/should_not_change.rs | 5 +++++ 3 files changed, 24 insertions(+) create mode 100644 tests/source/issue-4984/multiple_comments_within.rs create mode 100644 tests/target/issue-4984/multiple_comments_within.rs create mode 100644 tests/target/issue-4984/should_not_change.rs diff --git a/tests/source/issue-4984/multiple_comments_within.rs b/tests/source/issue-4984/multiple_comments_within.rs new file mode 100644 index 0000000000000..eb474a723d016 --- /dev/null +++ b/tests/source/issue-4984/multiple_comments_within.rs @@ -0,0 +1,8 @@ +#[derive( +/* ---------- Some really important comment that just had to go inside the derive --------- */ +Debug, Clone,/* Another comment */Eq, PartialEq, +)] +struct Foo { + a: i32, + b: T, +} diff --git a/tests/target/issue-4984/multiple_comments_within.rs b/tests/target/issue-4984/multiple_comments_within.rs new file mode 100644 index 0000000000000..d2924f0d0f2e2 --- /dev/null +++ b/tests/target/issue-4984/multiple_comments_within.rs @@ -0,0 +1,11 @@ +#[derive( + /* ---------- Some really important comment that just had to go inside the derive --------- */ + Debug, + Clone, + /* Another comment */ Eq, + PartialEq, +)] +struct Foo { + a: i32, + b: T, +} diff --git a/tests/target/issue-4984/should_not_change.rs b/tests/target/issue-4984/should_not_change.rs new file mode 100644 index 0000000000000..e46ee511084fe --- /dev/null +++ b/tests/target/issue-4984/should_not_change.rs @@ -0,0 +1,5 @@ +#[derive(Clone, Debug, Eq, PartialEq)] +struct Foo; + +#[derive(Clone)] +struct Bar; From 8b58cce673d6ae4fbc1f3a8d28859bc100a72ed8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Sat, 16 May 2020 22:20:51 +0200 Subject: [PATCH 72/98] Stabilize match_block_trailing_comma. (#4145) Servo has used this since forever, and it'd be useful to be able to use rustfmt stable there so that we can use the same rustfmt version in both Firefox and Servo. Feel free to close this if there's any reason it shouldn't be done. --- Configurations.md | 2 +- src/config/mod.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Configurations.md b/Configurations.md index ff83f02f87ba5..06db897a42e7e 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1626,7 +1626,7 @@ Put a trailing comma after a block based match arm (non-block arms are not affec - **Default value**: `false` - **Possible values**: `true`, `false` -- **Stable**: No (tracking issue: #3380) +- **Stable**: Yes #### `false` (default): diff --git a/src/config/mod.rs b/src/config/mod.rs index c6cee8ed22734..398a1814d8d1d 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -127,7 +127,7 @@ create_config! { "Add trailing semicolon after break, continue and return"; trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false, "How to handle trailing commas for lists"; - match_block_trailing_comma: bool, false, false, + match_block_trailing_comma: bool, false, true, "Put a trailing comma after a block based match arm (non-block arms are not affected)"; blank_lines_upper_bound: usize, 1, false, "Maximum number of blank lines which can be put between items"; From d41805704d4a07ac77e0bc59ea5c91cdb69dea26 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 11 Oct 2021 18:30:35 -0400 Subject: [PATCH 73/98] Prevent structs with ".." from being rewritten with alignment rustfmt should only support rewriting a struct in an expression position with alignment (non-default behavior) when there is no rest (with or without a base) and all of the fields are non-shorthand. --- src/expr.rs | 11 ++-- .../source/issue-4926/deeply_nested_struct.rs | 35 ++++++++++++ ...ply_nested_struct_with_long_field_names.rs | 43 +++++++++++++++ .../deeply_nested_struct_with_many_fields.rs | 44 +++++++++++++++ tests/source/issue-4926/enum_struct_field.rs | 35 ++++++++++++ tests/source/issue-4926/minimum_example.rs | 10 ++++ .../struct_with_long_field_names.rs | 21 ++++++++ .../issue-4926/struct_with_many_fields.rs | 21 ++++++++ .../target/issue-4926/deeply_nested_struct.rs | 38 +++++++++++++ ...ply_nested_struct_with_long_field_names.rs | 44 +++++++++++++++ .../deeply_nested_struct_with_many_fields.rs | 54 +++++++++++++++++++ tests/target/issue-4926/enum_struct_field.rs | 41 ++++++++++++++ tests/target/issue-4926/minimum_example.rs | 10 ++++ .../struct_with_long_field_names.rs | 24 +++++++++ .../issue-4926/struct_with_many_fields.rs | 34 ++++++++++++ 15 files changed, 458 insertions(+), 7 deletions(-) create mode 100644 tests/source/issue-4926/deeply_nested_struct.rs create mode 100644 tests/source/issue-4926/deeply_nested_struct_with_long_field_names.rs create mode 100644 tests/source/issue-4926/deeply_nested_struct_with_many_fields.rs create mode 100644 tests/source/issue-4926/enum_struct_field.rs create mode 100644 tests/source/issue-4926/minimum_example.rs create mode 100644 tests/source/issue-4926/struct_with_long_field_names.rs create mode 100644 tests/source/issue-4926/struct_with_many_fields.rs create mode 100644 tests/target/issue-4926/deeply_nested_struct.rs create mode 100644 tests/target/issue-4926/deeply_nested_struct_with_long_field_names.rs create mode 100644 tests/target/issue-4926/deeply_nested_struct_with_many_fields.rs create mode 100644 tests/target/issue-4926/enum_struct_field.rs create mode 100644 tests/target/issue-4926/minimum_example.rs create mode 100644 tests/target/issue-4926/struct_with_long_field_names.rs create mode 100644 tests/target/issue-4926/struct_with_many_fields.rs diff --git a/src/expr.rs b/src/expr.rs index 01cc388c186ef..3a54426b0ddbe 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1528,12 +1528,12 @@ fn rewrite_struct_lit<'a>( let path_shape = shape.sub_width(2)?; let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?; - let has_base = match struct_rest { + let has_base_or_rest = match struct_rest { ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)), ast::StructRest::Rest(_) if fields.is_empty() => { return Some(format!("{} {{ .. }}", path_str)); } - ast::StructRest::Base(_) => true, + ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true, _ => false, }; @@ -1542,7 +1542,7 @@ fn rewrite_struct_lit<'a>( let one_line_width = h_shape.map_or(0, |shape| shape.width); let body_lo = context.snippet_provider.span_after(span, "{"); - let fields_str = if struct_lit_can_be_aligned(fields, has_base) + let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest) && context.config.struct_field_align_threshold() > 0 { rewrite_with_alignment( @@ -1614,10 +1614,7 @@ fn rewrite_struct_lit<'a>( nested_shape, tactic, context, - force_no_trailing_comma - || has_base - || !context.use_block_indent() - || matches!(struct_rest, ast::StructRest::Rest(_)), + force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(), ); write_list(&item_vec, &fmt)? diff --git a/tests/source/issue-4926/deeply_nested_struct.rs b/tests/source/issue-4926/deeply_nested_struct.rs new file mode 100644 index 0000000000000..e55e41bd1a58a --- /dev/null +++ b/tests/source/issue-4926/deeply_nested_struct.rs @@ -0,0 +1,35 @@ + +// rustfmt-struct_field_align_threshold: 30 + +struct X { + a: i32, + b: i32, + c: i32, +} + +fn test(x: X) { + let d = { + let e = { + let f = { + let g = { + let h = { + let i = { + let j = { + matches!( + x, + X { a: 1_000, b: 1_000, .. } + ) + }; + j + }; + i + }; + h + }; + g + }; + f + }; + e + }; +} \ No newline at end of file diff --git a/tests/source/issue-4926/deeply_nested_struct_with_long_field_names.rs b/tests/source/issue-4926/deeply_nested_struct_with_long_field_names.rs new file mode 100644 index 0000000000000..516699fa2b8bc --- /dev/null +++ b/tests/source/issue-4926/deeply_nested_struct_with_long_field_names.rs @@ -0,0 +1,43 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + really_really_long_field_a: i32, + really_really_really_long_field_b: i32, + really_really_really_really_long_field_c: i32, + really_really_really_really_really_long_field_d: i32, + really_really_really_really_really_really_long_field_e: i32, + f: i32, +} + +fn test(x: X) { + let d = { + let e = { + let f = { + let g = { + let h = { + let i = { + let j = { + matches!( + x, + X { + really_really_long_field_a: 10, + really_really_really_long_field_b: 10, + really_really_really_really_long_field_c: 10, + really_really_really_really_really_long_field_d: 10, + really_really_really_really_really_really_long_field_e: 10, .. + } + ) + }; + j + }; + i + }; + h + }; + g + }; + f + }; + e + }; +} diff --git a/tests/source/issue-4926/deeply_nested_struct_with_many_fields.rs b/tests/source/issue-4926/deeply_nested_struct_with_many_fields.rs new file mode 100644 index 0000000000000..38fd6f02cf069 --- /dev/null +++ b/tests/source/issue-4926/deeply_nested_struct_with_many_fields.rs @@ -0,0 +1,44 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + a: i32, + b: i32, + c: i32, + d: i32, + e: i32, + f: i32, + g: i32, + h: i32, + i: i32, + j: i32, + k: i32, +} + +fn test(x: X) { + let d = { + let e = { + let f = { + let g = { + let h = { + let i = { + let j = { + matches!( + x, + X { + a: 1_000, b: 1_000, c: 1_000, d: 1_000, e: 1_000, f: 1_000, g: 1_000, h: 1_000, i: 1_000, j: 1_000, .. + } + ) + }; + j + }; + i + }; + h + }; + g + }; + f + }; + e + }; +} diff --git a/tests/source/issue-4926/enum_struct_field.rs b/tests/source/issue-4926/enum_struct_field.rs new file mode 100644 index 0000000000000..336378537df38 --- /dev/null +++ b/tests/source/issue-4926/enum_struct_field.rs @@ -0,0 +1,35 @@ +// rustfmt-struct_field_align_threshold: 30 +// rustfmt-enum_discrim_align_threshold: 30 +// rustfmt-imports_layout: HorizontalVertical + +#[derive(Default)] +struct InnerStructA { bbbbbbbbb: i32, cccccccc: i32 } + +enum SomeEnumNamedD { + E(InnerStructA), + F { + ggggggggggggggggggggggggg: bool, + h: bool, + } +} + +impl SomeEnumNamedD { + fn f_variant() -> Self { + Self::F { ggggggggggggggggggggggggg: true, h: true } + } +} + +fn main() { + let kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk = SomeEnumNamedD::f_variant(); + let something_we_care_about = matches!( + kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk, + SomeEnumNamedD::F { + ggggggggggggggggggggggggg: true, + .. + } + ); + + if something_we_care_about { + println!("Yup it happened"); + } +} diff --git a/tests/source/issue-4926/minimum_example.rs b/tests/source/issue-4926/minimum_example.rs new file mode 100644 index 0000000000000..2c3045dea489e --- /dev/null +++ b/tests/source/issue-4926/minimum_example.rs @@ -0,0 +1,10 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { a: i32, b: i32 } + +fn test(x: X) { + let y = matches!(x, X { + a: 1, + .. + }); +} diff --git a/tests/source/issue-4926/struct_with_long_field_names.rs b/tests/source/issue-4926/struct_with_long_field_names.rs new file mode 100644 index 0000000000000..b8a37f0714ee6 --- /dev/null +++ b/tests/source/issue-4926/struct_with_long_field_names.rs @@ -0,0 +1,21 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + really_really_long_field_a: i32, + really_really_really_long_field_b: i32, + really_really_really_really_long_field_c: i32, + really_really_really_really_really_long_field_d: i32, + really_really_really_really_really_really_long_field_e: i32, + f: i32, +} + +fn test(x: X) { + let y = matches!(x, X { + really_really_long_field_a: 10, + really_really_really_long_field_b: 10, + really_really_really_really_long_field_c: 10, + really_really_really_really_really_long_field_d: 10, + really_really_really_really_really_really_long_field_e: 10, + .. + }); +} diff --git a/tests/source/issue-4926/struct_with_many_fields.rs b/tests/source/issue-4926/struct_with_many_fields.rs new file mode 100644 index 0000000000000..4adfd3b306296 --- /dev/null +++ b/tests/source/issue-4926/struct_with_many_fields.rs @@ -0,0 +1,21 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + a: i32, + b: i32, + c: i32, + d: i32, + e: i32, + f: i32, + g: i32, + h: i32, + i: i32, + j: i32, + k: i32, +} + +fn test(x: X) { + let y = matches!(x, X { + a: 1_000, b: 1_000, c: 1_000, d: 1_000, e: 1_000, f: 1_000, g: 1_000, h: 1_000, i: 1_000, j: 1_000, .. + }); +} \ No newline at end of file diff --git a/tests/target/issue-4926/deeply_nested_struct.rs b/tests/target/issue-4926/deeply_nested_struct.rs new file mode 100644 index 0000000000000..072cf2f6674a1 --- /dev/null +++ b/tests/target/issue-4926/deeply_nested_struct.rs @@ -0,0 +1,38 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + a: i32, + b: i32, + c: i32, +} + +fn test(x: X) { + let d = { + let e = { + let f = { + let g = { + let h = { + let i = { + let j = { + matches!( + x, + X { + a: 1_000, + b: 1_000, + .. + } + ) + }; + j + }; + i + }; + h + }; + g + }; + f + }; + e + }; +} diff --git a/tests/target/issue-4926/deeply_nested_struct_with_long_field_names.rs b/tests/target/issue-4926/deeply_nested_struct_with_long_field_names.rs new file mode 100644 index 0000000000000..c7bc7f7296d6b --- /dev/null +++ b/tests/target/issue-4926/deeply_nested_struct_with_long_field_names.rs @@ -0,0 +1,44 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + really_really_long_field_a: i32, + really_really_really_long_field_b: i32, + really_really_really_really_long_field_c: i32, + really_really_really_really_really_long_field_d: i32, + really_really_really_really_really_really_long_field_e: i32, + f: i32, +} + +fn test(x: X) { + let d = { + let e = { + let f = { + let g = { + let h = { + let i = { + let j = { + matches!( + x, + X { + really_really_long_field_a: 10, + really_really_really_long_field_b: 10, + really_really_really_really_long_field_c: 10, + really_really_really_really_really_long_field_d: 10, + really_really_really_really_really_really_long_field_e: 10, + .. + } + ) + }; + j + }; + i + }; + h + }; + g + }; + f + }; + e + }; +} diff --git a/tests/target/issue-4926/deeply_nested_struct_with_many_fields.rs b/tests/target/issue-4926/deeply_nested_struct_with_many_fields.rs new file mode 100644 index 0000000000000..69793162519a7 --- /dev/null +++ b/tests/target/issue-4926/deeply_nested_struct_with_many_fields.rs @@ -0,0 +1,54 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + a: i32, + b: i32, + c: i32, + d: i32, + e: i32, + f: i32, + g: i32, + h: i32, + i: i32, + j: i32, + k: i32, +} + +fn test(x: X) { + let d = { + let e = { + let f = { + let g = { + let h = { + let i = { + let j = { + matches!( + x, + X { + a: 1_000, + b: 1_000, + c: 1_000, + d: 1_000, + e: 1_000, + f: 1_000, + g: 1_000, + h: 1_000, + i: 1_000, + j: 1_000, + .. + } + ) + }; + j + }; + i + }; + h + }; + g + }; + f + }; + e + }; +} diff --git a/tests/target/issue-4926/enum_struct_field.rs b/tests/target/issue-4926/enum_struct_field.rs new file mode 100644 index 0000000000000..2471df84653c9 --- /dev/null +++ b/tests/target/issue-4926/enum_struct_field.rs @@ -0,0 +1,41 @@ +// rustfmt-struct_field_align_threshold: 30 +// rustfmt-enum_discrim_align_threshold: 30 +// rustfmt-imports_layout: HorizontalVertical + +#[derive(Default)] +struct InnerStructA { + bbbbbbbbb: i32, + cccccccc: i32, +} + +enum SomeEnumNamedD { + E(InnerStructA), + F { + ggggggggggggggggggggggggg: bool, + h: bool, + }, +} + +impl SomeEnumNamedD { + fn f_variant() -> Self { + Self::F { + ggggggggggggggggggggggggg: true, + h: true, + } + } +} + +fn main() { + let kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk = SomeEnumNamedD::f_variant(); + let something_we_care_about = matches!( + kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk, + SomeEnumNamedD::F { + ggggggggggggggggggggggggg: true, + .. + } + ); + + if something_we_care_about { + println!("Yup it happened"); + } +} diff --git a/tests/target/issue-4926/minimum_example.rs b/tests/target/issue-4926/minimum_example.rs new file mode 100644 index 0000000000000..06e18427465c9 --- /dev/null +++ b/tests/target/issue-4926/minimum_example.rs @@ -0,0 +1,10 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + a: i32, + b: i32, +} + +fn test(x: X) { + let y = matches!(x, X { a: 1, .. }); +} diff --git a/tests/target/issue-4926/struct_with_long_field_names.rs b/tests/target/issue-4926/struct_with_long_field_names.rs new file mode 100644 index 0000000000000..ac4674ab5d520 --- /dev/null +++ b/tests/target/issue-4926/struct_with_long_field_names.rs @@ -0,0 +1,24 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + really_really_long_field_a: i32, + really_really_really_long_field_b: i32, + really_really_really_really_long_field_c: i32, + really_really_really_really_really_long_field_d: i32, + really_really_really_really_really_really_long_field_e: i32, + f: i32, +} + +fn test(x: X) { + let y = matches!( + x, + X { + really_really_long_field_a: 10, + really_really_really_long_field_b: 10, + really_really_really_really_long_field_c: 10, + really_really_really_really_really_long_field_d: 10, + really_really_really_really_really_really_long_field_e: 10, + .. + } + ); +} diff --git a/tests/target/issue-4926/struct_with_many_fields.rs b/tests/target/issue-4926/struct_with_many_fields.rs new file mode 100644 index 0000000000000..96dfe14bf7dd1 --- /dev/null +++ b/tests/target/issue-4926/struct_with_many_fields.rs @@ -0,0 +1,34 @@ +// rustfmt-struct_field_align_threshold: 30 + +struct X { + a: i32, + b: i32, + c: i32, + d: i32, + e: i32, + f: i32, + g: i32, + h: i32, + i: i32, + j: i32, + k: i32, +} + +fn test(x: X) { + let y = matches!( + x, + X { + a: 1_000, + b: 1_000, + c: 1_000, + d: 1_000, + e: 1_000, + f: 1_000, + g: 1_000, + h: 1_000, + i: 1_000, + j: 1_000, + .. + } + ); +} From f7c4a44149b4e3a683f5506929050f2b50117328 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 5 Oct 2021 01:24:10 -0400 Subject: [PATCH 74/98] Adjust non-empty tuple struct span to start before fields Resolves 5011 Tuple structs with visibility modifiers and comments before the first field were incorrectly formatted. Comments would duplicate part of the visibility modifier and struct name. When trying to parse the tuple fields the ``items::Context`` searches for the opening '(', but because the visibility modifier introduces another '(' -- for example ``pub(crate)`` -- the parsing gets messed up. Now the span is adjusted to start after the struct identifier, or after any generics. Adjusting the span in this way ensures that the ``items::Contex`` will correctly find the tuple fields. --- src/items.rs | 7 ++++++- tests/source/issue-5011.rs | 12 ++++++++++++ tests/target/issue-5011.rs | 8 ++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 tests/source/issue-5011.rs create mode 100644 tests/target/issue-5011.rs diff --git a/src/items.rs b/src/items.rs index e8eb1c5dfbb55..471a365e4706d 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1469,12 +1469,17 @@ fn format_tuple_struct( format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")"); } else { let shape = Shape::indented(offset, context.config).sub_width(1)?; + let lo = if let Some(generics) = struct_parts.generics { + generics.span.hi() + } else { + struct_parts.ident.span.hi() + }; result = overflow::rewrite_with_parens( context, &result, fields.iter(), shape, - span, + mk_sp(lo, span.hi()), context.config.fn_call_width(), None, )?; diff --git a/tests/source/issue-5011.rs b/tests/source/issue-5011.rs new file mode 100644 index 0000000000000..b48292164e43a --- /dev/null +++ b/tests/source/issue-5011.rs @@ -0,0 +1,12 @@ +pub(crate) struct ASlash( + // hello + i32 +); + +pub(crate) struct AStar( + /* hello */ + i32 +); + +pub(crate) struct BStar(/* hello */ i32); + diff --git a/tests/target/issue-5011.rs b/tests/target/issue-5011.rs new file mode 100644 index 0000000000000..9ad4a1929bdbf --- /dev/null +++ b/tests/target/issue-5011.rs @@ -0,0 +1,8 @@ +pub(crate) struct ASlash( + // hello + i32, +); + +pub(crate) struct AStar(/* hello */ i32); + +pub(crate) struct BStar(/* hello */ i32); From f2fb3c9659e072d7df6315906f1adbd06c3bc9e3 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Wed, 6 Oct 2021 13:09:24 -0400 Subject: [PATCH 75/98] Update connector search in ControlFlow::rewrite_pat_expr for for loops Resolves 5009 For loops represented by a ControlFlow object use " in" as their connector. rustfmt searches for the first uncommented occurrence of the word "in" within the current span and adjusts it's starting point to look for comments right after that. visually this looks like this: rustfmt starts looking for comments here | V for x in /* ... */ 0..1 {} This works well in most cases, however when the pattern also contains the word "in", this leads to issues. rustfmt starts looking for comments here | V for in_here in /* ... */ 0..1 {} ------- pattern In order to correctly identify the connector, the new approach first updates the span to start after the pattern and then searches for the first uncommented occurrence of "in". --- src/expr.rs | 2 +- tests/target/issue-5009/1_minimum_example.rs | 4 +++ .../2_many_in_connectors_in_pattern.rs | 3 ++ ...sted_for_loop_with_connector_in_pattern.rs | 5 +++ .../4_nested_for_loop_with_if_elseif_else.rs | 13 ++++++++ ...r_loop_with_connector_in_if_elseif_else.rs | 15 +++++++++ ...sted_for_loop_with_connector_in_pattern.rs | 32 +++++++++++++++++++ 7 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 tests/target/issue-5009/1_minimum_example.rs create mode 100644 tests/target/issue-5009/2_many_in_connectors_in_pattern.rs create mode 100644 tests/target/issue-5009/3_nested_for_loop_with_connector_in_pattern.rs create mode 100644 tests/target/issue-5009/4_nested_for_loop_with_if_elseif_else.rs create mode 100644 tests/target/issue-5009/5_nested_for_loop_with_connector_in_if_elseif_else.rs create mode 100644 tests/target/issue-5009/6_deeply_nested_for_loop_with_connector_in_pattern.rs diff --git a/src/expr.rs b/src/expr.rs index 3a54426b0ddbe..f40f80e425322 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -822,7 +822,7 @@ impl<'a> ControlFlow<'a> { let pat_string = pat.rewrite(context, pat_shape)?; let comments_lo = context .snippet_provider - .span_after(self.span, self.connector.trim()); + .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim()); let comments_span = mk_sp(comments_lo, expr.span.lo()); return rewrite_assign_rhs_with_comments( context, diff --git a/tests/target/issue-5009/1_minimum_example.rs b/tests/target/issue-5009/1_minimum_example.rs new file mode 100644 index 0000000000000..55836f4bf52c7 --- /dev/null +++ b/tests/target/issue-5009/1_minimum_example.rs @@ -0,0 +1,4 @@ +fn main() { + // the "in" inside the pattern produced invalid syntax + for variable_in_here /* ... */ in 0..1 {} +} diff --git a/tests/target/issue-5009/2_many_in_connectors_in_pattern.rs b/tests/target/issue-5009/2_many_in_connectors_in_pattern.rs new file mode 100644 index 0000000000000..d83590c6852fb --- /dev/null +++ b/tests/target/issue-5009/2_many_in_connectors_in_pattern.rs @@ -0,0 +1,3 @@ +fn main() { + for in_in_in_in_in_in_in_in /* ... */ in 0..1 {} +} diff --git a/tests/target/issue-5009/3_nested_for_loop_with_connector_in_pattern.rs b/tests/target/issue-5009/3_nested_for_loop_with_connector_in_pattern.rs new file mode 100644 index 0000000000000..9c800723939bd --- /dev/null +++ b/tests/target/issue-5009/3_nested_for_loop_with_connector_in_pattern.rs @@ -0,0 +1,5 @@ +fn main() { + for variable_in_x /* ... */ in 0..1 { + for variable_in_y /* ... */ in 0..1 {} + } +} diff --git a/tests/target/issue-5009/4_nested_for_loop_with_if_elseif_else.rs b/tests/target/issue-5009/4_nested_for_loop_with_if_elseif_else.rs new file mode 100644 index 0000000000000..a716d0d3082a5 --- /dev/null +++ b/tests/target/issue-5009/4_nested_for_loop_with_if_elseif_else.rs @@ -0,0 +1,13 @@ +fn main() { + for variable_in_x /* ... */ in 0..1 { + for variable_in_y /* ... */ in 0..1 { + if false { + + } else if false { + + } else { + + } + } + } +} diff --git a/tests/target/issue-5009/5_nested_for_loop_with_connector_in_if_elseif_else.rs b/tests/target/issue-5009/5_nested_for_loop_with_connector_in_if_elseif_else.rs new file mode 100644 index 0000000000000..41ea46d4cb9b8 --- /dev/null +++ b/tests/target/issue-5009/5_nested_for_loop_with_connector_in_if_elseif_else.rs @@ -0,0 +1,15 @@ +fn main() { + let in_ = false; + + for variable_in_x /* ... */ in 0..1 { + for variable_in_y /* ... */ in 0..1 { + if in_ { + + } else if in_ { + + } else { + + } + } + } +} diff --git a/tests/target/issue-5009/6_deeply_nested_for_loop_with_connector_in_pattern.rs b/tests/target/issue-5009/6_deeply_nested_for_loop_with_connector_in_pattern.rs new file mode 100644 index 0000000000000..789e54f7e5fb5 --- /dev/null +++ b/tests/target/issue-5009/6_deeply_nested_for_loop_with_connector_in_pattern.rs @@ -0,0 +1,32 @@ +fn main() { + for variable_in_a /* ... */ in 0..1 { + for variable_in_b /* ... */ in 0..1 { + for variable_in_c /* ... */ in 0..1 { + for variable_in_d /* ... */ in 0..1 { + for variable_in_e /* ... */ in 0..1 { + for variable_in_f /* ... */ in 0..1 { + for variable_in_g /* ... */ in 0..1 { + for variable_in_h /* ... */ in 0..1 { + for variable_in_i /* ... */ in 0..1 { + for variable_in_j /* ... */ in 0..1 { + for variable_in_k /* ... */ in 0..1 { + for variable_in_l /* ... */ in 0..1 { + for variable_in_m /* ... */ in 0..1 { + for variable_in_n /* ... */ in 0..1 { + for variable_in_o /* ... */ in 0..1 { + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } +} From c9c1932be3299b40eab63106deeb5d5ad2283b61 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 13 Oct 2021 21:22:34 -0500 Subject: [PATCH 76/98] feat: stabilize disable_all_formatting --- Configurations.md | 6 ++++-- src/config/mod.rs | 2 +- src/test/mod.rs | 5 ----- 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/Configurations.md b/Configurations.md index 06db897a42e7e..7a77dbe154b60 100644 --- a/Configurations.md +++ b/Configurations.md @@ -521,11 +521,13 @@ fn main() { ## `disable_all_formatting` -Don't reformat anything +Don't reformat anything. + +Note that this option may be soft-deprecated in the future once the [ignore](#ignore) option is stabilized. Nightly toolchain users are encouraged to use [ignore](#ignore) instead when possible. - **Default value**: `false` - **Possible values**: `true`, `false` -- **Stable**: No (tracking issue: #3388) +- **Stable**: Yes ## `edition` diff --git a/src/config/mod.rs b/src/config/mod.rs index 398a1814d8d1d..c5419d860c943 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -155,7 +155,7 @@ create_config! { "Require a specific version of rustfmt"; unstable_features: bool, false, false, "Enables unstable features. Only available on nightly channel"; - disable_all_formatting: bool, false, false, "Don't reformat anything"; + disable_all_formatting: bool, false, true, "Don't reformat anything"; skip_children: bool, false, false, "Don't reformat out of line modules"; hide_parse_errors: bool, false, false, "Hide errors from the parser"; error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width"; diff --git a/src/test/mod.rs b/src/test/mod.rs index ece1b91bfd7c5..48d61289a9b8f 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -469,11 +469,6 @@ fn stdin_works_with_modified_lines() { #[test] fn stdin_disable_all_formatting_test() { init_log(); - match option_env!("CFG_RELEASE_CHANNEL") { - None | Some("nightly") => {} - // These tests require nightly. - _ => return, - } let input = String::from("fn main() { println!(\"This should not be formatted.\"); }"); let mut child = Command::new(rustfmt().to_str().unwrap()) .stdin(Stdio::piped()) From a9a1393cbff49bbba9e83aa164ef208485579f92 Mon Sep 17 00:00:00 2001 From: Hudson Ayers Date: Wed, 13 Oct 2021 17:01:31 -0700 Subject: [PATCH 77/98] Add -Z location-detail flag --- compiler/rustc_session/src/config.rs | 17 ++++++++++++++++- compiler/rustc_session/src/options.rs | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index ac4bce7350b90..299dfed9d5dce 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -174,6 +174,20 @@ impl LinkerPluginLto { } } +/// The different settings that can be enabled via the `-Z location-detail` flag. +#[derive(Clone, PartialEq, Hash, Debug)] +pub struct LocationDetail { + pub file: bool, + pub line: bool, + pub column: bool, +} + +impl LocationDetail { + pub fn all() -> Self { + Self { file: true, line: true, column: true } + } +} + #[derive(Clone, PartialEq, Hash, Debug)] pub enum SwitchWithOptPath { Enabled(Option), @@ -2422,7 +2436,7 @@ crate mod dep_tracking { use super::LdImpl; use super::{ CFGuard, CrateType, DebugInfo, ErrorOutputType, InstrumentCoverage, LinkerPluginLto, - LtoCli, OptLevel, OutputType, OutputTypes, Passes, SourceFileHashAlgorithm, + LocationDetail, LtoCli, OptLevel, OutputType, OutputTypes, Passes, SourceFileHashAlgorithm, SwitchWithOptPath, SymbolManglingVersion, TrimmedDefPaths, }; use crate::lint; @@ -2513,6 +2527,7 @@ crate mod dep_tracking { Option, OutputType, RealFileName, + LocationDetail, ); impl DepTrackingHash for (T1, T2) diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index b3d36b396c51c..0bc868234afb1 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -368,6 +368,8 @@ mod desc { "either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, `fat`, or omitted"; pub const parse_linker_plugin_lto: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc), or the path to the linker plugin"; + pub const parse_location_detail: &str = + "comma seperated list of location details to track: `file`, `line`, or `column`"; pub const parse_switch_with_opt_path: &str = "an optional path to the profiling data output directory"; pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`"; @@ -484,6 +486,25 @@ mod parse { } } + crate fn parse_location_detail(ld: &mut LocationDetail, v: Option<&str>) -> bool { + if let Some(v) = v { + ld.line = false; + ld.file = false; + ld.column = false; + for s in v.split(',') { + match s { + "file" => ld.file = true, + "line" => ld.line = true, + "column" => ld.column = true, + _ => return false, + } + } + true + } else { + false + } + } + crate fn parse_opt_comma_list(slot: &mut Option>, v: Option<&str>) -> bool { match v { Some(s) => { @@ -1152,6 +1173,9 @@ options! { "a list LLVM plugins to enable (space separated)"), llvm_time_trace: bool = (false, parse_bool, [UNTRACKED], "generate JSON tracing data file from LLVM data (default: no)"), + location_detail: LocationDetail = (LocationDetail::all(), parse_location_detail, [TRACKED], + "comma seperated list of location details to be tracked when using caller_location \ + valid options are `file`, `line`, and `column` (default: all)"), ls: bool = (false, parse_bool, [UNTRACKED], "list the symbols defined by a library crate (default: no)"), macro_backtrace: bool = (false, parse_bool, [UNTRACKED], From 0cff306b61922ed5f460a4f6cbd4134498a3c42f Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 13 Oct 2021 21:41:50 -0500 Subject: [PATCH 78/98] ci: fix release asset upload job --- .github/workflows/upload-assets.yml | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/.github/workflows/upload-assets.yml b/.github/workflows/upload-assets.yml index 9a5fd0dd1d31b..f4dd394445301 100644 --- a/.github/workflows/upload-assets.yml +++ b/.github/workflows/upload-assets.yml @@ -1,8 +1,10 @@ name: upload on: + push: release: types: [created] + workflow_dispatch: jobs: build-release: @@ -14,42 +16,40 @@ jobs: - build: linux-x86_64 os: ubuntu-latest rust: nightly + target: x86_64-unknown-linux-gnu - build: macos-x86_64 os: macos-latest rust: nightly + target: x86_64-apple-darwin - build: windows-x86_64-gnu os: windows-latest rust: nightly-x86_64-gnu + target: x86_64-pc-windows-gnu - build: windows-x86_64-msvc os: windows-latest rust: nightly-x86_64-msvc + target: x86_64-pc-windows-msvc runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - - name: Install Rust - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: ${{ matrix.rust }} - override: true + # Run build + - name: install rustup + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup-init.sh + sh rustup-init.sh -y --default-toolchain none + rustup target add ${{ matrix.target }} - name: Add mingw64 to path for x86_64-gnu run: echo "C:\msys64\mingw64\bin" >> $GITHUB_PATH if: matrix.rust == 'nightly-x86_64-gnu' shell: bash - - name: Install cargo-make - uses: actions-rs/cargo@v1 - with: - command: install - args: --force cargo-make - - name: Build release binaries uses: actions-rs/cargo@v1 with: - command: make - args: release + command: build + args: --release - name: Build archive shell: bash @@ -70,6 +70,7 @@ jobs: fi - name: Upload Release Asset + if: github.event_name == 'release' uses: actions/upload-release-asset@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 5f4811ed7bc600e0cbe40c962e8933adb9baaddf Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Thu, 14 Oct 2021 17:16:28 -0400 Subject: [PATCH 79/98] Handle DefinitiveListTactic::SpecialMacro when writing pre-comments Resolves 4615 Previously only Vertical and Mixed enum variants of DefinitiveListTactic were considered when rewriting pre-comments for inner items in lists::write_list. Because we failed to considering the SpecialMacro variant we ended up in a scenario where a ListItem with a pre_comment and a pre_comment_style of ListItemCommentStyle::DifferentLine was written on the same line as the list item itself. Now we apply the same pre-comment formatting to SpecialMacro, Vertical, and Mixed variants of DefinitiveListTactic. --- src/lists.rs | 46 +++++++++++----------- tests/source/issue-4615/minimum_example.rs | 4 ++ tests/target/issue-4615/minimum_example.rs | 5 +++ 3 files changed, 33 insertions(+), 22 deletions(-) create mode 100644 tests/source/issue-4615/minimum_example.rs create mode 100644 tests/target/issue-4615/minimum_example.rs diff --git a/src/lists.rs b/src/lists.rs index 73e886c55637e..f0c2ae1499f01 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -367,29 +367,31 @@ where result.push_str(&comment); if !inner_item.is_empty() { - if tactic == DefinitiveListTactic::Vertical || tactic == DefinitiveListTactic::Mixed - { - // We cannot keep pre-comments on the same line if the comment if normalized. - let keep_comment = if formatting.config.normalize_comments() - || item.pre_comment_style == ListItemCommentStyle::DifferentLine - { - false - } else { - // We will try to keep the comment on the same line with the item here. - // 1 = ` ` - let total_width = total_item_width(item) + item_sep_len + 1; - total_width <= formatting.shape.width - }; - if keep_comment { - result.push(' '); - } else { - result.push('\n'); - result.push_str(indent_str); - // This is the width of the item (without comments). - line_len = item.item.as_ref().map_or(0, |s| unicode_str_width(&s)); + match tactic { + DefinitiveListTactic::SpecialMacro(_) + | DefinitiveListTactic::Vertical + | DefinitiveListTactic::Mixed => { + // We cannot keep pre-comments on the same line if the comment is normalized + let keep_comment = if formatting.config.normalize_comments() + || item.pre_comment_style == ListItemCommentStyle::DifferentLine + { + false + } else { + // We will try to keep the comment on the same line with the item here. + // 1 = ` ` + let total_width = total_item_width(item) + item_sep_len + 1; + total_width <= formatting.shape.width + }; + if keep_comment { + result.push(' '); + } else { + result.push('\n'); + result.push_str(indent_str); + // This is the width of the item (without comments). + line_len = item.item.as_ref().map_or(0, |s| unicode_str_width(&s)); + } } - } else { - result.push(' '); + _ => result.push(' '), } } item_max_width = None; diff --git a/tests/source/issue-4615/minimum_example.rs b/tests/source/issue-4615/minimum_example.rs new file mode 100644 index 0000000000000..89af5d1239dd0 --- /dev/null +++ b/tests/source/issue-4615/minimum_example.rs @@ -0,0 +1,4 @@ +info!(//debug + "{}: sending function_code={:04x} data={:04x} crc=0x{:04X} data={:02X?}", + self.name, function_code, data, crc, output_cmd +); diff --git a/tests/target/issue-4615/minimum_example.rs b/tests/target/issue-4615/minimum_example.rs new file mode 100644 index 0000000000000..223b89b812d3d --- /dev/null +++ b/tests/target/issue-4615/minimum_example.rs @@ -0,0 +1,5 @@ +info!( + //debug + "{}: sending function_code={:04x} data={:04x} crc=0x{:04X} data={:02X?}", + self.name, function_code, data, crc, output_cmd +); From 1ae5c35f8d2a0d2ce5d914a479839dc0f3eb70f9 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 18 Oct 2021 20:48:58 -0400 Subject: [PATCH 80/98] Replace match expression with match! macro This is a follow up to 5f4811ed7bc600e0cbe40c962e8933adb9baaddf The matches! macro expresses the condition more succinctly and avoids the extra level of indentation introduced with the match arm body. --- src/lists.rs | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index f0c2ae1499f01..c04b478761693 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -367,31 +367,29 @@ where result.push_str(&comment); if !inner_item.is_empty() { - match tactic { - DefinitiveListTactic::SpecialMacro(_) - | DefinitiveListTactic::Vertical - | DefinitiveListTactic::Mixed => { - // We cannot keep pre-comments on the same line if the comment is normalized - let keep_comment = if formatting.config.normalize_comments() - || item.pre_comment_style == ListItemCommentStyle::DifferentLine - { - false - } else { - // We will try to keep the comment on the same line with the item here. - // 1 = ` ` - let total_width = total_item_width(item) + item_sep_len + 1; - total_width <= formatting.shape.width - }; - if keep_comment { - result.push(' '); - } else { - result.push('\n'); - result.push_str(indent_str); - // This is the width of the item (without comments). - line_len = item.item.as_ref().map_or(0, |s| unicode_str_width(&s)); - } + use DefinitiveListTactic::*; + if matches!(tactic, Vertical | Mixed | SpecialMacro(_)) { + // We cannot keep pre-comments on the same line if the comment is normalized. + let keep_comment = if formatting.config.normalize_comments() + || item.pre_comment_style == ListItemCommentStyle::DifferentLine + { + false + } else { + // We will try to keep the comment on the same line with the item here. + // 1 = ` ` + let total_width = total_item_width(item) + item_sep_len + 1; + total_width <= formatting.shape.width + }; + if keep_comment { + result.push(' '); + } else { + result.push('\n'); + result.push_str(indent_str); + // This is the width of the item (without comments). + line_len = item.item.as_ref().map_or(0, |s| unicode_str_width(&s)); } - _ => result.push(' '), + } else { + result.push(' ') } } item_max_width = None; From 5f79583c3c83aa3b8a832e4effacb9141de4c2aa Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Tue, 19 Oct 2021 23:13:06 -0500 Subject: [PATCH 81/98] chore: bump toolchain, fix conflict --- Cargo.lock | 6 ------ rust-toolchain | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8e4f909896527..7263f0474770a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -118,12 +118,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -[[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" diff --git a/rust-toolchain b/rust-toolchain index b0cd4464df8e5..b19ecbdb07c4f 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2021-07-23" +channel = "nightly-2021-10-20" components = ["rustc-dev"] From efa8f5521d3813cc897ba29ea0ef98c7aef66bb6 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 20 Oct 2021 00:00:30 -0500 Subject: [PATCH 82/98] chore: bump version and changelog --- CHANGELOG.md | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68354b6ceaf25..b59438dc4fe78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,73 @@ ## [Unreleased] +## [1.4.38] 2021-10-20 + +### Changed + +- Switched from `rustc-ap-*` crates to `rustc_private` for consumption model of rustc internals +- `annotate-snippets` updated to v0.8 [PR #4762](https://github.com/rust-lang/rustfmt/pull/4762) +- Greatly improved the performance of `cargo fmt` in large workspaces utilizing the `--all` flag by updating to a newer version of `cargo_metadata` that leverages updated `cargo` output from v1.51+ [PR #4997](https://github.com/rust-lang/rustfmt/pull/4997) +- Improved formatting of long slice patterns [#4530](https://github.com/rust-lang/rustfmt/issues/4530) + - **Note you must have `version = Two` in your configuration to take advantage of the new formatting** +- Stabilized `match_block_trailing_comma` configuration option [#3380](https://github.com/rust-lang/rustfmt/issues/3380) - [https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#match_block_trailing_comma](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#match_block_trailing_comma) +- Stabilized `disable_all_formatting` configuration option [#5026](https://github.com/rust-lang/rustfmt/pull/5026) - [https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#disable_all_formatting](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#disable_all_formatting) +- Various improvements to the configuration documentation website [https://rust-lang.github.io/rustfmt/?version=v1.4.38]([https://rust-lang.github.io/rustfmt/?version=v1.4.38]) +- Addressed various clippy and rustc warnings + + +### Fixed + +- Resolved issue where specious whitespace would be inserted when a block style comment was terminated within string literal processing [#4312](https://github.com/rust-lang/rustfmt/issues/4312) +- Nested out-of-line mods are again parsed and formatted [#4874](https://github.com/rust-lang/rustfmt/issues/4874) +- Accepts `2021` for edition value from rustfmt command line [PR #4847](https://github.com/rust-lang/rustfmt/pull/4847) +- Unstable command line options are no longer displayed in `--help` text on stable [PR #4798](https://github.com/rust-lang/rustfmt/issues/4798) +- Stopped panicking on patterns in match arms which start with non-ascii characters [#4868](https://github.com/rust-lang/rustfmt/issues/4868) +- Stopped stripping defaults on const params [#4816](https://github.com/rust-lang/rustfmt/issues/4816) +- Fixed issue with dropped content with GAT aliases with self bounds in impls [#4911](https://github.com/rust-lang/rustfmt/issues/4911) +- Stopped removing generic args on associated type constraints [#4943](https://github.com/rust-lang/rustfmt/issues/4943) +- Stopped dropping visibility on certain trait and impl items [#4960](https://github.com/rust-lang/rustfmt/issues/4960) +- Fixed dropping of qualified paths in struct patterns [#4908](https://github.com/rust-lang/rustfmt/issues/4908) and [#5005](https://github.com/rust-lang/rustfmt/issues/5005) +- Fixed bug in line width calculation that was causing specious formatting of certain patterns [#4031](https://github.com/rust-lang/rustfmt/issues/4031) + - **Note that this bug fix may cause observable formatting changes in cases where code had been formatted with prior versions of rustfmt that contained the bug** +- Fixed bug where rustfmt would drop parameter attributes if they were too long in certain cases [#4579](https://github.com/rust-lang/rustfmt/issues/4579) +- Resolved idempotency issue with extern body elements [#4963](https://github.com/rust-lang/rustfmt/issues/4963) +- rustfmt will now handle doc-style comments on function parameters, since they could appear with certain macro usage patterns even though it's generally invalid syntax [#4936](https://github.com/rust-lang/rustfmt/issues/4936) +- Fixed bug in `match_block_trailing_comma` where commas were not added to the blocks of bodies whose arm had a guard that did not fit on the same line as the pattern [#4998](https://github.com/rust-lang/rustfmt/pull/4998) +- Fixed bug in cases where derive attributes started with a block style comment [#4984](https://github.com/rust-lang/rustfmt/issues/4984) +- Fixed issue where the struct rest could be lost when `struct_field_align_threshold` was enabled [#4926](https://github.com/rust-lang/rustfmt/issues/4926) +- Handles cases where certain control flow type expressions have comments between patterns/keywords and the pattern ident contains the keyword [#5009](https://github.com/rust-lang/rustfmt/issues/5009) +- Handles tuple structs that have explicit visibilities and start with a block style comment [#5011](https://github.com/rust-lang/rustfmt/issues/5011) +- Handles leading line-style comments in certain types of macro calls [#4615](https://github.com/rust-lang/rustfmt/issues/4615) + + +### Added +- Granular width heuristic options made available for user control [PR #4782](https://github.com/rust-lang/rustfmt/pull/4782). This includes the following: + - [`array_width`](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#array_width) + - [`attr_fn_like_width`](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#attr_fn_like_width) + - [`chain_width`](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#chain_width) + - [`fn_call_width`](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#fn_call_width) + - [`single_line_if_else_max_width`](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#single_line_if_else_max_width) + - [`struct_lit_width`](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#struct_lit_width) + - [`struct_variant_width`](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#struct_variant_width) + +Note this hit the rustup distributions prior to the v1.4.38 release as part of an out-of-cycle updates, but is listed in this version because the feature was not in the other v1.4.37 releases. See also the `use_small_heuristics` section on the configuration site for more information +[https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#use_small_heuristics](https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#use_small_heuristics) + +- New `One` variant added to `imports_granularity` configuration option which can be used to reformat all imports into a single use statement [#4669](https://github.com/rust-lang/rustfmt/issues/4669) +- rustfmt will now skip files that are annotated with `@generated` at the top of the file [#3958](https://github.com/rust-lang/rustfmt/issues/3958) +- New configuration option `hex_literal_case` that allows user to control the casing utilized for hex literals [PR #4903](https://github.com/rust-lang/rustfmt/pull/4903) + +See the section on the configuration site for more information +https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#hex_literal_case + +- `cargo fmt` now directly supports the `--check` flag, which means it's now possible to run `cargo fmt --check` instead of the more verbose `cargo fmt -- --check` [#3888](https://github.com/rust-lang/rustfmt/issues/3888) + +### Install/Download Options +- **rustup (nightly)** - *pending* +- **GitHub Release Binaries** - [Release v1.4.38](https://github.com/rust-lang/rustfmt/releases/tag/v1.4.38) +- **Build from source** - [Tag v1.4.38](https://github.com/rust-lang/rustfmt/tree/v1.4.38), see instructions for how to [install rustfmt from source][install-from-source] + ## [1.4.37] 2021-04-03 ### Changed diff --git a/Cargo.lock b/Cargo.lock index 7263f0474770a..2ef83ddd1ae6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -429,7 +429,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.4.37" +version = "1.4.38" dependencies = [ "annotate-snippets", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index d282766e00b4f..8d9c4a7fb20cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustfmt-nightly" -version = "1.4.37" +version = "1.4.38" description = "Tool to find and fix Rust formatting issues" repository = "https://github.com/rust-lang/rustfmt" readme = "README.md" From 0697f565f1d11601c159799f9542e0c7735ca98a Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 20 Oct 2021 00:15:20 -0500 Subject: [PATCH 83/98] update rustfmt --- Cargo.lock | 80 +++++++++++++++++++++++++----------------------------- 1 file changed, 37 insertions(+), 43 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aaa709e50f60d..2182a656da566 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -265,6 +265,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81a18687293a1546b67c246452202bbbf143d239cb43494cc163da14979082da" +[[package]] +name = "camino" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d74260d9bf6944e2208aa46841b4b8f0d7ffc0849a06837b2f510337f86b2b" +dependencies = [ + "serde", +] + [[package]] name = "cargo" version = "0.58.0" @@ -272,7 +281,7 @@ dependencies = [ "anyhow", "atty", "bytesize", - "cargo-platform", + "cargo-platform 0.1.2", "cargo-test-macro", "cargo-test-support", "cargo-util", @@ -374,6 +383,15 @@ dependencies = [ "serde", ] +[[package]] +name = "cargo-platform" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbdb825da8a5df079a43676dbe042702f1707b1109f713a01420fbb4cc71fa27" +dependencies = [ + "serde", +] + [[package]] name = "cargo-test-macro" version = "0.1.0" @@ -421,23 +439,24 @@ dependencies = [ [[package]] name = "cargo_metadata" -version = "0.8.2" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "700b3731fd7d357223d0000f4dbf1808401b694609035c3c411fbc0cd375c426" +checksum = "d5a5f7b42f606b7f23674f6f4d877628350682bc40687d3fae65679a58d55345" dependencies = [ - "semver 0.9.0", + "semver 0.11.0", "serde", - "serde_derive", "serde_json", ] [[package]] name = "cargo_metadata" -version = "0.12.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5a5f7b42f606b7f23674f6f4d877628350682bc40687d3fae65679a58d55345" +checksum = "c297bd3135f558552f99a0daa180876984ea2c4ffa7470314540dff8c654109a" dependencies = [ - "semver 0.11.0", + "camino", + "cargo-platform 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "semver 1.0.3", "serde", "serde_json", ] @@ -1069,9 +1088,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.6.2" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aafcde04e90a5226a6443b7aabdb016ba2f8307c847d524724bd9b346dd1a2d3" +checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" dependencies = [ "atty", "humantime 1.3.0", @@ -1082,12 +1101,12 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.7.1" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" +checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" dependencies = [ "atty", - "humantime 1.3.0", + "humantime 2.0.1", "log", "regex", "termcolor", @@ -1688,15 +1707,6 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b141fdc7836c525d4d594027d318c84161ca17aaf8113ab1f81ab93ae897485" -[[package]] -name = "itertools" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f56a2d0bc861f9165be4eb3442afd3c236d8a98afd426f65d92324ae1091a484" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.9.0" @@ -4664,19 +4674,19 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.4.37" +version = "1.4.38" dependencies = [ "annotate-snippets", "anyhow", "bytecount", - "cargo_metadata 0.8.2", + "cargo_metadata 0.14.0", "derive-new", "diff", "dirs", - "env_logger 0.6.2", + "env_logger 0.8.4", "getopts", "ignore", - "itertools 0.8.2", + "itertools 0.9.0", "lazy_static", "log", "regex", @@ -4759,23 +4769,13 @@ dependencies = [ "libc", ] -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser 0.7.0", - "serde", -] - [[package]] name = "semver" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" dependencies = [ - "semver-parser 0.10.2", + "semver-parser", "serde", ] @@ -4788,12 +4788,6 @@ dependencies = [ "serde", ] -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - [[package]] name = "semver-parser" version = "0.10.2" From d3ecb02bddbb1dd70fb7937966415d13c1a17eba Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 20 Oct 2021 10:12:22 -0500 Subject: [PATCH 84/98] ensure cargo-fmt tests are excluded from root workspace --- .../cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tools/rustfmt/tests/cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml b/src/tools/rustfmt/tests/cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml index df1886c82be31..eaf1d76f999d4 100644 --- a/src/tools/rustfmt/tests/cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml +++ b/src/tools/rustfmt/tests/cargo-fmt/source/workspaces/path-dep-above/e/Cargo.toml @@ -4,3 +4,5 @@ version = "0.1.0" edition = "2018" [dependencies] c = { path = "../ws/c" } + +[workspace] From 65b3c853178b04c5cbe41f26e6a1b1b90d7b8cc6 Mon Sep 17 00:00:00 2001 From: Andre Bogus Date: Tue, 19 Oct 2021 23:06:19 +0200 Subject: [PATCH 85/98] Add edition configuration to compiletest --- src/tools/compiletest/src/common.rs | 3 +++ src/tools/compiletest/src/header.rs | 6 ++++++ src/tools/compiletest/src/main.rs | 4 +++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index cd0a56d08d8bc..82fe790a576ab 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -349,6 +349,9 @@ pub struct Config { /// The current Rust channel pub channel: String, + /// The default Rust edition + pub edition: Option, + // Configuration for various run-make tests frobbing things like C compilers // or querying about various LLVM component information. pub cc: String, diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index efd8550279959..98d1ee19f69a1 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -222,6 +222,7 @@ impl TestProps { /// `//[foo]`), then the property is ignored unless `cfg` is /// `Some("foo")`. fn load_from(&mut self, testfile: &Path, cfg: Option<&str>, config: &Config) { + let mut has_edition = false; if !testfile.is_dir() { let file = File::open(testfile).unwrap(); @@ -240,6 +241,7 @@ impl TestProps { if let Some(edition) = config.parse_edition(ln) { self.compile_flags.push(format!("--edition={}", edition)); + has_edition = true; if edition == "2021" { self.compile_flags.push("-Zunstable-options".to_string()); } @@ -391,6 +393,10 @@ impl TestProps { } } } + + if let (Some(edition), false) = (&config.edition, has_edition) { + self.compile_flags.push(format!("--edition={}", edition)); + } } fn update_fail_mode(&mut self, ln: &str, config: &Config) { diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index 87aba8c5d32bf..58cde108b3322 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -147,7 +147,8 @@ pub fn parse_config(args: Vec) -> Config { ) .optflag("", "force-rerun", "rerun tests even if the inputs are unchanged") .optflag("h", "help", "show this message") - .reqopt("", "channel", "current Rust channel", "CHANNEL"); + .reqopt("", "channel", "current Rust channel", "CHANNEL") + .optopt("", "edition", "default Rust edition", "EDITION"); let (argv0, args_) = args.split_first().unwrap(); if args.len() == 1 || args[1] == "-h" || args[1] == "--help" { @@ -282,6 +283,7 @@ pub fn parse_config(args: Vec) -> Config { rustfix_coverage: matches.opt_present("rustfix-coverage"), has_tidy, channel: matches.opt_str("channel").unwrap(), + edition: matches.opt_str("edition"), cc: matches.opt_str("cc").unwrap(), cxx: matches.opt_str("cxx").unwrap(), From e1e273fb64a115ee28dad5a51864e9ca6daac676 Mon Sep 17 00:00:00 2001 From: Hans Kratz Date: Thu, 21 Oct 2021 11:02:47 +0200 Subject: [PATCH 86/98] CI: make cache download attempt time out after 10 minutes --- src/ci/docker/run.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh index e42b4748fdc78..ab81a9d1de2e4 100755 --- a/src/ci/docker/run.sh +++ b/src/ci/docker/run.sh @@ -70,7 +70,8 @@ if [ -f "$docker_dir/$image/Dockerfile" ]; then echo "Attempting to download $url" rm -f /tmp/rustci_docker_cache set +e - retry curl -y 30 -Y 10 --connect-timeout 30 -f -L -C - -o /tmp/rustci_docker_cache "$url" + retry curl --max-time 600 -y 30 -Y 10 --connect-timeout 30 -f -L -C - \ + -o /tmp/rustci_docker_cache "$url" loaded_images=$(docker load -i /tmp/rustci_docker_cache | sed 's/.* sha/sha/') set -e echo "Downloaded containers:\n$loaded_images" From 838e673d3b767c32dd54a3d8fee3c9caa65caa68 Mon Sep 17 00:00:00 2001 From: Hans Kratz Date: Thu, 21 Oct 2021 11:11:20 +0200 Subject: [PATCH 87/98] Debug output before loading docker images as that might hang. --- src/ci/docker/run.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh index ab81a9d1de2e4..b9b6add99f883 100755 --- a/src/ci/docker/run.sh +++ b/src/ci/docker/run.sh @@ -72,6 +72,7 @@ if [ -f "$docker_dir/$image/Dockerfile" ]; then set +e retry curl --max-time 600 -y 30 -Y 10 --connect-timeout 30 -f -L -C - \ -o /tmp/rustci_docker_cache "$url" + echo "Loading images into docker" loaded_images=$(docker load -i /tmp/rustci_docker_cache | sed 's/.* sha/sha/') set -e echo "Downloaded containers:\n$loaded_images" From e1d94b8fd1ca1a1de6a56a3c53bb105fefacdd9c Mon Sep 17 00:00:00 2001 From: Hudson Ayers Date: Thu, 14 Oct 2021 09:20:32 -0700 Subject: [PATCH 88/98] Configure saved panic locations based on location-detail flag --- .../src/interpret/intrinsics/caller_location.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs index d4cbba1802931..b5e97ec8fe0f4 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs @@ -80,10 +80,17 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { line: u32, col: u32, ) -> MPlaceTy<'tcx, M::PointerTag> { - let file = - self.allocate_str(&filename.as_str(), MemoryKind::CallerLocation, Mutability::Not); - let line = Scalar::from_u32(line); - let col = Scalar::from_u32(col); + let loc_details = &self.tcx.sess.opts.debugging_opts.location_detail; + let file = if loc_details.file { + self.allocate_str(&filename.as_str(), MemoryKind::CallerLocation, Mutability::Not) + } else { + // FIXME: This creates a new allocation each time. It might be preferable to + // perform this allocation only once, and re-use the `MPlaceTy`. + // See https://github.com/rust-lang/rust/pull/89920#discussion_r730012398 + self.allocate_str("", MemoryKind::CallerLocation, Mutability::Not) + }; + let line = if loc_details.line { Scalar::from_u32(line) } else { Scalar::from_u32(0) }; + let col = if loc_details.column { Scalar::from_u32(col) } else { Scalar::from_u32(0) }; // Allocate memory for `CallerLocation` struct. let loc_ty = self From 8090f67fb7abc459b24eaa87a5309ed49ed96866 Mon Sep 17 00:00:00 2001 From: Hudson Ayers Date: Thu, 14 Oct 2021 10:46:07 -0700 Subject: [PATCH 89/98] document the unstable location-detail flag --- .../src/compiler-flags/location-detail.md | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/doc/unstable-book/src/compiler-flags/location-detail.md diff --git a/src/doc/unstable-book/src/compiler-flags/location-detail.md b/src/doc/unstable-book/src/compiler-flags/location-detail.md new file mode 100644 index 0000000000000..08d937cc28200 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/location-detail.md @@ -0,0 +1,43 @@ +# `location-detail` + +The tracking issue for this feature is: [#70580](https://github.com/rust-lang/rust/issues/70580). + +------------------------ + +Option `-Z location-detail=val` controls what location details are tracked when +using `caller_location`. This allows users to control what location details +are printed as part of panic messages, by allowing them to exclude any combination +of filenames, line numbers, and column numbers. This option is intended to provide +users with a way to mitigate the size impact of `#[track_caller]`. + +This option supports a comma separated list of location details to be included. Valid options +within this list are: + +- `file` - the filename of the panic will be included in the panic output +- `line` - the source line of the panic will be included in the panic output +- `column` - the source column of the panic will be included in the panic output + +Any combination of these three options are supported. If this option is not specified, +all three are included by default. + +An example of a panic output when using `-Z location-detail=line`: +```text +panicked at 'Process blink had a fault', :323:0 +``` + +The code size savings from this option are two-fold. First, the `&'static str` values +for each path to a file containing a panic are removed from the binary. For projects +with deep directory structures and many files with panics, this can add up. This category +of savings can only be realized by excluding filenames from the panic output. Second, +savings can be realized by allowing multiple panics to be fused into a single panicking +branch. It is often the case that within a single file, multiple panics with the same +panic message exist -- e.g. two calls to `Option::unwrap()` in a single line, or +two calls to `Result::expect()` on adjacent lines. If column and line information +are included in the `Location` struct passed to the panic handler, these branches cannot +be fused, as the output is different depending on which panic occurs. However if line +and column information is identical for all panics, these branches can be fused, which +can lead to substantial code size savings, especially for small embedded binaries with +many panics. + +The savings from this option are amplified when combined with the use of `-Zbuild-std`, as +otherwise paths for panics within the standard library are still included in your binary. From b802629311ee9873978e91f185657fd6ae3cba28 Mon Sep 17 00:00:00 2001 From: Hudson Ayers Date: Fri, 15 Oct 2021 08:58:28 -0700 Subject: [PATCH 90/98] add tests for -Zlocation-detail --- compiler/rustc_interface/src/tests.rs | 5 ++++- src/test/ui/panics/location-detail-panic-no-column.rs | 7 +++++++ .../ui/panics/location-detail-panic-no-column.run.stderr | 2 ++ src/test/ui/panics/location-detail-panic-no-file.rs | 7 +++++++ .../ui/panics/location-detail-panic-no-file.run.stderr | 2 ++ src/test/ui/panics/location-detail-panic-no-line.rs | 7 +++++++ .../ui/panics/location-detail-panic-no-line.run.stderr | 2 ++ src/test/ui/panics/location-detail-unwrap-no-file.rs | 8 ++++++++ .../ui/panics/location-detail-unwrap-no-file.run.stderr | 2 ++ 9 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/test/ui/panics/location-detail-panic-no-column.rs create mode 100644 src/test/ui/panics/location-detail-panic-no-column.run.stderr create mode 100644 src/test/ui/panics/location-detail-panic-no-file.rs create mode 100644 src/test/ui/panics/location-detail-panic-no-file.run.stderr create mode 100644 src/test/ui/panics/location-detail-panic-no-line.rs create mode 100644 src/test/ui/panics/location-detail-panic-no-line.run.stderr create mode 100644 src/test/ui/panics/location-detail-unwrap-no-file.rs create mode 100644 src/test/ui/panics/location-detail-unwrap-no-file.run.stderr diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 844e5ab56a420..dab4d485e2d0b 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -5,7 +5,9 @@ use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig}; use rustc_session::config::InstrumentCoverage; use rustc_session::config::Strip; use rustc_session::config::{build_configuration, build_session_options, to_crate_config}; -use rustc_session::config::{rustc_optgroups, ErrorOutputType, ExternLocation, Options, Passes}; +use rustc_session::config::{ + rustc_optgroups, ErrorOutputType, ExternLocation, LocationDetail, Options, Passes, +}; use rustc_session::config::{CFGuard, ExternEntry, LinkerPluginLto, LtoCli, SwitchWithOptPath}; use rustc_session::config::{ Externs, OutputType, OutputTypes, SymbolManglingVersion, WasiExecModel, @@ -733,6 +735,7 @@ fn test_debugging_options_tracking_hash() { tracked!(instrument_mcount, true); tracked!(link_only, true); tracked!(llvm_plugins, vec![String::from("plugin_name")]); + tracked!(location_detail, LocationDetail { file: true, line: false, column: false }); tracked!(merge_functions, Some(MergeFunctions::Disabled)); tracked!(mir_emit_retag, true); tracked!(mir_opt_level, Some(4)); diff --git a/src/test/ui/panics/location-detail-panic-no-column.rs b/src/test/ui/panics/location-detail-panic-no-column.rs new file mode 100644 index 0000000000000..673e638ca0d6b --- /dev/null +++ b/src/test/ui/panics/location-detail-panic-no-column.rs @@ -0,0 +1,7 @@ +// run-fail +// check-run-results +// compile-flags: -Zlocation-detail=line,file + +fn main() { + panic!("column-redacted"); +} diff --git a/src/test/ui/panics/location-detail-panic-no-column.run.stderr b/src/test/ui/panics/location-detail-panic-no-column.run.stderr new file mode 100644 index 0000000000000..9f35623fba392 --- /dev/null +++ b/src/test/ui/panics/location-detail-panic-no-column.run.stderr @@ -0,0 +1,2 @@ +thread 'main' panicked at 'column-redacted', $DIR/location-detail-panic-no-column.rs:6:0 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace diff --git a/src/test/ui/panics/location-detail-panic-no-file.rs b/src/test/ui/panics/location-detail-panic-no-file.rs new file mode 100644 index 0000000000000..0e5d52cfd1534 --- /dev/null +++ b/src/test/ui/panics/location-detail-panic-no-file.rs @@ -0,0 +1,7 @@ +// run-fail +// check-run-results +// compile-flags: -Zlocation-detail=line,column + +fn main() { + panic!("file-redacted"); +} diff --git a/src/test/ui/panics/location-detail-panic-no-file.run.stderr b/src/test/ui/panics/location-detail-panic-no-file.run.stderr new file mode 100644 index 0000000000000..1e07e3a07afd5 --- /dev/null +++ b/src/test/ui/panics/location-detail-panic-no-file.run.stderr @@ -0,0 +1,2 @@ +thread 'main' panicked at 'file-redacted', :6:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace diff --git a/src/test/ui/panics/location-detail-panic-no-line.rs b/src/test/ui/panics/location-detail-panic-no-line.rs new file mode 100644 index 0000000000000..57f6d0ebcb9fa --- /dev/null +++ b/src/test/ui/panics/location-detail-panic-no-line.rs @@ -0,0 +1,7 @@ +// run-fail +// check-run-results +// compile-flags: -Zlocation-detail=file,column + +fn main() { + panic!("line-redacted"); +} diff --git a/src/test/ui/panics/location-detail-panic-no-line.run.stderr b/src/test/ui/panics/location-detail-panic-no-line.run.stderr new file mode 100644 index 0000000000000..cc3f1624c49ab --- /dev/null +++ b/src/test/ui/panics/location-detail-panic-no-line.run.stderr @@ -0,0 +1,2 @@ +thread 'main' panicked at 'line-redacted', $DIR/location-detail-panic-no-line.rs:0:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace diff --git a/src/test/ui/panics/location-detail-unwrap-no-file.rs b/src/test/ui/panics/location-detail-unwrap-no-file.rs new file mode 100644 index 0000000000000..d7f96f058e082 --- /dev/null +++ b/src/test/ui/panics/location-detail-unwrap-no-file.rs @@ -0,0 +1,8 @@ +// run-fail +// check-run-results +// compile-flags: -Zlocation-detail=line,column + +fn main() { + let opt: Option = None; + opt.unwrap(); +} diff --git a/src/test/ui/panics/location-detail-unwrap-no-file.run.stderr b/src/test/ui/panics/location-detail-unwrap-no-file.run.stderr new file mode 100644 index 0000000000000..f8f84b5c49a22 --- /dev/null +++ b/src/test/ui/panics/location-detail-unwrap-no-file.run.stderr @@ -0,0 +1,2 @@ +thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', :7:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace From 3e6a69534f52b08057d18643b62d0f926b80909f Mon Sep 17 00:00:00 2001 From: Hans Kratz Date: Thu, 21 Oct 2021 22:52:00 +0200 Subject: [PATCH 91/98] Time out docker load after 10 minutes, kill after 12 due to CI hangs. --- src/ci/docker/run.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh index b9b6add99f883..b1dacf79d2695 100755 --- a/src/ci/docker/run.sh +++ b/src/ci/docker/run.sh @@ -73,7 +73,10 @@ if [ -f "$docker_dir/$image/Dockerfile" ]; then retry curl --max-time 600 -y 30 -Y 10 --connect-timeout 30 -f -L -C - \ -o /tmp/rustci_docker_cache "$url" echo "Loading images into docker" - loaded_images=$(docker load -i /tmp/rustci_docker_cache | sed 's/.* sha/sha/') + # docker load sometimes hangs in the CI, so time out after 10 minutes with TERM, + # KILL after 12 minutes + loaded_images=$(/usr/bin/timeout -k 720 600 docker load -i /tmp/rustci_docker_cache \ + | sed 's/.* sha/sha/') set -e echo "Downloaded containers:\n$loaded_images" fi From 170214fa16046cd9db435502d3e51928c1b5268b Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Thu, 21 Oct 2021 17:22:54 -0500 Subject: [PATCH 92/98] fix doc issue in rustfmt --- src/tools/rustfmt/src/comment.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rustfmt/src/comment.rs b/src/tools/rustfmt/src/comment.rs index 6082542485856..dc4f4516252b1 100644 --- a/src/tools/rustfmt/src/comment.rs +++ b/src/tools/rustfmt/src/comment.rs @@ -403,7 +403,7 @@ enum CodeBlockAttribute { impl CodeBlockAttribute { /// Parse comma separated attributes list. Return rust only if all /// attributes are valid rust attributes - /// See https://doc.rust-lang.org/rustdoc/print.html#attributes + /// See fn new(attributes: &str) -> CodeBlockAttribute { for attribute in attributes.split(",") { match attribute.trim() { From afcee19d88658e54f4a3c82892ba6d937e0f78d4 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Wed, 20 Oct 2021 17:04:01 -0700 Subject: [PATCH 93/98] Make RSplit: Clone not require T: Clone This addresses a TODO comment. The behavior of #[derive(Clone)] *does* result in a T: Clone requirement. Add a manual Clone implementation, matching Split and SplitInclusive. --- library/core/src/slice/iter.rs | 12 +++++++++++- src/test/ui/iterators/rsplit-clone.rs | 11 +++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 src/test/ui/iterators/rsplit-clone.rs diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index dbf97851b03e4..07ecae7830351 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -839,7 +839,6 @@ impl FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> b /// [`rsplit`]: slice::rsplit /// [slices]: slice #[stable(feature = "slice_rsplit", since = "1.27.0")] -#[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`? pub struct RSplit<'a, T: 'a, P> where P: FnMut(&T) -> bool, @@ -867,6 +866,17 @@ where } } +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +#[stable(feature = "slice_rsplit", since = "1.27.0")] +impl Clone for RSplit<'_, T, P> +where + P: Clone + FnMut(&T) -> bool, +{ + fn clone(&self) -> Self { + RSplit { inner: self.inner.clone() } + } +} + #[stable(feature = "slice_rsplit", since = "1.27.0")] impl<'a, T, P> Iterator for RSplit<'a, T, P> where diff --git a/src/test/ui/iterators/rsplit-clone.rs b/src/test/ui/iterators/rsplit-clone.rs new file mode 100644 index 0000000000000..911da74295722 --- /dev/null +++ b/src/test/ui/iterators/rsplit-clone.rs @@ -0,0 +1,11 @@ +// check-pass + +// RSplit previously required T: Clone in order to be Clone + +struct NotClone; + +fn main() { + let elements = [NotClone, NotClone, NotClone]; + let rsplit = elements.rsplit(|_| false); + rsplit.clone(); +} From 4a439769ecd292106d62270d171568ac7aa0164b Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Wed, 17 Mar 2021 17:23:09 +0100 Subject: [PATCH 94/98] Implement split_array and split_array_mut --- library/core/src/array/mod.rs | 78 +++++++++++++++++++++++++++++++++++ library/core/src/slice/mod.rs | 74 +++++++++++++++++++++++++++++++++ library/core/tests/array.rs | 33 +++++++++++++++ library/core/tests/lib.rs | 1 + library/core/tests/slice.rs | 33 +++++++++++++++ 5 files changed, 219 insertions(+) diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index b27c36baf37c5..73340fda2cbcc 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -500,6 +500,84 @@ impl [T; N] { // items. unsafe { collect_into_array_unchecked(&mut self.iter_mut()) } } + + /// Divides one array reference into two at an index. + /// + /// The first will contain all indices from `[0, M)` (excluding + /// the index `M` itself) and the second will contain all + /// indices from `[M, N)` (excluding the index `N` itself). + /// + /// # Panics + /// + /// Panics if `M > N`. + /// + /// # Examples + /// + /// ``` + /// #![feature(split_array)] + /// + /// let v = [1, 2, 3, 4, 5, 6]; + /// + /// { + /// let (left, right) = v.split_array_ref::<0>(); + /// assert_eq!(left, &[]); + /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]); + /// } + /// + /// { + /// let (left, right) = v.split_array_ref::<2>(); + /// assert_eq!(left, &[1, 2]); + /// assert_eq!(right, &[3, 4, 5, 6]); + /// } + /// + /// { + /// let (left, right) = v.split_array_ref::<6>(); + /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]); + /// assert_eq!(right, &[]); + /// } + /// ``` + #[unstable( + feature = "split_array", + reason = "return type should have array as 2nd element", + issue = "90091" + )] + #[inline] + pub fn split_array_ref(&self) -> (&[T; M], &[T]) { + (&self[..]).split_array_ref::() + } + + /// Divides one mutable array reference into two at an index. + /// + /// The first will contain all indices from `[0, M)` (excluding + /// the index `M` itself) and the second will contain all + /// indices from `[M, N)` (excluding the index `N` itself). + /// + /// # Panics + /// + /// Panics if `M > N`. + /// + /// # Examples + /// + /// ``` + /// #![feature(split_array)] + /// + /// let mut v = [1, 0, 3, 0, 5, 6]; + /// let (left, right) = v.split_array_mut::<2>(); + /// assert_eq!(left, &mut [1, 0][..]); + /// assert_eq!(right, &mut [3, 0, 5, 6]); + /// left[1] = 2; + /// right[1] = 4; + /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); + /// ``` + #[unstable( + feature = "split_array", + reason = "return type should have array as 2nd element", + issue = "90091" + )] + #[inline] + pub fn split_array_mut(&mut self) -> (&mut [T; M], &mut [T]) { + (&mut self[..]).split_array_mut::() + } } /// Pulls `N` items from `iter` and returns them as an array. If the iterator diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 664875a8773ed..aaa00653b99c2 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -1665,6 +1665,80 @@ impl [T] { unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } } + /// Divides one slice into an array and a remainder slice at an index. + /// + /// The array will contain all indices from `[0, N)` (excluding + /// the index `N` itself) and the slice will contain all + /// indices from `[N, len)` (excluding the index `len` itself). + /// + /// # Panics + /// + /// Panics if `N > len`. + /// + /// # Examples + /// + /// ``` + /// #![feature(split_array)] + /// + /// let v = &[1, 2, 3, 4, 5, 6][..]; + /// + /// { + /// let (left, right) = v.split_array_ref::<0>(); + /// assert_eq!(left, &[]); + /// assert_eq!(right, [1, 2, 3, 4, 5, 6]); + /// } + /// + /// { + /// let (left, right) = v.split_array_ref::<2>(); + /// assert_eq!(left, &[1, 2]); + /// assert_eq!(right, [3, 4, 5, 6]); + /// } + /// + /// { + /// let (left, right) = v.split_array_ref::<6>(); + /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]); + /// assert_eq!(right, []); + /// } + /// ``` + #[unstable(feature = "split_array", reason = "new API", issue = "90091")] + #[inline] + pub fn split_array_ref(&self) -> (&[T; N], &[T]) { + let (a, b) = self.split_at(N); + // SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at) + unsafe { (&*(a.as_ptr() as *const [T; N]), b) } + } + + /// Divides one mutable slice into an array and a remainder slice at an index. + /// + /// The array will contain all indices from `[0, N)` (excluding + /// the index `N` itself) and the slice will contain all + /// indices from `[N, len)` (excluding the index `len` itself). + /// + /// # Panics + /// + /// Panics if `N > len`. + /// + /// # Examples + /// + /// ``` + /// #![feature(split_array)] + /// + /// let mut v = &mut [1, 0, 3, 0, 5, 6][..]; + /// let (left, right) = v.split_array_mut::<2>(); + /// assert_eq!(left, &mut [1, 0]); + /// assert_eq!(right, [3, 0, 5, 6]); + /// left[1] = 2; + /// right[1] = 4; + /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); + /// ``` + #[unstable(feature = "split_array", reason = "new API", issue = "90091")] + #[inline] + pub fn split_array_mut(&mut self) -> (&mut [T; N], &mut [T]) { + let (a, b) = self.split_at_mut(N); + // SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at_mut) + unsafe { (&mut *(a.as_mut_ptr() as *mut [T; N]), b) } + } + /// Returns an iterator over subslices separated by elements that match /// `pred`. The matched element is not contained in the subslices. /// diff --git a/library/core/tests/array.rs b/library/core/tests/array.rs index b3af1328c90d4..1d4307ca0fbda 100644 --- a/library/core/tests/array.rs +++ b/library/core/tests/array.rs @@ -436,3 +436,36 @@ where std::panic::set_hook(prev_hook); result } + +#[test] +fn array_split_array_mut() { + let mut v = [1, 2, 3, 4, 5, 6]; + + { + let (left, right) = v.split_array_mut::<0>(); + assert_eq!(left, &mut []); + assert_eq!(right, &mut [1, 2, 3, 4, 5, 6]); + } + + { + let (left, right) = v.split_array_mut::<6>(); + assert_eq!(left, &mut [1, 2, 3, 4, 5, 6]); + assert_eq!(right, &mut []); + } +} + +#[should_panic] +#[test] +fn array_split_array_ref_out_of_bounds() { + let v = [1, 2, 3, 4, 5, 6]; + + v.split_array_ref::<7>(); +} + +#[should_panic] +#[test] +fn array_split_array_mut_out_of_bounds() { + let mut v = [1, 2, 3, 4, 5, 6]; + + v.split_array_mut::<7>(); +} diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index ab0295c63143d..507a79c3de1c4 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -70,6 +70,7 @@ #![feature(integer_atomics)] #![feature(int_roundings)] #![feature(slice_group_by)] +#![feature(split_array)] #![feature(trusted_random_access)] #![feature(unsize)] #![feature(unzip_option)] diff --git a/library/core/tests/slice.rs b/library/core/tests/slice.rs index b6a326f3d7368..7a008345243c0 100644 --- a/library/core/tests/slice.rs +++ b/library/core/tests/slice.rs @@ -2191,3 +2191,36 @@ mod swap_panics { x.swap(2, 5); } } + +#[test] +fn slice_split_array_mut() { + let v = &mut [1, 2, 3, 4, 5, 6][..]; + + { + let (left, right) = v.split_array_mut::<0>(); + assert_eq!(left, &mut []); + assert_eq!(right, [1, 2, 3, 4, 5, 6]); + } + + { + let (left, right) = v.split_array_mut::<6>(); + assert_eq!(left, &mut [1, 2, 3, 4, 5, 6]); + assert_eq!(right, []); + } +} + +#[should_panic] +#[test] +fn slice_split_array_ref_out_of_bounds() { + let v = &[1, 2, 3, 4, 5, 6][..]; + + v.split_array_ref::<7>(); +} + +#[should_panic] +#[test] +fn slice_split_array_mut_out_of_bounds() { + let v = &mut [1, 2, 3, 4, 5, 6][..]; + + v.split_array_mut::<7>(); +} From c736c2a3aef0069fc9af918bea841d35dfba7b7a Mon Sep 17 00:00:00 2001 From: Steven Date: Fri, 22 Oct 2021 09:55:32 -0400 Subject: [PATCH 95/98] Add comment documenting why we can't use a simpler solution See #90144 for context. r? @joshtriplett --- library/std/src/sys/windows/os.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/std/src/sys/windows/os.rs b/library/std/src/sys/windows/os.rs index 883690c483167..b5209aa690b4c 100644 --- a/library/std/src/sys/windows/os.rs +++ b/library/std/src/sys/windows/os.rs @@ -281,6 +281,10 @@ pub fn temp_dir() -> PathBuf { #[cfg(not(target_vendor = "uwp"))] fn home_dir_crt() -> Option { unsafe { + // The magic constant -4 can be used as the token passed to GetUserProfileDirectoryW below + // instead of us having to go through these multiple steps to get a token. However this is + // not implemented on Windows 7, only Windows 8 and up. When we drop support for Windows 7 + // we can simplify this code. See #90144 for details. use crate::sys::handle::Handle; let me = c::GetCurrentProcess(); From 7d7ebf88057ad6e16331e02a86c5951ecd1f23db Mon Sep 17 00:00:00 2001 From: Charles Lew Date: Sun, 10 Oct 2021 14:50:39 +0800 Subject: [PATCH 96/98] add feature flag for `type_changing_struct_update` --- compiler/rustc_feature/src/active.rs | 4 +++ compiler/rustc_span/src/symbol.rs | 1 + ...eature-gate-type_changing_struct_update.rs | 26 +++++++++++++++++++ ...re-gate-type_changing_struct_update.stderr | 12 +++++++++ 4 files changed, 43 insertions(+) create mode 100644 src/test/ui/feature-gates/feature-gate-type_changing_struct_update.rs create mode 100644 src/test/ui/feature-gates/feature-gate-type_changing_struct_update.stderr diff --git a/compiler/rustc_feature/src/active.rs b/compiler/rustc_feature/src/active.rs index a2fadb13a5741..af40705cbfc31 100644 --- a/compiler/rustc_feature/src/active.rs +++ b/compiler/rustc_feature/src/active.rs @@ -681,6 +681,10 @@ declare_features! ( /// Allows using the `non_exhaustive_omitted_patterns` lint. (active, non_exhaustive_omitted_patterns_lint, "1.57.0", Some(89554), None), + /// Allows creation of instances of a struct by moving fields that have + /// not changed from prior instances of the same struct (RFC #2528) + (incomplete, type_changing_struct_update, "1.58.0", Some(86555), None), + // ------------------------------------------------------------------------- // feature-group-end: actual feature gates // ------------------------------------------------------------------------- diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 9551120ca5522..0327e56f9d7c0 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1335,6 +1335,7 @@ symbols! { type_alias_enum_variants, type_alias_impl_trait, type_ascription, + type_changing_struct_update, type_id, type_length_limit, type_macros, diff --git a/src/test/ui/feature-gates/feature-gate-type_changing_struct_update.rs b/src/test/ui/feature-gates/feature-gate-type_changing_struct_update.rs new file mode 100644 index 0000000000000..520c1478f3234 --- /dev/null +++ b/src/test/ui/feature-gates/feature-gate-type_changing_struct_update.rs @@ -0,0 +1,26 @@ +#[derive(Debug)] +struct Machine { + state: S, + common_field1: &'static str, + common_field2: i32, +} +#[derive(Debug)] +struct State1; +#[derive(Debug, PartialEq)] +struct State2; + +fn update_to_state2() { + let m1: Machine = Machine { + state: State1, + common_field1: "hello", + common_field2: 2, + }; + let m2: Machine = Machine { + state: State2, + ..m1 //~ ERROR mismatched types + }; + // FIXME: this should trigger feature gate + assert_eq!(State2, m2.state); +} + +fn main() {} diff --git a/src/test/ui/feature-gates/feature-gate-type_changing_struct_update.stderr b/src/test/ui/feature-gates/feature-gate-type_changing_struct_update.stderr new file mode 100644 index 0000000000000..9934fe6816430 --- /dev/null +++ b/src/test/ui/feature-gates/feature-gate-type_changing_struct_update.stderr @@ -0,0 +1,12 @@ +error[E0308]: mismatched types + --> $DIR/feature-gate-type_changing_struct_update.rs:20:11 + | +LL | ..m1 + | ^^ expected struct `State2`, found struct `State1` + | + = note: expected struct `Machine` + found struct `Machine` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. From 2ed566559b5114848a6750971bcc0169a227b975 Mon Sep 17 00:00:00 2001 From: Jane Lusby Date: Fri, 22 Oct 2021 10:47:34 -0700 Subject: [PATCH 97/98] Apply suggestions from code review --- library/std/src/os/unix/process.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/library/std/src/os/unix/process.rs b/library/std/src/os/unix/process.rs index c3d9f3030093a..be82274b54a55 100644 --- a/library/std/src/os/unix/process.rs +++ b/library/std/src/os/unix/process.rs @@ -237,27 +237,27 @@ pub trait ExitStatusExt: Sealed { fn signal(&self) -> Option; /// If the process was terminated by a signal, says whether it dumped core. - #[stable(feature = "unix_process_wait_more", since = "1.57.0")] + #[stable(feature = "unix_process_wait_more", since = "1.58.0")] fn core_dumped(&self) -> bool; /// If the process was stopped by a signal, returns that signal. /// /// In other words, if `WIFSTOPPED`, this returns `WSTOPSIG`. This is only possible if the status came from /// a `wait` system call which was passed `WUNTRACED`, and was then converted into an `ExitStatus`. - #[stable(feature = "unix_process_wait_more", since = "1.57.0")] + #[stable(feature = "unix_process_wait_more", since = "1.58.0")] fn stopped_signal(&self) -> Option; /// Whether the process was continued from a stopped status. /// /// Ie, `WIFCONTINUED`. This is only possible if the status came from a `wait` system call /// which was passed `WCONTINUED`, and was then converted into an `ExitStatus`. - #[stable(feature = "unix_process_wait_more", since = "1.57.0")] + #[stable(feature = "unix_process_wait_more", since = "1.58.0")] fn continued(&self) -> bool; /// Returns the underlying raw `wait` status. /// /// The returned integer is a **wait status, not an exit status**. - #[stable(feature = "unix_process_wait_more", since = "1.57.0")] + #[stable(feature = "unix_process_wait_more", since = "1.58.0")] fn into_raw(self) -> i32; } From 98ed5548d7e604470ab9a97ffed4d9c12e424d83 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Thu, 30 Sep 2021 22:47:41 -0700 Subject: [PATCH 98/98] nice_region_error: Include lifetime placeholders in error output As you can see in src/test/ui/traits/self-without-lifetime-constraint.stderr you can get very confusing type names if you don't have this. Fixes #87763 --- .../trait_impl_difference.rs | 59 +++++++++++++++---- .../mismatched_trait_impl-2.stderr | 8 +-- .../mismatched_trait_impl.nll.stderr | 8 +-- .../mismatched_trait_impl.stderr | 8 +-- ...ime-mismatch-between-trait-and-impl.stderr | 8 +-- .../issue-75361-mismatched-impl.stderr | 8 +-- .../param-without-lifetime-constraint.stderr | 8 +-- .../self-without-lifetime-constraint.stderr | 8 +-- 8 files changed, 76 insertions(+), 39 deletions(-) diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs index ea9d0eae17e2c..b9e7ee12bc86d 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs @@ -9,10 +9,13 @@ use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; -use rustc_middle::ty::error::ExpectedFound; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::print::RegionHighlightMode; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor}; + use rustc_span::{MultiSpan, Span, Symbol}; +use std::ops::ControlFlow; + impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`. pub(super) fn try_report_impl_not_conforming_to_trait(&self) -> Option { @@ -69,6 +72,47 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { .tcx() .sess .struct_span_err(sp, "`impl` item signature doesn't match `trait` item signature"); + + // Mark all unnamed regions in the type with a number. + // This diagnostic is called in response to lifetime errors, so be informative. + struct HighlightBuilder<'tcx> { + highlight: RegionHighlightMode, + tcx: TyCtxt<'tcx>, + counter: usize, + } + + impl HighlightBuilder<'tcx> { + fn build(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> RegionHighlightMode { + let mut builder = + HighlightBuilder { highlight: RegionHighlightMode::default(), counter: 1, tcx }; + builder.visit_ty(ty); + builder.highlight + } + } + + impl<'tcx> ty::fold::TypeVisitor<'tcx> for HighlightBuilder<'tcx> { + fn tcx_for_anon_const_substs(&self) -> Option> { + Some(self.tcx) + } + + fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow { + if !r.has_name() && self.counter <= 3 { + self.highlight.highlighting_region(r, self.counter); + self.counter += 1; + } + r.super_visit_with(self) + } + } + + let expected_highlight = HighlightBuilder::build(self.tcx(), expected); + let expected = self + .infcx + .extract_inference_diagnostics_data(expected.into(), Some(expected_highlight)) + .name; + let found_highlight = HighlightBuilder::build(self.tcx(), found); + let found = + self.infcx.extract_inference_diagnostics_data(found.into(), Some(found_highlight)).name; + err.span_label(sp, &format!("found `{}`", found)); err.span_label(trait_sp, &format!("expected `{}`", expected)); @@ -96,15 +140,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { ); } - if let Some((expected, found)) = - self.infcx.expected_found_str_ty(ExpectedFound { expected, found }) - { - // Highlighted the differences when showing the "expected/found" note. - err.note_expected_found(&"", expected, &"", found); - } else { - // This fallback shouldn't be necessary, but let's keep it in just in case. - err.note(&format!("expected `{}`\n found `{}`", expected, found)); - } + err.note(&format!("expected `{}`\n found `{}`", expected, found)); + err.span_help( type_param_span, "the lifetime requirements from the `impl` do not correspond to the requirements in \ diff --git a/src/test/ui/in-band-lifetimes/mismatched_trait_impl-2.stderr b/src/test/ui/in-band-lifetimes/mismatched_trait_impl-2.stderr index b15efd6c770eb..0546b6b51b273 100644 --- a/src/test/ui/in-band-lifetimes/mismatched_trait_impl-2.stderr +++ b/src/test/ui/in-band-lifetimes/mismatched_trait_impl-2.stderr @@ -2,15 +2,15 @@ error: `impl` item signature doesn't match `trait` item signature --> $DIR/mismatched_trait_impl-2.rs:8:5 | LL | fn deref(&self) -> &dyn Trait { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&Struct) -> &dyn Trait` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&'1 Struct) -> &'1 (dyn Trait + '1)` | ::: $SRC_DIR/core/src/ops/deref.rs:LL:COL | LL | fn deref(&self) -> &Self::Target; - | --------------------------------- expected `fn(&Struct) -> &(dyn Trait + 'static)` + | --------------------------------- expected `fn(&'1 Struct) -> &'1 (dyn Trait + 'static)` | - = note: expected `fn(&Struct) -> &(dyn Trait + 'static)` - found `fn(&Struct) -> &dyn Trait` + = note: expected `fn(&'1 Struct) -> &'1 (dyn Trait + 'static)` + found `fn(&'1 Struct) -> &'1 (dyn Trait + '1)` = help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` = help: verify the lifetime relationships in the `trait` and `impl` between the `self` argument, the other inputs and its output diff --git a/src/test/ui/in-band-lifetimes/mismatched_trait_impl.nll.stderr b/src/test/ui/in-band-lifetimes/mismatched_trait_impl.nll.stderr index 149c2aeb958c0..c7a90c57add83 100644 --- a/src/test/ui/in-band-lifetimes/mismatched_trait_impl.nll.stderr +++ b/src/test/ui/in-band-lifetimes/mismatched_trait_impl.nll.stderr @@ -2,13 +2,13 @@ error: `impl` item signature doesn't match `trait` item signature --> $DIR/mismatched_trait_impl.rs:9:5 | LL | fn foo(&self, x: &'a u32, y: &u32) -> &'a u32; - | ---------------------------------------------- expected `fn(&i32, &'a u32, &u32) -> &'a u32` + | ---------------------------------------------- expected `fn(&'1 i32, &'a u32, &'2 u32) -> &'a u32` ... LL | fn foo(&self, x: &u32, y: &'a u32) -> &'a u32 { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&i32, &u32, &u32) -> &u32` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&'1 i32, &'2 u32, &'3 u32) -> &'3 u32` | - = note: expected `fn(&i32, &'a u32, &u32) -> &'a u32` - found `fn(&i32, &u32, &u32) -> &u32` + = note: expected `fn(&'1 i32, &'a u32, &'2 u32) -> &'a u32` + found `fn(&'1 i32, &'2 u32, &'3 u32) -> &'3 u32` = help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` = help: verify the lifetime relationships in the `trait` and `impl` between the `self` argument, the other inputs and its output diff --git a/src/test/ui/in-band-lifetimes/mismatched_trait_impl.stderr b/src/test/ui/in-band-lifetimes/mismatched_trait_impl.stderr index 9a0bd827850cf..84e5339122ead 100644 --- a/src/test/ui/in-band-lifetimes/mismatched_trait_impl.stderr +++ b/src/test/ui/in-band-lifetimes/mismatched_trait_impl.stderr @@ -2,13 +2,13 @@ error: `impl` item signature doesn't match `trait` item signature --> $DIR/mismatched_trait_impl.rs:9:5 | LL | fn foo(&self, x: &'a u32, y: &u32) -> &'a u32; - | ---------------------------------------------- expected `fn(&i32, &'a u32, &u32) -> &'a u32` + | ---------------------------------------------- expected `fn(&'1 i32, &'a u32, &'2 u32) -> &'a u32` ... LL | fn foo(&self, x: &u32, y: &'a u32) -> &'a u32 { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&i32, &u32, &u32) -> &u32` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&'1 i32, &'2 u32, &'3 u32) -> &'3 u32` | - = note: expected `fn(&i32, &'a u32, &u32) -> &'a u32` - found `fn(&i32, &u32, &u32) -> &u32` + = note: expected `fn(&'1 i32, &'a u32, &'2 u32) -> &'a u32` + found `fn(&'1 i32, &'2 u32, &'3 u32) -> &'3 u32` = help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` = help: verify the lifetime relationships in the `trait` and `impl` between the `self` argument, the other inputs and its output diff --git a/src/test/ui/lifetimes/lifetime-mismatch-between-trait-and-impl.stderr b/src/test/ui/lifetimes/lifetime-mismatch-between-trait-and-impl.stderr index 060e6954403c0..3040a8512ce1d 100644 --- a/src/test/ui/lifetimes/lifetime-mismatch-between-trait-and-impl.stderr +++ b/src/test/ui/lifetimes/lifetime-mismatch-between-trait-and-impl.stderr @@ -2,13 +2,13 @@ error: `impl` item signature doesn't match `trait` item signature --> $DIR/lifetime-mismatch-between-trait-and-impl.rs:6:5 | LL | fn foo<'a>(x: &i32, y: &'a i32) -> &'a i32; - | ------------------------------------------- expected `fn(&i32, &'a i32) -> &'a i32` + | ------------------------------------------- expected `fn(&'1 i32, &'a i32) -> &'a i32` ... LL | fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&i32, &i32) -> &i32` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&'1 i32, &'1 i32) -> &'1 i32` | - = note: expected `fn(&i32, &'a i32) -> &'a i32` - found `fn(&i32, &i32) -> &i32` + = note: expected `fn(&'1 i32, &'a i32) -> &'a i32` + found `fn(&'1 i32, &'1 i32) -> &'1 i32` = help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` = help: verify the lifetime relationships in the `trait` and `impl` between the `self` argument, the other inputs and its output diff --git a/src/test/ui/mismatched_types/issue-75361-mismatched-impl.stderr b/src/test/ui/mismatched_types/issue-75361-mismatched-impl.stderr index 9867addaf38e7..2a2c23c94212f 100644 --- a/src/test/ui/mismatched_types/issue-75361-mismatched-impl.stderr +++ b/src/test/ui/mismatched_types/issue-75361-mismatched-impl.stderr @@ -2,13 +2,13 @@ error: `impl` item signature doesn't match `trait` item signature --> $DIR/issue-75361-mismatched-impl.rs:18:3 | LL | fn adjacent_edges(&self) -> Box>; - | --------------------------------------------------------------------- expected `fn(&T) -> Box<(dyn MyTrait + 'static)>` + | --------------------------------------------------------------------- expected `fn(&'1 T) -> Box<(dyn MyTrait + 'static)>` ... LL | fn adjacent_edges(&self) -> Box + '_> { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&T) -> Box>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&'1 T) -> Box<(dyn MyTrait + '1)>` | - = note: expected `fn(&T) -> Box<(dyn MyTrait + 'static)>` - found `fn(&T) -> Box>` + = note: expected `fn(&'1 T) -> Box<(dyn MyTrait + 'static)>` + found `fn(&'1 T) -> Box<(dyn MyTrait + '1)>` help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` --> $DIR/issue-75361-mismatched-impl.rs:12:55 | diff --git a/src/test/ui/traits/param-without-lifetime-constraint.stderr b/src/test/ui/traits/param-without-lifetime-constraint.stderr index 763fb5186cc9a..118b2cf3ecd85 100644 --- a/src/test/ui/traits/param-without-lifetime-constraint.stderr +++ b/src/test/ui/traits/param-without-lifetime-constraint.stderr @@ -2,13 +2,13 @@ error: `impl` item signature doesn't match `trait` item signature --> $DIR/param-without-lifetime-constraint.rs:14:5 | LL | fn get_relation(&self) -> To; - | ----------------------------- expected `fn(&Article) -> &ProofReader` + | ----------------------------- expected `fn(&'1 Article) -> &'2 ProofReader` ... LL | fn get_relation(&self) -> &ProofReader { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&Article) -> &ProofReader` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&'1 Article) -> &'1 ProofReader` | - = note: expected `fn(&Article) -> &ProofReader` - found `fn(&Article) -> &ProofReader` + = note: expected `fn(&'1 Article) -> &'2 ProofReader` + found `fn(&'1 Article) -> &'1 ProofReader` help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` --> $DIR/param-without-lifetime-constraint.rs:10:31 | diff --git a/src/test/ui/traits/self-without-lifetime-constraint.stderr b/src/test/ui/traits/self-without-lifetime-constraint.stderr index 73b5aec022c60..85fada3b87c38 100644 --- a/src/test/ui/traits/self-without-lifetime-constraint.stderr +++ b/src/test/ui/traits/self-without-lifetime-constraint.stderr @@ -2,13 +2,13 @@ error: `impl` item signature doesn't match `trait` item signature --> $DIR/self-without-lifetime-constraint.rs:45:5 | LL | fn column_result(value: ValueRef<'_>) -> FromSqlResult; - | -------------------------------------------------------------------- expected `fn(ValueRef<'_>) -> Result<(&str, &&str), FromSqlError>` + | -------------------------------------------------------------------- expected `fn(ValueRef<'1>) -> Result<(&'2 str, &'1 &'2 str), FromSqlError>` ... LL | fn column_result(value: ValueRef<'_>) -> FromSqlResult<&str, &&str> { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(ValueRef<'_>) -> Result<(&str, &&str), FromSqlError>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(ValueRef<'1>) -> Result<(&'1 str, &'1 &'1 str), FromSqlError>` | - = note: expected `fn(ValueRef<'_>) -> Result<(&str, &&str), _>` - found `fn(ValueRef<'_>) -> Result<(&str, &&str), _>` + = note: expected `fn(ValueRef<'1>) -> Result<(&'2 str, &'1 &'2 str), FromSqlError>` + found `fn(ValueRef<'1>) -> Result<(&'1 str, &'1 &'1 str), FromSqlError>` help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` --> $DIR/self-without-lifetime-constraint.rs:41:60 |