1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use if_chain::if_chain;
4 use rustc_ast::ast::LitKind;
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::symbol::sym;
10 use std::path::{Component, Path};
12 declare_clippy_lint! {
14 ///* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)
15 /// calls on `PathBuf` that can cause overwrites.
17 /// ### Why is this bad?
18 /// Calling `push` with a root path at the start can overwrite the
19 /// previous defined path.
23 /// use std::path::PathBuf;
25 /// let mut x = PathBuf::from("/foo");
27 /// assert_eq!(x, PathBuf::from("/bar"));
32 /// use std::path::PathBuf;
34 /// let mut x = PathBuf::from("/foo");
36 /// assert_eq!(x, PathBuf::from("/foo/bar"));
38 #[clippy::version = "1.36.0"]
39 pub PATH_BUF_PUSH_OVERWRITE,
41 "calling `push` with file system root on `PathBuf` can overwrite it"
44 declare_lint_pass!(PathBufPushOverwrite => [PATH_BUF_PUSH_OVERWRITE]);
46 impl<'tcx> LateLintPass<'tcx> for PathBufPushOverwrite {
47 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
49 if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
50 if path.ident.name == sym!(push);
52 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&args[0]).peel_refs(), sym::PathBuf);
53 if let Some(get_index_arg) = args.get(1);
54 if let ExprKind::Lit(ref lit) = get_index_arg.kind;
55 if let LitKind::Str(ref path_lit, _) = lit.node;
56 if let pushed_path = Path::new(&*path_lit.as_str());
57 if let Some(pushed_path_lit) = pushed_path.to_str();
58 if pushed_path.has_root();
59 if let Some(root) = pushed_path.components().next();
60 if root == Component::RootDir;
64 PATH_BUF_PUSH_OVERWRITE,
66 "calling `push` with '/' or '\\' (file system root) will overwrite the previous path definition",
68 format!("\"{}\"", pushed_path_lit.trim_start_matches(|c| c == '/' || c == '\\')),
69 Applicability::MachineApplicable,