]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/conf.rs
e773cc0e02505f49838614c8df4b2b6ece21176b
[rust.git] / clippy_lints / src / utils / conf.rs
1 use std::{fmt, fs, io};
2 use std::io::Read;
3 use syntax::{ast, codemap, ptr};
4 use syntax::parse::token;
5 use toml;
6
7 /// Get the configuration file from arguments.
8 pub fn conf_file(args: &[ptr::P<ast::MetaItem>]) -> Result<Option<token::InternedString>, (&'static str, codemap::Span)> {
9     for arg in args {
10         match arg.node {
11             ast::MetaItemKind::Word(ref name) |
12             ast::MetaItemKind::List(ref name, _) => {
13                 if name == &"conf_file" {
14                     return Err(("`conf_file` must be a named value", arg.span));
15                 }
16             }
17             ast::MetaItemKind::NameValue(ref name, ref value) => {
18                 if name == &"conf_file" {
19                     return if let ast::LitKind::Str(ref file, _) = value.node {
20                         Ok(Some(file.clone()))
21                     } else {
22                         Err(("`conf_file` value must be a string", value.span))
23                     };
24                 }
25             }
26         }
27     }
28
29     Ok(None)
30 }
31
32 /// Error from reading a configuration file.
33 #[derive(Debug)]
34 pub enum ConfError {
35     IoError(io::Error),
36     TomlError(Vec<toml::ParserError>),
37     TypeError(&'static str, &'static str, &'static str),
38     UnknownKey(String),
39 }
40
41 impl fmt::Display for ConfError {
42     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
43         match *self {
44             ConfError::IoError(ref err) => err.fmt(f),
45             ConfError::TomlError(ref errs) => {
46                 let mut first = true;
47                 for err in errs {
48                     if !first {
49                         try!(", ".fmt(f));
50                         first = false;
51                     }
52
53                     try!(err.fmt(f));
54                 }
55
56                 Ok(())
57             }
58             ConfError::TypeError(ref key, ref expected, ref got) => {
59                 write!(f, "`{}` is expected to be a `{}` but is a `{}`", key, expected, got)
60             }
61             ConfError::UnknownKey(ref key) => write!(f, "unknown key `{}`", key),
62         }
63     }
64 }
65
66 impl From<io::Error> for ConfError {
67     fn from(e: io::Error) -> Self {
68         ConfError::IoError(e)
69     }
70 }
71
72 macro_rules! define_Conf {
73     ($(#[$doc: meta] ($toml_name: tt, $rust_name: ident, $default: expr => $($ty: tt)+),)+) => {
74         /// Type used to store lint configuration.
75         pub struct Conf {
76             $(#[$doc] pub $rust_name: define_Conf!(TY $($ty)+),)+
77         }
78
79         impl Default for Conf {
80             fn default() -> Conf {
81                 Conf {
82                     $($rust_name: define_Conf!(DEFAULT $($ty)+, $default),)+
83                 }
84             }
85         }
86
87         impl Conf {
88             /// Set the property `name` (which must be the `toml` name) to the given value
89             #[allow(cast_sign_loss)]
90             fn set(&mut self, name: String, value: toml::Value) -> Result<(), ConfError> {
91                 match name.as_str() {
92                     $(
93                         define_Conf!(PAT $toml_name) => {
94                             if let Some(value) = define_Conf!(CONV $($ty)+, value) {
95                                 self.$rust_name = value;
96                             }
97                             else {
98                                 return Err(ConfError::TypeError(define_Conf!(EXPR $toml_name),
99                                                                 stringify!($($ty)+),
100                                                                 value.type_str()));
101                             }
102                         },
103                     )+
104                     "third-party" => {
105                         // for external tools such as clippy-service
106                         return Ok(());
107                     }
108                     _ => {
109                         return Err(ConfError::UnknownKey(name));
110                     }
111                 }
112
113                 Ok(())
114             }
115         }
116     };
117
118     // hack to convert tts
119     (PAT $pat: pat) => { $pat };
120     (EXPR $e: expr) => { $e };
121     (TY $ty: ty) => { $ty };
122
123     // how to read the value?
124     (CONV i64, $value: expr) => { $value.as_integer() };
125     (CONV u64, $value: expr) => { $value.as_integer().iter().filter_map(|&i| if i >= 0 { Some(i as u64) } else { None }).next() };
126     (CONV String, $value: expr) => { $value.as_str().map(Into::into) };
127     (CONV Vec<String>, $value: expr) => {{
128         let slice = $value.as_slice();
129
130         if let Some(slice) = slice {
131             if slice.iter().any(|v| v.as_str().is_none()) {
132                 None
133             }
134             else {
135                 Some(slice.iter().map(|v| v.as_str().unwrap_or_else(|| unreachable!()).to_owned()).collect())
136             }
137         }
138         else {
139             None
140         }
141     }};
142
143     // provide a nicer syntax to declare the default value of `Vec<String>` variables
144     (DEFAULT Vec<String>, $e: expr) => { $e.iter().map(|&e| e.to_owned()).collect() };
145     (DEFAULT $ty: ty, $e: expr) => { $e };
146 }
147
148 define_Conf! {
149     /// Lint: BLACKLISTED_NAME. The list of blacklisted names to lint about
150     ("blacklisted-names", blacklisted_names, ["foo", "bar", "baz"] => Vec<String>),
151     /// Lint: CYCLOMATIC_COMPLEXITY. The maximum cyclomatic complexity a function can have
152     ("cyclomatic-complexity-threshold", cyclomatic_complexity_threshold, 25 => u64),
153     /// Lint: DOC_MARKDOWN. The list of words this lint should not consider as identifiers needing ticks
154     ("doc-valid-idents", doc_valid_idents, ["MiB", "GiB", "TiB", "PiB", "EiB", "GitHub"] => Vec<String>),
155     /// Lint: TOO_MANY_ARGUMENTS. The maximum number of argument a function or method can have
156     ("too-many-arguments-threshold", too_many_arguments_threshold, 7 => u64),
157     /// Lint: TYPE_COMPLEXITY. The maximum complexity a type can have
158     ("type-complexity-threshold", type_complexity_threshold, 250 => u64),
159     /// Lint: MANY_SINGLE_CHAR_NAMES. The maximum number of single char bindings a scope may have
160     ("single-char-binding-names-threshold", max_single_char_names, 5 => u64),
161 }
162
163 /// Read the `toml` configuration file. The function will ignore “File not found” errors iif
164 /// `!must_exist`, in which case, it will return the default configuration.
165 /// In case of error, the function tries to continue as much as possible.
166 pub fn read_conf(path: &str, must_exist: bool) -> (Conf, Vec<ConfError>) {
167     let mut conf = Conf::default();
168     let mut errors = Vec::new();
169
170     let file = match fs::File::open(path) {
171         Ok(mut file) => {
172             let mut buf = String::new();
173
174             if let Err(err) = file.read_to_string(&mut buf) {
175                 errors.push(err.into());
176                 return (conf, errors);
177             }
178
179             buf
180         }
181         Err(ref err) if !must_exist && err.kind() == io::ErrorKind::NotFound => {
182             return (conf, errors);
183         }
184         Err(err) => {
185             errors.push(err.into());
186             return (conf, errors);
187         }
188     };
189
190     let mut parser = toml::Parser::new(&file);
191     let toml = if let Some(toml) = parser.parse() {
192         toml
193     } else {
194         errors.push(ConfError::TomlError(parser.errors));
195         return (conf, errors);
196     };
197
198     for (key, value) in toml {
199         if let Err(err) = conf.set(key, value) {
200             errors.push(err);
201         }
202     }
203
204     (conf, errors)
205 }