]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/path.rs
Fix resolution of eager macro contents
[rust.git] / crates / hir_def / src / path.rs
1 //! A desugared representation of paths like `crate::foo` or `<Type as Trait>::bar`.
2 mod lower;
3
4 use std::{
5     fmt::{self, Display},
6     iter,
7 };
8
9 use crate::{body::LowerCtx, intern::Interned, type_ref::LifetimeRef};
10 use hir_expand::name::{name, Name};
11 use syntax::ast;
12
13 use crate::type_ref::{TypeBound, TypeRef};
14
15 pub use hir_expand::mod_path::{path, ModPath, PathKind};
16
17 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub enum ImportAlias {
19     /// Unnamed alias, as in `use Foo as _;`
20     Underscore,
21     /// Named alias
22     Alias(Name),
23 }
24
25 impl Display for ImportAlias {
26     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27         match self {
28             ImportAlias::Underscore => f.write_str("_"),
29             ImportAlias::Alias(name) => f.write_str(&name.to_smol_str()),
30         }
31     }
32 }
33
34 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
35 pub struct Path {
36     /// Type based path like `<T>::foo`.
37     /// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
38     type_anchor: Option<Interned<TypeRef>>,
39     mod_path: Interned<ModPath>,
40     /// Invariant: the same len as `self.mod_path.segments`
41     generic_args: Box<[Option<Interned<GenericArgs>>]>,
42 }
43
44 /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
45 /// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
46 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
47 pub struct GenericArgs {
48     pub args: Vec<GenericArg>,
49     /// This specifies whether the args contain a Self type as the first
50     /// element. This is the case for path segments like `<T as Trait>`, where
51     /// `T` is actually a type parameter for the path `Trait` specifying the
52     /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
53     /// is left out.
54     pub has_self_type: bool,
55     /// Associated type bindings like in `Iterator<Item = T>`.
56     pub bindings: Vec<AssociatedTypeBinding>,
57     /// Whether these generic args were desugared from `Trait(Arg) -> Output`
58     /// parenthesis notation typically used for the `Fn` traits.
59     pub desugared_from_fn: bool,
60 }
61
62 /// An associated type binding like in `Iterator<Item = T>`.
63 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
64 pub struct AssociatedTypeBinding {
65     /// The name of the associated type.
66     pub name: Name,
67     /// The type bound to this associated type (in `Item = T`, this would be the
68     /// `T`). This can be `None` if there are bounds instead.
69     pub type_ref: Option<TypeRef>,
70     /// Bounds for the associated type, like in `Iterator<Item:
71     /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
72     /// feature.)
73     pub bounds: Vec<Interned<TypeBound>>,
74 }
75
76 /// A single generic argument.
77 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
78 pub enum GenericArg {
79     Type(TypeRef),
80     Lifetime(LifetimeRef),
81 }
82
83 impl Path {
84     /// Converts an `ast::Path` to `Path`. Works with use trees.
85     /// It correctly handles `$crate` based path from macro call.
86     pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
87         lower::lower_path(path, ctx)
88     }
89
90     /// Converts a known mod path to `Path`.
91     pub fn from_known_path(
92         path: ModPath,
93         generic_args: impl Into<Box<[Option<Interned<GenericArgs>>]>>,
94     ) -> Path {
95         Path { type_anchor: None, mod_path: Interned::new(path), generic_args: generic_args.into() }
96     }
97
98     pub fn kind(&self) -> &PathKind {
99         &self.mod_path.kind
100     }
101
102     pub fn type_anchor(&self) -> Option<&TypeRef> {
103         self.type_anchor.as_deref()
104     }
105
106     pub fn segments(&self) -> PathSegments<'_> {
107         PathSegments { segments: self.mod_path.segments(), generic_args: &self.generic_args }
108     }
109
110     pub fn mod_path(&self) -> &ModPath {
111         &self.mod_path
112     }
113
114     pub fn qualifier(&self) -> Option<Path> {
115         if self.mod_path.is_ident() {
116             return None;
117         }
118         let res = Path {
119             type_anchor: self.type_anchor.clone(),
120             mod_path: Interned::new(ModPath::from_segments(
121                 self.mod_path.kind.clone(),
122                 self.mod_path.segments()[..self.mod_path.segments().len() - 1].iter().cloned(),
123             )),
124             generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec().into(),
125         };
126         Some(res)
127     }
128
129     pub fn is_self_type(&self) -> bool {
130         self.type_anchor.is_none()
131             && *self.generic_args == [None]
132             && self.mod_path.as_ident() == Some(&name!(Self))
133     }
134 }
135
136 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
137 pub struct PathSegment<'a> {
138     pub name: &'a Name,
139     pub args_and_bindings: Option<&'a GenericArgs>,
140 }
141
142 pub struct PathSegments<'a> {
143     segments: &'a [Name],
144     generic_args: &'a [Option<Interned<GenericArgs>>],
145 }
146
147 impl<'a> PathSegments<'a> {
148     pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
149     pub fn is_empty(&self) -> bool {
150         self.len() == 0
151     }
152     pub fn len(&self) -> usize {
153         self.segments.len()
154     }
155     pub fn first(&self) -> Option<PathSegment<'a>> {
156         self.get(0)
157     }
158     pub fn last(&self) -> Option<PathSegment<'a>> {
159         self.get(self.len().checked_sub(1)?)
160     }
161     pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
162         assert_eq!(self.segments.len(), self.generic_args.len());
163         let res = PathSegment {
164             name: self.segments.get(idx)?,
165             args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
166         };
167         Some(res)
168     }
169     pub fn skip(&self, len: usize) -> PathSegments<'a> {
170         assert_eq!(self.segments.len(), self.generic_args.len());
171         PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
172     }
173     pub fn take(&self, len: usize) -> PathSegments<'a> {
174         assert_eq!(self.segments.len(), self.generic_args.len());
175         PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
176     }
177     pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
178         self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
179             name,
180             args_and_bindings: args.as_ref().map(|it| &**it),
181         })
182     }
183 }
184
185 impl GenericArgs {
186     pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
187         lower::lower_generic_args(lower_ctx, node)
188     }
189
190     pub(crate) fn empty() -> GenericArgs {
191         GenericArgs {
192             args: Vec::new(),
193             has_self_type: false,
194             bindings: Vec::new(),
195             desugared_from_fn: false,
196         }
197     }
198 }
199
200 impl From<Name> for Path {
201     fn from(name: Name) -> Path {
202         Path {
203             type_anchor: None,
204             mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
205             generic_args: Box::new([None]),
206         }
207     }
208 }
209
210 impl From<Name> for Box<Path> {
211     fn from(name: Name) -> Box<Path> {
212         Box::new(Path::from(name))
213     }
214 }