|
| 1 | +use std::collections::btree_map::Entry; |
| 2 | +use std::collections::BTreeMap; |
| 3 | + |
| 4 | +use clippy_utils::diagnostics::span_lint_hir_and_then; |
| 5 | +use clippy_utils::is_lint_allowed; |
| 6 | +use itertools::Itertools; |
| 7 | +use rustc_hir::def_id::LocalDefId; |
| 8 | +use rustc_hir::intravisit::{walk_block, walk_expr, walk_stmt, Visitor}; |
| 9 | +use rustc_hir::{BlockCheckMode, Expr, ExprKind, HirId, Stmt, UnsafeSource}; |
| 10 | +use rustc_lint::{LateContext, LateLintPass}; |
| 11 | +use rustc_session::impl_lint_pass; |
| 12 | +use rustc_span::{sym, Span, SyntaxContext}; |
| 13 | + |
| 14 | +declare_clippy_lint! { |
| 15 | + /// ### What it does |
| 16 | + /// Looks for macros that expand metavariables in an unsafe block. |
| 17 | + /// |
| 18 | + /// ### Why is this bad? |
| 19 | + /// This hides an unsafe block and allows the user of the macro to write unsafe code without an explicit |
| 20 | + /// unsafe block at callsite, making it possible to perform unsafe operations in seemingly safe code. |
| 21 | + /// |
| 22 | + /// The macro should be restructured so that these metavariables are referenced outside of unsafe blocks |
| 23 | + /// and that the usual unsafety checks apply to the macro argument. |
| 24 | + /// |
| 25 | + /// This is usually done by binding it to a variable outside of the unsafe block |
| 26 | + /// and then using that variable inside of the block as shown in the example, or by referencing it a second time |
| 27 | + /// in a safe context, e.g. `if false { $expr }`. |
| 28 | + /// |
| 29 | + /// ### Known limitations |
| 30 | + /// Due to how macros are represented in the compiler at the time Clippy runs its lints, |
| 31 | + /// it's not possible to look for metavariables in macro definitions directly. |
| 32 | + /// |
| 33 | + /// Instead, this lint looks at expansions of macros. |
| 34 | + /// This leads to false negatives for macros that are never actually invoked. |
| 35 | + /// |
| 36 | + /// By default, this lint is rather conservative and will only emit warnings on publicly-exported |
| 37 | + /// macros from the same crate, because oftentimes private internal macros are one-off macros where |
| 38 | + /// this lint would just be noise (e.g. macros that generate `impl` blocks). |
| 39 | + /// The default behavior should help with preventing a high number of such false positives, |
| 40 | + /// however it can be configured to also emit warnings in private macros if desired. |
| 41 | + /// |
| 42 | + /// ### Example |
| 43 | + /// ```no_run |
| 44 | + /// /// Gets the first element of a slice |
| 45 | + /// macro_rules! first { |
| 46 | + /// ($slice:expr) => { |
| 47 | + /// unsafe { |
| 48 | + /// let slice = $slice; // ⚠️ expansion inside of `unsafe {}` |
| 49 | + /// |
| 50 | + /// assert!(!slice.is_empty()); |
| 51 | + /// // SAFETY: slice is checked to have at least one element |
| 52 | + /// slice.first().unwrap_unchecked() |
| 53 | + /// } |
| 54 | + /// } |
| 55 | + /// } |
| 56 | + /// |
| 57 | + /// assert_eq!(*first!(&[1i32]), 1); |
| 58 | + /// |
| 59 | + /// // This will compile as a consequence (note the lack of `unsafe {}`) |
| 60 | + /// assert_eq!(*first!(std::hint::unreachable_unchecked() as &[i32]), 1); |
| 61 | + /// ``` |
| 62 | + /// Use instead: |
| 63 | + /// ```compile_fail |
| 64 | + /// macro_rules! first { |
| 65 | + /// ($slice:expr) => {{ |
| 66 | + /// let slice = $slice; // ✅ outside of `unsafe {}` |
| 67 | + /// unsafe { |
| 68 | + /// assert!(!slice.is_empty()); |
| 69 | + /// // SAFETY: slice is checked to have at least one element |
| 70 | + /// slice.first().unwrap_unchecked() |
| 71 | + /// } |
| 72 | + /// }} |
| 73 | + /// } |
| 74 | + /// |
| 75 | + /// assert_eq!(*first!(&[1]), 1); |
| 76 | + /// |
| 77 | + /// // This won't compile: |
| 78 | + /// assert_eq!(*first!(std::hint::unreachable_unchecked() as &[i32]), 1); |
| 79 | + /// ``` |
| 80 | + #[clippy::version = "1.80.0"] |
| 81 | + pub MACRO_METAVARS_IN_UNSAFE, |
| 82 | + suspicious, |
| 83 | + "expanding macro metavariables in an unsafe block" |
| 84 | +} |
| 85 | +impl_lint_pass!(ExprMetavarsInUnsafe => [MACRO_METAVARS_IN_UNSAFE]); |
| 86 | + |
| 87 | +#[derive(Clone, Debug)] |
| 88 | +pub enum MetavarState { |
| 89 | + ReferencedInUnsafe { unsafe_blocks: Vec<HirId> }, |
| 90 | + ReferencedInSafe, |
| 91 | +} |
| 92 | + |
| 93 | +#[derive(Default)] |
| 94 | +pub struct ExprMetavarsInUnsafe { |
| 95 | + pub warn_unsafe_macro_metavars_in_private_macros: bool, |
| 96 | + /// A metavariable can be expanded more than once, potentially across multiple bodies, so it |
| 97 | + /// requires some state kept across HIR nodes to make it possible to delay a warning |
| 98 | + /// and later undo: |
| 99 | + /// |
| 100 | + /// ```ignore |
| 101 | + /// macro_rules! x { |
| 102 | + /// ($v:expr) => { |
| 103 | + /// unsafe { $v; } // unsafe context, it might be possible to emit a warning here, so add it to the map |
| 104 | + /// |
| 105 | + /// $v; // `$v` expanded another time but in a safe context, set to ReferencedInSafe to suppress |
| 106 | + /// } |
| 107 | + /// } |
| 108 | + /// ``` |
| 109 | + pub metavar_expns: BTreeMap<Span, MetavarState>, |
| 110 | +} |
| 111 | + |
| 112 | +struct BodyVisitor<'a, 'tcx> { |
| 113 | + /// Stack of unsafe blocks -- the top item always represents the last seen unsafe block from |
| 114 | + /// within a relevant macro. |
| 115 | + macro_unsafe_blocks: Vec<HirId>, |
| 116 | + /// When this is >0, it means that the node currently being visited is "within" a |
| 117 | + /// macro definition. This is not necessary for correctness, it merely helps reduce the number |
| 118 | + /// of spans we need to insert into the map, since only spans from macros are relevant. |
| 119 | + expn_depth: u32, |
| 120 | + cx: &'a LateContext<'tcx>, |
| 121 | + lint: &'a mut ExprMetavarsInUnsafe, |
| 122 | +} |
| 123 | + |
| 124 | +fn is_public_macro(cx: &LateContext<'_>, def_id: LocalDefId) -> bool { |
| 125 | + (cx.effective_visibilities.is_exported(def_id) || cx.tcx.has_attr(def_id, sym::macro_export)) |
| 126 | + && !cx.tcx.is_doc_hidden(def_id) |
| 127 | +} |
| 128 | + |
| 129 | +impl<'a, 'tcx> Visitor<'tcx> for BodyVisitor<'a, 'tcx> { |
| 130 | + fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) { |
| 131 | + let from_expn = s.span.from_expansion(); |
| 132 | + if from_expn { |
| 133 | + self.expn_depth += 1; |
| 134 | + } |
| 135 | + walk_stmt(self, s); |
| 136 | + if from_expn { |
| 137 | + self.expn_depth -= 1; |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + fn visit_expr(&mut self, e: &'tcx Expr<'tcx>) { |
| 142 | + let ctxt = e.span.ctxt(); |
| 143 | + |
| 144 | + if let ExprKind::Block(block, _) = e.kind |
| 145 | + && let BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) = block.rules |
| 146 | + && !ctxt.is_root() |
| 147 | + && let Some(macro_def_id) = ctxt.outer_expn_data().macro_def_id |
| 148 | + && let Some(macro_def_id) = macro_def_id.as_local() |
| 149 | + && (self.lint.warn_unsafe_macro_metavars_in_private_macros || is_public_macro(self.cx, macro_def_id)) |
| 150 | + { |
| 151 | + self.macro_unsafe_blocks.push(block.hir_id); |
| 152 | + walk_block(self, block); |
| 153 | + self.macro_unsafe_blocks.pop(); |
| 154 | + } else if ctxt.is_root() && self.expn_depth > 0 { |
| 155 | + let unsafe_block = self.macro_unsafe_blocks.last().copied(); |
| 156 | + |
| 157 | + match (self.lint.metavar_expns.entry(e.span), unsafe_block) { |
| 158 | + (Entry::Vacant(e), None) => { |
| 159 | + e.insert(MetavarState::ReferencedInSafe); |
| 160 | + }, |
| 161 | + (Entry::Vacant(e), Some(unsafe_block)) => { |
| 162 | + e.insert(MetavarState::ReferencedInUnsafe { |
| 163 | + unsafe_blocks: vec![unsafe_block], |
| 164 | + }); |
| 165 | + }, |
| 166 | + (Entry::Occupied(mut e), None) => { |
| 167 | + if let MetavarState::ReferencedInUnsafe { .. } = *e.get() { |
| 168 | + e.insert(MetavarState::ReferencedInSafe); |
| 169 | + } |
| 170 | + }, |
| 171 | + (Entry::Occupied(mut e), Some(unsafe_block)) => { |
| 172 | + if let MetavarState::ReferencedInUnsafe { unsafe_blocks } = e.get_mut() |
| 173 | + && !unsafe_blocks.contains(&unsafe_block) |
| 174 | + { |
| 175 | + unsafe_blocks.push(unsafe_block); |
| 176 | + } |
| 177 | + }, |
| 178 | + } |
| 179 | + |
| 180 | + // NB: No need to visit descendant nodes. They're guaranteed to represent the same |
| 181 | + // metavariable |
| 182 | + } else { |
| 183 | + walk_expr(self, e); |
| 184 | + } |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +impl<'tcx> LateLintPass<'tcx> for ExprMetavarsInUnsafe { |
| 189 | + fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx rustc_hir::Body<'tcx>) { |
| 190 | + if is_lint_allowed(cx, MACRO_METAVARS_IN_UNSAFE, body.value.hir_id) { |
| 191 | + return; |
| 192 | + } |
| 193 | + |
| 194 | + // This BodyVisitor is separate and not part of the lint pass because there is no |
| 195 | + // `check_stmt_post` on `(Late)LintPass`, which we'd need to detect when we're leaving a macro span |
| 196 | + |
| 197 | + let mut vis = BodyVisitor { |
| 198 | + #[expect(clippy::bool_to_int_with_if)] // obfuscates the meaning |
| 199 | + expn_depth: if body.value.span.from_expansion() { 1 } else { 0 }, |
| 200 | + macro_unsafe_blocks: Vec::new(), |
| 201 | + lint: self, |
| 202 | + cx |
| 203 | + }; |
| 204 | + vis.visit_body(body); |
| 205 | + } |
| 206 | + |
| 207 | + fn check_crate_post(&mut self, cx: &LateContext<'tcx>) { |
| 208 | + // Aggregate all unsafe blocks from all spans: |
| 209 | + // ``` |
| 210 | + // macro_rules! x { |
| 211 | + // ($w:expr, $x:expr, $y:expr) => { $w; unsafe { $w; $x; }; unsafe { $x; $y; }; } |
| 212 | + // } |
| 213 | + // $w: [] (unsafe#0 is never added because it was referenced in a safe context) |
| 214 | + // $x: [unsafe#0, unsafe#1] |
| 215 | + // $y: [unsafe#1] |
| 216 | + // ``` |
| 217 | + // We want to lint unsafe blocks #0 and #1 |
| 218 | + let bad_unsafe_blocks = self |
| 219 | + .metavar_expns |
| 220 | + .iter() |
| 221 | + .filter_map(|(_, state)| match state { |
| 222 | + MetavarState::ReferencedInUnsafe { unsafe_blocks } => Some(unsafe_blocks.as_slice()), |
| 223 | + MetavarState::ReferencedInSafe => None, |
| 224 | + }) |
| 225 | + .flatten() |
| 226 | + .copied() |
| 227 | + .map(|id| { |
| 228 | + // Remove the syntax context to hide "in this macro invocation" in the diagnostic. |
| 229 | + // The invocation doesn't matter. Also we want to dedupe by the unsafe block and not by anything |
| 230 | + // related to the callsite. |
| 231 | + let span = cx.tcx.hir().span(id); |
| 232 | + |
| 233 | + (id, Span::new(span.lo(), span.hi(), SyntaxContext::root(), None)) |
| 234 | + }) |
| 235 | + .dedup_by(|&(_, a), &(_, b)| a == b); |
| 236 | + |
| 237 | + for (id, span) in bad_unsafe_blocks { |
| 238 | + span_lint_hir_and_then( |
| 239 | + cx, |
| 240 | + MACRO_METAVARS_IN_UNSAFE, |
| 241 | + id, |
| 242 | + span, |
| 243 | + "this macro expands metavariables in an unsafe block", |
| 244 | + |diag| { |
| 245 | + diag.note("this allows the user of the macro to write unsafe code outside of an unsafe block"); |
| 246 | + diag.help( |
| 247 | + "consider expanding any metavariables outside of this block, e.g. by storing them in a variable", |
| 248 | + ); |
| 249 | + diag.help( |
| 250 | + "... or also expand referenced metavariables in a safe context to require an unsafe block at callsite", |
| 251 | + ); |
| 252 | + }, |
| 253 | + ); |
| 254 | + } |
| 255 | + } |
| 256 | +} |
0 commit comments