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