Skip to main content

clippy_utils/
macros.rs

1#![allow(clippy::similar_names)] // `expr` and `expn`
2
3use std::sync::{Arc, OnceLock};
4
5use crate::visitors::{Descend, for_each_expr_without_closures};
6use crate::{get_unique_builtin_attr, sym};
7
8use arrayvec::ArrayVec;
9use rustc_ast::{FormatArgs, FormatArgument, FormatPlaceholder};
10use rustc_data_structures::fx::FxHashMap;
11use rustc_hir::{self as hir, Expr, ExprKind, HirId, Node, QPath};
12use rustc_lint::{LateContext, LintContext};
13use rustc_span::def_id::DefId;
14use rustc_span::hygiene::{self, MacroKind, SyntaxContext};
15use rustc_span::{BytePos, ExpnData, ExpnId, ExpnKind, Span, SpanData, Symbol};
16use std::ops::ControlFlow;
17
18const FORMAT_MACRO_DIAG_ITEMS: &[Symbol] = &[
19    sym::assert_eq_macro,
20    sym::assert_macro,
21    sym::assert_ne_macro,
22    sym::debug_assert_eq_macro,
23    sym::debug_assert_macro,
24    sym::debug_assert_ne_macro,
25    sym::eprint_macro,
26    sym::eprintln_macro,
27    sym::format_args_macro,
28    sym::format_macro,
29    sym::print_macro,
30    sym::println_macro,
31    sym::std_panic_macro,
32    sym::todo_macro,
33    sym::unimplemented_macro,
34    sym::write_macro,
35    sym::writeln_macro,
36];
37
38/// Returns true if a given Macro `DefId` is a format macro (e.g. `println!`)
39pub fn is_format_macro(cx: &LateContext<'_>, macro_def_id: DefId) -> bool {
40    if let Some(name) = cx.tcx.get_diagnostic_name(macro_def_id) {
41        FORMAT_MACRO_DIAG_ITEMS.contains(&name)
42    } else {
43        // Allow users to tag any macro as being format!-like
44        // TODO: consider deleting FORMAT_MACRO_DIAG_ITEMS and using just this method
45        get_unique_builtin_attr(
46            cx.sess(),
47            #[allow(deprecated)]
48            cx.tcx.get_all_attrs(macro_def_id),
49            sym::format_args,
50        )
51        .is_some()
52    }
53}
54
55/// A macro call, like `vec![1, 2, 3]`.
56///
57/// Use `tcx.item_name(macro_call.def_id)` to get the macro name.
58/// Even better is to check if it is a diagnostic item.
59///
60/// This structure is similar to `ExpnData` but it precludes desugaring expansions.
61#[derive(Debug)]
62pub struct MacroCall {
63    /// Macro `DefId`
64    pub def_id: DefId,
65    /// Kind of macro
66    pub kind: MacroKind,
67    /// The expansion produced by the macro call
68    pub expn: ExpnId,
69    /// Span of the macro call site
70    pub span: Span,
71}
72
73impl MacroCall {
74    pub fn is_local(&self) -> bool {
75        span_is_local(self.span)
76    }
77}
78
79/// Returns an iterator of expansions that created the given span
80pub fn expn_backtrace(mut span: Span) -> impl Iterator<Item = (ExpnId, ExpnData)> {
81    std::iter::from_fn(move || {
82        let ctxt = span.ctxt();
83        if ctxt == SyntaxContext::root() {
84            return None;
85        }
86        let expn = ctxt.outer_expn();
87        let data = expn.expn_data();
88        span = data.call_site;
89        Some((expn, data))
90    })
91}
92
93/// Checks whether the span is from the root expansion or a locally defined macro
94pub fn span_is_local(span: Span) -> bool {
95    !span.from_expansion() || expn_is_local(span.ctxt().outer_expn())
96}
97
98/// Checks whether the expansion is the root expansion or a locally defined macro
99pub fn expn_is_local(expn: ExpnId) -> bool {
100    if expn == ExpnId::root() {
101        return true;
102    }
103    let data = expn.expn_data();
104    let backtrace = expn_backtrace(data.call_site);
105    std::iter::once((expn, data))
106        .chain(backtrace)
107        .find_map(|(_, data)| data.macro_def_id)
108        .is_none_or(DefId::is_local)
109}
110
111/// Returns an iterator of macro expansions that created the given span.
112/// Note that desugaring expansions are skipped.
113pub fn macro_backtrace(span: Span) -> impl Iterator<Item = MacroCall> {
114    expn_backtrace(span).filter_map(|(expn, data)| match data {
115        ExpnData {
116            kind: ExpnKind::Macro(kind, _),
117            macro_def_id: Some(def_id),
118            call_site: span,
119            ..
120        } => Some(MacroCall {
121            def_id,
122            kind,
123            expn,
124            span,
125        }),
126        _ => None,
127    })
128}
129
130/// If the macro backtrace of `span` has a macro call at the root expansion
131/// (i.e. not a nested macro call), returns `Some` with the `MacroCall`
132///
133/// If you only want to check whether the root macro has a specific name,
134/// consider using [`matching_root_macro_call`] instead.
135pub fn root_macro_call(span: Span) -> Option<MacroCall> {
136    macro_backtrace(span).last()
137}
138
139/// A combination of [`root_macro_call`] and
140/// [`is_diagnostic_item`](rustc_middle::ty::TyCtxt::is_diagnostic_item) that returns a `MacroCall`
141/// at the root expansion if only it matches the given name.
142pub fn matching_root_macro_call(cx: &LateContext<'_>, span: Span, name: Symbol) -> Option<MacroCall> {
143    root_macro_call(span).filter(|mc| cx.tcx.is_diagnostic_item(name, mc.def_id))
144}
145
146/// Like [`root_macro_call`], but only returns `Some` if `node` is the "first node"
147/// produced by the macro call, as in [`first_node_in_macro`].
148pub fn root_macro_call_first_node(cx: &LateContext<'_>, node: &impl HirNode) -> Option<MacroCall> {
149    if first_node_in_macro(cx, node) != Some(ExpnId::root()) {
150        return None;
151    }
152    root_macro_call(node.span())
153}
154
155/// Like [`macro_backtrace`], but only returns macro calls where `node` is the "first node" of the
156/// macro call, as in [`first_node_in_macro`].
157pub fn first_node_macro_backtrace(cx: &LateContext<'_>, node: &impl HirNode) -> impl Iterator<Item = MacroCall> {
158    let span = node.span();
159    first_node_in_macro(cx, node)
160        .into_iter()
161        .flat_map(move |expn| macro_backtrace(span).take_while(move |macro_call| macro_call.expn != expn))
162}
163
164/// If `node` is the "first node" in a macro expansion, returns `Some` with the `ExpnId` of the
165/// macro call site (i.e. the parent of the macro expansion).
166///
167/// This generally means that `node` is the outermost node of an entire macro expansion, but there
168/// are some caveats noted below. This is useful for finding macro calls while visiting the HIR
169/// without processing the macro call at every node within its expansion.
170///
171/// If you already have immediate access to the parent node, it is simpler to
172/// just check the context of that span directly (e.g. `parent.span.from_expansion()`).
173///
174/// If a macro call is in statement position, it expands to one or more statements.
175/// In that case, each statement *and* their immediate descendants will all yield `Some`
176/// with the `ExpnId` of the containing block.
177///
178/// A node may be the "first node" of multiple macro calls in a macro backtrace.
179/// The expansion of the outermost macro call site is returned in such cases.
180pub fn first_node_in_macro(cx: &LateContext<'_>, node: &impl HirNode) -> Option<ExpnId> {
181    // get the macro expansion or return `None` if not found
182    // `macro_backtrace` importantly ignores desugaring expansions
183    let expn = macro_backtrace(node.span()).next()?.expn;
184
185    // get the parent node, possibly skipping over a statement
186    // if the parent is not found, it is sensible to return `Some(root)`
187    let mut parent_iter = cx.tcx.hir_parent_iter(node.hir_id());
188    let (parent_id, _) = match parent_iter.next() {
189        None => return Some(ExpnId::root()),
190        Some((_, Node::Stmt(_))) => match parent_iter.next() {
191            None => return Some(ExpnId::root()),
192            Some(next) => next,
193        },
194        Some(next) => next,
195    };
196
197    // get the macro expansion of the parent node
198    let parent_span = cx.tcx.hir_span(parent_id);
199    let Some(parent_macro_call) = macro_backtrace(parent_span).next() else {
200        // the parent node is not in a macro
201        return Some(ExpnId::root());
202    };
203
204    if parent_macro_call.expn.is_descendant_of(expn) {
205        // `node` is input to a macro call
206        return None;
207    }
208
209    Some(parent_macro_call.expn)
210}
211
212/* Specific Macro Utils */
213
214/// Is `def_id` of `std::panic`, `core::panic` or any inner implementation macros
215pub fn is_panic(cx: &LateContext<'_>, def_id: DefId) -> bool {
216    let Some(name) = cx.tcx.get_diagnostic_name(def_id) else {
217        return false;
218    };
219    matches!(
220        name,
221        sym::core_panic_macro
222            | sym::std_panic_macro
223            | sym::core_panic_2015_macro
224            | sym::std_panic_2015_macro
225            | sym::core_panic_2021_macro
226    )
227}
228
229/// Is `def_id` of `assert!` or `debug_assert!`
230pub fn is_assert_macro(cx: &LateContext<'_>, def_id: DefId) -> bool {
231    let Some(name) = cx.tcx.get_diagnostic_name(def_id) else {
232        return false;
233    };
234    matches!(name, sym::assert_macro | sym::debug_assert_macro)
235}
236
237/// A call to a function in [`std::rt`] or [`core::panicking`] that results in a panic, typically
238/// part of a `panic!()` expansion (often wrapped in a block) but may be called directly by other
239/// macros such as `assert`.
240#[derive(Debug)]
241pub enum PanicCall<'a> {
242    // The default message - `panic!()`, `assert!(true)`, etc.
243    DefaultMessage,
244    /// A string literal or any `&str` in edition 2015/2018 - `panic!("message")` or
245    /// `panic!(message)`.
246    ///
247    /// In edition 2021+ `panic!("message")` will be a [`PanicCall::Format`] and `panic!(message)` a
248    /// compile error.
249    Str2015(&'a Expr<'a>),
250    /// A single argument that implements `Display` - `panic!("{}", object)`.
251    ///
252    /// `panic!("{object}")` will still be a [`PanicCall::Format`].
253    Display(&'a Expr<'a>),
254    /// Anything else - `panic!("error {}: {}", a, b)`, `panic!("on edition 2021+")`.
255    ///
256    /// See [`FormatArgsStorage::get`] to examine the contents of the formatting.
257    Format(&'a Expr<'a>),
258}
259
260impl<'a> PanicCall<'a> {
261    pub fn parse(expr: &'a Expr<'a>) -> Option<Self> {
262        let ExprKind::Call(callee, args) = &expr.kind else {
263            return None;
264        };
265        let ExprKind::Path(QPath::Resolved(_, path)) = &callee.kind else {
266            return None;
267        };
268        let name = path.segments.last().unwrap().ident.name;
269
270        let [arg, rest @ ..] = args else {
271            return None;
272        };
273        let result = match name {
274            sym::panic | sym::begin_panic | sym::panic_str_2015 => {
275                if arg.span.eq_ctxt(expr.span) || arg.span.is_dummy() {
276                    Self::DefaultMessage
277                } else {
278                    Self::Str2015(arg)
279                }
280            },
281            sym::panic_display => {
282                let ExprKind::AddrOf(_, _, e) = &arg.kind else {
283                    return None;
284                };
285                Self::Display(e)
286            },
287            sym::panic_fmt => Self::Format(arg),
288            // Since Rust 1.52, `assert_{eq,ne}` macros expand to use:
289            // `core::panicking::assert_failed(.., left_val, right_val, None | Some(format_args!(..)));`
290            sym::assert_failed => {
291                // It should have 4 arguments in total (we already matched with the first argument,
292                // so we're just checking for 3)
293                if rest.len() != 3 {
294                    return None;
295                }
296                // `msg_arg` is either `None` (no custom message) or `Some(format_args!(..))` (custom message)
297                let msg_arg = &rest[2];
298                match msg_arg.kind {
299                    ExprKind::Call(_, [fmt_arg]) => Self::Format(fmt_arg),
300                    _ => Self::DefaultMessage,
301                }
302            },
303            _ => return None,
304        };
305        Some(result)
306    }
307
308    pub fn is_default_message(&self) -> bool {
309        matches!(self, Self::DefaultMessage)
310    }
311}
312
313/// Finds the arguments of an `assert!` or `debug_assert!` macro call within the macro expansion
314pub fn find_assert_args<'a>(
315    cx: &LateContext<'_>,
316    expr: &'a Expr<'a>,
317    expn: ExpnId,
318) -> Option<(&'a Expr<'a>, PanicCall<'a>)> {
319    find_assert_args_inner(cx, expr, expn).map(|([e], p)| (e, p))
320}
321
322/// Finds the arguments of an `assert_eq!` or `debug_assert_eq!` macro call within the macro
323/// expansion
324pub fn find_assert_eq_args<'a>(
325    cx: &LateContext<'_>,
326    expr: &'a Expr<'a>,
327    expn: ExpnId,
328) -> Option<(&'a Expr<'a>, &'a Expr<'a>, PanicCall<'a>)> {
329    find_assert_args_inner(cx, expr, expn).map(|([a, b], p)| (a, b, p))
330}
331
332fn find_assert_args_inner<'a, const N: usize>(
333    cx: &LateContext<'_>,
334    expr: &'a Expr<'a>,
335    expn: ExpnId,
336) -> Option<([&'a Expr<'a>; N], PanicCall<'a>)> {
337    let macro_id = expn.expn_data().macro_def_id?;
338    let (expr, expn) = match cx.tcx.item_name(macro_id).as_str().strip_prefix("debug_") {
339        None => (expr, expn),
340        Some(inner_name) => find_assert_within_debug_assert(cx, expr, expn, Symbol::intern(inner_name))?,
341    };
342    let mut args = ArrayVec::new();
343    let panic_expn = for_each_expr_without_closures(expr, |e| {
344        if args.is_full() {
345            match PanicCall::parse(e) {
346                Some(expn) => ControlFlow::Break(expn),
347                None => ControlFlow::Continue(Descend::Yes),
348            }
349        } else if is_assert_arg(cx, e, expn) {
350            args.push(e);
351            ControlFlow::Continue(Descend::No)
352        } else {
353            ControlFlow::Continue(Descend::Yes)
354        }
355    });
356    let args = args.into_inner().ok()?;
357    Some((args, panic_expn?))
358}
359
360fn find_assert_within_debug_assert<'a>(
361    cx: &LateContext<'_>,
362    expr: &'a Expr<'a>,
363    expn: ExpnId,
364    assert_name: Symbol,
365) -> Option<(&'a Expr<'a>, ExpnId)> {
366    for_each_expr_without_closures(expr, |e| {
367        if !e.span.from_expansion() {
368            return ControlFlow::Continue(Descend::No);
369        }
370        let e_expn = e.span.ctxt().outer_expn();
371        if e_expn == expn {
372            ControlFlow::Continue(Descend::Yes)
373        } else if e_expn.expn_data().macro_def_id.map(|id| cx.tcx.item_name(id)) == Some(assert_name) {
374            ControlFlow::Break((e, e_expn))
375        } else {
376            ControlFlow::Continue(Descend::No)
377        }
378    })
379}
380
381fn is_assert_arg(cx: &LateContext<'_>, expr: &Expr<'_>, assert_expn: ExpnId) -> bool {
382    if !expr.span.from_expansion() {
383        return true;
384    }
385    let result = macro_backtrace(expr.span).try_for_each(|macro_call| {
386        if macro_call.expn == assert_expn {
387            ControlFlow::Break(false)
388        } else {
389            match cx.tcx.item_name(macro_call.def_id) {
390                // `cfg!(debug_assertions)` in `debug_assert!`
391                sym::cfg => ControlFlow::Continue(()),
392                // assert!(other_macro!(..))
393                _ => ControlFlow::Break(true),
394            }
395        }
396    });
397    match result {
398        ControlFlow::Break(is_assert_arg) => is_assert_arg,
399        ControlFlow::Continue(()) => true,
400    }
401}
402
403/// Stores AST [`FormatArgs`] nodes for use in late lint passes, as they are in a desugared form in
404/// the HIR
405#[derive(Default, Clone)]
406pub struct FormatArgsStorage(Arc<OnceLock<FxHashMap<Span, FormatArgs>>>);
407
408impl FormatArgsStorage {
409    /// Returns an AST [`FormatArgs`] node if a `format_args` expansion is found as a descendant of
410    /// `expn_id`
411    ///
412    /// See also [`find_format_arg_expr`]
413    pub fn get(&self, cx: &LateContext<'_>, start: &Expr<'_>, expn_id: ExpnId) -> Option<&FormatArgs> {
414        let format_args_expr = for_each_expr_without_closures(start, |expr| {
415            let ctxt = expr.span.ctxt();
416            if ctxt.outer_expn().is_descendant_of(expn_id) {
417                if macro_backtrace(expr.span)
418                    .map(|macro_call| cx.tcx.item_name(macro_call.def_id))
419                    .any(|name| matches!(name, sym::const_format_args | sym::format_args | sym::format_args_nl))
420                {
421                    ControlFlow::Break(expr)
422                } else {
423                    ControlFlow::Continue(Descend::Yes)
424                }
425            } else {
426                ControlFlow::Continue(Descend::No)
427            }
428        })?;
429
430        debug_assert!(self.0.get().is_some(), "`FormatArgsStorage` not yet populated");
431
432        self.0.get()?.get(&format_args_expr.span.with_parent(None))
433    }
434
435    /// Should only be called by `FormatArgsCollector`
436    pub fn set(&self, format_args: FxHashMap<Span, FormatArgs>) {
437        self.0
438            .set(format_args)
439            .expect("`FormatArgsStorage::set` should only be called once");
440    }
441}
442
443/// Attempt to find the [`rustc_hir::Expr`] that corresponds to the [`FormatArgument`]'s value
444pub fn find_format_arg_expr<'hir>(start: &'hir Expr<'hir>, target: &FormatArgument) -> Option<&'hir Expr<'hir>> {
445    let SpanData {
446        lo,
447        hi,
448        ctxt,
449        parent: _,
450    } = target.expr.span.data();
451
452    for_each_expr_without_closures(start, |expr| {
453        // When incremental compilation is enabled spans gain a parent during AST to HIR lowering,
454        // since we're comparing an AST span to a HIR one we need to ignore the parent field
455        let data = expr.span.data();
456        if data.lo == lo && data.hi == hi && data.ctxt == ctxt {
457            ControlFlow::Break(expr)
458        } else {
459            ControlFlow::Continue(())
460        }
461    })
462}
463
464/// Span of the `:` and format specifiers
465///
466/// ```ignore
467/// format!("{:.}"), format!("{foo:.}")
468///           ^^                  ^^
469/// ```
470pub fn format_placeholder_format_span(placeholder: &FormatPlaceholder) -> Option<Span> {
471    let base = placeholder.span?.data();
472
473    // `base.hi` is `{...}|`, subtract 1 byte (the length of '}') so that it points before the closing
474    // brace `{...|}`
475    Some(Span::new(
476        placeholder.argument.span?.hi(),
477        base.hi - BytePos(1),
478        base.ctxt,
479        base.parent,
480    ))
481}
482
483/// Span covering the format string and values
484///
485/// ```ignore
486/// format("{}.{}", 10, 11)
487/// //     ^^^^^^^^^^^^^^^
488/// ```
489pub fn format_args_inputs_span(format_args: &FormatArgs) -> Span {
490    match format_args.arguments.explicit_args() {
491        [] => format_args.span,
492        [.., last] => format_args
493            .span
494            .to(hygiene::walk_chain(last.expr.span, format_args.span.ctxt())),
495    }
496}
497
498/// Returns the [`Span`] of the value at `index` extended to the previous comma, e.g. for the value
499/// `10`
500///
501/// ```ignore
502/// format("{}.{}", 10, 11)
503/// //            ^^^^
504/// ```
505pub fn format_arg_removal_span(format_args: &FormatArgs, index: usize) -> Option<Span> {
506    let ctxt = format_args.span.ctxt();
507
508    let current = hygiene::walk_chain(format_args.arguments.by_index(index)?.expr.span, ctxt);
509
510    let prev = if index == 0 {
511        format_args.span
512    } else {
513        hygiene::walk_chain(format_args.arguments.by_index(index - 1)?.expr.span, ctxt)
514    };
515
516    Some(current.with_lo(prev.hi()))
517}
518
519/// Where a format parameter is being used in the format string
520#[derive(Debug, Copy, Clone, PartialEq, Eq)]
521pub enum FormatParamUsage {
522    /// Appears as an argument, e.g. `format!("{}", foo)`
523    Argument,
524    /// Appears as a width, e.g. `format!("{:width$}", foo, width = 1)`
525    Width,
526    /// Appears as a precision, e.g. `format!("{:.precision$}", foo, precision = 1)`
527    Precision,
528}
529
530/// A node with a `HirId` and a `Span`
531pub trait HirNode {
532    fn hir_id(&self) -> HirId;
533    fn span(&self) -> Span;
534}
535
536macro_rules! impl_hir_node {
537    ($($t:ident),*) => {
538        $(impl HirNode for hir::$t<'_> {
539            fn hir_id(&self) -> HirId {
540                self.hir_id
541            }
542            fn span(&self) -> Span {
543                self.span
544            }
545        })*
546    };
547}
548
549impl_hir_node!(Expr, Pat);
550
551impl HirNode for hir::Item<'_> {
552    fn hir_id(&self) -> HirId {
553        self.hir_id()
554    }
555
556    fn span(&self) -> Span {
557        self.span
558    }
559}