1 use crate::utils::{constants, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_then};
2 use if_chain::if_chain;
3 use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_errors::Applicability;
9 use syntax::source_map::Span;
10 use syntax::visit::{walk_expr, FnKind, Visitor};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for structure field patterns bound to wildcards.
15 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
16 /// the fields that are actually bound.
18 /// **Known problems:** None.
22 /// let { a: _, b: ref b, c: _ } = ..
24 pub UNNEEDED_FIELD_PATTERN,
26 "struct fields bound to a wildcard instead of using `..`"
29 declare_clippy_lint! {
30 /// **What it does:** Checks for function arguments having the similar names
31 /// differing by an underscore.
33 /// **Why is this bad?** It affects code readability.
35 /// **Known problems:** None.
39 /// fn foo(a: i32, _a: i32) {}
41 pub DUPLICATE_UNDERSCORE_ARGUMENT,
43 "function arguments having names which only differ by an underscore"
46 declare_clippy_lint! {
47 /// **What it does:** Detects closures called in the same expression where they
50 /// **Why is this bad?** It is unnecessarily adding to the expression's
53 /// **Known problems:** None.
59 pub REDUNDANT_CLOSURE_CALL,
61 "throwaway closures called in the expression they are defined"
64 declare_clippy_lint! {
65 /// **What it does:** Detects expressions of the form `--x`.
67 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
70 /// **Known problems:** None.
79 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
82 declare_clippy_lint! {
83 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
86 /// **Why is this bad?** It looks confusing.
88 /// **Known problems:** None.
92 /// let y = 0x1a9BAcD;
94 pub MIXED_CASE_HEX_LITERALS,
96 "hex literals whose letter digits are not consistently upper- or lowercased"
99 declare_clippy_lint! {
100 /// **What it does:** Warns if literal suffixes are not separated by an
103 /// **Why is this bad?** It is much less readable.
105 /// **Known problems:** None.
109 /// let y = 123832i32;
111 pub UNSEPARATED_LITERAL_SUFFIX,
113 "literals whose suffix is not separated by an underscore"
116 declare_clippy_lint! {
117 /// **What it does:** Warns if an integral constant literal starts with `0`.
119 /// **Why is this bad?** In some languages (including the infamous C language
121 /// family), this marks an octal constant. In Rust however, this is a decimal
122 /// constant. This could
123 /// be confusing for both the writer and a reader of the constant.
125 /// **Known problems:** None.
133 /// println!("{}", a);
137 /// prints `123`, while in C:
140 /// #include <stdio.h>
144 /// printf("%d\n", a);
148 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
149 pub ZERO_PREFIXED_LITERAL,
151 "integer literals starting with `0`"
154 declare_clippy_lint! {
155 /// **What it does:** Warns if a generic shadows a built-in type.
157 /// **Why is this bad?** This gives surprising type errors.
159 /// **Known problems:** None.
164 /// impl<u32> Foo<u32> {
165 /// fn impl_func(&self) -> u32 {
170 pub BUILTIN_TYPE_SHADOW,
172 "shadowing a builtin type"
175 #[derive(Copy, Clone)]
176 pub struct MiscEarly;
178 impl LintPass for MiscEarly {
179 fn get_lints(&self) -> LintArray {
181 UNNEEDED_FIELD_PATTERN,
182 DUPLICATE_UNDERSCORE_ARGUMENT,
183 REDUNDANT_CLOSURE_CALL,
185 MIXED_CASE_HEX_LITERALS,
186 UNSEPARATED_LITERAL_SUFFIX,
187 ZERO_PREFIXED_LITERAL,
192 fn name(&self) -> &'static str {
197 // Used to find `return` statements or equivalents e.g. `?`
198 struct ReturnVisitor {
204 Self { found_return: false }
208 impl<'ast> Visitor<'ast> for ReturnVisitor {
209 fn visit_expr(&mut self, ex: &'ast Expr) {
210 if let ExprKind::Ret(_) = ex.node {
211 self.found_return = true;
212 } else if let ExprKind::Try(_) = ex.node {
213 self.found_return = true;
220 impl EarlyLintPass for MiscEarly {
221 fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
222 for param in &gen.params {
223 if let GenericParamKind::Type { .. } = param.kind {
224 let name = param.ident.as_str();
225 if constants::BUILTIN_TYPES.contains(&&*name) {
230 &format!("This generic shadows the built-in type `{}`", name),
237 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat, _: &mut bool) {
238 if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
243 .expect("A path must have at least one segment")
247 for field in pfields {
248 if let PatKind::Wild = field.node.pat.node {
252 if !pfields.is_empty() && wilds == pfields.len() {
255 UNNEEDED_FIELD_PATTERN,
257 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
258 &format!("Try with `{} {{ .. }}` instead", type_name),
263 let mut normal = vec![];
265 for field in pfields {
266 match field.node.pat.node {
269 if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
275 for field in pfields {
276 if let PatKind::Wild = field.node.pat.node {
281 UNNEEDED_FIELD_PATTERN,
283 "You matched a field with a wildcard pattern. Consider using `..` instead",
288 UNNEEDED_FIELD_PATTERN,
290 "You matched a field with a wildcard pattern. Consider using `..` \
292 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
301 fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, decl: &FnDecl, _: Span, _: NodeId) {
302 let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
304 for arg in &decl.inputs {
305 if let PatKind::Ident(_, ident, None) = arg.pat.node {
306 let arg_name = ident.to_string();
308 if arg_name.starts_with('_') {
309 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
312 DUPLICATE_UNDERSCORE_ARGUMENT,
315 "`{}` already exists, having another argument having almost the same \
316 name makes code comprehension and documentation more difficult",
317 arg_name[1..].to_owned()
322 registered_names.insert(arg_name, arg.pat.span);
328 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
329 if in_external_macro(cx.sess(), expr.span) {
333 ExprKind::Call(ref paren, _) => {
334 if let ExprKind::Paren(ref closure) = paren.node {
335 if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.node {
336 let mut visitor = ReturnVisitor::new();
337 visitor.visit_expr(block);
338 if !visitor.found_return {
341 REDUNDANT_CLOSURE_CALL,
343 "Try not to call a closure in the expression where it is declared.",
345 if decl.inputs.is_empty() {
346 let hint = snippet(cx, block.span, "..").into_owned();
349 "Try doing something like: ",
351 Applicability::MachineApplicable, // snippet
360 ExprKind::Unary(UnOp::Neg, ref inner) => {
361 if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
366 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
370 ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
375 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
376 for w in block.stmts.windows(2) {
378 if let StmtKind::Local(ref local) = w[0].node;
379 if let Option::Some(ref t) = local.init;
380 if let ExprKind::Closure(..) = t.node;
381 if let PatKind::Ident(_, ident, _) = local.pat.node;
382 if let StmtKind::Semi(ref second) = w[1].node;
383 if let ExprKind::Assign(_, ref call) = second.node;
384 if let ExprKind::Call(ref closure, _) = call.node;
385 if let ExprKind::Path(_, ref path) = closure.node;
387 if ident == path.segments[0].ident {
390 REDUNDANT_CLOSURE_CALL,
392 "Closure called just once immediately after it was declared",
402 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
404 if let LitKind::Int(value, ..) = lit.node;
405 if let Some(src) = snippet_opt(cx, lit.span);
406 if let Some(firstch) = src.chars().next();
407 if char::to_digit(firstch, 10).is_some();
410 for ch in src.chars() {
411 if ch == 'i' || ch == 'u' {
413 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
414 "integer type suffix should be separated by an underscore");
420 if src.starts_with("0x") {
421 let mut seen = (false, false);
422 for ch in src.chars() {
424 'a' ..= 'f' => seen.0 = true,
425 'A' ..= 'F' => seen.1 = true,
426 'i' | 'u' => break, // start of suffix already
430 if seen.0 && seen.1 {
431 span_lint(cx, MIXED_CASE_HEX_LITERALS, lit.span,
432 "inconsistent casing in hexadecimal literal");
434 } else if src.starts_with("0b") || src.starts_with("0o") {
436 } else if value != 0 && src.starts_with('0') {
437 span_lint_and_then(cx,
438 ZERO_PREFIXED_LITERAL,
440 "this is a decimal constant",
444 "if you mean to use a decimal constant, remove the `0` to remove confusion",
445 src.trim_start_matches(|c| c == '_' || c == '0').to_string(),
446 Applicability::MaybeIncorrect,
450 "if you mean to use an octal constant, use `0o`",
451 format!("0o{}", src.trim_start_matches(|c| c == '_' || c == '0')),
452 Applicability::MaybeIncorrect,
459 if let LitKind::Float(..) = lit.node;
460 if let Some(src) = snippet_opt(cx, lit.span);
461 if let Some(firstch) = src.chars().next();
462 if char::to_digit(firstch, 10).is_some();
465 for ch in src.chars() {
468 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
469 "float type suffix should be separated by an underscore");