]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/serde_api.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / serde_api.rs
1 use rustc::lint::*;
2 use rustc::{declare_lint, lint_array};
3 use rustc::hir::*;
4 use crate::utils::{get_trait_def_id, paths, span_lint};
5
6 /// **What it does:** Checks for mis-uses of the serde API.
7 ///
8 /// **Why is this bad?** Serde is very finnicky about how its API should be
9 /// used, but the type system can't be used to enforce it (yet?).
10 ///
11 /// **Known problems:** None.
12 ///
13 /// **Example:** Implementing `Visitor::visit_string` but not
14 /// `Visitor::visit_str`.
15 declare_clippy_lint! {
16     pub SERDE_API_MISUSE,
17     correctness,
18     "various things that will negatively affect your serde experience"
19 }
20
21
22 #[derive(Copy, Clone)]
23 pub struct Serde;
24
25 impl LintPass for Serde {
26     fn get_lints(&self) -> LintArray {
27         lint_array!(SERDE_API_MISUSE)
28     }
29 }
30
31 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Serde {
32     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
33         if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, ref items) = item.node {
34             let did = trait_ref.path.def.def_id();
35             if let Some(visit_did) = get_trait_def_id(cx, &paths::SERDE_DE_VISITOR) {
36                 if did == visit_did {
37                     let mut seen_str = None;
38                     let mut seen_string = None;
39                     for item in items {
40                         match &*item.ident.as_str() {
41                             "visit_str" => seen_str = Some(item.span),
42                             "visit_string" => seen_string = Some(item.span),
43                             _ => {},
44                         }
45                     }
46                     if let Some(span) = seen_string {
47                         if seen_str.is_none() {
48                             span_lint(
49                                 cx,
50                                 SERDE_API_MISUSE,
51                                 span,
52                                 "you should not implement `visit_string` without also implementing `visit_str`",
53                             );
54                         }
55                     }
56                 }
57             }
58         }
59     }
60 }