]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/path.rs
Merge #8583
[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     sync::Arc,
8 };
9
10 use crate::{body::LowerCtx, intern::Interned, type_ref::LifetimeRef};
11 use base_db::CrateId;
12 use hir_expand::{
13     hygiene::Hygiene,
14     name::{name, Name},
15 };
16 use syntax::ast;
17
18 use crate::{
19     type_ref::{TypeBound, TypeRef},
20     InFile,
21 };
22
23 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
24 pub struct ModPath {
25     pub kind: PathKind,
26     segments: Vec<Name>,
27 }
28
29 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
30 pub enum PathKind {
31     Plain,
32     /// `self::` is `Super(0)`
33     Super(u8),
34     Crate,
35     /// Absolute path (::foo)
36     Abs,
37     /// `$crate` from macro expansion
38     DollarCrate(CrateId),
39 }
40
41 #[derive(Debug, Clone, PartialEq, Eq)]
42 pub enum ImportAlias {
43     /// Unnamed alias, as in `use Foo as _;`
44     Underscore,
45     /// Named alias
46     Alias(Name),
47 }
48
49 impl ModPath {
50     pub fn from_src(path: ast::Path, hygiene: &Hygiene) -> Option<ModPath> {
51         let ctx = LowerCtx::with_hygiene(hygiene);
52         lower::lower_path(path, &ctx).map(|it| (*it.mod_path).clone())
53     }
54
55     pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath {
56         let segments = segments.into_iter().collect::<Vec<_>>();
57         ModPath { kind, segments }
58     }
59
60     /// Creates a `ModPath` from a `PathKind`, with no extra path segments.
61     pub const fn from_kind(kind: PathKind) -> ModPath {
62         ModPath { kind, segments: Vec::new() }
63     }
64
65     /// Calls `cb` with all paths, represented by this use item.
66     pub(crate) fn expand_use_item(
67         item_src: InFile<ast::Use>,
68         hygiene: &Hygiene,
69         mut cb: impl FnMut(ModPath, &ast::UseTree, /* is_glob */ bool, Option<ImportAlias>),
70     ) {
71         if let Some(tree) = item_src.value.use_tree() {
72             lower::lower_use_tree(None, tree, hygiene, &mut cb);
73         }
74     }
75
76     pub fn segments(&self) -> &[Name] {
77         &self.segments
78     }
79
80     pub fn push_segment(&mut self, segment: Name) {
81         self.segments.push(segment);
82     }
83
84     pub fn pop_segment(&mut self) -> Option<Name> {
85         self.segments.pop()
86     }
87
88     /// Returns the number of segments in the path (counting special segments like `$crate` and
89     /// `super`).
90     pub fn len(&self) -> usize {
91         self.segments.len()
92             + match self.kind {
93                 PathKind::Plain => 0,
94                 PathKind::Super(i) => i as usize,
95                 PathKind::Crate => 1,
96                 PathKind::Abs => 0,
97                 PathKind::DollarCrate(_) => 1,
98             }
99     }
100
101     pub fn is_ident(&self) -> bool {
102         self.as_ident().is_some()
103     }
104
105     pub fn is_self(&self) -> bool {
106         self.kind == PathKind::Super(0) && self.segments.is_empty()
107     }
108
109     /// If this path is a single identifier, like `foo`, return its name.
110     pub fn as_ident(&self) -> Option<&Name> {
111         if self.kind != PathKind::Plain {
112             return None;
113         }
114
115         match &*self.segments {
116             [name] => Some(name),
117             _ => None,
118         }
119     }
120 }
121
122 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
123 pub struct Path {
124     /// Type based path like `<T>::foo`.
125     /// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
126     type_anchor: Option<Interned<TypeRef>>,
127     mod_path: Interned<ModPath>,
128     /// Invariant: the same len as `self.mod_path.segments`
129     generic_args: Vec<Option<Arc<GenericArgs>>>,
130 }
131
132 /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
133 /// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
134 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
135 pub struct GenericArgs {
136     pub args: Vec<GenericArg>,
137     /// This specifies whether the args contain a Self type as the first
138     /// element. This is the case for path segments like `<T as Trait>`, where
139     /// `T` is actually a type parameter for the path `Trait` specifying the
140     /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
141     /// is left out.
142     pub has_self_type: bool,
143     /// Associated type bindings like in `Iterator<Item = T>`.
144     pub bindings: Vec<AssociatedTypeBinding>,
145 }
146
147 /// An associated type binding like in `Iterator<Item = T>`.
148 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
149 pub struct AssociatedTypeBinding {
150     /// The name of the associated type.
151     pub name: Name,
152     /// The type bound to this associated type (in `Item = T`, this would be the
153     /// `T`). This can be `None` if there are bounds instead.
154     pub type_ref: Option<TypeRef>,
155     /// Bounds for the associated type, like in `Iterator<Item:
156     /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
157     /// feature.)
158     pub bounds: Vec<TypeBound>,
159 }
160
161 /// A single generic argument.
162 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
163 pub enum GenericArg {
164     Type(TypeRef),
165     Lifetime(LifetimeRef),
166 }
167
168 impl Path {
169     /// Converts an `ast::Path` to `Path`. Works with use trees.
170     /// It correctly handles `$crate` based path from macro call.
171     pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
172         lower::lower_path(path, ctx)
173     }
174
175     /// Converts a known mod path to `Path`.
176     pub(crate) fn from_known_path(
177         path: ModPath,
178         generic_args: Vec<Option<Arc<GenericArgs>>>,
179     ) -> Path {
180         Path { type_anchor: None, mod_path: Interned::new(path), generic_args }
181     }
182
183     pub fn kind(&self) -> &PathKind {
184         &self.mod_path.kind
185     }
186
187     pub fn type_anchor(&self) -> Option<&TypeRef> {
188         self.type_anchor.as_deref()
189     }
190
191     pub fn segments(&self) -> PathSegments<'_> {
192         PathSegments {
193             segments: self.mod_path.segments.as_slice(),
194             generic_args: self.generic_args.as_slice(),
195         }
196     }
197
198     pub fn mod_path(&self) -> &ModPath {
199         &self.mod_path
200     }
201
202     pub fn qualifier(&self) -> Option<Path> {
203         if self.mod_path.is_ident() {
204             return None;
205         }
206         let res = Path {
207             type_anchor: self.type_anchor.clone(),
208             mod_path: Interned::new(ModPath::from_segments(
209                 self.mod_path.kind.clone(),
210                 self.mod_path.segments[..self.mod_path.segments.len() - 1].iter().cloned(),
211             )),
212             generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec(),
213         };
214         Some(res)
215     }
216
217     pub fn is_self_type(&self) -> bool {
218         self.type_anchor.is_none()
219             && self.generic_args == &[None]
220             && self.mod_path.as_ident() == Some(&name!(Self))
221     }
222 }
223
224 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
225 pub struct PathSegment<'a> {
226     pub name: &'a Name,
227     pub args_and_bindings: Option<&'a GenericArgs>,
228 }
229
230 pub struct PathSegments<'a> {
231     segments: &'a [Name],
232     generic_args: &'a [Option<Arc<GenericArgs>>],
233 }
234
235 impl<'a> PathSegments<'a> {
236     pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
237     pub fn is_empty(&self) -> bool {
238         self.len() == 0
239     }
240     pub fn len(&self) -> usize {
241         self.segments.len()
242     }
243     pub fn first(&self) -> Option<PathSegment<'a>> {
244         self.get(0)
245     }
246     pub fn last(&self) -> Option<PathSegment<'a>> {
247         self.get(self.len().checked_sub(1)?)
248     }
249     pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
250         assert_eq!(self.segments.len(), self.generic_args.len());
251         let res = PathSegment {
252             name: self.segments.get(idx)?,
253             args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
254         };
255         Some(res)
256     }
257     pub fn skip(&self, len: usize) -> PathSegments<'a> {
258         assert_eq!(self.segments.len(), self.generic_args.len());
259         PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
260     }
261     pub fn take(&self, len: usize) -> PathSegments<'a> {
262         assert_eq!(self.segments.len(), self.generic_args.len());
263         PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
264     }
265     pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
266         self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
267             name,
268             args_and_bindings: args.as_ref().map(|it| &**it),
269         })
270     }
271 }
272
273 impl GenericArgs {
274     pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
275         lower::lower_generic_args(lower_ctx, node)
276     }
277
278     pub(crate) fn empty() -> GenericArgs {
279         GenericArgs { args: Vec::new(), has_self_type: false, bindings: Vec::new() }
280     }
281 }
282
283 impl From<Name> for Path {
284     fn from(name: Name) -> Path {
285         Path {
286             type_anchor: None,
287             mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
288             generic_args: vec![None],
289         }
290     }
291 }
292
293 impl From<Name> for Box<Path> {
294     fn from(name: Name) -> Box<Path> {
295         Box::new(Path::from(name))
296     }
297 }
298
299 impl From<Name> for ModPath {
300     fn from(name: Name) -> ModPath {
301         ModPath::from_segments(PathKind::Plain, iter::once(name))
302     }
303 }
304
305 impl Display for ModPath {
306     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307         let mut first_segment = true;
308         let mut add_segment = |s| -> fmt::Result {
309             if !first_segment {
310                 f.write_str("::")?;
311             }
312             first_segment = false;
313             f.write_str(s)?;
314             Ok(())
315         };
316         match self.kind {
317             PathKind::Plain => {}
318             PathKind::Super(0) => add_segment("self")?,
319             PathKind::Super(n) => {
320                 for _ in 0..n {
321                     add_segment("super")?;
322                 }
323             }
324             PathKind::Crate => add_segment("crate")?,
325             PathKind::Abs => add_segment("")?,
326             PathKind::DollarCrate(_) => add_segment("$crate")?,
327         }
328         for segment in &self.segments {
329             if !first_segment {
330                 f.write_str("::")?;
331             }
332             first_segment = false;
333             write!(f, "{}", segment)?;
334         }
335         Ok(())
336     }
337 }
338
339 pub use hir_expand::name as __name;
340
341 #[macro_export]
342 macro_rules! __known_path {
343     (core::iter::IntoIterator) => {};
344     (core::iter::Iterator) => {};
345     (core::result::Result) => {};
346     (core::option::Option) => {};
347     (core::ops::Range) => {};
348     (core::ops::RangeFrom) => {};
349     (core::ops::RangeFull) => {};
350     (core::ops::RangeTo) => {};
351     (core::ops::RangeToInclusive) => {};
352     (core::ops::RangeInclusive) => {};
353     (core::future::Future) => {};
354     (core::ops::Try) => {};
355     ($path:path) => {
356         compile_error!("Please register your known path in the path module")
357     };
358 }
359
360 #[macro_export]
361 macro_rules! __path {
362     ($start:ident $(:: $seg:ident)*) => ({
363         $crate::__known_path!($start $(:: $seg)*);
364         $crate::path::ModPath::from_segments($crate::path::PathKind::Abs, vec![
365             $crate::path::__name![$start], $($crate::path::__name![$seg],)*
366         ])
367     });
368 }
369
370 pub use crate::__path as path;