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