]>
Commit | Line | Data |
---|---|---|
416331ca XL |
1 | use super::LoweringContext; |
2 | use super::ImplTraitContext; | |
3 | use super::ImplTraitPosition; | |
4 | use super::ImplTraitTypeIdVisitor; | |
5 | use super::AnonymousLifetimeMode; | |
6 | use super::ParamMode; | |
7 | ||
8 | use crate::hir::{self, HirVec}; | |
9 | use crate::hir::ptr::P; | |
10 | use crate::hir::def_id::DefId; | |
11 | use crate::hir::def::{Res, DefKind}; | |
12 | use crate::util::nodemap::NodeMap; | |
13 | ||
14 | use rustc_data_structures::thin_vec::ThinVec; | |
15 | ||
16 | use std::collections::BTreeSet; | |
17 | use smallvec::SmallVec; | |
18 | use syntax::attr; | |
19 | use syntax::ast::*; | |
20 | use syntax::visit::{self, Visitor}; | |
21 | use syntax::ext::base::SpecialDerives; | |
22 | use syntax::source_map::{respan, DesugaringKind, Spanned}; | |
23 | use syntax::symbol::{kw, sym}; | |
24 | use syntax_pos::Span; | |
25 | ||
26 | pub(super) struct ItemLowerer<'tcx, 'interner> { | |
27 | pub(super) lctx: &'tcx mut LoweringContext<'interner>, | |
28 | } | |
29 | ||
30 | impl<'tcx, 'interner> ItemLowerer<'tcx, 'interner> { | |
31 | fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F) | |
32 | where | |
33 | F: FnOnce(&mut Self), | |
34 | { | |
35 | let old = self.lctx.is_in_trait_impl; | |
36 | self.lctx.is_in_trait_impl = if let &None = trait_impl_ref { | |
37 | false | |
38 | } else { | |
39 | true | |
40 | }; | |
41 | f(self); | |
42 | self.lctx.is_in_trait_impl = old; | |
43 | } | |
44 | } | |
45 | ||
46 | impl<'tcx, 'interner> Visitor<'tcx> for ItemLowerer<'tcx, 'interner> { | |
47 | fn visit_mod(&mut self, m: &'tcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) { | |
48 | self.lctx.modules.insert(n, hir::ModuleItems { | |
49 | items: BTreeSet::new(), | |
50 | trait_items: BTreeSet::new(), | |
51 | impl_items: BTreeSet::new(), | |
52 | }); | |
53 | ||
54 | let old = self.lctx.current_module; | |
55 | self.lctx.current_module = n; | |
56 | visit::walk_mod(self, m); | |
57 | self.lctx.current_module = old; | |
58 | } | |
59 | ||
60 | fn visit_item(&mut self, item: &'tcx Item) { | |
61 | let mut item_hir_id = None; | |
62 | self.lctx.with_hir_id_owner(item.id, |lctx| { | |
e1599b0c XL |
63 | lctx.without_in_scope_lifetime_defs(|lctx| { |
64 | if let Some(hir_item) = lctx.lower_item(item) { | |
65 | item_hir_id = Some(hir_item.hir_id); | |
66 | lctx.insert_item(hir_item); | |
67 | } | |
68 | }) | |
416331ca XL |
69 | }); |
70 | ||
71 | if let Some(hir_id) = item_hir_id { | |
72 | self.lctx.with_parent_item_lifetime_defs(hir_id, |this| { | |
73 | let this = &mut ItemLowerer { lctx: this }; | |
74 | if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node { | |
75 | this.with_trait_impl_ref(opt_trait_ref, |this| { | |
76 | visit::walk_item(this, item) | |
77 | }); | |
78 | } else { | |
79 | visit::walk_item(this, item); | |
80 | } | |
81 | }); | |
82 | } | |
83 | } | |
84 | ||
85 | fn visit_trait_item(&mut self, item: &'tcx TraitItem) { | |
86 | self.lctx.with_hir_id_owner(item.id, |lctx| { | |
87 | let hir_item = lctx.lower_trait_item(item); | |
88 | let id = hir::TraitItemId { hir_id: hir_item.hir_id }; | |
89 | lctx.trait_items.insert(id, hir_item); | |
90 | lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id); | |
91 | }); | |
92 | ||
93 | visit::walk_trait_item(self, item); | |
94 | } | |
95 | ||
96 | fn visit_impl_item(&mut self, item: &'tcx ImplItem) { | |
97 | self.lctx.with_hir_id_owner(item.id, |lctx| { | |
98 | let hir_item = lctx.lower_impl_item(item); | |
99 | let id = hir::ImplItemId { hir_id: hir_item.hir_id }; | |
100 | lctx.impl_items.insert(id, hir_item); | |
101 | lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id); | |
102 | }); | |
103 | visit::walk_impl_item(self, item); | |
104 | } | |
105 | } | |
106 | ||
107 | impl LoweringContext<'_> { | |
108 | // Same as the method above, but accepts `hir::GenericParam`s | |
109 | // instead of `ast::GenericParam`s. | |
110 | // This should only be used with generics that have already had their | |
111 | // in-band lifetimes added. In practice, this means that this function is | |
112 | // only used when lowering a child item of a trait or impl. | |
113 | fn with_parent_item_lifetime_defs<T>( | |
114 | &mut self, | |
115 | parent_hir_id: hir::HirId, | |
116 | f: impl FnOnce(&mut LoweringContext<'_>) -> T, | |
117 | ) -> T { | |
118 | let old_len = self.in_scope_lifetimes.len(); | |
119 | ||
120 | let parent_generics = match self.items.get(&parent_hir_id).unwrap().node { | |
121 | hir::ItemKind::Impl(_, _, _, ref generics, ..) | |
122 | | hir::ItemKind::Trait(_, _, ref generics, ..) => { | |
123 | &generics.params[..] | |
124 | } | |
125 | _ => &[], | |
126 | }; | |
127 | let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind { | |
e1599b0c | 128 | hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()), |
416331ca XL |
129 | _ => None, |
130 | }); | |
131 | self.in_scope_lifetimes.extend(lt_def_names); | |
132 | ||
133 | let res = f(self); | |
134 | ||
135 | self.in_scope_lifetimes.truncate(old_len); | |
136 | res | |
137 | } | |
138 | ||
e1599b0c XL |
139 | // Clears (and restores) the `in_scope_lifetimes` field. Used when |
140 | // visiting nested items, which never inherit in-scope lifetimes | |
141 | // from their surrounding environment. | |
142 | fn without_in_scope_lifetime_defs<T>( | |
143 | &mut self, | |
144 | f: impl FnOnce(&mut LoweringContext<'_>) -> T, | |
145 | ) -> T { | |
146 | let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]); | |
147 | ||
148 | // this vector is only used when walking over impl headers, | |
149 | // input types, and the like, and should not be non-empty in | |
150 | // between items | |
151 | assert!(self.lifetimes_to_define.is_empty()); | |
152 | ||
153 | let res = f(self); | |
154 | ||
155 | assert!(self.in_scope_lifetimes.is_empty()); | |
156 | self.in_scope_lifetimes = old_in_scope_lifetimes; | |
157 | ||
158 | res | |
159 | } | |
160 | ||
416331ca XL |
161 | pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod { |
162 | hir::Mod { | |
163 | inner: m.inner, | |
164 | item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(), | |
165 | } | |
166 | } | |
167 | ||
168 | pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> { | |
169 | let node_ids = match i.node { | |
170 | ItemKind::Use(ref use_tree) => { | |
171 | let mut vec = smallvec![i.id]; | |
172 | self.lower_item_id_use_tree(use_tree, i.id, &mut vec); | |
173 | vec | |
174 | } | |
175 | ItemKind::MacroDef(..) => SmallVec::new(), | |
176 | ItemKind::Fn(..) | | |
177 | ItemKind::Impl(.., None, _, _) => smallvec![i.id], | |
178 | ItemKind::Static(ref ty, ..) => { | |
179 | let mut ids = smallvec![i.id]; | |
180 | if self.sess.features_untracked().impl_trait_in_bindings { | |
181 | let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids }; | |
182 | visitor.visit_ty(ty); | |
183 | } | |
184 | ids | |
185 | }, | |
186 | ItemKind::Const(ref ty, ..) => { | |
187 | let mut ids = smallvec![i.id]; | |
188 | if self.sess.features_untracked().impl_trait_in_bindings { | |
189 | let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids }; | |
190 | visitor.visit_ty(ty); | |
191 | } | |
192 | ids | |
193 | }, | |
194 | _ => smallvec![i.id], | |
195 | }; | |
196 | ||
197 | node_ids.into_iter().map(|node_id| hir::ItemId { | |
198 | id: self.allocate_hir_id_counter(node_id) | |
199 | }).collect() | |
200 | } | |
201 | ||
202 | fn lower_item_id_use_tree( | |
203 | &mut self, | |
204 | tree: &UseTree, | |
205 | base_id: NodeId, | |
206 | vec: &mut SmallVec<[NodeId; 1]> | |
207 | ) { | |
208 | match tree.kind { | |
209 | UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec { | |
210 | vec.push(id); | |
211 | self.lower_item_id_use_tree(nested, id, vec); | |
212 | }, | |
213 | UseTreeKind::Glob => {} | |
214 | UseTreeKind::Simple(_, id1, id2) => { | |
215 | for (_, &id) in self.expect_full_res_from_use(base_id) | |
216 | .skip(1) | |
217 | .zip([id1, id2].iter()) | |
218 | { | |
219 | vec.push(id); | |
220 | } | |
221 | }, | |
222 | } | |
223 | } | |
224 | ||
225 | pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> { | |
226 | let mut ident = i.ident; | |
227 | let mut vis = self.lower_visibility(&i.vis, None); | |
228 | let mut attrs = self.lower_attrs_extendable(&i.attrs); | |
229 | if self.resolver.has_derives(i.id, SpecialDerives::PARTIAL_EQ | SpecialDerives::EQ) { | |
230 | // Add `#[structural_match]` if the item derived both `PartialEq` and `Eq`. | |
231 | let ident = Ident::new(sym::structural_match, i.span); | |
232 | attrs.push(attr::mk_attr_outer(attr::mk_word_item(ident))); | |
233 | } | |
234 | let attrs = attrs.into(); | |
235 | ||
236 | if let ItemKind::MacroDef(ref def) = i.node { | |
237 | if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) { | |
238 | let body = self.lower_token_stream(def.stream()); | |
239 | let hir_id = self.lower_node_id(i.id); | |
240 | self.exported_macros.push(hir::MacroDef { | |
241 | name: ident.name, | |
242 | vis, | |
243 | attrs, | |
244 | hir_id, | |
245 | span: i.span, | |
246 | body, | |
247 | legacy: def.legacy, | |
248 | }); | |
249 | } else { | |
250 | self.non_exported_macro_attrs.extend(attrs.into_iter()); | |
251 | } | |
252 | return None; | |
253 | } | |
254 | ||
255 | let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node); | |
256 | ||
257 | Some(hir::Item { | |
258 | hir_id: self.lower_node_id(i.id), | |
259 | ident, | |
260 | attrs, | |
261 | node, | |
262 | vis, | |
263 | span: i.span, | |
264 | }) | |
265 | } | |
266 | ||
267 | fn lower_item_kind( | |
268 | &mut self, | |
269 | id: NodeId, | |
270 | ident: &mut Ident, | |
271 | attrs: &hir::HirVec<Attribute>, | |
272 | vis: &mut hir::Visibility, | |
273 | i: &ItemKind, | |
274 | ) -> hir::ItemKind { | |
275 | match *i { | |
276 | ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name), | |
277 | ItemKind::Use(ref use_tree) => { | |
278 | // Start with an empty prefix. | |
279 | let prefix = Path { | |
280 | segments: vec![], | |
281 | span: use_tree.span, | |
282 | }; | |
283 | ||
284 | self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs) | |
285 | } | |
286 | ItemKind::Static(ref t, m, ref e) => { | |
287 | hir::ItemKind::Static( | |
288 | self.lower_ty( | |
289 | t, | |
290 | if self.sess.features_untracked().impl_trait_in_bindings { | |
291 | ImplTraitContext::OpaqueTy(None) | |
292 | } else { | |
293 | ImplTraitContext::Disallowed(ImplTraitPosition::Binding) | |
294 | } | |
295 | ), | |
296 | self.lower_mutability(m), | |
297 | self.lower_const_body(e), | |
298 | ) | |
299 | } | |
300 | ItemKind::Const(ref t, ref e) => { | |
301 | hir::ItemKind::Const( | |
302 | self.lower_ty( | |
303 | t, | |
304 | if self.sess.features_untracked().impl_trait_in_bindings { | |
305 | ImplTraitContext::OpaqueTy(None) | |
306 | } else { | |
307 | ImplTraitContext::Disallowed(ImplTraitPosition::Binding) | |
308 | } | |
309 | ), | |
310 | self.lower_const_body(e) | |
311 | ) | |
312 | } | |
313 | ItemKind::Fn(ref decl, header, ref generics, ref body) => { | |
314 | let fn_def_id = self.resolver.definitions().local_def_id(id); | |
315 | self.with_new_scopes(|this| { | |
316 | this.current_item = Some(ident.span); | |
317 | ||
318 | // Note: we don't need to change the return type from `T` to | |
319 | // `impl Future<Output = T>` here because lower_body | |
320 | // only cares about the input argument patterns in the function | |
321 | // declaration (decl), not the return types. | |
322 | let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body); | |
323 | ||
324 | let (generics, fn_decl) = this.add_in_band_defs( | |
325 | generics, | |
326 | fn_def_id, | |
327 | AnonymousLifetimeMode::PassThrough, | |
328 | |this, idty| this.lower_fn_decl( | |
329 | &decl, | |
330 | Some((fn_def_id, idty)), | |
331 | true, | |
332 | header.asyncness.node.opt_return_id() | |
333 | ), | |
334 | ); | |
335 | ||
336 | hir::ItemKind::Fn( | |
337 | fn_decl, | |
338 | this.lower_fn_header(header), | |
339 | generics, | |
340 | body_id, | |
341 | ) | |
342 | }) | |
343 | } | |
344 | ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)), | |
345 | ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)), | |
346 | ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)), | |
347 | ItemKind::TyAlias(ref t, ref generics) => hir::ItemKind::TyAlias( | |
348 | self.lower_ty(t, ImplTraitContext::disallowed()), | |
349 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
350 | ), | |
351 | ItemKind::OpaqueTy(ref b, ref generics) => hir::ItemKind::OpaqueTy( | |
352 | hir::OpaqueTy { | |
353 | generics: self.lower_generics(generics, | |
354 | ImplTraitContext::OpaqueTy(None)), | |
355 | bounds: self.lower_param_bounds(b, | |
356 | ImplTraitContext::OpaqueTy(None)), | |
357 | impl_trait_fn: None, | |
358 | origin: hir::OpaqueTyOrigin::TypeAlias, | |
359 | }, | |
360 | ), | |
361 | ItemKind::Enum(ref enum_definition, ref generics) => { | |
362 | hir::ItemKind::Enum( | |
363 | hir::EnumDef { | |
364 | variants: enum_definition | |
365 | .variants | |
366 | .iter() | |
367 | .map(|x| self.lower_variant(x)) | |
368 | .collect(), | |
369 | }, | |
370 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
371 | ) | |
372 | }, | |
373 | ItemKind::Struct(ref struct_def, ref generics) => { | |
374 | let struct_def = self.lower_variant_data(struct_def); | |
375 | hir::ItemKind::Struct( | |
376 | struct_def, | |
377 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
378 | ) | |
379 | } | |
380 | ItemKind::Union(ref vdata, ref generics) => { | |
381 | let vdata = self.lower_variant_data(vdata); | |
382 | hir::ItemKind::Union( | |
383 | vdata, | |
384 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
385 | ) | |
386 | } | |
387 | ItemKind::Impl( | |
388 | unsafety, | |
389 | polarity, | |
390 | defaultness, | |
391 | ref ast_generics, | |
392 | ref trait_ref, | |
393 | ref ty, | |
394 | ref impl_items, | |
395 | ) => { | |
396 | let def_id = self.resolver.definitions().local_def_id(id); | |
397 | ||
398 | // Lower the "impl header" first. This ordering is important | |
399 | // for in-band lifetimes! Consider `'a` here: | |
400 | // | |
401 | // impl Foo<'a> for u32 { | |
402 | // fn method(&'a self) { .. } | |
403 | // } | |
404 | // | |
405 | // Because we start by lowering the `Foo<'a> for u32` | |
406 | // part, we will add `'a` to the list of generics on | |
407 | // the impl. When we then encounter it later in the | |
408 | // method, it will not be considered an in-band | |
409 | // lifetime to be added, but rather a reference to a | |
410 | // parent lifetime. | |
411 | let lowered_trait_impl_id = self.lower_node_id(id); | |
412 | let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs( | |
413 | ast_generics, | |
414 | def_id, | |
415 | AnonymousLifetimeMode::CreateParameter, | |
416 | |this, _| { | |
417 | let trait_ref = trait_ref.as_ref().map(|trait_ref| { | |
418 | this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed()) | |
419 | }); | |
420 | ||
421 | if let Some(ref trait_ref) = trait_ref { | |
422 | if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res { | |
423 | this.trait_impls.entry(def_id).or_default().push( | |
424 | lowered_trait_impl_id); | |
425 | } | |
426 | } | |
427 | ||
428 | let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed()); | |
429 | ||
430 | (trait_ref, lowered_ty) | |
431 | }, | |
432 | ); | |
433 | ||
434 | let new_impl_items = self.with_in_scope_lifetime_defs( | |
435 | &ast_generics.params, | |
436 | |this| { | |
437 | impl_items | |
438 | .iter() | |
439 | .map(|item| this.lower_impl_item_ref(item)) | |
440 | .collect() | |
441 | }, | |
442 | ); | |
443 | ||
444 | hir::ItemKind::Impl( | |
445 | self.lower_unsafety(unsafety), | |
446 | self.lower_impl_polarity(polarity), | |
447 | self.lower_defaultness(defaultness, true /* [1] */), | |
448 | generics, | |
449 | trait_ref, | |
450 | lowered_ty, | |
451 | new_impl_items, | |
452 | ) | |
453 | } | |
454 | ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => { | |
455 | let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed()); | |
456 | let items = items | |
457 | .iter() | |
458 | .map(|item| self.lower_trait_item_ref(item)) | |
459 | .collect(); | |
460 | hir::ItemKind::Trait( | |
461 | self.lower_is_auto(is_auto), | |
462 | self.lower_unsafety(unsafety), | |
463 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
464 | bounds, | |
465 | items, | |
466 | ) | |
467 | } | |
468 | ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias( | |
469 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
470 | self.lower_param_bounds(bounds, ImplTraitContext::disallowed()), | |
471 | ), | |
472 | ItemKind::MacroDef(..) | |
473 | | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"), | |
474 | } | |
475 | ||
476 | // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to | |
477 | // not cause an assertion failure inside the `lower_defaultness` function. | |
478 | } | |
479 | ||
480 | fn lower_use_tree( | |
481 | &mut self, | |
482 | tree: &UseTree, | |
483 | prefix: &Path, | |
484 | id: NodeId, | |
485 | vis: &mut hir::Visibility, | |
486 | ident: &mut Ident, | |
487 | attrs: &hir::HirVec<Attribute>, | |
488 | ) -> hir::ItemKind { | |
489 | debug!("lower_use_tree(tree={:?})", tree); | |
490 | debug!("lower_use_tree: vis = {:?}", vis); | |
491 | ||
492 | let path = &tree.prefix; | |
493 | let segments = prefix | |
494 | .segments | |
495 | .iter() | |
496 | .chain(path.segments.iter()) | |
497 | .cloned() | |
498 | .collect(); | |
499 | ||
500 | match tree.kind { | |
501 | UseTreeKind::Simple(rename, id1, id2) => { | |
502 | *ident = tree.ident(); | |
503 | ||
504 | // First, apply the prefix to the path. | |
505 | let mut path = Path { | |
506 | segments, | |
507 | span: path.span, | |
508 | }; | |
509 | ||
510 | // Correctly resolve `self` imports. | |
511 | if path.segments.len() > 1 | |
512 | && path.segments.last().unwrap().ident.name == kw::SelfLower | |
513 | { | |
514 | let _ = path.segments.pop(); | |
515 | if rename.is_none() { | |
516 | *ident = path.segments.last().unwrap().ident; | |
517 | } | |
518 | } | |
519 | ||
520 | let mut resolutions = self.expect_full_res_from_use(id); | |
521 | // We want to return *something* from this function, so hold onto the first item | |
522 | // for later. | |
523 | let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err)); | |
524 | ||
525 | // Here, we are looping over namespaces, if they exist for the definition | |
526 | // being imported. We only handle type and value namespaces because we | |
527 | // won't be dealing with macros in the rest of the compiler. | |
528 | // Essentially a single `use` which imports two names is desugared into | |
529 | // two imports. | |
530 | for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) { | |
531 | let ident = *ident; | |
532 | let mut path = path.clone(); | |
533 | for seg in &mut path.segments { | |
534 | seg.id = self.sess.next_node_id(); | |
535 | } | |
536 | let span = path.span; | |
537 | ||
538 | self.with_hir_id_owner(new_node_id, |this| { | |
539 | let new_id = this.lower_node_id(new_node_id); | |
540 | let res = this.lower_res(res); | |
541 | let path = | |
542 | this.lower_path_extra(res, &path, ParamMode::Explicit, None); | |
543 | let item = hir::ItemKind::Use(P(path), hir::UseKind::Single); | |
544 | let vis = this.rebuild_vis(&vis); | |
545 | ||
546 | this.insert_item( | |
547 | hir::Item { | |
548 | hir_id: new_id, | |
549 | ident, | |
550 | attrs: attrs.into_iter().cloned().collect(), | |
551 | node: item, | |
552 | vis, | |
553 | span, | |
554 | }, | |
555 | ); | |
556 | }); | |
557 | } | |
558 | ||
559 | let path = | |
560 | P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None)); | |
561 | hir::ItemKind::Use(path, hir::UseKind::Single) | |
562 | } | |
563 | UseTreeKind::Glob => { | |
564 | let path = P(self.lower_path( | |
565 | id, | |
566 | &Path { | |
567 | segments, | |
568 | span: path.span, | |
569 | }, | |
570 | ParamMode::Explicit, | |
571 | )); | |
572 | hir::ItemKind::Use(path, hir::UseKind::Glob) | |
573 | } | |
574 | UseTreeKind::Nested(ref trees) => { | |
575 | // Nested imports are desugared into simple imports. | |
576 | // So, if we start with | |
577 | // | |
578 | // ``` | |
579 | // pub(x) use foo::{a, b}; | |
580 | // ``` | |
581 | // | |
582 | // we will create three items: | |
583 | // | |
584 | // ``` | |
585 | // pub(x) use foo::a; | |
586 | // pub(x) use foo::b; | |
587 | // pub(x) use foo::{}; // <-- this is called the `ListStem` | |
588 | // ``` | |
589 | // | |
590 | // The first two are produced by recursively invoking | |
591 | // `lower_use_tree` (and indeed there may be things | |
592 | // like `use foo::{a::{b, c}}` and so forth). They | |
593 | // wind up being directly added to | |
594 | // `self.items`. However, the structure of this | |
595 | // function also requires us to return one item, and | |
596 | // for that we return the `{}` import (called the | |
597 | // `ListStem`). | |
598 | ||
599 | let prefix = Path { | |
600 | segments, | |
601 | span: prefix.span.to(path.span), | |
602 | }; | |
603 | ||
604 | // Add all the nested `PathListItem`s to the HIR. | |
605 | for &(ref use_tree, id) in trees { | |
606 | let new_hir_id = self.lower_node_id(id); | |
607 | ||
608 | let mut prefix = prefix.clone(); | |
609 | ||
610 | // Give the segments new node-ids since they are being cloned. | |
611 | for seg in &mut prefix.segments { | |
612 | seg.id = self.sess.next_node_id(); | |
613 | } | |
614 | ||
615 | // Each `use` import is an item and thus are owners of the | |
616 | // names in the path. Up to this point the nested import is | |
617 | // the current owner, since we want each desugared import to | |
618 | // own its own names, we have to adjust the owner before | |
619 | // lowering the rest of the import. | |
620 | self.with_hir_id_owner(id, |this| { | |
621 | let mut vis = this.rebuild_vis(&vis); | |
622 | let mut ident = *ident; | |
623 | ||
624 | let item = this.lower_use_tree(use_tree, | |
625 | &prefix, | |
626 | id, | |
627 | &mut vis, | |
628 | &mut ident, | |
629 | attrs); | |
630 | ||
631 | this.insert_item( | |
632 | hir::Item { | |
633 | hir_id: new_hir_id, | |
634 | ident, | |
635 | attrs: attrs.into_iter().cloned().collect(), | |
636 | node: item, | |
637 | vis, | |
638 | span: use_tree.span, | |
639 | }, | |
640 | ); | |
641 | }); | |
642 | } | |
643 | ||
644 | // Subtle and a bit hacky: we lower the privacy level | |
645 | // of the list stem to "private" most of the time, but | |
646 | // not for "restricted" paths. The key thing is that | |
647 | // we don't want it to stay as `pub` (with no caveats) | |
648 | // because that affects rustdoc and also the lints | |
649 | // about `pub` items. But we can't *always* make it | |
650 | // private -- particularly not for restricted paths -- | |
651 | // because it contains node-ids that would then be | |
652 | // unused, failing the check that HirIds are "densely | |
653 | // assigned". | |
654 | match vis.node { | |
655 | hir::VisibilityKind::Public | | |
656 | hir::VisibilityKind::Crate(_) | | |
657 | hir::VisibilityKind::Inherited => { | |
658 | *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited); | |
659 | } | |
660 | hir::VisibilityKind::Restricted { .. } => { | |
661 | // Do nothing here, as described in the comment on the match. | |
662 | } | |
663 | } | |
664 | ||
665 | let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err); | |
666 | let res = self.lower_res(res); | |
667 | let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None)); | |
668 | hir::ItemKind::Use(path, hir::UseKind::ListStem) | |
669 | } | |
670 | } | |
671 | } | |
672 | ||
673 | /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated | |
674 | /// many times in the HIR tree; for each occurrence, we need to assign distinct | |
675 | /// `NodeId`s. (See, e.g., #56128.) | |
676 | fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path { | |
677 | debug!("rebuild_use_path(path = {:?})", path); | |
678 | let segments = path.segments.iter().map(|seg| hir::PathSegment { | |
679 | ident: seg.ident, | |
680 | hir_id: seg.hir_id.map(|_| self.next_id()), | |
681 | res: seg.res, | |
682 | args: None, | |
683 | infer_args: seg.infer_args, | |
684 | }).collect(); | |
685 | hir::Path { | |
686 | span: path.span, | |
687 | res: path.res, | |
688 | segments, | |
689 | } | |
690 | } | |
691 | ||
692 | fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility { | |
693 | let vis_kind = match vis.node { | |
694 | hir::VisibilityKind::Public => hir::VisibilityKind::Public, | |
695 | hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar), | |
696 | hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited, | |
697 | hir::VisibilityKind::Restricted { ref path, hir_id: _ } => { | |
698 | hir::VisibilityKind::Restricted { | |
699 | path: P(self.rebuild_use_path(path)), | |
700 | hir_id: self.next_id(), | |
701 | } | |
702 | } | |
703 | }; | |
704 | respan(vis.span, vis_kind) | |
705 | } | |
706 | ||
707 | fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem { | |
708 | let def_id = self.resolver.definitions().local_def_id(i.id); | |
709 | hir::ForeignItem { | |
710 | hir_id: self.lower_node_id(i.id), | |
711 | ident: i.ident, | |
712 | attrs: self.lower_attrs(&i.attrs), | |
713 | node: match i.node { | |
714 | ForeignItemKind::Fn(ref fdec, ref generics) => { | |
715 | let (generics, (fn_dec, fn_args)) = self.add_in_band_defs( | |
716 | generics, | |
717 | def_id, | |
718 | AnonymousLifetimeMode::PassThrough, | |
719 | |this, _| { | |
720 | ( | |
e1599b0c | 721 | // Disallow `impl Trait` in foreign items. |
416331ca | 722 | this.lower_fn_decl(fdec, None, false, None), |
e1599b0c | 723 | this.lower_fn_params_to_names(fdec), |
416331ca XL |
724 | ) |
725 | }, | |
726 | ); | |
727 | ||
728 | hir::ForeignItemKind::Fn(fn_dec, fn_args, generics) | |
729 | } | |
730 | ForeignItemKind::Static(ref t, m) => { | |
731 | hir::ForeignItemKind::Static( | |
732 | self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m)) | |
733 | } | |
734 | ForeignItemKind::Ty => hir::ForeignItemKind::Type, | |
e1599b0c | 735 | ForeignItemKind::Macro(_) => panic!("macro shouldn't exist here"), |
416331ca XL |
736 | }, |
737 | vis: self.lower_visibility(&i.vis, None), | |
738 | span: i.span, | |
739 | } | |
740 | } | |
741 | ||
742 | fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod { | |
743 | hir::ForeignMod { | |
744 | abi: fm.abi, | |
745 | items: fm.items | |
746 | .iter() | |
747 | .map(|x| self.lower_foreign_item(x)) | |
748 | .collect(), | |
749 | } | |
750 | } | |
751 | ||
752 | fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> { | |
e1599b0c | 753 | P(hir::GlobalAsm { asm: ga.asm }) |
416331ca XL |
754 | } |
755 | ||
756 | fn lower_variant(&mut self, v: &Variant) -> hir::Variant { | |
e1599b0c XL |
757 | hir::Variant { |
758 | attrs: self.lower_attrs(&v.attrs), | |
759 | data: self.lower_variant_data(&v.data), | |
760 | disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)), | |
761 | id: self.lower_node_id(v.id), | |
762 | ident: v.ident, | |
416331ca XL |
763 | span: v.span, |
764 | } | |
765 | } | |
766 | ||
767 | fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData { | |
768 | match *vdata { | |
769 | VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct( | |
770 | fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(), | |
771 | recovered, | |
772 | ), | |
773 | VariantData::Tuple(ref fields, id) => { | |
774 | hir::VariantData::Tuple( | |
775 | fields | |
776 | .iter() | |
777 | .enumerate() | |
778 | .map(|f| self.lower_struct_field(f)) | |
779 | .collect(), | |
780 | self.lower_node_id(id), | |
781 | ) | |
782 | }, | |
783 | VariantData::Unit(id) => { | |
784 | hir::VariantData::Unit(self.lower_node_id(id)) | |
785 | }, | |
786 | } | |
787 | } | |
788 | ||
789 | fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField { | |
790 | let ty = if let TyKind::Path(ref qself, ref path) = f.ty.node { | |
791 | let t = self.lower_path_ty( | |
792 | &f.ty, | |
793 | qself, | |
794 | path, | |
795 | ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124) | |
796 | ImplTraitContext::disallowed() | |
797 | ); | |
798 | P(t) | |
799 | } else { | |
800 | self.lower_ty(&f.ty, ImplTraitContext::disallowed()) | |
801 | }; | |
802 | hir::StructField { | |
803 | span: f.span, | |
804 | hir_id: self.lower_node_id(f.id), | |
805 | ident: match f.ident { | |
806 | Some(ident) => ident, | |
807 | // FIXME(jseyfried): positional field hygiene. | |
808 | None => Ident::new(sym::integer(index), f.span), | |
809 | }, | |
810 | vis: self.lower_visibility(&f.vis, None), | |
811 | ty, | |
812 | attrs: self.lower_attrs(&f.attrs), | |
813 | } | |
814 | } | |
815 | ||
816 | fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem { | |
817 | let trait_item_def_id = self.resolver.definitions().local_def_id(i.id); | |
818 | ||
819 | let (generics, node) = match i.node { | |
820 | TraitItemKind::Const(ref ty, ref default) => ( | |
821 | self.lower_generics(&i.generics, ImplTraitContext::disallowed()), | |
822 | hir::TraitItemKind::Const( | |
823 | self.lower_ty(ty, ImplTraitContext::disallowed()), | |
824 | default | |
825 | .as_ref() | |
826 | .map(|x| self.lower_const_body(x)), | |
827 | ), | |
828 | ), | |
829 | TraitItemKind::Method(ref sig, None) => { | |
e1599b0c | 830 | let names = self.lower_fn_params_to_names(&sig.decl); |
416331ca XL |
831 | let (generics, sig) = self.lower_method_sig( |
832 | &i.generics, | |
833 | sig, | |
834 | trait_item_def_id, | |
835 | false, | |
836 | None, | |
837 | ); | |
838 | (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names))) | |
839 | } | |
840 | TraitItemKind::Method(ref sig, Some(ref body)) => { | |
841 | let body_id = self.lower_fn_body_block(&sig.decl, body); | |
842 | let (generics, sig) = self.lower_method_sig( | |
843 | &i.generics, | |
844 | sig, | |
845 | trait_item_def_id, | |
846 | false, | |
847 | None, | |
848 | ); | |
849 | (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id))) | |
850 | } | |
851 | TraitItemKind::Type(ref bounds, ref default) => { | |
852 | let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed()); | |
853 | let node = hir::TraitItemKind::Type( | |
854 | self.lower_param_bounds(bounds, ImplTraitContext::disallowed()), | |
855 | default | |
856 | .as_ref() | |
857 | .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())), | |
858 | ); | |
859 | ||
860 | (generics, node) | |
861 | }, | |
862 | TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"), | |
863 | }; | |
864 | ||
865 | hir::TraitItem { | |
866 | hir_id: self.lower_node_id(i.id), | |
867 | ident: i.ident, | |
868 | attrs: self.lower_attrs(&i.attrs), | |
869 | generics, | |
870 | node, | |
871 | span: i.span, | |
872 | } | |
873 | } | |
874 | ||
875 | fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef { | |
876 | let (kind, has_default) = match i.node { | |
877 | TraitItemKind::Const(_, ref default) => { | |
878 | (hir::AssocItemKind::Const, default.is_some()) | |
879 | } | |
880 | TraitItemKind::Type(_, ref default) => { | |
881 | (hir::AssocItemKind::Type, default.is_some()) | |
882 | } | |
883 | TraitItemKind::Method(ref sig, ref default) => ( | |
884 | hir::AssocItemKind::Method { | |
885 | has_self: sig.decl.has_self(), | |
886 | }, | |
887 | default.is_some(), | |
888 | ), | |
889 | TraitItemKind::Macro(..) => unimplemented!(), | |
890 | }; | |
891 | hir::TraitItemRef { | |
892 | id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) }, | |
893 | ident: i.ident, | |
894 | span: i.span, | |
895 | defaultness: self.lower_defaultness(Defaultness::Default, has_default), | |
896 | kind, | |
897 | } | |
898 | } | |
899 | ||
900 | fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem { | |
901 | let impl_item_def_id = self.resolver.definitions().local_def_id(i.id); | |
902 | ||
903 | let (generics, node) = match i.node { | |
904 | ImplItemKind::Const(ref ty, ref expr) => ( | |
905 | self.lower_generics(&i.generics, ImplTraitContext::disallowed()), | |
906 | hir::ImplItemKind::Const( | |
907 | self.lower_ty(ty, ImplTraitContext::disallowed()), | |
908 | self.lower_const_body(expr), | |
909 | ), | |
910 | ), | |
911 | ImplItemKind::Method(ref sig, ref body) => { | |
912 | self.current_item = Some(i.span); | |
913 | let body_id = self.lower_maybe_async_body( | |
914 | &sig.decl, sig.header.asyncness.node, body | |
915 | ); | |
916 | let impl_trait_return_allow = !self.is_in_trait_impl; | |
917 | let (generics, sig) = self.lower_method_sig( | |
918 | &i.generics, | |
919 | sig, | |
920 | impl_item_def_id, | |
921 | impl_trait_return_allow, | |
922 | sig.header.asyncness.node.opt_return_id(), | |
923 | ); | |
924 | ||
925 | (generics, hir::ImplItemKind::Method(sig, body_id)) | |
926 | } | |
927 | ImplItemKind::TyAlias(ref ty) => ( | |
928 | self.lower_generics(&i.generics, ImplTraitContext::disallowed()), | |
929 | hir::ImplItemKind::TyAlias(self.lower_ty(ty, ImplTraitContext::disallowed())), | |
930 | ), | |
931 | ImplItemKind::OpaqueTy(ref bounds) => ( | |
932 | self.lower_generics(&i.generics, ImplTraitContext::disallowed()), | |
933 | hir::ImplItemKind::OpaqueTy( | |
934 | self.lower_param_bounds(bounds, ImplTraitContext::disallowed()), | |
935 | ), | |
936 | ), | |
937 | ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"), | |
938 | }; | |
939 | ||
940 | hir::ImplItem { | |
941 | hir_id: self.lower_node_id(i.id), | |
942 | ident: i.ident, | |
943 | attrs: self.lower_attrs(&i.attrs), | |
944 | generics, | |
945 | vis: self.lower_visibility(&i.vis, None), | |
946 | defaultness: self.lower_defaultness(i.defaultness, true /* [1] */), | |
947 | node, | |
948 | span: i.span, | |
949 | } | |
950 | ||
951 | // [1] since `default impl` is not yet implemented, this is always true in impls | |
952 | } | |
953 | ||
954 | fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef { | |
955 | hir::ImplItemRef { | |
956 | id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) }, | |
957 | ident: i.ident, | |
958 | span: i.span, | |
959 | vis: self.lower_visibility(&i.vis, Some(i.id)), | |
960 | defaultness: self.lower_defaultness(i.defaultness, true /* [1] */), | |
961 | kind: match i.node { | |
962 | ImplItemKind::Const(..) => hir::AssocItemKind::Const, | |
963 | ImplItemKind::TyAlias(..) => hir::AssocItemKind::Type, | |
964 | ImplItemKind::OpaqueTy(..) => hir::AssocItemKind::OpaqueTy, | |
965 | ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method { | |
966 | has_self: sig.decl.has_self(), | |
967 | }, | |
968 | ImplItemKind::Macro(..) => unimplemented!(), | |
969 | }, | |
970 | } | |
971 | ||
972 | // [1] since `default impl` is not yet implemented, this is always true in impls | |
973 | } | |
974 | ||
975 | /// If an `explicit_owner` is given, this method allocates the `HirId` in | |
976 | /// the address space of that item instead of the item currently being | |
977 | /// lowered. This can happen during `lower_impl_item_ref()` where we need to | |
978 | /// lower a `Visibility` value although we haven't lowered the owning | |
979 | /// `ImplItem` in question yet. | |
980 | fn lower_visibility( | |
981 | &mut self, | |
982 | v: &Visibility, | |
983 | explicit_owner: Option<NodeId>, | |
984 | ) -> hir::Visibility { | |
985 | let node = match v.node { | |
986 | VisibilityKind::Public => hir::VisibilityKind::Public, | |
987 | VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar), | |
988 | VisibilityKind::Restricted { ref path, id } => { | |
989 | debug!("lower_visibility: restricted path id = {:?}", id); | |
990 | let lowered_id = if let Some(owner) = explicit_owner { | |
991 | self.lower_node_id_with_owner(id, owner) | |
992 | } else { | |
993 | self.lower_node_id(id) | |
994 | }; | |
995 | let res = self.expect_full_res(id); | |
996 | let res = self.lower_res(res); | |
997 | hir::VisibilityKind::Restricted { | |
998 | path: P(self.lower_path_extra( | |
999 | res, | |
1000 | path, | |
1001 | ParamMode::Explicit, | |
1002 | explicit_owner, | |
1003 | )), | |
1004 | hir_id: lowered_id, | |
1005 | } | |
1006 | }, | |
1007 | VisibilityKind::Inherited => hir::VisibilityKind::Inherited, | |
1008 | }; | |
1009 | respan(v.span, node) | |
1010 | } | |
1011 | ||
1012 | fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness { | |
1013 | match d { | |
1014 | Defaultness::Default => hir::Defaultness::Default { | |
1015 | has_value: has_value, | |
1016 | }, | |
1017 | Defaultness::Final => { | |
1018 | assert!(has_value); | |
1019 | hir::Defaultness::Final | |
1020 | } | |
1021 | } | |
1022 | } | |
1023 | ||
1024 | fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity { | |
1025 | match i { | |
1026 | ImplPolarity::Positive => hir::ImplPolarity::Positive, | |
1027 | ImplPolarity::Negative => hir::ImplPolarity::Negative, | |
1028 | } | |
1029 | } | |
1030 | ||
e1599b0c | 1031 | fn record_body(&mut self, params: HirVec<hir::Param>, value: hir::Expr) -> hir::BodyId { |
416331ca XL |
1032 | let body = hir::Body { |
1033 | generator_kind: self.generator_kind, | |
e1599b0c | 1034 | params, |
416331ca XL |
1035 | value, |
1036 | }; | |
1037 | let id = body.id(); | |
1038 | self.bodies.insert(id, body); | |
1039 | id | |
1040 | } | |
1041 | ||
1042 | fn lower_body( | |
1043 | &mut self, | |
e1599b0c | 1044 | f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Param>, hir::Expr), |
416331ca XL |
1045 | ) -> hir::BodyId { |
1046 | let prev_gen_kind = self.generator_kind.take(); | |
e1599b0c XL |
1047 | let (parameters, result) = f(self); |
1048 | let body_id = self.record_body(parameters, result); | |
416331ca XL |
1049 | self.generator_kind = prev_gen_kind; |
1050 | body_id | |
1051 | } | |
1052 | ||
e1599b0c XL |
1053 | fn lower_param(&mut self, param: &Param) -> hir::Param { |
1054 | hir::Param { | |
1055 | attrs: self.lower_attrs(¶m.attrs), | |
1056 | hir_id: self.lower_node_id(param.id), | |
1057 | pat: self.lower_pat(¶m.pat), | |
1058 | span: param.span, | |
416331ca XL |
1059 | } |
1060 | } | |
1061 | ||
1062 | pub(super) fn lower_fn_body( | |
1063 | &mut self, | |
1064 | decl: &FnDecl, | |
1065 | body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr, | |
1066 | ) -> hir::BodyId { | |
1067 | self.lower_body(|this| ( | |
e1599b0c | 1068 | decl.inputs.iter().map(|x| this.lower_param(x)).collect(), |
416331ca XL |
1069 | body(this), |
1070 | )) | |
1071 | } | |
1072 | ||
1073 | fn lower_fn_body_block(&mut self, decl: &FnDecl, body: &Block) -> hir::BodyId { | |
e1599b0c | 1074 | self.lower_fn_body(decl, |this| this.lower_block_expr(body)) |
416331ca XL |
1075 | } |
1076 | ||
1077 | pub(super) fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId { | |
1078 | self.lower_body(|this| (hir_vec![], this.lower_expr(expr))) | |
1079 | } | |
1080 | ||
1081 | fn lower_maybe_async_body( | |
1082 | &mut self, | |
1083 | decl: &FnDecl, | |
1084 | asyncness: IsAsync, | |
1085 | body: &Block, | |
1086 | ) -> hir::BodyId { | |
1087 | let closure_id = match asyncness { | |
1088 | IsAsync::Async { closure_id, .. } => closure_id, | |
1089 | IsAsync::NotAsync => return self.lower_fn_body_block(decl, body), | |
1090 | }; | |
1091 | ||
1092 | self.lower_body(|this| { | |
e1599b0c | 1093 | let mut parameters: Vec<hir::Param> = Vec::new(); |
416331ca XL |
1094 | let mut statements: Vec<hir::Stmt> = Vec::new(); |
1095 | ||
e1599b0c | 1096 | // Async function parameters are lowered into the closure body so that they are |
416331ca XL |
1097 | // captured and so that the drop order matches the equivalent non-async functions. |
1098 | // | |
1099 | // from: | |
1100 | // | |
1101 | // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) { | |
e1599b0c | 1102 | // <body> |
416331ca XL |
1103 | // } |
1104 | // | |
1105 | // into: | |
1106 | // | |
1107 | // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) { | |
1108 | // async move { | |
1109 | // let __arg2 = __arg2; | |
1110 | // let <pattern> = __arg2; | |
1111 | // let __arg1 = __arg1; | |
1112 | // let <pattern> = __arg1; | |
1113 | // let __arg0 = __arg0; | |
1114 | // let <pattern> = __arg0; | |
e1599b0c | 1115 | // drop-temps { <body> } // see comments later in fn for details |
416331ca XL |
1116 | // } |
1117 | // } | |
1118 | // | |
1119 | // If `<pattern>` is a simple ident, then it is lowered to a single | |
1120 | // `let <pattern> = <pattern>;` statement as an optimization. | |
e1599b0c XL |
1121 | // |
1122 | // Note that the body is embedded in `drop-temps`; an | |
1123 | // equivalent desugaring would be `return { <body> | |
1124 | // };`. The key point is that we wish to drop all the | |
1125 | // let-bound variables and temporaries created in the body | |
1126 | // (and its tail expression!) before we drop the | |
1127 | // parameters (c.f. rust-lang/rust#64512). | |
1128 | for (index, parameter) in decl.inputs.iter().enumerate() { | |
1129 | let parameter = this.lower_param(parameter); | |
1130 | let span = parameter.pat.span; | |
416331ca XL |
1131 | |
1132 | // Check if this is a binding pattern, if so, we can optimize and avoid adding a | |
e1599b0c XL |
1133 | // `let <pat> = __argN;` statement. In this case, we do not rename the parameter. |
1134 | let (ident, is_simple_parameter) = match parameter.pat.node { | |
416331ca XL |
1135 | hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) => |
1136 | (ident, true), | |
1137 | _ => { | |
1138 | // Replace the ident for bindings that aren't simple. | |
1139 | let name = format!("__arg{}", index); | |
1140 | let ident = Ident::from_str(&name); | |
1141 | ||
1142 | (ident, false) | |
1143 | }, | |
1144 | }; | |
1145 | ||
1146 | let desugared_span = | |
1147 | this.mark_span_with_reason(DesugaringKind::Async, span, None); | |
1148 | ||
e1599b0c | 1149 | // Construct a parameter representing `__argN: <ty>` to replace the parameter of the |
416331ca XL |
1150 | // async function. |
1151 | // | |
e1599b0c XL |
1152 | // If this is the simple case, this parameter will end up being the same as the |
1153 | // original parameter, but with a different pattern id. | |
416331ca | 1154 | let mut stmt_attrs = ThinVec::new(); |
e1599b0c XL |
1155 | stmt_attrs.extend(parameter.attrs.iter().cloned()); |
1156 | let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident); | |
1157 | let new_parameter = hir::Param { | |
1158 | attrs: parameter.attrs, | |
1159 | hir_id: parameter.hir_id, | |
1160 | pat: new_parameter_pat, | |
1161 | span: parameter.span, | |
416331ca XL |
1162 | }; |
1163 | ||
1164 | ||
e1599b0c | 1165 | if is_simple_parameter { |
416331ca XL |
1166 | // If this is the simple case, then we only insert one statement that is |
1167 | // `let <pat> = <pat>;`. We re-use the original argument's pattern so that | |
1168 | // `HirId`s are densely assigned. | |
e1599b0c | 1169 | let expr = this.expr_ident(desugared_span, ident, new_parameter_id); |
416331ca XL |
1170 | let stmt = this.stmt_let_pat( |
1171 | stmt_attrs, | |
1172 | desugared_span, | |
1173 | Some(P(expr)), | |
e1599b0c | 1174 | parameter.pat, |
416331ca XL |
1175 | hir::LocalSource::AsyncFn |
1176 | ); | |
1177 | statements.push(stmt); | |
1178 | } else { | |
1179 | // If this is not the simple case, then we construct two statements: | |
1180 | // | |
1181 | // ``` | |
1182 | // let __argN = __argN; | |
1183 | // let <pat> = __argN; | |
1184 | // ``` | |
1185 | // | |
e1599b0c | 1186 | // The first statement moves the parameter into the closure and thus ensures |
416331ca XL |
1187 | // that the drop order is correct. |
1188 | // | |
1189 | // The second statement creates the bindings that the user wrote. | |
1190 | ||
1191 | // Construct the `let mut __argN = __argN;` statement. It must be a mut binding | |
1192 | // because the user may have specified a `ref mut` binding in the next | |
1193 | // statement. | |
1194 | let (move_pat, move_id) = this.pat_ident_binding_mode( | |
1195 | desugared_span, ident, hir::BindingAnnotation::Mutable); | |
e1599b0c | 1196 | let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id); |
416331ca XL |
1197 | let move_stmt = this.stmt_let_pat( |
1198 | ThinVec::new(), | |
1199 | desugared_span, | |
1200 | Some(P(move_expr)), | |
1201 | move_pat, | |
1202 | hir::LocalSource::AsyncFn | |
1203 | ); | |
1204 | ||
1205 | // Construct the `let <pat> = __argN;` statement. We re-use the original | |
e1599b0c | 1206 | // parameter's pattern so that `HirId`s are densely assigned. |
416331ca XL |
1207 | let pattern_expr = this.expr_ident(desugared_span, ident, move_id); |
1208 | let pattern_stmt = this.stmt_let_pat( | |
1209 | stmt_attrs, | |
1210 | desugared_span, | |
1211 | Some(P(pattern_expr)), | |
e1599b0c | 1212 | parameter.pat, |
416331ca XL |
1213 | hir::LocalSource::AsyncFn |
1214 | ); | |
1215 | ||
1216 | statements.push(move_stmt); | |
1217 | statements.push(pattern_stmt); | |
1218 | }; | |
1219 | ||
e1599b0c | 1220 | parameters.push(new_parameter); |
416331ca XL |
1221 | } |
1222 | ||
1223 | let async_expr = this.make_async_expr( | |
1224 | CaptureBy::Value, closure_id, None, body.span, | |
1225 | |this| { | |
e1599b0c XL |
1226 | // Create a block from the user's function body: |
1227 | let user_body = this.lower_block_expr(body); | |
1228 | ||
1229 | // Transform into `drop-temps { <user-body> }`, an expression: | |
1230 | let desugared_span = this.mark_span_with_reason( | |
1231 | DesugaringKind::Async, | |
1232 | user_body.span, | |
1233 | None, | |
1234 | ); | |
1235 | let user_body = this.expr_drop_temps( | |
1236 | desugared_span, | |
1237 | P(user_body), | |
1238 | ThinVec::new(), | |
1239 | ); | |
1240 | ||
1241 | // As noted above, create the final block like | |
1242 | // | |
1243 | // ``` | |
1244 | // { | |
1245 | // let $param_pattern = $raw_param; | |
1246 | // ... | |
1247 | // drop-temps { <user-body> } | |
1248 | // } | |
1249 | // ``` | |
1250 | let body = this.block_all( | |
1251 | desugared_span, | |
1252 | statements.into(), | |
1253 | Some(P(user_body)), | |
1254 | ); | |
1255 | this.expr_block(P(body), ThinVec::new()) | |
416331ca | 1256 | }); |
e1599b0c | 1257 | (HirVec::from(parameters), this.expr(body.span, async_expr, ThinVec::new())) |
416331ca XL |
1258 | }) |
1259 | } | |
1260 | ||
1261 | fn lower_method_sig( | |
1262 | &mut self, | |
1263 | generics: &Generics, | |
1264 | sig: &MethodSig, | |
1265 | fn_def_id: DefId, | |
1266 | impl_trait_return_allow: bool, | |
1267 | is_async: Option<NodeId>, | |
1268 | ) -> (hir::Generics, hir::MethodSig) { | |
1269 | let header = self.lower_fn_header(sig.header); | |
1270 | let (generics, decl) = self.add_in_band_defs( | |
1271 | generics, | |
1272 | fn_def_id, | |
1273 | AnonymousLifetimeMode::PassThrough, | |
1274 | |this, idty| this.lower_fn_decl( | |
1275 | &sig.decl, | |
1276 | Some((fn_def_id, idty)), | |
1277 | impl_trait_return_allow, | |
1278 | is_async, | |
1279 | ), | |
1280 | ); | |
1281 | (generics, hir::MethodSig { header, decl }) | |
1282 | } | |
1283 | ||
1284 | fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto { | |
1285 | match a { | |
1286 | IsAuto::Yes => hir::IsAuto::Yes, | |
1287 | IsAuto::No => hir::IsAuto::No, | |
1288 | } | |
1289 | } | |
1290 | ||
1291 | fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader { | |
1292 | hir::FnHeader { | |
1293 | unsafety: self.lower_unsafety(h.unsafety), | |
1294 | asyncness: self.lower_asyncness(h.asyncness.node), | |
1295 | constness: self.lower_constness(h.constness), | |
1296 | abi: h.abi, | |
1297 | } | |
1298 | } | |
1299 | ||
1300 | pub(super) fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety { | |
1301 | match u { | |
1302 | Unsafety::Unsafe => hir::Unsafety::Unsafe, | |
1303 | Unsafety::Normal => hir::Unsafety::Normal, | |
1304 | } | |
1305 | } | |
1306 | ||
1307 | fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness { | |
1308 | match c.node { | |
1309 | Constness::Const => hir::Constness::Const, | |
1310 | Constness::NotConst => hir::Constness::NotConst, | |
1311 | } | |
1312 | } | |
1313 | ||
1314 | fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync { | |
1315 | match a { | |
1316 | IsAsync::Async { .. } => hir::IsAsync::Async, | |
1317 | IsAsync::NotAsync => hir::IsAsync::NotAsync, | |
1318 | } | |
1319 | } | |
1320 | ||
1321 | pub(super) fn lower_generics( | |
1322 | &mut self, | |
1323 | generics: &Generics, | |
1324 | itctx: ImplTraitContext<'_>) | |
1325 | -> hir::Generics | |
1326 | { | |
1327 | // Collect `?Trait` bounds in where clause and move them to parameter definitions. | |
1328 | // FIXME: this could probably be done with less rightward drift. It also looks like two | |
1329 | // control paths where `report_error` is called are the only paths that advance to after the | |
1330 | // match statement, so the error reporting could probably just be moved there. | |
1331 | let mut add_bounds: NodeMap<Vec<_>> = Default::default(); | |
1332 | for pred in &generics.where_clause.predicates { | |
1333 | if let WherePredicate::BoundPredicate(ref bound_pred) = *pred { | |
1334 | 'next_bound: for bound in &bound_pred.bounds { | |
1335 | if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound { | |
1336 | let report_error = |this: &mut Self| { | |
1337 | this.diagnostic().span_err( | |
1338 | bound_pred.bounded_ty.span, | |
1339 | "`?Trait` bounds are only permitted at the \ | |
1340 | point where a type parameter is declared", | |
1341 | ); | |
1342 | }; | |
1343 | // Check if the where clause type is a plain type parameter. | |
1344 | match bound_pred.bounded_ty.node { | |
1345 | TyKind::Path(None, ref path) | |
1346 | if path.segments.len() == 1 | |
1347 | && bound_pred.bound_generic_params.is_empty() => | |
1348 | { | |
1349 | if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver | |
1350 | .get_partial_res(bound_pred.bounded_ty.id) | |
1351 | .map(|d| d.base_res()) | |
1352 | { | |
1353 | if let Some(node_id) = | |
1354 | self.resolver.definitions().as_local_node_id(def_id) | |
1355 | { | |
1356 | for param in &generics.params { | |
1357 | match param.kind { | |
1358 | GenericParamKind::Type { .. } => { | |
1359 | if node_id == param.id { | |
1360 | add_bounds.entry(param.id) | |
1361 | .or_default() | |
1362 | .push(bound.clone()); | |
1363 | continue 'next_bound; | |
1364 | } | |
1365 | } | |
1366 | _ => {} | |
1367 | } | |
1368 | } | |
1369 | } | |
1370 | } | |
1371 | report_error(self) | |
1372 | } | |
1373 | _ => report_error(self), | |
1374 | } | |
1375 | } | |
1376 | } | |
1377 | } | |
1378 | } | |
1379 | ||
1380 | hir::Generics { | |
1381 | params: self.lower_generic_params(&generics.params, &add_bounds, itctx), | |
1382 | where_clause: self.lower_where_clause(&generics.where_clause), | |
1383 | span: generics.span, | |
1384 | } | |
1385 | } | |
1386 | ||
1387 | fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause { | |
1388 | self.with_anonymous_lifetime_mode( | |
1389 | AnonymousLifetimeMode::ReportError, | |
1390 | |this| { | |
1391 | hir::WhereClause { | |
1392 | predicates: wc.predicates | |
1393 | .iter() | |
1394 | .map(|predicate| this.lower_where_predicate(predicate)) | |
1395 | .collect(), | |
1396 | span: wc.span, | |
1397 | } | |
1398 | }, | |
1399 | ) | |
1400 | } | |
1401 | ||
1402 | fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate { | |
1403 | match *pred { | |
1404 | WherePredicate::BoundPredicate(WhereBoundPredicate { | |
1405 | ref bound_generic_params, | |
1406 | ref bounded_ty, | |
1407 | ref bounds, | |
1408 | span, | |
1409 | }) => { | |
1410 | self.with_in_scope_lifetime_defs( | |
1411 | &bound_generic_params, | |
1412 | |this| { | |
1413 | hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate { | |
1414 | bound_generic_params: this.lower_generic_params( | |
1415 | bound_generic_params, | |
1416 | &NodeMap::default(), | |
1417 | ImplTraitContext::disallowed(), | |
1418 | ), | |
1419 | bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()), | |
1420 | bounds: bounds | |
1421 | .iter() | |
1422 | .filter_map(|bound| match *bound { | |
1423 | // Ignore `?Trait` bounds. | |
1424 | // They were copied into type parameters already. | |
1425 | GenericBound::Trait(_, TraitBoundModifier::Maybe) => None, | |
1426 | _ => Some(this.lower_param_bound( | |
1427 | bound, | |
1428 | ImplTraitContext::disallowed(), | |
1429 | )), | |
1430 | }) | |
1431 | .collect(), | |
1432 | span, | |
1433 | }) | |
1434 | }, | |
1435 | ) | |
1436 | } | |
1437 | WherePredicate::RegionPredicate(WhereRegionPredicate { | |
1438 | ref lifetime, | |
1439 | ref bounds, | |
1440 | span, | |
1441 | }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { | |
1442 | span, | |
1443 | lifetime: self.lower_lifetime(lifetime), | |
1444 | bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()), | |
1445 | }), | |
1446 | WherePredicate::EqPredicate(WhereEqPredicate { | |
1447 | id, | |
1448 | ref lhs_ty, | |
1449 | ref rhs_ty, | |
1450 | span, | |
1451 | }) => { | |
1452 | hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { | |
1453 | hir_id: self.lower_node_id(id), | |
1454 | lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()), | |
1455 | rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()), | |
1456 | span, | |
1457 | }) | |
1458 | }, | |
1459 | } | |
1460 | } | |
1461 | } |