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