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