2 use std::collections::HashMap;
5 use syntax::codemap::Span;
6 use syntax::visit::FnKind;
7 use utils::{constants, span_lint, span_help_and_lint, snippet, snippet_opt, span_lint_and_then};
9 /// **What it does:** Checks for structure field patterns bound to wildcards.
11 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
12 /// the fields that are actually bound.
14 /// **Known problems:** None.
18 /// let { a: _, b: ref b, c: _ } = ..
21 pub UNNEEDED_FIELD_PATTERN,
23 "struct fields bound to a wildcard instead of using `..`"
26 /// **What it does:** Checks for function arguments having the similar names
27 /// differing by an underscore.
29 /// **Why is this bad?** It affects code readability.
31 /// **Known problems:** None.
35 /// fn foo(a: i32, _a: i32) {}
38 pub DUPLICATE_UNDERSCORE_ARGUMENT,
40 "function arguments having names which only differ by an underscore"
43 /// **What it does:** Detects closures called in the same expression where they are defined.
45 /// **Why is this bad?** It is unnecessarily adding to the expression's complexity.
47 /// **Known problems:** None.
54 pub REDUNDANT_CLOSURE_CALL,
56 "throwaway closures called in the expression they are defined"
59 /// **What it does:** Detects expressions of the form `--x`.
61 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
64 /// **Known problems:** None.
73 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
76 /// **What it does:** Warns on hexadecimal literals with mixed-case letter digits.
78 /// **Why is this bad?** It looks confusing.
80 /// **Known problems:** None.
84 /// let y = 0x1a9BAcD;
87 pub MIXED_CASE_HEX_LITERALS,
89 "hex literals whose letter digits are not consistently upper- or lowercased"
92 /// **What it does:** Warns if literal suffixes are not separated by an underscore.
94 /// **Why is this bad?** It is much less readable.
96 /// **Known problems:** None.
100 /// let y = 123832i32;
103 pub UNSEPARATED_LITERAL_SUFFIX,
105 "literals whose suffix is not separated by an underscore"
108 /// **What it does:** Warns if an integral constant literal starts with `0`.
110 /// **Why is this bad?** In some languages (including the infamous C language and most of its
111 /// familly), this marks an octal constant. In Rust however, this is a decimal constant. This could
112 /// be confusing for both the writer and a reader of the constant.
114 /// **Known problems:** None.
122 /// println!("{}", a);
126 /// prints `123`, while in C:
129 /// #include <stdio.h>
133 /// printf("%d\n", a);
137 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
139 pub ZERO_PREFIXED_LITERAL,
141 "integer literals starting with `0`"
144 /// **What it does:** Warns if a generic shadows a built-in type.
146 /// **Why is this bad?** This gives surprising type errors.
148 /// **Known problems:** None.
153 /// impl<u32> Foo<u32> {
154 /// fn impl_func(&self) -> u32 {
160 pub BUILTIN_TYPE_SHADOW,
162 "shadowing a builtin type"
165 #[derive(Copy, Clone)]
166 pub struct MiscEarly;
168 impl LintPass for MiscEarly {
169 fn get_lints(&self) -> LintArray {
170 lint_array!(UNNEEDED_FIELD_PATTERN,
171 DUPLICATE_UNDERSCORE_ARGUMENT,
172 REDUNDANT_CLOSURE_CALL,
174 MIXED_CASE_HEX_LITERALS,
175 UNSEPARATED_LITERAL_SUFFIX,
176 ZERO_PREFIXED_LITERAL,
181 impl EarlyLintPass for MiscEarly {
182 fn check_generics(&mut self, cx: &EarlyContext, gen: &Generics) {
183 for ty in &gen.ty_params {
184 let name = ty.ident.name.as_str();
185 if constants::BUILTIN_TYPES.contains(&&*name) {
189 &format!("This generic shadows the built-in type `{}`", name));
194 fn check_pat(&mut self, cx: &EarlyContext, pat: &Pat) {
195 if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
197 let type_name = npat.segments.last().expect("A path must have at least one segment").identifier.name;
199 for field in pfields {
200 if field.node.pat.node == PatKind::Wild {
204 if !pfields.is_empty() && wilds == pfields.len() {
205 span_help_and_lint(cx,
206 UNNEEDED_FIELD_PATTERN,
208 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
209 &format!("Try with `{} {{ .. }}` instead", type_name));
213 let mut normal = vec![];
215 for field in pfields {
216 if field.node.pat.node != PatKind::Wild {
217 if let Ok(n) = cx.sess().codemap().span_to_snippet(field.span) {
222 for field in pfields {
223 if field.node.pat.node == PatKind::Wild {
227 UNNEEDED_FIELD_PATTERN,
229 "You matched a field with a wildcard pattern. Consider using `..` instead");
231 span_help_and_lint(cx,
232 UNNEEDED_FIELD_PATTERN,
234 "You matched a field with a wildcard pattern. Consider using `..` \
236 &format!("Try with `{} {{ {}, .. }}`",
238 normal[..].join(", ")));
246 fn check_fn(&mut self, cx: &EarlyContext, _: FnKind, decl: &FnDecl, _: Span, _: NodeId) {
247 let mut registered_names: HashMap<String, Span> = HashMap::new();
249 for arg in &decl.inputs {
250 if let PatKind::Ident(_, sp_ident, None) = arg.pat.node {
251 let arg_name = sp_ident.node.to_string();
253 if arg_name.starts_with('_') {
254 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
256 DUPLICATE_UNDERSCORE_ARGUMENT,
258 &format!("`{}` already exists, having another argument having almost the same \
259 name makes code comprehension and documentation more difficult",
260 arg_name[1..].to_owned()));;
263 registered_names.insert(arg_name, arg.pat.span);
269 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
271 ExprKind::Call(ref paren, _) => {
272 if let ExprKind::Paren(ref closure) = paren.node {
273 if let ExprKind::Closure(_, ref decl, ref block, _) = closure.node {
274 span_lint_and_then(cx,
275 REDUNDANT_CLOSURE_CALL,
277 "Try not to call a closure in the expression where it is declared.",
278 |db| if decl.inputs.is_empty() {
279 let hint = snippet(cx, block.span, "..").into_owned();
280 db.span_suggestion(expr.span, "Try doing something like: ", hint);
285 ExprKind::Unary(UnOp::Neg, ref inner) => {
286 if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
290 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op");
293 ExprKind::Lit(ref lit) => {
295 let LitKind::Int(value, ..) = lit.node,
296 let Some(src) = snippet_opt(cx, lit.span),
297 let Some(firstch) = src.chars().next(),
298 char::to_digit(firstch, 10).is_some()
301 for ch in src.chars() {
302 if ch == 'i' || ch == 'u' {
304 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
305 "integer type suffix should be separated by an underscore");
311 if src.starts_with("0x") {
312 let mut seen = (false, false);
313 for ch in src.chars() {
315 'a' ... 'f' => seen.0 = true,
316 'A' ... 'F' => seen.1 = true,
317 'i' | 'u' => break, // start of suffix already
321 if seen.0 && seen.1 {
322 span_lint(cx, MIXED_CASE_HEX_LITERALS, lit.span,
323 "inconsistent casing in hexadecimal literal");
325 } else if src.starts_with("0b") || src.starts_with("0o") {
327 } else if value != 0 && src.starts_with('0') {
328 span_lint_and_then(cx,
329 ZERO_PREFIXED_LITERAL,
331 "this is a decimal constant",
335 "if you mean to use a decimal constant, remove the `0` to remove confusion:",
336 src[1..].to_string(),
340 "if you mean to use an octal constant, use `0o`:",
341 format!("0o{}", &src[1..]),
347 let LitKind::Float(..) = lit.node,
348 let Some(src) = snippet_opt(cx, lit.span),
349 let Some(firstch) = src.chars().next(),
350 char::to_digit(firstch, 10).is_some()
353 for ch in src.chars() {
356 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
357 "float type suffix should be separated by an underscore");
369 fn check_block(&mut self, cx: &EarlyContext, block: &Block) {
370 for w in block.stmts.windows(2) {
372 let StmtKind::Local(ref local) = w[0].node,
373 let Option::Some(ref t) = local.init,
374 let ExprKind::Closure(_, _, _, _) = t.node,
375 let PatKind::Ident(_, sp_ident, _) = local.pat.node,
376 let StmtKind::Semi(ref second) = w[1].node,
377 let ExprKind::Assign(_, ref call) = second.node,
378 let ExprKind::Call(ref closure, _) = call.node,
379 let ExprKind::Path(_, ref path) = closure.node
381 if sp_ident.node == (&path.segments[0]).identifier {
384 REDUNDANT_CLOSURE_CALL,
386 "Closure called just once immediately after it was declared",