]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-def/src/path.rs
Auto merge of #102783 - RalfJung:tls, r=thomcc
[rust.git] / src / tools / rust-analyzer / 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;
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() && *self.generic_args == [None] && self.mod_path.is_Self()
138     }
139 }
140
141 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
142 pub struct PathSegment<'a> {
143     pub name: &'a Name,
144     pub args_and_bindings: Option<&'a GenericArgs>,
145 }
146
147 pub struct PathSegments<'a> {
148     segments: &'a [Name],
149     generic_args: &'a [Option<Interned<GenericArgs>>],
150 }
151
152 impl<'a> PathSegments<'a> {
153     pub const EMPTY: PathSegments<'static> = PathSegments { segments: &[], generic_args: &[] };
154     pub fn is_empty(&self) -> bool {
155         self.len() == 0
156     }
157     pub fn len(&self) -> usize {
158         self.segments.len()
159     }
160     pub fn first(&self) -> Option<PathSegment<'a>> {
161         self.get(0)
162     }
163     pub fn last(&self) -> Option<PathSegment<'a>> {
164         self.get(self.len().checked_sub(1)?)
165     }
166     pub fn get(&self, idx: usize) -> Option<PathSegment<'a>> {
167         assert_eq!(self.segments.len(), self.generic_args.len());
168         let res = PathSegment {
169             name: self.segments.get(idx)?,
170             args_and_bindings: self.generic_args.get(idx).unwrap().as_ref().map(|it| &**it),
171         };
172         Some(res)
173     }
174     pub fn skip(&self, len: usize) -> PathSegments<'a> {
175         assert_eq!(self.segments.len(), self.generic_args.len());
176         PathSegments { segments: &self.segments[len..], generic_args: &self.generic_args[len..] }
177     }
178     pub fn take(&self, len: usize) -> PathSegments<'a> {
179         assert_eq!(self.segments.len(), self.generic_args.len());
180         PathSegments { segments: &self.segments[..len], generic_args: &self.generic_args[..len] }
181     }
182     pub fn iter(&self) -> impl Iterator<Item = PathSegment<'a>> {
183         self.segments.iter().zip(self.generic_args.iter()).map(|(name, args)| PathSegment {
184             name,
185             args_and_bindings: args.as_ref().map(|it| &**it),
186         })
187     }
188 }
189
190 impl GenericArgs {
191     pub(crate) fn from_ast(
192         lower_ctx: &LowerCtx<'_>,
193         node: ast::GenericArgList,
194     ) -> Option<GenericArgs> {
195         lower::lower_generic_args(lower_ctx, node)
196     }
197
198     pub(crate) fn empty() -> GenericArgs {
199         GenericArgs {
200             args: Vec::new(),
201             has_self_type: false,
202             bindings: Vec::new(),
203             desugared_from_fn: false,
204         }
205     }
206 }
207
208 impl From<Name> for Path {
209     fn from(name: Name) -> Path {
210         Path {
211             type_anchor: None,
212             mod_path: Interned::new(ModPath::from_segments(PathKind::Plain, iter::once(name))),
213             generic_args: Box::new([None]),
214         }
215     }
216 }
217
218 impl From<Name> for Box<Path> {
219     fn from(name: Name) -> Box<Path> {
220         Box::new(Path::from(name))
221     }
222 }