]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/macros.rs
Lower the assume intrinsic to a MIR statement
[rust.git] / clippy_utils / src / macros.rs
1 #![allow(clippy::similar_names)] // `expr` and `expn`
2
3 use crate::is_path_diagnostic_item;
4 use crate::source::snippet_opt;
5 use crate::visitors::expr_visitor_no_bodies;
6
7 use arrayvec::ArrayVec;
8 use itertools::{izip, Either, Itertools};
9 use rustc_ast::ast::LitKind;
10 use rustc_hir::intravisit::Visitor;
11 use rustc_hir::{self as hir, Expr, ExprKind, HirId, Node, QPath};
12 use rustc_lexer::unescape::unescape_literal;
13 use rustc_lexer::{tokenize, unescape, LiteralKind, TokenKind};
14 use rustc_lint::LateContext;
15 use rustc_parse_format::{self as rpf, Alignment};
16 use rustc_span::def_id::DefId;
17 use rustc_span::hygiene::{self, MacroKind, SyntaxContext};
18 use rustc_span::{sym, BytePos, ExpnData, ExpnId, ExpnKind, Pos, Span, SpanData, Symbol};
19 use std::ops::ControlFlow;
20
21 const FORMAT_MACRO_DIAG_ITEMS: &[Symbol] = &[
22     sym::assert_eq_macro,
23     sym::assert_macro,
24     sym::assert_ne_macro,
25     sym::debug_assert_eq_macro,
26     sym::debug_assert_macro,
27     sym::debug_assert_ne_macro,
28     sym::eprint_macro,
29     sym::eprintln_macro,
30     sym::format_args_macro,
31     sym::format_macro,
32     sym::print_macro,
33     sym::println_macro,
34     sym::std_panic_macro,
35     sym::write_macro,
36     sym::writeln_macro,
37 ];
38
39 /// Returns true if a given Macro `DefId` is a format macro (e.g. `println!`)
40 pub fn is_format_macro(cx: &LateContext<'_>, macro_def_id: DefId) -> bool {
41     if let Some(name) = cx.tcx.get_diagnostic_name(macro_def_id) {
42         FORMAT_MACRO_DIAG_ITEMS.contains(&name)
43     } else {
44         false
45     }
46 }
47
48 /// A macro call, like `vec![1, 2, 3]`.
49 ///
50 /// Use `tcx.item_name(macro_call.def_id)` to get the macro name.
51 /// Even better is to check if it is a diagnostic item.
52 ///
53 /// This structure is similar to `ExpnData` but it precludes desugaring expansions.
54 #[derive(Debug)]
55 pub struct MacroCall {
56     /// Macro `DefId`
57     pub def_id: DefId,
58     /// Kind of macro
59     pub kind: MacroKind,
60     /// The expansion produced by the macro call
61     pub expn: ExpnId,
62     /// Span of the macro call site
63     pub span: Span,
64 }
65
66 impl MacroCall {
67     pub fn is_local(&self) -> bool {
68         span_is_local(self.span)
69     }
70 }
71
72 /// Returns an iterator of expansions that created the given span
73 pub fn expn_backtrace(mut span: Span) -> impl Iterator<Item = (ExpnId, ExpnData)> {
74     std::iter::from_fn(move || {
75         let ctxt = span.ctxt();
76         if ctxt == SyntaxContext::root() {
77             return None;
78         }
79         let expn = ctxt.outer_expn();
80         let data = expn.expn_data();
81         span = data.call_site;
82         Some((expn, data))
83     })
84 }
85
86 /// Checks whether the span is from the root expansion or a locally defined macro
87 pub fn span_is_local(span: Span) -> bool {
88     !span.from_expansion() || expn_is_local(span.ctxt().outer_expn())
89 }
90
91 /// Checks whether the expansion is the root expansion or a locally defined macro
92 pub fn expn_is_local(expn: ExpnId) -> bool {
93     if expn == ExpnId::root() {
94         return true;
95     }
96     let data = expn.expn_data();
97     let backtrace = expn_backtrace(data.call_site);
98     std::iter::once((expn, data))
99         .chain(backtrace)
100         .find_map(|(_, data)| data.macro_def_id)
101         .map_or(true, DefId::is_local)
102 }
103
104 /// Returns an iterator of macro expansions that created the given span.
105 /// Note that desugaring expansions are skipped.
106 pub fn macro_backtrace(span: Span) -> impl Iterator<Item = MacroCall> {
107     expn_backtrace(span).filter_map(|(expn, data)| match data {
108         ExpnData {
109             kind: ExpnKind::Macro(kind, _),
110             macro_def_id: Some(def_id),
111             call_site: span,
112             ..
113         } => Some(MacroCall {
114             def_id,
115             kind,
116             expn,
117             span,
118         }),
119         _ => None,
120     })
121 }
122
123 /// If the macro backtrace of `span` has a macro call at the root expansion
124 /// (i.e. not a nested macro call), returns `Some` with the `MacroCall`
125 pub fn root_macro_call(span: Span) -> Option<MacroCall> {
126     macro_backtrace(span).last()
127 }
128
129 /// Like [`root_macro_call`], but only returns `Some` if `node` is the "first node"
130 /// produced by the macro call, as in [`first_node_in_macro`].
131 pub fn root_macro_call_first_node(cx: &LateContext<'_>, node: &impl HirNode) -> Option<MacroCall> {
132     if first_node_in_macro(cx, node) != Some(ExpnId::root()) {
133         return None;
134     }
135     root_macro_call(node.span())
136 }
137
138 /// Like [`macro_backtrace`], but only returns macro calls where `node` is the "first node" of the
139 /// macro call, as in [`first_node_in_macro`].
140 pub fn first_node_macro_backtrace(cx: &LateContext<'_>, node: &impl HirNode) -> impl Iterator<Item = MacroCall> {
141     let span = node.span();
142     first_node_in_macro(cx, node)
143         .into_iter()
144         .flat_map(move |expn| macro_backtrace(span).take_while(move |macro_call| macro_call.expn != expn))
145 }
146
147 /// If `node` is the "first node" in a macro expansion, returns `Some` with the `ExpnId` of the
148 /// macro call site (i.e. the parent of the macro expansion). This generally means that `node`
149 /// is the outermost node of an entire macro expansion, but there are some caveats noted below.
150 /// This is useful for finding macro calls while visiting the HIR without processing the macro call
151 /// at every node within its expansion.
152 ///
153 /// If you already have immediate access to the parent node, it is simpler to
154 /// just check the context of that span directly (e.g. `parent.span.from_expansion()`).
155 ///
156 /// If a macro call is in statement position, it expands to one or more statements.
157 /// In that case, each statement *and* their immediate descendants will all yield `Some`
158 /// with the `ExpnId` of the containing block.
159 ///
160 /// A node may be the "first node" of multiple macro calls in a macro backtrace.
161 /// The expansion of the outermost macro call site is returned in such cases.
162 pub fn first_node_in_macro(cx: &LateContext<'_>, node: &impl HirNode) -> Option<ExpnId> {
163     // get the macro expansion or return `None` if not found
164     // `macro_backtrace` importantly ignores desugaring expansions
165     let expn = macro_backtrace(node.span()).next()?.expn;
166
167     // get the parent node, possibly skipping over a statement
168     // if the parent is not found, it is sensible to return `Some(root)`
169     let hir = cx.tcx.hir();
170     let mut parent_iter = hir.parent_iter(node.hir_id());
171     let (parent_id, _) = match parent_iter.next() {
172         None => return Some(ExpnId::root()),
173         Some((_, Node::Stmt(_))) => match parent_iter.next() {
174             None => return Some(ExpnId::root()),
175             Some(next) => next,
176         },
177         Some(next) => next,
178     };
179
180     // get the macro expansion of the parent node
181     let parent_span = hir.span(parent_id);
182     let Some(parent_macro_call) = macro_backtrace(parent_span).next() else {
183         // the parent node is not in a macro
184         return Some(ExpnId::root());
185     };
186
187     if parent_macro_call.expn.is_descendant_of(expn) {
188         // `node` is input to a macro call
189         return None;
190     }
191
192     Some(parent_macro_call.expn)
193 }
194
195 /* Specific Macro Utils */
196
197 /// Is `def_id` of `std::panic`, `core::panic` or any inner implementation macros
198 pub fn is_panic(cx: &LateContext<'_>, def_id: DefId) -> bool {
199     let Some(name) = cx.tcx.get_diagnostic_name(def_id) else { return false };
200     matches!(
201         name.as_str(),
202         "core_panic_macro"
203             | "std_panic_macro"
204             | "core_panic_2015_macro"
205             | "std_panic_2015_macro"
206             | "core_panic_2021_macro"
207     )
208 }
209
210 pub enum PanicExpn<'a> {
211     /// No arguments - `panic!()`
212     Empty,
213     /// A string literal or any `&str` - `panic!("message")` or `panic!(message)`
214     Str(&'a Expr<'a>),
215     /// A single argument that implements `Display` - `panic!("{}", object)`
216     Display(&'a Expr<'a>),
217     /// Anything else - `panic!("error {}: {}", a, b)`
218     Format(FormatArgsExpn<'a>),
219 }
220
221 impl<'a> PanicExpn<'a> {
222     pub fn parse(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Self> {
223         if !macro_backtrace(expr.span).any(|macro_call| is_panic(cx, macro_call.def_id)) {
224             return None;
225         }
226         let ExprKind::Call(callee, [arg]) = &expr.kind else { return None };
227         let ExprKind::Path(QPath::Resolved(_, path)) = &callee.kind else { return None };
228         let result = match path.segments.last().unwrap().ident.as_str() {
229             "panic" if arg.span.ctxt() == expr.span.ctxt() => Self::Empty,
230             "panic" | "panic_str" => Self::Str(arg),
231             "panic_display" => {
232                 let ExprKind::AddrOf(_, _, e) = &arg.kind else { return None };
233                 Self::Display(e)
234             },
235             "panic_fmt" => Self::Format(FormatArgsExpn::parse(cx, arg)?),
236             _ => return None,
237         };
238         Some(result)
239     }
240 }
241
242 /// Finds the arguments of an `assert!` or `debug_assert!` macro call within the macro expansion
243 pub fn find_assert_args<'a>(
244     cx: &LateContext<'_>,
245     expr: &'a Expr<'a>,
246     expn: ExpnId,
247 ) -> Option<(&'a Expr<'a>, PanicExpn<'a>)> {
248     find_assert_args_inner(cx, expr, expn).map(|([e], p)| (e, p))
249 }
250
251 /// Finds the arguments of an `assert_eq!` or `debug_assert_eq!` macro call within the macro
252 /// expansion
253 pub fn find_assert_eq_args<'a>(
254     cx: &LateContext<'_>,
255     expr: &'a Expr<'a>,
256     expn: ExpnId,
257 ) -> Option<(&'a Expr<'a>, &'a Expr<'a>, PanicExpn<'a>)> {
258     find_assert_args_inner(cx, expr, expn).map(|([a, b], p)| (a, b, p))
259 }
260
261 fn find_assert_args_inner<'a, const N: usize>(
262     cx: &LateContext<'_>,
263     expr: &'a Expr<'a>,
264     expn: ExpnId,
265 ) -> Option<([&'a Expr<'a>; N], PanicExpn<'a>)> {
266     let macro_id = expn.expn_data().macro_def_id?;
267     let (expr, expn) = match cx.tcx.item_name(macro_id).as_str().strip_prefix("debug_") {
268         None => (expr, expn),
269         Some(inner_name) => find_assert_within_debug_assert(cx, expr, expn, Symbol::intern(inner_name))?,
270     };
271     let mut args = ArrayVec::new();
272     let mut panic_expn = None;
273     expr_visitor_no_bodies(|e| {
274         if args.is_full() {
275             if panic_expn.is_none() && e.span.ctxt() != expr.span.ctxt() {
276                 panic_expn = PanicExpn::parse(cx, e);
277             }
278             panic_expn.is_none()
279         } else if is_assert_arg(cx, e, expn) {
280             args.push(e);
281             false
282         } else {
283             true
284         }
285     })
286     .visit_expr(expr);
287     let args = args.into_inner().ok()?;
288     // if no `panic!(..)` is found, use `PanicExpn::Empty`
289     // to indicate that the default assertion message is used
290     let panic_expn = panic_expn.unwrap_or(PanicExpn::Empty);
291     Some((args, panic_expn))
292 }
293
294 fn find_assert_within_debug_assert<'a>(
295     cx: &LateContext<'_>,
296     expr: &'a Expr<'a>,
297     expn: ExpnId,
298     assert_name: Symbol,
299 ) -> Option<(&'a Expr<'a>, ExpnId)> {
300     let mut found = None;
301     expr_visitor_no_bodies(|e| {
302         if found.is_some() || !e.span.from_expansion() {
303             return false;
304         }
305         let e_expn = e.span.ctxt().outer_expn();
306         if e_expn == expn {
307             return true;
308         }
309         if e_expn.expn_data().macro_def_id.map(|id| cx.tcx.item_name(id)) == Some(assert_name) {
310             found = Some((e, e_expn));
311         }
312         false
313     })
314     .visit_expr(expr);
315     found
316 }
317
318 fn is_assert_arg(cx: &LateContext<'_>, expr: &Expr<'_>, assert_expn: ExpnId) -> bool {
319     if !expr.span.from_expansion() {
320         return true;
321     }
322     let result = macro_backtrace(expr.span).try_for_each(|macro_call| {
323         if macro_call.expn == assert_expn {
324             ControlFlow::Break(false)
325         } else {
326             match cx.tcx.item_name(macro_call.def_id) {
327                 // `cfg!(debug_assertions)` in `debug_assert!`
328                 sym::cfg => ControlFlow::CONTINUE,
329                 // assert!(other_macro!(..))
330                 _ => ControlFlow::Break(true),
331             }
332         }
333     });
334     match result {
335         ControlFlow::Break(is_assert_arg) => is_assert_arg,
336         ControlFlow::Continue(()) => true,
337     }
338 }
339
340 /// The format string doesn't exist in the HIR, so we reassemble it from source code
341 #[derive(Debug)]
342 pub struct FormatString {
343     /// Span of the whole format string literal, including `[r#]"`.
344     pub span: Span,
345     /// Snippet of the whole format string literal, including `[r#]"`.
346     pub snippet: String,
347     /// If the string is raw `r"..."`/`r#""#`, how many `#`s does it have on each side.
348     pub style: Option<usize>,
349     /// The unescaped value of the format string, e.g. `"val â€“ {}"` for the literal
350     /// `"val \u{2013} {}"`.
351     pub unescaped: String,
352     /// The format string split by format args like `{..}`.
353     pub parts: Vec<Symbol>,
354 }
355
356 impl FormatString {
357     fn new(cx: &LateContext<'_>, pieces: &Expr<'_>) -> Option<Self> {
358         // format_args!(r"a {} b \", 1);
359         //
360         // expands to
361         //
362         // ::core::fmt::Arguments::new_v1(&["a ", " b \\"],
363         //      &[::core::fmt::ArgumentV1::new_display(&1)]);
364         //
365         // where `pieces` is the expression `&["a ", " b \\"]`. It has the span of `r"a {} b \"`
366         let span = pieces.span;
367         let snippet = snippet_opt(cx, span)?;
368
369         let (inner, style) = match tokenize(&snippet).next()?.kind {
370             TokenKind::Literal { kind, .. } => {
371                 let style = match kind {
372                     LiteralKind::Str { .. } => None,
373                     LiteralKind::RawStr { n_hashes: Some(n), .. } => Some(n.into()),
374                     _ => return None,
375                 };
376
377                 let start = style.map_or(1, |n| 2 + n);
378                 let end = snippet.len() - style.map_or(1, |n| 1 + n);
379
380                 (&snippet[start..end], style)
381             },
382             _ => return None,
383         };
384
385         let mode = if style.is_some() {
386             unescape::Mode::RawStr
387         } else {
388             unescape::Mode::Str
389         };
390
391         let mut unescaped = String::with_capacity(inner.len());
392         unescape_literal(inner, mode, &mut |_, ch| {
393             unescaped.push(ch.unwrap());
394         });
395
396         let mut parts = Vec::new();
397         expr_visitor_no_bodies(|expr| {
398             if let ExprKind::Lit(lit) = &expr.kind {
399                 if let LitKind::Str(symbol, _) = lit.node {
400                     parts.push(symbol);
401                 }
402             }
403
404             true
405         })
406         .visit_expr(pieces);
407
408         Some(Self {
409             span,
410             snippet,
411             style,
412             unescaped,
413             parts,
414         })
415     }
416 }
417
418 struct FormatArgsValues<'tcx> {
419     /// See `FormatArgsExpn::value_args`
420     value_args: Vec<&'tcx Expr<'tcx>>,
421     /// Maps an `rt::v1::Argument::position` or an `rt::v1::Count::Param` to its index in
422     /// `value_args`
423     pos_to_value_index: Vec<usize>,
424     /// Used to check if a value is declared inline & to resolve `InnerSpan`s.
425     format_string_span: SpanData,
426 }
427
428 impl<'tcx> FormatArgsValues<'tcx> {
429     fn new(args: &'tcx Expr<'tcx>, format_string_span: SpanData) -> Self {
430         let mut pos_to_value_index = Vec::new();
431         let mut value_args = Vec::new();
432         expr_visitor_no_bodies(|expr| {
433             if expr.span.ctxt() == args.span.ctxt() {
434                 // ArgumentV1::new_<format_trait>(<val>)
435                 // ArgumentV1::from_usize(<val>)
436                 if let ExprKind::Call(callee, [val]) = expr.kind
437                     && let ExprKind::Path(QPath::TypeRelative(ty, _)) = callee.kind
438                     && let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind
439                     && path.segments.last().unwrap().ident.name == sym::ArgumentV1
440                 {
441                     let val_idx = if val.span.ctxt() == expr.span.ctxt()
442                         && let ExprKind::Field(_, field) = val.kind
443                         && let Ok(idx) = field.name.as_str().parse()
444                     {
445                         // tuple index
446                         idx
447                     } else {
448                         // assume the value expression is passed directly
449                         pos_to_value_index.len()
450                     };
451
452                     pos_to_value_index.push(val_idx);
453                 }
454
455                 true
456             } else {
457                 // assume that any expr with a differing span is a value
458                 value_args.push(expr);
459
460                 false
461             }
462         })
463         .visit_expr(args);
464
465         Self {
466             value_args,
467             pos_to_value_index,
468             format_string_span,
469         }
470     }
471 }
472
473 /// The positions of a format argument's value, precision and width
474 ///
475 /// A position is an index into the second argument of `Arguments::new_v1[_formatted]`
476 #[derive(Debug, Default, Copy, Clone)]
477 struct ParamPosition {
478     /// The position stored in `rt::v1::Argument::position`.
479     value: usize,
480     /// The position stored in `rt::v1::FormatSpec::width` if it is a `Count::Param`.
481     width: Option<usize>,
482     /// The position stored in `rt::v1::FormatSpec::precision` if it is a `Count::Param`.
483     precision: Option<usize>,
484 }
485
486 /// Parses the `fmt` arg of `Arguments::new_v1_formatted(pieces, args, fmt, _)`
487 fn parse_rt_fmt<'tcx>(fmt_arg: &'tcx Expr<'tcx>) -> Option<impl Iterator<Item = ParamPosition> + 'tcx> {
488     fn parse_count(expr: &Expr<'_>) -> Option<usize> {
489         // ::core::fmt::rt::v1::Count::Param(1usize),
490         if let ExprKind::Call(ctor, [val]) = expr.kind
491             && let ExprKind::Path(QPath::Resolved(_, path)) = ctor.kind
492             && path.segments.last()?.ident.name == sym::Param
493             && let ExprKind::Lit(lit) = &val.kind
494             && let LitKind::Int(pos, _) = lit.node
495         {
496             Some(pos as usize)
497         } else {
498             None
499         }
500     }
501
502     if let ExprKind::AddrOf(.., array) = fmt_arg.kind
503         && let ExprKind::Array(specs) = array.kind
504     {
505         Some(specs.iter().map(|spec| {
506             let mut position = ParamPosition::default();
507
508             // ::core::fmt::rt::v1::Argument {
509             //     position: 0usize,
510             //     format: ::core::fmt::rt::v1::FormatSpec {
511             //         ..
512             //         precision: ::core::fmt::rt::v1::Count::Implied,
513             //         width: ::core::fmt::rt::v1::Count::Implied,
514             //     },
515             // }
516
517             // TODO: this can be made much nicer next sync with `Visitor::visit_expr_field`
518             if let ExprKind::Struct(_, fields, _) = spec.kind {
519                 for field in fields {
520                     match (field.ident.name, &field.expr.kind) {
521                         (sym::position, ExprKind::Lit(lit)) => {
522                             if let LitKind::Int(pos, _) = lit.node {
523                                 position.value = pos as usize;
524                             }
525                         },
526                         (sym::format, &ExprKind::Struct(_, spec_fields, _)) => {
527                             for spec_field in spec_fields {
528                                 match spec_field.ident.name {
529                                     sym::precision => {
530                                         position.precision = parse_count(spec_field.expr);
531                                     },
532                                     sym::width => {
533                                         position.width = parse_count(spec_field.expr);
534                                     },
535                                     _ => {},
536                                 }
537                             }
538                         },
539                         _ => {},
540                     }
541                 }
542             }
543
544             position
545         }))
546     } else {
547         None
548     }
549 }
550
551 /// `Span::from_inner`, but for `rustc_parse_format`'s `InnerSpan`
552 fn span_from_inner(base: SpanData, inner: rpf::InnerSpan) -> Span {
553     Span::new(
554         base.lo + BytePos::from_usize(inner.start),
555         base.lo + BytePos::from_usize(inner.end),
556         base.ctxt,
557         base.parent,
558     )
559 }
560
561 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
562 pub enum FormatParamKind {
563     /// An implicit parameter , such as `{}` or `{:?}`.
564     Implicit,
565     /// A parameter with an explicit number, or an asterisk precision. e.g. `{1}`, `{0:?}`,
566     /// `{:.0$}` or `{:.*}`.
567     Numbered,
568     /// A named parameter with a named `value_arg`, such as the `x` in `format!("{x}", x = 1)`.
569     Named(Symbol),
570     /// An implicit named parameter, such as the `y` in `format!("{y}")`.
571     NamedInline(Symbol),
572 }
573
574 /// A `FormatParam` is any place in a `FormatArgument` that refers to a supplied value, e.g.
575 ///
576 /// ```
577 /// let precision = 2;
578 /// format!("{:.precision$}", 0.1234);
579 /// ```
580 ///
581 /// has two `FormatParam`s, a [`FormatParamKind::Implicit`] `.kind` with a `.value` of `0.1234`
582 /// and a [`FormatParamKind::NamedInline("precision")`] `.kind` with a `.value` of `2`
583 #[derive(Debug, Copy, Clone)]
584 pub struct FormatParam<'tcx> {
585     /// The expression this parameter refers to.
586     pub value: &'tcx Expr<'tcx>,
587     /// How this parameter refers to its `value`.
588     pub kind: FormatParamKind,
589     /// Span of the parameter, may be zero width. Includes the whitespace of implicit parameters.
590     ///
591     /// ```text
592     /// format!("{}, {  }, {0}, {name}", ...);
593     ///          ^    ~~    ~    ~~~~
594     /// ```
595     pub span: Span,
596 }
597
598 impl<'tcx> FormatParam<'tcx> {
599     fn new(
600         mut kind: FormatParamKind,
601         position: usize,
602         inner: rpf::InnerSpan,
603         values: &FormatArgsValues<'tcx>,
604     ) -> Option<Self> {
605         let value_index = *values.pos_to_value_index.get(position)?;
606         let value = *values.value_args.get(value_index)?;
607         let span = span_from_inner(values.format_string_span, inner);
608
609         // if a param is declared inline, e.g. `format!("{x}")`, the generated expr's span points
610         // into the format string
611         if let FormatParamKind::Named(name) = kind && values.format_string_span.contains(value.span.data()) {
612             kind = FormatParamKind::NamedInline(name);
613         }
614
615         Some(Self { value, kind, span })
616     }
617 }
618
619 /// Used by [width](https://doc.rust-lang.org/std/fmt/#width) and
620 /// [precision](https://doc.rust-lang.org/std/fmt/#precision) specifiers.
621 #[derive(Debug, Copy, Clone)]
622 pub enum Count<'tcx> {
623     /// Specified with a literal number, stores the value.
624     Is(usize, Span),
625     /// Specified using `$` and `*` syntaxes. The `*` format is still considered to be
626     /// `FormatParamKind::Numbered`.
627     Param(FormatParam<'tcx>),
628     /// Not specified.
629     Implied,
630 }
631
632 impl<'tcx> Count<'tcx> {
633     fn new(
634         count: rpf::Count<'_>,
635         position: Option<usize>,
636         inner: Option<rpf::InnerSpan>,
637         values: &FormatArgsValues<'tcx>,
638     ) -> Option<Self> {
639         Some(match count {
640             rpf::Count::CountIs(val) => Self::Is(val, span_from_inner(values.format_string_span, inner?)),
641             rpf::Count::CountIsName(name, span) => Self::Param(FormatParam::new(
642                 FormatParamKind::Named(Symbol::intern(name)),
643                 position?,
644                 span,
645                 values,
646             )?),
647             rpf::Count::CountIsParam(_) | rpf::Count::CountIsStar(_) => {
648                 Self::Param(FormatParam::new(FormatParamKind::Numbered, position?, inner?, values)?)
649             },
650             rpf::Count::CountImplied => Self::Implied,
651         })
652     }
653
654     pub fn is_implied(self) -> bool {
655         matches!(self, Count::Implied)
656     }
657
658     pub fn param(self) -> Option<FormatParam<'tcx>> {
659         match self {
660             Count::Param(param) => Some(param),
661             _ => None,
662         }
663     }
664 }
665
666 /// Specification for the formatting of an argument in the format string. See
667 /// <https://doc.rust-lang.org/std/fmt/index.html#formatting-parameters> for the precise meanings.
668 #[derive(Debug)]
669 pub struct FormatSpec<'tcx> {
670     /// Optionally specified character to fill alignment with.
671     pub fill: Option<char>,
672     /// Optionally specified alignment.
673     pub align: Alignment,
674     /// Packed version of various flags provided, see [`rustc_parse_format::Flag`].
675     pub flags: u32,
676     /// Represents either the maximum width or the integer precision.
677     pub precision: Count<'tcx>,
678     /// The minimum width, will be padded according to `width`/`align`
679     pub width: Count<'tcx>,
680     /// The formatting trait used by the argument, e.g. `sym::Display` for `{}`, `sym::Debug` for
681     /// `{:?}`.
682     pub r#trait: Symbol,
683     pub trait_span: Option<Span>,
684 }
685
686 impl<'tcx> FormatSpec<'tcx> {
687     fn new(spec: rpf::FormatSpec<'_>, positions: ParamPosition, values: &FormatArgsValues<'tcx>) -> Option<Self> {
688         Some(Self {
689             fill: spec.fill,
690             align: spec.align,
691             flags: spec.flags,
692             precision: Count::new(spec.precision, positions.precision, spec.precision_span, values)?,
693             width: Count::new(spec.width, positions.width, spec.width_span, values)?,
694             r#trait: match spec.ty {
695                 "" => sym::Display,
696                 "?" => sym::Debug,
697                 "o" => sym!(Octal),
698                 "x" => sym!(LowerHex),
699                 "X" => sym!(UpperHex),
700                 "p" => sym::Pointer,
701                 "b" => sym!(Binary),
702                 "e" => sym!(LowerExp),
703                 "E" => sym!(UpperExp),
704                 _ => return None,
705             },
706             trait_span: spec
707                 .ty_span
708                 .map(|span| span_from_inner(values.format_string_span, span)),
709         })
710     }
711
712     /// Returns true if this format spec would change the contents of a string when formatted
713     pub fn has_string_formatting(&self) -> bool {
714         self.r#trait != sym::Display || !self.width.is_implied() || !self.precision.is_implied()
715     }
716 }
717
718 /// A format argument, such as `{}`, `{foo:?}`.
719 #[derive(Debug)]
720 pub struct FormatArg<'tcx> {
721     /// The parameter the argument refers to.
722     pub param: FormatParam<'tcx>,
723     /// How to format `param`.
724     pub format: FormatSpec<'tcx>,
725     /// span of the whole argument, `{..}`.
726     pub span: Span,
727 }
728
729 /// A parsed `format_args!` expansion.
730 #[derive(Debug)]
731 pub struct FormatArgsExpn<'tcx> {
732     /// The format string literal.
733     pub format_string: FormatString,
734     // The format arguments, such as `{:?}`.
735     pub args: Vec<FormatArg<'tcx>>,
736     /// Has an added newline due to `println!()`/`writeln!()`/etc. The last format string part will
737     /// include this added newline.
738     pub newline: bool,
739     /// Values passed after the format string and implicit captures. `[1, z + 2, x]` for
740     /// `format!("{x} {} {y}", 1, z + 2)`.
741     value_args: Vec<&'tcx Expr<'tcx>>,
742 }
743
744 impl<'tcx> FormatArgsExpn<'tcx> {
745     pub fn parse(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<Self> {
746         let macro_name = macro_backtrace(expr.span)
747             .map(|macro_call| cx.tcx.item_name(macro_call.def_id))
748             .find(|&name| matches!(name, sym::const_format_args | sym::format_args | sym::format_args_nl))?;
749         let newline = macro_name == sym::format_args_nl;
750
751         // ::core::fmt::Arguments::new_v1(pieces, args)
752         // ::core::fmt::Arguments::new_v1_formatted(pieces, args, fmt, _unsafe_arg)
753         if let ExprKind::Call(callee, [pieces, args, rest @ ..]) = expr.kind
754             && let ExprKind::Path(QPath::TypeRelative(ty, seg)) = callee.kind
755             && is_path_diagnostic_item(cx, ty, sym::Arguments)
756             && matches!(seg.ident.as_str(), "new_v1" | "new_v1_formatted")
757         {
758             let format_string = FormatString::new(cx, pieces)?;
759
760             let mut parser = rpf::Parser::new(
761                 &format_string.unescaped,
762                 format_string.style,
763                 Some(format_string.snippet.clone()),
764                 // `format_string.unescaped` does not contain the appended newline
765                 false,
766                 rpf::ParseMode::Format,
767             );
768
769             let parsed_args = parser
770                 .by_ref()
771                 .filter_map(|piece| match piece {
772                     rpf::Piece::NextArgument(a) => Some(a),
773                     rpf::Piece::String(_) => None,
774                 })
775                 .collect_vec();
776             if !parser.errors.is_empty() {
777                 return None;
778             }
779
780             let positions = if let Some(fmt_arg) = rest.first() {
781                 // If the argument contains format specs, `new_v1_formatted(_, _, fmt, _)`, parse
782                 // them.
783
784                 Either::Left(parse_rt_fmt(fmt_arg)?)
785             } else {
786                 // If no format specs are given, the positions are in the given order and there are
787                 // no `precision`/`width`s to consider.
788
789                 Either::Right((0..).map(|n| ParamPosition {
790                     value: n,
791                     width: None,
792                     precision: None,
793                 }))
794             };
795
796             let values = FormatArgsValues::new(args, format_string.span.data());
797
798             let args = izip!(positions, parsed_args, parser.arg_places)
799                 .map(|(position, parsed_arg, arg_span)| {
800                     Some(FormatArg {
801                         param: FormatParam::new(
802                             match parsed_arg.position {
803                                 rpf::Position::ArgumentImplicitlyIs(_) => FormatParamKind::Implicit,
804                                 rpf::Position::ArgumentIs(_) => FormatParamKind::Numbered,
805                                 // NamedInline is handled by `FormatParam::new()`
806                                 rpf::Position::ArgumentNamed(name) => FormatParamKind::Named(Symbol::intern(name)),
807                             },
808                             position.value,
809                             parsed_arg.position_span,
810                             &values,
811                         )?,
812                         format: FormatSpec::new(parsed_arg.format, position, &values)?,
813                         span: span_from_inner(values.format_string_span, arg_span),
814                     })
815                 })
816                 .collect::<Option<Vec<_>>>()?;
817
818             Some(Self {
819                 format_string,
820                 args,
821                 value_args: values.value_args,
822                 newline,
823             })
824         } else {
825             None
826         }
827     }
828
829     pub fn find_nested(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, expn_id: ExpnId) -> Option<Self> {
830         let mut format_args = None;
831         expr_visitor_no_bodies(|e| {
832             if format_args.is_some() {
833                 return false;
834             }
835             let e_ctxt = e.span.ctxt();
836             if e_ctxt == expr.span.ctxt() {
837                 return true;
838             }
839             if e_ctxt.outer_expn().is_descendant_of(expn_id) {
840                 format_args = FormatArgsExpn::parse(cx, e);
841             }
842             false
843         })
844         .visit_expr(expr);
845         format_args
846     }
847
848     /// Source callsite span of all inputs
849     pub fn inputs_span(&self) -> Span {
850         match *self.value_args {
851             [] => self.format_string.span,
852             [.., last] => self
853                 .format_string
854                 .span
855                 .to(hygiene::walk_chain(last.span, self.format_string.span.ctxt())),
856         }
857     }
858
859     /// Iterator of all format params, both values and those referenced by `width`/`precision`s.
860     pub fn params(&'tcx self) -> impl Iterator<Item = FormatParam<'tcx>> {
861         self.args
862             .iter()
863             .flat_map(|arg| [Some(arg.param), arg.format.precision.param(), arg.format.width.param()])
864             .flatten()
865     }
866 }
867
868 /// A node with a `HirId` and a `Span`
869 pub trait HirNode {
870     fn hir_id(&self) -> HirId;
871     fn span(&self) -> Span;
872 }
873
874 macro_rules! impl_hir_node {
875     ($($t:ident),*) => {
876         $(impl HirNode for hir::$t<'_> {
877             fn hir_id(&self) -> HirId {
878                 self.hir_id
879             }
880             fn span(&self) -> Span {
881                 self.span
882             }
883         })*
884     };
885 }
886
887 impl_hir_node!(Expr, Pat);
888
889 impl HirNode for hir::Item<'_> {
890     fn hir_id(&self) -> HirId {
891         self.hir_id()
892     }
893
894     fn span(&self) -> Span {
895         self.span
896     }
897 }