1use crate::res::MaybeQPath;
8use crate::sym;
9use rustc_ast::Mutability;
10use rustc_data_structures::fx::FxHashMap;
11use rustc_hir::def::Namespace::{MacroNS, TypeNS, ValueNS};
12use rustc_hir::def::{DefKind, Namespace, Res};
13use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
14use rustc_hir::{ItemKind, Node, UseKind};
15use rustc_lint::LateContext;
16use rustc_middle::ty::fast_reject::SimplifiedType;
17use rustc_middle::ty::layout::HasTyCtxt;
18use rustc_middle::ty::{FloatTy, IntTy, Ty, TyCtxt, UintTy};
19use rustc_span::{Ident, STDLIB_STABLE_CRATES, Symbol};
20use std::sync::OnceLock;
21
22#[derive(Clone, Copy, PartialEq, Debug)]
25pub enum PathNS {
26 Type,
27 Value,
28 Macro,
29
30 Arbitrary,
36}
37
38impl PathNS {
39 fn matches(self, ns: Option<Namespace>) -> bool {
40 let required = match self {
41 PathNS::Type => TypeNS,
42 PathNS::Value => ValueNS,
43 PathNS::Macro => MacroNS,
44 PathNS::Arbitrary => return true,
45 };
46
47 ns == Some(required)
48 }
49}
50
51pub struct PathLookup {
62 ns: PathNS,
63 path: &'static [Symbol],
64 once: OnceLock<Vec<DefId>>,
65}
66
67impl PathLookup {
68 #[doc(hidden)]
70 pub const fn new(ns: PathNS, path: &'static [Symbol]) -> Self {
71 Self {
72 ns,
73 path,
74 once: OnceLock::new(),
75 }
76 }
77
78 pub fn get<'tcx>(&self, tcx: &impl HasTyCtxt<'tcx>) -> &[DefId] {
80 self.once.get_or_init(|| lookup_path(tcx.tcx(), self.ns, self.path))
81 }
82
83 pub fn only(&self, cx: &LateContext<'_>) -> Option<DefId> {
88 let ids = self.get(cx);
89 debug_assert!(STDLIB_STABLE_CRATES.contains(&self.path[0]));
90 debug_assert!(ids.len() <= 1, "{ids:?}");
91 ids.first().copied()
92 }
93
94 pub fn matches<'tcx>(&self, tcx: &impl HasTyCtxt<'tcx>, def_id: DefId) -> bool {
96 self.get(&tcx.tcx()).contains(&def_id)
97 }
98
99 pub fn matches_path<'tcx>(&self, cx: &LateContext<'_>, maybe_path: impl MaybeQPath<'tcx>) -> bool {
101 maybe_path
102 .res(cx)
103 .opt_def_id()
104 .is_some_and(|def_id| self.matches(cx, def_id))
105 }
106
107 pub fn matches_ty<'tcx>(&self, tcx: &impl HasTyCtxt<'tcx>, ty: Ty<'_>) -> bool {
109 ty.ty_adt_def().is_some_and(|adt| self.matches(&tcx.tcx(), adt.did()))
110 }
111}
112
113macro_rules! path_macros {
114 ($($name:ident: $ns:expr,)*) => {
115 $(
116 #[doc(hidden)]
118 #[macro_export]
119 macro_rules! $name {
120 ($$($$seg:ident $$(::)?)*) => {
121 PathLookup::new($ns, &[$$(sym::$$seg,)*])
122 };
123 }
124 )*
125 };
126}
127
128path_macros! {
129 type_path: PathNS::Type,
130 value_path: PathNS::Value,
131 macro_path: PathNS::Macro,
132}
133
134pub static FUTURES_IO_ASYNCREADEXT: PathLookup = type_path!(futures_util::AsyncReadExt);
136pub static FUTURES_IO_ASYNCWRITEEXT: PathLookup = type_path!(futures_util::AsyncWriteExt);
137pub static ITERTOOLS_NEXT_TUPLE: PathLookup = value_path!(itertools::Itertools::next_tuple);
138pub static PARKING_LOT_GUARDS: [PathLookup; 3] = [
139 type_path!(lock_api::mutex::MutexGuard),
140 type_path!(lock_api::rwlock::RwLockReadGuard),
141 type_path!(lock_api::rwlock::RwLockWriteGuard),
142];
143pub static REGEX_BUILDER_NEW: PathLookup = value_path!(regex::RegexBuilder::new);
144pub static REGEX_BYTES_BUILDER_NEW: PathLookup = value_path!(regex::bytes::RegexBuilder::new);
145pub static REGEX_BYTES_NEW: PathLookup = value_path!(regex::bytes::Regex::new);
146pub static REGEX_BYTES_SET_NEW: PathLookup = value_path!(regex::bytes::RegexSet::new);
147pub static REGEX_NEW: PathLookup = value_path!(regex::Regex::new);
148pub static REGEX_SET_NEW: PathLookup = value_path!(regex::RegexSet::new);
149pub static SERDE_DESERIALIZE: PathLookup = type_path!(serde::de::Deserialize);
150pub static SERDE_DE_VISITOR: PathLookup = type_path!(serde::de::Visitor);
151pub static TOKIO_FILE_OPTIONS: PathLookup = value_path!(tokio::fs::File::options);
152pub static TOKIO_IO_ASYNCREADEXT: PathLookup = type_path!(tokio::io::AsyncReadExt);
153pub static TOKIO_IO_ASYNCWRITEEXT: PathLookup = type_path!(tokio::io::AsyncWriteExt);
154pub static TOKIO_IO_OPEN_OPTIONS: PathLookup = type_path!(tokio::fs::OpenOptions);
155pub static TOKIO_IO_OPEN_OPTIONS_NEW: PathLookup = value_path!(tokio::fs::OpenOptions::new);
156pub static LAZY_STATIC: PathLookup = macro_path!(lazy_static::lazy_static);
157pub static ONCE_CELL_SYNC_LAZY: PathLookup = type_path!(once_cell::sync::Lazy);
158pub static ONCE_CELL_SYNC_LAZY_NEW: PathLookup = value_path!(once_cell::sync::Lazy::new);
159
160pub fn lookup_path_str(tcx: TyCtxt<'_>, ns: PathNS, path: &str) -> Vec<DefId> {
166 let path: Vec<Symbol> = path.split("::").map(Symbol::intern).collect();
167 lookup_path(tcx, ns, &path)
168}
169
170pub fn lookup_path(tcx: TyCtxt<'_>, ns: PathNS, path: &[Symbol]) -> Vec<DefId> {
183 let (root, rest) = match *path {
184 [] | [_] => return Vec::new(),
185 [root, ref rest @ ..] => (root, rest),
186 };
187
188 let mut out = Vec::new();
189 for &base in find_crates(tcx, root).iter().chain(find_primitive_impls(tcx, root)) {
190 lookup_with_base(tcx, base, ns, rest, &mut out);
191 }
192 out
193}
194
195pub fn find_crates(tcx: TyCtxt<'_>, name: Symbol) -> &'static [DefId] {
197 static BY_NAME: OnceLock<FxHashMap<Symbol, Vec<DefId>>> = OnceLock::new();
198 let map = BY_NAME.get_or_init(|| {
199 let mut map = FxHashMap::default();
200 map.insert(tcx.crate_name(LOCAL_CRATE), vec![LOCAL_CRATE.as_def_id()]);
201 for &num in tcx.crates(()) {
202 map.entry(tcx.crate_name(num)).or_default().push(num.as_def_id());
203 }
204 map
205 });
206 match map.get(&name) {
207 Some(def_ids) => def_ids,
208 None => &[],
209 }
210}
211
212fn find_primitive_impls(tcx: TyCtxt<'_>, name: Symbol) -> &[DefId] {
213 let ty = match name {
214 sym::bool => SimplifiedType::Bool,
215 sym::char => SimplifiedType::Char,
216 sym::str => SimplifiedType::Str,
217 sym::array => SimplifiedType::Array,
218 sym::slice => SimplifiedType::Slice,
219 sym::const_ptr => SimplifiedType::Ptr(Mutability::Not),
223 sym::mut_ptr => SimplifiedType::Ptr(Mutability::Mut),
224 sym::isize => SimplifiedType::Int(IntTy::Isize),
225 sym::i8 => SimplifiedType::Int(IntTy::I8),
226 sym::i16 => SimplifiedType::Int(IntTy::I16),
227 sym::i32 => SimplifiedType::Int(IntTy::I32),
228 sym::i64 => SimplifiedType::Int(IntTy::I64),
229 sym::i128 => SimplifiedType::Int(IntTy::I128),
230 sym::usize => SimplifiedType::Uint(UintTy::Usize),
231 sym::u8 => SimplifiedType::Uint(UintTy::U8),
232 sym::u16 => SimplifiedType::Uint(UintTy::U16),
233 sym::u32 => SimplifiedType::Uint(UintTy::U32),
234 sym::u64 => SimplifiedType::Uint(UintTy::U64),
235 sym::u128 => SimplifiedType::Uint(UintTy::U128),
236 sym::f32 => SimplifiedType::Float(FloatTy::F32),
237 sym::f64 => SimplifiedType::Float(FloatTy::F64),
238 _ => return &[],
239 };
240
241 tcx.incoherent_impls(ty)
242}
243
244fn lookup_with_base(tcx: TyCtxt<'_>, mut base: DefId, ns: PathNS, mut path: &[Symbol], out: &mut Vec<DefId>) {
246 loop {
247 match *path {
248 [segment] => {
249 out.extend(item_child_by_name(tcx, base, ns, segment));
250
251 let inherent_impl_children = tcx
254 .inherent_impls(base)
255 .iter()
256 .filter_map(|&impl_def_id| item_child_by_name(tcx, impl_def_id, ns, segment));
257 out.extend(inherent_impl_children);
258
259 return;
260 },
261 [segment, ref rest @ ..] => {
262 path = rest;
263 let Some(child) = item_child_by_name(tcx, base, PathNS::Type, segment) else {
264 return;
265 };
266 base = child;
267 },
268 [] => unreachable!(),
269 }
270 }
271}
272
273fn item_child_by_name(tcx: TyCtxt<'_>, def_id: DefId, ns: PathNS, name: Symbol) -> Option<DefId> {
274 if let Some(local_id) = def_id.as_local() {
275 local_item_child_by_name(tcx, local_id, ns, name)
276 } else {
277 non_local_item_child_by_name(tcx, def_id, ns, name)
278 }
279}
280
281fn local_item_child_by_name(tcx: TyCtxt<'_>, local_id: LocalDefId, ns: PathNS, name: Symbol) -> Option<DefId> {
282 let root_mod;
283 let item_kind = match tcx.hir_node_by_def_id(local_id) {
284 Node::Crate(r#mod) => {
285 root_mod = ItemKind::Mod(Ident::dummy(), r#mod);
286 &root_mod
287 },
288 Node::Item(item) => &item.kind,
289 _ => return None,
290 };
291
292 match item_kind {
293 ItemKind::Mod(_, r#mod) => r#mod.item_ids.iter().find_map(|&item_id| {
294 let item = tcx.hir_item(item_id);
295 if let ItemKind::Use(path, UseKind::Single(ident)) = item.kind {
296 if ident.name == name {
297 let opt_def_id = |ns: Option<Res>| ns.and_then(|res| res.opt_def_id());
298 match ns {
299 PathNS::Type => opt_def_id(path.res.type_ns),
300 PathNS::Value => opt_def_id(path.res.value_ns),
301 PathNS::Macro => opt_def_id(path.res.macro_ns),
302 PathNS::Arbitrary => unreachable!(),
303 }
304 } else {
305 None
306 }
307 } else if let Some(ident) = item.kind.ident()
308 && ident.name == name
309 && ns.matches(tcx.def_kind(item.owner_id).ns())
310 {
311 Some(item.owner_id.to_def_id())
312 } else {
313 None
314 }
315 }),
316 ItemKind::Impl(..) | ItemKind::Trait(..) => tcx
317 .associated_items(local_id)
318 .filter_by_name_unhygienic(name)
319 .find(|assoc_item| ns.matches(Some(assoc_item.namespace())))
320 .map(|assoc_item| assoc_item.def_id),
321 _ => None,
322 }
323}
324
325fn non_local_item_child_by_name(tcx: TyCtxt<'_>, def_id: DefId, ns: PathNS, name: Symbol) -> Option<DefId> {
326 match tcx.def_kind(def_id) {
327 DefKind::Mod | DefKind::Enum | DefKind::Trait => tcx.module_children(def_id).iter().find_map(|child| {
328 if child.ident.name == name && ns.matches(child.res.ns()) {
329 child.res.opt_def_id()
330 } else {
331 None
332 }
333 }),
334 DefKind::Impl { .. } => tcx
335 .associated_item_def_ids(def_id)
336 .iter()
337 .copied()
338 .find(|assoc_def_id| tcx.item_name(*assoc_def_id) == name && ns.matches(tcx.def_kind(assoc_def_id).ns())),
339 _ => None,
340 }
341}