1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::fn_def_id;
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_hir::{def::Res, def_id::DefId, Crate, Expr};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use rustc_span::Symbol;
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,
16 /// and it's beneficial to lint for them as needed.
19 /// An example clippy.toml configuration:
22 /// disallowed-methods = ["std::vec::Vec::leak", "std::time::Instant::now"]
26 /// // Example code where clippy issues a warning
27 /// let xs = vec![1, 2, 3, 4];
28 /// xs.leak(); // Vec::leak is disallowed in the config.
30 /// let _now = Instant::now(); // Instant::now is disallowed in the config.
35 /// // Example code which does not raise clippy warning
36 /// let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config.
37 /// xs.push(123); // Vec::push is _not_ disallowed in the config.
39 pub DISALLOWED_METHOD,
41 "use of a disallowed method call"
44 #[derive(Clone, Debug)]
45 pub struct DisallowedMethod {
46 disallowed: FxHashSet<Vec<Symbol>>,
47 def_ids: FxHashSet<(DefId, Vec<Symbol>)>,
50 impl DisallowedMethod {
51 pub fn new(disallowed: &FxHashSet<String>) -> Self {
53 disallowed: disallowed
55 .map(|s| s.split("::").map(|seg| Symbol::intern(seg)).collect::<Vec<_>>())
57 def_ids: FxHashSet::default(),
62 impl_lint_pass!(DisallowedMethod => [DISALLOWED_METHOD]);
64 impl<'tcx> LateLintPass<'tcx> for DisallowedMethod {
65 fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
66 for path in &self.disallowed {
67 let segs = path.iter().map(ToString::to_string).collect::<Vec<_>>();
68 if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &segs.iter().map(String::as_str).collect::<Vec<_>>())
70 self.def_ids.insert((id, path.clone()));
75 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
76 if let Some(def_id) = fn_def_id(cx, expr) {
77 if self.def_ids.iter().any(|(id, _)| def_id == *id) {
78 let func_path = cx.get_def_path(def_id);
79 let func_path_string = func_path
81 .map(Symbol::to_ident_string)
89 &format!("use of a disallowed method `{}`", func_path_string),