2023-04-11 08:31:08 -05:00
|
|
|
use arrayvec::ArrayVec;
|
2021-10-21 06:11:36 -05:00
|
|
|
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
|
2022-12-01 11:29:38 -06:00
|
|
|
use clippy_utils::is_diag_trait_item;
|
2022-10-23 08:18:45 -05:00
|
|
|
use clippy_utils::macros::{
|
2023-04-11 08:31:08 -05:00
|
|
|
find_format_arg_expr, find_format_args, format_arg_removal_span, format_placeholder_format_span, is_assert_macro,
|
|
|
|
is_format_macro, is_panic, root_macro_call, root_macro_call_first_node, FormatParamUsage,
|
2022-10-23 08:18:45 -05:00
|
|
|
};
|
2022-12-01 11:29:38 -06:00
|
|
|
use clippy_utils::msrvs::{self, Msrv};
|
2021-10-21 06:11:36 -05:00
|
|
|
use clippy_utils::source::snippet_opt;
|
2023-01-11 17:25:09 -06:00
|
|
|
use clippy_utils::ty::{implements_trait, is_type_lang_item};
|
2021-10-21 06:11:36 -05:00
|
|
|
use if_chain::if_chain;
|
2022-08-31 08:24:45 -05:00
|
|
|
use itertools::Itertools;
|
2023-04-11 08:31:08 -05:00
|
|
|
use rustc_ast::{
|
|
|
|
FormatArgPosition, FormatArgPositionKind, FormatArgsPiece, FormatArgumentKind, FormatCount, FormatOptions,
|
|
|
|
FormatPlaceholder, FormatTrait,
|
|
|
|
};
|
2022-12-01 11:29:38 -06:00
|
|
|
use rustc_errors::{
|
|
|
|
Applicability,
|
|
|
|
SuggestionStyle::{CompletelyHidden, ShowCode},
|
|
|
|
};
|
2023-04-11 08:31:08 -05:00
|
|
|
use rustc_hir::{Expr, ExprKind, LangItem};
|
2022-10-06 10:41:53 -05:00
|
|
|
use rustc_lint::{LateContext, LateLintPass, LintContext};
|
2021-10-21 06:11:36 -05:00
|
|
|
use rustc_middle::ty::adjustment::{Adjust, Adjustment};
|
|
|
|
use rustc_middle::ty::Ty;
|
2022-10-06 02:44:38 -05:00
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
2022-10-23 08:18:45 -05:00
|
|
|
use rustc_span::def_id::DefId;
|
|
|
|
use rustc_span::edition::Edition::Edition2021;
|
2023-04-11 08:31:08 -05:00
|
|
|
use rustc_span::{sym, Span, Symbol};
|
2021-10-21 06:11:36 -05: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 05:33:31 -06:00
|
|
|
#[clippy::version = "1.58.0"]
|
2021-10-21 06:11:36 -05: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 05:33:31 -06:00
|
|
|
#[clippy::version = "1.58.0"]
|
2021-10-21 06:11:36 -05:00
|
|
|
pub TO_STRING_IN_FORMAT_ARGS,
|
|
|
|
perf,
|
|
|
|
"`to_string` applied to a type that implements `Display` in format args"
|
|
|
|
}
|
|
|
|
|
2022-10-06 02:44:38 -05: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$}");
|
|
|
|
/// ```
|
|
|
|
///
|
2022-12-01 11:29:38 -06:00
|
|
|
/// If allow-mixed-uninlined-format-args is set to false in clippy.toml,
|
|
|
|
/// the following code will also trigger the lint:
|
|
|
|
/// ```rust
|
|
|
|
/// # let var = 42;
|
|
|
|
/// format!("{} {}", var, 1+2);
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// # let var = 42;
|
|
|
|
/// format!("{var} {}", 1+2);
|
2022-10-06 02:44:38 -05:00
|
|
|
/// ```
|
|
|
|
///
|
2022-12-01 11:29:38 -06:00
|
|
|
/// ### Known Problems
|
|
|
|
///
|
2022-10-06 02:44:38 -05:00
|
|
|
/// If a format string contains a numbered argument that cannot be inlined
|
|
|
|
/// nothing will be suggested, e.g. `println!("{0}={1}", var, 1+2)`.
|
2022-12-17 07:12:54 -06:00
|
|
|
#[clippy::version = "1.66.0"]
|
2022-10-06 02:44:38 -05:00
|
|
|
pub UNINLINED_FORMAT_ARGS,
|
2023-02-10 07:01:19 -06:00
|
|
|
pedantic,
|
2022-10-06 02:44:38 -05:00
|
|
|
"using non-inlined variables in `format!` calls"
|
|
|
|
}
|
|
|
|
|
2022-10-23 08:18:45 -05:00
|
|
|
declare_clippy_lint! {
|
|
|
|
/// ### What it does
|
|
|
|
/// Detects [formatting parameters] that have no effect on the output of
|
|
|
|
/// `format!()`, `println!()` or similar macros.
|
|
|
|
///
|
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Shorter format specifiers are easier to read, it may also indicate that
|
|
|
|
/// an expected formatting operation such as adding padding isn't happening.
|
|
|
|
///
|
|
|
|
/// ### Example
|
|
|
|
/// ```rust
|
|
|
|
/// println!("{:.}", 1.0);
|
|
|
|
///
|
|
|
|
/// println!("not padded: {:5}", format_args!("..."));
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// println!("{}", 1.0);
|
|
|
|
///
|
|
|
|
/// println!("not padded: {}", format_args!("..."));
|
|
|
|
/// // OR
|
|
|
|
/// println!("padded: {:5}", format!("..."));
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// [formatting parameters]: https://doc.rust-lang.org/std/fmt/index.html#formatting-parameters
|
|
|
|
#[clippy::version = "1.66.0"]
|
|
|
|
pub UNUSED_FORMAT_SPECS,
|
|
|
|
complexity,
|
|
|
|
"use of a format specifier that has no effect"
|
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(FormatArgs => [
|
|
|
|
FORMAT_IN_FORMAT_ARGS,
|
|
|
|
TO_STRING_IN_FORMAT_ARGS,
|
|
|
|
UNINLINED_FORMAT_ARGS,
|
|
|
|
UNUSED_FORMAT_SPECS,
|
|
|
|
]);
|
2022-10-06 02:44:38 -05:00
|
|
|
|
|
|
|
pub struct FormatArgs {
|
2022-12-01 11:29:38 -06:00
|
|
|
msrv: Msrv,
|
|
|
|
ignore_mixed: bool,
|
2022-10-06 02:44:38 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl FormatArgs {
|
|
|
|
#[must_use]
|
2022-12-01 11:29:38 -06:00
|
|
|
pub fn new(msrv: Msrv, allow_mixed_uninlined_format_args: bool) -> Self {
|
|
|
|
Self {
|
|
|
|
msrv,
|
|
|
|
ignore_mixed: allow_mixed_uninlined_format_args,
|
|
|
|
}
|
2022-10-06 02:44:38 -05:00
|
|
|
}
|
|
|
|
}
|
2021-10-21 06:11:36 -05:00
|
|
|
|
|
|
|
impl<'tcx> LateLintPass<'tcx> for FormatArgs {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
|
2023-04-11 08:31:08 -05:00
|
|
|
let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return };
|
|
|
|
if !is_format_macro(cx, macro_call.def_id) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let name = cx.tcx.item_name(macro_call.def_id);
|
|
|
|
|
|
|
|
find_format_args(cx, expr, macro_call.expn, |format_args| {
|
|
|
|
for piece in &format_args.template {
|
|
|
|
if let FormatArgsPiece::Placeholder(placeholder) = piece
|
|
|
|
&& let Ok(index) = placeholder.argument.index
|
|
|
|
&& let Some(arg) = format_args.arguments.all_args().get(index)
|
|
|
|
{
|
|
|
|
let arg_expr = find_format_arg_expr(expr, arg);
|
|
|
|
|
|
|
|
check_unused_format_specifier(cx, placeholder, arg_expr);
|
|
|
|
|
|
|
|
if placeholder.format_trait != FormatTrait::Display
|
|
|
|
|| placeholder.format_options != FormatOptions::default()
|
|
|
|
|| is_aliased(format_args, index)
|
|
|
|
{
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Ok(arg_hir_expr) = arg_expr {
|
|
|
|
check_format_in_format_args(cx, macro_call.span, name, arg_hir_expr);
|
|
|
|
check_to_string_in_format_args(cx, name, arg_hir_expr);
|
|
|
|
}
|
2022-10-06 02:44:38 -05:00
|
|
|
}
|
2022-10-23 08:18:45 -05:00
|
|
|
}
|
2023-04-11 08:31:08 -05:00
|
|
|
|
2022-12-01 11:29:38 -06:00
|
|
|
if self.msrv.meets(msrvs::FORMAT_ARGS_CAPTURE) {
|
2023-04-11 08:31:08 -05:00
|
|
|
check_uninlined_args(cx, format_args, macro_call.span, macro_call.def_id, self.ignore_mixed);
|
2021-10-21 06:11:36 -05:00
|
|
|
}
|
2023-04-11 08:31:08 -05:00
|
|
|
});
|
2021-10-21 06:11:36 -05:00
|
|
|
}
|
2022-10-06 02:44:38 -05:00
|
|
|
|
|
|
|
extract_msrv_attr!(LateContext);
|
|
|
|
}
|
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
fn check_unused_format_specifier(
|
|
|
|
cx: &LateContext<'_>,
|
|
|
|
placeholder: &FormatPlaceholder,
|
|
|
|
arg_expr: Result<&Expr<'_>, &rustc_ast::Expr>,
|
|
|
|
) {
|
|
|
|
let ty_or_ast_expr = arg_expr.map(|expr| cx.typeck_results().expr_ty(expr).peel_refs());
|
2022-10-23 08:18:45 -05:00
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
let is_format_args = match ty_or_ast_expr {
|
|
|
|
Ok(ty) => is_type_lang_item(cx, ty, LangItem::FormatArguments),
|
|
|
|
Err(expr) => matches!(expr.peel_parens_and_refs().kind, rustc_ast::ExprKind::FormatArgs(_)),
|
|
|
|
};
|
2022-10-23 08:18:45 -05:00
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
let options = &placeholder.format_options;
|
2022-10-23 08:18:45 -05:00
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
let arg_span = match arg_expr {
|
|
|
|
Ok(expr) => expr.span,
|
|
|
|
Err(expr) => expr.span,
|
|
|
|
};
|
2022-10-23 08:18:45 -05:00
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
if let Some(placeholder_span) = placeholder.span
|
|
|
|
&& is_format_args
|
|
|
|
&& *options != FormatOptions::default()
|
|
|
|
{
|
2022-10-23 08:18:45 -05:00
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
UNUSED_FORMAT_SPECS,
|
2023-04-11 08:31:08 -05:00
|
|
|
placeholder_span,
|
2022-10-23 08:18:45 -05:00
|
|
|
"format specifiers have no effect on `format_args!()`",
|
|
|
|
|diag| {
|
2023-04-11 08:31:08 -05:00
|
|
|
let mut suggest_format = |spec| {
|
2022-10-23 08:18:45 -05:00
|
|
|
let message = format!("for the {spec} to apply consider using `format!()`");
|
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
if let Some(mac_call) = root_macro_call(arg_span)
|
2022-10-23 08:18:45 -05:00
|
|
|
&& cx.tcx.is_diagnostic_item(sym::format_args_macro, mac_call.def_id)
|
|
|
|
{
|
|
|
|
diag.span_suggestion(
|
|
|
|
cx.sess().source_map().span_until_char(mac_call.span, '!'),
|
|
|
|
message,
|
|
|
|
"format",
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
);
|
2023-04-11 08:31:08 -05:00
|
|
|
} else {
|
|
|
|
diag.help(message);
|
2022-10-23 08:18:45 -05:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
if options.width.is_some() {
|
|
|
|
suggest_format("width");
|
2022-10-23 08:18:45 -05:00
|
|
|
}
|
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
if options.precision.is_some() {
|
|
|
|
suggest_format("precision");
|
2022-10-23 08:18:45 -05:00
|
|
|
}
|
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
if let Some(format_span) = format_placeholder_format_span(placeholder) {
|
|
|
|
diag.span_suggestion_verbose(
|
|
|
|
format_span,
|
|
|
|
"if the current behavior is intentional, remove the format specifiers",
|
|
|
|
"",
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
);
|
|
|
|
}
|
2022-10-23 08:18:45 -05:00
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-01 11:29:38 -06:00
|
|
|
fn check_uninlined_args(
|
|
|
|
cx: &LateContext<'_>,
|
2023-04-11 08:31:08 -05:00
|
|
|
args: &rustc_ast::FormatArgs,
|
2022-12-01 11:29:38 -06:00
|
|
|
call_site: Span,
|
|
|
|
def_id: DefId,
|
|
|
|
ignore_mixed: bool,
|
|
|
|
) {
|
2023-04-11 08:31:08 -05:00
|
|
|
if args.span.from_expansion() {
|
2022-10-06 02:44:38 -05:00
|
|
|
return;
|
|
|
|
}
|
2022-12-17 07:12:54 -06:00
|
|
|
if call_site.edition() < Edition2021 && (is_panic(cx, def_id) || is_assert_macro(cx, def_id)) {
|
|
|
|
// panic!, assert!, and debug_assert! before 2021 edition considers a single string argument as
|
|
|
|
// non-format
|
2022-10-23 08:18:45 -05:00
|
|
|
return;
|
|
|
|
}
|
2022-10-06 02:44:38 -05:00
|
|
|
|
|
|
|
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)
|
2023-04-11 08:31:08 -05:00
|
|
|
for (pos, usage) in format_arg_positions(args) {
|
|
|
|
if !check_one_arg(args, pos, usage, &mut fixes, ignore_mixed) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if fixes.is_empty() {
|
2022-10-06 02:44:38 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-12-01 11:29:38 -06:00
|
|
|
// multiline span display suggestion is sometimes broken: https://github.com/rust-lang/rust/pull/102729#discussion_r988704308
|
|
|
|
// in those cases, make the code suggestion hidden
|
|
|
|
let multiline_fix = fixes.iter().any(|(span, _)| cx.sess().source_map().is_multiline(*span));
|
2022-10-06 02:44:38 -05:00
|
|
|
|
2023-01-19 14:45:38 -06:00
|
|
|
// Suggest removing each argument only once, for example in `format!("{0} {0}", arg)`.
|
|
|
|
fixes.sort_unstable_by_key(|(span, _)| *span);
|
|
|
|
fixes.dedup_by_key(|(span, _)| *span);
|
|
|
|
|
2022-10-06 02:44:38 -05:00
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
UNINLINED_FORMAT_ARGS,
|
|
|
|
call_site,
|
|
|
|
"variables can be used directly in the `format!` string",
|
|
|
|
|diag| {
|
2022-12-01 11:29:38 -06:00
|
|
|
diag.multipart_suggestion_with_style(
|
|
|
|
"change this to",
|
|
|
|
fixes,
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
if multiline_fix { CompletelyHidden } else { ShowCode },
|
|
|
|
);
|
2022-10-06 02:44:38 -05:00
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-12-01 11:29:38 -06:00
|
|
|
fn check_one_arg(
|
2023-04-11 08:31:08 -05:00
|
|
|
args: &rustc_ast::FormatArgs,
|
|
|
|
pos: &FormatArgPosition,
|
|
|
|
usage: FormatParamUsage,
|
2022-12-01 11:29:38 -06:00
|
|
|
fixes: &mut Vec<(Span, String)>,
|
|
|
|
ignore_mixed: bool,
|
|
|
|
) -> bool {
|
2023-04-11 08:31:08 -05:00
|
|
|
let index = pos.index.unwrap();
|
|
|
|
let arg = &args.arguments.all_args()[index];
|
|
|
|
|
|
|
|
if !matches!(arg.kind, FormatArgumentKind::Captured(_))
|
|
|
|
&& let rustc_ast::ExprKind::Path(None, path) = &arg.expr.kind
|
|
|
|
&& let [segment] = path.segments.as_slice()
|
2023-02-25 18:08:29 -06:00
|
|
|
&& segment.args.is_none()
|
2023-04-11 08:31:08 -05:00
|
|
|
&& let Some(arg_span) = format_arg_removal_span(args, index)
|
|
|
|
&& let Some(pos_span) = pos.span
|
2022-10-06 02:44:38 -05:00
|
|
|
{
|
2023-04-11 08:31:08 -05:00
|
|
|
let replacement = match usage {
|
2022-10-06 02:44:38 -05:00
|
|
|
FormatParamUsage::Argument => segment.ident.name.to_string(),
|
|
|
|
FormatParamUsage::Width => format!("{}$", segment.ident.name),
|
|
|
|
FormatParamUsage::Precision => format!(".{}$", segment.ident.name),
|
|
|
|
};
|
2023-04-11 08:31:08 -05:00
|
|
|
fixes.push((pos_span, replacement));
|
2022-10-06 02:44:38 -05:00
|
|
|
fixes.push((arg_span, String::new()));
|
|
|
|
true // successful inlining, continue checking
|
|
|
|
} else {
|
2022-12-01 11:29:38 -06:00
|
|
|
// Do not continue inlining (return false) in case
|
|
|
|
// * if we can't inline a numbered argument, e.g. `print!("{0} ...", foo.bar, ...)`
|
|
|
|
// * if allow_mixed_uninlined_format_args is false and this arg hasn't been inlined already
|
2023-04-11 08:31:08 -05:00
|
|
|
pos.kind != FormatArgPositionKind::Number
|
|
|
|
&& (!ignore_mixed || matches!(arg.kind, FormatArgumentKind::Captured(_)))
|
2021-10-21 06:11:36 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symbol, arg: &Expr<'_>) {
|
2022-01-13 06:18:19 -06:00
|
|
|
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 06:11:36 -05:00
|
|
|
}
|
2022-01-13 06:18:19 -06:00
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
FORMAT_IN_FORMAT_ARGS,
|
|
|
|
call_site,
|
2022-10-06 02:44:38 -05:00
|
|
|
&format!("`format!` in `{name}!` args"),
|
2022-01-13 06:18:19 -06:00
|
|
|
|diag| {
|
2022-12-29 07:28:34 -06:00
|
|
|
diag.help(format!(
|
2022-10-06 02:44:38 -05:00
|
|
|
"combine the `format!(..)` arguments with the outer `{name}!(..)` call"
|
2022-01-13 06:18:19 -06:00
|
|
|
));
|
|
|
|
diag.help("or consider changing `format!` to `format_args!`");
|
|
|
|
},
|
|
|
|
);
|
2021-10-21 06:11:36 -05:00
|
|
|
}
|
|
|
|
|
2022-01-13 06:18:19 -06:00
|
|
|
fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Expr<'_>) {
|
2021-10-21 06:11:36 -05:00
|
|
|
if_chain! {
|
|
|
|
if !value.span.from_expansion();
|
2022-10-23 08:18:45 -05:00
|
|
|
if let ExprKind::MethodCall(_, receiver, [], to_string_span) = value.kind;
|
2021-10-21 06:11:36 -05: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 08:24:45 -05: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 06:11:36 -05:00
|
|
|
if let Some(receiver_snippet) = snippet_opt(cx, receiver.span);
|
|
|
|
then {
|
2022-08-31 08:24:45 -05: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,
|
2022-10-23 08:18:45 -05:00
|
|
|
to_string_span.with_lo(receiver.span.hi()),
|
2022-08-31 08:24:45 -05:00
|
|
|
&format!(
|
2022-10-06 02:44:38 -05:00
|
|
|
"`to_string` applied to a type that implements `Display` in `{name}!` args"
|
2022-08-31 08:24:45 -05:00
|
|
|
),
|
|
|
|
"remove this",
|
|
|
|
String::new(),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
TO_STRING_IN_FORMAT_ARGS,
|
|
|
|
value.span,
|
|
|
|
&format!(
|
2022-10-06 02:44:38 -05:00
|
|
|
"`to_string` applied to a type that implements `Display` in `{name}!` args"
|
2022-08-31 08:24:45 -05:00
|
|
|
),
|
|
|
|
"use this",
|
|
|
|
format!(
|
2022-10-06 02:44:38 -05:00
|
|
|
"{}{:*>n_needed_derefs$}{receiver_snippet}",
|
2022-08-31 08:24:45 -05:00
|
|
|
if needs_ref { "&" } else { "" },
|
2022-10-06 02:44:38 -05:00
|
|
|
""
|
2022-08-31 08:24:45 -05:00
|
|
|
),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
2021-10-21 06:11:36 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-11 08:31:08 -05:00
|
|
|
fn format_arg_positions(
|
|
|
|
format_args: &rustc_ast::FormatArgs,
|
|
|
|
) -> impl Iterator<Item = (&FormatArgPosition, FormatParamUsage)> {
|
|
|
|
format_args.template.iter().flat_map(|piece| match piece {
|
|
|
|
FormatArgsPiece::Placeholder(placeholder) => {
|
|
|
|
let mut positions = ArrayVec::<_, 3>::new();
|
|
|
|
|
|
|
|
positions.push((&placeholder.argument, FormatParamUsage::Argument));
|
|
|
|
if let Some(FormatCount::Argument(position)) = &placeholder.format_options.width {
|
|
|
|
positions.push((position, FormatParamUsage::Width));
|
|
|
|
}
|
|
|
|
if let Some(FormatCount::Argument(position)) = &placeholder.format_options.precision {
|
|
|
|
positions.push((position, FormatParamUsage::Precision));
|
|
|
|
}
|
|
|
|
|
|
|
|
positions
|
|
|
|
},
|
|
|
|
FormatArgsPiece::Literal(_) => ArrayVec::new(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns true if the format argument at `index` is referred to by multiple format params
|
|
|
|
fn is_aliased(format_args: &rustc_ast::FormatArgs, index: usize) -> bool {
|
|
|
|
format_arg_positions(format_args)
|
|
|
|
.filter(|(position, _)| position.index == Ok(index))
|
|
|
|
.at_most_one()
|
|
|
|
.is_err()
|
2021-10-21 06:11:36 -05: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 {
|
2023-04-11 08:31:08 -05:00
|
|
|
if let Some(Adjustment {
|
|
|
|
kind: Adjust::Deref(overloaded_deref),
|
|
|
|
target,
|
|
|
|
}) = iter.next()
|
|
|
|
{
|
2021-10-21 06:11:36 -05:00
|
|
|
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-24 21:13:38 -06:00
|
|
|
ty = *target;
|
2021-10-21 06:11:36 -05:00
|
|
|
} else {
|
|
|
|
return (n_needed, ty);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|