-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathderive_deserialize_allowing_unknown.rs
165 lines (147 loc) · 5.1 KB
/
derive_deserialize_allowing_unknown.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use clippy_utils::diagnostics::span_lint;
use clippy_utils::{def_path_res, paths};
use rustc_ast::tokenstream::{TokenStream, TokenTree};
use rustc_ast::{AttrStyle, DelimArgs};
use rustc_hir::def::Res;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::{
AttrArgs, AttrItem, AttrPath, Attribute, HirId, Impl, Item, ItemKind, Path, QPath, TraitRef, Ty, TyKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::TyCtxt;
use rustc_session::declare_lint_pass;
use rustc_span::sym;
use std::sync::OnceLock;
declare_clippy_lint! {
/// ### What it does
/// Checks for structs or enums that derive `serde::Deserialize` and that
/// do not have a `#[serde(deny_unknown_fields)]` attribute.
///
/// ### Why is this bad?
/// If the struct or enum is used in [`clippy_config::conf::Conf`] and a
/// user inserts an unknown field by mistake, the user's error will be
/// silently ignored.
///
/// ### Example
/// ```rust
/// #[derive(serde::Deserialize)]
/// pub struct DisallowedPath {
/// path: String,
/// reason: Option<String>,
/// replacement: Option<String>,
/// }
/// ```
///
/// Use instead:
/// ```rust
/// #[derive(serde::Deserialize)]
/// #[serde(deny_unknown_fields)]
/// pub struct DisallowedPath {
/// path: String,
/// reason: Option<String>,
/// replacement: Option<String>,
/// }
/// ```
pub DERIVE_DESERIALIZE_ALLOWING_UNKNOWN,
internal,
"`#[derive(serde::Deserialize)]` without `#[serde(deny_unknown_fields)]`"
}
declare_lint_pass!(DeriveDeserializeAllowingUnknown => [DERIVE_DESERIALIZE_ALLOWING_UNKNOWN]);
impl<'tcx> LateLintPass<'tcx> for DeriveDeserializeAllowingUnknown {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
// Is this an `impl` (of a certain form)?
let ItemKind::Impl(Impl {
of_trait: Some(TraitRef {
path: Path { res, .. }, ..
}),
self_ty:
Ty {
kind:
TyKind::Path(QPath::Resolved(
None,
Path {
res: Res::Def(_, self_ty_def_id),
..
},
)),
..
},
..
}) = item.kind
else {
return;
};
// Is it an `impl` of the trait `serde::Deserialize`?
if !is_serde_deserialize_res(cx.tcx, res) {
return;
}
// Is it derived?
if !cx.tcx.has_attr(item.owner_id, sym::automatically_derived) {
return;
}
// Is `self_ty` local?
let Some(local_def_id) = self_ty_def_id.as_local() else {
return;
};
// Does `self_ty` have a variant with named fields?
if !has_variant_with_named_fields(cx.tcx, local_def_id) {
return;
}
let hir_id = cx.tcx.local_def_id_to_hir_id(local_def_id);
// Does `self_ty` have `#[serde(deny_unknown_fields)]`?
if let Some(tokens) = find_serde_attr_item(cx.tcx, hir_id)
&& tokens.iter().any(is_deny_unknown_fields_token)
{
return;
}
span_lint(
cx,
DERIVE_DESERIALIZE_ALLOWING_UNKNOWN,
item.span,
"`#[derive(serde::Deserialize)]` without `#[serde(deny_unknown_fields)]`",
);
}
}
fn is_serde_deserialize_res(tcx: TyCtxt<'_>, res: &Res) -> bool {
static SERDE_DESERIALIZE_RESES: OnceLock<Vec<Res>> = OnceLock::new();
let serde_deserialize_reses = SERDE_DESERIALIZE_RESES.get_or_init(|| def_path_res(tcx, &paths::SERDE_DESERIALIZE));
serde_deserialize_reses.contains(res)
}
// Determines whether `def_id` corresponds to an ADT with at least one variant with named fields. A
// variant has named fields if its `ctor` field is `None`.
fn has_variant_with_named_fields(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
let ty = tcx.type_of(def_id).skip_binder();
let rustc_middle::ty::Adt(adt_def, _) = ty.kind() else {
return false;
};
adt_def.variants().iter().any(|variant_def| variant_def.ctor.is_none())
}
fn find_serde_attr_item(tcx: TyCtxt<'_>, hir_id: HirId) -> Option<&TokenStream> {
tcx.hir().attrs(hir_id).iter().find_map(|attribute| {
if let Attribute::Unparsed(attr_item) = attribute
&& let AttrItem {
path: AttrPath { segments, .. },
args: AttrArgs::Delimited(DelimArgs { tokens, .. }),
style: AttrStyle::Outer,
..
} = &**attr_item
&& segments.len() == 1
&& segments[0].as_str() == "serde"
{
Some(tokens)
} else {
None
}
})
}
fn is_deny_unknown_fields_token(tt: &TokenTree) -> bool {
if let TokenTree::Token(token, _) = tt
&& token
.ident()
.is_some_and(|(token, _)| token.as_str() == "deny_unknown_fields")
{
true
} else {
false
}
}