2021-10-21 11:11:36 +00:00
|
|
|
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
|
new uninlined_format_args lint to inline explicit arguments
Implement https://github.com/rust-lang/rust-clippy/issues/8368 - a new
lint to inline format arguments such as `print!("{}", var)` into
`print!("{var}")`.
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
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: [`uninlined_format_args`]: A new lint to inline format
arguments, i.e. `print!("{}", var)` into `print!("{var}")`
2022-09-14 16:25:48 +00:00
|
|
|
use clippy_utils::macros::FormatParamKind::{Implicit, Named, Numbered, Starred};
|
|
|
|
use clippy_utils::macros::{is_format_macro, FormatArgsExpn, FormatParam, FormatParamUsage};
|
|
|
|
use clippy_utils::source::{expand_past_previous_comma, snippet_opt};
|
2021-10-21 11:11:36 +00:00
|
|
|
use clippy_utils::ty::implements_trait;
|
new uninlined_format_args lint to inline explicit arguments
Implement https://github.com/rust-lang/rust-clippy/issues/8368 - a new
lint to inline format arguments such as `print!("{}", var)` into
`print!("{var}")`.
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
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: [`uninlined_format_args`]: A new lint to inline format
arguments, i.e. `print!("{}", var)` into `print!("{var}")`
2022-09-14 16:25:48 +00:00
|
|
|
use clippy_utils::{is_diag_trait_item, meets_msrv, msrvs};
|
2021-10-21 11:11:36 +00:00
|
|
|
use if_chain::if_chain;
|
2022-08-31 13:24:45 +00:00
|
|
|
use itertools::Itertools;
|
2021-10-21 11:11:36 +00:00
|
|
|
use rustc_errors::Applicability;
|
new uninlined_format_args lint to inline explicit arguments
Implement https://github.com/rust-lang/rust-clippy/issues/8368 - a new
lint to inline format arguments such as `print!("{}", var)` into
`print!("{var}")`.
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
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: [`uninlined_format_args`]: A new lint to inline format
arguments, i.e. `print!("{}", var)` into `print!("{var}")`
2022-09-14 16:25:48 +00:00
|
|
|
use rustc_hir::{Expr, ExprKind, HirId, Path, QPath};
|
2021-10-21 11:11:36 +00:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
|
|
|
use rustc_middle::ty::adjustment::{Adjust, Adjustment};
|
|
|
|
use rustc_middle::ty::Ty;
|
new uninlined_format_args lint to inline explicit arguments
Implement https://github.com/rust-lang/rust-clippy/issues/8368 - a new
lint to inline format arguments such as `print!("{}", var)` into
`print!("{var}")`.
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
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: [`uninlined_format_args`]: A new lint to inline format
arguments, i.e. `print!("{}", var)` into `print!("{var}")`
2022-09-14 16:25:48 +00:00
|
|
|
use rustc_semver::RustcVersion;
|
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
2021-12-06 11:33:31 +00:00
|
|
|
use rustc_span::{sym, ExpnData, ExpnKind, Span, Symbol};
|
2021-10-21 11:11:36 +00:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
|
|
|
/// ### What it does
|
|
|
|
/// Detects `format!` within the arguments of another macro that does
|
|
|
|
/// formatting such as `format!` itself, `write!` or `println!`. Suggests
|
|
|
|
/// inlining the `format!` call.
|
|
|
|
///
|
|
|
|
/// ### Why is this bad?
|
|
|
|
/// The recommended code is both shorter and avoids a temporary allocation.
|
|
|
|
///
|
|
|
|
/// ### Example
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::panic::Location;
|
|
|
|
/// println!("error: {}", format!("something failed at {}", Location::caller()));
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::panic::Location;
|
|
|
|
/// println!("error: something failed at {}", Location::caller());
|
|
|
|
/// ```
|
2021-12-06 11:33:31 +00:00
|
|
|
#[clippy::version = "1.58.0"]
|
2021-10-21 11:11:36 +00:00
|
|
|
pub FORMAT_IN_FORMAT_ARGS,
|
|
|
|
perf,
|
|
|
|
"`format!` used in a macro that does formatting"
|
|
|
|
}
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
|
|
|
/// ### What it does
|
|
|
|
/// Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string)
|
|
|
|
/// applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html)
|
|
|
|
/// in a macro that does formatting.
|
|
|
|
///
|
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Since the type implements `Display`, the use of `to_string` is
|
|
|
|
/// unnecessary.
|
|
|
|
///
|
|
|
|
/// ### Example
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::panic::Location;
|
|
|
|
/// println!("error: something failed at {}", Location::caller().to_string());
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::panic::Location;
|
|
|
|
/// println!("error: something failed at {}", Location::caller());
|
|
|
|
/// ```
|
2021-12-06 11:33:31 +00:00
|
|
|
#[clippy::version = "1.58.0"]
|
2021-10-21 11:11:36 +00:00
|
|
|
pub TO_STRING_IN_FORMAT_ARGS,
|
|
|
|
perf,
|
|
|
|
"`to_string` applied to a type that implements `Display` in format args"
|
|
|
|
}
|
|
|
|
|
new uninlined_format_args lint to inline explicit arguments
Implement https://github.com/rust-lang/rust-clippy/issues/8368 - a new
lint to inline format arguments such as `print!("{}", var)` into
`print!("{var}")`.
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
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: [`uninlined_format_args`]: A new lint to inline format
arguments, i.e. `print!("{}", var)` into `print!("{var}")`
2022-09-14 16:25:48 +00:00
|
|
|
declare_clippy_lint! {
|
|
|
|
/// ### What it does
|
|
|
|
/// Detect when a variable is not inlined in a format string,
|
|
|
|
/// and suggests to inline it.
|
|
|
|
///
|
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Non-inlined code is slightly more difficult to read and understand,
|
|
|
|
/// as it requires arguments to be matched against the format string.
|
|
|
|
/// The inlined syntax, where allowed, is simpler.
|
|
|
|
///
|
|
|
|
/// ### Example
|
|
|
|
/// ```rust
|
|
|
|
/// # let var = 42;
|
|
|
|
/// # let width = 1;
|
|
|
|
/// # let prec = 2;
|
|
|
|
/// format!("{}", var);
|
|
|
|
/// format!("{v:?}", v = var);
|
|
|
|
/// format!("{0} {0}", var);
|
|
|
|
/// format!("{0:1$}", var, width);
|
|
|
|
/// format!("{:.*}", prec, var);
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// # let var = 42;
|
|
|
|
/// # let width = 1;
|
|
|
|
/// # let prec = 2;
|
|
|
|
/// format!("{var}");
|
|
|
|
/// format!("{var:?}");
|
|
|
|
/// format!("{var} {var}");
|
|
|
|
/// format!("{var:width$}");
|
|
|
|
/// format!("{var:.prec$}");
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// ### Known Problems
|
|
|
|
///
|
|
|
|
/// There may be a false positive if the format string is expanded from certain proc macros:
|
|
|
|
///
|
|
|
|
/// ```ignore
|
|
|
|
/// println!(indoc!("{}"), var);
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// If a format string contains a numbered argument that cannot be inlined
|
|
|
|
/// nothing will be suggested, e.g. `println!("{0}={1}", var, 1+2)`.
|
|
|
|
#[clippy::version = "1.65.0"]
|
|
|
|
pub UNINLINED_FORMAT_ARGS,
|
|
|
|
pedantic,
|
|
|
|
"using non-inlined variables in `format!` calls"
|
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(FormatArgs => [FORMAT_IN_FORMAT_ARGS, UNINLINED_FORMAT_ARGS, TO_STRING_IN_FORMAT_ARGS]);
|
|
|
|
|
|
|
|
pub struct FormatArgs {
|
|
|
|
msrv: Option<RustcVersion>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FormatArgs {
|
|
|
|
#[must_use]
|
|
|
|
pub fn new(msrv: Option<RustcVersion>) -> Self {
|
|
|
|
Self { msrv }
|
|
|
|
}
|
|
|
|
}
|
2021-10-21 11:11:36 +00:00
|
|
|
|
|
|
|
impl<'tcx> LateLintPass<'tcx> for FormatArgs {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
|
|
|
|
if_chain! {
|
2022-01-13 12:18:19 +00:00
|
|
|
if let Some(format_args) = FormatArgsExpn::parse(cx, expr);
|
2021-10-21 11:11:36 +00:00
|
|
|
let expr_expn_data = expr.span.ctxt().outer_expn_data();
|
|
|
|
let outermost_expn_data = outermost_expn_data(expr_expn_data);
|
|
|
|
if let Some(macro_def_id) = outermost_expn_data.macro_def_id;
|
2022-02-26 13:26:21 +00:00
|
|
|
if is_format_macro(cx, macro_def_id);
|
2021-10-21 11:11:36 +00:00
|
|
|
if let ExpnKind::Macro(_, name) = outermost_expn_data.kind;
|
|
|
|
then {
|
2022-08-31 13:24:45 +00:00
|
|
|
for arg in &format_args.args {
|
2022-08-30 12:20:49 +00:00
|
|
|
if !arg.format.is_default() {
|
2021-10-21 11:11:36 +00:00
|
|
|
continue;
|
|
|
|
}
|
2022-08-31 13:24:45 +00:00
|
|
|
if is_aliased(&format_args, arg.param.value.hir_id) {
|
2021-10-21 11:11:36 +00:00
|
|
|
continue;
|
|
|
|
}
|
2022-08-31 13:24:45 +00:00
|
|
|
check_format_in_format_args(cx, outermost_expn_data.call_site, name, arg.param.value);
|
|
|
|
check_to_string_in_format_args(cx, name, arg.param.value);
|
2021-10-21 11:11:36 +00:00
|
|
|
}
|
new uninlined_format_args lint to inline explicit arguments
Implement https://github.com/rust-lang/rust-clippy/issues/8368 - a new
lint to inline format arguments such as `print!("{}", var)` into
`print!("{var}")`.
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
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: [`uninlined_format_args`]: A new lint to inline format
arguments, i.e. `print!("{}", var)` into `print!("{var}")`
2022-09-14 16:25:48 +00:00
|
|
|
if meets_msrv(self.msrv, msrvs::FORMAT_ARGS_CAPTURE) {
|
|
|
|
check_uninlined_args(cx, &format_args, outermost_expn_data.call_site);
|
|
|
|
}
|
2021-10-21 11:11:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
new uninlined_format_args lint to inline explicit arguments
Implement https://github.com/rust-lang/rust-clippy/issues/8368 - a new
lint to inline format arguments such as `print!("{}", var)` into
`print!("{var}")`.
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
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: [`uninlined_format_args`]: A new lint to inline format
arguments, i.e. `print!("{}", var)` into `print!("{var}")`
2022-09-14 16:25:48 +00:00
|
|
|
|
|
|
|
extract_msrv_attr!(LateContext);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_uninlined_args(cx: &LateContext<'_>, args: &FormatArgsExpn<'_>, call_site: Span) {
|
|
|
|
if args.format_string.span.from_expansion() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut fixes = Vec::new();
|
|
|
|
// If any of the arguments are referenced by an index number,
|
|
|
|
// and that argument is not a simple variable and cannot be inlined,
|
|
|
|
// we cannot remove any other arguments in the format string,
|
|
|
|
// because the index numbers might be wrong after inlining.
|
|
|
|
// Example of an un-inlinable format: print!("{}{1}", foo, 2)
|
|
|
|
if !args.params().all(|p| check_one_arg(cx, &p, &mut fixes)) || fixes.is_empty() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME: Properly ignore a rare case where the format string is wrapped in a macro.
|
|
|
|
// Example: `format!(indoc!("{}"), foo);`
|
|
|
|
// If inlined, they will cause a compilation error:
|
|
|
|
// > to avoid ambiguity, `format_args!` cannot capture variables
|
|
|
|
// > when the format string is expanded from a macro
|
|
|
|
// @Alexendoo explanation:
|
|
|
|
// > indoc! is a proc macro that is producing a string literal with its span
|
|
|
|
// > set to its input it's not marked as from expansion, and since it's compatible
|
|
|
|
// > tokenization wise clippy_utils::is_from_proc_macro wouldn't catch it either
|
|
|
|
// This might be a relatively expensive test, so do it only we are ready to replace.
|
|
|
|
// See more examples in tests/ui/uninlined_format_args.rs
|
|
|
|
|
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
UNINLINED_FORMAT_ARGS,
|
|
|
|
call_site,
|
|
|
|
"variables can be used directly in the `format!` string",
|
|
|
|
|diag| {
|
|
|
|
diag.multipart_suggestion("change this to", fixes, Applicability::MachineApplicable);
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_one_arg(cx: &LateContext<'_>, param: &FormatParam<'_>, fixes: &mut Vec<(Span, String)>) -> bool {
|
|
|
|
if matches!(param.kind, Implicit | Starred | Named(_) | Numbered)
|
|
|
|
&& let ExprKind::Path(QPath::Resolved(None, path)) = param.value.kind
|
|
|
|
&& let Path { span, segments, .. } = path
|
|
|
|
&& let [segment] = segments
|
|
|
|
{
|
|
|
|
let replacement = match param.usage {
|
|
|
|
FormatParamUsage::Argument => segment.ident.name.to_string(),
|
|
|
|
FormatParamUsage::Width => format!("{}$", segment.ident.name),
|
|
|
|
FormatParamUsage::Precision => format!(".{}$", segment.ident.name),
|
|
|
|
};
|
|
|
|
fixes.push((param.span, replacement));
|
|
|
|
let arg_span = expand_past_previous_comma(cx, *span);
|
|
|
|
fixes.push((arg_span, String::new()));
|
|
|
|
true // successful inlining, continue checking
|
|
|
|
} else {
|
|
|
|
// if we can't inline a numbered argument, we can't continue
|
|
|
|
param.kind != Numbered
|
|
|
|
}
|
2021-10-21 11:11:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn outermost_expn_data(expn_data: ExpnData) -> ExpnData {
|
|
|
|
if expn_data.call_site.from_expansion() {
|
|
|
|
outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data())
|
|
|
|
} else {
|
|
|
|
expn_data
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-13 12:18:19 +00:00
|
|
|
fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symbol, arg: &Expr<'_>) {
|
|
|
|
let expn_data = arg.span.ctxt().outer_expn_data();
|
|
|
|
if expn_data.call_site.from_expansion() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let Some(mac_id) = expn_data.macro_def_id else { return };
|
|
|
|
if !cx.tcx.is_diagnostic_item(sym::format_macro, mac_id) {
|
|
|
|
return;
|
2021-10-21 11:11:36 +00:00
|
|
|
}
|
2022-01-13 12:18:19 +00:00
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
FORMAT_IN_FORMAT_ARGS,
|
|
|
|
call_site,
|
2022-09-23 17:42:59 +00:00
|
|
|
&format!("`format!` in `{name}!` args"),
|
2022-01-13 12:18:19 +00:00
|
|
|
|diag| {
|
|
|
|
diag.help(&format!(
|
2022-09-23 17:42:59 +00:00
|
|
|
"combine the `format!(..)` arguments with the outer `{name}!(..)` call"
|
2022-01-13 12:18:19 +00:00
|
|
|
));
|
|
|
|
diag.help("or consider changing `format!` to `format_args!`");
|
|
|
|
},
|
|
|
|
);
|
2021-10-21 11:11:36 +00:00
|
|
|
}
|
|
|
|
|
2022-01-13 12:18:19 +00:00
|
|
|
fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
|
2021-10-21 11:11:36 +00:00
|
|
|
if_chain! {
|
|
|
|
if !value.span.from_expansion();
|
2022-09-01 09:43:35 +00:00
|
|
|
if let ExprKind::MethodCall(_, receiver, [], _) = value.kind;
|
2021-10-21 11:11:36 +00:00
|
|
|
if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id);
|
|
|
|
if is_diag_trait_item(cx, method_def_id, sym::ToString);
|
|
|
|
let receiver_ty = cx.typeck_results().expr_ty(receiver);
|
|
|
|
if let Some(display_trait_id) = cx.tcx.get_diagnostic_item(sym::Display);
|
2022-08-31 13:24:45 +00:00
|
|
|
let (n_needed_derefs, target) =
|
|
|
|
count_needed_derefs(receiver_ty, cx.typeck_results().expr_adjustments(receiver).iter());
|
|
|
|
if implements_trait(cx, target, display_trait_id, &[]);
|
|
|
|
if let Some(sized_trait_id) = cx.tcx.lang_items().sized_trait();
|
2021-10-21 11:11:36 +00:00
|
|
|
if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
|
|
|
|
then {
|
2022-08-31 13:24:45 +00:00
|
|
|
let needs_ref = !implements_trait(cx, receiver_ty, sized_trait_id, &[]);
|
|
|
|
if n_needed_derefs == 0 && !needs_ref {
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
TO_STRING_IN_FORMAT_ARGS,
|
|
|
|
value.span.with_lo(receiver.span.hi()),
|
|
|
|
&format!(
|
2022-09-23 17:42:59 +00:00
|
|
|
"`to_string` applied to a type that implements `Display` in `{name}!` args"
|
2022-08-31 13:24:45 +00:00
|
|
|
),
|
|
|
|
"remove this",
|
|
|
|
String::new(),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
TO_STRING_IN_FORMAT_ARGS,
|
|
|
|
value.span,
|
|
|
|
&format!(
|
2022-09-23 17:42:59 +00:00
|
|
|
"`to_string` applied to a type that implements `Display` in `{name}!` args"
|
2022-08-31 13:24:45 +00:00
|
|
|
),
|
|
|
|
"use this",
|
|
|
|
format!(
|
2022-09-23 17:42:59 +00:00
|
|
|
"{}{:*>n_needed_derefs$}{receiver_snippet}",
|
2022-08-31 13:24:45 +00:00
|
|
|
if needs_ref { "&" } else { "" },
|
2022-09-23 17:42:59 +00:00
|
|
|
""
|
2022-08-31 13:24:45 +00:00
|
|
|
),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
2021-10-21 11:11:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
new uninlined_format_args lint to inline explicit arguments
Implement https://github.com/rust-lang/rust-clippy/issues/8368 - a new
lint to inline format arguments such as `print!("{}", var)` into
`print!("{var}")`.
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
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: [`uninlined_format_args`]: A new lint to inline format
arguments, i.e. `print!("{}", var)` into `print!("{var}")`
2022-09-14 16:25:48 +00:00
|
|
|
/// Returns true if `hir_id` is referred to by multiple format params
|
2022-08-31 13:24:45 +00:00
|
|
|
fn is_aliased(args: &FormatArgsExpn<'_>, hir_id: HirId) -> bool {
|
2022-08-18 17:25:02 +00:00
|
|
|
args.params()
|
|
|
|
.filter(|param| param.value.hir_id == hir_id)
|
|
|
|
.at_most_one()
|
|
|
|
.is_err()
|
2021-10-21 11:11:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
|
|
|
|
where
|
|
|
|
I: Iterator<Item = &'tcx Adjustment<'tcx>>,
|
|
|
|
{
|
|
|
|
let mut n_total = 0;
|
|
|
|
let mut n_needed = 0;
|
|
|
|
loop {
|
|
|
|
if let Some(Adjustment {
|
|
|
|
kind: Adjust::Deref(overloaded_deref),
|
|
|
|
target,
|
|
|
|
}) = iter.next()
|
|
|
|
{
|
|
|
|
n_total += 1;
|
|
|
|
if overloaded_deref.is_some() {
|
|
|
|
n_needed = n_total;
|
|
|
|
}
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 03:13:38 +00:00
|
|
|
ty = *target;
|
2021-10-21 11:11:36 +00:00
|
|
|
} else {
|
|
|
|
return (n_needed, ty);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|