]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/serde_api.rs
Auto merge of #82680 - jturner314:div_euclid-docs, r=JohnTitor
[rust.git] / src / tools / clippy / clippy_lints / src / serde_api.rs
1 use crate::utils::{get_trait_def_id, paths, span_lint};
2 use rustc_hir::{Impl, Item, ItemKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5
6 declare_clippy_lint! {
7     /// **What it does:** Checks for mis-uses of the serde API.
8     ///
9     /// **Why is this bad?** Serde is very finnicky about how its API should be
10     /// used, but the type system can't be used to enforce it (yet?).
11     ///
12     /// **Known problems:** None.
13     ///
14     /// **Example:** Implementing `Visitor::visit_string` but not
15     /// `Visitor::visit_str`.
16     pub SERDE_API_MISUSE,
17     correctness,
18     "various things that will negatively affect your serde experience"
19 }
20
21 declare_lint_pass!(SerdeApi => [SERDE_API_MISUSE]);
22
23 impl<'tcx> LateLintPass<'tcx> for SerdeApi {
24     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
25         if let ItemKind::Impl(Impl {
26             of_trait: Some(ref trait_ref),
27             items,
28             ..
29         }) = item.kind
30         {
31             let did = trait_ref.path.res.def_id();
32             if let Some(visit_did) = get_trait_def_id(cx, &paths::SERDE_DE_VISITOR) {
33                 if did == visit_did {
34                     let mut seen_str = None;
35                     let mut seen_string = None;
36                     for item in items {
37                         match &*item.ident.as_str() {
38                             "visit_str" => seen_str = Some(item.span),
39                             "visit_string" => seen_string = Some(item.span),
40                             _ => {},
41                         }
42                     }
43                     if let Some(span) = seen_string {
44                         if seen_str.is_none() {
45                             span_lint(
46                                 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     }
57 }