Skip to content

Commit

Permalink
Merge branch 'master' into surrounding-empty-lines
Browse files Browse the repository at this point in the history
  • Loading branch information
richardpringle authored Jan 2, 2024
2 parents 8b6edcf + 85e21fa commit 9b7251c
Show file tree
Hide file tree
Showing 41 changed files with 338 additions and 145 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ diff = "0.1"
dirs = "4.0"
getopts = "0.2"
ignore = "0.4"
itertools = "0.10"
itertools = "0.11"
lazy_static = "1.4"
regex = "1.7"
serde = { version = "1.0.160", features = ["derive"] }
Expand Down
12 changes: 10 additions & 2 deletions Configurations.md
Original file line number Diff line number Diff line change
Expand Up @@ -1111,7 +1111,7 @@ See also [`format_macro_bodies`](#format_macro_bodies).

## `format_macro_bodies`

Format the bodies of macros.
Format the bodies of declarative macro definitions.

- **Default value**: `true`
- **Possible values**: `true`, `false`
Expand Down Expand Up @@ -1261,12 +1261,20 @@ Control the case of the letters in hexadecimal literal values

## `hide_parse_errors`

Do not show parse errors if the parser failed to parse files.
This option is deprecated and has been renamed to `show_parse_errors` to avoid confusion around the double negative default of `hide_parse_errors=false`.

- **Default value**: `false`
- **Possible values**: `true`, `false`
- **Stable**: No (tracking issue: [#3390](https://github.com/rust-lang/rustfmt/issues/3390))

## `show_parse_errors`

Show parse errors if the parser failed to parse files.

- **Default value**: `true`
- **Possible values**: `true`, `false`
- **Stable**: No (tracking issue: [#5977](https://github.com/rust-lang/rustfmt/issues/5977))

## `ignore`

Skip formatting files and directories that match the specified pattern.
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[toolchain]
channel = "nightly-2023-10-22"
channel = "nightly-2023-12-28"
components = ["llvm-tools", "rustc-dev"]
38 changes: 26 additions & 12 deletions src/closures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub(crate) fn rewrite_closure(
binder: &ast::ClosureBinder,
constness: ast::Const,
capture: ast::CaptureBy,
is_async: &ast::Async,
coroutine_kind: &Option<ast::CoroutineKind>,
movability: ast::Movability,
fn_decl: &ast::FnDecl,
body: &ast::Expr,
Expand All @@ -40,7 +40,16 @@ pub(crate) fn rewrite_closure(
debug!("rewrite_closure {:?}", body);

let (prefix, extra_offset) = rewrite_closure_fn_decl(
binder, constness, capture, is_async, movability, fn_decl, body, span, context, shape,
binder,
constness,
capture,
coroutine_kind,
movability,
fn_decl,
body,
span,
context,
shape,
)?;
// 1 = space between `|...|` and body.
let body_shape = shape.offset_left(extra_offset)?;
Expand Down Expand Up @@ -188,7 +197,7 @@ fn rewrite_closure_expr(
fn allow_multi_line(expr: &ast::Expr) -> bool {
match expr.kind {
ast::ExprKind::Match(..)
| ast::ExprKind::Async(..)
| ast::ExprKind::Gen(..)
| ast::ExprKind::Block(..)
| ast::ExprKind::TryBlock(..)
| ast::ExprKind::Loop(..)
Expand Down Expand Up @@ -233,7 +242,7 @@ fn rewrite_closure_fn_decl(
binder: &ast::ClosureBinder,
constness: ast::Const,
capture: ast::CaptureBy,
asyncness: &ast::Async,
coroutine_kind: &Option<ast::CoroutineKind>,
movability: ast::Movability,
fn_decl: &ast::FnDecl,
body: &ast::Expr,
Expand Down Expand Up @@ -263,16 +272,21 @@ fn rewrite_closure_fn_decl(
} else {
""
};
let is_async = if asyncness.is_async() { "async " } else { "" };
let mover = if capture == ast::CaptureBy::Value {
let coro = match coroutine_kind {
Some(ast::CoroutineKind::Async { .. }) => "async ",
Some(ast::CoroutineKind::Gen { .. }) => "gen ",
Some(ast::CoroutineKind::AsyncGen { .. }) => "async gen ",
None => "",
};
let mover = if matches!(capture, ast::CaptureBy::Value { .. }) {
"move "
} else {
""
};
// 4 = "|| {".len(), which is overconservative when the closure consists of
// a single expression.
let nested_shape = shape
.shrink_left(binder.len() + const_.len() + immovable.len() + is_async.len() + mover.len())?
.shrink_left(binder.len() + const_.len() + immovable.len() + coro.len() + mover.len())?
.sub_width(4)?;

// 1 = |
Expand Down Expand Up @@ -310,7 +324,7 @@ fn rewrite_closure_fn_decl(
.tactic(tactic)
.preserve_newline(true);
let list_str = write_list(&item_vec, &fmt)?;
let mut prefix = format!("{binder}{const_}{immovable}{is_async}{mover}|{list_str}|");
let mut prefix = format!("{binder}{const_}{immovable}{coro}{mover}|{list_str}|");

if !ret_str.is_empty() {
if prefix.contains('\n') {
Expand Down Expand Up @@ -339,7 +353,7 @@ pub(crate) fn rewrite_last_closure(
ref binder,
constness,
capture_clause,
ref asyncness,
ref coroutine_kind,
movability,
ref fn_decl,
ref body,
Expand All @@ -360,7 +374,7 @@ pub(crate) fn rewrite_last_closure(
binder,
constness,
capture_clause,
asyncness,
coroutine_kind,
movability,
fn_decl,
body,
Expand Down Expand Up @@ -434,7 +448,7 @@ fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bo

fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
match expr.kind {
ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop { .. } => true,
ast::ExprKind::Loop(..) if version == Version::Two => true,
ast::ExprKind::AddrOf(_, _, ref expr)
| ast::ExprKind::Try(ref expr)
Expand All @@ -459,7 +473,7 @@ fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
| ast::ExprKind::Block(..)
| ast::ExprKind::While(..)
| ast::ExprKind::Loop(..)
| ast::ExprKind::ForLoop(..)
| ast::ExprKind::ForLoop { .. }
| ast::ExprKind::TryBlock(..) => false,
_ => true,
}
Expand Down
8 changes: 2 additions & 6 deletions src/comment.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Formatting and tools for comments.

use std::{self, borrow::Cow, iter};
use std::{borrow::Cow, iter};

use itertools::{multipeek, MultiPeek};
use lazy_static::lazy_static;
Expand Down Expand Up @@ -173,10 +173,7 @@ pub(crate) fn combine_strs_with_missing_comments(
) -> Option<String> {
trace!(
"combine_strs_with_missing_comments `{}` `{}` {:?} {:?}",
prev_str,
next_str,
span,
shape
prev_str, next_str, span, shape
);

let mut result =
Expand Down Expand Up @@ -1847,7 +1844,6 @@ fn remove_comment_header(comment: &str) -> &str {
#[cfg(test)]
mod test {
use super::*;
use crate::shape::{Indent, Shape};

#[test]
fn char_classes() {
Expand Down
20 changes: 18 additions & 2 deletions src/config/config_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ macro_rules! create_config {
| "chain_width" => self.0.set_heuristics(),
"merge_imports" => self.0.set_merge_imports(),
"fn_args_layout" => self.0.set_fn_args_layout(),
"hide_parse_errors" => self.0.set_hide_parse_errors(),
&_ => (),
}
}
Expand Down Expand Up @@ -184,6 +185,7 @@ macro_rules! create_config {
self.set_ignore(dir);
self.set_merge_imports();
self.set_fn_args_layout();
self.set_hide_parse_errors();
self
}

Expand Down Expand Up @@ -278,19 +280,21 @@ macro_rules! create_config {
| "chain_width" => self.set_heuristics(),
"merge_imports" => self.set_merge_imports(),
"fn_args_layout" => self.set_fn_args_layout(),
"hide_parse_errors" => self.set_hide_parse_errors(),
&_ => (),
}
}

#[allow(unreachable_pub)]
pub fn is_hidden_option(name: &str) -> bool {
const HIDE_OPTIONS: [&str; 6] = [
const HIDE_OPTIONS: [&str; 7] = [
"verbose",
"verbose_diff",
"file_lines",
"width_heuristics",
"merge_imports",
"fn_args_layout"
"fn_args_layout",
"hide_parse_errors"
];
HIDE_OPTIONS.contains(&name)
}
Expand Down Expand Up @@ -461,6 +465,18 @@ macro_rules! create_config {
}
}

fn set_hide_parse_errors(&mut self) {
if self.was_set().hide_parse_errors() {
eprintln!(
"Warning: the `hide_parse_errors` option is deprecated. \
Use `show_parse_errors` instead"
);
if !self.was_set().show_parse_errors() {
self.show_parse_errors.2 = self.hide_parse_errors();
}
}
}

#[allow(unreachable_pub)]
/// Returns `true` if the config key was explicitly set and is the default value.
pub fn is_default(&self, key: &str) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion src/config/file_lines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::path::PathBuf;
use std::{cmp, fmt, iter, str};

use rustc_data_structures::sync::Lrc;
use rustc_span::{self, SourceFile};
use rustc_span::SourceFile;
use serde::{ser, Deserialize, Deserializer, Serialize, Serializer};
use serde_json as json;
use thiserror::Error;
Expand Down
18 changes: 13 additions & 5 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::cell::Cell;
use std::default::Default;
use std::fs::File;
use std::io::{Error, ErrorKind, Read};
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -27,6 +26,7 @@ pub(crate) mod file_lines;
#[allow(unreachable_pub)]
pub(crate) mod lists;
pub(crate) mod macro_names;
pub(crate) mod style_edition;

// This macro defines configuration options used in rustfmt. Each option
// is defined as follows:
Expand Down Expand Up @@ -74,7 +74,7 @@ create_config! {
format_strings: bool, false, false, "Format string literals where necessary";
format_macro_matchers: bool, false, false,
"Format the metavariable matching patterns in macros";
format_macro_bodies: bool, true, false, "Format the bodies of macros";
format_macro_bodies: bool, true, false, "Format the bodies of declarative macro definitions";
skip_macro_invocations: MacroSelectors, MacroSelectors::default(), false,
"Skip formatting the bodies of macros invoked with the following names.";
hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false,
Expand Down Expand Up @@ -172,7 +172,8 @@ create_config! {
"Enables unstable features. Only available on nightly channel";
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";
hide_parse_errors: bool, false, false, "(deprecated: use show_parse_errors instead)";
show_parse_errors: bool, true, false, "Show errors from the parser (unstable)";
error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
error_on_unformatted: bool, false, false,
"Error if unable to get comments or string literals within max_width, \
Expand Down Expand Up @@ -207,6 +208,7 @@ impl PartialConfig {
cloned.print_misformatted_file_names = None;
cloned.merge_imports = None;
cloned.fn_args_layout = None;
cloned.hide_parse_errors = None;

::toml::to_string(&cloned).map_err(ToTomlError)
}
Expand Down Expand Up @@ -459,6 +461,13 @@ mod test {
fn_params_layout: Density, Density::Tall, true,
"Control the layout of parameters in a function signatures.";

// hide_parse_errors renamed to show_parse_errors
hide_parse_errors: bool, false, false,
"(deprecated: use show_parse_errors instead)";
show_parse_errors: bool, true, false,
"Show errors from the parser (unstable)";


// Width Heuristics
use_small_heuristics: Heuristics, Heuristics::Default, true,
"Whether to use different formatting for items and \
Expand Down Expand Up @@ -685,7 +694,7 @@ required_version = "{}"
unstable_features = false
disable_all_formatting = false
skip_children = false
hide_parse_errors = false
show_parse_errors = true
error_on_line_overflow = false
error_on_unformatted = false
ignore = []
Expand Down Expand Up @@ -1021,7 +1030,6 @@ make_backup = false
#[cfg(test)]
mod partially_unstable_option {
use super::mock::{Config, PartiallyUnstableOption};
use super::*;

/// From the command line, we can override with a stable variant.
#[test]
Expand Down
26 changes: 26 additions & 0 deletions src/config/options.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(unused_imports)]

use std::collections::{hash_set, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -468,3 +470,27 @@ pub enum MatchArmLeadingPipe {
/// Preserve any existing leading pipes
Preserve,
}

/// Defines the default values for each config according to [the style guide].
/// rustfmt output may differ between style editions.
///
/// [the style guide]: https://doc.rust-lang.org/nightly/style-guide/
#[config_type]
pub enum StyleEdition {
#[value = "2015"]
#[doc_hint = "2015"]
/// [Edition 2015]()
Edition2015,
#[value = "2018"]
#[doc_hint = "2018"]
/// [Edition 2018]()
Edition2018,
#[value = "2021"]
#[doc_hint = "2021"]
/// [Edition 2021]()
Edition2021,
#[value = "2024"]
#[doc_hint = "2024"]
/// [Edition 2024]().
Edition2024,
}
Loading

0 comments on commit 9b7251c

Please sign in to comment.