1 use std::{fmt, fs, io};
3 use syntax::{ast, codemap, ptr};
4 use syntax::parse::token;
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)> {
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));
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()))
22 Err(("`conf_file` value must be a string", value.span))
32 /// Error from reading a configuration file.
36 TomlError(Vec<toml::ParserError>),
37 TypeError(&'static str, &'static str, &'static str),
41 impl fmt::Display for ConfError {
42 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
44 ConfError::IoError(ref err) => err.fmt(f),
45 ConfError::TomlError(ref errs) => {
58 ConfError::TypeError(ref key, ref expected, ref got) => {
59 write!(f, "`{}` is expected to be a `{}` but is a `{}`", key, expected, got)
61 ConfError::UnknownKey(ref key) => write!(f, "unknown key `{}`", key),
66 impl From<io::Error> for ConfError {
67 fn from(e: io::Error) -> Self {
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.
76 $(#[$doc] pub $rust_name: define_Conf!(TY $($ty)+),)+
79 impl Default for Conf {
80 fn default() -> Conf {
82 $($rust_name: define_Conf!(DEFAULT $($ty)+, $default),)+
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> {
93 define_Conf!(PAT $toml_name) => {
94 if let Some(value) = define_Conf!(CONV $($ty)+, value) {
95 self.$rust_name = value;
98 return Err(ConfError::TypeError(define_Conf!(EXPR $toml_name),
105 // for external tools such as clippy-service
109 return Err(ConfError::UnknownKey(name));
118 // hack to convert tts
119 (PAT $pat: pat) => { $pat };
120 (EXPR $e: expr) => { $e };
121 (TY $ty: ty) => { $ty };
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();
130 if let Some(slice) = slice {
131 if slice.iter().any(|v| v.as_str().is_none()) {
135 Some(slice.iter().map(|v| v.as_str().unwrap_or_else(|| unreachable!()).to_owned()).collect())
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 };
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),
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();
170 let file = match fs::File::open(path) {
172 let mut buf = String::new();
174 if let Err(err) = file.read_to_string(&mut buf) {
175 errors.push(err.into());
176 return (conf, errors);
181 Err(ref err) if !must_exist && err.kind() == io::ErrorKind::NotFound => {
182 return (conf, errors);
185 errors.push(err.into());
186 return (conf, errors);
190 let mut parser = toml::Parser::new(&file);
191 let toml = if let Some(toml) = parser.parse() {
194 errors.push(ConfError::TomlError(parser.errors));
195 return (conf, errors);
198 for (key, value) in toml {
199 if let Err(err) = conf.set(key, value) {