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