]> git.lizzy.rs Git - rust.git/blob - src/config.rs
Merge pull request #1745 from topecongiro/assignment
[rust.git] / src / config.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 extern crate toml;
12
13 use std::cell::Cell;
14 use std::fs;
15 use std::fs::File;
16 use std::env;
17 use std::io::{Error, ErrorKind, Read};
18 use std::path::{Path, PathBuf};
19
20 use file_lines::FileLines;
21 use lists::{SeparatorTactic, ListTactic};
22
23 macro_rules! configuration_option_enum{
24     ($e:ident: $( $x:ident ),+ $(,)*) => {
25         #[derive(Copy, Clone, Eq, PartialEq, Debug)]
26         pub enum $e {
27             $( $x ),+
28         }
29
30         impl_enum_serialize_and_deserialize!($e, $( $x ),+);
31     }
32 }
33
34 configuration_option_enum! { Style:
35     Rfc, // Follow the style RFCs style.
36     Legacy, // Follow the traditional Rustfmt style.
37 }
38
39 configuration_option_enum! { NewlineStyle:
40     Windows, // \r\n
41     Unix, // \n
42     Native, // \r\n in Windows, \n on other platforms
43 }
44
45 configuration_option_enum! { BraceStyle:
46     AlwaysNextLine,
47     PreferSameLine,
48     // Prefer same line except where there is a where clause, in which case force
49     // the brace to the next line.
50     SameLineWhere,
51 }
52
53 configuration_option_enum! { ControlBraceStyle:
54     // K&R style, Rust community default
55     AlwaysSameLine,
56     // Stroustrup style
57     ClosingNextLine,
58     // Allman style
59     AlwaysNextLine,
60 }
61
62 // How to indent a function's return type.
63 configuration_option_enum! { ReturnIndent:
64     // Aligned with the arguments
65     WithArgs,
66     // Aligned with the where clause
67     WithWhereClause,
68 }
69
70 configuration_option_enum! { IndentStyle:
71     // First line on the same line as the opening brace, all lines aligned with
72     // the first line.
73     Visual,
74     // First line is on a new line and all lines align with block indent.
75     Block,
76 }
77
78 configuration_option_enum! { Density:
79     // Fit as much on one line as possible.
80     Compressed,
81     // Use more lines.
82     Tall,
83     // Try to compress if the body is empty.
84     CompressedIfEmpty,
85     // Place every item on a separate line.
86     Vertical,
87 }
88
89 configuration_option_enum! { TypeDensity:
90     // No spaces around "=" and "+"
91     Compressed,
92     // Spaces around " = " and " + "
93     Wide,
94 }
95
96
97 impl Density {
98     pub fn to_list_tactic(self) -> ListTactic {
99         match self {
100             Density::Compressed => ListTactic::Mixed,
101             Density::Tall |
102             Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
103             Density::Vertical => ListTactic::Vertical,
104         }
105     }
106 }
107
108 configuration_option_enum! { LicensePolicy:
109     // Do not place license text at top of files
110     NoLicense,
111     // Use the text in "license" field as the license
112     TextLicense,
113     // Use a text file as the license text
114     FileLicense,
115 }
116
117 configuration_option_enum! { MultilineStyle:
118     // Use horizontal layout if it fits in one line, fall back to vertical
119     PreferSingle,
120     // Use vertical layout
121     ForceMulti,
122 }
123
124 impl MultilineStyle {
125     pub fn to_list_tactic(self) -> ListTactic {
126         match self {
127             MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
128             MultilineStyle::ForceMulti => ListTactic::Vertical,
129         }
130     }
131 }
132
133 configuration_option_enum! { ReportTactic:
134     Always,
135     Unnumbered,
136     Never,
137 }
138
139 configuration_option_enum! { WriteMode:
140     // Backs the original file up and overwrites the original.
141     Replace,
142     // Overwrites original file without backup.
143     Overwrite,
144     // Writes the output to stdout.
145     Display,
146     // Writes the diff to stdout.
147     Diff,
148     // Displays how much of the input file was processed
149     Coverage,
150     // Unfancy stdout
151     Plain,
152     // Outputs a checkstyle XML file.
153     Checkstyle,
154 }
155
156 /// Trait for types that can be used in `Config`.
157 pub trait ConfigType: Sized {
158     /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
159     /// pipe-separated list of variants; for other types it returns "<type>".
160     fn doc_hint() -> String;
161 }
162
163 impl ConfigType for bool {
164     fn doc_hint() -> String {
165         String::from("<boolean>")
166     }
167 }
168
169 impl ConfigType for usize {
170     fn doc_hint() -> String {
171         String::from("<unsigned integer>")
172     }
173 }
174
175 impl ConfigType for isize {
176     fn doc_hint() -> String {
177         String::from("<signed integer>")
178     }
179 }
180
181 impl ConfigType for String {
182     fn doc_hint() -> String {
183         String::from("<string>")
184     }
185 }
186
187 impl ConfigType for FileLines {
188     fn doc_hint() -> String {
189         String::from("<json>")
190     }
191 }
192
193 pub struct ConfigHelpItem {
194     option_name: &'static str,
195     doc_string: &'static str,
196     variant_names: String,
197     default: &'static str,
198 }
199
200 impl ConfigHelpItem {
201     pub fn option_name(&self) -> &'static str {
202         self.option_name
203     }
204
205     pub fn doc_string(&self) -> &'static str {
206         self.doc_string
207     }
208
209     pub fn variant_names(&self) -> &String {
210         &self.variant_names
211     }
212
213     pub fn default(&self) -> &'static str {
214         self.default
215     }
216 }
217
218 macro_rules! create_config {
219     ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => (
220         #[derive(Clone)]
221         pub struct Config {
222             // For each config item, we store a bool indicating whether it has
223             // been accessed and the value, and a bool whether the option was
224             // manually initialised, or taken from the default,
225             $($i: (Cell<bool>, bool, $ty)),+
226         }
227
228         // Just like the Config struct but with each property wrapped
229         // as Option<T>. This is used to parse a rustfmt.toml that doesn't
230         // specity all properties of `Config`.
231         // We first parse into `PartialConfig`, then create a default `Config`
232         // and overwrite the properties with corresponding values from `PartialConfig`.
233         #[derive(Deserialize, Serialize, Clone)]
234         pub struct PartialConfig {
235             $(pub $i: Option<$ty>),+
236         }
237
238         impl PartialConfig {
239             pub fn to_toml(&self) -> Result<String, String> {
240                 // file_lines can't be specified in TOML
241                 let mut cloned = self.clone();
242                 cloned.file_lines = None;
243
244                 toml::to_string(&cloned)
245                     .map_err(|e| format!("Could not output config: {}", e.to_string()))
246             }
247         }
248
249         // Macro hygiene won't allow us to make `set_$i()` methods on Config
250         // for each item, so this struct is used to give the API to set values:
251         // `config.get().option(false)`. It's pretty ugly. Consider replacing
252         // with `config.set_option(false)` if we ever get a stable/usable
253         // `concat_idents!()`.
254         pub struct ConfigSetter<'a>(&'a mut Config);
255
256         impl<'a> ConfigSetter<'a> {
257             $(
258             pub fn $i(&mut self, value: $ty) {
259                 (self.0).$i.2 = value;
260             }
261             )+
262         }
263
264         // Query each option, returns true if the user set the option, false if
265         // a default was used.
266         pub struct ConfigWasSet<'a>(&'a Config);
267
268         impl<'a> ConfigWasSet<'a> {
269             $(
270             pub fn $i(&self) -> bool {
271                 (self.0).$i.1
272             }
273             )+
274         }
275
276         impl Config {
277
278             $(
279             pub fn $i(&self) -> $ty {
280                 self.$i.0.set(true);
281                 self.$i.2.clone()
282             }
283             )+
284
285             pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
286                 ConfigSetter(self)
287             }
288
289             pub fn was_set<'a>(&'a self) -> ConfigWasSet<'a> {
290                 ConfigWasSet(self)
291             }
292
293             fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
294             $(
295                 if let Some(val) = parsed.$i {
296                     self.$i.1 = true;
297                     self.$i.2 = val;
298                 }
299             )+
300                 self
301             }
302
303             pub fn from_toml(toml: &str) -> Result<Config, String> {
304                 let parsed: toml::Value =
305                     toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
306                 let mut err: String = String::new();
307                 {
308                     let table = parsed
309                         .as_table()
310                         .ok_or(String::from("Parsed config was not table"))?;
311                     for (key, _) in table {
312                         match &**key {
313                             $(
314                                 stringify!($i) => (),
315                             )+
316                                 _ => {
317                                     let msg =
318                                         &format!("Warning: Unknown configuration option `{}`\n",
319                                                  key);
320                                     err.push_str(msg)
321                                 }
322                         }
323                     }
324                 }
325                 match parsed.try_into() {
326                     Ok(parsed_config) =>
327                         Ok(Config::default().fill_from_parsed_config(parsed_config)),
328                     Err(e) => {
329                         err.push_str("Error: Decoding config file failed:\n");
330                         err.push_str(format!("{}\n", e).as_str());
331                         err.push_str("Please check your config file.\n");
332                         Err(err)
333                     }
334                 }
335             }
336
337             pub fn used_options(&self) -> PartialConfig {
338                 PartialConfig {
339                     $(
340                         $i: if self.$i.0.get() {
341                                 Some(self.$i.2.clone())
342                             } else {
343                                 None
344                             },
345                     )+
346                 }
347             }
348
349             pub fn all_options(&self) -> PartialConfig {
350                 PartialConfig {
351                     $(
352                         $i: Some(self.$i.2.clone()),
353                     )+
354                 }
355             }
356
357             pub fn override_value(&mut self, key: &str, val: &str)
358             {
359                 match key {
360                     $(
361                         stringify!($i) => {
362                             self.$i.2 = val.parse::<$ty>()
363                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
364                                                  stringify!($i),
365                                                  val,
366                                                  stringify!($ty)));
367                         }
368                     )+
369                     _ => panic!("Unknown config key in override: {}", key)
370                 }
371             }
372
373             /// Construct a `Config` from the toml file specified at `file_path`.
374             ///
375             /// This method only looks at the provided path, for a method that
376             /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
377             ///
378             /// Return a `Config` if the config could be read and parsed from
379             /// the file, Error otherwise.
380             pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
381                 let mut file = File::open(&file_path)?;
382                 let mut toml = String::new();
383                 file.read_to_string(&mut toml)?;
384                 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
385             }
386
387             /// Resolve the config for input in `dir`.
388             ///
389             /// Searches for `rustfmt.toml` beginning with `dir`, and
390             /// recursively checking parents of `dir` if no config file is found.
391             /// If no config file exists in `dir` or in any parent, a
392             /// default `Config` will be returned (and the returned path will be empty).
393             ///
394             /// Returns the `Config` to use, and the path of the project file if there was
395             /// one.
396             pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
397
398                 /// Try to find a project file in the given directory and its parents.
399                 /// Returns the path of a the nearest project file if one exists,
400                 /// or `None` if no project file was found.
401                 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
402                     let mut current = if dir.is_relative() {
403                         env::current_dir()?.join(dir)
404                     } else {
405                         dir.to_path_buf()
406                     };
407
408                     current = fs::canonicalize(current)?;
409
410                     loop {
411                         match get_toml_path(&current) {
412                             Ok(Some(path)) => return Ok(Some(path)),
413                             Err(e) => return Err(e),
414                             _ => ()
415                         }
416
417                         // If the current directory has no parent, we're done searching.
418                         if !current.pop() {
419                             return Ok(None);
420                         }
421                     }
422                 }
423
424                 match resolve_project_file(dir)? {
425                     None => Ok((Config::default(), None)),
426                     Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
427                 }
428             }
429
430
431             pub fn print_docs() {
432                 use std::cmp;
433                 let max = 0;
434                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
435                 let mut space_str = String::with_capacity(max);
436                 for _ in 0..max {
437                     space_str.push(' ');
438                 }
439                 println!("Configuration Options:");
440                 $(
441                     let name_raw = stringify!($i);
442                     let mut name_out = String::with_capacity(max);
443                     for _ in name_raw.len()..max-1 {
444                         name_out.push(' ')
445                     }
446                     name_out.push_str(name_raw);
447                     name_out.push(' ');
448                     println!("{}{} Default: {:?}",
449                              name_out,
450                              <$ty>::doc_hint(),
451                              $def);
452                     $(
453                         println!("{}{}", space_str, $dstring);
454                     )+
455                     println!("");
456                 )+
457             }
458         }
459
460         // Template for the default configuration
461         impl Default for Config {
462             fn default() -> Config {
463                 Config {
464                     $(
465                         $i: (Cell::new(false), false, $def),
466                     )+
467                 }
468             }
469         }
470     )
471 }
472
473 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
474 ///
475 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
476 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
477     const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
478     for config_file_name in &CONFIG_FILE_NAMES {
479         let config_file = dir.join(config_file_name);
480         match fs::metadata(&config_file) {
481             // Only return if it's a file to handle the unlikely situation of a directory named
482             // `rustfmt.toml`.
483             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
484             // Return the error if it's something other than `NotFound`; otherwise we didn't
485             // find the project file yet, and continue searching.
486             Err(e) => {
487                 if e.kind() != ErrorKind::NotFound {
488                     return Err(e);
489                 }
490             }
491             _ => {}
492         }
493     }
494     Ok(None)
495 }
496
497
498
499 create_config! {
500     verbose: bool, false, "Use verbose output";
501     disable_all_formatting: bool, false, "Don't reformat anything";
502     skip_children: bool, false, "Don't reformat out of line modules";
503     file_lines: FileLines, FileLines::all(),
504         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
505          via the --file-lines option";
506     max_width: usize, 100, "Maximum width of each line";
507     error_on_line_overflow: bool, true, "Error if unable to get all lines within max_width";
508     tab_spaces: usize, 4, "Number of spaces per tab";
509     fn_call_width: usize, 60,
510         "Maximum width of the args of a function call before falling back to vertical formatting";
511     struct_lit_width: usize, 18,
512         "Maximum width in the body of a struct lit before falling back to vertical formatting";
513     struct_variant_width: usize, 35,
514         "Maximum width in the body of a struct variant before falling back to vertical formatting";
515     force_explicit_abi: bool, true, "Always print the abi for extern items";
516     newline_style: NewlineStyle, NewlineStyle::Unix, "Unix or Windows line endings";
517     fn_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for functions";
518     item_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for structs and enums";
519     control_style: Style, Style::Rfc, "Indent style for control flow statements";
520     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine,
521         "Brace style for control flow constructs";
522     impl_empty_single_line: bool, true, "Put empty-body implementations on a single line";
523     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical,
524         "How to handle trailing commas for lists";
525     fn_empty_single_line: bool, true, "Put empty-body functions on a single line";
526     fn_single_line: bool, false, "Put single-expression functions on a single line";
527     fn_return_indent: ReturnIndent, ReturnIndent::WithArgs,
528         "Location of return type in function declaration";
529     fn_args_paren_newline: bool, false, "If function argument parenthesis goes on a newline";
530     fn_args_density: Density, Density::Tall, "Argument density in functions";
531     fn_args_layout: IndentStyle, IndentStyle::Block,
532         "Layout of function arguments and tuple structs";
533     array_layout: IndentStyle, IndentStyle::Block, "Indent on arrays";
534     array_width: usize, 60,
535         "Maximum width of an array literal before falling back to vertical formatting";
536     array_horizontal_layout_threshold: usize, 0,
537         "How many elements array must have before rustfmt uses horizontal layout.";
538     type_punctuation_density: TypeDensity, TypeDensity::Wide,
539         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
540     where_style: Style, Style::Rfc, "Overall strategy for where clauses";
541     // TODO:
542     // 1. Should we at least try to put the where clause on the same line as the rest of the
543     // function decl?
544     // 2. Currently options `Tall` and `Vertical` produce the same output.
545     where_density: Density, Density::CompressedIfEmpty, "Density of a where clause";
546     where_layout: ListTactic, ListTactic::Vertical, "Element layout inside a where clause";
547     where_pred_indent: IndentStyle, IndentStyle::Visual,
548         "Indentation style of a where predicate";
549     generics_indent: IndentStyle, IndentStyle::Block, "Indentation of generics";
550     struct_lit_style: IndentStyle, IndentStyle::Block, "Style of struct definition";
551     struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle,
552         "Multiline style on literal structs";
553     fn_call_style: IndentStyle, IndentStyle::Block, "Indentation for function calls, etc.";
554     report_todo: ReportTactic, ReportTactic::Never,
555         "Report all, none or unnumbered occurrences of TODO in source file comments";
556     report_fixme: ReportTactic, ReportTactic::Never,
557         "Report all, none or unnumbered occurrences of FIXME in source file comments";
558     chain_indent: IndentStyle, IndentStyle::Block, "Indentation of chain";
559     chain_one_line_max: usize, 60, "Maximum length of a chain to fit on a single line";
560     chain_split_single_child: bool, false, "Split a chain with a single child if its length \
561                                             exceeds `chain_one_line_max`";
562     reorder_imports: bool, false, "Reorder import statements alphabetically";
563     reorder_imports_in_group: bool, false, "Reorder import statements in group";
564     reorder_imported_names: bool, false,
565         "Reorder lists of names in import statements alphabetically";
566     single_line_if_else_max_width: usize, 50, "Maximum line length for single line if-else \
567                                                 expressions. A value of zero means always break \
568                                                 if-else expressions.";
569     format_strings: bool, false, "Format string literals where necessary";
570     force_format_strings: bool, false, "Always format string literals";
571     take_source_hints: bool, false, "Retain some formatting characteristics from the source code";
572     hard_tabs: bool, false, "Use tab characters for indentation, spaces for alignment";
573     wrap_comments: bool, false, "Break comments to fit on the line";
574     comment_width: usize, 80, "Maximum length of comments. No effect unless wrap_comments = true";
575     normalize_comments: bool, false, "Convert /* */ comments to // comments where possible";
576     wrap_match_arms: bool, true, "Wrap multiline match arms in blocks";
577     match_block_trailing_comma: bool, false,
578         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
579     indent_match_arms: bool, true, "Indent match arms instead of keeping them at the same \
580                                     indentation level as the match keyword";
581     closure_block_indent_threshold: isize, 7, "How many lines a closure must have before it is \
582                                                block indented. -1 means never use block indent.";
583     space_before_type_annotation: bool, false,
584         "Leave a space before the colon in a type annotation";
585     space_after_type_annotation_colon: bool, true,
586         "Leave a space after the colon in a type annotation";
587     space_before_struct_lit_field_colon: bool, false,
588         "Leave a space before the colon in a struct literal field";
589     space_after_struct_lit_field_colon: bool, true,
590         "Leave a space after the colon in a struct literal field";
591     space_before_bound: bool, false, "Leave a space before the colon in a trait or lifetime bound";
592     space_after_bound_colon: bool, true,
593         "Leave a space after the colon in a trait or lifetime bound";
594     spaces_around_ranges: bool, false, "Put spaces around the  .. and ... range operators";
595     spaces_within_angle_brackets: bool, false, "Put spaces within non-empty generic arguments";
596     spaces_within_square_brackets: bool, false, "Put spaces within non-empty square brackets";
597     spaces_within_parens: bool, false, "Put spaces within non-empty parentheses";
598     use_try_shorthand: bool, false, "Replace uses of the try! macro by the ? shorthand";
599     write_mode: WriteMode, WriteMode::Replace,
600         "What Write Mode to use when none is supplied: Replace, Overwrite, Display, Diff, Coverage";
601     condense_wildcard_suffixes: bool, false, "Replace strings of _ wildcards by a single .. in \
602                                               tuple patterns";
603     combine_control_expr: bool, true, "Combine control expressions with funciton calls.";
604     struct_field_align_threshold: usize, 0, "Align struct fields if their diffs fits within \
605                                              threshold."
606 }
607
608 #[cfg(test)]
609 mod test {
610     use super::Config;
611
612     #[test]
613     fn test_config_set() {
614         let mut config = Config::default();
615         config.set().verbose(false);
616         assert_eq!(config.verbose(), false);
617         config.set().verbose(true);
618         assert_eq!(config.verbose(), true);
619     }
620
621     #[test]
622     fn test_config_used_to_toml() {
623         let config = Config::default();
624
625         let verbose = config.verbose();
626         let skip_children = config.skip_children();
627
628         let used_options = config.used_options();
629         let toml = used_options.to_toml().unwrap();
630         assert_eq!(
631             toml,
632             format!("verbose = {}\nskip_children = {}\n", verbose, skip_children)
633         );
634     }
635
636     #[test]
637     fn test_was_set() {
638         let config = Config::from_toml("hard_tabs = true").unwrap();
639
640         assert_eq!(config.was_set().hard_tabs(), true);
641         assert_eq!(config.was_set().verbose(), false);
642     }
643 }