Skip to content

Commit c38e9d7

Browse files
committed
new needless-format-args lint to inline explicit arguments
Implement rust-lang#8368 - a new lint to inline format arguments such as `print!("{}", var)` into `print!("{var}")`. ### Supported cases code | suggestion | comment ---|---|--- `print!("{}", var)` | `print!("{var}")` | simple variables `print!("{0}", var)` | `print!("{var}")` | positional variables `print!("{v}", v=var)` | `print!("{var}")` | named variables `print!("{0} {0}", var)` | `print!("{var} {var}")` | aliased variables `print!("{0:1$}", var, width)` | `print!("{var:width$}")` | width support `print!("{0:.1$}", var, prec)` | `print!("{var:.prec$}")` | precision support `print!("{:.*}", prec, var)` | `print!("{var:.prec$}")` | asterisk support ### Unsupported cases code | suggestion | comment ---|---|--- `print!("{0}={1}", var, 1+2)` | `print!("{var}={0}", 1+2)` | Format string uses an indexed argument that cannot be inlined. Supporting this case requires re-indexing of the format string. changelog: [`needless-format-args`]: A new lint to inline format arguments, i.e. `print!("{}", var)` into `print!("{var}")`
1 parent 8b1ad17 commit c38e9d7

13 files changed

+1246
-18
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4072,6 +4072,7 @@ Released 2018-09-13
40724072
[`needless_continue`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_continue
40734073
[`needless_doctest_main`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_doctest_main
40744074
[`needless_for_each`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_for_each
4075+
[`needless_format_args`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_format_args
40754076
[`needless_late_init`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_late_init
40764077
[`needless_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
40774078
[`needless_match`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_match

clippy_lints/src/format_args.rs

+101-5
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
22
use clippy_utils::is_diag_trait_item;
3-
use clippy_utils::macros::{is_format_macro, FormatArgsExpn};
4-
use clippy_utils::source::snippet_opt;
3+
use clippy_utils::macros::FormatParamKind::{Implicit, Named, Numbered, Starred};
4+
use clippy_utils::macros::{is_format_macro, FormatArgsExpn, FormatParam};
5+
use clippy_utils::source::{expand_past_previous_comma, snippet_opt};
56
use clippy_utils::ty::implements_trait;
67
use if_chain::if_chain;
78
use itertools::Itertools;
89
use rustc_errors::Applicability;
9-
use rustc_hir::{Expr, ExprKind, HirId};
10+
use rustc_hir::{Expr, ExprKind, HirId, Path, QPath};
1011
use rustc_lint::{LateContext, LateLintPass};
1112
use rustc_middle::ty::adjustment::{Adjust, Adjustment};
1213
use rustc_middle::ty::Ty;
@@ -64,7 +65,33 @@ declare_clippy_lint! {
6465
"`to_string` applied to a type that implements `Display` in format args"
6566
}
6667

67-
declare_lint_pass!(FormatArgs => [FORMAT_IN_FORMAT_ARGS, TO_STRING_IN_FORMAT_ARGS]);
68+
declare_clippy_lint! {
69+
/// ### What it does
70+
/// Detect when a variable is not inlined in a format string,
71+
/// and suggests to inline it.
72+
///
73+
/// ### Why is this bad?
74+
/// Non-inlined code is slightly more difficult to read and understand,
75+
/// as it requires arguments to be matched against the format string.
76+
/// The inlined syntax, where allowed, is simpler.
77+
///
78+
/// ### Example
79+
/// ```rust
80+
/// # let foo = 42;
81+
/// format!("{}", foo);
82+
/// ```
83+
/// Use instead:
84+
/// ```rust
85+
/// # let foo = 42;
86+
/// format!("{foo}");
87+
/// ```
88+
#[clippy::version = "1.64.0"]
89+
pub NEEDLESS_FORMAT_ARGS,
90+
nursery,
91+
"using non-inlined variables in `format!` calls"
92+
}
93+
94+
declare_lint_pass!(FormatArgs => [FORMAT_IN_FORMAT_ARGS, NEEDLESS_FORMAT_ARGS, TO_STRING_IN_FORMAT_ARGS]);
6895

6996
impl<'tcx> LateLintPass<'tcx> for FormatArgs {
7097
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
@@ -76,7 +103,23 @@ impl<'tcx> LateLintPass<'tcx> for FormatArgs {
76103
if is_format_macro(cx, macro_def_id);
77104
if let ExpnKind::Macro(_, name) = outermost_expn_data.kind;
78105
then {
106+
// if at least some of the arguments/format/precision are referenced by an index,
107+
// e.g. format!("{} {1}", foo, bar) or format!("{:1$}", foo, 2)
108+
// we cannot remove an argument from a list until we support renumbering.
109+
// We are OK if we inline all numbered arguments.
110+
let mut do_inline = true;
111+
// if we find one or more suggestions, this becomes a Vec of replacements
112+
let mut inline_spans = None;
79113
for arg in &format_args.args {
114+
if do_inline {
115+
do_inline = check_inline(cx, &arg.param, ParamType::Argument, &mut inline_spans);
116+
}
117+
if do_inline && let Some(p) = arg.format.width.param() {
118+
do_inline = check_inline(cx, &p, ParamType::Width, &mut inline_spans);
119+
}
120+
if do_inline && let Some(p) = arg.format.precision.param() {
121+
do_inline = check_inline(cx, &p, ParamType::Precision, &mut inline_spans);
122+
}
80123
if !arg.format.is_default() {
81124
continue;
82125
}
@@ -86,11 +129,64 @@ impl<'tcx> LateLintPass<'tcx> for FormatArgs {
86129
check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg.param.value);
87130
check_to_string_in_format_args(cx, name, arg.param.value);
88131
}
132+
if do_inline && let Some(inline_spans) = inline_spans {
133+
span_lint_and_then(
134+
cx,
135+
NEEDLESS_FORMAT_ARGS,
136+
outermost_expn_data.call_site,
137+
"variables can be used directly in the `format!` string",
138+
|diag| {
139+
diag.multipart_suggestion("change this to", inline_spans, Applicability::MachineApplicable);
140+
},
141+
);
142+
}
89143
}
90144
}
91145
}
92146
}
93147

148+
#[derive(Debug, Clone, Copy)]
149+
enum ParamType {
150+
Argument,
151+
Width,
152+
Precision,
153+
}
154+
155+
fn check_inline(
156+
cx: &LateContext<'_>,
157+
param: &FormatParam<'_>,
158+
ptype: ParamType,
159+
inline_spans: &mut Option<Vec<(Span, String)>>,
160+
) -> bool {
161+
if matches!(param.kind, Implicit | Starred | Named(_) | Numbered)
162+
&& let ExprKind::Path(QPath::Resolved(None, path)) = param.value.kind
163+
&& let Path { span, segments, .. } = path
164+
&& let [segment] = segments
165+
{
166+
let c = inline_spans.get_or_insert_with(Vec::new);
167+
// TODO: Note the inconsistency here, that we may want to address separately:
168+
// implicit, numbered, and starred `param.span` spans the whole relevant string:
169+
// the empty space between `{}`, or the entire value `1$`, `.2$`, or `.*`
170+
// but the named argument spans just the name itself, without the surrounding `.` and `$`.
171+
let replacement = if param.kind == Numbered || param.kind == Starred {
172+
match ptype {
173+
ParamType::Argument => segment.ident.name.to_string(),
174+
ParamType::Width => format!("{}$", segment.ident.name),
175+
ParamType::Precision => format!(".{}$", segment.ident.name),
176+
}
177+
} else {
178+
segment.ident.name.to_string()
179+
};
180+
c.push((param.span, replacement));
181+
let arg_span = expand_past_previous_comma(cx, *span);
182+
c.push((arg_span, String::new()));
183+
true // successful inlining, continue checking
184+
} else {
185+
// if we can't inline a numbered argument, we can't continue
186+
param.kind != Numbered
187+
}
188+
}
189+
94190
fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
95191
if expn_data.call_site.from_expansion() {
96192
outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
@@ -170,7 +266,7 @@ fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Ex
170266
}
171267
}
172268

173-
// Returns true if `hir_id` is referred to by multiple format params
269+
/// Returns true if `hir_id` is referred to by multiple format params
174270
fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
175271
args.params()
176272
.filter(|param| param.value.hir_id == hir_id)

clippy_lints/src/lib.register_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ store.register_lints(&[
158158
floating_point_arithmetic::SUBOPTIMAL_FLOPS,
159159
format::USELESS_FORMAT,
160160
format_args::FORMAT_IN_FORMAT_ARGS,
161+
format_args::NEEDLESS_FORMAT_ARGS,
161162
format_args::TO_STRING_IN_FORMAT_ARGS,
162163
format_impl::PRINT_IN_FORMAT_IMPL,
163164
format_impl::RECURSIVE_FORMAT_IMPL,

clippy_lints/src/lib.register_nursery.rs

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ store.register_group(true, "clippy::nursery", Some("clippy_nursery"), vec![
1010
LintId::of(fallible_impl_from::FALLIBLE_IMPL_FROM),
1111
LintId::of(floating_point_arithmetic::IMPRECISE_FLOPS),
1212
LintId::of(floating_point_arithmetic::SUBOPTIMAL_FLOPS),
13+
LintId::of(format_args::NEEDLESS_FORMAT_ARGS),
1314
LintId::of(future_not_send::FUTURE_NOT_SEND),
1415
LintId::of(index_refutable_slice::INDEX_REFUTABLE_SLICE),
1516
LintId::of(let_if_seq::USELESS_LET_IF_SEQ),

clippy_lints/src/write.rs

+2-9
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
22
use clippy_utils::macros::{root_macro_call_first_node, FormatArgsExpn, MacroCall};
3-
use clippy_utils::source::snippet_opt;
3+
use clippy_utils::source::{expand_past_previous_comma, snippet_opt};
44
use rustc_ast::LitKind;
55
use rustc_errors::Applicability;
66
use rustc_hir::{Expr, ExprKind, HirIdMap, Impl, Item, ItemKind};
77
use rustc_lint::{LateContext, LateLintPass, LintContext};
88
use rustc_session::{declare_tool_lint, impl_lint_pass};
9-
use rustc_span::{sym, BytePos, Span};
9+
use rustc_span::{sym, BytePos};
1010

1111
declare_clippy_lint! {
1212
/// ### What it does
@@ -542,10 +542,3 @@ fn conservative_unescape(literal: &str) -> Result<String, UnescapeErr> {
542542

543543
if err { Err(UnescapeErr::Lint) } else { Ok(unescaped) }
544544
}
545-
546-
// Expand from `writeln!(o, "")` to `writeln!(o, "")`
547-
// ^^ ^^^^
548-
fn expand_past_previous_comma(cx: &LateContext<'_>, span: Span) -> Span {
549-
let extended = cx.sess().source_map().span_extend_to_prev_char(span, ',', true);
550-
extended.with_lo(extended.lo() - BytePos(1))
551-
}

clippy_utils/src/macros.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -549,9 +549,10 @@ fn span_from_inner(base: SpanData, inner: rpf::InnerSpan) -> Span {
549549
pub enum FormatParamKind {
550550
/// An implicit parameter , such as `{}` or `{:?}`.
551551
Implicit,
552-
/// A parameter with an explicit number, or an asterisk precision. e.g. `{1}`, `{0:?}`,
553-
/// `{:.0$}` or `{:.*}`.
552+
/// A parameter with an explicit number, e.g. `{1}`, `{0:?}`, or `{:.0$}`
554553
Numbered,
554+
/// A parameter with an asterisk precision. e.g. `{:.*}`.
555+
Starred,
555556
/// A named parameter with a named `value_arg`, such as the `x` in `format!("{x}", x = 1)`.
556557
Named(Symbol),
557558
/// An implicit named parameter, such as the `y` in `format!("{y}")`.
@@ -631,9 +632,12 @@ impl<'tcx> Count<'tcx> {
631632
span,
632633
values,
633634
)?),
634-
rpf::Count::CountIsParam(_) | rpf::Count::CountIsStar(_) => {
635+
rpf::Count::CountIsParam(_) => {
635636
Self::Param(FormatParam::new(FormatParamKind::Numbered, position?, inner?, values)?)
636637
},
638+
rpf::Count::CountIsStar(_) => {
639+
Self::Param(FormatParam::new(FormatParamKind::Starred, position?, inner?, values)?)
640+
},
637641
rpf::Count::CountImplied => Self::Implied,
638642
})
639643
}
@@ -723,7 +727,7 @@ pub struct FormatArg<'tcx> {
723727
pub struct FormatArgsExpn<'tcx> {
724728
/// The format string literal.
725729
pub format_string: FormatString,
726-
// The format arguments, such as `{:?}`.
730+
/// The format arguments, such as `{:?}`.
727731
pub args: Vec<FormatArg<'tcx>>,
728732
/// Has an added newline due to `println!()`/`writeln!()`/etc. The last format string part will
729733
/// include this added newline.

clippy_utils/src/msrvs.rs

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ macro_rules! msrv_aliases {
1313
// names may refer to stabilized feature flags or library items
1414
msrv_aliases! {
1515
1,62,0 { BOOL_THEN_SOME }
16+
1,58,0 { NEEDLESS_FORMAT_ARGS }
1617
1,53,0 { OR_PATTERNS, MANUAL_BITS, BTREE_MAP_RETAIN, BTREE_SET_RETAIN, ARRAY_INTO_ITERATOR }
1718
1,52,0 { STR_SPLIT_ONCE, REM_EUCLID_CONST }
1819
1,51,0 { BORROW_AS_PTR, UNSIGNED_ABS }

clippy_utils/src/source.rs

+10
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,16 @@ pub fn trim_span(sm: &SourceMap, span: Span) -> Span {
392392
.span()
393393
}
394394

395+
/// Expand a span to include a preceding comma
396+
/// ```rust,ignore
397+
/// writeln!(o, "") -> writeln!(o, "")
398+
/// ^^ ^^^^
399+
/// ```
400+
pub fn expand_past_previous_comma(cx: &LateContext<'_>, span: Span) -> Span {
401+
let extended = cx.sess().source_map().span_extend_to_prev_char(span, ',', true);
402+
extended.with_lo(extended.lo() - BytePos(1))
403+
}
404+
395405
#[cfg(test)]
396406
mod test {
397407
use super::{reindent_multiline, without_block_comments};

src/docs.rs

+1
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ docs! {
340340
"needless_continue",
341341
"needless_doctest_main",
342342
"needless_for_each",
343+
"needless_format_args",
343344
"needless_late_init",
344345
"needless_lifetimes",
345346
"needless_match",

src/docs/needless_format_args.txt

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
### What it does
2+
Detect when a variable is not inlined in a format string,
3+
and suggests to inline it.
4+
5+
### Why is this bad?
6+
Non-inlined code is slightly more difficult to read and understand,
7+
as it requires arguments to be matched against the format string.
8+
The inlined syntax, where allowed, is simpler.
9+
10+
### Example
11+
```
12+
format!("{}", foo);
13+
```
14+
Use instead:
15+
```
16+
format!("{foo}");
17+
```

0 commit comments

Comments
 (0)