2 constants, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then,
4 use if_chain::if_chain;
5 use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_errors::Applicability;
11 use syntax::source_map::Span;
12 use syntax::visit::{walk_expr, FnKind, Visitor};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for structure field patterns bound to wildcards.
17 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
18 /// the fields that are actually bound.
20 /// **Known problems:** None.
24 /// let { a: _, b: ref b, c: _ } = ..
26 pub UNNEEDED_FIELD_PATTERN,
28 "struct fields bound to a wildcard instead of using `..`"
31 declare_clippy_lint! {
32 /// **What it does:** Checks for function arguments having the similar names
33 /// differing by an underscore.
35 /// **Why is this bad?** It affects code readability.
37 /// **Known problems:** None.
41 /// fn foo(a: i32, _a: i32) {}
43 pub DUPLICATE_UNDERSCORE_ARGUMENT,
45 "function arguments having names which only differ by an underscore"
48 declare_clippy_lint! {
49 /// **What it does:** Detects closures called in the same expression where they
52 /// **Why is this bad?** It is unnecessarily adding to the expression's
55 /// **Known problems:** None.
61 pub REDUNDANT_CLOSURE_CALL,
63 "throwaway closures called in the expression they are defined"
66 declare_clippy_lint! {
67 /// **What it does:** Detects expressions of the form `--x`.
69 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
72 /// **Known problems:** None.
81 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
84 declare_clippy_lint! {
85 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
88 /// **Why is this bad?** It looks confusing.
90 /// **Known problems:** None.
94 /// let y = 0x1a9BAcD;
96 pub MIXED_CASE_HEX_LITERALS,
98 "hex literals whose letter digits are not consistently upper- or lowercased"
101 declare_clippy_lint! {
102 /// **What it does:** Warns if literal suffixes are not separated by an
105 /// **Why is this bad?** It is much less readable.
107 /// **Known problems:** None.
111 /// let y = 123832i32;
113 pub UNSEPARATED_LITERAL_SUFFIX,
115 "literals whose suffix is not separated by an underscore"
118 declare_clippy_lint! {
119 /// **What it does:** Warns if an integral constant literal starts with `0`.
121 /// **Why is this bad?** In some languages (including the infamous C language
123 /// family), this marks an octal constant. In Rust however, this is a decimal
124 /// constant. This could
125 /// be confusing for both the writer and a reader of the constant.
127 /// **Known problems:** None.
135 /// println!("{}", a);
139 /// prints `123`, while in C:
142 /// #include <stdio.h>
146 /// printf("%d\n", a);
150 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
151 pub ZERO_PREFIXED_LITERAL,
153 "integer literals starting with `0`"
156 declare_clippy_lint! {
157 /// **What it does:** Warns if a generic shadows a built-in type.
159 /// **Why is this bad?** This gives surprising type errors.
161 /// **Known problems:** None.
166 /// impl<u32> Foo<u32> {
167 /// fn impl_func(&self) -> u32 {
172 pub BUILTIN_TYPE_SHADOW,
174 "shadowing a builtin type"
177 declare_lint_pass!(MiscEarlyLints => [
178 UNNEEDED_FIELD_PATTERN,
179 DUPLICATE_UNDERSCORE_ARGUMENT,
180 REDUNDANT_CLOSURE_CALL,
182 MIXED_CASE_HEX_LITERALS,
183 UNSEPARATED_LITERAL_SUFFIX,
184 ZERO_PREFIXED_LITERAL,
188 // Used to find `return` statements or equivalents e.g., `?`
189 struct ReturnVisitor {
195 Self { found_return: false }
199 impl<'ast> Visitor<'ast> for ReturnVisitor {
200 fn visit_expr(&mut self, ex: &'ast Expr) {
201 if let ExprKind::Ret(_) = ex.node {
202 self.found_return = true;
203 } else if let ExprKind::Try(_) = ex.node {
204 self.found_return = true;
211 impl EarlyLintPass for MiscEarlyLints {
212 fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
213 for param in &gen.params {
214 if let GenericParamKind::Type { .. } = param.kind {
215 let name = param.ident.as_str();
216 if constants::BUILTIN_TYPES.contains(&&*name) {
221 &format!("This generic shadows the built-in type `{}`", name),
228 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) {
229 if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
234 .expect("A path must have at least one segment")
238 for field in pfields {
239 if let PatKind::Wild = field.pat.node {
243 if !pfields.is_empty() && wilds == pfields.len() {
246 UNNEEDED_FIELD_PATTERN,
248 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
249 &format!("Try with `{} {{ .. }}` instead", type_name),
254 let mut normal = vec![];
256 for field in pfields {
257 match field.pat.node {
260 if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
266 for field in pfields {
267 if let PatKind::Wild = field.pat.node {
272 UNNEEDED_FIELD_PATTERN,
274 "You matched a field with a wildcard pattern. Consider using `..` instead",
279 UNNEEDED_FIELD_PATTERN,
281 "You matched a field with a wildcard pattern. Consider using `..` \
283 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
292 fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, decl: &FnDecl, _: Span, _: NodeId) {
293 let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
295 for arg in &decl.inputs {
296 if let PatKind::Ident(_, ident, None) = arg.pat.node {
297 let arg_name = ident.to_string();
299 if arg_name.starts_with('_') {
300 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
303 DUPLICATE_UNDERSCORE_ARGUMENT,
306 "`{}` already exists, having another argument having almost the same \
307 name makes code comprehension and documentation more difficult",
308 arg_name[1..].to_owned()
313 registered_names.insert(arg_name, arg.pat.span);
319 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
320 if in_external_macro(cx.sess(), expr.span) {
324 ExprKind::Call(ref paren, _) => {
325 if let ExprKind::Paren(ref closure) = paren.node {
326 if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.node {
327 let mut visitor = ReturnVisitor::new();
328 visitor.visit_expr(block);
329 if !visitor.found_return {
332 REDUNDANT_CLOSURE_CALL,
334 "Try not to call a closure in the expression where it is declared.",
336 if decl.inputs.is_empty() {
337 let hint = snippet(cx, block.span, "..").into_owned();
340 "Try doing something like: ",
342 Applicability::MachineApplicable, // snippet
351 ExprKind::Unary(UnOp::Neg, ref inner) => {
352 if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
357 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
361 ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
366 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
367 for w in block.stmts.windows(2) {
369 if let StmtKind::Local(ref local) = w[0].node;
370 if let Option::Some(ref t) = local.init;
371 if let ExprKind::Closure(..) = t.node;
372 if let PatKind::Ident(_, ident, _) = local.pat.node;
373 if let StmtKind::Semi(ref second) = w[1].node;
374 if let ExprKind::Assign(_, ref call) = second.node;
375 if let ExprKind::Call(ref closure, _) = call.node;
376 if let ExprKind::Path(_, ref path) = closure.node;
378 if ident == path.segments[0].ident {
381 REDUNDANT_CLOSURE_CALL,
383 "Closure called just once immediately after it was declared",
392 impl MiscEarlyLints {
393 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
395 if let LitKind::Int(value, ..) = lit.node;
396 if let Some(src) = snippet_opt(cx, lit.span);
397 if let Some(firstch) = src.chars().next();
398 if char::to_digit(firstch, 10).is_some();
401 for (idx, ch) in src.chars().enumerate() {
402 if ch == 'i' || ch == 'u' {
406 UNSEPARATED_LITERAL_SUFFIX,
408 "integer type suffix should be separated by an underscore",
410 format!("{}_{}", &src[0..idx], &src[idx..]),
411 Applicability::MachineApplicable,
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",
442 "if you mean to use a decimal constant, remove the `0` to remove confusion",
443 src.trim_start_matches(|c| c == '_' || c == '0').to_string(),
444 Applicability::MaybeIncorrect,
448 "if you mean to use an octal constant, use `0o`",
449 format!("0o{}", src.trim_start_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 (idx, ch) in src.chars().enumerate() {
468 UNSEPARATED_LITERAL_SUFFIX,
470 "float type suffix should be separated by an underscore",
472 format!("{}_{}", &src[0..idx], &src[idx..]),
473 Applicability::MachineApplicable,