Skip to content

Commit 6f33f69

Browse files
committed
Auto merge of #8112 - Alexendoo:disallowed_methods_primitives, r=flip1995
Allow primitive types in disallowed_methods Fixes #8079 changelog: `disallowed_methods`: Now can disallow methods of primitive types
2 parents 7c82ae1 + 04eb27a commit 6f33f69

File tree

6 files changed

+67
-29
lines changed

6 files changed

+67
-29
lines changed

clippy_lints/src/disallowed_methods.rs

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ declare_clippy_lint! {
5959
#[derive(Clone, Debug)]
6060
pub struct DisallowedMethods {
6161
conf_disallowed: Vec<conf::DisallowedMethod>,
62-
disallowed: DefIdMap<Option<String>>,
62+
disallowed: DefIdMap<usize>,
6363
}
6464

6565
impl DisallowedMethods {
@@ -75,17 +75,10 @@ impl_lint_pass!(DisallowedMethods => [DISALLOWED_METHODS]);
7575

7676
impl<'tcx> LateLintPass<'tcx> for DisallowedMethods {
7777
fn check_crate(&mut self, cx: &LateContext<'_>) {
78-
for conf in &self.conf_disallowed {
79-
let (path, reason) = match conf {
80-
conf::DisallowedMethod::Simple(path) => (path, None),
81-
conf::DisallowedMethod::WithReason { path, reason } => (
82-
path,
83-
reason.as_ref().map(|reason| format!("{} (from clippy.toml)", reason)),
84-
),
85-
};
86-
let segs: Vec<_> = path.split("::").collect();
78+
for (index, conf) in self.conf_disallowed.iter().enumerate() {
79+
let segs: Vec<_> = conf.path().split("::").collect();
8780
if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &segs) {
88-
self.disallowed.insert(id, reason);
81+
self.disallowed.insert(id, index);
8982
}
9083
}
9184
}
@@ -95,15 +88,17 @@ impl<'tcx> LateLintPass<'tcx> for DisallowedMethods {
9588
Some(def_id) => def_id,
9689
None => return,
9790
};
98-
let reason = match self.disallowed.get(&def_id) {
99-
Some(reason) => reason,
91+
let conf = match self.disallowed.get(&def_id) {
92+
Some(&index) => &self.conf_disallowed[index],
10093
None => return,
10194
};
102-
let func_path = cx.tcx.def_path_str(def_id);
103-
let msg = format!("use of a disallowed method `{}`", func_path);
95+
let msg = format!("use of a disallowed method `{}`", conf.path());
10496
span_lint_and_then(cx, DISALLOWED_METHODS, expr.span, &msg, |diag| {
105-
if let Some(reason) = reason {
106-
diag.note(reason);
97+
if let conf::DisallowedMethod::WithReason {
98+
reason: Some(reason), ..
99+
} = conf
100+
{
101+
diag.note(&format!("{} (from clippy.toml)", reason));
107102
}
108103
});
109104
}

clippy_lints/src/utils/conf.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ pub enum DisallowedMethod {
2323
WithReason { path: String, reason: Option<String> },
2424
}
2525

26+
impl DisallowedMethod {
27+
pub fn path(&self) -> &str {
28+
let (Self::Simple(path) | Self::WithReason { path, .. }) = self;
29+
30+
path
31+
}
32+
}
33+
2634
/// A single disallowed type, used by the `DISALLOWED_TYPES` lint.
2735
#[derive(Clone, Debug, Deserialize)]
2836
#[serde(untagged)]

clippy_utils/src/lib.rs

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,16 +70,16 @@ use rustc_data_structures::fx::FxHashMap;
7070
use rustc_data_structures::unhash::UnhashMap;
7171
use rustc_hir as hir;
7272
use rustc_hir::def::{DefKind, Res};
73-
use rustc_hir::def_id::DefId;
73+
use rustc_hir::def_id::{CrateNum, DefId};
7474
use rustc_hir::hir_id::{HirIdMap, HirIdSet};
7575
use rustc_hir::intravisit::{walk_expr, ErasedMap, FnKind, NestedVisitorMap, Visitor};
7676
use rustc_hir::itemlikevisit::ItemLikeVisitor;
7777
use rustc_hir::LangItem::{OptionNone, ResultErr, ResultOk};
7878
use rustc_hir::{
79-
def, Arm, BindingAnnotation, Block, BlockCheckMode, Body, Constness, Destination, Expr, ExprKind, FnDecl,
80-
ForeignItem, GenericArgs, HirId, Impl, ImplItem, ImplItemKind, IsAsync, Item, ItemKind, LangItem, Local,
81-
MatchSource, Mutability, Node, Param, Pat, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, TraitItem,
82-
TraitItemKind, TraitRef, TyKind, UnOp,
79+
def, lang_items, Arm, BindingAnnotation, Block, BlockCheckMode, Body, Constness, Destination, Expr, ExprKind,
80+
FnDecl, ForeignItem, GenericArgs, HirId, Impl, ImplItem, ImplItemKind, IsAsync, Item, ItemKind, LangItem, Local,
81+
MatchSource, Mutability, Node, Param, Pat, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, Target,
82+
TraitItem, TraitItemKind, TraitRef, TyKind, UnOp,
8383
};
8484
use rustc_lint::{LateContext, Level, Lint, LintContext};
8585
use rustc_middle::hir::exports::Export;
@@ -525,18 +525,34 @@ pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Res {
525525
.iter()
526526
.find(|item| item.ident.name.as_str() == name)
527527
}
528+
fn find_primitive(tcx: TyCtxt<'_>, name: &str) -> Option<DefId> {
529+
if let Some(&(index, Target::Impl)) = lang_items::ITEM_REFS.get(&Symbol::intern(name)) {
530+
tcx.lang_items().items()[index]
531+
} else {
532+
None
533+
}
534+
}
535+
fn find_crate(tcx: TyCtxt<'_>, name: &str) -> Option<DefId> {
536+
tcx.crates(())
537+
.iter()
538+
.find(|&&num| tcx.crate_name(num).as_str() == name)
539+
.map(CrateNum::as_def_id)
540+
}
528541

529-
let (krate, first, path) = match *path {
530-
[krate, first, ref path @ ..] => (krate, first, path),
542+
let (base, first, path) = match *path {
543+
[base, first, ref path @ ..] => (base, first, path),
531544
[primitive] => {
532545
return PrimTy::from_name(Symbol::intern(primitive)).map_or(Res::Err, Res::PrimTy);
533546
},
534547
_ => return Res::Err,
535548
};
536549
let tcx = cx.tcx;
537-
let crates = tcx.crates(());
538-
let krate = try_res!(crates.iter().find(|&&num| tcx.crate_name(num).as_str() == krate));
539-
let first = try_res!(item_child_by_name(tcx, krate.as_def_id(), first));
550+
let first = try_res!(
551+
find_primitive(tcx, base)
552+
.or_else(|| find_crate(tcx, base))
553+
.and_then(|id| item_child_by_name(tcx, id, first))
554+
);
555+
540556
let last = path
541557
.iter()
542558
.copied()

tests/ui-toml/toml_disallowed_methods/clippy.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
disallowed-methods = [
22
# just a string is shorthand for path only
33
"std::iter::Iterator::sum",
4+
"f32::clamp",
5+
"slice::sort_unstable",
46
# can give path and reason with an inline table
57
{ path = "regex::Regex::is_match", reason = "no matching allowed" },
68
# can use an inline table but omit reason

tests/ui-toml/toml_disallowed_methods/conf_disallowed_methods.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ fn main() {
77
let re = Regex::new(r"ab.*c").unwrap();
88
re.is_match("abc");
99

10-
let a = vec![1, 2, 3, 4];
10+
let mut a = vec![1, 2, 3, 4];
1111
a.iter().sum::<i32>();
12+
13+
a.sort_unstable();
14+
15+
let _ = 2.0f32.clamp(3.0f32, 4.0f32);
16+
let _ = 2.0f64.clamp(3.0f64, 4.0f64);
1217
}

tests/ui-toml/toml_disallowed_methods/conf_disallowed_methods.stderr

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,17 @@ error: use of a disallowed method `std::iter::Iterator::sum`
2020
LL | a.iter().sum::<i32>();
2121
| ^^^^^^^^^^^^^^^^^^^^^
2222

23-
error: aborting due to 3 previous errors
23+
error: use of a disallowed method `slice::sort_unstable`
24+
--> $DIR/conf_disallowed_methods.rs:13:5
25+
|
26+
LL | a.sort_unstable();
27+
| ^^^^^^^^^^^^^^^^^
28+
29+
error: use of a disallowed method `f32::clamp`
30+
--> $DIR/conf_disallowed_methods.rs:15:13
31+
|
32+
LL | let _ = 2.0f32.clamp(3.0f32, 4.0f32);
33+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
34+
35+
error: aborting due to 5 previous errors
2436

0 commit comments

Comments
 (0)