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