]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/def.rs
Rollup merge of #96122 - TaKO8Ki:fix-invalid-error-for-suggestion-to-add-slice-in...
[rust.git] / compiler / rustc_hir / src / def.rs
1 use crate::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
2 use crate::hir;
3
4 use rustc_ast as ast;
5 use rustc_ast::NodeId;
6 use rustc_macros::HashStable_Generic;
7 use rustc_span::hygiene::MacroKind;
8 use rustc_span::Symbol;
9
10 use std::array::IntoIter;
11 use std::fmt::Debug;
12
13 /// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct.
14 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
15 #[derive(HashStable_Generic)]
16 pub enum CtorOf {
17     /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit struct.
18     Struct,
19     /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit variant.
20     Variant,
21 }
22
23 /// What kind of constructor something is.
24 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
25 #[derive(HashStable_Generic)]
26 pub enum CtorKind {
27     /// Constructor function automatically created by a tuple struct/variant.
28     Fn,
29     /// Constructor constant automatically created by a unit struct/variant.
30     Const,
31     /// Unusable name in value namespace created by a struct variant.
32     Fictive,
33 }
34
35 /// An attribute that is not a macro; e.g., `#[inline]` or `#[rustfmt::skip]`.
36 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
37 #[derive(HashStable_Generic)]
38 pub enum NonMacroAttrKind {
39     /// Single-segment attribute defined by the language (`#[inline]`)
40     Builtin(Symbol),
41     /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`).
42     Tool,
43     /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
44     DeriveHelper,
45     /// Single-segment custom attribute registered by a derive macro
46     /// but used before that derive macro was expanded (deprecated).
47     DeriveHelperCompat,
48     /// Single-segment custom attribute registered with `#[register_attr]`.
49     Registered,
50 }
51
52 /// What kind of definition something is; e.g., `mod` vs `struct`.
53 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
54 #[derive(HashStable_Generic)]
55 pub enum DefKind {
56     // Type namespace
57     Mod,
58     /// Refers to the struct itself, [`DefKind::Ctor`] refers to its constructor if it exists.
59     Struct,
60     Union,
61     Enum,
62     /// Refers to the variant itself, [`DefKind::Ctor`] refers to its constructor if it exists.
63     Variant,
64     Trait,
65     /// Type alias: `type Foo = Bar;`
66     TyAlias,
67     /// Type from an `extern` block.
68     ForeignTy,
69     /// Trait alias: `trait IntIterator = Iterator<Item = i32>;`
70     TraitAlias,
71     /// Associated type: `trait MyTrait { type Assoc; }`
72     AssocTy,
73     /// Type parameter: the `T` in `struct Vec<T> { ... }`
74     TyParam,
75
76     // Value namespace
77     Fn,
78     Const,
79     /// Constant generic parameter: `struct Foo<const N: usize> { ... }`
80     ConstParam,
81     Static(ast::Mutability),
82     /// Refers to the struct or enum variant's constructor.
83     ///
84     /// The reason `Ctor` exists in addition to [`DefKind::Struct`] and
85     /// [`DefKind::Variant`] is because structs and enum variants exist
86     /// in the *type* namespace, whereas struct and enum variant *constructors*
87     /// exist in the *value* namespace.
88     ///
89     /// You may wonder why enum variants exist in the type namespace as opposed
90     /// to the value namespace. Check out [RFC 2593] for intuition on why that is.
91     ///
92     /// [RFC 2593]: https://github.com/rust-lang/rfcs/pull/2593
93     Ctor(CtorOf, CtorKind),
94     /// Associated function: `impl MyStruct { fn associated() {} }`
95     AssocFn,
96     /// Associated constant: `trait MyTrait { const ASSOC: usize; }`
97     AssocConst,
98
99     // Macro namespace
100     Macro(MacroKind),
101
102     // Not namespaced (or they are, but we don't treat them so)
103     ExternCrate,
104     Use,
105     /// An `extern` block.
106     ForeignMod,
107     /// Anonymous constant, e.g. the `1 + 2` in `[u8; 1 + 2]`
108     AnonConst,
109     /// An inline constant, e.g. `const { 1 + 2 }`
110     InlineConst,
111     /// Opaque type, aka `impl Trait`.
112     OpaqueTy,
113     Field,
114     /// Lifetime parameter: the `'a` in `struct Foo<'a> { ... }`
115     LifetimeParam,
116     /// A use of `global_asm!`.
117     GlobalAsm,
118     Impl,
119     Closure,
120     Generator,
121 }
122
123 impl DefKind {
124     pub fn descr(self, def_id: DefId) -> &'static str {
125         match self {
126             DefKind::Fn => "function",
127             DefKind::Mod if def_id.index == CRATE_DEF_INDEX && def_id.krate != LOCAL_CRATE => {
128                 "crate"
129             }
130             DefKind::Mod => "module",
131             DefKind::Static(..) => "static",
132             DefKind::Enum => "enum",
133             DefKind::Variant => "variant",
134             DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
135             DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
136             DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant",
137             DefKind::Struct => "struct",
138             DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
139             DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
140             DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => {
141                 panic!("impossible struct constructor")
142             }
143             DefKind::OpaqueTy => "opaque type",
144             DefKind::TyAlias => "type alias",
145             DefKind::TraitAlias => "trait alias",
146             DefKind::AssocTy => "associated type",
147             DefKind::Union => "union",
148             DefKind::Trait => "trait",
149             DefKind::ForeignTy => "foreign type",
150             DefKind::AssocFn => "associated function",
151             DefKind::Const => "constant",
152             DefKind::AssocConst => "associated constant",
153             DefKind::TyParam => "type parameter",
154             DefKind::ConstParam => "const parameter",
155             DefKind::Macro(macro_kind) => macro_kind.descr(),
156             DefKind::LifetimeParam => "lifetime parameter",
157             DefKind::Use => "import",
158             DefKind::ForeignMod => "foreign module",
159             DefKind::AnonConst => "constant expression",
160             DefKind::InlineConst => "inline constant",
161             DefKind::Field => "field",
162             DefKind::Impl => "implementation",
163             DefKind::Closure => "closure",
164             DefKind::Generator => "generator",
165             DefKind::ExternCrate => "extern crate",
166             DefKind::GlobalAsm => "global assembly block",
167         }
168     }
169
170     /// Gets an English article for the definition.
171     pub fn article(&self) -> &'static str {
172         match *self {
173             DefKind::AssocTy
174             | DefKind::AssocConst
175             | DefKind::AssocFn
176             | DefKind::Enum
177             | DefKind::OpaqueTy
178             | DefKind::Impl
179             | DefKind::Use
180             | DefKind::InlineConst
181             | DefKind::ExternCrate => "an",
182             DefKind::Macro(macro_kind) => macro_kind.article(),
183             _ => "a",
184         }
185     }
186
187     pub fn ns(&self) -> Option<Namespace> {
188         match self {
189             DefKind::Mod
190             | DefKind::Struct
191             | DefKind::Union
192             | DefKind::Enum
193             | DefKind::Variant
194             | DefKind::Trait
195             | DefKind::OpaqueTy
196             | DefKind::TyAlias
197             | DefKind::ForeignTy
198             | DefKind::TraitAlias
199             | DefKind::AssocTy
200             | DefKind::TyParam => Some(Namespace::TypeNS),
201
202             DefKind::Fn
203             | DefKind::Const
204             | DefKind::ConstParam
205             | DefKind::Static(..)
206             | DefKind::Ctor(..)
207             | DefKind::AssocFn
208             | DefKind::AssocConst => Some(Namespace::ValueNS),
209
210             DefKind::Macro(..) => Some(Namespace::MacroNS),
211
212             // Not namespaced.
213             DefKind::AnonConst
214             | DefKind::InlineConst
215             | DefKind::Field
216             | DefKind::LifetimeParam
217             | DefKind::ExternCrate
218             | DefKind::Closure
219             | DefKind::Generator
220             | DefKind::Use
221             | DefKind::ForeignMod
222             | DefKind::GlobalAsm
223             | DefKind::Impl => None,
224         }
225     }
226
227     #[inline]
228     pub fn is_fn_like(self) -> bool {
229         match self {
230             DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator => true,
231             _ => false,
232         }
233     }
234 }
235
236 /// The resolution of a path or export.
237 ///
238 /// For every path or identifier in Rust, the compiler must determine
239 /// what the path refers to. This process is called name resolution,
240 /// and `Res` is the primary result of name resolution.
241 ///
242 /// For example, everything prefixed with `/* Res */` in this example has
243 /// an associated `Res`:
244 ///
245 /// ```
246 /// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
247 ///     /* Res */ String::from(/* Res */ s)
248 /// }
249 ///
250 /// /* Res */ str_to_string("hello");
251 /// ```
252 ///
253 /// The associated `Res`s will be:
254 ///
255 /// - `str` will resolve to [`Res::PrimTy`];
256 /// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
257 ///   for `String` as defined in the standard library;
258 /// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
259 ///   pointing to `String::from`;
260 /// - `s` will resolve to [`Res::Local`];
261 /// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
262 ///   pointing to the definition of `str_to_string` in the current crate.
263 //
264 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
265 #[derive(HashStable_Generic)]
266 pub enum Res<Id = hir::HirId> {
267     /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
268     ///
269     /// **Not bound to a specific namespace.**
270     Def(DefKind, DefId),
271
272     // Type namespace
273     /// A primitive type such as `i32` or `str`.
274     ///
275     /// **Belongs to the type namespace.**
276     PrimTy(hir::PrimTy),
277     /// The `Self` type, optionally with the [`DefId`] of the trait it belongs to and
278     /// optionally with the [`DefId`] of the item introducing the `Self` type alias.
279     ///
280     /// **Belongs to the type namespace.**
281     ///
282     /// Examples:
283     /// ```
284     /// struct Bar(Box<Self>);
285     /// // `Res::SelfTy { trait_: None, alias_of: Some(Bar) }`
286     ///
287     /// trait Foo {
288     ///     fn foo() -> Box<Self>;
289     ///     // `Res::SelfTy { trait_: Some(Foo), alias_of: None }`
290     /// }
291     ///
292     /// impl Bar {
293     ///     fn blah() {
294     ///         let _: Self;
295     ///         // `Res::SelfTy { trait_: None, alias_of: Some(::{impl#0}) }`
296     ///     }
297     /// }
298     ///
299     /// impl Foo for Bar {
300     ///     fn foo() -> Box<Self> {
301     ///     // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
302     ///         let _: Self;
303     ///         // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
304     ///
305     ///         todo!()
306     ///     }
307     /// }
308     /// ```
309     ///
310     /// *See also [`Res::SelfCtor`].*
311     ///
312     /// -----
313     ///
314     /// HACK(min_const_generics): self types also have an optional requirement to **not** mention
315     /// any generic parameters to allow the following with `min_const_generics`:
316     /// ```
317     /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
318     ///
319     /// struct Bar([u8; baz::<Self>()]);
320     /// const fn baz<T>() -> usize { 10 }
321     /// ```
322     /// We do however allow `Self` in repeat expression even if it is generic to not break code
323     /// which already works on stable while causing the `const_evaluatable_unchecked` future compat lint:
324     /// ```
325     /// fn foo<T>() {
326     ///     let _bar = [1_u8; std::mem::size_of::<*mut T>()];
327     /// }
328     /// ```
329     // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
330     SelfTy {
331         /// The trait this `Self` is a generic arg for.
332         trait_: Option<DefId>,
333         /// The item introducing the `Self` type alias. Can be used in the `type_of` query
334         /// to get the underlying type. Additionally whether the `Self` type is disallowed
335         /// from mentioning generics (i.e. when used in an anonymous constant).
336         alias_to: Option<(DefId, bool)>,
337     },
338     /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
339     ///
340     /// **Belongs to the type namespace.**
341     ToolMod,
342
343     // Value namespace
344     /// The `Self` constructor, along with the [`DefId`]
345     /// of the impl it is associated with.
346     ///
347     /// **Belongs to the value namespace.**
348     ///
349     /// *See also [`Res::SelfTy`].*
350     SelfCtor(DefId),
351     /// A local variable or function parameter.
352     ///
353     /// **Belongs to the value namespace.**
354     Local(Id),
355
356     // Macro namespace
357     /// An attribute that is *not* implemented via macro.
358     /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
359     /// as opposed to `#[test]`, which is a builtin macro.
360     ///
361     /// **Belongs to the macro namespace.**
362     NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
363
364     // All namespaces
365     /// Name resolution failed. We use a dummy `Res` variant so later phases
366     /// of the compiler won't crash and can instead report more errors.
367     ///
368     /// **Not bound to a specific namespace.**
369     Err,
370 }
371
372 /// The result of resolving a path before lowering to HIR,
373 /// with "module" segments resolved and associated item
374 /// segments deferred to type checking.
375 /// `base_res` is the resolution of the resolved part of the
376 /// path, `unresolved_segments` is the number of unresolved
377 /// segments.
378 ///
379 /// ```text
380 /// module::Type::AssocX::AssocY::MethodOrAssocType
381 /// ^~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
382 /// base_res      unresolved_segments = 3
383 ///
384 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
385 ///       ^~~~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~
386 ///       base_res        unresolved_segments = 2
387 /// ```
388 #[derive(Copy, Clone, Debug)]
389 pub struct PartialRes {
390     base_res: Res<NodeId>,
391     unresolved_segments: usize,
392 }
393
394 impl PartialRes {
395     #[inline]
396     pub fn new(base_res: Res<NodeId>) -> Self {
397         PartialRes { base_res, unresolved_segments: 0 }
398     }
399
400     #[inline]
401     pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
402         if base_res == Res::Err {
403             unresolved_segments = 0
404         }
405         PartialRes { base_res, unresolved_segments }
406     }
407
408     #[inline]
409     pub fn base_res(&self) -> Res<NodeId> {
410         self.base_res
411     }
412
413     #[inline]
414     pub fn unresolved_segments(&self) -> usize {
415         self.unresolved_segments
416     }
417 }
418
419 /// Different kinds of symbols can coexist even if they share the same textual name.
420 /// Therefore, they each have a separate universe (known as a "namespace").
421 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
422 pub enum Namespace {
423     /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
424     /// (and, by extension, crates).
425     ///
426     /// Note that the type namespace includes other items; this is not an
427     /// exhaustive list.
428     TypeNS,
429     /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
430     ValueNS,
431     /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
432     /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
433     /// like `#[inline]` and `#[rustfmt::skip]`.
434     MacroNS,
435 }
436
437 impl Namespace {
438     /// The English description of the namespace.
439     pub fn descr(self) -> &'static str {
440         match self {
441             Self::TypeNS => "type",
442             Self::ValueNS => "value",
443             Self::MacroNS => "macro",
444         }
445     }
446 }
447
448 /// Just a helper ‒ separate structure for each namespace.
449 #[derive(Copy, Clone, Default, Debug)]
450 pub struct PerNS<T> {
451     pub value_ns: T,
452     pub type_ns: T,
453     pub macro_ns: T,
454 }
455
456 impl<T> PerNS<T> {
457     pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
458         PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
459     }
460
461     pub fn into_iter(self) -> IntoIter<T, 3> {
462         [self.value_ns, self.type_ns, self.macro_ns].into_iter()
463     }
464
465     pub fn iter(&self) -> IntoIter<&T, 3> {
466         [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
467     }
468 }
469
470 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
471     type Output = T;
472
473     fn index(&self, ns: Namespace) -> &T {
474         match ns {
475             Namespace::ValueNS => &self.value_ns,
476             Namespace::TypeNS => &self.type_ns,
477             Namespace::MacroNS => &self.macro_ns,
478         }
479     }
480 }
481
482 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
483     fn index_mut(&mut self, ns: Namespace) -> &mut T {
484         match ns {
485             Namespace::ValueNS => &mut self.value_ns,
486             Namespace::TypeNS => &mut self.type_ns,
487             Namespace::MacroNS => &mut self.macro_ns,
488         }
489     }
490 }
491
492 impl<T> PerNS<Option<T>> {
493     /// Returns `true` if all the items in this collection are `None`.
494     pub fn is_empty(&self) -> bool {
495         self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
496     }
497
498     /// Returns an iterator over the items which are `Some`.
499     pub fn present_items(self) -> impl Iterator<Item = T> {
500         [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
501     }
502 }
503
504 impl CtorKind {
505     pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
506         match *vdata {
507             ast::VariantData::Tuple(..) => CtorKind::Fn,
508             ast::VariantData::Unit(..) => CtorKind::Const,
509             ast::VariantData::Struct(..) => CtorKind::Fictive,
510         }
511     }
512
513     pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
514         match *vdata {
515             hir::VariantData::Tuple(..) => CtorKind::Fn,
516             hir::VariantData::Unit(..) => CtorKind::Const,
517             hir::VariantData::Struct(..) => CtorKind::Fictive,
518         }
519     }
520 }
521
522 impl NonMacroAttrKind {
523     pub fn descr(self) -> &'static str {
524         match self {
525             NonMacroAttrKind::Builtin(..) => "built-in attribute",
526             NonMacroAttrKind::Tool => "tool attribute",
527             NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
528                 "derive helper attribute"
529             }
530             NonMacroAttrKind::Registered => "explicitly registered attribute",
531         }
532     }
533
534     pub fn article(self) -> &'static str {
535         match self {
536             NonMacroAttrKind::Registered => "an",
537             _ => "a",
538         }
539     }
540
541     /// Users of some attributes cannot mark them as used, so they are considered always used.
542     pub fn is_used(self) -> bool {
543         match self {
544             NonMacroAttrKind::Tool
545             | NonMacroAttrKind::DeriveHelper
546             | NonMacroAttrKind::DeriveHelperCompat => true,
547             NonMacroAttrKind::Builtin(..) | NonMacroAttrKind::Registered => false,
548         }
549     }
550 }
551
552 impl<Id> Res<Id> {
553     /// Return the `DefId` of this `Def` if it has an ID, else panic.
554     pub fn def_id(&self) -> DefId
555     where
556         Id: Debug,
557     {
558         self.opt_def_id()
559             .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
560     }
561
562     /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
563     pub fn opt_def_id(&self) -> Option<DefId> {
564         match *self {
565             Res::Def(_, id) => Some(id),
566
567             Res::Local(..)
568             | Res::PrimTy(..)
569             | Res::SelfTy { .. }
570             | Res::SelfCtor(..)
571             | Res::ToolMod
572             | Res::NonMacroAttr(..)
573             | Res::Err => None,
574         }
575     }
576
577     /// Return the `DefId` of this `Res` if it represents a module.
578     pub fn mod_def_id(&self) -> Option<DefId> {
579         match *self {
580             Res::Def(DefKind::Mod, id) => Some(id),
581             _ => None,
582         }
583     }
584
585     /// A human readable name for the res kind ("function", "module", etc.).
586     pub fn descr(&self) -> &'static str {
587         match *self {
588             Res::Def(kind, def_id) => kind.descr(def_id),
589             Res::SelfCtor(..) => "self constructor",
590             Res::PrimTy(..) => "builtin type",
591             Res::Local(..) => "local variable",
592             Res::SelfTy { .. } => "self type",
593             Res::ToolMod => "tool module",
594             Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
595             Res::Err => "unresolved item",
596         }
597     }
598
599     /// Gets an English article for the `Res`.
600     pub fn article(&self) -> &'static str {
601         match *self {
602             Res::Def(kind, _) => kind.article(),
603             Res::NonMacroAttr(kind) => kind.article(),
604             Res::Err => "an",
605             _ => "a",
606         }
607     }
608
609     pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
610         match self {
611             Res::Def(kind, id) => Res::Def(kind, id),
612             Res::SelfCtor(id) => Res::SelfCtor(id),
613             Res::PrimTy(id) => Res::PrimTy(id),
614             Res::Local(id) => Res::Local(map(id)),
615             Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
616             Res::ToolMod => Res::ToolMod,
617             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
618             Res::Err => Res::Err,
619         }
620     }
621
622     pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
623         Ok(match self {
624             Res::Def(kind, id) => Res::Def(kind, id),
625             Res::SelfCtor(id) => Res::SelfCtor(id),
626             Res::PrimTy(id) => Res::PrimTy(id),
627             Res::Local(id) => Res::Local(map(id)?),
628             Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
629             Res::ToolMod => Res::ToolMod,
630             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
631             Res::Err => Res::Err,
632         })
633     }
634
635     #[track_caller]
636     pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
637         self.map_id(|_| panic!("unexpected `Res::Local`"))
638     }
639
640     pub fn macro_kind(self) -> Option<MacroKind> {
641         match self {
642             Res::Def(DefKind::Macro(kind), _) => Some(kind),
643             Res::NonMacroAttr(..) => Some(MacroKind::Attr),
644             _ => None,
645         }
646     }
647
648     /// Returns `None` if this is `Res::Err`
649     pub fn ns(&self) -> Option<Namespace> {
650         match self {
651             Res::Def(kind, ..) => kind.ns(),
652             Res::PrimTy(..) | Res::SelfTy { .. } | Res::ToolMod => Some(Namespace::TypeNS),
653             Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
654             Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
655             Res::Err => None,
656         }
657     }
658
659     /// Always returns `true` if `self` is `Res::Err`
660     pub fn matches_ns(&self, ns: Namespace) -> bool {
661         self.ns().map_or(true, |actual_ns| actual_ns == ns)
662     }
663
664     /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
665     pub fn expected_in_tuple_struct_pat(&self) -> bool {
666         matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
667     }
668 }