]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/serde_api.rs
Rollup merge of #82917 - cuviper:iter-zip, r=m-ou-se
[rust.git] / 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:** Checks for mis-uses of the serde API.
9     ///
10     /// **Why is this bad?** Serde is very finnicky about how its API should be
11     /// used, but the type system can't be used to enforce it (yet?).
12     ///
13     /// **Known problems:** None.
14     ///
15     /// **Example:** Implementing `Visitor::visit_string` but not
16     /// `Visitor::visit_str`.
17     pub SERDE_API_MISUSE,
18     correctness,
19     "various things that will negatively affect your serde experience"
20 }
21
22 declare_lint_pass!(SerdeApi => [SERDE_API_MISUSE]);
23
24 impl<'tcx> LateLintPass<'tcx> for SerdeApi {
25     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
26         if let ItemKind::Impl(Impl {
27             of_trait: Some(ref trait_ref),
28             items,
29             ..
30         }) = item.kind
31         {
32             let did = trait_ref.path.res.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.ident.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(
47                                 cx,
48                                 SERDE_API_MISUSE,
49                                 span,
50                                 "you should not implement `visit_string` without also implementing `visit_str`",
51                             );
52                         }
53                     }
54                 }
55             }
56         }
57     }
58 }