1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use std::default::Default;
15 use std::io::{Error, ErrorKind, Read};
16 use std::path::{Path, PathBuf};
29 use config::config_type::ConfigType;
30 use config::file_lines::FileLines;
31 pub use config::lists::*;
32 pub use config::options::*;
33 use config::summary::Summary;
35 /// This macro defines configuration options used in rustfmt. Each option
36 /// is defined as follows:
38 /// `name: value type, default value, is stable, description;`
41 max_width: usize, 100, true, "Maximum width of each line";
42 hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
43 tab_spaces: usize, 4, true, "Number of spaces per tab";
44 newline_style: NewlineStyle, NewlineStyle::Unix, true, "Unix or Windows line endings";
45 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
46 use_small_heuristics: bool, true, false, "Whether to use different formatting for items and \
47 expressions if they satisfy a heuristic notion of 'small'.";
49 // strings and comments
50 format_strings: bool, false, false, "Format string literals where necessary";
51 wrap_comments: bool, false, true, "Break comments to fit on the line";
52 comment_width: usize, 80, false,
53 "Maximum length of comments. No effect unless wrap_comments = true";
54 normalize_comments: bool, false, true, "Convert /* */ comments to // comments where possible";
55 license_template_path: String, String::default(), false, "Beginning of file must match license template";
57 // Single line expressions and items.
58 empty_item_single_line: bool, true, false,
59 "Put empty-body functions and impls on a single line";
60 struct_lit_single_line: bool, true, false,
61 "Put small struct literals on a single line";
62 fn_single_line: bool, false, false, "Put single-expression functions on a single line";
63 where_single_line: bool, false, false, "To force single line where layout";
66 imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
67 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
70 reorder_extern_crates: bool, true, false, "Reorder extern crate statements alphabetically";
71 reorder_extern_crates_in_group: bool, true, false, "Reorder extern crate statements in group";
72 reorder_imports: bool, false, false, "Reorder import statements alphabetically";
73 reorder_imports_in_group: bool, false, false, "Reorder import statements in group";
74 reorder_imported_names: bool, true, false,
75 "Reorder lists of names in import statements alphabetically";
76 reorder_modules: bool, false, false, "Reorder module statemtents alphabetically in group";
78 // Spaces around punctuation
79 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
80 "Where to put a binary operator when a binary expression goes multiline.";
81 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
82 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
83 space_before_colon: bool, false, false, "Leave a space before the colon";
84 space_after_colon: bool, true, false, "Leave a space after the colon";
85 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ... range operators";
86 spaces_within_parens_and_brackets: bool, false, false,
87 "Put spaces within non-empty parentheses or brackets";
90 combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
91 struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
93 remove_blank_lines_at_start_or_end_of_block: bool, true, false,
94 "Remove blank lines at start or end of a block";
95 match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
96 the same line with the pattern of arms";
97 force_multiline_blocks: bool, false, false,
98 "Force multiline closure bodies and match arms to be wrapped in a block";
99 fn_args_density: Density, Density::Tall, false, "Argument density in functions";
100 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
101 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
102 "Brace style for control flow constructs";
103 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
104 "How to handle trailing commas for lists";
105 trailing_semicolon: bool, true, false,
106 "Add trailing semicolon after break, continue and return";
107 match_block_trailing_comma: bool, false, false,
108 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
109 blank_lines_upper_bound: usize, 1, false,
110 "Maximum number of blank lines which can be put between items.";
111 blank_lines_lower_bound: usize, 0, false,
112 "Minimum number of blank lines which must be put between items.";
114 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
115 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
116 use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
117 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
119 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
120 use_field_init_shorthand: bool, false, false, "Use field initialization shorthand if possible";
122 // Control options (changes the operation of rustfmt, rather than the formatting)
123 write_mode: WriteMode, WriteMode::Overwrite, false,
124 "What Write Mode to use when none is supplied: \
125 Replace, Overwrite, Display, Plain, Diff, Coverage";
126 color: Color, Color::Auto, false,
127 "What Color option to use when none is supplied: Always, Never, Auto";
128 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
129 "Require a specific version of rustfmt.";
130 unstable_features: bool, false, true,
131 "Enables unstable features. Only available on nightly channel";
132 disable_all_formatting: bool, false, false, "Don't reformat anything";
133 skip_children: bool, false, false, "Don't reformat out of line modules";
134 hide_parse_errors: bool, false, false, "Hide errors from the parser";
135 error_on_line_overflow: bool, true, false, "Error if unable to get all lines within max_width";
136 error_on_unformatted: bool, false, false,
137 "Error if unable to get comments or string literals within max_width, \
138 or they are left with trailing whitespaces";
139 report_todo: ReportTactic, ReportTactic::Never, false,
140 "Report all, none or unnumbered occurrences of TODO in source file comments";
141 report_fixme: ReportTactic, ReportTactic::Never, false,
142 "Report all, none or unnumbered occurrences of FIXME in source file comments";
145 verbose: bool, false, false, "Use verbose output";
146 file_lines: FileLines, FileLines::all(), false,
147 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
148 via the --file-lines option";
149 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
150 "'small' heuristic values";
153 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
155 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
156 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
157 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
158 for config_file_name in &CONFIG_FILE_NAMES {
159 let config_file = dir.join(config_file_name);
160 match fs::metadata(&config_file) {
161 // Only return if it's a file to handle the unlikely situation of a directory named
163 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
164 // Return the error if it's something other than `NotFound`; otherwise we didn't
165 // find the project file yet, and continue searching.
167 if e.kind() != ErrorKind::NotFound {
177 /// Convert the license template into a string which can be turned into a regex.
179 /// The license template could use regex syntax directly, but that would require a lot of manual
180 /// escaping, which is inconvenient. It is therefore literal by default, with optional regex
181 /// subparts delimited by `{` and `}`. Additionally:
183 /// - to insert literal `{`, `}` or `\`, escape it with `\`
184 /// - an empty regex placeholder (`{}`) is shorthand for `{.*?}`
186 /// This function parses this input format and builds a properly escaped *string* representation of
187 /// the equivalent regular expression. It **does not** however guarantee that the returned string is
188 /// a syntactically valid regular expression.
194 /// rustfmt_config::parse_license_template(
196 /// // Copyright {\d+} The \} Rust \\ Project \{ Developers. See the {([A-Z]+)}
197 /// // file at the top-level directory of this distribution and at
200 /// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
201 /// // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
202 /// // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
203 /// // option. This file may not be copied, modified, or distributed
204 /// // except according to those terms.
208 /// // Copyright \d+ The \} Rust \\ Project \{ Developers\. See the ([A-Z]+)
209 /// // file at the top\-level directory of this distribution and at
212 /// // Licensed under the Apache License, Version 2\.0 <LICENSE\-APACHE or
213 /// // http://www\.apache\.org/licenses/LICENSE\-2\.0> or the MIT license
214 /// // <LICENSE\-MIT or http://opensource\.org/licenses/MIT>, at your
215 /// // option\. This file may not be copied, modified, or distributed
216 /// // except according to those terms\.
220 pub fn parse_license_template(template: &str) -> Result<String, String> {
221 // the template is parsed using a state machine
225 // the u32 keeps track of brace nesting
230 let mut parsed = String::from("^");
231 let mut buffer = String::new();
232 let mut state = State::Lit;
234 // keeps track of last line on which a regex placeholder was started
235 let mut open_brace_line = 0;
236 for chr in template.chars() {
240 state = match state {
241 State::Lit => match chr {
243 parsed.push_str(®ex::escape(&buffer));
245 open_brace_line = linum;
248 '}' => return Err(format!("escape or balance closing brace on l. {}", linum)),
249 '\\' => State::LitEsc,
259 State::Re(brace_nesting) => {
263 State::Re(brace_nesting + 1)
266 match brace_nesting {
268 // default regex for empty placeholder {}
269 if buffer.is_empty() {
270 buffer = ".*?".to_string();
272 parsed.push_str(&buffer);
278 State::Re(brace_nesting - 1)
284 State::ReEsc(brace_nesting)
288 State::Re(brace_nesting)
292 State::ReEsc(brace_nesting) => {
294 State::Re(brace_nesting)
299 State::Re(_) | State::ReEsc(_) => {
301 "escape or balance opening brace on l. {}",
305 State::LitEsc => return Err(format!("incomplete escape sequence on l. {}", linum)),
308 parsed.push_str(®ex::escape(&buffer));
315 use super::{parse_license_template, Config};
318 fn test_config_set() {
319 let mut config = Config::default();
320 config.set().verbose(false);
321 assert_eq!(config.verbose(), false);
322 config.set().verbose(true);
323 assert_eq!(config.verbose(), true);
327 fn test_config_used_to_toml() {
328 let config = Config::default();
330 let merge_derives = config.merge_derives();
331 let skip_children = config.skip_children();
333 let used_options = config.used_options();
334 let toml = used_options.to_toml().unwrap();
338 "merge_derives = {}\nskip_children = {}\n",
339 merge_derives, skip_children,
346 let config = Config::from_toml("hard_tabs = true").unwrap();
348 assert_eq!(config.was_set().hard_tabs(), true);
349 assert_eq!(config.was_set().verbose(), false);
353 fn test_parse_license_template() {
355 parse_license_template("literal (.*)").unwrap(),
359 parse_license_template(r"escaping \}").unwrap(),
362 assert!(parse_license_template("unbalanced } without escape").is_err());
364 parse_license_template(r"{\d+} place{-?}holder{s?}").unwrap(),
365 r"^\d+ place-?holders?"
368 parse_license_template("default {}").unwrap(),
372 parse_license_template(r"unbalanced nested braces {\{{3}}").unwrap(),
373 r"^unbalanced nested braces \{{3}"
376 parse_license_template("parsing error }").unwrap_err(),
377 "escape or balance closing brace on l. 1"
380 parse_license_template("parsing error {\nsecond line").unwrap_err(),
381 "escape or balance opening brace on l. 1"
384 parse_license_template(r"parsing error \").unwrap_err(),
385 "incomplete escape sequence on l. 1"
389 // FIXME(#2183) these tests cannot be run in parallel because they use env vars
391 // fn test_as_not_nightly_channel() {
392 // let mut config = Config::default();
393 // assert_eq!(config.was_set().unstable_features(), false);
394 // config.set().unstable_features(true);
395 // assert_eq!(config.was_set().unstable_features(), false);
399 // fn test_as_nightly_channel() {
400 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
401 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
402 // let mut config = Config::default();
403 // config.set().unstable_features(true);
404 // assert_eq!(config.was_set().unstable_features(), false);
405 // config.set().unstable_features(true);
406 // assert_eq!(config.unstable_features(), true);
407 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
411 // fn test_unstable_from_toml() {
412 // let mut config = Config::from_toml("unstable_features = true").unwrap();
413 // assert_eq!(config.was_set().unstable_features(), false);
414 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
415 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
416 // config = Config::from_toml("unstable_features = true").unwrap();
417 // assert_eq!(config.was_set().unstable_features(), true);
418 // assert_eq!(config.unstable_features(), true);
419 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);