]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/path.rs
Merge #9368
[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, 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_string()),
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: Vec<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 }
139
140 /// An associated type binding like in `Iterator<Item = T>`.
141 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
142 pub struct AssociatedTypeBinding {
143     /// The name of the associated type.
144     pub name: Name,
145     /// The type bound to this associated type (in `Item = T`, this would be the
146     /// `T`). This can be `None` if there are bounds instead.
147     pub type_ref: Option<TypeRef>,
148     /// Bounds for the associated type, like in `Iterator<Item:
149     /// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
150     /// feature.)
151     pub bounds: Vec<Interned<TypeBound>>,
152 }
153
154 /// A single generic argument.
155 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
156 pub enum GenericArg {
157     Type(TypeRef),
158     Lifetime(LifetimeRef),
159 }
160
161 impl Path {
162     /// Converts an `ast::Path` to `Path`. Works with use trees.
163     /// It correctly handles `$crate` based path from macro call.
164     pub fn from_src(path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
165         lower::lower_path(path, ctx)
166     }
167
168     /// Converts a known mod path to `Path`.
169     pub fn from_known_path(
170         path: ModPath,
171         generic_args: Vec<Option<Interned<GenericArgs>>>,
172     ) -> Path {
173         Path { type_anchor: None, mod_path: Interned::new(path), generic_args }
174     }
175
176     pub fn kind(&self) -> &PathKind {
177         &self.mod_path.kind
178     }
179
180     pub fn type_anchor(&self) -> Option<&TypeRef> {
181         self.type_anchor.as_deref()
182     }
183
184     pub fn segments(&self) -> PathSegments<'_> {
185         PathSegments {
186             segments: self.mod_path.segments.as_slice(),
187             generic_args: self.generic_args.as_slice(),
188         }
189     }
190
191     pub fn mod_path(&self) -> &ModPath {
192         &self.mod_path
193     }
194
195     pub fn qualifier(&self) -> Option<Path> {
196         if self.mod_path.is_ident() {
197             return None;
198         }
199         let res = Path {
200             type_anchor: self.type_anchor.clone(),
201             mod_path: Interned::new(ModPath::from_segments(
202                 self.mod_path.kind.clone(),
203                 self.mod_path.segments[..self.mod_path.segments.len() - 1].iter().cloned(),
204             )),
205             generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec(),
206         };
207         Some(res)
208     }
209
210     pub fn is_self_type(&self) -> bool {
211         self.type_anchor.is_none()
212             && self.generic_args == [None]
213             && self.mod_path.as_ident() == Some(&name!(Self))
214     }
215 }
216
217 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
218 pub struct PathSegment<'a> {
219     pub name: &'a Name,
220     pub args_and_bindings: Option<&'a GenericArgs>,
221 }
222
223 pub struct PathSegments<'a> {
224     segments: &'a [Name],
225     generic_args: &'a [Option<Interned<GenericArgs>>],
226 }
227
228 impl<'a> PathSegments<'a> {
229     pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
230     pub fn is_empty(&self) -> bool {
231         self.len() == 0
232     }
233     pub fn len(&self) -> usize {
234         self.segments.len()
235     }
236     pub fn first(&self) -> Option<PathSegment<'a>> {
237         self.get(0)
238     }
239     pub fn last(&self) -> Option<PathSegment<'a>> {
240         self.get(self.len().checked_sub(1)?)
241     }
242     pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
243         assert_eq!(self.segments.len(), self.generic_args.len());
244         let res = PathSegment {
245             name: self.segments.get(idx)?,
246             args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
247         };
248         Some(res)
249     }
250     pub fn skip(&self, len: usize) -> PathSegments<'a> {
251         assert_eq!(self.segments.len(), self.generic_args.len());
252         PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
253     }
254     pub fn take(&self, len: usize) -> PathSegments<'a> {
255         assert_eq!(self.segments.len(), self.generic_args.len());
256         PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
257     }
258     pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
259         self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
260             name,
261             args_and_bindings: args.as_ref().map(|it| &**it),
262         })
263     }
264 }
265
266 impl GenericArgs {
267     pub(crate) fn from_ast(lower_ctx: &LowerCtx, node: ast::GenericArgList) -> Option<GenericArgs> {
268         lower::lower_generic_args(lower_ctx, node)
269     }
270
271     pub(crate) fn empty() -> GenericArgs {
272         GenericArgs { args: Vec::new(), has_self_type: false, bindings: Vec::new() }
273     }
274 }
275
276 impl From<Name> for Path {
277     fn from(name: Name) -> Path {
278         Path {
279             type_anchor: None,
280             mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
281             generic_args: vec![None],
282         }
283     }
284 }
285
286 impl From<Name> for Box<Path> {
287     fn from(name: Name) -> Box<Path> {
288         Box::new(Path::from(name))
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;