1 #![allow(clippy::similar_names)] // `expr` and `expn`
3 use crate::is_path_diagnostic_item;
4 use crate::source::snippet_opt;
5 use crate::visitors::expr_visitor_no_bodies;
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;
21 const FORMAT_MACRO_DIAG_ITEMS: &[Symbol] = &[
25 sym::debug_assert_eq_macro,
26 sym::debug_assert_macro,
27 sym::debug_assert_ne_macro,
30 sym::format_args_macro,
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)
48 /// A macro call, like `vec![1, 2, 3]`.
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.
53 /// This structure is similar to `ExpnData` but it precludes desugaring expansions.
55 pub struct MacroCall {
60 /// The expansion produced by the macro call
62 /// Span of the macro call site
67 pub fn is_local(&self) -> bool {
68 span_is_local(self.span)
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() {
79 let expn = ctxt.outer_expn();
80 let data = expn.expn_data();
81 span = data.call_site;
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())
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() {
96 let data = expn.expn_data();
97 let backtrace = expn_backtrace(data.call_site);
98 std::iter::once((expn, data))
100 .find_map(|(_, data)| data.macro_def_id)
101 .map_or(true, DefId::is_local)
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 {
109 kind: ExpnKind::Macro(kind, _),
110 macro_def_id: Some(def_id),
113 } => Some(MacroCall {
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()
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()) {
135 root_macro_call(node.span())
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)
144 .flat_map(move |expn| macro_backtrace(span).take_while(move |macro_call| macro_call.expn != expn))
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.
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()`).
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.
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;
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()),
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());
187 if parent_macro_call.expn.is_descendant_of(expn) {
188 // `node` is input to a macro call
192 Some(parent_macro_call.expn)
195 /* Specific Macro Utils */
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 };
204 | "core_panic_2015_macro"
205 | "std_panic_2015_macro"
206 | "core_panic_2021_macro"
210 pub enum PanicExpn<'a> {
211 /// No arguments - `panic!()`
213 /// A string literal or any `&str` - `panic!("message")` or `panic!(message)`
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>),
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)) {
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),
232 let ExprKind::AddrOf(_, _, e) = &arg.kind else { return None };
235 "panic_fmt" => Self::Format(FormatArgsExpn::parse(cx, arg)?),
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<'_>,
247 ) -> Option<(&'a Expr<'a>, PanicExpn<'a>)> {
248 find_assert_args_inner(cx, expr, expn).map(|([e], p)| (e, p))
251 /// Finds the arguments of an `assert_eq!` or `debug_assert_eq!` macro call within the macro
253 pub fn find_assert_eq_args<'a>(
254 cx: &LateContext<'_>,
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))
261 fn find_assert_args_inner<'a, const N: usize>(
262 cx: &LateContext<'_>,
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))?,
271 let mut args = ArrayVec::new();
272 let mut panic_expn = None;
273 expr_visitor_no_bodies(|e| {
275 if panic_expn.is_none() && e.span.ctxt() != expr.span.ctxt() {
276 panic_expn = PanicExpn::parse(cx, e);
279 } else if is_assert_arg(cx, e, expn) {
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))
294 fn find_assert_within_debug_assert<'a>(
295 cx: &LateContext<'_>,
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() {
305 let e_expn = e.span.ctxt().outer_expn();
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));
318 fn is_assert_arg(cx: &LateContext<'_>, expr: &Expr<'_>, assert_expn: ExpnId) -> bool {
319 if !expr.span.from_expansion() {
322 let result = macro_backtrace(expr.span).try_for_each(|macro_call| {
323 if macro_call.expn == assert_expn {
324 ControlFlow::Break(false)
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),
335 ControlFlow::Break(is_assert_arg) => is_assert_arg,
336 ControlFlow::Continue(()) => true,
340 /// The format string doesn't exist in the HIR, so we reassemble it from source code
342 pub struct FormatString {
343 /// Span of the whole format string literal, including `[r#]"`.
345 /// Snippet of the whole format string literal, including `[r#]"`.
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>,
357 fn new(cx: &LateContext<'_>, pieces: &Expr<'_>) -> Option<Self> {
358 // format_args!(r"a {} b \", 1);
362 // ::core::fmt::Arguments::new_v1(&["a ", " b \\"],
363 // &[::core::fmt::ArgumentV1::new_display(&1)]);
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)?;
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()),
377 let start = style.map_or(1, |n| 2 + n);
378 let end = snippet.len() - style.map_or(1, |n| 1 + n);
380 (&snippet[start..end], style)
385 let mode = if style.is_some() {
386 unescape::Mode::RawStr
391 let mut unescaped = String::with_capacity(inner.len());
392 unescape_literal(inner, mode, &mut |_, ch| {
393 unescaped.push(ch.unwrap());
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 {
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
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,
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
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()
448 // assume the value expression is passed directly
449 pos_to_value_index.len()
452 pos_to_value_index.push(val_idx);
457 // assume that any expr with a differing span is a value
458 value_args.push(expr);
473 /// The positions of a format argument's value, precision and width
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`.
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>,
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
502 if let ExprKind::AddrOf(.., array) = fmt_arg.kind
503 && let ExprKind::Array(specs) = array.kind
505 Some(specs.iter().map(|spec| {
506 let mut position = ParamPosition::default();
508 // ::core::fmt::rt::v1::Argument {
510 // format: ::core::fmt::rt::v1::FormatSpec {
512 // precision: ::core::fmt::rt::v1::Count::Implied,
513 // width: ::core::fmt::rt::v1::Count::Implied,
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;
526 (sym::format, &ExprKind::Struct(_, spec_fields, _)) => {
527 for spec_field in spec_fields {
528 match spec_field.ident.name {
530 position.precision = parse_count(spec_field.expr);
533 position.width = parse_count(spec_field.expr);
551 /// `Span::from_inner`, but for `rustc_parse_format`'s `InnerSpan`
552 fn span_from_inner(base: SpanData, inner: rpf::InnerSpan) -> Span {
554 base.lo + BytePos::from_usize(inner.start),
555 base.lo + BytePos::from_usize(inner.end),
561 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
562 pub enum FormatParamKind {
563 /// An implicit parameter , such as `{}` or `{:?}`.
565 /// A parameter with an explicit number, or an asterisk precision. e.g. `{1}`, `{0:?}`,
566 /// `{:.0$}` or `{:.*}`.
568 /// A named parameter with a named `value_arg`, such as the `x` in `format!("{x}", x = 1)`.
570 /// An implicit named parameter, such as the `y` in `format!("{y}")`.
574 /// A `FormatParam` is any place in a `FormatArgument` that refers to a supplied value, e.g.
577 /// let precision = 2;
578 /// format!("{:.precision$}", 0.1234);
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.
592 /// format!("{}, { }, {0}, {name}", ...);
598 impl<'tcx> FormatParam<'tcx> {
600 mut kind: FormatParamKind,
602 inner: rpf::InnerSpan,
603 values: &FormatArgsValues<'tcx>,
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);
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);
615 Some(Self { value, kind, span })
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.
625 /// Specified using `$` and `*` syntaxes. The `*` format is still considered to be
626 /// `FormatParamKind::Numbered`.
627 Param(FormatParam<'tcx>),
632 impl<'tcx> Count<'tcx> {
634 count: rpf::Count<'_>,
635 position: Option<usize>,
636 inner: Option<rpf::InnerSpan>,
637 values: &FormatArgsValues<'tcx>,
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)),
647 rpf::Count::CountIsParam(_) | rpf::Count::CountIsStar(_) => {
648 Self::Param(FormatParam::new(FormatParamKind::Numbered, position?, inner?, values)?)
650 rpf::Count::CountImplied => Self::Implied,
654 pub fn is_implied(self) -> bool {
655 matches!(self, Count::Implied)
658 pub fn param(self) -> Option<FormatParam<'tcx>> {
660 Count::Param(param) => Some(param),
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.
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`].
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
683 pub trait_span: Option<Span>,
686 impl<'tcx> FormatSpec<'tcx> {
687 fn new(spec: rpf::FormatSpec<'_>, positions: ParamPosition, values: &FormatArgsValues<'tcx>) -> Option<Self> {
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 {
698 "x" => sym!(LowerHex),
699 "X" => sym!(UpperHex),
702 "e" => sym!(LowerExp),
703 "E" => sym!(UpperExp),
708 .map(|span| span_from_inner(values.format_string_span, span)),
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()
718 /// A format argument, such as `{}`, `{foo:?}`.
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, `{..}`.
729 /// A parsed `format_args!` expansion.
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.
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>>,
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;
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")
758 let format_string = FormatString::new(cx, pieces)?;
760 let mut parser = rpf::Parser::new(
761 &format_string.unescaped,
763 Some(format_string.snippet.clone()),
764 // `format_string.unescaped` does not contain the appended newline
766 rpf::ParseMode::Format,
769 let parsed_args = parser
771 .filter_map(|piece| match piece {
772 rpf::Piece::NextArgument(a) => Some(a),
773 rpf::Piece::String(_) => None,
776 if !parser.errors.is_empty() {
780 let positions = if let Some(fmt_arg) = rest.first() {
781 // If the argument contains format specs, `new_v1_formatted(_, _, fmt, _)`, parse
784 Either::Left(parse_rt_fmt(fmt_arg)?)
786 // If no format specs are given, the positions are in the given order and there are
787 // no `precision`/`width`s to consider.
789 Either::Right((0..).map(|n| ParamPosition {
796 let values = FormatArgsValues::new(args, format_string.span.data());
798 let args = izip!(positions, parsed_args, parser.arg_places)
799 .map(|(position, parsed_arg, arg_span)| {
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)),
809 parsed_arg.position_span,
812 format: FormatSpec::new(parsed_arg.format, position, &values)?,
813 span: span_from_inner(values.format_string_span, arg_span),
816 .collect::<Option<Vec<_>>>()?;
821 value_args: values.value_args,
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() {
835 let e_ctxt = e.span.ctxt();
836 if e_ctxt == expr.span.ctxt() {
839 if e_ctxt.outer_expn().is_descendant_of(expn_id) {
840 format_args = FormatArgsExpn::parse(cx, e);
848 /// Source callsite span of all inputs
849 pub fn inputs_span(&self) -> Span {
850 match *self.value_args {
851 [] => self.format_string.span,
855 .to(hygiene::walk_chain(last.span, self.format_string.span.ctxt())),
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>> {
863 .flat_map(|arg| [Some(arg.param), arg.format.precision.param(), arg.format.width.param()])
868 /// A node with a `HirId` and a `Span`
870 fn hir_id(&self) -> HirId;
871 fn span(&self) -> Span;
874 macro_rules! impl_hir_node {
876 $(impl HirNode for hir::$t<'_> {
877 fn hir_id(&self) -> HirId {
880 fn span(&self) -> Span {
887 impl_hir_node!(Expr, Pat);
889 impl HirNode for hir::Item<'_> {
890 fn hir_id(&self) -> HirId {
894 fn span(&self) -> Span {