]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/path.rs
Merge #10809
[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, db::DefDatabase, intern::Interned, type_ref::LifetimeRef};
10 use base_db::CrateId;
11 use hir_expand::{
12     hygiene::Hygiene,
13     name::{name, Name},
14 };
15 use syntax::ast;
16
17 use crate::type_ref::{TypeBound, TypeRef};
18
19 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
20 pub struct ModPath {
21     pub kind: PathKind,
22     segments: Vec<Name>,
23 }
24
25 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
26 pub enum PathKind {
27     Plain,
28     /// `self::` is `Super(0)`
29     Super(u8),
30     Crate,
31     /// Absolute path (::foo)
32     Abs,
33     /// `$crate` from macro expansion
34     DollarCrate(CrateId),
35 }
36
37 #[derive(Debug, Clone, PartialEq, Eq)]
38 pub enum ImportAlias {
39     /// Unnamed alias, as in `use Foo as _;`
40     Underscore,
41     /// Named alias
42     Alias(Name),
43 }
44
45 impl Display for ImportAlias {
46     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47         match self {
48             ImportAlias::Underscore => f.write_str("_"),
49             ImportAlias::Alias(name) => f.write_str(&name.to_smol_str()),
50         }
51     }
52 }
53
54 impl ModPath {
55     pub fn from_src(db: &dyn DefDatabase, path: ast::Path, hygiene: &Hygiene) -> Option<ModPath> {
56         lower::convert_path(db, None, path, hygiene)
57     }
58
59     pub fn from_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> ModPath {
60         let segments = segments.into_iter().collect::<Vec<_>>();
61         ModPath { kind, segments }
62     }
63
64     /// Creates a `ModPath` from a `PathKind`, with no extra path segments.
65     pub const fn from_kind(kind: PathKind) -> ModPath {
66         ModPath { kind, segments: Vec::new() }
67     }
68
69     pub fn segments(&self) -> &[Name] {
70         &self.segments
71     }
72
73     pub fn push_segment(&mut self, segment: Name) {
74         self.segments.push(segment);
75     }
76
77     pub fn pop_segment(&mut self) -> Option<Name> {
78         self.segments.pop()
79     }
80
81     /// Returns the number of segments in the path (counting special segments like `$crate` and
82     /// `super`).
83     pub fn len(&self) -> usize {
84         self.segments.len()
85             + match self.kind {
86                 PathKind::Plain => 0,
87                 PathKind::Super(i) => i as usize,
88                 PathKind::Crate => 1,
89                 PathKind::Abs => 0,
90                 PathKind::DollarCrate(_) => 1,
91             }
92     }
93
94     pub fn is_ident(&self) -> bool {
95         self.as_ident().is_some()
96     }
97
98     pub fn is_self(&self) -> bool {
99         self.kind == PathKind::Super(0) && self.segments.is_empty()
100     }
101
102     /// If this path is a single identifier, like `foo`, return its name.
103     pub fn as_ident(&self) -> Option<&Name> {
104         if self.kind != PathKind::Plain {
105             return None;
106         }
107
108         match &*self.segments {
109             [name] => Some(name),
110             _ => None,
111         }
112     }
113 }
114
115 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
116 pub struct Path {
117     /// Type based path like `<T>::foo`.
118     /// Note that paths like `<Type as Trait>::foo` are desugard to `Trait::<Self=Type>::foo`.
119     type_anchor: Option<Interned<TypeRef>>,
120     mod_path: Interned<ModPath>,
121     /// Invariant: the same len as `self.mod_path.segments`
122     generic_args: Box<[Option<Interned<GenericArgs>>]>,
123 }
124
125 /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This
126 /// also includes bindings of associated types, like in `Iterator<Item = Foo>`.
127 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
128 pub struct GenericArgs {
129     pub args: Vec<GenericArg>,
130     /// This specifies whether the args contain a Self type as the first
131     /// element. This is the case for path segments like `<T as Trait>`, where
132     /// `T` is actually a type parameter for the path `Trait` specifying the
133     /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type
134     /// is left out.
135     pub has_self_type: bool,
136     /// Associated type bindings like in `Iterator<Item = T>`.
137     pub bindings: Vec<AssociatedTypeBinding>,
138     /// Whether these generic args were desugared from `Trait(Arg) -> Output`
139     /// parenthesis notation typically used for the `Fn` traits.
140     pub desugared_from_fn: bool,
141 }
142
143 /// An associated type binding like in `Iterator<Item = T>`.
144 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
145 pub struct AssociatedTypeBinding {
146     /// The name of the associated type.
147     pub name: Name,
148     /// The type bound to this associated type (in `Item = T`, this would be the
149     /// `T`). This can be `None` if there are bounds instead.
150     pub type_ref: Option<TypeRef>,
151     /// Bounds for the associated type, like in `Iterator<Item:
152     /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
153     /// feature.)
154     pub bounds: Vec<Interned<TypeBound>>,
155 }
156
157 /// A single generic argument.
158 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
159 pub enum GenericArg {
160     Type(TypeRef),
161     Lifetime(LifetimeRef),
162 }
163
164 impl Path {
165     /// Converts an `ast::Path` to `Path`. Works with use trees.
166     /// It correctly handles `$crate` based path from macro call.
167     pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
168         lower::lower_path(path, ctx)
169     }
170
171     /// Converts a known mod path to `Path`.
172     pub fn from_known_path(
173         path: ModPath,
174         generic_args: impl Into<Box<[Option<Interned<GenericArgs>>]>>,
175     ) -> Path {
176         Path { type_anchor: None, mod_path: Interned::new(path), generic_args: generic_args.into() }
177     }
178
179     pub fn kind(&self) -> &PathKind {
180         &self.mod_path.kind
181     }
182
183     pub fn type_anchor(&self) -> Option<&TypeRef> {
184         self.type_anchor.as_deref()
185     }
186
187     pub fn segments(&self) -> PathSegments<'_> {
188         PathSegments {
189             segments: self.mod_path.segments.as_slice(),
190             generic_args: &self.generic_args,
191         }
192     }
193
194     pub fn mod_path(&self) -> &ModPath {
195         &self.mod_path
196     }
197
198     pub fn qualifier(&self) -> Option<Path> {
199         if self.mod_path.is_ident() {
200             return None;
201         }
202         let res = Path {
203             type_anchor: self.type_anchor.clone(),
204             mod_path: Interned::new(ModPath::from_segments(
205                 self.mod_path.kind.clone(),
206                 self.mod_path.segments[..self.mod_path.segments.len() - 1].iter().cloned(),
207             )),
208             generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec().into(),
209         };
210         Some(res)
211     }
212
213     pub fn is_self_type(&self) -> bool {
214         self.type_anchor.is_none()
215             && *self.generic_args == [None]
216             && self.mod_path.as_ident() == Some(&name!(Self))
217     }
218 }
219
220 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
221 pub struct PathSegment<'a> {
222     pub name: &'a Name,
223     pub args_and_bindings: Option<&'a GenericArgs>,
224 }
225
226 pub struct PathSegments<'a> {
227     segments: &'a [Name],
228     generic_args: &'a [Option<Interned<GenericArgs>>],
229 }
230
231 impl<'a> PathSegments<'a> {
232     pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
233     pub fn is_empty(&self) -> bool {
234         self.len() == 0
235     }
236     pub fn len(&self) -> usize {
237         self.segments.len()
238     }
239     pub fn first(&self) -> Option<PathSegment<'a>> {
240         self.get(0)
241     }
242     pub fn last(&self) -> Option<PathSegment<'a>> {
243         self.get(self.len().checked_sub(1)?)
244     }
245     pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
246         assert_eq!(self.segments.len(), self.generic_args.len());
247         let res = PathSegment {
248             name: self.segments.get(idx)?,
249             args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
250         };
251         Some(res)
252     }
253     pub fn skip(&self, len: usize) -> PathSegments<'a> {
254         assert_eq!(self.segments.len(), self.generic_args.len());
255         PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
256     }
257     pub fn take(&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 iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
262         self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
263             name,
264             args_and_bindings: args.as_ref().map(|it| &**it),
265         })
266     }
267 }
268
269 impl GenericArgs {
270     pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
271         lower::lower_generic_args(lower_ctx, node)
272     }
273
274     pub(crate) fn empty() -> GenericArgs {
275         GenericArgs {
276             args: Vec::new(),
277             has_self_type: false,
278             bindings: Vec::new(),
279             desugared_from_fn: false,
280         }
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: Box::new([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;