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