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