]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/serde_api.rs
Move `max_value` handling to consts module
[rust.git] / clippy_lints / src / serde_api.rs
1 use crate::utils::{get_trait_def_id, paths, span_lint};
2 use rustc::hir::*;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
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 #[derive(Copy, Clone)]
22 pub struct Serde;
23
24 impl LintPass for Serde {
25     fn get_lints(&self) -> LintArray {
26         lint_array!(SERDE_API_MISUSE)
27     }
28
29     fn name(&self) -> &'static str {
30         "SerdeAPI"
31     }
32 }
33
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Serde {
35     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
36         if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, ref items) = item.node {
37             let did = trait_ref.path.def.def_id();
38             if let Some(visit_did) = get_trait_def_id(cx, &paths::SERDE_DE_VISITOR) {
39                 if did == visit_did {
40                     let mut seen_str = None;
41                     let mut seen_string = None;
42                     for item in items {
43                         match &*item.ident.as_str() {
44                             "visit_str" => seen_str = Some(item.span),
45                             "visit_string" => seen_string = Some(item.span),
46                             _ => {},
47                         }
48                     }
49                     if let Some(span) = seen_string {
50                         if seen_str.is_none() {
51                             span_lint(
52                                 cx,
53                                 SERDE_API_MISUSE,
54                                 span,
55                                 "you should not implement `visit_string` without also implementing `visit_str`",
56                             );
57                         }
58                     }
59                 }
60             }
61         }
62     }
63 }