Skip to content

Commit 36e6469

Browse files
committed
Auto merge of rust-lang#7621 - azdavis:master, r=camsteffen
Allow giving reasons for `disallowed_methods` Fixes rust-lang#7609. This permits writing the config for `disallowed-methods` as either a list of strings (like before) or a list of tables, where each table gives the path to the disallowed method and an optional reason for why the method is disallowed. changelog: Allow giving reasons for [`disallowed_methods`]
2 parents 27afd6a + 293db0d commit 36e6469

File tree

5 files changed

+69
-44
lines changed

5 files changed

+69
-44
lines changed

clippy_lints/src/disallowed_method.rs

+48-36
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,44 @@
1-
use clippy_utils::diagnostics::span_lint;
1+
use clippy_utils::diagnostics::span_lint_and_then;
22
use clippy_utils::fn_def_id;
33

4-
use rustc_data_structures::fx::FxHashSet;
5-
use rustc_hir::{def::Res, def_id::DefId, Crate, Expr};
4+
use rustc_hir::{def::Res, def_id::DefIdMap, Crate, Expr};
65
use rustc_lint::{LateContext, LateLintPass};
76
use rustc_session::{declare_tool_lint, impl_lint_pass};
8-
use rustc_span::Symbol;
7+
8+
use crate::utils::conf;
99

1010
declare_clippy_lint! {
1111
/// ### What it does
1212
/// Denies the configured methods and functions in clippy.toml
1313
///
1414
/// ### Why is this bad?
15-
/// Some methods are undesirable in certain contexts,
16-
/// and it's beneficial to lint for them as needed.
15+
/// Some methods are undesirable in certain contexts, and it's beneficial to
16+
/// lint for them as needed.
1717
///
1818
/// ### Example
1919
/// An example clippy.toml configuration:
2020
/// ```toml
2121
/// # clippy.toml
22-
/// disallowed-methods = ["std::vec::Vec::leak", "std::time::Instant::now"]
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
28+
/// # is disallowed.
29+
/// { path = "std::vec::Vec::leak", reason = "no leaking memory" },
30+
/// ]
2331
/// ```
2432
///
2533
/// ```rust,ignore
2634
/// // Example code where clippy issues a warning
2735
/// let xs = vec![1, 2, 3, 4];
2836
/// xs.leak(); // Vec::leak is disallowed in the config.
37+
/// // The diagnostic contains the message "no leaking memory".
2938
///
3039
/// let _now = Instant::now(); // Instant::now is disallowed in the config.
40+
///
41+
/// let _box = Box::new(3); // Box::new is disallowed in the config.
3142
/// ```
3243
///
3344
/// Use instead:
@@ -43,18 +54,15 @@ declare_clippy_lint! {
4354

4455
#[derive(Clone, Debug)]
4556
pub struct DisallowedMethod {
46-
disallowed: FxHashSet<Vec<Symbol>>,
47-
def_ids: FxHashSet<(DefId, Vec<Symbol>)>,
57+
conf_disallowed: Vec<conf::DisallowedMethod>,
58+
disallowed: DefIdMap<Option<String>>,
4859
}
4960

5061
impl DisallowedMethod {
51-
pub fn new(disallowed: &FxHashSet<String>) -> Self {
62+
pub fn new(conf_disallowed: Vec<conf::DisallowedMethod>) -> Self {
5263
Self {
53-
disallowed: disallowed
54-
.iter()
55-
.map(|s| s.split("::").map(|seg| Symbol::intern(seg)).collect::<Vec<_>>())
56-
.collect(),
57-
def_ids: FxHashSet::default(),
64+
conf_disallowed,
65+
disallowed: DefIdMap::default(),
5866
}
5967
}
6068
}
@@ -63,32 +71,36 @@ impl_lint_pass!(DisallowedMethod => [DISALLOWED_METHOD]);
6371

6472
impl<'tcx> LateLintPass<'tcx> for DisallowedMethod {
6573
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<_>>())
69-
{
70-
self.def_ids.insert((id, path.clone()));
74+
for conf in &self.conf_disallowed {
75+
let (path, reason) = match conf {
76+
conf::DisallowedMethod::Simple(path) => (path, None),
77+
conf::DisallowedMethod::WithReason { path, reason } => (
78+
path,
79+
reason.as_ref().map(|reason| format!("{} (from clippy.toml)", reason)),
80+
),
81+
};
82+
let segs: Vec<_> = path.split("::").collect();
83+
if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &segs) {
84+
self.disallowed.insert(id, reason);
7185
}
7286
}
7387
}
7488

7589
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
80-
.into_iter()
81-
.map(Symbol::to_ident_string)
82-
.collect::<Vec<_>>()
83-
.join("::");
84-
85-
span_lint(
86-
cx,
87-
DISALLOWED_METHOD,
88-
expr.span,
89-
&format!("use of a disallowed method `{}`", func_path_string),
90-
);
90+
let def_id = match fn_def_id(cx, expr) {
91+
Some(def_id) => def_id,
92+
None => return,
93+
};
94+
let reason = match self.disallowed.get(&def_id) {
95+
Some(reason) => reason,
96+
None => return,
97+
};
98+
let func_path = cx.tcx.def_path_str(def_id);
99+
let msg = format!("use of a disallowed method `{}`", func_path);
100+
span_lint_and_then(cx, DISALLOWED_METHOD, expr.span, &msg, |diag| {
101+
if let Some(reason) = reason {
102+
diag.note(reason);
91103
}
92-
}
104+
});
93105
}
94106
}

clippy_lints/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2105,8 +2105,8 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
21052105
store.register_late_pass(|| Box::new(float_equality_without_abs::FloatEqualityWithoutAbs));
21062106
store.register_late_pass(|| Box::new(semicolon_if_nothing_returned::SemicolonIfNothingReturned));
21072107
store.register_late_pass(|| Box::new(async_yields_async::AsyncYieldsAsync));
2108-
let disallowed_methods = conf.disallowed_methods.iter().cloned().collect::<FxHashSet<_>>();
2109-
store.register_late_pass(move || Box::new(disallowed_method::DisallowedMethod::new(&disallowed_methods)));
2108+
let disallowed_methods = conf.disallowed_methods.clone();
2109+
store.register_late_pass(move || Box::new(disallowed_method::DisallowedMethod::new(disallowed_methods.clone())));
21102110
store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86AttSyntax));
21112111
store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86IntelSyntax));
21122112
store.register_late_pass(|| Box::new(undropped_manually_drops::UndroppedManuallyDrops));

clippy_lints/src/utils/conf.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ pub struct Rename {
1515
pub rename: String,
1616
}
1717

18+
/// A single disallowed method, used by the `DISALLOWED_METHOD` lint.
19+
#[derive(Clone, Debug, Deserialize)]
20+
#[serde(untagged)]
21+
pub enum DisallowedMethod {
22+
Simple(String),
23+
WithReason { path: String, reason: Option<String> },
24+
}
25+
1826
/// Conf with parse errors
1927
#[derive(Default)]
2028
pub struct TryConf {
@@ -243,7 +251,7 @@ define_Conf! {
243251
/// Lint: DISALLOWED_METHOD.
244252
///
245253
/// The list of disallowed methods, written as fully qualified paths.
246-
(disallowed_methods: Vec<String> = Vec::new()),
254+
(disallowed_methods: Vec<crate::utils::conf::DisallowedMethod> = Vec::new()),
247255
/// Lint: DISALLOWED_TYPE.
248256
///
249257
/// The list of disallowed types, written as fully qualified paths.
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
disallowed-methods = [
2+
# just a string is shorthand for path only
23
"std::iter::Iterator::sum",
3-
"regex::Regex::is_match",
4-
"regex::Regex::new"
4+
# can give path and reason with an inline table
5+
{ path = "regex::Regex::is_match", reason = "no matching allowed" },
6+
# can use an inline table but omit reason
7+
{ path = "regex::Regex::new" },
58
]

tests/ui-toml/toml_disallowed_method/conf_disallowed_method.stderr

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
1-
error: use of a disallowed method `regex::re_unicode::Regex::new`
1+
error: use of a disallowed method `regex::Regex::new`
22
--> $DIR/conf_disallowed_method.rs:7:14
33
|
44
LL | let re = Regex::new(r"ab.*c").unwrap();
55
| ^^^^^^^^^^^^^^^^^^^^
66
|
77
= note: `-D clippy::disallowed-method` implied by `-D warnings`
88

9-
error: use of a disallowed method `regex::re_unicode::Regex::is_match`
9+
error: use of a disallowed method `regex::Regex::is_match`
1010
--> $DIR/conf_disallowed_method.rs:8:5
1111
|
1212
LL | re.is_match("abc");
1313
| ^^^^^^^^^^^^^^^^^^
14+
|
15+
= note: no matching allowed (from clippy.toml)
1416

15-
error: use of a disallowed method `core::iter::traits::iterator::Iterator::sum`
17+
error: use of a disallowed method `std::iter::Iterator::sum`
1618
--> $DIR/conf_disallowed_method.rs:11:5
1719
|
1820
LL | a.iter().sum::<i32>();

0 commit comments

Comments
 (0)