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