]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/path/lower.rs
Merge #8207
[rust.git] / crates / hir_def / src / path / lower.rs
1 //! Transforms syntax into `Path` objects, ideally with accounting for hygiene
2
3 mod lower_use;
4
5 use crate::intern::Interned;
6 use std::sync::Arc;
7
8 use either::Either;
9 use hir_expand::{
10     hygiene::Hygiene,
11     name::{name, AsName},
12 };
13 use syntax::ast::{self, AstNode, TypeBoundsOwner};
14
15 use super::AssociatedTypeBinding;
16 use crate::{
17     body::LowerCtx,
18     path::{GenericArg, GenericArgs, ModPath, Path, PathKind},
19     type_ref::{LifetimeRef, TypeBound, TypeRef},
20 };
21
22 pub(super) use lower_use::lower_use_tree;
23
24 /// Converts an `ast::Path` to `Path`. Works with use trees.
25 /// It correctly handles `$crate` based path from macro call.
26 pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> {
27     let mut kind = PathKind::Plain;
28     let mut type_anchor = None;
29     let mut segments = Vec::new();
30     let mut generic_args = Vec::new();
31     let ctx = LowerCtx::with_hygiene(hygiene);
32     loop {
33         let segment = path.segment()?;
34
35         if segment.coloncolon_token().is_some() {
36             kind = PathKind::Abs;
37         }
38
39         match segment.kind()? {
40             ast::PathSegmentKind::Name(name_ref) => {
41                 // FIXME: this should just return name
42                 match hygiene.name_ref_to_name(name_ref) {
43                     Either::Left(name) => {
44                         let args = segment
45                             .generic_arg_list()
46                             .and_then(|it| lower_generic_args(&ctx, it))
47                             .or_else(|| {
48                                 lower_generic_args_from_fn_path(
49                                     &ctx,
50                                     segment.param_list(),
51                                     segment.ret_type(),
52                                 )
53                             })
54                             .map(Arc::new);
55                         segments.push(name);
56                         generic_args.push(args)
57                     }
58                     Either::Right(crate_id) => {
59                         kind = PathKind::DollarCrate(crate_id);
60                         break;
61                     }
62                 }
63             }
64             ast::PathSegmentKind::Type { type_ref, trait_ref } => {
65                 assert!(path.qualifier().is_none()); // this can only occur at the first segment
66
67                 let self_type = TypeRef::from_ast(&ctx, type_ref?);
68
69                 match trait_ref {
70                     // <T>::foo
71                     None => {
72                         type_anchor = Some(Interned::new(self_type));
73                         kind = PathKind::Plain;
74                     }
75                     // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo
76                     Some(trait_ref) => {
77                         let path = Path::from_src(trait_ref.path()?, hygiene)?;
78                         let mod_path = (*path.mod_path).clone();
79                         let num_segments = path.mod_path.segments.len();
80                         kind = mod_path.kind;
81
82                         let mut prefix_segments = mod_path.segments;
83                         prefix_segments.reverse();
84                         segments.extend(prefix_segments);
85
86                         let mut prefix_args = path.generic_args;
87                         prefix_args.reverse();
88                         generic_args.extend(prefix_args);
89
90                         // Insert the type reference (T in the above example) as Self parameter for the trait
91                         let last_segment =
92                             generic_args.iter_mut().rev().nth(num_segments.saturating_sub(1))?;
93                         if last_segment.is_none() {
94                             *last_segment = Some(Arc::new(GenericArgs::empty()));
95                         };
96                         let args = last_segment.as_mut().unwrap();
97                         let mut args_inner = Arc::make_mut(args);
98                         args_inner.has_self_type = true;
99                         args_inner.args.insert(0, GenericArg::Type(self_type));
100                     }
101                 }
102             }
103             ast::PathSegmentKind::CrateKw => {
104                 kind = PathKind::Crate;
105                 break;
106             }
107             ast::PathSegmentKind::SelfKw => {
108                 // don't break out if `self` is the last segment of a path, this mean we got an
109                 // use tree like `foo::{self}` which we want to resolve as `foo`
110                 if !segments.is_empty() {
111                     kind = PathKind::Super(0);
112                     break;
113                 }
114             }
115             ast::PathSegmentKind::SuperKw => {
116                 let nested_super_count = if let PathKind::Super(n) = kind { n } else { 0 };
117                 kind = PathKind::Super(nested_super_count + 1);
118             }
119         }
120         path = match qualifier(&path) {
121             Some(it) => it,
122             None => break,
123         };
124     }
125     segments.reverse();
126     generic_args.reverse();
127
128     if segments.is_empty() && kind == PathKind::Plain && type_anchor.is_none() {
129         // plain empty paths don't exist, this means we got a single `self` segment as our path
130         kind = PathKind::Super(0);
131     }
132
133     // handle local_inner_macros :
134     // Basically, even in rustc it is quite hacky:
135     // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456
136     // We follow what it did anyway :)
137     if segments.len() == 1 && kind == PathKind::Plain {
138         if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) {
139             if let Some(crate_id) = hygiene.local_inner_macros(path) {
140                 kind = PathKind::DollarCrate(crate_id);
141             }
142         }
143     }
144
145     let mod_path = Interned::new(ModPath::from_segments(kind, segments));
146     return Some(Path { type_anchor, mod_path, generic_args });
147
148     fn qualifier(path: &ast::Path) -> Option<ast::Path> {
149         if let Some(q) = path.qualifier() {
150             return Some(q);
151         }
152         // FIXME: this bottom up traversal is not too precise.
153         // Should we handle do a top-down analysis, recording results?
154         let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
155         let use_tree = use_tree_list.parent_use_tree();
156         use_tree.path()
157     }
158 }
159
160 pub(super) fn lower_generic_args(
161     lower_ctx: &LowerCtx,
162     node: ast::GenericArgList,
163 ) -> Option<GenericArgs> {
164     let mut args = Vec::new();
165     let mut bindings = Vec::new();
166     for generic_arg in node.generic_args() {
167         match generic_arg {
168             ast::GenericArg::TypeArg(type_arg) => {
169                 let type_ref = TypeRef::from_ast_opt(lower_ctx, type_arg.ty());
170                 args.push(GenericArg::Type(type_ref));
171             }
172             ast::GenericArg::AssocTypeArg(assoc_type_arg) => {
173                 if let Some(name_ref) = assoc_type_arg.name_ref() {
174                     let name = name_ref.as_name();
175                     let type_ref = assoc_type_arg.ty().map(|it| TypeRef::from_ast(lower_ctx, it));
176                     let bounds = if let Some(l) = assoc_type_arg.type_bound_list() {
177                         l.bounds().map(|it| TypeBound::from_ast(lower_ctx, it)).collect()
178                     } else {
179                         Vec::new()
180                     };
181                     bindings.push(AssociatedTypeBinding { name, type_ref, bounds });
182                 }
183             }
184             ast::GenericArg::LifetimeArg(lifetime_arg) => {
185                 if let Some(lifetime) = lifetime_arg.lifetime() {
186                     let lifetime_ref = LifetimeRef::new(&lifetime);
187                     args.push(GenericArg::Lifetime(lifetime_ref))
188                 }
189             }
190             // constants are ignored for now.
191             ast::GenericArg::ConstArg(_) => (),
192         }
193     }
194
195     if args.is_empty() && bindings.is_empty() {
196         return None;
197     }
198     Some(GenericArgs { args, has_self_type: false, bindings })
199 }
200
201 /// Collect `GenericArgs` from the parts of a fn-like path, i.e. `Fn(X, Y)
202 /// -> Z` (which desugars to `Fn<(X, Y), Output=Z>`).
203 fn lower_generic_args_from_fn_path(
204     ctx: &LowerCtx,
205     params: Option<ast::ParamList>,
206     ret_type: Option<ast::RetType>,
207 ) -> Option<GenericArgs> {
208     let mut args = Vec::new();
209     let mut bindings = Vec::new();
210     if let Some(params) = params {
211         let mut param_types = Vec::new();
212         for param in params.params() {
213             let type_ref = TypeRef::from_ast_opt(&ctx, param.ty());
214             param_types.push(type_ref);
215         }
216         let arg = GenericArg::Type(TypeRef::Tuple(param_types));
217         args.push(arg);
218     }
219     if let Some(ret_type) = ret_type {
220         let type_ref = TypeRef::from_ast_opt(&ctx, ret_type.ty());
221         bindings.push(AssociatedTypeBinding {
222             name: name![Output],
223             type_ref: Some(type_ref),
224             bounds: Vec::new(),
225         });
226     }
227     if args.is_empty() && bindings.is_empty() {
228         None
229     } else {
230         Some(GenericArgs { args, has_self_type: false, bindings })
231     }
232 }