|
| 1 | +use rustc_hir::{def::DefKind, Body, Item, ItemKind, Node, Path, QPath, TyKind}; |
| 2 | +use rustc_span::def_id::{DefId, LOCAL_CRATE}; |
| 3 | +use rustc_span::{sym, symbol::kw, ExpnKind, MacroKind}; |
| 4 | + |
| 5 | +use smallvec::{smallvec, SmallVec}; |
| 6 | + |
| 7 | +use crate::lints::{NonLocalDefinitionsCargoUpdateNote, NonLocalDefinitionsDiag}; |
| 8 | +use crate::{LateContext, LateLintPass, LintContext}; |
| 9 | + |
| 10 | +declare_lint! { |
| 11 | + /// The `non_local_definitions` lint checks for `impl` blocks and `#[macro_export]` |
| 12 | + /// macro inside bodies (functions, enum discriminant, ...). |
| 13 | + /// |
| 14 | + /// ### Example |
| 15 | + /// |
| 16 | + /// ```rust |
| 17 | + /// trait MyTrait {} |
| 18 | + /// struct MyStruct; |
| 19 | + /// |
| 20 | + /// fn foo() { |
| 21 | + /// impl MyTrait for MyStruct {} |
| 22 | + /// } |
| 23 | + /// ``` |
| 24 | + /// |
| 25 | + /// {{produces}} |
| 26 | + /// |
| 27 | + /// ### Explanation |
| 28 | + /// |
| 29 | + /// Creating non-local definitions go against expectation and can create discrepancies |
| 30 | + /// in tooling. It should be avoided. It may become deny-by-default in edition 2024 |
| 31 | + /// and higher, see see the tracking issue <https://github.com/rust-lang/rust/issues/120363>. |
| 32 | + /// |
| 33 | + /// An `impl` definition is non-local if it is nested inside an item and neither |
| 34 | + /// the type nor the trait are at the same nesting level as the `impl` block. |
| 35 | + /// |
| 36 | + /// All nested bodies (functions, enum discriminant, array length, consts) (expect for |
| 37 | + /// `const _: Ty = { ... }` in top-level module, which is still undecided) are checked. |
| 38 | + pub NON_LOCAL_DEFINITIONS, |
| 39 | + Warn, |
| 40 | + "checks for non-local definitions", |
| 41 | + report_in_external_macro |
| 42 | +} |
| 43 | + |
| 44 | +#[derive(Default)] |
| 45 | +pub struct NonLocalDefinitions { |
| 46 | + body_depth: u32, |
| 47 | +} |
| 48 | + |
| 49 | +impl_lint_pass!(NonLocalDefinitions => [NON_LOCAL_DEFINITIONS]); |
| 50 | + |
| 51 | +// FIXME(Urgau): Figure out how to handle modules nested in bodies. |
| 52 | +// It's currently not handled by the current logic because modules are not bodies. |
| 53 | +// They don't even follow the correct order (check_body -> check_mod -> check_body_post) |
| 54 | +// instead check_mod is called after every body has been handled. |
| 55 | + |
| 56 | +impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { |
| 57 | + fn check_body(&mut self, _cx: &LateContext<'tcx>, _body: &'tcx Body<'tcx>) { |
| 58 | + self.body_depth += 1; |
| 59 | + } |
| 60 | + |
| 61 | + fn check_body_post(&mut self, _cx: &LateContext<'tcx>, _body: &'tcx Body<'tcx>) { |
| 62 | + self.body_depth -= 1; |
| 63 | + } |
| 64 | + |
| 65 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { |
| 66 | + if self.body_depth == 0 { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + let parent = cx.tcx.parent(item.owner_id.def_id.into()); |
| 71 | + let parent_def_kind = cx.tcx.def_kind(parent); |
| 72 | + let parent_opt_item_name = cx.tcx.opt_item_name(parent); |
| 73 | + |
| 74 | + // Per RFC we (currently) ignore anon-const (`const _: Ty = ...`) in top-level module. |
| 75 | + if self.body_depth == 1 |
| 76 | + && parent_def_kind == DefKind::Const |
| 77 | + && parent_opt_item_name == Some(kw::Underscore) |
| 78 | + { |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + let cargo_update = || { |
| 83 | + let oexpn = item.span.ctxt().outer_expn_data(); |
| 84 | + if let Some(def_id) = oexpn.macro_def_id |
| 85 | + && let ExpnKind::Macro(macro_kind, macro_name) = oexpn.kind |
| 86 | + && def_id.krate != LOCAL_CRATE |
| 87 | + && std::env::var_os("CARGO").is_some() |
| 88 | + { |
| 89 | + Some(NonLocalDefinitionsCargoUpdateNote { |
| 90 | + macro_kind: macro_kind.descr(), |
| 91 | + macro_name, |
| 92 | + crate_name: cx.tcx.crate_name(def_id.krate), |
| 93 | + }) |
| 94 | + } else { |
| 95 | + None |
| 96 | + } |
| 97 | + }; |
| 98 | + |
| 99 | + match item.kind { |
| 100 | + ItemKind::Impl(impl_) => { |
| 101 | + // The RFC states: |
| 102 | + // |
| 103 | + // > An item nested inside an expression-containing item (through any |
| 104 | + // > level of nesting) may not define an impl Trait for Type unless |
| 105 | + // > either the **Trait** or the **Type** is also nested inside the |
| 106 | + // > same expression-containing item. |
| 107 | + // |
| 108 | + // To achieve this we get try to get the paths of the _Trait_ and |
| 109 | + // _Type_, and we look inside thoses paths to try a find in one |
| 110 | + // of them a type whose parent is the same as the impl definition. |
| 111 | + // |
| 112 | + // If that's the case this means that this impl block declaration |
| 113 | + // is using local items and so we don't lint on it. |
| 114 | + |
| 115 | + // We also ignore anon-const in item by including the anon-const |
| 116 | + // parent as well; and since it's quite uncommon, we use smallvec |
| 117 | + // to avoid unnecessary heap allocations. |
| 118 | + let local_parents: SmallVec<[DefId; 1]> = if parent_def_kind == DefKind::Const |
| 119 | + && parent_opt_item_name == Some(kw::Underscore) |
| 120 | + { |
| 121 | + smallvec![parent, cx.tcx.parent(parent)] |
| 122 | + } else { |
| 123 | + smallvec![parent] |
| 124 | + }; |
| 125 | + |
| 126 | + let self_ty_has_local_parent = match impl_.self_ty.kind { |
| 127 | + TyKind::Path(QPath::Resolved(_, ty_path)) => { |
| 128 | + path_has_local_parent(ty_path, cx, &*local_parents) |
| 129 | + } |
| 130 | + TyKind::TraitObject([principle_poly_trait_ref, ..], _, _) => { |
| 131 | + path_has_local_parent( |
| 132 | + principle_poly_trait_ref.trait_ref.path, |
| 133 | + cx, |
| 134 | + &*local_parents, |
| 135 | + ) |
| 136 | + } |
| 137 | + TyKind::TraitObject([], _, _) |
| 138 | + | TyKind::InferDelegation(_, _) |
| 139 | + | TyKind::Slice(_) |
| 140 | + | TyKind::Array(_, _) |
| 141 | + | TyKind::Ptr(_) |
| 142 | + | TyKind::Ref(_, _) |
| 143 | + | TyKind::BareFn(_) |
| 144 | + | TyKind::Never |
| 145 | + | TyKind::Tup(_) |
| 146 | + | TyKind::Path(_) |
| 147 | + | TyKind::AnonAdt(_) |
| 148 | + | TyKind::OpaqueDef(_, _, _) |
| 149 | + | TyKind::Typeof(_) |
| 150 | + | TyKind::Infer |
| 151 | + | TyKind::Err(_) => false, |
| 152 | + }; |
| 153 | + |
| 154 | + let of_trait_has_local_parent = impl_ |
| 155 | + .of_trait |
| 156 | + .map(|of_trait| path_has_local_parent(of_trait.path, cx, &*local_parents)) |
| 157 | + .unwrap_or(false); |
| 158 | + |
| 159 | + // If none of them have a local parent (LOGICAL NOR) this means that |
| 160 | + // this impl definition is a non-local definition and so we lint on it. |
| 161 | + if !(self_ty_has_local_parent || of_trait_has_local_parent) { |
| 162 | + let const_anon = if self.body_depth == 1 |
| 163 | + && parent_def_kind == DefKind::Const |
| 164 | + && parent_opt_item_name != Some(kw::Underscore) |
| 165 | + && let Some(parent) = parent.as_local() |
| 166 | + && let Node::Item(item) = cx.tcx.hir_node_by_def_id(parent) |
| 167 | + && let ItemKind::Const(ty, _, _) = item.kind |
| 168 | + && let TyKind::Tup(&[]) = ty.kind |
| 169 | + { |
| 170 | + Some(item.ident.span) |
| 171 | + } else { |
| 172 | + None |
| 173 | + }; |
| 174 | + |
| 175 | + cx.emit_span_lint( |
| 176 | + NON_LOCAL_DEFINITIONS, |
| 177 | + item.span, |
| 178 | + NonLocalDefinitionsDiag::Impl { |
| 179 | + depth: self.body_depth, |
| 180 | + body_kind_descr: cx.tcx.def_kind_descr(parent_def_kind, parent), |
| 181 | + body_name: parent_opt_item_name |
| 182 | + .map(|s| s.to_ident_string()) |
| 183 | + .unwrap_or_else(|| "<unnameable>".to_string()), |
| 184 | + cargo_update: cargo_update(), |
| 185 | + const_anon, |
| 186 | + }, |
| 187 | + ) |
| 188 | + } |
| 189 | + } |
| 190 | + ItemKind::Macro(_macro, MacroKind::Bang) |
| 191 | + if cx.tcx.has_attr(item.owner_id.def_id, sym::macro_export) => |
| 192 | + { |
| 193 | + cx.emit_span_lint( |
| 194 | + NON_LOCAL_DEFINITIONS, |
| 195 | + item.span, |
| 196 | + NonLocalDefinitionsDiag::MacroRules { |
| 197 | + depth: self.body_depth, |
| 198 | + body_kind_descr: cx.tcx.def_kind_descr(parent_def_kind, parent), |
| 199 | + body_name: parent_opt_item_name |
| 200 | + .map(|s| s.to_ident_string()) |
| 201 | + .unwrap_or_else(|| "<unnameable>".to_string()), |
| 202 | + cargo_update: cargo_update(), |
| 203 | + }, |
| 204 | + ) |
| 205 | + } |
| 206 | + _ => {} |
| 207 | + } |
| 208 | + } |
| 209 | +} |
| 210 | + |
| 211 | +/// Given a path and a parent impl def id, this checks if the if parent resolution |
| 212 | +/// def id correspond to the def id of the parent impl definition. |
| 213 | +/// |
| 214 | +/// Given this path, we will look at the path (and ignore any generic args): |
| 215 | +/// |
| 216 | +/// ```text |
| 217 | +/// std::convert::PartialEq<Foo<Bar>> |
| 218 | +/// ^^^^^^^^^^^^^^^^^^^^^^^ |
| 219 | +/// ``` |
| 220 | +fn path_has_local_parent(path: &Path<'_>, cx: &LateContext<'_>, local_parents: &[DefId]) -> bool { |
| 221 | + path.res.opt_def_id().is_some_and(|did| local_parents.contains(&cx.tcx.parent(did))) |
| 222 | +} |
0 commit comments