Skip to content

Commit

Permalink
Clamp width settings to max_width before warning about exceeding it
Browse files Browse the repository at this point in the history
Within a macro scope, max_width is reduced, which can trigger warnings
if it is reduced below some other width setting (e.g. struct_lit_width.)
Width settings were already being clamped to max_width, but only after
the warning fired.  The order is now reversed.
  • Loading branch information
rs-sac committed Oct 7, 2024
1 parent 5f48fe9 commit f772d4c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
18 changes: 12 additions & 6 deletions src/config/config_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,18 +431,24 @@ macro_rules! create_config {
heuristic_value: usize,
config_key: &str,
| -> usize {
if !was_set {
return heuristic_value;
}
if override_value > max_width {
let value = if !was_set {
heuristic_value
} else {
override_value
};

let value = value.min(max_width);

if value > max_width {
eprintln!(
"`{0}` cannot have a value that exceeds `max_width`. \
`{0}` will be set to the same value as `max_width`",
config_key,
);
return max_width;
max_width
} else {
value
}
override_value
};

let fn_call_width = get_width_value(
Expand Down
23 changes: 19 additions & 4 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,21 @@ mod test {
assert_eq!(config.was_set().verbose(), false);
}

#[test]
fn test_clamp_to_max_width() {
let toml = r#"
max_width = 100
struct_lit_width = 200
"#;
let mut config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
assert_eq!(config.struct_lit_width(), config.max_width());

// simulate entering a macro scope
let new = config.max_width() - 4;
config.set().max_width(new);
assert_eq!(config.struct_lit_width(), config.max_width());
}

const PRINT_DOCS_STABLE_OPTION: &str = "stable_option <boolean> Default: false";
const PRINT_DOCS_UNSTABLE_OPTION: &str = "unstable_option <boolean> Default: false (unstable)";
const PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION: &str =
Expand Down Expand Up @@ -1049,10 +1064,10 @@ make_backup = false
max_width = 100
"#;
let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
assert_eq!(config.array_width(), usize::MAX);
assert_eq!(config.attr_fn_like_width(), usize::MAX);
assert_eq!(config.chain_width(), usize::MAX);
assert_eq!(config.fn_call_width(), usize::MAX);
assert_eq!(config.array_width(), config.max_width());
assert_eq!(config.attr_fn_like_width(), config.max_width());
assert_eq!(config.chain_width(), config.max_width());
assert_eq!(config.fn_call_width(), config.max_width());
assert_eq!(config.single_line_if_else_max_width(), 0);
assert_eq!(config.struct_lit_width(), 0);
assert_eq!(config.struct_variant_width(), 0);
Expand Down

0 comments on commit f772d4c

Please sign in to comment.