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