Skip to content

sync rustfmt subtree #90680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 29 commits into from
Nov 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
2b41b6d
Merge commit 'efa8f5521d3813cc897ba29ea0ef98c7aef66bb6' into rustfmt-…
calebcartwright Oct 20, 2021
606c7d4
ensure cargo-fmt tests are excluded from root workspace
calebcartwright Oct 20, 2021
051e2b4
fix doc issue in rustfmt
calebcartwright Oct 21, 2021
599b2fd
Add One option to group_imports (#4966)
Heliozoa Oct 23, 2021
757da8c
Merge remote-tracking branch 'upstream/master' into another-subtree-sync
calebcartwright Oct 24, 2021
50369f5
Merge pull request #5043 from calebcartwright/another-subtree-sync
calebcartwright Oct 24, 2021
d454e81
Add rustdoc CI check
ytmimi Oct 23, 2021
c493ee4
fix clippy::needless_borrow
matthiaskrgr Oct 23, 2021
0b8ffac
fix a bunch of the other clippy warnings that look interesting
matthiaskrgr Oct 23, 2021
8b766f3
Remove legacy-rustfmt.toml (#4169)
topecongiro May 11, 2020
bc46af9
Retain trailing comments in module when using rustfmt::skip attribute
ytmimi Oct 19, 2021
ed5a025
refactor: minor parser cleanup
calebcartwright Oct 30, 2021
54b1e0b
README grammar fix (#3926)
enterprisey Nov 14, 2019
a24ed3c
Fix MSRV
Nov 25, 2020
a4d7011
Document RUSTFMT environment variable (#4464)
MonliH Oct 11, 2020
5ce82e1
Prevent trailing whitespace in where clause bound predicate
ytmimi Oct 8, 2021
c1eab15
Use a custom env var for log settings intead of default RUST_LOG
peterjoel Oct 7, 2020
bd86077
Remove grave accent that shouldn't be there
wooster0 Nov 1, 2021
e75c4d7
ci: drop appveyor
calebcartwright Nov 4, 2021
a5f8505
fix: handle external mods imported via external->inline load hierarchy
calebcartwright Nov 4, 2021
9027db9
Update IntelliJ Integration (#4238)
dima74 Jun 6, 2020
4d50e7c
Put empty trait braces on same line if possible
mujpao Nov 2, 2021
19c5c74
refactor: dedupe & simplify ty alias formatting
calebcartwright Nov 6, 2021
bf3c52f
ast: Fix naming conventions in AST structures
petrochenkov Nov 7, 2021
e4472d3
refactor: dedupe associated item visitation
calebcartwright Nov 6, 2021
4621915
Merge remote-tracking branch 'upstream/master' into rustup-2021-11-s1
calebcartwright Nov 7, 2021
31bc54a
chore: bump toolchain
calebcartwright Nov 8, 2021
ea199ba
Merge pull request #5070 from calebcartwright/rustup-2021-11-s1
calebcartwright Nov 8, 2021
30fb124
Merge commit 'ea199bacef07213dbe008841b89c450e3bf0c638' into rustfmt-…
calebcartwright Nov 8, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/tools/rustfmt/.github/workflows/rustdoc_check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: rustdoc check
on:
push:
branches:
- master
pull_request:

jobs:
rustdoc_check:
runs-on: ubuntu-latest
name: rustdoc check
steps:
- name: checkout
uses: actions/checkout@v2

- 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 x86_64-unknown-linux-gnu

- name: document rustfmt
env:
RUSTDOCFLAGS: --document-private-items --enable-index-page --show-type-layout --generate-link-to-definition -Zunstable-options -Dwarnings
run: cargo doc -Zskip-rustdoc-fingerprint --no-deps -p rustfmt-nightly -p rustfmt-config_proc_macro
19 changes: 18 additions & 1 deletion src/tools/rustfmt/Configurations.md
Original file line number Diff line number Diff line change
Expand Up @@ -2062,7 +2062,7 @@ use sit;
Controls the strategy for how imports are grouped together.

- **Default value**: `Preserve`
- **Possible values**: `Preserve`, `StdExternalCrate`
- **Possible values**: `Preserve`, `StdExternalCrate`, `One`
- **Stable**: No

#### `Preserve` (default):
Expand Down Expand Up @@ -2108,6 +2108,23 @@ use super::update::convert_publish_payload;
use crate::models::Event;
```

#### `One`:

Discard existing import groups, and create a single group for everything

```rust
use super::schema::{Context, Payload};
use super::update::convert_publish_payload;
use crate::models::Event;
use alloc::alloc::Layout;
use broker::database::PooledConnection;
use chrono::Utc;
use core::f32;
use juniper::{FieldError, FieldResult};
use std::sync::Arc;
use uuid::Uuid;
```

## `reorder_modules`

Reorder `mod` declarations alphabetically in group.
Expand Down
2 changes: 1 addition & 1 deletion src/tools/rustfmt/Contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ example, the `issue-1111.rs` test file is configured by the file
## Debugging

Some `rewrite_*` methods use the `debug!` macro for printing useful information.
These messages can be printed by using the environment variable `RUST_LOG=rustfmt=DEBUG`.
These messages can be printed by using the environment variable `RUSTFMT_LOG=rustfmt=DEBUG`.
These traces can be helpful in understanding which part of the code was used
and get a better grasp on the execution flow.

Expand Down
23 changes: 21 additions & 2 deletions src/tools/rustfmt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ cargo +nightly fmt

## Limitations

Rustfmt tries to work on as much Rust code as possible, sometimes, the code
Rustfmt tries to work on as much Rust code as possible. Sometimes, the code
doesn't even need to compile! As we approach a 1.0 release we are also looking
to limit areas of instability; in particular, post-1.0, the formatting of most
code should not change as Rustfmt improves. However, there are some things that
Expand Down Expand Up @@ -102,6 +102,25 @@ read data from stdin. Alternatively, you can use `cargo fmt` to format all
binary and library targets of your crate.

You can run `rustfmt --help` for information about available arguments.
The easiest way to run rustfmt against a project is with `cargo fmt`. `cargo fmt` works on both
single-crate projects and [cargo workspaces](https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html).
Please see `cargo fmt --help` for usage information.

You can specify the path to your own `rustfmt` binary for cargo to use by setting the`RUSTFMT`
environment variable. This was added in v1.4.22, so you must have this version or newer to leverage this feature (`cargo fmt --version`)

### Running `rustfmt` directly

To format individual files or arbitrary codes from stdin, the `rustfmt` binary should be used. Some
examples follow:

- `rustfmt lib.rs main.rs` will format "lib.rs" and "main.rs" in place
- `rustfmt` will read a code from stdin and write formatting to stdout
- `echo "fn main() {}" | rustfmt` would emit "fn main() {}".

For more information, including arguments and emit options, see `rustfmt --help`.

### Verifying code is formatted

When running with `--check`, Rustfmt will exit with `0` if Rustfmt would not
make any formatting changes to the input, and `1` if Rustfmt would make changes.
Expand Down Expand Up @@ -129,7 +148,7 @@ rustfmt to exit with an error code if the input is not formatted correctly.
It will also print any found differences. (Older versions of Rustfmt don't
support `--check`, use `--write-mode diff`).

A minimal Travis setup could look like this (requires Rust 1.24.0 or greater):
A minimal Travis setup could look like this (requires Rust 1.31.0 or greater):

```yaml
language: rust
Expand Down
8 changes: 0 additions & 8 deletions src/tools/rustfmt/appveyor.yml

This file was deleted.

23 changes: 16 additions & 7 deletions src/tools/rustfmt/intellij.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,28 @@
## Installation

- Install [CLion](https://www.jetbrains.com/clion/), [IntelliJ Ultimate or CE](https://www.jetbrains.com/idea/) through the direct download link or using the [JetBrains Toolbox](https://www.jetbrains.com/toolbox/).
CLion provides a built-in debugger interface but its not free like IntelliJ CE - which does not provide the debugger interface. (IntelliJ seems to lack the toolchain for that, see this discussion [intellij-rust/issues/535](https://github.com/intellij-rust/intellij-rust/issues/535))
- Install the [Rust Plugin](https://intellij-rust.github.io/) by navigating to File -> Settings -> Plugins and press "Install JetBrains Plugin"
![plugins](https://user-images.githubusercontent.com/1133787/47240861-f40af680-d3e9-11e8-9b82-cdd5c8d5f5b8.png)
CLion and IntelliJ Ultimate [provide a built-in debugger interface](https://github.com/intellij-rust/intellij-rust#compatible-ides) but they are not free like IntelliJ CE.

- Install the [Rust Plugin](https://intellij-rust.github.io/) by navigating to File Settings Plugins and searching the plugin in the Marketplace
![plugins](https://user-images.githubusercontent.com/6505554/83944518-6f1e5c00-a81d-11ea-9c35-e16948811ba8.png)

- Press "Install" on the rust plugin
![install rust](https://user-images.githubusercontent.com/1133787/47240803-c0c86780-d3e9-11e8-9265-22f735e4d7ed.png)
- Press "Install" on the Rust plugin
![install rust](https://user-images.githubusercontent.com/6505554/83944533-82c9c280-a81d-11ea-86b3-ee2e31bc7d12.png)

- Restart CLion/IntelliJ

## Configuration

- Open the settings window (File -> Settings) and search for "reformat"
### Run Rustfmt on save

- Open Rustfmt settings (File → Settings → Languages & Frameworks → Rust → Rustfmt) and enable "Run rustfmt on Save"
![run_rustfmt_on_save](https://user-images.githubusercontent.com/6505554/83944610-3468f380-a81e-11ea-9c34-0cbd18dd4969.png)

- IntellJ uses autosave, so now your files will always be formatted according to rustfmt. Alternatively you can use Ctrl+S to reformat file manually

### Bind shortcut to "Reformat File with Rustfmt" action

- Open the settings window (File → Settings) and search for "reformat"
![keymap](https://user-images.githubusercontent.com/1133787/47240922-2ae10c80-d3ea-11e8-9d8f-c798d9749240.png)
- Right-click on "Reformat File with Rustfmt" and assign a keyboard shortcut

Expand Down
2 changes: 0 additions & 2 deletions src/tools/rustfmt/legacy-rustfmt.toml

This file was deleted.

2 changes: 1 addition & 1 deletion src/tools/rustfmt/rust-toolchain
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[toolchain]
channel = "nightly-2021-10-20"
channel = "nightly-2021-11-08"
components = ["rustc-dev"]
4 changes: 2 additions & 2 deletions src/tools/rustfmt/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ impl Rewrite for [ast::Attribute] {
if next.is_doc_comment() {
let snippet = context.snippet(missing_span);
let (_, mlb) = has_newlines_before_after_comment(snippet);
result.push_str(&mlb);
result.push_str(mlb);
}
}
result.push('\n');
Expand Down Expand Up @@ -484,7 +484,7 @@ impl Rewrite for [ast::Attribute] {
if next.is_doc_comment() {
let snippet = context.snippet(missing_span);
let (_, mlb) = has_newlines_before_after_comment(snippet);
result.push_str(&mlb);
result.push_str(mlb);
}
}
result.push('\n');
Expand Down
2 changes: 1 addition & 1 deletion src/tools/rustfmt/src/attr/doc_comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ mod tests {
) {
assert_eq!(
expected_comment,
format!("{}", DocCommentFormatter::new(&literal, style))
format!("{}", DocCommentFormatter::new(literal, style))
);
}
}
2 changes: 1 addition & 1 deletion src/tools/rustfmt/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::rustfmt::{
};

fn main() {
env_logger::init();
env_logger::Builder::from_env("RUSTFMT_LOG").init();
let opts = make_opts();

let exit_code = match execute(&opts) {
Expand Down
6 changes: 3 additions & 3 deletions src/tools/rustfmt/src/cargo-fmt/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,12 +401,12 @@ fn get_targets_root_only(

fn get_targets_recursive(
manifest_path: Option<&Path>,
mut targets: &mut BTreeSet<Target>,
targets: &mut BTreeSet<Target>,
visited: &mut BTreeSet<String>,
) -> Result<(), io::Error> {
let metadata = get_cargo_metadata(manifest_path)?;
for package in &metadata.packages {
add_targets(&package.targets, &mut targets);
add_targets(&package.targets, targets);

// Look for local dependencies using information available since cargo v1.51
// It's theoretically possible someone could use a newer version of rustfmt with
Expand All @@ -427,7 +427,7 @@ fn get_targets_recursive(
.any(|p| p.manifest_path.eq(&manifest_path))
{
visited.insert(dependency.name.to_owned());
get_targets_recursive(Some(&manifest_path), &mut targets, visited)?;
get_targets_recursive(Some(&manifest_path), targets, visited)?;
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/tools/rustfmt/src/chains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,7 @@ impl<'a> ChainFormatterShared<'a> {
} else {
self.rewrites
.iter()
.map(|rw| utils::unicode_str_width(&rw))
.map(|rw| utils::unicode_str_width(rw))
.sum()
} + last.tries;
let one_line_budget = if self.child_count == 1 {
Expand Down Expand Up @@ -673,7 +673,7 @@ impl<'a> ChainFormatterShared<'a> {
ChainItemKind::Comment(_, CommentPosition::Top) => result.push_str(&connector),
_ => result.push_str(&connector),
}
result.push_str(&rewrite);
result.push_str(rewrite);
}

Some(result)
Expand Down
18 changes: 9 additions & 9 deletions src/tools/rustfmt/src/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ impl CodeBlockAttribute {
/// 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(",") {
for attribute in attributes.split(',') {
match attribute.trim() {
"" | "rust" | "should_panic" | "no_run" | "edition2015" | "edition2018"
| "edition2021" => (),
Expand Down Expand Up @@ -563,7 +563,7 @@ impl<'a> CommentRewrite<'a> {
result.push_str(line);
result.push_str(match iter.peek() {
Some(next_line) if next_line.is_empty() => sep.trim_end(),
Some(..) => &sep,
Some(..) => sep,
None => "",
});
}
Expand Down Expand Up @@ -622,7 +622,7 @@ impl<'a> CommentRewrite<'a> {
let is_last = i == count_newlines(orig);

if let Some(ref mut ib) = self.item_block {
if ib.add_line(&line) {
if ib.add_line(line) {
return false;
}
self.is_prev_line_multi_line = false;
Expand Down Expand Up @@ -684,8 +684,8 @@ impl<'a> CommentRewrite<'a> {
self.item_block = None;
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);
} else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(line) {
let ib = ItemizedBlock::new(line);
self.item_block = Some(ib);
return false;
}
Expand Down Expand Up @@ -941,7 +941,7 @@ fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a s
{
(&line[4..], true)
} else if let CommentStyle::Custom(opener) = *style {
if let Some(ref stripped) = line.strip_prefix(opener) {
if let Some(stripped) = line.strip_prefix(opener) {
(stripped, true)
} else {
(&line[opener.trim_end().len()..], false)
Expand Down Expand Up @@ -1384,7 +1384,7 @@ impl<'a> Iterator for LineClasses<'a> {
None => unreachable!(),
};

while let Some((kind, c)) = self.base.next() {
for (kind, c) in self.base.by_ref() {
// needed to set the kind of the ending character on the last line
self.kind = kind;
if c == '\n' {
Expand Down Expand Up @@ -1570,7 +1570,7 @@ pub(crate) fn recover_comment_removed(
context.parse_sess.span_to_filename(span),
vec![FormattingError::from_span(
span,
&context.parse_sess,
context.parse_sess,
ErrorKind::LostComment,
)],
);
Expand Down Expand Up @@ -1675,7 +1675,7 @@ impl<'a> Iterator for CommentReducer<'a> {
fn remove_comment_header(comment: &str) -> &str {
if comment.starts_with("///") || comment.starts_with("//!") {
&comment[3..]
} else if let Some(ref stripped) = comment.strip_prefix("//") {
} else if let Some(stripped) = comment.strip_prefix("//") {
stripped
} else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
|| comment.starts_with("/*!")
Expand Down
4 changes: 3 additions & 1 deletion src/tools/rustfmt/src/config/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub enum NewlineStyle {
Windows,
/// Force CR (`\n).
Unix,
/// `\r\n` in Windows, `\n`` on other platforms.
/// `\r\n` in Windows, `\n` on other platforms.
Native,
}

Expand Down Expand Up @@ -112,6 +112,8 @@ pub enum GroupImportsTactic {
/// 2. other imports
/// 3. `self` / `crate` / `super` imports
StdExternalCrate,
/// Discard existing groups, and create a single group for everything
One,
}

#[config_type]
Expand Down
4 changes: 2 additions & 2 deletions src/tools/rustfmt/src/emitter/checkstyle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,15 +121,15 @@ mod tests {
format!(r#"<file name="{}">"#, bin_file),
format!(
r#"<error line="2" severity="warning" message="Should be `{}`" />"#,
XmlEscaped(&r#" println!("Hello, world!");"#),
XmlEscaped(r#" println!("Hello, world!");"#),
),
String::from("</file>"),
];
let exp_lib_xml = vec![
format!(r#"<file name="{}">"#, lib_file),
format!(
r#"<error line="2" severity="warning" message="Should be `{}`" />"#,
XmlEscaped(&r#" println!("Greetings!");"#),
XmlEscaped(r#" println!("Greetings!");"#),
),
String::from("</file>"),
];
Expand Down
2 changes: 1 addition & 1 deletion src/tools/rustfmt/src/emitter/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl Emitter for DiffEmitter {
}: FormattedFile<'_>,
) -> Result<EmitterResult, io::Error> {
const CONTEXT_SIZE: usize = 3;
let mismatch = make_diff(&original_text, formatted_text, CONTEXT_SIZE);
let mismatch = make_diff(original_text, formatted_text, CONTEXT_SIZE);
let has_diff = !mismatch.is_empty();

if has_diff {
Expand Down
Loading