Skip to main content

rustfmt_nightly/config/
mod.rs

1use std::cell::Cell;
2use std::fs::File;
3use std::io::{Error, ErrorKind, Read};
4use std::path::{Path, PathBuf};
5use std::{env, fs};
6
7use thiserror::Error;
8
9use crate::config::config_type::ConfigType;
10#[allow(unreachable_pub)]
11pub use crate::config::file_lines::{FileLines, FileName, Range};
12#[allow(unreachable_pub)]
13pub use crate::config::macro_names::MacroSelector;
14#[allow(unreachable_pub)]
15pub use crate::config::options::*;
16
17#[macro_use]
18pub(crate) mod config_type;
19#[macro_use]
20#[allow(unreachable_pub)]
21pub(crate) mod options;
22
23pub(crate) mod file_lines;
24#[allow(unreachable_pub)]
25pub(crate) mod lists;
26pub(crate) mod macro_names;
27pub(crate) mod style_edition;
28
29// This macro defines configuration options used in rustfmt. Each option
30// is defined as follows:
31//
32// `name: value type, is stable, description;`
33create_config! {
34    // Fundamental stuff
35    max_width: MaxWidth, true, "Maximum width of each line";
36    hard_tabs: HardTabs, true, "Use tab characters for indentation, spaces for alignment";
37    tab_spaces: TabSpaces, true, "Number of spaces per tab";
38    newline_style: NewlineStyleConfig, true, "Unix or Windows line endings";
39    indent_style: IndentStyleConfig, false, "How do we indent expressions or items";
40
41    // Width Heuristics
42    use_small_heuristics: UseSmallHeuristics, true, "Whether to use different \
43        formatting for items and expressions if they satisfy a heuristic notion of 'small'";
44    width_heuristics: WidthHeuristicsConfig, false, "'small' heuristic values";
45    fn_call_width: FnCallWidth, true, "Maximum width of the args of a function call before \
46        falling back to vertical formatting.";
47    attr_fn_like_width: AttrFnLikeWidth, true, "Maximum width of the args of a function-like \
48        attributes before falling back to vertical formatting.";
49    struct_lit_width: StructLitWidth, true, "Maximum width in the body of a struct lit before \
50        falling back to vertical formatting.";
51    struct_variant_width: StructVariantWidth, true, "Maximum width in the body of a struct variant \
52        before falling back to vertical formatting.";
53    array_width: ArrayWidth, true,  "Maximum width of an array literal before falling \
54        back to vertical formatting.";
55    chain_width: ChainWidth, true, "Maximum length of a chain to fit on a single line.";
56    single_line_if_else_max_width: SingleLineIfElseMaxWidth, true, "Maximum line length for single \
57        line if-else expressions. A value of zero means always break if-else expressions.";
58    single_line_let_else_max_width: SingleLineLetElseMaxWidth, true, "Maximum line length for \
59        single line let-else statements. A value of zero means always format the divergent `else` \
60        block over multiple lines.";
61
62    // Comments. macros, and strings
63    wrap_comments: WrapComments, false, "Break comments to fit on the line";
64    format_code_in_doc_comments: FormatCodeInDocComments, false, "Format the code snippet in \
65        doc comments.";
66    doc_comment_code_block_width: DocCommentCodeBlockWidth, false, "Maximum width for code \
67        snippets in doc comments. No effect unless format_code_in_doc_comments = true";
68    doc_comment_code_block_small_heuristics: DocUseSmallHeuristics, false,
69        "Value for use_small_heuristics for code blocks in doc comments. \
70        No effect unless format_code_in_doc_comments = true";
71    comment_width: CommentWidth, false,
72        "Maximum length of comments. No effect unless wrap_comments = true";
73    normalize_comments: NormalizeComments, false, "Convert /* */ comments to // comments where \
74        possible";
75    normalize_doc_attributes: NormalizeDocAttributes, false, "Normalize doc attributes as doc \
76        comments";
77    format_strings: FormatStrings, false, "Format string literals where necessary";
78    format_macro_matchers: FormatMacroMatchers, false,
79        "Format the metavariable matching patterns in macros";
80    format_macro_bodies: FormatMacroBodies, false,
81        "Format the bodies of declarative macro definitions";
82    skip_macro_invocations: SkipMacroInvocations, false,
83        "Skip formatting the bodies of macros invoked with the following names.";
84    hex_literal_case: HexLiteralCaseConfig, true, "Format hexadecimal integer literals";
85    float_literal_trailing_zero: FloatLiteralTrailingZeroConfig, false,
86        "Add or remove trailing zero in floating-point literals";
87
88    // Single line expressions and items
89    empty_item_single_line: EmptyItemSingleLine, false,
90        "Put empty-body functions and impls on a single line";
91    struct_lit_single_line: StructLitSingleLine, false,
92        "Put small struct literals on a single line";
93    fn_single_line: FnSingleLine, false, "Put single-expression functions on a single line";
94    where_single_line: WhereSingleLine, false, "Force where-clauses to be on a single line";
95
96    // Imports
97    imports_indent: ImportsIndent, false, "Indent of imports";
98    imports_layout: ImportsLayout, false, "Item layout inside a import block";
99    imports_granularity: ImportsGranularityConfig, false,
100        "Merge or split imports to the provided granularity";
101    group_imports: GroupImportsTacticConfig, false,
102        "Controls the strategy for how imports are grouped together";
103    merge_imports: MergeImports, false, "(deprecated: use imports_granularity instead)";
104
105    // Ordering
106    reorder_imports: ReorderImports, true, "Reorder import and extern crate statements \
107        alphabetically";
108    reorder_modules: ReorderModules, true, "Reorder module statements alphabetically in group";
109    reorder_impl_items: ReorderImplItems, false, "Reorder impl items";
110
111    // Spaces around punctuation
112    type_punctuation_density: TypePunctuationDensity, false,
113        "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
114    space_before_colon: SpaceBeforeColon, false, "Leave a space before the colon";
115    space_after_colon: SpaceAfterColon, false, "Leave a space after the colon";
116    spaces_around_ranges: SpacesAroundRanges, false, "Put spaces around the  .. and ..= range \
117        operators";
118    binop_separator: BinopSeparator, false,
119        "Where to put a binary operator when a binary expression goes multiline";
120
121    // Misc.
122    remove_nested_parens: RemoveNestedParens, true, "Remove nested parens";
123    combine_control_expr: CombineControlExpr, false, "Combine control expressions with function \
124        calls";
125    short_array_element_width_threshold: ShortArrayElementWidthThreshold, true,
126        "Width threshold for an array element to be considered short";
127    overflow_delimited_expr: OverflowDelimitedExpr, false,
128        "Allow trailing bracket/brace delimited expressions to overflow";
129    struct_field_align_threshold: StructFieldAlignThreshold, false,
130        "Align struct fields if their diffs fits within threshold";
131    enum_discrim_align_threshold: EnumDiscrimAlignThreshold, false,
132        "Align enum variants discrims, if their diffs fit within threshold";
133    match_arm_blocks: MatchArmBlocks, false, "Wrap the body of arms in blocks when it does not fit \
134        on the same line with the pattern of arms";
135    match_arm_leading_pipes: MatchArmLeadingPipeConfig, true,
136        "Determines whether leading pipes are emitted on match arms";
137    match_arm_indent: MatchArmIndent, false,
138        "Determines whether match arms are indented";
139    force_multiline_blocks: ForceMultilineBlocks, false,
140        "Force multiline closure bodies and match arms to be wrapped in a block";
141    fn_args_layout: FnArgsLayout, true,
142        "(deprecated: use fn_params_layout instead)";
143    fn_params_layout: FnParamsLayout, true,
144        "Control the layout of parameters in function signatures.";
145    brace_style: BraceStyleConfig, false, "Brace style for items";
146    control_brace_style: ControlBraceStyleConfig, false,
147        "Brace style for control flow constructs";
148    trailing_semicolon: TrailingSemicolon, false,
149        "Add trailing semicolon after break, continue and return";
150    trailing_comma: TrailingComma, false,
151        "How to handle trailing commas for lists";
152    match_block_trailing_comma: MatchBlockTrailingComma, true,
153        "Put a trailing comma after a block based match arm (non-block arms are not affected)";
154    blank_lines_upper_bound: BlankLinesUpperBound, false,
155        "Maximum number of blank lines which can be put between items";
156    blank_lines_lower_bound: BlankLinesLowerBound, false,
157        "Minimum number of blank lines which must be put between items";
158    edition: EditionConfig, true, "The edition of the parser (RFC 2052)";
159    style_edition: StyleEditionConfig, true, "The edition of the Style Guide (RFC 3338)";
160    version: VersionConfig, false, "Version of formatting rules";
161    inline_attribute_width: InlineAttributeWidth, false,
162        "Write an item and its attribute on the same line \
163        if their combined width is below a threshold";
164    format_generated_files: FormatGeneratedFiles, false, "Format generated files";
165    generated_marker_line_search_limit: GeneratedMarkerLineSearchLimit, false, "Number of lines to \
166        check for a `@generated` marker when `format_generated_files` is enabled";
167
168    // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
169    merge_derives: MergeDerives, true, "Merge multiple `#[derive(...)]` into a single one";
170    use_try_shorthand: UseTryShorthand, true, "Replace uses of the try! macro by the ? shorthand";
171    use_field_init_shorthand: UseFieldInitShorthand, true, "Use field initialization shorthand if \
172        possible";
173    force_explicit_abi: ForceExplicitAbi, true, "Always print the abi for extern items";
174    condense_wildcard_suffixes: CondenseWildcardSuffixes, false, "Replace strings of _ wildcards \
175        by a single .. in tuple patterns";
176
177    // Control options (changes the operation of rustfmt, rather than the formatting)
178    color: ColorConfig, false,
179        "What Color option to use when none is supplied: Always, Never, Auto";
180    required_version: RequiredVersion, false,
181        "Require a specific version of rustfmt";
182    unstable_features: UnstableFeatures, false,
183            "Enables unstable features. Only available on nightly channel";
184    disable_all_formatting: DisableAllFormatting, true, "Don't reformat anything";
185    skip_children: SkipChildren, false, "Don't reformat out of line modules";
186    hide_parse_errors: HideParseErrors, false, "Hide errors from the parser";
187    show_parse_errors: ShowParseErrors, false, "Show errors from the parser (unstable)";
188    error_on_line_overflow: ErrorOnLineOverflow, false, "Error if unable to get all lines within \
189        max_width";
190    error_on_unformatted: ErrorOnUnformatted, false,
191        "Error if unable to get comments or string literals within max_width, \
192         or they are left with trailing whitespaces";
193    ignore: Ignore, false,
194        "Skip formatting the specified files and directories";
195
196    // Not user-facing
197    verbose: Verbose, false, "How much to information to emit to the user";
198    file_lines: FileLinesConfig, false,
199        "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
200         via the --file-lines option";
201    emit_mode: EmitModeConfig, false,
202        "What emit Mode to use when none is supplied";
203    make_backup: MakeBackup, false, "Backup changed files";
204    print_misformatted_file_names: PrintMisformattedFileNames, true,
205        "Prints the names of mismatched files that were formatted. Prints the names of \
206         files that would be formatted when used with `--check` mode. ";
207}
208
209#[derive(Error, Debug)]
210#[error("Could not output config: {0}")]
211pub struct ToTomlError(toml::ser::Error);
212
213impl PartialConfig {
214    pub fn to_toml(&self) -> Result<String, ToTomlError> {
215        // Non-user-facing options can't be specified in TOML
216        let mut cloned = self.clone();
217        cloned.file_lines = None;
218        cloned.verbose = None;
219        cloned.width_heuristics = None;
220        cloned.print_misformatted_file_names = None;
221        cloned.merge_imports = None;
222        cloned.fn_args_layout = None;
223        cloned.hide_parse_errors = None;
224
225        ::toml::to_string(&cloned).map_err(ToTomlError)
226    }
227
228    pub(super) fn to_parsed_config(
229        self,
230        style_edition_override: Option<StyleEdition>,
231        edition_override: Option<Edition>,
232        version_override: Option<Version>,
233        dir: &Path,
234    ) -> Config {
235        Config::default_for_possible_style_edition(
236            style_edition_override.or(self.style_edition),
237            edition_override.or(self.edition),
238            version_override.or(self.version),
239        )
240        .fill_from_parsed_config(self, dir)
241    }
242}
243
244fn check_semver_version(range_requirement: &str, actual: &str) -> bool {
245    let mut version_req = match semver::VersionReq::parse(range_requirement) {
246        Ok(r) => r,
247        Err(e) => {
248            eprintln!("Error: failed to parse required version {range_requirement:?}: {e}");
249            return false;
250        }
251    };
252    let actual_version = match semver::Version::parse(actual) {
253        Ok(v) => v,
254        Err(e) => {
255            eprintln!("Error: failed to parse current version {actual:?}: {e}");
256            return false;
257        }
258    };
259
260    range_requirement
261        .split(',')
262        .enumerate()
263        .for_each(|(i, label)| {
264            // the label refers to the current comparator
265            let Some(comparator) = version_req.comparators.get_mut(i) else {
266                return;
267            };
268
269            // semver crate handles "1.0.0" as "^1.0.0", and we want to treat it as "=1.0.0"
270            // because of this, we need to iterate over the comparators, and change each one
271            // that has "default caret operator" to an exact operator
272            // this condition overrides the "default caret operator" of semver create.
273            if !label.starts_with('^') && comparator.op == semver::Op::Caret {
274                comparator.op = semver::Op::Exact;
275            }
276        });
277
278    version_req.matches(&actual_version)
279}
280
281impl Config {
282    pub fn default_for_possible_style_edition(
283        style_edition: Option<StyleEdition>,
284        edition: Option<Edition>,
285        version: Option<Version>,
286    ) -> Config {
287        // Ensures the configuration defaults associated with Style Editions
288        // follow the precedence set in
289        // https://rust-lang.github.io/rfcs/3338-style-evolution.html
290        // 'version' is a legacy alias for 'style_edition' that we'll support
291        // for some period of time
292        // FIXME(calebcartwright) - remove 'version' at some point
293        match (style_edition, version, edition) {
294            (Some(se), _, _) => Self::default_with_style_edition(se),
295            (None, Some(Version::Two), _) => {
296                Self::default_with_style_edition(StyleEdition::Edition2024)
297            }
298            (None, Some(Version::One), _) => {
299                Self::default_with_style_edition(StyleEdition::Edition2015)
300            }
301            (None, None, Some(e)) => Self::default_with_style_edition(e.into()),
302            (None, None, None) => Config::default(),
303        }
304    }
305
306    pub(crate) fn version_meets_requirement(&self) -> bool {
307        if self.was_set().required_version() {
308            let version = env!("CARGO_PKG_VERSION");
309            let required_version = self.required_version();
310            if !check_semver_version(&required_version, version) {
311                eprintln!(
312                    "Error: rustfmt version ({}) doesn't match the required version ({})",
313                    version, required_version
314                );
315                return false;
316            }
317        }
318
319        true
320    }
321
322    /// Constructs a `Config` from the toml file specified at `file_path`.
323    ///
324    /// This method only looks at the provided path, for a method that
325    /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
326    ///
327    /// Returns a `Config` if the config could be read and parsed from
328    /// the file, otherwise errors.
329    pub(super) fn from_toml_path(
330        file_path: &Path,
331        edition: Option<Edition>,
332        style_edition: Option<StyleEdition>,
333        version: Option<Version>,
334    ) -> Result<Config, Error> {
335        let mut file = File::open(&file_path)?;
336        let mut toml = String::new();
337        file.read_to_string(&mut toml)?;
338        Config::from_toml_for_style_edition(&toml, file_path, edition, style_edition, version)
339            .map_err(|err| Error::new(ErrorKind::InvalidData, err))
340    }
341
342    /// Resolves the config for input in `dir`.
343    ///
344    /// Searches for `rustfmt.toml` beginning with `dir`, and
345    /// recursively checking parents of `dir` if no config file is found.
346    /// If no config file exists in `dir` or in any parent, a
347    /// default `Config` will be returned (and the returned path will be empty).
348    ///
349    /// Returns the `Config` to use, and the path of the project file if there was
350    /// one.
351    pub(super) fn from_resolved_toml_path(
352        dir: &Path,
353        edition: Option<Edition>,
354        style_edition: Option<StyleEdition>,
355        version: Option<Version>,
356    ) -> Result<(Config, Option<PathBuf>), Error> {
357        match resolve_project_file(dir).or_else(|_| config_from_user_dirs())? {
358            None => Ok((
359                Config::default_for_possible_style_edition(style_edition, edition, version),
360                None,
361            )),
362            Some(path) => Config::from_toml_path(&path, edition, style_edition, version)
363                .map(|config| (config, Some(path))),
364        }
365    }
366
367    #[allow(dead_code)]
368    pub(super) fn from_toml(toml: &str, file_path: &Path) -> Result<Config, String> {
369        Self::from_toml_for_style_edition(toml, file_path, None, None, None)
370    }
371
372    pub(crate) fn from_toml_for_style_edition(
373        toml: &str,
374        file_path: &Path,
375        edition: Option<Edition>,
376        style_edition: Option<StyleEdition>,
377        version: Option<Version>,
378    ) -> Result<Config, String> {
379        let parsed: ::toml::Value =
380            toml::from_str(toml).map_err(|e| format!("Could not parse TOML: {}", e))?;
381        let mut err = String::new();
382        let table = parsed
383            .as_table()
384            .ok_or_else(|| String::from("Parsed config was not table"))?;
385        for key in table.keys() {
386            if !Config::is_valid_name(key) {
387                let msg = &format!("Warning: Unknown configuration option `{key}`\n");
388                err.push_str(msg)
389            }
390        }
391
392        match parsed.try_into::<PartialConfig>() {
393            Ok(parsed_config) => {
394                if !err.is_empty() {
395                    eprint!("{err}");
396                }
397                let dir = file_path.parent().ok_or_else(|| {
398                    format!("failed to get parent directory for {}", file_path.display())
399                })?;
400
401                Ok(parsed_config.to_parsed_config(style_edition, edition, version, dir))
402            }
403            Err(e) => {
404                let err_msg = format!(
405                    "The file `{}` failed to parse.\nError details: {e}",
406                    file_path.display()
407                );
408                err.push_str(&err_msg);
409                Err(err_msg)
410            }
411        }
412    }
413}
414
415/// Looks for a configuration file in the given directory and its parents.
416///
417/// Returns the path of the configuration file nearest to that directory if one exists, or `None` if
418/// none was found.
419fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
420    let mut current = if dir.is_relative() {
421        env::current_dir()?.join(dir)
422    } else {
423        dir.to_path_buf()
424    };
425
426    current = fs::canonicalize(current)?;
427
428    loop {
429        match get_toml_path(&current) {
430            Ok(Some(path)) => return Ok(Some(path)),
431            Err(e) => return Err(e),
432            _ => (),
433        }
434
435        // If the current directory has no parent, we're done searching.
436        if !current.pop() {
437            break Ok(None);
438        }
439    }
440}
441
442/// Looks for a configuration file in the user's home directory and configuration directory.
443///
444/// Returns the path of the first configuration file found in that order, or `None` if none was
445/// found.
446fn config_from_user_dirs() -> Result<Option<PathBuf>, Error> {
447    for dir in [
448        dirs::home_dir(),
449        dirs::config_dir().map(|d| d.join("rustfmt")),
450    ]
451    .iter()
452    .flatten()
453    {
454        if let Some(path) = get_toml_path(&dir)? {
455            return Ok(Some(path));
456        }
457    }
458
459    Ok(None)
460}
461
462/// Loads a config by checking the client-supplied options and if appropriate, the
463/// file system (including searching the file system for overrides).
464pub fn load_config<O: CliOptions>(
465    file_path: Option<&Path>,
466    options: Option<O>,
467) -> Result<(Config, Option<PathBuf>), Error> {
468    let (over_ride, edition, style_edition, version) = match options {
469        Some(ref opts) => (
470            config_path(opts)?,
471            opts.edition(),
472            opts.style_edition(),
473            opts.version(),
474        ),
475        None => (None, None, None, None),
476    };
477
478    let result = if let Some(over_ride) = over_ride {
479        Config::from_toml_path(over_ride.as_ref(), edition, style_edition, version)
480            .map(|p| (p, Some(over_ride.to_owned())))
481    } else if let Some(file_path) = file_path {
482        Config::from_resolved_toml_path(file_path, edition, style_edition, version)
483    } else {
484        Ok((
485            Config::default_for_possible_style_edition(style_edition, edition, version),
486            None,
487        ))
488    };
489
490    result.map(|(mut c, p)| {
491        if let Some(options) = options {
492            options.apply_to(&mut c);
493        }
494        (c, p)
495    })
496}
497
498// Check for the presence of known config file names (`rustfmt.toml`, `.rustfmt.toml`) in `dir`
499//
500// Return the path if a config file exists, empty if no file exists, and Error for IO errors
501fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
502    const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
503    for config_file_name in &CONFIG_FILE_NAMES {
504        let config_file = dir.join(config_file_name);
505        match fs::metadata(&config_file) {
506            // Only return if it's a file to handle the unlikely situation of a directory named
507            // `rustfmt.toml`.
508            Ok(ref md) if md.is_file() => return Ok(Some(config_file.canonicalize()?)),
509            // We didn't find the project file yet, and continue searching if:
510            // `NotFound` => file not found
511            // `NotADirectory` => rare case where expected directory is a file
512            // Otherwise, return the error
513            Err(e) => {
514                if !matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) {
515                    let ctx = format!("Failed to get metadata for config file {:?}", &config_file);
516                    let err = anyhow::Error::new(e).context(ctx);
517                    return Err(Error::new(ErrorKind::Other, err));
518                }
519            }
520            _ => {}
521        }
522    }
523    Ok(None)
524}
525
526fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
527    let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
528        Err(Error::new(
529            ErrorKind::NotFound,
530            format!(
531                "Error: unable to find a config file for the given path: `{}`",
532                path
533            ),
534        ))
535    };
536
537    // Read the config_path and convert to parent dir if a file is provided.
538    // If a config file cannot be found from the given path, return error.
539    match options.config_path() {
540        Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
541        Some(path) if path.is_dir() => resolve_project_file(path),
542        Some(path) => Ok(Some(
543            // Canonicalize only after checking above that the `path.exists()`.
544            path.canonicalize()?,
545        )),
546        None => Ok(None),
547    }
548}
549
550#[cfg(test)]
551mod test {
552    use super::*;
553    use std::str;
554
555    use crate::config::macro_names::{MacroName, MacroSelectors};
556    use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
557
558    #[allow(dead_code)]
559    mod mock {
560        use super::super::*;
561        use rustfmt_config_proc_macro::config_type;
562
563        #[config_type]
564        pub(crate) enum PartiallyUnstableOption {
565            V1,
566            V2,
567            #[unstable_variant]
568            V3,
569        }
570
571        config_option_with_style_edition_default!(
572            StableOption, bool, _ => false;
573            UnstableOption, bool, _ => false;
574            PartiallyUnstable, PartiallyUnstableOption, _ => PartiallyUnstableOption::V1;
575        );
576
577        create_config! {
578            // Options that are used by the generated functions
579            max_width: MaxWidth, true, "Maximum width of each line";
580            required_version: RequiredVersion, false, "Require a specific version of rustfmt.";
581            ignore: Ignore, false, "Skip formatting the specified files and directories.";
582            verbose: Verbose, false, "How much to information to emit to the user";
583            file_lines: FileLinesConfig, false,
584                "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
585                    via the --file-lines option";
586
587            // merge_imports deprecation
588            imports_granularity: ImportsGranularityConfig, false, "Merge imports";
589            merge_imports: MergeImports, false, "(deprecated: use imports_granularity instead)";
590
591            // fn_args_layout renamed to fn_params_layout
592            fn_args_layout: FnArgsLayout, true, "(deprecated: use fn_params_layout instead)";
593            fn_params_layout: FnParamsLayout, true,
594                "Control the layout of parameters in a function signatures.";
595
596            // hide_parse_errors renamed to show_parse_errors
597            hide_parse_errors: HideParseErrors, false,
598                "(deprecated: use show_parse_errors instead)";
599            show_parse_errors: ShowParseErrors, false,
600                "Show errors from the parser (unstable)";
601
602
603            // Width Heuristics
604            use_small_heuristics: UseSmallHeuristics, true,
605                "Whether to use different formatting for items and \
606                 expressions if they satisfy a heuristic notion of 'small'.";
607            width_heuristics: WidthHeuristicsConfig, false, "'small' heuristic values";
608
609            fn_call_width: FnCallWidth, true, "Maximum width of the args of a function call before \
610                falling back to vertical formatting.";
611            attr_fn_like_width: AttrFnLikeWidth, true, "Maximum width of the args of a \
612                function-like attributes before falling back to vertical formatting.";
613            struct_lit_width: StructLitWidth, true, "Maximum width in the body of a struct lit \
614                before falling back to vertical formatting.";
615            struct_variant_width: StructVariantWidth, true, "Maximum width in the body of a struct \
616                variant before falling back to vertical formatting.";
617            array_width: ArrayWidth, true,  "Maximum width of an array literal before falling \
618                back to vertical formatting.";
619            chain_width: ChainWidth, true, "Maximum length of a chain to fit on a single line.";
620            single_line_if_else_max_width: SingleLineIfElseMaxWidth, true, "Maximum line length \
621                for single line if-else expressions. A value of zero means always break if-else \
622                expressions.";
623            single_line_let_else_max_width: SingleLineLetElseMaxWidth, false, "Maximum line length \
624                for single line let-else statements. A value of zero means always format the \
625                divergent `else` block over multiple lines.";
626
627            // Options that are used by the tests
628            stable_option: StableOption, true, "A stable option";
629            unstable_option: UnstableOption, false, "An unstable option";
630            partially_unstable_option: PartiallyUnstable, true, "A partially unstable option";
631            edition: EditionConfig, true, "blah";
632            style_edition: StyleEditionConfig, true, "blah";
633            version: VersionConfig, false, "blah blah"
634        }
635
636        #[cfg(test)]
637        mod partially_unstable_option {
638            use super::{Config, PartialConfig, PartiallyUnstableOption};
639            use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
640            use std::path::Path;
641
642            /// From the config file, we can fill with a stable variant
643            #[test]
644            fn test_from_toml_stable_value() {
645                let toml = r#"
646                    partially_unstable_option = "V2"
647                "#;
648                let partial_config: PartialConfig = toml::from_str(toml).unwrap();
649                let config = Config::default();
650                let config = config.fill_from_parsed_config(partial_config, Path::new(""));
651                assert_eq!(
652                    config.partially_unstable_option(),
653                    PartiallyUnstableOption::V2
654                );
655            }
656
657            /// From the config file, we cannot fill with an unstable variant (stable only)
658            #[stable_only_test]
659            #[test]
660            fn test_from_toml_unstable_value_on_stable() {
661                let toml = r#"
662                    partially_unstable_option = "V3"
663                "#;
664                let partial_config: PartialConfig = toml::from_str(toml).unwrap();
665                let config = Config::default();
666                let config = config.fill_from_parsed_config(partial_config, Path::new(""));
667                assert_eq!(
668                    config.partially_unstable_option(),
669                    // default value from config, i.e. fill failed
670                    PartiallyUnstableOption::V1
671                );
672            }
673
674            /// From the config file, we can fill with an unstable variant (nightly only)
675            #[nightly_only_test]
676            #[test]
677            fn test_from_toml_unstable_value_on_nightly() {
678                let toml = r#"
679                    partially_unstable_option = "V3"
680                "#;
681                let partial_config: PartialConfig = toml::from_str(toml).unwrap();
682                let config = Config::default();
683                let config = config.fill_from_parsed_config(partial_config, Path::new(""));
684                assert_eq!(
685                    config.partially_unstable_option(),
686                    PartiallyUnstableOption::V3
687                );
688            }
689        }
690    }
691
692    #[test]
693    fn test_config_set() {
694        let mut config = Config::default();
695        config.set().verbose(Verbosity::Quiet);
696        assert_eq!(config.verbose(), Verbosity::Quiet);
697        config.set().verbose(Verbosity::Normal);
698        assert_eq!(config.verbose(), Verbosity::Normal);
699    }
700
701    #[test]
702    fn test_adjust_max_width() {
703        // Regression tests for #7147, where we didn't handle overflows / integral cast outside of
704        // range properly.
705
706        // Reduce with huge amount saturates to zero instead of wraparound.
707        let mut config = Config::default();
708        config.reduce_max_width(usize::MAX);
709        assert_eq!(config.max_width(), 0);
710
711        // Increase with huge amount saturates instead of wraparound.
712        let mut config = Config::default();
713        config.set().max_width(usize::MAX - 1);
714        config.increase_max_width(2);
715        assert_eq!(config.max_width(), usize::MAX);
716    }
717
718    #[test]
719    fn test_config_used_to_toml() {
720        let config = Config::default();
721
722        let merge_derives = config.merge_derives();
723        let skip_children = config.skip_children();
724
725        let used_options = config.used_options();
726        let toml = used_options.to_toml().unwrap();
727        assert_eq!(
728            toml,
729            format!("merge_derives = {merge_derives}\nskip_children = {skip_children}\n",)
730        );
731    }
732
733    #[test]
734    fn test_was_set() {
735        let config = Config::from_toml("hard_tabs = true", Path::new("./rustfmt.toml")).unwrap();
736
737        assert_eq!(config.was_set().hard_tabs(), true);
738        assert_eq!(config.was_set().verbose(), false);
739    }
740
741    const PRINT_DOCS_STABLE_OPTION: &str = "stable_option <boolean> Default: false";
742    const PRINT_DOCS_UNSTABLE_OPTION: &str = "unstable_option <boolean> Default: false (unstable)";
743    const PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION: &str =
744        "partially_unstable_option [V1|V2|V3 (unstable)] Default: V1";
745
746    #[test]
747    fn test_print_docs_exclude_unstable() {
748        use self::mock::Config;
749
750        let mut output = Vec::new();
751        Config::print_docs(&mut output, false);
752
753        let s = str::from_utf8(&output).unwrap();
754        assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true);
755        assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), false);
756        assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true);
757    }
758
759    #[test]
760    fn test_print_docs_include_unstable() {
761        use self::mock::Config;
762
763        let mut output = Vec::new();
764        Config::print_docs(&mut output, true);
765
766        let s = str::from_utf8(&output).unwrap();
767        assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true);
768        assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), true);
769        assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true);
770    }
771
772    #[test]
773    fn test_dump_default_config() {
774        let default_config = format!(
775            r#"max_width = 100
776hard_tabs = false
777tab_spaces = 4
778newline_style = "Auto"
779indent_style = "Block"
780use_small_heuristics = "Default"
781fn_call_width = 60
782attr_fn_like_width = 70
783struct_lit_width = 18
784struct_variant_width = 35
785array_width = 60
786chain_width = 60
787single_line_if_else_max_width = 50
788single_line_let_else_max_width = 50
789wrap_comments = false
790format_code_in_doc_comments = false
791doc_comment_code_block_width = 100
792doc_comment_code_block_small_heuristics = "Inherit"
793comment_width = 80
794normalize_comments = false
795normalize_doc_attributes = false
796format_strings = false
797format_macro_matchers = false
798format_macro_bodies = true
799skip_macro_invocations = []
800hex_literal_case = "Preserve"
801float_literal_trailing_zero = "Preserve"
802empty_item_single_line = true
803struct_lit_single_line = true
804fn_single_line = false
805where_single_line = false
806imports_indent = "Block"
807imports_layout = "Mixed"
808imports_granularity = "Preserve"
809group_imports = "Preserve"
810reorder_imports = true
811reorder_modules = true
812reorder_impl_items = false
813type_punctuation_density = "Wide"
814space_before_colon = false
815space_after_colon = true
816spaces_around_ranges = false
817binop_separator = "Front"
818remove_nested_parens = true
819combine_control_expr = true
820short_array_element_width_threshold = 10
821overflow_delimited_expr = false
822struct_field_align_threshold = 0
823enum_discrim_align_threshold = 0
824match_arm_blocks = true
825match_arm_leading_pipes = "Never"
826match_arm_indent = true
827force_multiline_blocks = false
828fn_params_layout = "Tall"
829brace_style = "SameLineWhere"
830control_brace_style = "AlwaysSameLine"
831trailing_semicolon = true
832trailing_comma = "Vertical"
833match_block_trailing_comma = false
834blank_lines_upper_bound = 1
835blank_lines_lower_bound = 0
836edition = "2015"
837style_edition = "2015"
838version = "One"
839inline_attribute_width = 0
840format_generated_files = true
841generated_marker_line_search_limit = 5
842merge_derives = true
843use_try_shorthand = false
844use_field_init_shorthand = false
845force_explicit_abi = true
846condense_wildcard_suffixes = false
847color = "Auto"
848required_version = "{}"
849unstable_features = false
850disable_all_formatting = false
851skip_children = false
852show_parse_errors = true
853error_on_line_overflow = false
854error_on_unformatted = false
855ignore = []
856emit_mode = "Files"
857make_backup = false
858"#,
859            env!("CARGO_PKG_VERSION")
860        );
861        let toml = Config::default().all_options().to_toml().unwrap();
862        assert_eq!(&toml, &default_config);
863    }
864
865    #[test]
866    fn test_dump_style_edition_2024_config() {
867        let edition_2024_config = format!(
868            r#"max_width = 100
869hard_tabs = false
870tab_spaces = 4
871newline_style = "Auto"
872indent_style = "Block"
873use_small_heuristics = "Default"
874fn_call_width = 60
875attr_fn_like_width = 70
876struct_lit_width = 18
877struct_variant_width = 35
878array_width = 60
879chain_width = 60
880single_line_if_else_max_width = 50
881single_line_let_else_max_width = 50
882wrap_comments = false
883format_code_in_doc_comments = false
884doc_comment_code_block_width = 100
885doc_comment_code_block_small_heuristics = "Inherit"
886comment_width = 80
887normalize_comments = false
888normalize_doc_attributes = false
889format_strings = false
890format_macro_matchers = false
891format_macro_bodies = true
892skip_macro_invocations = []
893hex_literal_case = "Preserve"
894float_literal_trailing_zero = "Preserve"
895empty_item_single_line = true
896struct_lit_single_line = true
897fn_single_line = false
898where_single_line = false
899imports_indent = "Block"
900imports_layout = "Mixed"
901imports_granularity = "Preserve"
902group_imports = "Preserve"
903reorder_imports = true
904reorder_modules = true
905reorder_impl_items = false
906type_punctuation_density = "Wide"
907space_before_colon = false
908space_after_colon = true
909spaces_around_ranges = false
910binop_separator = "Front"
911remove_nested_parens = true
912combine_control_expr = true
913short_array_element_width_threshold = 10
914overflow_delimited_expr = false
915struct_field_align_threshold = 0
916enum_discrim_align_threshold = 0
917match_arm_blocks = true
918match_arm_leading_pipes = "Never"
919match_arm_indent = true
920force_multiline_blocks = false
921fn_params_layout = "Tall"
922brace_style = "SameLineWhere"
923control_brace_style = "AlwaysSameLine"
924trailing_semicolon = true
925trailing_comma = "Vertical"
926match_block_trailing_comma = false
927blank_lines_upper_bound = 1
928blank_lines_lower_bound = 0
929edition = "2015"
930style_edition = "2024"
931version = "Two"
932inline_attribute_width = 0
933format_generated_files = true
934generated_marker_line_search_limit = 5
935merge_derives = true
936use_try_shorthand = false
937use_field_init_shorthand = false
938force_explicit_abi = true
939condense_wildcard_suffixes = false
940color = "Auto"
941required_version = "{}"
942unstable_features = false
943disable_all_formatting = false
944skip_children = false
945show_parse_errors = true
946error_on_line_overflow = false
947error_on_unformatted = false
948ignore = []
949emit_mode = "Files"
950make_backup = false
951"#,
952            env!("CARGO_PKG_VERSION")
953        );
954        let toml = Config::default_with_style_edition(StyleEdition::Edition2024)
955            .all_options()
956            .to_toml()
957            .unwrap();
958        assert_eq!(&toml, &edition_2024_config);
959    }
960
961    #[test]
962    fn test_editions_2015_2018_2021_identical() {
963        let get_edition_toml = |style_edition: StyleEdition| {
964            Config::default_with_style_edition(style_edition)
965                .all_options()
966                .to_toml()
967                .unwrap()
968        };
969        let edition2015 = get_edition_toml(StyleEdition::Edition2015);
970        let edition2018 = get_edition_toml(StyleEdition::Edition2018);
971        let edition2021 = get_edition_toml(StyleEdition::Edition2021);
972        assert_eq!(edition2015, edition2018);
973        assert_eq!(edition2018, edition2021);
974    }
975
976    #[stable_only_test]
977    #[test]
978    fn test_as_not_nightly_channel() {
979        let mut config = Config::default();
980        assert_eq!(config.was_set().unstable_features(), false);
981        config.set().unstable_features(true);
982        assert_eq!(config.was_set().unstable_features(), false);
983    }
984
985    #[nightly_only_test]
986    #[test]
987    fn test_as_nightly_channel() {
988        let mut config = Config::default();
989        config.set().unstable_features(true);
990        // When we don't set the config from toml or command line options it
991        // doesn't get marked as set by the user.
992        assert_eq!(config.was_set().unstable_features(), false);
993        config.set().unstable_features(true);
994        assert_eq!(config.unstable_features(), true);
995    }
996
997    #[nightly_only_test]
998    #[test]
999    fn test_unstable_from_toml() {
1000        let config =
1001            Config::from_toml("unstable_features = true", Path::new("./rustfmt.toml")).unwrap();
1002        assert_eq!(config.was_set().unstable_features(), true);
1003        assert_eq!(config.unstable_features(), true);
1004    }
1005
1006    #[test]
1007    fn test_set_cli() {
1008        let mut config = Config::default();
1009        assert_eq!(config.was_set().edition(), false);
1010        assert_eq!(config.was_set_cli().edition(), false);
1011        config.set().edition(Edition::Edition2021);
1012        assert_eq!(config.was_set().edition(), false);
1013        assert_eq!(config.was_set_cli().edition(), false);
1014        config.set_cli().edition(Edition::Edition2021);
1015        assert_eq!(config.was_set().edition(), false);
1016        assert_eq!(config.was_set_cli().edition(), true);
1017        assert_eq!(config.was_set_cli().emit_mode(), false);
1018    }
1019
1020    #[cfg(test)]
1021    mod deprecated_option_merge_imports {
1022        use super::*;
1023
1024        #[nightly_only_test]
1025        #[test]
1026        fn test_old_option_set() {
1027            let toml = r#"
1028                unstable_features = true
1029                merge_imports = true
1030            "#;
1031            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1032            assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
1033        }
1034
1035        #[nightly_only_test]
1036        #[test]
1037        fn test_both_set() {
1038            let toml = r#"
1039                unstable_features = true
1040                merge_imports = true
1041                imports_granularity = "Preserve"
1042            "#;
1043            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1044            assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
1045        }
1046
1047        #[nightly_only_test]
1048        #[test]
1049        fn test_new_overridden() {
1050            let toml = r#"
1051                unstable_features = true
1052                merge_imports = true
1053            "#;
1054            let mut config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1055            config.override_value("imports_granularity", "Preserve");
1056            assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
1057        }
1058
1059        #[nightly_only_test]
1060        #[test]
1061        fn test_old_overridden() {
1062            let toml = r#"
1063                unstable_features = true
1064                imports_granularity = "Module"
1065            "#;
1066            let mut config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1067            config.override_value("merge_imports", "true");
1068            // no effect: the new option always takes precedence
1069            assert_eq!(config.imports_granularity(), ImportGranularity::Module);
1070        }
1071    }
1072
1073    #[cfg(test)]
1074    mod use_small_heuristics {
1075        use super::*;
1076
1077        #[test]
1078        fn test_default_sets_correct_widths() {
1079            let toml = r#"
1080                use_small_heuristics = "Default"
1081                max_width = 200
1082            "#;
1083            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1084            assert_eq!(config.array_width(), 120);
1085            assert_eq!(config.attr_fn_like_width(), 140);
1086            assert_eq!(config.chain_width(), 120);
1087            assert_eq!(config.fn_call_width(), 120);
1088            assert_eq!(config.single_line_if_else_max_width(), 100);
1089            assert_eq!(config.struct_lit_width(), 36);
1090            assert_eq!(config.struct_variant_width(), 70);
1091        }
1092
1093        #[test]
1094        fn test_max_sets_correct_widths() {
1095            let toml = r#"
1096                use_small_heuristics = "Max"
1097                max_width = 120
1098            "#;
1099            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1100            assert_eq!(config.array_width(), 120);
1101            assert_eq!(config.attr_fn_like_width(), 120);
1102            assert_eq!(config.chain_width(), 120);
1103            assert_eq!(config.fn_call_width(), 120);
1104            assert_eq!(config.single_line_if_else_max_width(), 120);
1105            assert_eq!(config.struct_lit_width(), 120);
1106            assert_eq!(config.struct_variant_width(), 120);
1107        }
1108
1109        #[test]
1110        fn test_off_sets_correct_widths() {
1111            let toml = r#"
1112                use_small_heuristics = "Off"
1113                max_width = 100
1114            "#;
1115            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1116            assert_eq!(config.array_width(), usize::MAX);
1117            assert_eq!(config.attr_fn_like_width(), usize::MAX);
1118            assert_eq!(config.chain_width(), usize::MAX);
1119            assert_eq!(config.fn_call_width(), usize::MAX);
1120            assert_eq!(config.single_line_if_else_max_width(), 0);
1121            assert_eq!(config.struct_lit_width(), 0);
1122            assert_eq!(config.struct_variant_width(), 0);
1123        }
1124
1125        #[test]
1126        fn test_override_works_with_default() {
1127            let toml = r#"
1128                use_small_heuristics = "Default"
1129                array_width = 20
1130                attr_fn_like_width = 40
1131                chain_width = 20
1132                fn_call_width = 90
1133                single_line_if_else_max_width = 40
1134                struct_lit_width = 30
1135                struct_variant_width = 34
1136            "#;
1137            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1138            assert_eq!(config.array_width(), 20);
1139            assert_eq!(config.attr_fn_like_width(), 40);
1140            assert_eq!(config.chain_width(), 20);
1141            assert_eq!(config.fn_call_width(), 90);
1142            assert_eq!(config.single_line_if_else_max_width(), 40);
1143            assert_eq!(config.struct_lit_width(), 30);
1144            assert_eq!(config.struct_variant_width(), 34);
1145        }
1146
1147        #[test]
1148        fn test_override_with_max() {
1149            let toml = r#"
1150                use_small_heuristics = "Max"
1151                array_width = 20
1152                attr_fn_like_width = 40
1153                chain_width = 20
1154                fn_call_width = 90
1155                single_line_if_else_max_width = 40
1156                struct_lit_width = 30
1157                struct_variant_width = 34
1158            "#;
1159            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1160            assert_eq!(config.array_width(), 20);
1161            assert_eq!(config.attr_fn_like_width(), 40);
1162            assert_eq!(config.chain_width(), 20);
1163            assert_eq!(config.fn_call_width(), 90);
1164            assert_eq!(config.single_line_if_else_max_width(), 40);
1165            assert_eq!(config.struct_lit_width(), 30);
1166            assert_eq!(config.struct_variant_width(), 34);
1167        }
1168
1169        #[test]
1170        fn test_override_with_off() {
1171            let toml = r#"
1172                use_small_heuristics = "Off"
1173                array_width = 20
1174                attr_fn_like_width = 40
1175                chain_width = 20
1176                fn_call_width = 90
1177                single_line_if_else_max_width = 40
1178                struct_lit_width = 30
1179                struct_variant_width = 34
1180            "#;
1181            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1182            assert_eq!(config.array_width(), 20);
1183            assert_eq!(config.attr_fn_like_width(), 40);
1184            assert_eq!(config.chain_width(), 20);
1185            assert_eq!(config.fn_call_width(), 90);
1186            assert_eq!(config.single_line_if_else_max_width(), 40);
1187            assert_eq!(config.struct_lit_width(), 30);
1188            assert_eq!(config.struct_variant_width(), 34);
1189        }
1190
1191        #[test]
1192        fn test_fn_call_width_config_exceeds_max_width() {
1193            let toml = r#"
1194                max_width = 90
1195                fn_call_width = 95
1196            "#;
1197            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1198            assert_eq!(config.fn_call_width(), 90);
1199        }
1200
1201        #[test]
1202        fn test_attr_fn_like_width_config_exceeds_max_width() {
1203            let toml = r#"
1204                max_width = 80
1205                attr_fn_like_width = 90
1206            "#;
1207            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1208            assert_eq!(config.attr_fn_like_width(), 80);
1209        }
1210
1211        #[test]
1212        fn test_struct_lit_config_exceeds_max_width() {
1213            let toml = r#"
1214                max_width = 78
1215                struct_lit_width = 90
1216            "#;
1217            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1218            assert_eq!(config.struct_lit_width(), 78);
1219        }
1220
1221        #[test]
1222        fn test_struct_variant_width_config_exceeds_max_width() {
1223            let toml = r#"
1224                max_width = 80
1225                struct_variant_width = 90
1226            "#;
1227            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1228            assert_eq!(config.struct_variant_width(), 80);
1229        }
1230
1231        #[test]
1232        fn test_array_width_config_exceeds_max_width() {
1233            let toml = r#"
1234                max_width = 60
1235                array_width = 80
1236            "#;
1237            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1238            assert_eq!(config.array_width(), 60);
1239        }
1240
1241        #[test]
1242        fn test_chain_width_config_exceeds_max_width() {
1243            let toml = r#"
1244                max_width = 80
1245                chain_width = 90
1246            "#;
1247            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1248            assert_eq!(config.chain_width(), 80);
1249        }
1250
1251        #[test]
1252        fn test_single_line_if_else_max_width_config_exceeds_max_width() {
1253            let toml = r#"
1254                max_width = 70
1255                single_line_if_else_max_width = 90
1256            "#;
1257            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1258            assert_eq!(config.single_line_if_else_max_width(), 70);
1259        }
1260
1261        #[test]
1262        fn test_override_fn_call_width_exceeds_max_width() {
1263            let mut config = Config::default();
1264            config.override_value("fn_call_width", "101");
1265            assert_eq!(config.fn_call_width(), 100);
1266        }
1267
1268        #[test]
1269        fn test_override_attr_fn_like_width_exceeds_max_width() {
1270            let mut config = Config::default();
1271            config.override_value("attr_fn_like_width", "101");
1272            assert_eq!(config.attr_fn_like_width(), 100);
1273        }
1274
1275        #[test]
1276        fn test_override_struct_lit_exceeds_max_width() {
1277            let mut config = Config::default();
1278            config.override_value("struct_lit_width", "101");
1279            assert_eq!(config.struct_lit_width(), 100);
1280        }
1281
1282        #[test]
1283        fn test_override_struct_variant_width_exceeds_max_width() {
1284            let mut config = Config::default();
1285            config.override_value("struct_variant_width", "101");
1286            assert_eq!(config.struct_variant_width(), 100);
1287        }
1288
1289        #[test]
1290        fn test_override_array_width_exceeds_max_width() {
1291            let mut config = Config::default();
1292            config.override_value("array_width", "101");
1293            assert_eq!(config.array_width(), 100);
1294        }
1295
1296        #[test]
1297        fn test_override_chain_width_exceeds_max_width() {
1298            let mut config = Config::default();
1299            config.override_value("chain_width", "101");
1300            assert_eq!(config.chain_width(), 100);
1301        }
1302
1303        #[test]
1304        fn test_override_single_line_if_else_max_width_exceeds_max_width() {
1305            let mut config = Config::default();
1306            config.override_value("single_line_if_else_max_width", "101");
1307            assert_eq!(config.single_line_if_else_max_width(), 100);
1308        }
1309    }
1310
1311    #[cfg(test)]
1312    mod partially_unstable_option {
1313        use super::mock::{Config, PartiallyUnstableOption};
1314
1315        /// From the command line, we can override with a stable variant.
1316        #[test]
1317        fn test_override_stable_value() {
1318            let mut config = Config::default();
1319            config.override_value("partially_unstable_option", "V2");
1320            assert_eq!(
1321                config.partially_unstable_option(),
1322                PartiallyUnstableOption::V2
1323            );
1324        }
1325
1326        /// From the command line, we can override with an unstable variant.
1327        #[test]
1328        fn test_override_unstable_value() {
1329            let mut config = Config::default();
1330            config.override_value("partially_unstable_option", "V3");
1331            assert_eq!(
1332                config.partially_unstable_option(),
1333                PartiallyUnstableOption::V3
1334            );
1335        }
1336    }
1337
1338    #[test]
1339    fn test_override_skip_macro_invocations() {
1340        let mut config = Config::default();
1341        config.override_value("skip_macro_invocations", r#"["*", "println"]"#);
1342        assert_eq!(
1343            config.skip_macro_invocations(),
1344            MacroSelectors(vec![
1345                MacroSelector::All,
1346                MacroSelector::Name(MacroName::new("println".to_owned()))
1347            ])
1348        );
1349    }
1350
1351    #[cfg(test)]
1352    mod required_version {
1353        use super::*;
1354
1355        #[allow(dead_code)] // Only used in tests
1356        fn get_current_version() -> semver::Version {
1357            semver::Version::parse(env!("CARGO_PKG_VERSION")).unwrap()
1358        }
1359
1360        #[nightly_only_test]
1361        #[test]
1362        fn test_required_version_default() {
1363            let config = Config::default();
1364            assert!(config.version_meets_requirement());
1365        }
1366
1367        #[nightly_only_test]
1368        #[test]
1369        fn test_current_required_version() {
1370            let toml = format!("required_version=\"{}\"", env!("CARGO_PKG_VERSION"));
1371            let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1372
1373            assert!(config.version_meets_requirement());
1374        }
1375
1376        #[nightly_only_test]
1377        #[test]
1378        fn test_required_version_above() {
1379            let toml = "required_version=\"1000.0.0\"";
1380            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1381
1382            assert!(!config.version_meets_requirement());
1383        }
1384
1385        #[nightly_only_test]
1386        #[test]
1387        fn test_required_version_below() {
1388            let versions = vec!["0.0.0", "0.0.1", "0.1.0"];
1389
1390            for version in versions {
1391                let toml = format!("required_version=\"{}\"", version.to_string());
1392                let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1393
1394                assert!(!config.version_meets_requirement());
1395            }
1396        }
1397
1398        #[nightly_only_test]
1399        #[test]
1400        fn test_required_version_tilde() {
1401            let toml = format!("required_version=\"~{}\"", env!("CARGO_PKG_VERSION"));
1402            let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1403
1404            assert!(config.version_meets_requirement());
1405        }
1406
1407        #[nightly_only_test]
1408        #[test]
1409        fn test_required_version_caret() {
1410            let current_version = get_current_version();
1411
1412            for minor in current_version.minor..0 {
1413                let toml = format!(
1414                    "required_version=\"^{}.{}.0\"",
1415                    current_version.major.to_string(),
1416                    minor.to_string()
1417                );
1418                let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1419
1420                assert!(!config.version_meets_requirement());
1421            }
1422        }
1423
1424        #[nightly_only_test]
1425        #[test]
1426        fn test_required_version_greater_than() {
1427            let toml = "required_version=\">1.0.0\"";
1428            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1429
1430            assert!(config.version_meets_requirement());
1431        }
1432
1433        #[nightly_only_test]
1434        #[test]
1435        fn test_required_version_less_than() {
1436            let toml = "required_version=\"<1.0.0\"";
1437            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1438
1439            assert!(!config.version_meets_requirement());
1440        }
1441
1442        #[nightly_only_test]
1443        #[test]
1444        fn test_required_version_range() {
1445            let current_version = get_current_version();
1446
1447            let toml = format!(
1448                "required_version=\">={}.0.0, <{}.0.0\"",
1449                current_version.major,
1450                current_version.major + 1
1451            );
1452            let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1453
1454            assert!(config.version_meets_requirement());
1455        }
1456
1457        #[nightly_only_test]
1458        #[test]
1459        fn test_required_version_exact_boundary() {
1460            let toml = format!("required_version=\"{}\"", get_current_version().to_string());
1461            let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1462
1463            assert!(config.version_meets_requirement());
1464        }
1465
1466        #[nightly_only_test]
1467        #[test]
1468        fn test_required_version_pre_release() {
1469            let toml = format!(
1470                "required_version=\"^{}-alpha\"",
1471                get_current_version().to_string()
1472            );
1473            let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1474
1475            assert!(config.version_meets_requirement());
1476        }
1477
1478        #[nightly_only_test]
1479        #[test]
1480        fn test_required_version_with_build_metadata() {
1481            let toml = format!(
1482                "required_version=\"{}+build.1\"",
1483                get_current_version().to_string()
1484            );
1485
1486            let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1487
1488            assert!(config.version_meets_requirement());
1489        }
1490
1491        #[nightly_only_test]
1492        #[test]
1493        fn test_required_version_invalid_specification() {
1494            let toml = "required_version=\"not.a.version\"";
1495            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1496
1497            assert!(!config.version_meets_requirement())
1498        }
1499
1500        #[nightly_only_test]
1501        #[test]
1502        fn test_required_version_complex_range() {
1503            let current_version = get_current_version();
1504
1505            let toml = format!(
1506                "required_version=\">={}.0.0, <{}.0.0, ~{}.{}.0\"",
1507                current_version.major,
1508                current_version.major + 1,
1509                current_version.major,
1510                current_version.minor
1511            );
1512            let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1513
1514            assert!(config.version_meets_requirement());
1515        }
1516
1517        #[nightly_only_test]
1518        #[test]
1519        fn test_required_version_wildcard_major() {
1520            let toml = "required_version=\"1.x\"";
1521            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1522
1523            assert!(config.version_meets_requirement());
1524        }
1525
1526        #[nightly_only_test]
1527        #[test]
1528        fn test_required_version_wildcard_any() {
1529            let toml = "required_version=\"*\"";
1530            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1531
1532            assert!(config.version_meets_requirement());
1533        }
1534
1535        #[nightly_only_test]
1536        #[test]
1537        fn test_required_version_major_version_zero() {
1538            let toml = "required_version=\"0.1.0\"";
1539            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1540
1541            assert!(!config.version_meets_requirement());
1542        }
1543
1544        #[nightly_only_test]
1545        #[test]
1546        fn test_required_version_future_major_version() {
1547            let toml = "required_version=\"3.0.0\"";
1548            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1549
1550            assert!(!config.version_meets_requirement());
1551        }
1552
1553        #[nightly_only_test]
1554        #[test]
1555        fn test_required_version_fail_different_operator() {
1556            // != is not supported
1557            let toml = "required_version=\"!=1.0.0\"";
1558            let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1559
1560            assert!(!config.version_meets_requirement());
1561        }
1562    }
1563
1564    #[cfg(test)]
1565    mod check_semver_version {
1566        use super::*;
1567
1568        #[test]
1569        fn test_exact_version_match() {
1570            assert!(check_semver_version("1.0.0", "1.0.0"));
1571            assert!(!check_semver_version("1.0.0", "1.1.0"));
1572            assert!(!check_semver_version("1.0.0", "1.0.1"));
1573            assert!(!check_semver_version("1.0.0", "2.1.0"));
1574            assert!(!check_semver_version("1.0.0", "0.1.0"));
1575            assert!(!check_semver_version("1.0.0", "0.0.1"));
1576        }
1577
1578        #[test]
1579        fn test_version_mismatch() {
1580            assert!(!check_semver_version("2.0.0", "1.0.0"));
1581        }
1582
1583        #[test]
1584        fn test_patch_version_greater() {
1585            assert!(check_semver_version("^1.0.0", "1.0.1"));
1586        }
1587
1588        #[test]
1589        fn test_minor_version_greater() {
1590            assert!(check_semver_version("^1.0.0", "1.1.0"));
1591        }
1592
1593        #[test]
1594        fn test_major_version_less() {
1595            assert!(!check_semver_version("1.0.0", "0.9.0"));
1596        }
1597
1598        #[test]
1599        fn test_prerelease_less_than_release() {
1600            assert!(!check_semver_version("1.0.0", "1.0.0-alpha"));
1601        }
1602
1603        #[test]
1604        fn test_prerelease_version_specific_match() {
1605            assert!(check_semver_version("1.0.0-alpha", "1.0.0-alpha"));
1606        }
1607
1608        #[test]
1609        fn test_build_metadata_ignored() {
1610            assert!(check_semver_version("1.0.0", "1.0.0+build.1"));
1611        }
1612
1613        #[test]
1614        fn test_greater_than_requirement() {
1615            assert!(check_semver_version(">1.0.0", "1.1.0"));
1616        }
1617
1618        #[test]
1619        fn test_less_than_requirement_fails_when_greater() {
1620            assert!(!check_semver_version("<1.0.0", "1.1.0"));
1621        }
1622
1623        #[test]
1624        fn test_caret_requirement_matches_minor_update() {
1625            assert!(check_semver_version("^1.1.0", "1.2.0"));
1626        }
1627
1628        #[test]
1629        fn test_tilde_requirement_matches_patch_update() {
1630            assert!(check_semver_version("~1.0.0", "1.0.1"));
1631        }
1632
1633        #[test]
1634        fn test_range_requirement_inclusive() {
1635            assert!(check_semver_version(">=1.0.0, <2.0.0", "1.5.0"));
1636        }
1637
1638        #[test]
1639        fn test_pre_release_specific_match() {
1640            assert!(check_semver_version("1.0.0-alpha.1", "1.0.0-alpha.1"));
1641        }
1642
1643        #[test]
1644        fn test_pre_release_non_match_when_requiring_release() {
1645            assert!(!check_semver_version("1.0.0", "1.0.0-alpha.1"));
1646        }
1647
1648        // That's not our choice. `semver` does not support `||` operator.
1649        // Only asserting here to ensure this behavior (which match our docs).
1650        #[test]
1651        fn test_invalid_or() {
1652            assert!(!check_semver_version("1.0.0 || 2.0.0", "1.0.0"));
1653            assert!(!check_semver_version("1.0.0 || 2.0.0", "2.0.0"));
1654            assert!(!check_semver_version("1.0.0 || 2.0.0", "3.0.0"));
1655        }
1656
1657        #[test]
1658        fn test_wildcard_match_minor() {
1659            assert!(check_semver_version("1.*", "1.1.0"));
1660            assert!(check_semver_version("1.*, <2.0.0", "1.1.0"));
1661        }
1662
1663        #[test]
1664        fn test_wildcard_mismatch() {
1665            assert!(!check_semver_version("1.*, <2.0.0", "2.1.0"));
1666            assert!(!check_semver_version("1.*, <2.0.0", "2.0.0"));
1667            assert!(!check_semver_version("1.*, <2.*", "2.1.0"));
1668            assert!(!check_semver_version("1.*, <2.*", "2.0.0"));
1669
1670            assert!(!check_semver_version("1.*, >2.0.0", "1.1.0"));
1671            assert!(!check_semver_version("1.*, >2.0.0", "1.0.0"));
1672            assert!(!check_semver_version("1.*, >2.*", "1.1.0"));
1673            assert!(!check_semver_version("1.*, >2.*", "1.0.0"));
1674
1675            assert!(!check_semver_version("<1.5.0, >1.10.*", "1.6.0"));
1676        }
1677
1678        #[test]
1679        fn test_wildcard_match_major() {
1680            assert!(check_semver_version("2.*", "2.0.0"));
1681        }
1682
1683        #[test]
1684        fn test_wildcard_match_patch() {
1685            assert!(check_semver_version("1.0.*", "1.0.1"));
1686        }
1687
1688        #[test]
1689        fn test_invalid_inputs() {
1690            assert!(!check_semver_version("not.a.requirement", "1.0.0"));
1691            assert!(!check_semver_version("1.0.0", "not.a.version"));
1692        }
1693
1694        #[test]
1695        fn test_version_with_pre_release_and_build() {
1696            assert!(check_semver_version("1.0.0-alpha", "1.0.0-alpha+001"));
1697        }
1698
1699        // Demonstrates precedence of numeric identifiers over alphanumeric in pre-releases
1700        #[test]
1701        fn test_pre_release_numeric_vs_alphanumeric() {
1702            assert!(!check_semver_version("^1.0.0-alpha.beta", "1.0.0-alpha.1"));
1703            assert!(check_semver_version("^1.0.0-alpha.1", "1.0.0-alpha.beta"));
1704        }
1705
1706        // Any version is allowed when * is used
1707        #[test]
1708        fn test_wildcard_any() {
1709            assert!(check_semver_version("*", "1.0.0"));
1710            assert!(check_semver_version("*", "1.0.0+build"));
1711        }
1712
1713        // Demonstrates lexicographic ordering of alphanumeric identifiers in pre-releases
1714        #[test]
1715        fn test_pre_release_lexicographic_ordering() {
1716            assert!(check_semver_version(
1717                "^1.0.0-alpha.alpha",
1718                "1.0.0-alpha.beta",
1719            ));
1720            assert!(!check_semver_version(
1721                "^1.0.0-alpha.beta",
1722                "1.0.0-alpha.alpha",
1723            ));
1724        }
1725
1726        // These are not allowed. '*' can't be used with other version specifiers.
1727        #[test]
1728        fn test_wildcard_any_with_range() {
1729            assert!(!check_semver_version("*, <2.0.0", "1.0.0"));
1730            assert!(!check_semver_version("*, 1.0.0", "1.5.0"));
1731        }
1732    }
1733}