1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, LintContext, in_external_macro};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc_data_structures::fx::FxHashMap;
14 use if_chain::if_chain;
16 use crate::syntax::ast::*;
17 use crate::syntax::source_map::Span;
18 use crate::syntax::visit::{FnKind, Visitor, walk_expr};
19 use crate::utils::{constants, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_then};
20 use crate::rustc_errors::Applicability;
22 /// **What it does:** Checks for structure field patterns bound to wildcards.
24 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
25 /// the fields that are actually bound.
27 /// **Known problems:** None.
31 /// let { a: _, b: ref b, c: _ } = ..
33 declare_clippy_lint! {
34 pub UNNEEDED_FIELD_PATTERN,
36 "struct fields bound to a wildcard instead of using `..`"
39 /// **What it does:** Checks for function arguments having the similar names
40 /// differing by an underscore.
42 /// **Why is this bad?** It affects code readability.
44 /// **Known problems:** None.
48 /// fn foo(a: i32, _a: i32) {}
50 declare_clippy_lint! {
51 pub DUPLICATE_UNDERSCORE_ARGUMENT,
53 "function arguments having names which only differ by an underscore"
56 /// **What it does:** Detects closures called in the same expression where they
59 /// **Why is this bad?** It is unnecessarily adding to the expression's
62 /// **Known problems:** None.
68 declare_clippy_lint! {
69 pub REDUNDANT_CLOSURE_CALL,
71 "throwaway closures called in the expression they are defined"
74 /// **What it does:** Detects expressions of the form `--x`.
76 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
79 /// **Known problems:** None.
85 declare_clippy_lint! {
88 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
91 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
94 /// **Why is this bad?** It looks confusing.
96 /// **Known problems:** None.
100 /// let y = 0x1a9BAcD;
102 declare_clippy_lint! {
103 pub MIXED_CASE_HEX_LITERALS,
105 "hex literals whose letter digits are not consistently upper- or lowercased"
108 /// **What it does:** Warns if literal suffixes are not separated by an
111 /// **Why is this bad?** It is much less readable.
113 /// **Known problems:** None.
117 /// let y = 123832i32;
119 declare_clippy_lint! {
120 pub UNSEPARATED_LITERAL_SUFFIX,
122 "literals whose suffix is not separated by an underscore"
125 /// **What it does:** Warns if an integral constant literal starts with `0`.
127 /// **Why is this bad?** In some languages (including the infamous C language
129 /// family), this marks an octal constant. In Rust however, this is a decimal
130 /// constant. This could
131 /// be confusing for both the writer and a reader of the constant.
133 /// **Known problems:** None.
141 /// println!("{}", a);
145 /// prints `123`, while in C:
148 /// #include <stdio.h>
152 /// printf("%d\n", a);
156 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
157 declare_clippy_lint! {
158 pub ZERO_PREFIXED_LITERAL,
160 "integer literals starting with `0`"
163 /// **What it does:** Warns if a generic shadows a built-in type.
165 /// **Why is this bad?** This gives surprising type errors.
167 /// **Known problems:** None.
172 /// impl<u32> Foo<u32> {
173 /// fn impl_func(&self) -> u32 {
178 declare_clippy_lint! {
179 pub BUILTIN_TYPE_SHADOW,
181 "shadowing a builtin type"
184 #[derive(Copy, Clone)]
185 pub struct MiscEarly;
187 impl LintPass for MiscEarly {
188 fn get_lints(&self) -> LintArray {
190 UNNEEDED_FIELD_PATTERN,
191 DUPLICATE_UNDERSCORE_ARGUMENT,
192 REDUNDANT_CLOSURE_CALL,
194 MIXED_CASE_HEX_LITERALS,
195 UNSEPARATED_LITERAL_SUFFIX,
196 ZERO_PREFIXED_LITERAL,
202 // Used to find `return` statements or equivalents e.g. `?`
203 struct ReturnVisitor {
215 impl<'ast> Visitor<'ast> for ReturnVisitor {
216 fn visit_expr(&mut self, ex: &'ast Expr) {
217 if let ExprKind::Ret(_) = ex.node {
218 self.found_return = true;
219 } else if let ExprKind::Try(_) = ex.node {
220 self.found_return = true;
227 impl EarlyLintPass for MiscEarly {
228 fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
229 for param in &gen.params {
230 if let GenericParamKind::Type { .. } = param.kind {
231 let name = param.ident.as_str();
232 if constants::BUILTIN_TYPES.contains(&&*name) {
237 &format!("This generic shadows the built-in type `{}`", name),
244 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) {
245 if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
247 let type_name = npat.segments
249 .expect("A path must have at least one segment")
253 for field in pfields {
254 if let PatKind::Wild = field.node.pat.node {
258 if !pfields.is_empty() && wilds == pfields.len() {
261 UNNEEDED_FIELD_PATTERN,
263 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
264 &format!("Try with `{} {{ .. }}` instead", type_name),
269 let mut normal = vec![];
271 for field in pfields {
272 match field.node.pat.node {
274 _ => if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
279 for field in pfields {
280 if let PatKind::Wild = field.node.pat.node {
285 UNNEEDED_FIELD_PATTERN,
287 "You matched a field with a wildcard pattern. Consider using `..` instead",
292 UNNEEDED_FIELD_PATTERN,
294 "You matched a field with a wildcard pattern. Consider using `..` \
296 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
305 fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, decl: &FnDecl, _: Span, _: NodeId) {
306 let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
308 for arg in &decl.inputs {
309 if let PatKind::Ident(_, ident, None) = arg.pat.node {
310 let arg_name = ident.to_string();
312 if arg_name.starts_with('_') {
313 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
316 DUPLICATE_UNDERSCORE_ARGUMENT,
319 "`{}` already exists, having another argument having almost the same \
320 name makes code comprehension and documentation more difficult",
321 arg_name[1..].to_owned()
326 registered_names.insert(arg_name, arg.pat.span);
332 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
333 if in_external_macro(cx.sess(), expr.span) {
337 ExprKind::Call(ref paren, _) => if let ExprKind::Paren(ref closure) = paren.node {
338 if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.node {
339 let mut visitor = ReturnVisitor::new();
340 visitor.visit_expr(block);
341 if !visitor.found_return {
344 REDUNDANT_CLOSURE_CALL,
346 "Try not to call a closure in the expression where it is declared.",
347 |db| if decl.inputs.is_empty() {
348 let hint = snippet(cx, block.span, "..").into_owned();
349 db.span_suggestion_with_applicability(
351 "Try doing something like: ",
353 Applicability::MachineApplicable, // snippet
360 ExprKind::Unary(UnOp::Neg, ref inner) => if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
365 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
368 ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
373 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
374 for w in block.stmts.windows(2) {
376 if let StmtKind::Local(ref local) = w[0].node;
377 if let Option::Some(ref t) = local.init;
378 if let ExprKind::Closure(..) = t.node;
379 if let PatKind::Ident(_, ident, _) = local.pat.node;
380 if let StmtKind::Semi(ref second) = w[1].node;
381 if let ExprKind::Assign(_, ref call) = second.node;
382 if let ExprKind::Call(ref closure, _) = call.node;
383 if let ExprKind::Path(_, ref path) = closure.node;
385 if ident == path.segments[0].ident {
388 REDUNDANT_CLOSURE_CALL,
390 "Closure called just once immediately after it was declared",
400 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
402 if let LitKind::Int(value, ..) = lit.node;
403 if let Some(src) = snippet_opt(cx, lit.span);
404 if let Some(firstch) = src.chars().next();
405 if char::to_digit(firstch, 10).is_some();
408 for ch in src.chars() {
409 if ch == 'i' || ch == 'u' {
411 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
412 "integer type suffix should be separated by an underscore");
418 if src.starts_with("0x") {
419 let mut seen = (false, false);
420 for ch in src.chars() {
422 'a' ..= 'f' => seen.0 = true,
423 'A' ..= 'F' => seen.1 = true,
424 'i' | 'u' => break, // start of suffix already
428 if seen.0 && seen.1 {
429 span_lint(cx, MIXED_CASE_HEX_LITERALS, lit.span,
430 "inconsistent casing in hexadecimal literal");
432 } else if src.starts_with("0b") || src.starts_with("0o") {
434 } else if value != 0 && src.starts_with('0') {
435 span_lint_and_then(cx,
436 ZERO_PREFIXED_LITERAL,
438 "this is a decimal constant",
440 db.span_suggestion_with_applicability(
442 "if you mean to use a decimal constant, remove the `0` to remove confusion",
443 src.trim_left_matches(|c| c == '_' || c == '0').to_string(),
444 Applicability::MaybeIncorrect,
446 db.span_suggestion_with_applicability(
448 "if you mean to use an octal constant, use `0o`",
449 format!("0o{}", src.trim_left_matches(|c| c == '_' || c == '0')),
450 Applicability::MaybeIncorrect,
457 if let LitKind::Float(..) = lit.node;
458 if let Some(src) = snippet_opt(cx, lit.span);
459 if let Some(firstch) = src.chars().next();
460 if char::to_digit(firstch, 10).is_some();
463 for ch in src.chars() {
466 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
467 "float type suffix should be separated by an underscore");