2 use std::collections::HashMap;
5 use syntax::codemap::Span;
6 use syntax::visit::FnKind;
7 use utils::{constants, in_external_macro, snippet, snippet_opt, span_help_and_lint, span_lint, 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
46 /// **Why is this bad?** It is unnecessarily adding to the expression's
49 /// **Known problems:** None.
56 pub REDUNDANT_CLOSURE_CALL,
58 "throwaway closures called in the expression they are defined"
61 /// **What it does:** Detects expressions of the form `--x`.
63 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
66 /// **Known problems:** None.
75 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
78 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
81 /// **Why is this bad?** It looks confusing.
83 /// **Known problems:** None.
87 /// let y = 0x1a9BAcD;
90 pub MIXED_CASE_HEX_LITERALS,
92 "hex literals whose letter digits are not consistently upper- or lowercased"
95 /// **What it does:** Warns if literal suffixes are not separated by an
98 /// **Why is this bad?** It is much less readable.
100 /// **Known problems:** None.
104 /// let y = 123832i32;
107 pub UNSEPARATED_LITERAL_SUFFIX,
109 "literals whose suffix is not separated by an underscore"
112 /// **What it does:** Warns if an integral constant literal starts with `0`.
114 /// **Why is this bad?** In some languages (including the infamous C language
116 /// family), this marks an octal constant. In Rust however, this is a decimal
117 /// constant. This could
118 /// be confusing for both the writer and a reader of the constant.
120 /// **Known problems:** None.
128 /// println!("{}", a);
132 /// prints `123`, while in C:
135 /// #include <stdio.h>
139 /// printf("%d\n", a);
143 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
145 pub ZERO_PREFIXED_LITERAL,
147 "integer literals starting with `0`"
150 /// **What it does:** Warns if a generic shadows a built-in type.
152 /// **Why is this bad?** This gives surprising type errors.
154 /// **Known problems:** None.
159 /// impl<u32> Foo<u32> {
160 /// fn impl_func(&self) -> u32 {
166 pub BUILTIN_TYPE_SHADOW,
168 "shadowing a builtin type"
171 #[derive(Copy, Clone)]
172 pub struct MiscEarly;
174 impl LintPass for MiscEarly {
175 fn get_lints(&self) -> LintArray {
177 UNNEEDED_FIELD_PATTERN,
178 DUPLICATE_UNDERSCORE_ARGUMENT,
179 REDUNDANT_CLOSURE_CALL,
181 MIXED_CASE_HEX_LITERALS,
182 UNSEPARATED_LITERAL_SUFFIX,
183 ZERO_PREFIXED_LITERAL,
189 impl EarlyLintPass for MiscEarly {
190 fn check_generics(&mut self, cx: &EarlyContext, gen: &Generics) {
191 for ty in &gen.ty_params {
192 let name = ty.ident.name.as_str();
193 if constants::BUILTIN_TYPES.contains(&&*name) {
198 &format!("This generic shadows the built-in type `{}`", name),
204 fn check_pat(&mut self, cx: &EarlyContext, pat: &Pat) {
205 if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
207 let type_name = npat.segments
209 .expect("A path must have at least one segment")
213 for field in pfields {
214 if field.node.pat.node == PatKind::Wild {
218 if !pfields.is_empty() && wilds == pfields.len() {
221 UNNEEDED_FIELD_PATTERN,
223 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
224 &format!("Try with `{} {{ .. }}` instead", type_name),
229 let mut normal = vec![];
231 for field in pfields {
232 if field.node.pat.node != PatKind::Wild {
233 if let Ok(n) = cx.sess().codemap().span_to_snippet(field.span) {
238 for field in pfields {
239 if field.node.pat.node == PatKind::Wild {
244 UNNEEDED_FIELD_PATTERN,
246 "You matched a field with a wildcard pattern. Consider using `..` instead",
251 UNNEEDED_FIELD_PATTERN,
253 "You matched a field with a wildcard pattern. Consider using `..` \
255 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
264 fn check_fn(&mut self, cx: &EarlyContext, _: FnKind, decl: &FnDecl, _: Span, _: NodeId) {
265 let mut registered_names: HashMap<String, Span> = HashMap::new();
267 for arg in &decl.inputs {
268 if let PatKind::Ident(_, sp_ident, None) = arg.pat.node {
269 let arg_name = sp_ident.node.to_string();
271 if arg_name.starts_with('_') {
272 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
275 DUPLICATE_UNDERSCORE_ARGUMENT,
278 "`{}` already exists, having another argument having almost the same \
279 name makes code comprehension and documentation more difficult",
280 arg_name[1..].to_owned()
285 registered_names.insert(arg_name, arg.pat.span);
291 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
292 if in_external_macro(cx, expr.span) {
296 ExprKind::Call(ref paren, _) => if let ExprKind::Paren(ref closure) = paren.node {
297 if let ExprKind::Closure(_, ref decl, ref block, _) = closure.node {
300 REDUNDANT_CLOSURE_CALL,
302 "Try not to call a closure in the expression where it is declared.",
303 |db| if decl.inputs.is_empty() {
304 let hint = snippet(cx, block.span, "..").into_owned();
305 db.span_suggestion(expr.span, "Try doing something like: ", hint);
310 ExprKind::Unary(UnOp::Neg, ref inner) => if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
315 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
318 ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
323 fn check_block(&mut self, cx: &EarlyContext, block: &Block) {
324 for w in block.stmts.windows(2) {
326 if let StmtKind::Local(ref local) = w[0].node;
327 if let Option::Some(ref t) = local.init;
328 if let ExprKind::Closure(_, _, _, _) = t.node;
329 if let PatKind::Ident(_, sp_ident, _) = local.pat.node;
330 if let StmtKind::Semi(ref second) = w[1].node;
331 if let ExprKind::Assign(_, ref call) = second.node;
332 if let ExprKind::Call(ref closure, _) = call.node;
333 if let ExprKind::Path(_, ref path) = closure.node;
335 if sp_ident.node == (&path.segments[0]).identifier {
338 REDUNDANT_CLOSURE_CALL,
340 "Closure called just once immediately after it was declared",
350 fn check_lit(&self, cx: &EarlyContext, lit: &Lit) {
352 if let LitKind::Int(value, ..) = lit.node;
353 if let Some(src) = snippet_opt(cx, lit.span);
354 if let Some(firstch) = src.chars().next();
355 if char::to_digit(firstch, 10).is_some();
358 for ch in src.chars() {
359 if ch == 'i' || ch == 'u' {
361 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
362 "integer type suffix should be separated by an underscore");
368 if src.starts_with("0x") {
369 let mut seen = (false, false);
370 for ch in src.chars() {
372 'a' ... 'f' => seen.0 = true,
373 'A' ... 'F' => seen.1 = true,
374 'i' | 'u' => break, // start of suffix already
378 if seen.0 && seen.1 {
379 span_lint(cx, MIXED_CASE_HEX_LITERALS, lit.span,
380 "inconsistent casing in hexadecimal literal");
382 } else if src.starts_with("0b") || src.starts_with("0o") {
384 } else if value != 0 && src.starts_with('0') {
385 span_lint_and_then(cx,
386 ZERO_PREFIXED_LITERAL,
388 "this is a decimal constant",
392 "if you mean to use a decimal constant, remove the `0` to remove confusion",
393 src.trim_left_matches(|c| c == '_' || c == '0').to_string(),
397 "if you mean to use an octal constant, use `0o`",
398 format!("0o{}", src.trim_left_matches(|c| c == '_' || c == '0')),
405 if let LitKind::Float(..) = lit.node;
406 if let Some(src) = snippet_opt(cx, lit.span);
407 if let Some(firstch) = src.chars().next();
408 if char::to_digit(firstch, 10).is_some();
411 for ch in src.chars() {
414 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
415 "float type suffix should be separated by an underscore");