|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::macros::{root_macro_call, FormatArgsExpn}; |
| 3 | +use clippy_utils::sugg::Sugg; |
| 4 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 5 | +use rustc_errors::Applicability; |
| 6 | +use rustc_hir::{Expr, ExprKind}; |
| 7 | +use rustc_lint::{LateContext, LateLintPass}; |
| 8 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 9 | +use rustc_span::sym; |
| 10 | +use std::fmt::Write as _; |
| 11 | +use std::path::Path; |
| 12 | + |
| 13 | +declare_clippy_lint! { |
| 14 | + /// ### What it does |
| 15 | + /// Checks for `PathBuf::from(format!(..))` calls. |
| 16 | + /// |
| 17 | + /// ### Why is this bad? |
| 18 | + /// It is not OS-agnostic, and can be harder to read. |
| 19 | + /// |
| 20 | + /// ### Known Problems |
| 21 | + /// `.join()` introduces additional allocations that are not present when `PathBuf::push` is |
| 22 | + /// used instead. |
| 23 | + /// |
| 24 | + /// ### Example |
| 25 | + /// ```rust |
| 26 | + /// use std::path::PathBuf; |
| 27 | + /// let base_path = "/base"; |
| 28 | + /// PathBuf::from(format!("{}/foo/bar", base_path)); |
| 29 | + /// ``` |
| 30 | + /// Use instead: |
| 31 | + /// ```rust |
| 32 | + /// use std::path::Path; |
| 33 | + /// let base_path = "/base"; |
| 34 | + /// Path::new(&base_path).join("foo").join("bar"); |
| 35 | + /// ``` |
| 36 | + #[clippy::version = "1.62.0"] |
| 37 | + pub PATHS_FROM_FORMAT, |
| 38 | + pedantic, |
| 39 | + "builds a `PathBuf` from a format macro" |
| 40 | +} |
| 41 | + |
| 42 | +declare_lint_pass!(PathsFromFormat => [PATHS_FROM_FORMAT]); |
| 43 | + |
| 44 | +impl<'tcx> LateLintPass<'tcx> for PathsFromFormat { |
| 45 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { |
| 46 | + if_chain! { |
| 47 | + if let ExprKind::Call(_, args) = expr.kind; |
| 48 | + if let ty = cx.typeck_results().expr_ty(expr); |
| 49 | + if is_type_diagnostic_item(cx, ty, sym::PathBuf); |
| 50 | + if !args.is_empty(); |
| 51 | + if let Some(macro_call) = root_macro_call(args[0].span); |
| 52 | + if cx.tcx.item_name(macro_call.def_id) == sym::format; |
| 53 | + if let Some(format_args) = FormatArgsExpn::find_nested(cx, &args[0], macro_call.expn); |
| 54 | + then { |
| 55 | + let format_string_parts = format_args.format_string.parts; |
| 56 | + let format_value_args = format_args.args; |
| 57 | + let string_parts: Vec<&str> = format_string_parts.iter().map(rustc_span::Symbol::as_str).collect(); |
| 58 | + let mut applicability = Applicability::MachineApplicable; |
| 59 | + let real_vars: Vec<Sugg<'_>> = format_value_args.iter().map(|x| Sugg::hir_with_applicability(cx, x.param.value, "..", &mut applicability)).collect(); |
| 60 | + let mut paths_zip = string_parts.iter().take(real_vars.len()).zip(real_vars.clone()); |
| 61 | + let mut sugg = String::new(); |
| 62 | + if let Some((part, arg)) = paths_zip.next() { |
| 63 | + if is_valid_use_case(string_parts.first().unwrap_or(&""), string_parts.get(1).unwrap_or(&"")) { |
| 64 | + return; |
| 65 | + } |
| 66 | + if part.is_empty() { |
| 67 | + sugg = format!("Path::new(&{arg})"); |
| 68 | + } |
| 69 | + else { |
| 70 | + push_comps(&mut sugg, part); |
| 71 | + let _ = write!(sugg, ".join(&{arg})"); |
| 72 | + } |
| 73 | + } |
| 74 | + for n in 1..real_vars.len() { |
| 75 | + if let Some((part, arg)) = paths_zip.next() { |
| 76 | + if is_valid_use_case(string_parts.get(n).unwrap_or(&""), string_parts.get(n+1).unwrap_or(&"")) { |
| 77 | + return; |
| 78 | + } |
| 79 | + else if n < real_vars.len() { |
| 80 | + push_comps(&mut sugg, part); |
| 81 | + let _ = write!(sugg, ".join(&{arg})"); |
| 82 | + } |
| 83 | + else { |
| 84 | + sugg = format!("{sugg}.join(&{arg})"); |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + if real_vars.len() < string_parts.len() { |
| 89 | + push_comps(&mut sugg, string_parts[real_vars.len()]); |
| 90 | + } |
| 91 | + span_lint_and_sugg( |
| 92 | + cx, |
| 93 | + PATHS_FROM_FORMAT, |
| 94 | + expr.span, |
| 95 | + "`format!(..)` used to form `PathBuf`", |
| 96 | + "consider using `Path::new()` and `.join()` to make it OS-agnostic and improve code readability", |
| 97 | + sugg, |
| 98 | + Applicability::MaybeIncorrect, |
| 99 | + ); |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +fn push_comps(string: &mut String, path: &str) { |
| 106 | + let mut path = path.to_string(); |
| 107 | + if !string.is_empty() { |
| 108 | + path = path.trim_start_matches(|c| c == '\\' || c == '/').to_string(); |
| 109 | + } |
| 110 | + for n in Path::new(&path).components() { |
| 111 | + let mut x = n.as_os_str().to_string_lossy().to_string(); |
| 112 | + if string.is_empty() { |
| 113 | + let _ = write!(string, "Path::new(\"{x}\")"); |
| 114 | + } else { |
| 115 | + x = x.trim_end_matches(|c| c == '/' || c == '\\').to_string(); |
| 116 | + let _ = write!(string, ".join(\"{x}\")"); |
| 117 | + } |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +fn is_valid_use_case(string: &str, string2: &str) -> bool { |
| 122 | + !(string.is_empty() || string.ends_with('/') || string.ends_with('\\')) |
| 123 | + || !(string2.is_empty() || string2.starts_with('/') || string2.starts_with('\\')) |
| 124 | +} |
0 commit comments