1use rustc_errors::MultiSpan;
2use rustc_hir::attrs::AttributeKind;
3use rustc_hir::def::{DefKind, Res};
4use rustc_hir::intravisit::{self, Visitor, VisitorExt};
5use rustc_hir::{Body, HirId, Item, ItemKind, Node, Path, TyKind, find_attr};
6use rustc_middle::ty::TyCtxt;
7use rustc_session::{declare_lint, impl_lint_pass};
8use rustc_span::def_id::{DefId, LOCAL_CRATE};
9use rustc_span::{ExpnKind, Span, kw};
1011use crate::lints::{NonLocalDefinitionsCargoUpdateNote, NonLocalDefinitionsDiag};
12use crate::{LateContext, LateLintPass, LintContext, fluent_generatedas fluent};
1314#[doc =
r" The `non_local_definitions` lint checks for `impl` blocks and `#[macro_export]`"]
#[doc = r" macro inside bodies (functions, enum discriminant, ...)."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![warn(non_local_definitions)]"]
#[doc = r" trait MyTrait {}"]
#[doc = r" struct MyStruct;"]
#[doc = r""]
#[doc = r" fn foo() {"]
#[doc = r" impl MyTrait for MyStruct {}"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Creating non-local definitions go against expectation and can create discrepancies"]
#[doc =
r" in tooling. It should be avoided. It may become deny-by-default in edition 2024"]
#[doc =
r" and higher, see the tracking issue <https://github.com/rust-lang/rust/issues/120363>."]
#[doc = r""]
#[doc =
r" An `impl` definition is non-local if it is nested inside an item and neither"]
#[doc =
r" the type nor the trait are at the same nesting level as the `impl` block."]
#[doc = r""]
#[doc =
r" All nested bodies (functions, enum discriminant, array length, consts) (expect for"]
#[doc =
r" `const _: Ty = { ... }` in top-level module, which is still undecided) are checked."]
pub static NON_LOCAL_DEFINITIONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "NON_LOCAL_DEFINITIONS",
default_level: ::rustc_lint_defs::Warn,
desc: "checks for non-local definitions",
is_externally_loaded: false,
report_in_external_macro: true,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
15/// The `non_local_definitions` lint checks for `impl` blocks and `#[macro_export]`
16 /// macro inside bodies (functions, enum discriminant, ...).
17 ///
18 /// ### Example
19 ///
20 /// ```rust
21 /// #![warn(non_local_definitions)]
22 /// trait MyTrait {}
23 /// struct MyStruct;
24 ///
25 /// fn foo() {
26 /// impl MyTrait for MyStruct {}
27 /// }
28 /// ```
29 ///
30 /// {{produces}}
31 ///
32 /// ### Explanation
33 ///
34 /// Creating non-local definitions go against expectation and can create discrepancies
35 /// in tooling. It should be avoided. It may become deny-by-default in edition 2024
36 /// and higher, see the tracking issue <https://github.com/rust-lang/rust/issues/120363>.
37 ///
38 /// An `impl` definition is non-local if it is nested inside an item and neither
39 /// the type nor the trait are at the same nesting level as the `impl` block.
40 ///
41 /// All nested bodies (functions, enum discriminant, array length, consts) (expect for
42 /// `const _: Ty = { ... }` in top-level module, which is still undecided) are checked.
43pub NON_LOCAL_DEFINITIONS,
44 Warn,
45"checks for non-local definitions",
46 report_in_external_macro
47}4849#[derive(#[automatically_derived]
impl ::core::default::Default for NonLocalDefinitions {
#[inline]
fn default() -> NonLocalDefinitions {
NonLocalDefinitions {
body_depth: ::core::default::Default::default(),
}
}
}Default)]
50pub(crate) struct NonLocalDefinitions {
51 body_depth: u32,
52}
5354impl ::rustc_lint_defs::LintPass for NonLocalDefinitions {
fn name(&self) -> &'static str { "NonLocalDefinitions" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NON_LOCAL_DEFINITIONS]))
}
}
impl NonLocalDefinitions {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NON_LOCAL_DEFINITIONS]))
}
}impl_lint_pass!(NonLocalDefinitions => [NON_LOCAL_DEFINITIONS]);
5556// FIXME(Urgau): Figure out how to handle modules nested in bodies.
57// It's currently not handled by the current logic because modules are not bodies.
58// They don't even follow the correct order (check_body -> check_mod -> check_body_post)
59// instead check_mod is called after every body has been handled.
6061impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions {
62fn check_body(&mut self, _cx: &LateContext<'tcx>, _body: &Body<'tcx>) {
63self.body_depth += 1;
64 }
6566fn check_body_post(&mut self, _cx: &LateContext<'tcx>, _body: &Body<'tcx>) {
67self.body_depth -= 1;
68 }
6970fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
71if self.body_depth == 0 {
72return;
73 }
7475let def_id = item.owner_id.def_id.into();
76let parent = cx.tcx.parent(def_id);
77let parent_def_kind = cx.tcx.def_kind(parent);
78let parent_opt_item_name = cx.tcx.opt_item_name(parent);
7980// Per RFC we (currently) ignore anon-const (`const _: Ty = ...`) in top-level module.
81if self.body_depth == 1
82&& parent_def_kind == DefKind::Const83 && parent_opt_item_name == Some(kw::Underscore)
84 {
85return;
86 }
8788let cargo_update = || {
89let oexpn = item.span.ctxt().outer_expn_data();
90if let Some(def_id) = oexpn.macro_def_id
91 && let ExpnKind::Macro(macro_kind, macro_name) = oexpn.kind
92 && def_id.krate != LOCAL_CRATE93 && rustc_session::utils::was_invoked_from_cargo()
94 {
95Some(NonLocalDefinitionsCargoUpdateNote {
96 macro_kind: macro_kind.descr(),
97macro_name,
98 crate_name: cx.tcx.crate_name(def_id.krate),
99 })
100 } else {
101None102 }
103 };
104105// determining if we are in a doctest context can't currently be determined
106 // by the code itself (there are no specific attributes), but fortunately rustdoc
107 // sets a perma-unstable env var for libtest so we just reuse that for now
108let is_at_toplevel_doctest = || {
109self.body_depth == 2
110&& cx.tcx.env_var_os("UNSTABLE_RUSTDOC_TEST_PATH".as_ref()).is_some()
111 };
112113match item.kind {
114 ItemKind::Impl(impl_) => {
115// The RFC states:
116 //
117 // > An item nested inside an expression-containing item (through any
118 // > level of nesting) may not define an impl Trait for Type unless
119 // > either the **Trait** or the **Type** is also nested inside the
120 // > same expression-containing item.
121 //
122 // To achieve this we get try to get the paths of the _Trait_ and
123 // _Type_, and we look inside those paths to try a find in one
124 // of them a type whose parent is the same as the impl definition.
125 //
126 // If that's the case this means that this impl block declaration
127 // is using local items and so we don't lint on it.
128129 // 1. We collect all the `hir::Path` from the `Self` type and `Trait` ref
130 // of the `impl` definition
131let mut collector = PathCollector { paths: Vec::new() };
132collector.visit_ty_unambig(&impl_.self_ty);
133if let Some(of_trait) = impl_.of_trait {
134collector.visit_trait_ref(&of_trait.trait_ref);
135 }
136137// 1.5. Remove any path that doesn't resolve to a `DefId` or if it resolve to a
138 // type-param (e.g. `T`).
139collector.paths.retain(
140 |p| #[allow(non_exhaustive_omitted_patterns)] match p.res {
Res::Def(def_kind, _) if def_kind != DefKind::TyParam => true,
_ => false,
}matches!(p.res, Res::Def(def_kind, _) if def_kind != DefKind::TyParam),
141 );
142143// 1.9. We retrieve the parent def id of the impl item, ...
144 //
145 // ... modulo const-anons items, for enhanced compatibility with the ecosystem
146 // as that pattern is common with `serde`, `bevy`, ...
147 //
148 // For this example we want the `DefId` parent of the outermost const-anon items.
149 // ```
150 // const _: () = { // the parent of this const-anon
151 // const _: () = {
152 // impl Foo {}
153 // };
154 // };
155 // ```
156 //
157 // It isn't possible to mix a impl in a module with const-anon, but an item can
158 // be put inside a module and referenced by a impl so we also have to treat the
159 // item parent as transparent to module and for consistency we have to do the same
160 // for impl, otherwise the item-def and impl-def won't have the same parent.
161let outermost_impl_parent = peel_parent_while(cx.tcx, parent, |tcx, did| {
162tcx.def_kind(did) == DefKind::Mod163 || (tcx.def_kind(did) == DefKind::Const164 && tcx.opt_item_name(did) == Some(kw::Underscore))
165 });
166167// 2. We check if any of the paths reference a the `impl`-parent.
168 //
169 // If that the case we bail out, as was asked by T-lang, even though this isn't
170 // correct from a type-system point of view, as inference exists and one-impl-rule
171 // make its so that we could still leak the impl.
172if collector173 .paths
174 .iter()
175 .any(|path| path_has_local_parent(path, cx, parent, outermost_impl_parent))
176 {
177return;
178 }
179180// Get the span of the parent const item ident (if it's a not a const anon).
181 //
182 // Used to suggest changing the const item to a const anon.
183let span_for_const_anon_suggestion = if parent_def_kind == DefKind::Const184 && parent_opt_item_name != Some(kw::Underscore)
185 && let Some(parent) = parent.as_local()
186 && let Node::Item(item) = cx.tcx.hir_node_by_def_id(parent)
187 && let ItemKind::Const(ident, _, ty, _) = item.kind
188 && let TyKind::Tup(&[]) = ty.kind
189 {
190Some(ident.span)
191 } else {
192None193 };
194195let const_anon = #[allow(non_exhaustive_omitted_patterns)] match parent_def_kind {
DefKind::Const | DefKind::Static { .. } => true,
_ => false,
}matches!(parent_def_kind, DefKind::Const | DefKind::Static { .. })196 .then_some(span_for_const_anon_suggestion);
197198let impl_span = item.span.shrink_to_lo().to(impl_.self_ty.span);
199let mut ms = MultiSpan::from_span(impl_span);
200201for path in &collector.paths {
202 ms.push_span_label(
203 path_span_without_args(path),
204::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is not local",
path_name_to_string(path)))
})format!("`{}` is not local", path_name_to_string(path)),
205 );
206 }
207208let doctest = is_at_toplevel_doctest();
209210if !doctest {
211ms.push_span_label(
212cx.tcx.def_span(parent),
213 fluent::lint_non_local_definitions_impl_move_help,
214 );
215 }
216217let macro_to_change =
218if let ExpnKind::Macro(kind, name) = item.span.ctxt().outer_expn_data().kind {
219Some((name.to_string(), kind.descr()))
220 } else {
221None222 };
223224cx.emit_span_lint(
225NON_LOCAL_DEFINITIONS,
226ms,
227 NonLocalDefinitionsDiag::Impl {
228 depth: self.body_depth,
229 body_kind_descr: cx.tcx.def_kind_descr(parent_def_kind, parent),
230 body_name: parent_opt_item_name231 .map(|s| s.to_ident_string())
232 .unwrap_or_else(|| "<unnameable>".to_string()),
233 cargo_update: cargo_update(),
234const_anon,
235doctest,
236macro_to_change,
237 },
238 )
239 }
240 ItemKind::Macro(_, _macro, _kinds)
241if {
{
'done:
{
for i in cx.tcx.get_all_attrs(item.owner_id.def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::MacroExport { ..
}) => {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(
242 cx.tcx.get_all_attrs(item.owner_id.def_id),
243 AttributeKind::MacroExport { .. }
244 ) =>
245 {
246cx.emit_span_lint(
247NON_LOCAL_DEFINITIONS,
248item.span,
249 NonLocalDefinitionsDiag::MacroRules {
250 depth: self.body_depth,
251 body_kind_descr: cx.tcx.def_kind_descr(parent_def_kind, parent),
252 body_name: parent_opt_item_name253 .map(|s| s.to_ident_string())
254 .unwrap_or_else(|| "<unnameable>".to_string()),
255 cargo_update: cargo_update(),
256 doctest: is_at_toplevel_doctest(),
257 },
258 )
259 }
260_ => {}
261 }
262 }
263}
264265/// Simple hir::Path collector
266struct PathCollector<'tcx> {
267 paths: Vec<Path<'tcx>>,
268}
269270impl<'tcx> Visitor<'tcx> for PathCollector<'tcx> {
271fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
272self.paths.push(path.clone()); // need to clone, bc of the restricted lifetime
273intravisit::walk_path(self, path)
274 }
275}
276277/// Given a path, this checks if the if the parent resolution def id corresponds to
278/// the def id of the parent impl definition (the direct one and the outermost one).
279///
280/// Given this path, we will look at the path (and ignore any generic args):
281///
282/// ```text
283/// std::convert::PartialEq<Foo<Bar>>
284/// ^^^^^^^^^^^^^^^^^^^^^^^
285/// ```
286#[inline]
287fn path_has_local_parent(
288 path: &Path<'_>,
289 cx: &LateContext<'_>,
290 impl_parent: DefId,
291 outermost_impl_parent: Option<DefId>,
292) -> bool {
293path.res
294 .opt_def_id()
295 .is_some_and(|did| did_has_local_parent(did, cx.tcx, impl_parent, outermost_impl_parent))
296}
297298/// Given a def id this checks if the parent def id (modulo modules) correspond to
299/// the def id of the parent impl definition (the direct one and the outermost one).
300#[inline]
301fn did_has_local_parent(
302 did: DefId,
303 tcx: TyCtxt<'_>,
304 impl_parent: DefId,
305 outermost_impl_parent: Option<DefId>,
306) -> bool {
307if !did.is_local() {
308return false;
309 }
310311let Some(parent_did) = tcx.opt_parent(did) else {
312return false;
313 };
314315peel_parent_while(tcx, parent_did, |tcx, did| {
316tcx.def_kind(did) == DefKind::Mod317 || (tcx.def_kind(did) == DefKind::Const318 && tcx.opt_item_name(did) == Some(kw::Underscore))
319 })
320 .map(|parent_did| parent_did == impl_parent || Some(parent_did) == outermost_impl_parent)
321 .unwrap_or(false)
322}
323324/// Given a `DefId` checks if it satisfies `f` if it does check with it's parent and continue
325/// until it doesn't satisfies `f` and return the last `DefId` checked.
326///
327/// In other word this method return the first `DefId` that doesn't satisfies `f`.
328#[inline]
329fn peel_parent_while(
330 tcx: TyCtxt<'_>,
331mut did: DefId,
332mut f: impl FnMut(TyCtxt<'_>, DefId) -> bool,
333) -> Option<DefId> {
334while !did.is_crate_root() && f(tcx, did) {
335 did = tcx.opt_parent(did).filter(|parent_did| parent_did.is_local())?;
336 }
337338Some(did)
339}
340341/// Return for a given `Path` the span until the last args
342fn path_span_without_args(path: &Path<'_>) -> Span {
343if let Some(args) = &path.segments.last().unwrap().args {
344path.span.until(args.span_ext)
345 } else {
346path.span
347 }
348}
349350/// Return a "error message-able" ident for the last segment of the `Path`
351fn path_name_to_string(path: &Path<'_>) -> String {
352path.segments.last().unwrap().ident.to_string()
353}