]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
Move license template parsing into config phase
[rust.git] / src / config / mod.rs
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.
4 //
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.
10
11 use std::{env, fs};
12 use std::cell::Cell;
13 use std::default::Default;
14 use std::fs::File;
15 use std::io::{Error, ErrorKind, Read};
16 use std::path::{Path, PathBuf};
17
18 use regex::Regex;
19
20 #[macro_use]
21 mod config_type;
22 #[macro_use]
23 mod options;
24
25 pub mod file_lines;
26 pub mod lists;
27 pub mod summary;
28
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;
34
35 /// This macro defines configuration options used in rustfmt. Each option
36 /// is defined as follows:
37 ///
38 /// `name: value type, default value, is stable, description;`
39 create_config! {
40     // Fundamental stuff
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'.";
48
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";
56
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";
64
65     // Imports
66     imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
67     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
68
69     // Ordering
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";
77
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";
88
89     // Misc.
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 \
92                                              threshold.";
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.";
113
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 .. \
118                                               in tuple patterns";
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";
121
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";
143
144     // Not user-facing.
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";
151 }
152
153 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
154 ///
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
162             // `rustfmt.toml`.
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.
166             Err(e) => {
167                 if e.kind() != ErrorKind::NotFound {
168                     return Err(e);
169                 }
170             }
171             _ => {}
172         }
173     }
174     Ok(None)
175 }
176
177 /// Convert the license template into a string which can be turned into a regex.
178 ///
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:
182 ///
183 /// - to insert literal `{`, `}` or `\`, escape it with `\`
184 /// - an empty regex placeholder (`{}`) is shorthand for `{.*?}`
185 ///
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.
189 ///
190 /// # Examples
191 ///
192 /// ```
193 /// assert_eq!(
194 ///     rustfmt_config::parse_license_template(
195 ///         r"
196 /// // Copyright {\d+} The \} Rust \\ Project \{ Developers. See the {([A-Z]+)}
197 /// // file at the top-level directory of this distribution and at
198 /// // {}.
199 /// //
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.
205 /// "
206 ///     ).unwrap(),
207 ///     r"^
208 /// // Copyright \d+ The \} Rust \\ Project \{ Developers\. See the ([A-Z]+)
209 /// // file at the top\-level directory of this distribution and at
210 /// // .*?\.
211 /// //
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\.
217 /// "
218 /// );
219 /// ```
220 pub fn parse_license_template(template: &str) -> Result<String, String> {
221     // the template is parsed using a state machine
222     enum State {
223         Lit,
224         LitEsc,
225         // the u32 keeps track of brace nesting
226         Re(u32),
227         ReEsc(u32),
228     }
229
230     let mut parsed = String::from("^");
231     let mut buffer = String::new();
232     let mut state = State::Lit;
233     let mut linum = 1;
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() {
237         if chr == '\n' {
238             linum += 1;
239         }
240         state = match state {
241             State::Lit => match chr {
242                 '{' => {
243                     parsed.push_str(&regex::escape(&buffer));
244                     buffer.clear();
245                     open_brace_line = linum;
246                     State::Re(1)
247                 }
248                 '}' => return Err(format!("escape or balance closing brace on l. {}", linum)),
249                 '\\' => State::LitEsc,
250                 _ => {
251                     buffer.push(chr);
252                     State::Lit
253                 }
254             },
255             State::LitEsc => {
256                 buffer.push(chr);
257                 State::Lit
258             }
259             State::Re(brace_nesting) => {
260                 match chr {
261                     '{' => {
262                         buffer.push(chr);
263                         State::Re(brace_nesting + 1)
264                     }
265                     '}' => {
266                         match brace_nesting {
267                             1 => {
268                                 // default regex for empty placeholder {}
269                                 if buffer.is_empty() {
270                                     buffer = ".*?".to_string();
271                                 }
272                                 parsed.push_str(&buffer);
273                                 buffer.clear();
274                                 State::Lit
275                             }
276                             _ => {
277                                 buffer.push(chr);
278                                 State::Re(brace_nesting - 1)
279                             }
280                         }
281                     }
282                     '\\' => {
283                         buffer.push(chr);
284                         State::ReEsc(brace_nesting)
285                     }
286                     _ => {
287                         buffer.push(chr);
288                         State::Re(brace_nesting)
289                     }
290                 }
291             }
292             State::ReEsc(brace_nesting) => {
293                 buffer.push(chr);
294                 State::Re(brace_nesting)
295             }
296         }
297     }
298     match state {
299         State::Re(_) | State::ReEsc(_) => {
300             return Err(format!(
301                 "escape or balance opening brace on l. {}",
302                 open_brace_line
303             ));
304         }
305         State::LitEsc => return Err(format!("incomplete escape sequence on l. {}", linum)),
306         _ => (),
307     }
308     parsed.push_str(&regex::escape(&buffer));
309
310     Ok(parsed)
311 }
312
313 #[cfg(test)]
314 mod test {
315     use super::{parse_license_template, Config};
316
317     #[test]
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);
324     }
325
326     #[test]
327     fn test_config_used_to_toml() {
328         let config = Config::default();
329
330         let merge_derives = config.merge_derives();
331         let skip_children = config.skip_children();
332
333         let used_options = config.used_options();
334         let toml = used_options.to_toml().unwrap();
335         assert_eq!(
336             toml,
337             format!(
338                 "merge_derives = {}\nskip_children = {}\n",
339                 merge_derives, skip_children,
340             )
341         );
342     }
343
344     #[test]
345     fn test_was_set() {
346         let config = Config::from_toml("hard_tabs = true").unwrap();
347
348         assert_eq!(config.was_set().hard_tabs(), true);
349         assert_eq!(config.was_set().verbose(), false);
350     }
351
352     #[test]
353     fn test_parse_license_template() {
354         assert_eq!(
355             parse_license_template("literal (.*)").unwrap(),
356             r"^literal \(\.\*\)"
357         );
358         assert_eq!(
359             parse_license_template(r"escaping \}").unwrap(),
360             r"^escaping \}"
361         );
362         assert!(parse_license_template("unbalanced } without escape").is_err());
363         assert_eq!(
364             parse_license_template(r"{\d+} place{-?}holder{s?}").unwrap(),
365             r"^\d+ place-?holders?"
366         );
367         assert_eq!(
368             parse_license_template("default {}").unwrap(),
369             "^default .*?"
370         );
371         assert_eq!(
372             parse_license_template(r"unbalanced nested braces {\{{3}}").unwrap(),
373             r"^unbalanced nested braces \{{3}"
374         );
375         assert_eq!(
376             parse_license_template("parsing error }").unwrap_err(),
377             "escape or balance closing brace on l. 1"
378         );
379         assert_eq!(
380             parse_license_template("parsing error {\nsecond line").unwrap_err(),
381             "escape or balance opening brace on l. 1"
382         );
383         assert_eq!(
384             parse_license_template(r"parsing error \").unwrap_err(),
385             "incomplete escape sequence on l. 1"
386         );
387     }
388
389     // FIXME(#2183) these tests cannot be run in parallel because they use env vars
390     // #[test]
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);
396     // }
397
398     // #[test]
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);
408     // }
409
410     // #[test]
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);
420     // }
421 }