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