1 use clippy_utils::diagnostics::span_lint;
3 use rustc_data_structures::fx::FxHashSet;
5 def::Res, def_id::DefId, Item, ItemKind, PolyTraitRef, PrimTy, TraitBoundModifier, Ty, TyKind, UseKind,
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use rustc_span::{Span, Symbol};
11 declare_clippy_lint! {
13 /// Denies the configured types in clippy.toml.
15 /// ### Why is this bad?
16 /// Some types are undesirable in certain contexts.
19 /// An example clippy.toml configuration:
22 /// disallowed-types = ["std::collections::BTreeMap"]
26 /// use std::collections::BTreeMap;
28 /// let x = std::collections::BTreeMap::new();
32 /// // A similar type that is allowed by the config
33 /// use std::collections::HashMap;
37 "use of a disallowed type"
39 #[derive(Clone, Debug)]
40 pub struct DisallowedType {
41 disallowed: FxHashSet<Vec<Symbol>>,
42 def_ids: FxHashSet<DefId>,
43 prim_tys: FxHashSet<PrimTy>,
47 pub fn new(disallowed: &FxHashSet<String>) -> Self {
49 disallowed: disallowed
51 .map(|s| s.split("::").map(Symbol::intern).collect::<Vec<_>>())
53 def_ids: FxHashSet::default(),
54 prim_tys: FxHashSet::default(),
58 fn check_res_emit(&self, cx: &LateContext<'_>, res: &Res, span: Span) {
61 if self.def_ids.contains(did) {
62 emit(cx, &cx.tcx.def_path_str(*did), span);
65 Res::PrimTy(prim) => {
66 if self.prim_tys.contains(prim) {
67 emit(cx, prim.name_str(), span);
75 impl_lint_pass!(DisallowedType => [DISALLOWED_TYPE]);
77 impl<'tcx> LateLintPass<'tcx> for DisallowedType {
78 fn check_crate(&mut self, cx: &LateContext<'_>) {
79 for path in &self.disallowed {
80 let segs = path.iter().map(ToString::to_string).collect::<Vec<_>>();
81 match clippy_utils::path_to_res(cx, &segs.iter().map(String::as_str).collect::<Vec<_>>()) {
83 self.def_ids.insert(id);
86 self.prim_tys.insert(ty);
93 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
94 if let ItemKind::Use(path, UseKind::Single) = &item.kind {
95 self.check_res_emit(cx, &path.res, item.span);
99 fn check_ty(&mut self, cx: &LateContext<'tcx>, ty: &'tcx Ty<'tcx>) {
100 if let TyKind::Path(path) = &ty.kind {
101 self.check_res_emit(cx, &cx.qpath_res(path, ty.hir_id), ty.span);
105 fn check_poly_trait_ref(&mut self, cx: &LateContext<'tcx>, poly: &'tcx PolyTraitRef<'tcx>, _: TraitBoundModifier) {
106 self.check_res_emit(cx, &poly.trait_ref.path.res, poly.trait_ref.path.span);
110 fn emit(cx: &LateContext<'_>, name: &str, span: Span) {
115 &format!("`{}` is not allowed according to config", name),