|
| 1 | +// #![allow(unused_imports)] |
| 2 | +// #![allow(unused_variables)] |
| 3 | + |
| 4 | +// use std::fs::{create_dir_all, OpenOptions}; |
| 5 | +// use std::io::Write; |
| 6 | + |
| 7 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 8 | +use clippy_utils::macros::{FormatArgsArg, FormatArgsExpn, is_format_macro, root_macro_call_first_node}; |
| 9 | +use clippy_utils::source::{expand_past_previous_comma, snippet}; |
| 10 | +use if_chain::if_chain; |
| 11 | + |
| 12 | +use rustc_errors::Applicability; |
| 13 | +use rustc_hir::{Expr, ExprKind, Path, QPath}; |
| 14 | +use rustc_hir::def::Res; |
| 15 | +use rustc_lint::{LateContext, LateLintPass}; |
| 16 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 17 | +use rustc_span::ExpnData; |
| 18 | + |
| 19 | +declare_clippy_lint! { |
| 20 | + /// ### What it does |
| 21 | + /// |
| 22 | + /// ### Why is this bad? |
| 23 | + /// |
| 24 | + /// ### Example |
| 25 | + /// ```rust |
| 26 | + /// // example code where clippy issues a warning |
| 27 | + /// ``` |
| 28 | + /// Use instead: |
| 29 | + /// ```rust |
| 30 | + /// // example code which does not raise clippy warning |
| 31 | + /// ``` |
| 32 | + #[clippy::version = "1.64.0"] |
| 33 | + pub INLINE_FORMAT_ARGS, |
| 34 | + nursery, |
| 35 | + "default lint description" |
| 36 | +} |
| 37 | +declare_lint_pass!(InlineFormatArgs => [INLINE_FORMAT_ARGS]); |
| 38 | + |
| 39 | +impl<'tcx> LateLintPass<'tcx> for InlineFormatArgs { |
| 40 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { |
| 41 | + if_chain! { |
| 42 | + // TODO: are all these needed? They wre mostly copy/pasted from other places. |
| 43 | + if let Some(outer_macro) = root_macro_call_first_node(cx, expr); |
| 44 | + if let Some(format_args) = FormatArgsExpn::find_nested(cx, expr, outer_macro.expn); |
| 45 | + if !format_args.format_string_span.from_expansion(); |
| 46 | + let expr_expn_data = expr.span.ctxt().outer_expn_data(); |
| 47 | + let outermost_expn_data = outermost_expn_data(expr_expn_data); |
| 48 | + if let Some(macro_def_id) = outermost_expn_data.macro_def_id; |
| 49 | + if is_format_macro(cx, macro_def_id); |
| 50 | + // TODO: do we need this? |
| 51 | + // if let rustc_span::ExpnKind::Macro(_, name) = outermost_expn_data.kind; |
| 52 | + if let Some(args) = format_args.args(cx); |
| 53 | + if !args.is_empty(); |
| 54 | + then { |
| 55 | + let mut changes = None; |
| 56 | + for (i, arg) in args.iter().enumerate() { |
| 57 | + if_chain! { |
| 58 | + // If this condition is expensive, may want to move it to the end of this if chain? |
| 59 | + if arg.argument_span.is_empty() || snippet(cx, arg.argument_span, "").trim_end().is_empty(); |
| 60 | + if let ExprKind::Path(QPath::Resolved(None, Path { span, res, segments })) = arg.value.kind; |
| 61 | + if segments.len() == 1; |
| 62 | + // TODO: do we need this? |
| 63 | + if let Res::Local(_local_id) = res; |
| 64 | + if !is_aliased(&args, i); |
| 65 | + then { |
| 66 | + let c = changes.get_or_insert_with(|| vec![]); |
| 67 | + // TODO: is it ok to assume segments.len() == 1? |
| 68 | + // if not, could use this instead: |
| 69 | + // let var_name = snippet(cx, *span, "").trim_end(); |
| 70 | + // if var_name.is_empty() { continue; } |
| 71 | + let var_name = segments[0].ident.name; |
| 72 | + c.push((arg.argument_span, var_name.to_string())); |
| 73 | + let arg_span = expand_past_previous_comma(cx, *span); |
| 74 | + c.push((arg_span, "".to_string())); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + if let Some(changes) = changes { |
| 80 | + span_lint_and_then( |
| 81 | + cx, |
| 82 | + INLINE_FORMAT_ARGS, |
| 83 | + outer_macro.span, |
| 84 | + "REPLACE ME", |
| 85 | + |diag| { |
| 86 | + diag.multipart_suggestion( |
| 87 | + &format!("some interesting message"), |
| 88 | + changes, |
| 89 | + Applicability::MachineApplicable, |
| 90 | + ); |
| 91 | + }, |
| 92 | + ); |
| 93 | + } |
| 94 | + |
| 95 | +// let dumps_dir = "expected"; |
| 96 | +// create_dir_all(dumps_dir).unwrap(); |
| 97 | +// let full_str = snippet(cx, outer_macro.span, "panic").to_string() |
| 98 | +// .replace("/","--") |
| 99 | +// .replace("\t","[TAB]") |
| 100 | +// .replace("\n","[NL]") |
| 101 | +// .replace("\\","--"); |
| 102 | +// let filename = format!("{dumps_dir}/{full_str}.txt"); |
| 103 | +// let mut file = OpenOptions::new() |
| 104 | +// .write(true) |
| 105 | +// .create(true) |
| 106 | +// .truncate(true) |
| 107 | +// .open(&filename) |
| 108 | +// .unwrap(); |
| 109 | +// writeln!(file, "NAME {name:?}").unwrap(); |
| 110 | +// writeln!(file, "FMT {macro_def_id:?}").unwrap(); |
| 111 | +// for (i, part) in format_args.format_string_parts.iter().enumerate() { |
| 112 | +// writeln!(file, "FMT_PART {i} = {:?}", part).unwrap(); |
| 113 | +// } |
| 114 | +// for (i, part) in format_args.formatters.iter().enumerate() { |
| 115 | +// writeln!(file, "FORMATTERS {i} = {:?}", part).unwrap(); |
| 116 | +// } |
| 117 | +// for (i, part) in format_args.specs.iter().enumerate() { |
| 118 | +// writeln!(file, "SPECS {i} = {:#?}", part).unwrap(); |
| 119 | +// } |
| 120 | +// for (i, arg) in args.iter().enumerate() { |
| 121 | +// writeln!(file, "#{i} = TRAIT={:?}, HAS_STRFMT={:?}, ALIAS={:?}, HAS_PRIM_FMT={:?}, SPAN={:?}, ARG_SPAN={:?}, SPEC={:#?}\nVALUE={:#?}", |
| 122 | +// arg.format_trait, arg.has_string_formatting(), is_aliased(&args, i), arg.has_primitive_formatting(), |
| 123 | +// snippet(cx, arg.span, "<<<..>>>"), |
| 124 | +// snippet(cx, arg.argument_span, "<<<..>>>"), |
| 125 | +// arg.spec, arg.value).unwrap(); |
| 126 | +// } |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +// TODO: if this is a common pattern, should this be in utils? |
| 133 | +fn outermost_expn_data(expn_data: ExpnData) -> ExpnData { |
| 134 | + if expn_data.call_site.from_expansion() { |
| 135 | + outermost_expn_data(expn_data.call_site.ctxt().outer_expn_data()) |
| 136 | + } else { |
| 137 | + expn_data |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +// Returns true if `args[i]` "refers to" or "is referred to by" another argument. |
| 142 | +// TODO: this is not catching cases when the value is (also) used as precision or width |
| 143 | +fn is_aliased(args: &[FormatArgsArg<'_>], i: usize) -> bool { |
| 144 | + let value = args[i].value; |
| 145 | + args.iter() |
| 146 | + .enumerate() |
| 147 | + .any(|(j, arg)| i != j && std::ptr::eq(value, arg.value)) |
| 148 | +} |
0 commit comments