1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::fn_def_id;
4 use rustc_hir::{def::Res, def_id::DefIdMap, Expr};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use crate::utils::conf;
10 declare_clippy_lint! {
12 /// Denies the configured methods and functions in clippy.toml
14 /// ### Why is this bad?
15 /// Some methods are undesirable in certain contexts, and it's beneficial to
16 /// lint for them as needed.
19 /// An example clippy.toml configuration:
22 /// disallowed-methods = [
23 /// # Can use a string as the path of the disallowed method.
24 /// "std::boxed::Box::new",
25 /// # Can also use an inline table with a `path` key.
26 /// { path = "std::time::Instant::now" },
27 /// # When using an inline table, can add a `reason` for why the method
29 /// { path = "std::vec::Vec::leak", reason = "no leaking memory" },
34 /// // Example code where clippy issues a warning
35 /// let xs = vec![1, 2, 3, 4];
36 /// xs.leak(); // Vec::leak is disallowed in the config.
37 /// // The diagnostic contains the message "no leaking memory".
39 /// let _now = Instant::now(); // Instant::now is disallowed in the config.
41 /// let _box = Box::new(3); // Box::new is disallowed in the config.
46 /// // Example code which does not raise clippy warning
47 /// let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config.
48 /// xs.push(123); // Vec::push is _not_ disallowed in the config.
50 #[clippy::version = "1.49.0"]
51 pub DISALLOWED_METHODS,
53 "use of a disallowed method call"
56 #[derive(Clone, Debug)]
57 pub struct DisallowedMethods {
58 conf_disallowed: Vec<conf::DisallowedMethod>,
59 disallowed: DefIdMap<Option<String>>,
62 impl DisallowedMethods {
63 pub fn new(conf_disallowed: Vec<conf::DisallowedMethod>) -> Self {
66 disallowed: DefIdMap::default(),
71 impl_lint_pass!(DisallowedMethods => [DISALLOWED_METHODS]);
73 impl<'tcx> LateLintPass<'tcx> for DisallowedMethods {
74 fn check_crate(&mut self, cx: &LateContext<'_>) {
75 for conf in &self.conf_disallowed {
76 let (path, reason) = match conf {
77 conf::DisallowedMethod::Simple(path) => (path, None),
78 conf::DisallowedMethod::WithReason { path, reason } => (
80 reason.as_ref().map(|reason| format!("{} (from clippy.toml)", reason)),
83 let segs: Vec<_> = path.split("::").collect();
84 if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &segs) {
85 self.disallowed.insert(id, reason);
90 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
91 let def_id = match fn_def_id(cx, expr) {
92 Some(def_id) => def_id,
95 let reason = match self.disallowed.get(&def_id) {
96 Some(reason) => reason,
99 let func_path = cx.tcx.def_path_str(def_id);
100 let msg = format!("use of a disallowed method `{}`", func_path);
101 span_lint_and_then(cx, DISALLOWED_METHODS, expr.span, &msg, |diag| {
102 if let Some(reason) = reason {