]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/serde_api.rs
Auto merge of #89123 - the8472:push_in_capacity, r=amanieu
[rust.git] / src / tools / clippy / clippy_lints / src / serde_api.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{get_trait_def_id, paths};
3 use rustc_hir::{Impl, Item, ItemKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// ### What it does
9     /// Checks for mis-uses of the serde API.
10     ///
11     /// ### Why is this bad?
12     /// Serde is very finnicky about how its API should be
13     /// used, but the type system can't be used to enforce it (yet?).
14     ///
15     /// ### Example
16     /// Implementing `Visitor::visit_string` but not
17     /// `Visitor::visit_str`.
18     #[clippy::version = "pre 1.29.0"]
19     pub SERDE_API_MISUSE,
20     correctness,
21     "various things that will negatively affect your serde experience"
22 }
23
24 declare_lint_pass!(SerdeApi => [SERDE_API_MISUSE]);
25
26 impl<'tcx> LateLintPass<'tcx> for SerdeApi {
27     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
28         if let ItemKind::Impl(Impl {
29             of_trait: Some(ref trait_ref),
30             items,
31             ..
32         }) = item.kind
33         {
34             let did = trait_ref.path.res.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 }