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