1 #![allow(clippy::similar_names)] // `expr` and `expn`
3 use crate::visitors::expr_visitor_no_bodies;
5 use arrayvec::ArrayVec;
6 use if_chain::if_chain;
7 use rustc_ast::ast::LitKind;
8 use rustc_hir::intravisit::Visitor;
9 use rustc_hir::{self as hir, Expr, ExprKind, HirId, Node, QPath};
10 use rustc_lint::LateContext;
11 use rustc_span::def_id::DefId;
12 use rustc_span::hygiene::{self, MacroKind, SyntaxContext};
13 use rustc_span::{sym, ExpnData, ExpnId, ExpnKind, Span, Symbol};
14 use std::ops::ControlFlow;
16 const FORMAT_MACRO_DIAG_ITEMS: &[Symbol] = &[
20 sym::debug_assert_eq_macro,
21 sym::debug_assert_macro,
22 sym::debug_assert_ne_macro,
25 sym::format_args_macro,
34 /// Returns true if a given Macro `DefId` is a format macro (e.g. `println!`)
35 pub fn is_format_macro(cx: &LateContext<'_>, macro_def_id: DefId) -> bool {
36 if let Some(name) = cx.tcx.get_diagnostic_name(macro_def_id) {
37 FORMAT_MACRO_DIAG_ITEMS.contains(&name)
43 /// A macro call, like `vec![1, 2, 3]`.
45 /// Use `tcx.item_name(macro_call.def_id)` to get the macro name.
46 /// Even better is to check if it is a diagnostic item.
48 /// This structure is similar to `ExpnData` but it precludes desugaring expansions.
50 pub struct MacroCall {
55 /// The expansion produced by the macro call
57 /// Span of the macro call site
62 pub fn is_local(&self) -> bool {
63 span_is_local(self.span)
67 /// Returns an iterator of expansions that created the given span
68 pub fn expn_backtrace(mut span: Span) -> impl Iterator<Item = (ExpnId, ExpnData)> {
69 std::iter::from_fn(move || {
70 let ctxt = span.ctxt();
71 if ctxt == SyntaxContext::root() {
74 let expn = ctxt.outer_expn();
75 let data = expn.expn_data();
76 span = data.call_site;
81 /// Checks whether the span is from the root expansion or a locally defined macro
82 pub fn span_is_local(span: Span) -> bool {
83 !span.from_expansion() || expn_is_local(span.ctxt().outer_expn())
86 /// Checks whether the expansion is the root expansion or a locally defined macro
87 pub fn expn_is_local(expn: ExpnId) -> bool {
88 if expn == ExpnId::root() {
91 let data = expn.expn_data();
92 let backtrace = expn_backtrace(data.call_site);
93 std::iter::once((expn, data))
95 .find_map(|(_, data)| data.macro_def_id)
96 .map_or(true, DefId::is_local)
99 /// Returns an iterator of macro expansions that created the given span.
100 /// Note that desugaring expansions are skipped.
101 pub fn macro_backtrace(span: Span) -> impl Iterator<Item = MacroCall> {
102 expn_backtrace(span).filter_map(|(expn, data)| match data {
104 kind: ExpnKind::Macro(kind, _),
105 macro_def_id: Some(def_id),
108 } => Some(MacroCall {
118 /// If the macro backtrace of `span` has a macro call at the root expansion
119 /// (i.e. not a nested macro call), returns `Some` with the `MacroCall`
120 pub fn root_macro_call(span: Span) -> Option<MacroCall> {
121 macro_backtrace(span).last()
124 /// Like [`root_macro_call`], but only returns `Some` if `node` is the "first node"
125 /// produced by the macro call, as in [`first_node_in_macro`].
126 pub fn root_macro_call_first_node(cx: &LateContext<'_>, node: &impl HirNode) -> Option<MacroCall> {
127 if first_node_in_macro(cx, node) != Some(ExpnId::root()) {
130 root_macro_call(node.span())
133 /// Like [`macro_backtrace`], but only returns macro calls where `node` is the "first node" of the
134 /// macro call, as in [`first_node_in_macro`].
135 pub fn first_node_macro_backtrace(cx: &LateContext<'_>, node: &impl HirNode) -> impl Iterator<Item = MacroCall> {
136 let span = node.span();
137 first_node_in_macro(cx, node)
139 .flat_map(move |expn| macro_backtrace(span).take_while(move |macro_call| macro_call.expn != expn))
142 /// If `node` is the "first node" in a macro expansion, returns `Some` with the `ExpnId` of the
143 /// macro call site (i.e. the parent of the macro expansion). This generally means that `node`
144 /// is the outermost node of an entire macro expansion, but there are some caveats noted below.
145 /// This is useful for finding macro calls while visiting the HIR without processing the macro call
146 /// at every node within its expansion.
148 /// If you already have immediate access to the parent node, it is simpler to
149 /// just check the context of that span directly (e.g. `parent.span.from_expansion()`).
151 /// If a macro call is in statement position, it expands to one or more statements.
152 /// In that case, each statement *and* their immediate descendants will all yield `Some`
153 /// with the `ExpnId` of the containing block.
155 /// A node may be the "first node" of multiple macro calls in a macro backtrace.
156 /// The expansion of the outermost macro call site is returned in such cases.
157 pub fn first_node_in_macro(cx: &LateContext<'_>, node: &impl HirNode) -> Option<ExpnId> {
158 // get the macro expansion or return `None` if not found
159 // `macro_backtrace` importantly ignores desugaring expansions
160 let expn = macro_backtrace(node.span()).next()?.expn;
162 // get the parent node, possibly skipping over a statement
163 // if the parent is not found, it is sensible to return `Some(root)`
164 let hir = cx.tcx.hir();
165 let mut parent_iter = hir.parent_iter(node.hir_id());
166 let (parent_id, _) = match parent_iter.next() {
167 None => return Some(ExpnId::root()),
168 Some((_, Node::Stmt(_))) => match parent_iter.next() {
169 None => return Some(ExpnId::root()),
175 // get the macro expansion of the parent node
176 let parent_span = hir.span(parent_id);
177 let Some(parent_macro_call) = macro_backtrace(parent_span).next() else {
178 // the parent node is not in a macro
179 return Some(ExpnId::root());
182 if parent_macro_call.expn.is_descendant_of(expn) {
183 // `node` is input to a macro call
187 Some(parent_macro_call.expn)
190 /* Specific Macro Utils */
192 /// Is `def_id` of `std::panic`, `core::panic` or any inner implementation macros
193 pub fn is_panic(cx: &LateContext<'_>, def_id: DefId) -> bool {
194 let Some(name) = cx.tcx.get_diagnostic_name(def_id) else { return false };
199 | "core_panic_2015_macro"
200 | "std_panic_2015_macro"
201 | "core_panic_2021_macro"
205 pub enum PanicExpn<'a> {
206 /// No arguments - `panic!()`
208 /// A string literal or any `&str` - `panic!("message")` or `panic!(message)`
210 /// A single argument that implements `Display` - `panic!("{}", object)`
211 Display(&'a Expr<'a>),
212 /// Anything else - `panic!("error {}: {}", a, b)`
213 Format(FormatArgsExpn<'a>),
216 impl<'a> PanicExpn<'a> {
217 pub fn parse(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Self> {
218 if !macro_backtrace(expr.span).any(|macro_call| is_panic(cx, macro_call.def_id)) {
221 let ExprKind::Call(callee, [arg]) = &expr.kind else { return None };
222 let ExprKind::Path(QPath::Resolved(_, path)) = &callee.kind else { return None };
223 let result = match path.segments.last().unwrap().ident.as_str() {
224 "panic" if arg.span.ctxt() == expr.span.ctxt() => Self::Empty,
225 "panic" | "panic_str" => Self::Str(arg),
227 let ExprKind::AddrOf(_, _, e) = &arg.kind else { return None };
230 "panic_fmt" => Self::Format(FormatArgsExpn::parse(cx, arg)?),
237 /// Finds the arguments of an `assert!` or `debug_assert!` macro call within the macro expansion
238 pub fn find_assert_args<'a>(
239 cx: &LateContext<'_>,
242 ) -> Option<(&'a Expr<'a>, PanicExpn<'a>)> {
243 find_assert_args_inner(cx, expr, expn).map(|([e], p)| (e, p))
246 /// Finds the arguments of an `assert_eq!` or `debug_assert_eq!` macro call within the macro
248 pub fn find_assert_eq_args<'a>(
249 cx: &LateContext<'_>,
252 ) -> Option<(&'a Expr<'a>, &'a Expr<'a>, PanicExpn<'a>)> {
253 find_assert_args_inner(cx, expr, expn).map(|([a, b], p)| (a, b, p))
256 fn find_assert_args_inner<'a, const N: usize>(
257 cx: &LateContext<'_>,
260 ) -> Option<([&'a Expr<'a>; N], PanicExpn<'a>)> {
261 let macro_id = expn.expn_data().macro_def_id?;
262 let (expr, expn) = match cx.tcx.item_name(macro_id).as_str().strip_prefix("debug_") {
263 None => (expr, expn),
264 Some(inner_name) => find_assert_within_debug_assert(cx, expr, expn, Symbol::intern(inner_name))?,
266 let mut args = ArrayVec::new();
267 let mut panic_expn = None;
268 expr_visitor_no_bodies(|e| {
270 if panic_expn.is_none() && e.span.ctxt() != expr.span.ctxt() {
271 panic_expn = PanicExpn::parse(cx, e);
274 } else if is_assert_arg(cx, e, expn) {
282 let args = args.into_inner().ok()?;
283 // if no `panic!(..)` is found, use `PanicExpn::Empty`
284 // to indicate that the default assertion message is used
285 let panic_expn = panic_expn.unwrap_or(PanicExpn::Empty);
286 Some((args, panic_expn))
289 fn find_assert_within_debug_assert<'a>(
290 cx: &LateContext<'_>,
294 ) -> Option<(&'a Expr<'a>, ExpnId)> {
295 let mut found = None;
296 expr_visitor_no_bodies(|e| {
297 if found.is_some() || !e.span.from_expansion() {
300 let e_expn = e.span.ctxt().outer_expn();
304 if e_expn.expn_data().macro_def_id.map(|id| cx.tcx.item_name(id)) == Some(assert_name) {
305 found = Some((e, e_expn));
313 fn is_assert_arg(cx: &LateContext<'_>, expr: &Expr<'_>, assert_expn: ExpnId) -> bool {
314 if !expr.span.from_expansion() {
317 let result = macro_backtrace(expr.span).try_for_each(|macro_call| {
318 if macro_call.expn == assert_expn {
319 ControlFlow::Break(false)
321 match cx.tcx.item_name(macro_call.def_id) {
322 // `cfg!(debug_assertions)` in `debug_assert!`
323 sym::cfg => ControlFlow::CONTINUE,
324 // assert!(other_macro!(..))
325 _ => ControlFlow::Break(true),
330 ControlFlow::Break(is_assert_arg) => is_assert_arg,
331 ControlFlow::Continue(()) => true,
335 /// A parsed `format_args!` expansion
337 pub struct FormatArgsExpn<'tcx> {
338 /// Span of the first argument, the format string
339 pub format_string_span: Span,
340 /// The format string split by formatted args like `{..}`
341 pub format_string_parts: Vec<Symbol>,
342 /// Values passed after the format string
343 pub value_args: Vec<&'tcx Expr<'tcx>>,
344 /// Each element is a `value_args` index and a formatting trait (e.g. `sym::Debug`)
345 pub formatters: Vec<(usize, Symbol)>,
346 /// List of `fmt::v1::Argument { .. }` expressions. If this is empty,
347 /// then `formatters` represents the format args (`{..}`).
348 /// If this is non-empty, it represents the format args, and the `position`
349 /// parameters within the struct expressions are indexes of `formatters`.
350 pub specs: Vec<&'tcx Expr<'tcx>>,
353 impl<'tcx> FormatArgsExpn<'tcx> {
354 /// Parses an expanded `format_args!` or `format_args_nl!` invocation
355 pub fn parse(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<Self> {
356 macro_backtrace(expr.span).find(|macro_call| {
358 cx.tcx.item_name(macro_call.def_id),
359 sym::const_format_args | sym::format_args | sym::format_args_nl
362 let mut format_string_span: Option<Span> = None;
363 let mut format_string_parts: Vec<Symbol> = Vec::new();
364 let mut value_args: Vec<&Expr<'_>> = Vec::new();
365 let mut formatters: Vec<(usize, Symbol)> = Vec::new();
366 let mut specs: Vec<&Expr<'_>> = Vec::new();
367 expr_visitor_no_bodies(|e| {
368 // if we're still inside of the macro definition...
369 if e.span.ctxt() == expr.span.ctxt() {
370 // ArgumnetV1::new_<format_trait>(<value>)
372 if let ExprKind::Call(callee, [val]) = e.kind;
373 if let ExprKind::Path(QPath::TypeRelative(ty, seg)) = callee.kind;
374 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind;
375 if path.segments.last().unwrap().ident.name == sym::ArgumentV1;
376 if seg.ident.name.as_str().starts_with("new_");
378 let val_idx = if_chain! {
379 if val.span.ctxt() == expr.span.ctxt();
380 if let ExprKind::Field(_, field) = val.kind;
381 if let Ok(idx) = field.name.as_str().parse();
386 // assume the value expression is passed directly
390 let fmt_trait = match seg.ident.name.as_str() {
391 "new_display" => "Display",
392 "new_debug" => "Debug",
393 "new_lower_exp" => "LowerExp",
394 "new_upper_exp" => "UpperExp",
395 "new_octal" => "Octal",
396 "new_pointer" => "Pointer",
397 "new_binary" => "Binary",
398 "new_lower_hex" => "LowerHex",
399 "new_upper_hex" => "UpperHex",
402 formatters.push((val_idx, Symbol::intern(fmt_trait)));
405 if let ExprKind::Struct(QPath::Resolved(_, path), ..) = e.kind {
406 if path.segments.last().unwrap().ident.name == sym::Argument {
410 // walk through the macro expansion
413 // assume that the first expr with a differing context represents
414 // (and has the span of) the format string
415 if format_string_span.is_none() {
416 format_string_span = Some(e.span);
418 // walk the expr and collect string literals which are format string parts
419 expr_visitor_no_bodies(|e| {
420 if e.span.ctxt() != span.ctxt() {
421 // defensive check, probably doesn't happen
424 if let ExprKind::Lit(lit) = &e.kind {
425 if let LitKind::Str(symbol, _s) = lit.node {
426 format_string_parts.push(symbol);
433 // assume that any further exprs with a differing context are value args
436 // don't walk anything not from the macro expansion (e.a. inputs)
440 Some(FormatArgsExpn {
441 format_string_span: format_string_span?,
449 /// Finds a nested call to `format_args!` within a `format!`-like macro call
450 pub fn find_nested(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, expn_id: ExpnId) -> Option<Self> {
451 let mut format_args = None;
452 expr_visitor_no_bodies(|e| {
453 if format_args.is_some() {
456 let e_ctxt = e.span.ctxt();
457 if e_ctxt == expr.span.ctxt() {
460 if e_ctxt.outer_expn().is_descendant_of(expn_id) {
461 format_args = FormatArgsExpn::parse(cx, e);
469 /// Returns a vector of `FormatArgsArg`.
470 pub fn args(&self) -> Option<Vec<FormatArgsArg<'tcx>>> {
471 if self.specs.is_empty() {
472 let args = std::iter::zip(&self.value_args, &self.formatters)
473 .map(|(value, &(_, format_trait))| FormatArgsArg {
485 // struct `core::fmt::rt::v1::Argument`
486 if let ExprKind::Struct(_, fields, _) = spec.kind;
487 if let Some(position_field) = fields.iter().find(|f| f.ident.name == sym::position);
488 if let ExprKind::Lit(lit) = &position_field.expr.kind;
489 if let LitKind::Int(position, _) = lit.node;
490 if let Ok(i) = usize::try_from(position);
491 if let Some(&(j, format_trait)) = self.formatters.get(i);
494 value: self.value_args[j],
506 /// Source callsite span of all inputs
507 pub fn inputs_span(&self) -> Span {
508 match *self.value_args {
509 [] => self.format_string_span,
512 .to(hygiene::walk_chain(last.span, self.format_string_span.ctxt())),
517 /// Type representing a `FormatArgsExpn`'s format arguments
518 pub struct FormatArgsArg<'tcx> {
519 /// An element of `value_args` according to `position`
520 pub value: &'tcx Expr<'tcx>,
521 /// An element of `args` according to `position`
522 pub format_trait: Symbol,
523 /// An element of `specs`
524 pub spec: Option<&'tcx Expr<'tcx>>,
527 impl<'tcx> FormatArgsArg<'tcx> {
528 /// Returns true if any formatting parameters are used that would have an effect on strings,
529 /// like `{:+2}` instead of just `{}`.
530 pub fn has_string_formatting(&self) -> bool {
531 self.spec.map_or(false, |spec| {
532 // `!` because these conditions check that `self` is unformatted.
534 // struct `core::fmt::rt::v1::Argument`
535 if let ExprKind::Struct(_, fields, _) = spec.kind;
536 if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym::format);
537 // struct `core::fmt::rt::v1::FormatSpec`
538 if let ExprKind::Struct(_, subfields, _) = format_field.expr.kind;
539 if subfields.iter().all(|field| match field.ident.name {
540 sym::precision | sym::width => match field.expr.kind {
541 ExprKind::Path(QPath::Resolved(_, path)) => {
542 path.segments.last().unwrap().ident.name == sym::Implied
548 then { true } else { false }
554 /// A node with a `HirId` and a `Span`
556 fn hir_id(&self) -> HirId;
557 fn span(&self) -> Span;
560 macro_rules! impl_hir_node {
562 $(impl HirNode for hir::$t<'_> {
563 fn hir_id(&self) -> HirId {
566 fn span(&self) -> Span {
573 impl_hir_node!(Expr, Pat);
575 impl HirNode for hir::Item<'_> {
576 fn hir_id(&self) -> HirId {
580 fn span(&self) -> Span {