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