Skip to content
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

Backport some changes #4990

Merged
merged 2 commits into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
16 changes: 16 additions & 0 deletions Configurations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -1047,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`

Expand Down
5 changes: 5 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -136,6 +138,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";
Expand Down Expand Up @@ -569,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
Expand Down Expand Up @@ -604,6 +608,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
Expand Down
11 changes: 11 additions & 0 deletions src/config/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
33 changes: 32 additions & 1 deletion src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1168,6 +1168,7 @@ pub(crate) fn rewrite_literal(
) -> Option<String> {
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(),
Expand Down Expand Up @@ -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<String> {
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<SeparatorTactic> {
if context.inside_macro() {
if span_ends_with_comma(context, span) {
Expand Down
9 changes: 8 additions & 1 deletion src/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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
Expand Down Expand Up @@ -103,7 +105,12 @@ fn format_project<T: FormatHandler>(
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;
}
Expand Down
7 changes: 7 additions & 0 deletions src/formatting/generated.rs
Original file line number Diff line number Diff line change
@@ -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"))
}
6 changes: 6 additions & 0 deletions src/syntux/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<rustc_span::SourceFile> {
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();

Expand Down
2 changes: 1 addition & 1 deletion src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
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| {
(
Expand Down
8 changes: 8 additions & 0 deletions tests/source/configs/format_generated_files/false.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// @generated
// rustfmt-format_generated_files: false

fn main()
{
println!("hello, world")
;
}
8 changes: 8 additions & 0 deletions tests/source/configs/format_generated_files/true.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// @generated
// rustfmt-format_generated_files: true

fn main()
{
println!("hello, world")
;
}
5 changes: 5 additions & 0 deletions tests/source/hex_literal_lower.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// rustfmt-hex_literal_case: Lower
fn main() {
let h1 = 0xCAFE_5EA7;
let h2 = 0xCAFE_F00Du32;
}
5 changes: 5 additions & 0 deletions tests/source/hex_literal_upper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// rustfmt-hex_literal_case: Upper
fn main() {
let h1 = 0xCaFE_5ea7;
let h2 = 0xCAFE_F00Du32;
}
8 changes: 8 additions & 0 deletions tests/target/configs/format_generated_files/false.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// @generated
// rustfmt-format_generated_files: false

fn main()
{
println!("hello, world")
;
}
6 changes: 6 additions & 0 deletions tests/target/configs/format_generated_files/true.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// @generated
// rustfmt-format_generated_files: true

fn main() {
println!("hello, world");
}
5 changes: 5 additions & 0 deletions tests/target/hex_literal_lower.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// rustfmt-hex_literal_case: Lower
fn main() {
let h1 = 0xcafe_5ea7;
let h2 = 0xcafe_f00du32;
}
5 changes: 5 additions & 0 deletions tests/target/hex_literal_preserve.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// rustfmt-hex_literal_case: Preserve
fn main() {
let h1 = 0xcAfE_5Ea7;
let h2 = 0xCaFe_F00du32;
}
5 changes: 5 additions & 0 deletions tests/target/hex_literal_upper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// rustfmt-hex_literal_case: Upper
fn main() {
let h1 = 0xCAFE_5EA7;
let h2 = 0xCAFE_F00Du32;
}