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