]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering.rs
Convert more usages over
[rust.git] / src / librustc / hir / lowering.rs
1 // ignore-tidy-filelength
2
3 //! Lowers the AST to the HIR.
4 //!
5 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
6 //! much like a fold. Where lowering involves a bit more work things get more
7 //! interesting and there are some invariants you should know about. These mostly
8 //! concern spans and IDs.
9 //!
10 //! Spans are assigned to AST nodes during parsing and then are modified during
11 //! expansion to indicate the origin of a node and the process it went through
12 //! being expanded. IDs are assigned to AST nodes just before lowering.
13 //!
14 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
15 //! expansion we do not preserve the process of lowering in the spans, so spans
16 //! should not be modified here. When creating a new node (as opposed to
17 //! 'folding' an existing one), then you create a new ID using `next_id()`.
18 //!
19 //! You must ensure that IDs are unique. That means that you should only use the
20 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
21 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
22 //! If you do, you must then set the new node's ID to a fresh one.
23 //!
24 //! Spans are used for error messages and for tools to map semantics back to
25 //! source code. It is therefore not as important with spans as IDs to be strict
26 //! about use (you can't break the compiler by screwing up a span). Obviously, a
27 //! HIR node can only have a single span. But multiple nodes can have the same
28 //! span and spans don't need to be kept in order, etc. Where code is preserved
29 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
30 //! new it is probably best to give a span for the whole AST node being lowered.
31 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
32 //! get confused if the spans from leaf AST nodes occur in multiple places
33 //! in the HIR, especially for multiple identifiers.
34
35 use crate::dep_graph::DepGraph;
36 use crate::hir::{self, ParamName};
37 use crate::hir::HirVec;
38 use crate::hir::map::{DefKey, DefPathData, Definitions};
39 use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
40 use crate::hir::def::{Res, DefKind, PartialRes, PerNS};
41 use crate::hir::{GenericArg, ConstArg};
42 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
43                     ELIDED_LIFETIMES_IN_PATHS};
44 use crate::middle::cstore::CrateStore;
45 use crate::session::Session;
46 use crate::session::config::nightly_options;
47 use crate::util::common::FN_OUTPUT_NAME;
48 use crate::util::nodemap::{DefIdMap, NodeMap};
49 use errors::Applicability;
50 use rustc_data_structures::fx::FxHashSet;
51 use rustc_data_structures::indexed_vec::IndexVec;
52 use rustc_data_structures::thin_vec::ThinVec;
53 use rustc_data_structures::sync::Lrc;
54
55 use std::collections::{BTreeSet, BTreeMap};
56 use std::mem;
57 use smallvec::SmallVec;
58 use syntax::attr;
59 use syntax::ast;
60 use syntax::ast::*;
61 use syntax::errors;
62 use syntax::ext::hygiene::{Mark, SyntaxContext};
63 use syntax::print::pprust;
64 use syntax::ptr::P;
65 use syntax::source_map::{self, respan, ExpnInfo, CompilerDesugaringKind, Spanned};
66 use syntax::source_map::CompilerDesugaringKind::IfTemporary;
67 use syntax::std_inject;
68 use syntax::symbol::{kw, sym, Symbol};
69 use syntax::tokenstream::{TokenStream, TokenTree};
70 use syntax::parse::token::{self, Token};
71 use syntax::visit::{self, Visitor};
72 use syntax_pos::{DUMMY_SP, Span};
73
74 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
75
76 pub struct LoweringContext<'a> {
77     crate_root: Option<Symbol>,
78
79     /// Used to assign ids to HIR nodes that do not directly correspond to an AST node.
80     sess: &'a Session,
81
82     cstore: &'a dyn CrateStore,
83
84     resolver: &'a mut dyn Resolver,
85
86     /// The items being lowered are collected here.
87     items: BTreeMap<hir::HirId, hir::Item>,
88
89     trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
90     impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
91     bodies: BTreeMap<hir::BodyId, hir::Body>,
92     exported_macros: Vec<hir::MacroDef>,
93
94     trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
95
96     modules: BTreeMap<NodeId, hir::ModuleItems>,
97
98     generator_kind: Option<hir::GeneratorKind>,
99
100     /// Used to get the current `fn`'s def span to point to when using `await`
101     /// outside of an `async fn`.
102     current_item: Option<Span>,
103
104     catch_scopes: Vec<NodeId>,
105     loop_scopes: Vec<NodeId>,
106     is_in_loop_condition: bool,
107     is_in_trait_impl: bool,
108     is_in_dyn_type: bool,
109
110     /// What to do when we encounter either an "anonymous lifetime
111     /// reference". The term "anonymous" is meant to encompass both
112     /// `'_` lifetimes as well as fully elided cases where nothing is
113     /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
114     anonymous_lifetime_mode: AnonymousLifetimeMode,
115
116     /// Used to create lifetime definitions from in-band lifetime usages.
117     /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
118     /// When a named lifetime is encountered in a function or impl header and
119     /// has not been defined
120     /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
121     /// to this list. The results of this list are then added to the list of
122     /// lifetime definitions in the corresponding impl or function generics.
123     lifetimes_to_define: Vec<(Span, ParamName)>,
124
125     /// Whether or not in-band lifetimes are being collected. This is used to
126     /// indicate whether or not we're in a place where new lifetimes will result
127     /// in in-band lifetime definitions, such a function or an impl header,
128     /// including implicit lifetimes from `impl_header_lifetime_elision`.
129     is_collecting_in_band_lifetimes: bool,
130
131     /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
132     /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
133     /// against this list to see if it is already in-scope, or if a definition
134     /// needs to be created for it.
135     in_scope_lifetimes: Vec<Ident>,
136
137     current_module: NodeId,
138
139     type_def_lifetime_params: DefIdMap<usize>,
140
141     current_hir_id_owner: Vec<(DefIndex, u32)>,
142     item_local_id_counters: NodeMap<u32>,
143     node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
144
145     allow_try_trait: Option<Lrc<[Symbol]>>,
146     allow_gen_future: Option<Lrc<[Symbol]>>,
147 }
148
149 pub trait Resolver {
150     /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc.
151     fn resolve_ast_path(
152         &mut self,
153         path: &ast::Path,
154         is_value: bool,
155     ) -> Res<NodeId>;
156
157     /// Obtain resolution for a `NodeId` with a single resolution.
158     fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
159
160     /// Obtain per-namespace resolutions for `use` statement with the given `NoedId`.
161     fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
162
163     /// Obtain resolution for a label with the given `NodeId`.
164     fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
165
166     /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
167     /// This should only return `None` during testing.
168     fn definitions(&mut self) -> &mut Definitions;
169
170     /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
171     /// resolves it based on `is_value`.
172     fn resolve_str_path(
173         &mut self,
174         span: Span,
175         crate_root: Option<Symbol>,
176         components: &[Symbol],
177         is_value: bool,
178     ) -> (ast::Path, Res<NodeId>);
179 }
180
181 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
182 /// and if so, what meaning it has.
183 #[derive(Debug)]
184 enum ImplTraitContext<'a> {
185     /// Treat `impl Trait` as shorthand for a new universal generic parameter.
186     /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
187     /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
188     ///
189     /// Newly generated parameters should be inserted into the given `Vec`.
190     Universal(&'a mut Vec<hir::GenericParam>),
191
192     /// Treat `impl Trait` as shorthand for a new existential parameter.
193     /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
194     /// equivalent to a fresh existential parameter like `existential type T; fn foo() -> T`.
195     ///
196     /// We optionally store a `DefId` for the parent item here so we can look up necessary
197     /// information later. It is `None` when no information about the context should be stored
198     /// (e.g., for consts and statics).
199     Existential(Option<DefId> /* fn def-ID */),
200
201     /// `impl Trait` is not accepted in this position.
202     Disallowed(ImplTraitPosition),
203 }
204
205 /// Position in which `impl Trait` is disallowed.
206 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
207 enum ImplTraitPosition {
208     /// Disallowed in `let` / `const` / `static` bindings.
209     Binding,
210
211     /// All other posiitons.
212     Other,
213 }
214
215 impl<'a> ImplTraitContext<'a> {
216     #[inline]
217     fn disallowed() -> Self {
218         ImplTraitContext::Disallowed(ImplTraitPosition::Other)
219     }
220
221     fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
222         use self::ImplTraitContext::*;
223         match self {
224             Universal(params) => Universal(params),
225             Existential(fn_def_id) => Existential(*fn_def_id),
226             Disallowed(pos) => Disallowed(*pos),
227         }
228     }
229 }
230
231 pub fn lower_crate(
232     sess: &Session,
233     cstore: &dyn CrateStore,
234     dep_graph: &DepGraph,
235     krate: &Crate,
236     resolver: &mut dyn Resolver,
237 ) -> hir::Crate {
238     // We're constructing the HIR here; we don't care what we will
239     // read, since we haven't even constructed the *input* to
240     // incr. comp. yet.
241     dep_graph.assert_ignored();
242
243     LoweringContext {
244         crate_root: std_inject::injected_crate_name().map(Symbol::intern),
245         sess,
246         cstore,
247         resolver,
248         items: BTreeMap::new(),
249         trait_items: BTreeMap::new(),
250         impl_items: BTreeMap::new(),
251         bodies: BTreeMap::new(),
252         trait_impls: BTreeMap::new(),
253         modules: BTreeMap::new(),
254         exported_macros: Vec::new(),
255         catch_scopes: Vec::new(),
256         loop_scopes: Vec::new(),
257         is_in_loop_condition: false,
258         is_in_trait_impl: false,
259         is_in_dyn_type: false,
260         anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
261         type_def_lifetime_params: Default::default(),
262         current_module: CRATE_NODE_ID,
263         current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
264         item_local_id_counters: Default::default(),
265         node_id_to_hir_id: IndexVec::new(),
266         generator_kind: None,
267         current_item: None,
268         lifetimes_to_define: Vec::new(),
269         is_collecting_in_band_lifetimes: false,
270         in_scope_lifetimes: Vec::new(),
271         allow_try_trait: Some([sym::try_trait][..].into()),
272         allow_gen_future: Some([sym::gen_future][..].into()),
273     }.lower_crate(krate)
274 }
275
276 #[derive(Copy, Clone, PartialEq)]
277 enum ParamMode {
278     /// Any path in a type context.
279     Explicit,
280     /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
281     ExplicitNamed,
282     /// The `module::Type` in `module::Type::method` in an expression.
283     Optional,
284 }
285
286 enum ParenthesizedGenericArgs {
287     Ok,
288     Warn,
289     Err,
290 }
291
292 /// What to do when we encounter an **anonymous** lifetime
293 /// reference. Anonymous lifetime references come in two flavors. You
294 /// have implicit, or fully elided, references to lifetimes, like the
295 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
296 /// or `Ref<'_, T>`. These often behave the same, but not always:
297 ///
298 /// - certain usages of implicit references are deprecated, like
299 ///   `Ref<T>`, and we sometimes just give hard errors in those cases
300 ///   as well.
301 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
302 ///   the same as `Box<dyn Foo + '_>`.
303 ///
304 /// We describe the effects of the various modes in terms of three cases:
305 ///
306 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
307 ///   of a `&` (e.g., the missing lifetime in something like `&T`)
308 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
309 ///   there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
310 ///   elided bounds follow special rules. Note that this only covers
311 ///   cases where *nothing* is written; the `'_` in `Box<dyn Foo +
312 ///   '_>` is a case of "modern" elision.
313 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
314 ///   parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
315 ///   non-deprecated equivalent.
316 ///
317 /// Currently, the handling of lifetime elision is somewhat spread out
318 /// between HIR lowering and -- as described below -- the
319 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
320 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
321 /// everything into HIR lowering.
322 #[derive(Copy, Clone)]
323 enum AnonymousLifetimeMode {
324     /// For **Modern** cases, create a new anonymous region parameter
325     /// and reference that.
326     ///
327     /// For **Dyn Bound** cases, pass responsibility to
328     /// `resolve_lifetime` code.
329     ///
330     /// For **Deprecated** cases, report an error.
331     CreateParameter,
332
333     /// Give a hard error when either `&` or `'_` is written. Used to
334     /// rule out things like `where T: Foo<'_>`. Does not imply an
335     /// error on default object bounds (e.g., `Box<dyn Foo>`).
336     ReportError,
337
338     /// Pass responsibility to `resolve_lifetime` code for all cases.
339     PassThrough,
340
341     /// Used in the return types of `async fn` where there exists
342     /// exactly one argument-position elided lifetime.
343     ///
344     /// In `async fn`, we lower the arguments types using the `CreateParameter`
345     /// mode, meaning that non-`dyn` elided lifetimes are assigned a fresh name.
346     /// If any corresponding elided lifetimes appear in the output, we need to
347     /// replace them with references to the fresh name assigned to the corresponding
348     /// elided lifetime in the arguments.
349     ///
350     /// For **Modern cases**, replace the anonymous parameter with a
351     /// reference to a specific freshly-named lifetime that was
352     /// introduced in argument
353     ///
354     /// For **Dyn Bound** cases, pass responsibility to
355     /// `resole_lifetime` code.
356     Replace(LtReplacement),
357 }
358
359 /// The type of elided lifetime replacement to perform on `async fn` return types.
360 #[derive(Copy, Clone)]
361 enum LtReplacement {
362     /// Fresh name introduced by the single non-dyn elided lifetime
363     /// in the arguments of the async fn.
364     Some(ParamName),
365
366     /// There is no single non-dyn elided lifetime because no lifetimes
367     /// appeared in the arguments.
368     NoLifetimes,
369
370     /// There is no single non-dyn elided lifetime because multiple
371     /// lifetimes appeared in the arguments.
372     MultipleLifetimes,
373 }
374
375 /// Calculates the `LtReplacement` to use for elided lifetimes in the return
376 /// type based on the fresh elided lifetimes introduced in argument position.
377 fn get_elided_lt_replacement(arg_position_lifetimes: &[(Span, ParamName)]) -> LtReplacement {
378     match arg_position_lifetimes {
379         [] => LtReplacement::NoLifetimes,
380         [(_span, param)] => LtReplacement::Some(*param),
381         _ => LtReplacement::MultipleLifetimes,
382     }
383 }
384
385 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
386
387 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
388     fn visit_ty(&mut self, ty: &'a Ty) {
389         match ty.node {
390             | TyKind::Typeof(_)
391             | TyKind::BareFn(_)
392             => return,
393
394             TyKind::ImplTrait(id, _) => self.ids.push(id),
395             _ => {},
396         }
397         visit::walk_ty(self, ty);
398     }
399
400     fn visit_path_segment(
401         &mut self,
402         path_span: Span,
403         path_segment: &'v PathSegment,
404     ) {
405         if let Some(ref p) = path_segment.args {
406             if let GenericArgs::Parenthesized(_) = **p {
407                 return;
408             }
409         }
410         visit::walk_path_segment(self, path_span, path_segment)
411     }
412 }
413
414 impl<'a> LoweringContext<'a> {
415     fn lower_crate(mut self, c: &Crate) -> hir::Crate {
416         /// Full-crate AST visitor that inserts into a fresh
417         /// `LoweringContext` any information that may be
418         /// needed from arbitrary locations in the crate,
419         /// e.g., the number of lifetime generic parameters
420         /// declared for every type and trait definition.
421         struct MiscCollector<'tcx, 'interner> {
422             lctx: &'tcx mut LoweringContext<'interner>,
423             hir_id_owner: Option<NodeId>,
424         }
425
426         impl MiscCollector<'_, '_> {
427             fn allocate_use_tree_hir_id_counters(
428                 &mut self,
429                 tree: &UseTree,
430                 owner: DefIndex,
431             ) {
432                 match tree.kind {
433                     UseTreeKind::Simple(_, id1, id2) => {
434                         for &id in &[id1, id2] {
435                             self.lctx.resolver.definitions().create_def_with_parent(
436                                 owner,
437                                 id,
438                                 DefPathData::Misc,
439                                 Mark::root(),
440                                 tree.prefix.span,
441                             );
442                             self.lctx.allocate_hir_id_counter(id);
443                         }
444                     }
445                     UseTreeKind::Glob => (),
446                     UseTreeKind::Nested(ref trees) => {
447                         for &(ref use_tree, id) in trees {
448                             let hir_id = self.lctx.allocate_hir_id_counter(id);
449                             self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
450                         }
451                     }
452                 }
453             }
454
455             fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
456             where
457                 F: FnOnce(&mut Self) -> T,
458             {
459                 let old = mem::replace(&mut self.hir_id_owner, owner);
460                 let r = f(self);
461                 self.hir_id_owner = old;
462                 r
463             }
464         }
465
466         impl<'tcx, 'interner> Visitor<'tcx> for MiscCollector<'tcx, 'interner> {
467             fn visit_pat(&mut self, p: &'tcx Pat) {
468                 match p.node {
469                     // Doesn't generate a HIR node
470                     PatKind::Paren(..) => {},
471                     _ => {
472                         if let Some(owner) = self.hir_id_owner {
473                             self.lctx.lower_node_id_with_owner(p.id, owner);
474                         }
475                     }
476                 };
477
478                 visit::walk_pat(self, p)
479             }
480
481             fn visit_item(&mut self, item: &'tcx Item) {
482                 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
483
484                 match item.node {
485                     ItemKind::Struct(_, ref generics)
486                     | ItemKind::Union(_, ref generics)
487                     | ItemKind::Enum(_, ref generics)
488                     | ItemKind::Ty(_, ref generics)
489                     | ItemKind::Existential(_, ref generics)
490                     | ItemKind::Trait(_, _, ref generics, ..) => {
491                         let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
492                         let count = generics
493                             .params
494                             .iter()
495                             .filter(|param| match param.kind {
496                                 ast::GenericParamKind::Lifetime { .. } => true,
497                                 _ => false,
498                             })
499                             .count();
500                         self.lctx.type_def_lifetime_params.insert(def_id, count);
501                     }
502                     ItemKind::Use(ref use_tree) => {
503                         self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
504                     }
505                     _ => {}
506                 }
507
508                 self.with_hir_id_owner(Some(item.id), |this| {
509                     visit::walk_item(this, item);
510                 });
511             }
512
513             fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
514                 self.lctx.allocate_hir_id_counter(item.id);
515
516                 match item.node {
517                     TraitItemKind::Method(_, None) => {
518                         // Ignore patterns in trait methods without bodies
519                         self.with_hir_id_owner(None, |this| {
520                             visit::walk_trait_item(this, item)
521                         });
522                     }
523                     _ => self.with_hir_id_owner(Some(item.id), |this| {
524                         visit::walk_trait_item(this, item);
525                     })
526                 }
527             }
528
529             fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
530                 self.lctx.allocate_hir_id_counter(item.id);
531                 self.with_hir_id_owner(Some(item.id), |this| {
532                     visit::walk_impl_item(this, item);
533                 });
534             }
535
536             fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
537                 // Ignore patterns in foreign items
538                 self.with_hir_id_owner(None, |this| {
539                     visit::walk_foreign_item(this, i)
540                 });
541             }
542
543             fn visit_ty(&mut self, t: &'tcx Ty) {
544                 match t.node {
545                     // Mirrors the case in visit::walk_ty
546                     TyKind::BareFn(ref f) => {
547                         walk_list!(
548                             self,
549                             visit_generic_param,
550                             &f.generic_params
551                         );
552                         // Mirrors visit::walk_fn_decl
553                         for argument in &f.decl.inputs {
554                             // We don't lower the ids of argument patterns
555                             self.with_hir_id_owner(None, |this| {
556                                 this.visit_pat(&argument.pat);
557                             });
558                             self.visit_ty(&argument.ty)
559                         }
560                         self.visit_fn_ret_ty(&f.decl.output)
561                     }
562                     _ => visit::walk_ty(self, t),
563                 }
564             }
565         }
566
567         struct ItemLowerer<'tcx, 'interner> {
568             lctx: &'tcx mut LoweringContext<'interner>,
569         }
570
571         impl<'tcx, 'interner> ItemLowerer<'tcx, 'interner> {
572             fn with_trait_impl_ref<F>(&mut self, trait_impl_ref: &Option<TraitRef>, f: F)
573             where
574                 F: FnOnce(&mut Self),
575             {
576                 let old = self.lctx.is_in_trait_impl;
577                 self.lctx.is_in_trait_impl = if let &None = trait_impl_ref {
578                     false
579                 } else {
580                     true
581                 };
582                 f(self);
583                 self.lctx.is_in_trait_impl = old;
584             }
585         }
586
587         impl<'tcx, 'interner> Visitor<'tcx> for ItemLowerer<'tcx, 'interner> {
588             fn visit_mod(&mut self, m: &'tcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) {
589                 self.lctx.modules.insert(n, hir::ModuleItems {
590                     items: BTreeSet::new(),
591                     trait_items: BTreeSet::new(),
592                     impl_items: BTreeSet::new(),
593                 });
594
595                 let old = self.lctx.current_module;
596                 self.lctx.current_module = n;
597                 visit::walk_mod(self, m);
598                 self.lctx.current_module = old;
599             }
600
601             fn visit_item(&mut self, item: &'tcx Item) {
602                 let mut item_hir_id = None;
603                 self.lctx.with_hir_id_owner(item.id, |lctx| {
604                     if let Some(hir_item) = lctx.lower_item(item) {
605                         item_hir_id = Some(hir_item.hir_id);
606                         lctx.insert_item(hir_item);
607                     }
608                 });
609
610                 if let Some(hir_id) = item_hir_id {
611                     self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
612                         let this = &mut ItemLowerer { lctx: this };
613                         if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
614                             this.with_trait_impl_ref(opt_trait_ref, |this| {
615                                 visit::walk_item(this, item)
616                             });
617                         } else {
618                             visit::walk_item(this, item);
619                         }
620                     });
621                 }
622             }
623
624             fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
625                 self.lctx.with_hir_id_owner(item.id, |lctx| {
626                     let hir_item = lctx.lower_trait_item(item);
627                     let id = hir::TraitItemId { hir_id: hir_item.hir_id };
628                     lctx.trait_items.insert(id, hir_item);
629                     lctx.modules.get_mut(&lctx.current_module).unwrap().trait_items.insert(id);
630                 });
631
632                 visit::walk_trait_item(self, item);
633             }
634
635             fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
636                 self.lctx.with_hir_id_owner(item.id, |lctx| {
637                     let hir_item = lctx.lower_impl_item(item);
638                     let id = hir::ImplItemId { hir_id: hir_item.hir_id };
639                     lctx.impl_items.insert(id, hir_item);
640                     lctx.modules.get_mut(&lctx.current_module).unwrap().impl_items.insert(id);
641                 });
642                 visit::walk_impl_item(self, item);
643             }
644         }
645
646         self.lower_node_id(CRATE_NODE_ID);
647         debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
648
649         visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
650         visit::walk_crate(&mut ItemLowerer { lctx: &mut self }, c);
651
652         let module = self.lower_mod(&c.module);
653         let attrs = self.lower_attrs(&c.attrs);
654         let body_ids = body_ids(&self.bodies);
655
656         self.resolver
657             .definitions()
658             .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
659
660         hir::Crate {
661             module,
662             attrs,
663             span: c.span,
664             exported_macros: hir::HirVec::from(self.exported_macros),
665             items: self.items,
666             trait_items: self.trait_items,
667             impl_items: self.impl_items,
668             bodies: self.bodies,
669             body_ids,
670             trait_impls: self.trait_impls,
671             modules: self.modules,
672         }
673     }
674
675     fn insert_item(&mut self, item: hir::Item) {
676         let id = item.hir_id;
677         // FIXME: Use `debug_asset-rt`.
678         assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
679         self.items.insert(id, item);
680         self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
681     }
682
683     fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
684         // Set up the counter if needed.
685         self.item_local_id_counters.entry(owner).or_insert(0);
686         // Always allocate the first `HirId` for the owner itself.
687         let lowered = self.lower_node_id_with_owner(owner, owner);
688         debug_assert_eq!(lowered.local_id.as_u32(), 0);
689         lowered
690     }
691
692     fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
693     where
694         F: FnOnce(&mut Self) -> hir::HirId,
695     {
696         if ast_node_id == DUMMY_NODE_ID {
697             return hir::DUMMY_HIR_ID;
698         }
699
700         let min_size = ast_node_id.as_usize() + 1;
701
702         if min_size > self.node_id_to_hir_id.len() {
703             self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
704         }
705
706         let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
707
708         if existing_hir_id == hir::DUMMY_HIR_ID {
709             // Generate a new `HirId`.
710             let hir_id = alloc_hir_id(self);
711             self.node_id_to_hir_id[ast_node_id] = hir_id;
712
713             hir_id
714         } else {
715             existing_hir_id
716         }
717     }
718
719     fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
720     where
721         F: FnOnce(&mut Self) -> T,
722     {
723         let counter = self.item_local_id_counters
724             .insert(owner, HIR_ID_COUNTER_LOCKED)
725             .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
726         let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
727         self.current_hir_id_owner.push((def_index, counter));
728         let ret = f(self);
729         let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
730
731         debug_assert!(def_index == new_def_index);
732         debug_assert!(new_counter >= counter);
733
734         let prev = self.item_local_id_counters
735             .insert(owner, new_counter)
736             .unwrap();
737         debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
738         ret
739     }
740
741     /// This method allocates a new `HirId` for the given `NodeId` and stores it in
742     /// the `LoweringContext`'s `NodeId => HirId` map.
743     /// Take care not to call this method if the resulting `HirId` is then not
744     /// actually used in the HIR, as that would trigger an assertion in the
745     /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
746     /// properly. Calling the method twice with the same `NodeId` is fine though.
747     fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
748         self.lower_node_id_generic(ast_node_id, |this| {
749             let &mut (def_index, ref mut local_id_counter) =
750                 this.current_hir_id_owner.last_mut().unwrap();
751             let local_id = *local_id_counter;
752             *local_id_counter += 1;
753             hir::HirId {
754                 owner: def_index,
755                 local_id: hir::ItemLocalId::from_u32(local_id),
756             }
757         })
758     }
759
760     fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
761         self.lower_node_id_generic(ast_node_id, |this| {
762             let local_id_counter = this
763                 .item_local_id_counters
764                 .get_mut(&owner)
765                 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
766             let local_id = *local_id_counter;
767
768             // We want to be sure not to modify the counter in the map while it
769             // is also on the stack. Otherwise we'll get lost updates when writing
770             // back from the stack to the map.
771             debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
772
773             *local_id_counter += 1;
774             let def_index = this
775                 .resolver
776                 .definitions()
777                 .opt_def_index(owner)
778                 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
779                          that do not belong to the current owner");
780
781             hir::HirId {
782                 owner: def_index,
783                 local_id: hir::ItemLocalId::from_u32(local_id),
784             }
785         })
786     }
787
788     fn generator_movability_for_fn(
789         &mut self,
790         decl: &ast::FnDecl,
791         fn_decl_span: Span,
792         generator_kind: Option<hir::GeneratorKind>,
793         movability: Movability,
794     ) -> Option<hir::GeneratorMovability> {
795         match generator_kind {
796             Some(hir::GeneratorKind::Gen) =>  {
797                 if !decl.inputs.is_empty() {
798                     span_err!(
799                         self.sess,
800                         fn_decl_span,
801                         E0628,
802                         "generators cannot have explicit arguments"
803                     );
804                     self.sess.abort_if_errors();
805                 }
806                 Some(match movability {
807                     Movability::Movable => hir::GeneratorMovability::Movable,
808                     Movability::Static => hir::GeneratorMovability::Static,
809                 })
810             },
811             Some(hir::GeneratorKind::Async) => {
812                 bug!("non-`async` closure body turned `async` during lowering");
813             },
814             None => {
815                 if movability == Movability::Static {
816                     span_err!(
817                         self.sess,
818                         fn_decl_span,
819                         E0697,
820                         "closures cannot be static"
821                     );
822                 }
823                 None
824             },
825         }
826     }
827
828     fn record_body(&mut self, arguments: HirVec<hir::Arg>, value: hir::Expr) -> hir::BodyId {
829         let body = hir::Body {
830             generator_kind: self.generator_kind,
831             arguments,
832             value,
833         };
834         let id = body.id();
835         self.bodies.insert(id, body);
836         id
837     }
838
839     fn next_id(&mut self) -> hir::HirId {
840         self.lower_node_id(self.sess.next_node_id())
841     }
842
843     fn lower_res(&mut self, res: Res<NodeId>) -> Res {
844         res.map_id(|id| {
845             self.lower_node_id_generic(id, |_| {
846                 panic!("expected node_id to be lowered already for res {:#?}", res)
847             })
848         })
849     }
850
851     fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
852         self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
853             if pr.unresolved_segments() != 0 {
854                 bug!("path not fully resolved: {:?}", pr);
855             }
856             pr.base_res()
857         })
858     }
859
860     fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
861         self.resolver.get_import_res(id).present_items()
862     }
863
864     fn diagnostic(&self) -> &errors::Handler {
865         self.sess.diagnostic()
866     }
867
868     /// Reuses the span but adds information like the kind of the desugaring and features that are
869     /// allowed inside this span.
870     fn mark_span_with_reason(
871         &self,
872         reason: CompilerDesugaringKind,
873         span: Span,
874         allow_internal_unstable: Option<Lrc<[Symbol]>>,
875     ) -> Span {
876         let mark = Mark::fresh(Mark::root());
877         mark.set_expn_info(ExpnInfo {
878             def_site: Some(span),
879             allow_internal_unstable,
880             ..ExpnInfo::default(source_map::CompilerDesugaring(reason), span, self.sess.edition())
881         });
882         span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
883     }
884
885     fn with_anonymous_lifetime_mode<R>(
886         &mut self,
887         anonymous_lifetime_mode: AnonymousLifetimeMode,
888         op: impl FnOnce(&mut Self) -> R,
889     ) -> R {
890         let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
891         self.anonymous_lifetime_mode = anonymous_lifetime_mode;
892         let result = op(self);
893         self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
894         result
895     }
896
897     /// Creates a new `hir::GenericParam` for every new lifetime and
898     /// type parameter encountered while evaluating `f`. Definitions
899     /// are created with the parent provided. If no `parent_id` is
900     /// provided, no definitions will be returned.
901     ///
902     /// Presuming that in-band lifetimes are enabled, then
903     /// `self.anonymous_lifetime_mode` will be updated to match the
904     /// argument while `f` is running (and restored afterwards).
905     fn collect_in_band_defs<T, F>(
906         &mut self,
907         parent_id: DefId,
908         anonymous_lifetime_mode: AnonymousLifetimeMode,
909         f: F,
910     ) -> (Vec<hir::GenericParam>, T)
911     where
912         F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
913     {
914         assert!(!self.is_collecting_in_band_lifetimes);
915         assert!(self.lifetimes_to_define.is_empty());
916         let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
917
918         self.anonymous_lifetime_mode = anonymous_lifetime_mode;
919         self.is_collecting_in_band_lifetimes = true;
920
921         let (in_band_ty_params, res) = f(self);
922
923         self.is_collecting_in_band_lifetimes = false;
924         self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
925
926         let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
927
928         let params = lifetimes_to_define
929             .into_iter()
930             .map(|(span, hir_name)| self.lifetime_to_generic_param(
931                 span, hir_name, parent_id.index,
932             ))
933             .chain(in_band_ty_params.into_iter())
934             .collect();
935
936         (params, res)
937     }
938
939     /// Converts a lifetime into a new generic parameter.
940     fn lifetime_to_generic_param(
941         &mut self,
942         span: Span,
943         hir_name: ParamName,
944         parent_index: DefIndex,
945     ) -> hir::GenericParam {
946         let node_id = self.sess.next_node_id();
947
948         // Get the name we'll use to make the def-path. Note
949         // that collisions are ok here and this shouldn't
950         // really show up for end-user.
951         let (str_name, kind) = match hir_name {
952             ParamName::Plain(ident) => (
953                 ident.as_interned_str(),
954                 hir::LifetimeParamKind::InBand,
955             ),
956             ParamName::Fresh(_) => (
957                 kw::UnderscoreLifetime.as_interned_str(),
958                 hir::LifetimeParamKind::Elided,
959             ),
960             ParamName::Error => (
961                 kw::UnderscoreLifetime.as_interned_str(),
962                 hir::LifetimeParamKind::Error,
963             ),
964         };
965
966         // Add a definition for the in-band lifetime def.
967         self.resolver.definitions().create_def_with_parent(
968             parent_index,
969             node_id,
970             DefPathData::LifetimeNs(str_name),
971             Mark::root(),
972             span,
973         );
974
975         hir::GenericParam {
976             hir_id: self.lower_node_id(node_id),
977             name: hir_name,
978             attrs: hir_vec![],
979             bounds: hir_vec![],
980             span,
981             pure_wrt_drop: false,
982             kind: hir::GenericParamKind::Lifetime { kind }
983         }
984     }
985
986     /// When there is a reference to some lifetime `'a`, and in-band
987     /// lifetimes are enabled, then we want to push that lifetime into
988     /// the vector of names to define later. In that case, it will get
989     /// added to the appropriate generics.
990     fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
991         if !self.is_collecting_in_band_lifetimes {
992             return;
993         }
994
995         if !self.sess.features_untracked().in_band_lifetimes {
996             return;
997         }
998
999         if self.in_scope_lifetimes.contains(&ident.modern()) {
1000             return;
1001         }
1002
1003         let hir_name = ParamName::Plain(ident);
1004
1005         if self.lifetimes_to_define.iter()
1006                                    .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
1007             return;
1008         }
1009
1010         self.lifetimes_to_define.push((ident.span, hir_name));
1011     }
1012
1013     /// When we have either an elided or `'_` lifetime in an impl
1014     /// header, we convert it to an in-band lifetime.
1015     fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
1016         assert!(self.is_collecting_in_band_lifetimes);
1017         let index = self.lifetimes_to_define.len();
1018         let hir_name = ParamName::Fresh(index);
1019         self.lifetimes_to_define.push((span, hir_name));
1020         hir_name
1021     }
1022
1023     // Evaluates `f` with the lifetimes in `params` in-scope.
1024     // This is used to track which lifetimes have already been defined, and
1025     // which are new in-band lifetimes that need to have a definition created
1026     // for them.
1027     fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
1028     where
1029         F: FnOnce(&mut LoweringContext<'_>) -> T,
1030     {
1031         let old_len = self.in_scope_lifetimes.len();
1032         let lt_def_names = params.iter().filter_map(|param| match param.kind {
1033             GenericParamKind::Lifetime { .. } => Some(param.ident.modern()),
1034             _ => None,
1035         });
1036         self.in_scope_lifetimes.extend(lt_def_names);
1037
1038         let res = f(self);
1039
1040         self.in_scope_lifetimes.truncate(old_len);
1041         res
1042     }
1043
1044     // Same as the method above, but accepts `hir::GenericParam`s
1045     // instead of `ast::GenericParam`s.
1046     // This should only be used with generics that have already had their
1047     // in-band lifetimes added. In practice, this means that this function is
1048     // only used when lowering a child item of a trait or impl.
1049     fn with_parent_item_lifetime_defs<T, F>(&mut self,
1050         parent_hir_id: hir::HirId,
1051         f: F
1052     ) -> T where
1053         F: FnOnce(&mut LoweringContext<'_>) -> T,
1054     {
1055         let old_len = self.in_scope_lifetimes.len();
1056
1057         let parent_generics = match self.items.get(&parent_hir_id).unwrap().node {
1058             hir::ItemKind::Impl(_, _, _, ref generics, ..)
1059             | hir::ItemKind::Trait(_, _, ref generics, ..) => {
1060                 &generics.params[..]
1061             }
1062             _ => &[],
1063         };
1064         let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
1065             hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
1066             _ => None,
1067         });
1068         self.in_scope_lifetimes.extend(lt_def_names);
1069
1070         let res = f(self);
1071
1072         self.in_scope_lifetimes.truncate(old_len);
1073         res
1074     }
1075
1076     /// Appends in-band lifetime defs and argument-position `impl
1077     /// Trait` defs to the existing set of generics.
1078     ///
1079     /// Presuming that in-band lifetimes are enabled, then
1080     /// `self.anonymous_lifetime_mode` will be updated to match the
1081     /// argument while `f` is running (and restored afterwards).
1082     fn add_in_band_defs<F, T>(
1083         &mut self,
1084         generics: &Generics,
1085         parent_id: DefId,
1086         anonymous_lifetime_mode: AnonymousLifetimeMode,
1087         f: F,
1088     ) -> (hir::Generics, T)
1089     where
1090         F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
1091     {
1092         let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
1093             &generics.params,
1094             |this| {
1095                 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
1096                     let mut params = Vec::new();
1097                     // Note: it is necessary to lower generics *before* calling `f`.
1098                     // When lowering `async fn`, there's a final step when lowering
1099                     // the return type that assumes that all in-scope lifetimes have
1100                     // already been added to either `in_scope_lifetimes` or
1101                     // `lifetimes_to_define`. If we swapped the order of these two,
1102                     // in-band-lifetimes introduced by generics or where-clauses
1103                     // wouldn't have been added yet.
1104                     let generics = this.lower_generics(
1105                         generics,
1106                         ImplTraitContext::Universal(&mut params),
1107                     );
1108                     let res = f(this, &mut params);
1109                     (params, (generics, res))
1110                 })
1111             },
1112         );
1113
1114         lowered_generics.params = lowered_generics
1115             .params
1116             .into_iter()
1117             .chain(in_band_defs)
1118             .collect();
1119
1120         // FIXME(const_generics): the compiler doesn't always cope with
1121         // unsorted generic parameters at the moment, so we make sure
1122         // that they're ordered correctly here for now. (When we chain
1123         // the `in_band_defs`, we might make the order unsorted.)
1124         lowered_generics.params.sort_by_key(|param| {
1125             match param.kind {
1126                 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
1127                 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
1128                 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
1129             }
1130         });
1131
1132         (lowered_generics, res)
1133     }
1134
1135     fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
1136     where
1137         F: FnOnce(&mut LoweringContext<'_>) -> T,
1138     {
1139         let len = self.catch_scopes.len();
1140         self.catch_scopes.push(catch_id);
1141
1142         let result = f(self);
1143         assert_eq!(
1144             len + 1,
1145             self.catch_scopes.len(),
1146             "catch scopes should be added and removed in stack order"
1147         );
1148
1149         self.catch_scopes.pop().unwrap();
1150
1151         result
1152     }
1153
1154     fn make_async_expr(
1155         &mut self,
1156         capture_clause: CaptureBy,
1157         closure_node_id: NodeId,
1158         ret_ty: Option<&Ty>,
1159         span: Span,
1160         body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1161     ) -> hir::ExprKind {
1162         let capture_clause = self.lower_capture_clause(capture_clause);
1163         let output = match ret_ty {
1164             Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
1165             None => FunctionRetTy::Default(span),
1166         };
1167         let ast_decl = FnDecl {
1168             inputs: vec![],
1169             output,
1170             c_variadic: false
1171         };
1172         let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
1173         let body_id = self.lower_fn_body(&ast_decl, |this| {
1174             this.generator_kind = Some(hir::GeneratorKind::Async);
1175             body(this)
1176         });
1177         let generator = hir::Expr {
1178             hir_id: self.lower_node_id(closure_node_id),
1179             node: hir::ExprKind::Closure(capture_clause, decl, body_id, span,
1180                 Some(hir::GeneratorMovability::Static)),
1181             span,
1182             attrs: ThinVec::new(),
1183         };
1184
1185         let unstable_span = self.mark_span_with_reason(
1186             CompilerDesugaringKind::Async,
1187             span,
1188             self.allow_gen_future.clone(),
1189         );
1190         let gen_future = self.expr_std_path(
1191             unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
1192         hir::ExprKind::Call(P(gen_future), hir_vec![generator])
1193     }
1194
1195     fn lower_body(
1196         &mut self,
1197         f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Arg>, hir::Expr),
1198     ) -> hir::BodyId {
1199         let prev_gen_kind = self.generator_kind.take();
1200         let (arguments, result) = f(self);
1201         let body_id = self.record_body(arguments, result);
1202         self.generator_kind = prev_gen_kind;
1203         body_id
1204     }
1205
1206     fn lower_fn_body(
1207         &mut self,
1208         decl: &FnDecl,
1209         body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
1210     ) -> hir::BodyId {
1211         self.lower_body(|this| (
1212             decl.inputs.iter().map(|x| this.lower_arg(x)).collect(),
1213             body(this),
1214         ))
1215     }
1216
1217     fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
1218         self.lower_body(|this| (hir_vec![], this.lower_expr(expr)))
1219     }
1220
1221     fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
1222     where
1223         F: FnOnce(&mut LoweringContext<'_>) -> T,
1224     {
1225         // We're no longer in the base loop's condition; we're in another loop.
1226         let was_in_loop_condition = self.is_in_loop_condition;
1227         self.is_in_loop_condition = false;
1228
1229         let len = self.loop_scopes.len();
1230         self.loop_scopes.push(loop_id);
1231
1232         let result = f(self);
1233         assert_eq!(
1234             len + 1,
1235             self.loop_scopes.len(),
1236             "loop scopes should be added and removed in stack order"
1237         );
1238
1239         self.loop_scopes.pop().unwrap();
1240
1241         self.is_in_loop_condition = was_in_loop_condition;
1242
1243         result
1244     }
1245
1246     fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
1247     where
1248         F: FnOnce(&mut LoweringContext<'_>) -> T,
1249     {
1250         let was_in_loop_condition = self.is_in_loop_condition;
1251         self.is_in_loop_condition = true;
1252
1253         let result = f(self);
1254
1255         self.is_in_loop_condition = was_in_loop_condition;
1256
1257         result
1258     }
1259
1260     fn with_dyn_type_scope<T, F>(&mut self, in_scope: bool, f: F) -> T
1261     where
1262         F: FnOnce(&mut LoweringContext<'_>) -> T,
1263     {
1264         let was_in_dyn_type = self.is_in_dyn_type;
1265         self.is_in_dyn_type = in_scope;
1266
1267         let result = f(self);
1268
1269         self.is_in_dyn_type = was_in_dyn_type;
1270
1271         result
1272     }
1273
1274     fn with_new_scopes<T, F>(&mut self, f: F) -> T
1275     where
1276         F: FnOnce(&mut LoweringContext<'_>) -> T,
1277     {
1278         let was_in_loop_condition = self.is_in_loop_condition;
1279         self.is_in_loop_condition = false;
1280
1281         let catch_scopes = mem::take(&mut self.catch_scopes);
1282         let loop_scopes = mem::take(&mut self.loop_scopes);
1283         let ret = f(self);
1284         self.catch_scopes = catch_scopes;
1285         self.loop_scopes = loop_scopes;
1286
1287         self.is_in_loop_condition = was_in_loop_condition;
1288
1289         ret
1290     }
1291
1292     fn def_key(&mut self, id: DefId) -> DefKey {
1293         if id.is_local() {
1294             self.resolver.definitions().def_key(id.index)
1295         } else {
1296             self.cstore.def_key(id)
1297         }
1298     }
1299
1300     fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
1301         label.map(|label| hir::Label {
1302             ident: label.ident,
1303         })
1304     }
1305
1306     fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1307         let target_id = match destination {
1308             Some((id, _)) => {
1309                 if let Some(loop_id) = self.resolver.get_label_res(id) {
1310                     Ok(self.lower_node_id(loop_id))
1311                 } else {
1312                     Err(hir::LoopIdError::UnresolvedLabel)
1313                 }
1314             }
1315             None => {
1316                 self.loop_scopes
1317                     .last()
1318                     .cloned()
1319                     .map(|id| Ok(self.lower_node_id(id)))
1320                     .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1321                     .into()
1322             }
1323         };
1324         hir::Destination {
1325             label: self.lower_label(destination.map(|(_, label)| label)),
1326             target_id,
1327         }
1328     }
1329
1330     fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
1331         attrs
1332             .iter()
1333             .map(|a| self.lower_attr(a))
1334             .collect()
1335     }
1336
1337     fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
1338         // Note that we explicitly do not walk the path. Since we don't really
1339         // lower attributes (we use the AST version) there is nowhere to keep
1340         // the `HirId`s. We don't actually need HIR version of attributes anyway.
1341         Attribute {
1342             id: attr.id,
1343             style: attr.style,
1344             path: attr.path.clone(),
1345             tokens: self.lower_token_stream(attr.tokens.clone()),
1346             is_sugared_doc: attr.is_sugared_doc,
1347             span: attr.span,
1348         }
1349     }
1350
1351     fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1352         tokens
1353             .into_trees()
1354             .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1355             .collect()
1356     }
1357
1358     fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1359         match tree {
1360             TokenTree::Token(token) => self.lower_token(token),
1361             TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1362                 span,
1363                 delim,
1364                 self.lower_token_stream(tts),
1365             ).into(),
1366         }
1367     }
1368
1369     fn lower_token(&mut self, token: Token) -> TokenStream {
1370         match token.kind {
1371             token::Interpolated(nt) => {
1372                 let tts = nt.to_tokenstream(&self.sess.parse_sess, token.span);
1373                 self.lower_token_stream(tts)
1374             }
1375             _ => TokenTree::Token(token).into(),
1376         }
1377     }
1378
1379     fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
1380         hir::Arm {
1381             hir_id: self.next_id(),
1382             attrs: self.lower_attrs(&arm.attrs),
1383             pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(),
1384             guard: match arm.guard {
1385                 Some(ref x) => Some(hir::Guard::If(P(self.lower_expr(x)))),
1386                 _ => None,
1387             },
1388             body: P(self.lower_expr(&arm.body)),
1389             span: arm.span,
1390         }
1391     }
1392
1393     /// Given an associated type constraint like one of these:
1394     ///
1395     /// ```
1396     /// T: Iterator<Item: Debug>
1397     ///             ^^^^^^^^^^^
1398     /// T: Iterator<Item = Debug>
1399     ///             ^^^^^^^^^^^^
1400     /// ```
1401     ///
1402     /// returns a `hir::TypeBinding` representing `Item`.
1403     fn lower_assoc_ty_constraint(&mut self,
1404                                  c: &AssocTyConstraint,
1405                                  itctx: ImplTraitContext<'_>)
1406                                  -> hir::TypeBinding {
1407         debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", c, itctx);
1408
1409         let kind = match c.kind {
1410             AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1411                 ty: self.lower_ty(ty, itctx)
1412             },
1413             AssocTyConstraintKind::Bound { ref bounds } => {
1414                 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1415                 let (desugar_to_impl_trait, itctx) = match itctx {
1416                     // We are in the return position:
1417                     //
1418                     //     fn foo() -> impl Iterator<Item: Debug>
1419                     //
1420                     // so desugar to
1421                     //
1422                     //     fn foo() -> impl Iterator<Item = impl Debug>
1423                     ImplTraitContext::Existential(_) => (true, itctx),
1424
1425                     // We are in the argument position, but within a dyn type:
1426                     //
1427                     //     fn foo(x: dyn Iterator<Item: Debug>)
1428                     //
1429                     // so desugar to
1430                     //
1431                     //     fn foo(x: dyn Iterator<Item = impl Debug>)
1432                     ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1433
1434                     // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1435                     // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1436                     // "impl trait context" to permit `impl Debug` in this position (it desugars
1437                     // then to an existential type).
1438                     //
1439                     // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1440                     ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1441                         (true, ImplTraitContext::Existential(None)),
1442
1443                     // We are in the argument position, but not within a dyn type:
1444                     //
1445                     //     fn foo(x: impl Iterator<Item: Debug>)
1446                     //
1447                     // so we leave it as is and this gets expanded in astconv to a bound like
1448                     // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1449                     // `impl Iterator`.
1450                     _ => (false, itctx),
1451                 };
1452
1453                 if desugar_to_impl_trait {
1454                     // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1455                     // constructing the HIR for `impl bounds...` and then lowering that.
1456
1457                     let impl_trait_node_id = self.sess.next_node_id();
1458                     let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1459                     self.resolver.definitions().create_def_with_parent(
1460                         parent_def_index,
1461                         impl_trait_node_id,
1462                         DefPathData::ImplTrait,
1463                         Mark::root(),
1464                         DUMMY_SP
1465                     );
1466
1467                     self.with_dyn_type_scope(false, |this| {
1468                         let ty = this.lower_ty(
1469                             &Ty {
1470                                 id: this.sess.next_node_id(),
1471                                 node: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1472                                 span: DUMMY_SP,
1473                             },
1474                             itctx,
1475                         );
1476
1477                         hir::TypeBindingKind::Equality {
1478                             ty
1479                         }
1480                     })
1481                 } else {
1482                     // Desugar `AssocTy: Bounds` into a type binding where the
1483                     // later desugars into a trait predicate.
1484                     let bounds = self.lower_param_bounds(bounds, itctx);
1485
1486                     hir::TypeBindingKind::Constraint {
1487                         bounds
1488                     }
1489                 }
1490             }
1491         };
1492
1493         hir::TypeBinding {
1494             hir_id: self.lower_node_id(c.id),
1495             ident: c.ident,
1496             kind,
1497             span: c.span,
1498         }
1499     }
1500
1501     fn lower_generic_arg(&mut self,
1502                          arg: &ast::GenericArg,
1503                          itctx: ImplTraitContext<'_>)
1504                          -> hir::GenericArg {
1505         match arg {
1506             ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(&lt)),
1507             ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1508             ast::GenericArg::Const(ct) => {
1509                 GenericArg::Const(ConstArg {
1510                     value: self.lower_anon_const(&ct),
1511                     span: ct.value.span,
1512                 })
1513             }
1514         }
1515     }
1516
1517     fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1518         P(self.lower_ty_direct(t, itctx))
1519     }
1520
1521     fn lower_path_ty(
1522         &mut self,
1523         t: &Ty,
1524         qself: &Option<QSelf>,
1525         path: &Path,
1526         param_mode: ParamMode,
1527         itctx: ImplTraitContext<'_>
1528     ) -> hir::Ty {
1529         let id = self.lower_node_id(t.id);
1530         let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1531         let ty = self.ty_path(id, t.span, qpath);
1532         if let hir::TyKind::TraitObject(..) = ty.node {
1533             self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1534         }
1535         ty
1536     }
1537
1538     fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1539         let kind = match t.node {
1540             TyKind::Infer => hir::TyKind::Infer,
1541             TyKind::Err => hir::TyKind::Err,
1542             TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1543             TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1544             TyKind::Rptr(ref region, ref mt) => {
1545                 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1546                 let lifetime = match *region {
1547                     Some(ref lt) => self.lower_lifetime(lt),
1548                     None => self.elided_ref_lifetime(span),
1549                 };
1550                 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1551             }
1552             TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1553                 &f.generic_params,
1554                 |this| {
1555                     this.with_anonymous_lifetime_mode(
1556                         AnonymousLifetimeMode::PassThrough,
1557                         |this| {
1558                             hir::TyKind::BareFn(P(hir::BareFnTy {
1559                                 generic_params: this.lower_generic_params(
1560                                     &f.generic_params,
1561                                     &NodeMap::default(),
1562                                     ImplTraitContext::disallowed(),
1563                                 ),
1564                                 unsafety: this.lower_unsafety(f.unsafety),
1565                                 abi: f.abi,
1566                                 decl: this.lower_fn_decl(&f.decl, None, false, None),
1567                                 arg_names: this.lower_fn_args_to_names(&f.decl),
1568                             }))
1569                         },
1570                     )
1571                 },
1572             ),
1573             TyKind::Never => hir::TyKind::Never,
1574             TyKind::Tup(ref tys) => {
1575                 hir::TyKind::Tup(tys.iter().map(|ty| {
1576                     self.lower_ty_direct(ty, itctx.reborrow())
1577                 }).collect())
1578             }
1579             TyKind::Paren(ref ty) => {
1580                 return self.lower_ty_direct(ty, itctx);
1581             }
1582             TyKind::Path(ref qself, ref path) => {
1583                 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1584             }
1585             TyKind::ImplicitSelf => {
1586                 let res = self.expect_full_res(t.id);
1587                 let res = self.lower_res(res);
1588                 hir::TyKind::Path(hir::QPath::Resolved(
1589                     None,
1590                     P(hir::Path {
1591                         res,
1592                         segments: hir_vec![hir::PathSegment::from_ident(
1593                             Ident::with_empty_ctxt(kw::SelfUpper)
1594                         )],
1595                         span: t.span,
1596                     }),
1597                 ))
1598             },
1599             TyKind::Array(ref ty, ref length) => {
1600                 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1601             }
1602             TyKind::Typeof(ref expr) => {
1603                 hir::TyKind::Typeof(self.lower_anon_const(expr))
1604             }
1605             TyKind::TraitObject(ref bounds, kind) => {
1606                 let mut lifetime_bound = None;
1607                 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1608                     let bounds = bounds
1609                         .iter()
1610                         .filter_map(|bound| match *bound {
1611                             GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1612                                 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1613                             }
1614                             GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1615                             GenericBound::Outlives(ref lifetime) => {
1616                                 if lifetime_bound.is_none() {
1617                                     lifetime_bound = Some(this.lower_lifetime(lifetime));
1618                                 }
1619                                 None
1620                             }
1621                         })
1622                         .collect();
1623                     let lifetime_bound =
1624                         lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1625                     (bounds, lifetime_bound)
1626                 });
1627                 if kind != TraitObjectSyntax::Dyn {
1628                     self.maybe_lint_bare_trait(t.span, t.id, false);
1629                 }
1630                 hir::TyKind::TraitObject(bounds, lifetime_bound)
1631             }
1632             TyKind::ImplTrait(def_node_id, ref bounds) => {
1633                 let span = t.span;
1634                 match itctx {
1635                     ImplTraitContext::Existential(fn_def_id) => {
1636                         self.lower_existential_impl_trait(
1637                             span, fn_def_id, def_node_id,
1638                             |this| this.lower_param_bounds(bounds, itctx),
1639                         )
1640                     }
1641                     ImplTraitContext::Universal(in_band_ty_params) => {
1642                         // Add a definition for the in-band `Param`.
1643                         let def_index = self
1644                             .resolver
1645                             .definitions()
1646                             .opt_def_index(def_node_id)
1647                             .unwrap();
1648
1649                         let hir_bounds = self.lower_param_bounds(
1650                             bounds,
1651                             ImplTraitContext::Universal(in_band_ty_params),
1652                         );
1653                         // Set the name to `impl Bound1 + Bound2`.
1654                         let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
1655                         in_band_ty_params.push(hir::GenericParam {
1656                             hir_id: self.lower_node_id(def_node_id),
1657                             name: ParamName::Plain(ident),
1658                             pure_wrt_drop: false,
1659                             attrs: hir_vec![],
1660                             bounds: hir_bounds,
1661                             span,
1662                             kind: hir::GenericParamKind::Type {
1663                                 default: None,
1664                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1665                             }
1666                         });
1667
1668                         hir::TyKind::Path(hir::QPath::Resolved(
1669                             None,
1670                             P(hir::Path {
1671                                 span,
1672                                 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1673                                 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1674                             }),
1675                         ))
1676                     }
1677                     ImplTraitContext::Disallowed(pos) => {
1678                         let allowed_in = if self.sess.features_untracked()
1679                                                 .impl_trait_in_bindings {
1680                             "bindings or function and inherent method return types"
1681                         } else {
1682                             "function and inherent method return types"
1683                         };
1684                         let mut err = struct_span_err!(
1685                             self.sess,
1686                             t.span,
1687                             E0562,
1688                             "`impl Trait` not allowed outside of {}",
1689                             allowed_in,
1690                         );
1691                         if pos == ImplTraitPosition::Binding &&
1692                             nightly_options::is_nightly_build() {
1693                             help!(err,
1694                                   "add #![feature(impl_trait_in_bindings)] to the crate attributes \
1695                                    to enable");
1696                         }
1697                         err.emit();
1698                         hir::TyKind::Err
1699                     }
1700                 }
1701             }
1702             TyKind::Mac(_) => bug!("`TyMac` should have been expanded by now."),
1703             TyKind::CVarArgs => {
1704                 // Create the implicit lifetime of the "spoofed" `VaListImpl`.
1705                 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1706                 let lt = self.new_implicit_lifetime(span);
1707                 hir::TyKind::CVarArgs(lt)
1708             },
1709         };
1710
1711         hir::Ty {
1712             node: kind,
1713             span: t.span,
1714             hir_id: self.lower_node_id(t.id),
1715         }
1716     }
1717
1718     fn lower_existential_impl_trait(
1719         &mut self,
1720         span: Span,
1721         fn_def_id: Option<DefId>,
1722         exist_ty_node_id: NodeId,
1723         lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1724     ) -> hir::TyKind {
1725         // Make sure we know that some funky desugaring has been going on here.
1726         // This is a first: there is code in other places like for loop
1727         // desugaring that explicitly states that we don't want to track that.
1728         // Not tracking it makes lints in rustc and clippy very fragile, as
1729         // frequently opened issues show.
1730         let exist_ty_span = self.mark_span_with_reason(
1731             CompilerDesugaringKind::ExistentialType,
1732             span,
1733             None,
1734         );
1735
1736         let exist_ty_def_index = self
1737             .resolver
1738             .definitions()
1739             .opt_def_index(exist_ty_node_id)
1740             .unwrap();
1741
1742         self.allocate_hir_id_counter(exist_ty_node_id);
1743
1744         let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, lower_bounds);
1745
1746         let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1747             exist_ty_node_id,
1748             exist_ty_def_index,
1749             &hir_bounds,
1750         );
1751
1752         self.with_hir_id_owner(exist_ty_node_id, |lctx| {
1753             let exist_ty_item = hir::ExistTy {
1754                 generics: hir::Generics {
1755                     params: lifetime_defs,
1756                     where_clause: hir::WhereClause {
1757                         predicates: hir_vec![],
1758                         span,
1759                     },
1760                     span,
1761                 },
1762                 bounds: hir_bounds,
1763                 impl_trait_fn: fn_def_id,
1764                 origin: hir::ExistTyOrigin::ReturnImplTrait,
1765             };
1766
1767             trace!("exist ty from impl trait def-index: {:#?}", exist_ty_def_index);
1768             let exist_ty_id = lctx.generate_existential_type(
1769                 exist_ty_node_id,
1770                 exist_ty_item,
1771                 span,
1772                 exist_ty_span,
1773             );
1774
1775             // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1776             hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, lifetimes)
1777         })
1778     }
1779
1780     /// Registers a new existential type with the proper `NodeId`s and
1781     /// returns the lowered node-ID for the existential type.
1782     fn generate_existential_type(
1783         &mut self,
1784         exist_ty_node_id: NodeId,
1785         exist_ty_item: hir::ExistTy,
1786         span: Span,
1787         exist_ty_span: Span,
1788     ) -> hir::HirId {
1789         let exist_ty_item_kind = hir::ItemKind::Existential(exist_ty_item);
1790         let exist_ty_id = self.lower_node_id(exist_ty_node_id);
1791         // Generate an `existential type Foo: Trait;` declaration.
1792         trace!("registering existential type with id {:#?}", exist_ty_id);
1793         let exist_ty_item = hir::Item {
1794             hir_id: exist_ty_id,
1795             ident: Ident::invalid(),
1796             attrs: Default::default(),
1797             node: exist_ty_item_kind,
1798             vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1799             span: exist_ty_span,
1800         };
1801
1802         // Insert the item into the global item list. This usually happens
1803         // automatically for all AST items. But this existential type item
1804         // does not actually exist in the AST.
1805         self.insert_item(exist_ty_item);
1806         exist_ty_id
1807     }
1808
1809     fn lifetimes_from_impl_trait_bounds(
1810         &mut self,
1811         exist_ty_id: NodeId,
1812         parent_index: DefIndex,
1813         bounds: &hir::GenericBounds,
1814     ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1815         // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1816         // appear in the bounds, excluding lifetimes that are created within the bounds.
1817         // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1818         struct ImplTraitLifetimeCollector<'r, 'a> {
1819             context: &'r mut LoweringContext<'a>,
1820             parent: DefIndex,
1821             exist_ty_id: NodeId,
1822             collect_elided_lifetimes: bool,
1823             currently_bound_lifetimes: Vec<hir::LifetimeName>,
1824             already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1825             output_lifetimes: Vec<hir::GenericArg>,
1826             output_lifetime_params: Vec<hir::GenericParam>,
1827         }
1828
1829         impl<'r, 'a, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1830             fn nested_visit_map<'this>(
1831                 &'this mut self,
1832             ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1833                 hir::intravisit::NestedVisitorMap::None
1834             }
1835
1836             fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1837                 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1838                 if parameters.parenthesized {
1839                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1840                     self.collect_elided_lifetimes = false;
1841                     hir::intravisit::walk_generic_args(self, span, parameters);
1842                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1843                 } else {
1844                     hir::intravisit::walk_generic_args(self, span, parameters);
1845                 }
1846             }
1847
1848             fn visit_ty(&mut self, t: &'v hir::Ty) {
1849                 // Don't collect elided lifetimes used inside of `fn()` syntax.
1850                 if let hir::TyKind::BareFn(_) = t.node {
1851                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1852                     self.collect_elided_lifetimes = false;
1853
1854                     // Record the "stack height" of `for<'a>` lifetime bindings
1855                     // to be able to later fully undo their introduction.
1856                     let old_len = self.currently_bound_lifetimes.len();
1857                     hir::intravisit::walk_ty(self, t);
1858                     self.currently_bound_lifetimes.truncate(old_len);
1859
1860                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1861                 } else {
1862                     hir::intravisit::walk_ty(self, t)
1863                 }
1864             }
1865
1866             fn visit_poly_trait_ref(
1867                 &mut self,
1868                 trait_ref: &'v hir::PolyTraitRef,
1869                 modifier: hir::TraitBoundModifier,
1870             ) {
1871                 // Record the "stack height" of `for<'a>` lifetime bindings
1872                 // to be able to later fully undo their introduction.
1873                 let old_len = self.currently_bound_lifetimes.len();
1874                 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1875                 self.currently_bound_lifetimes.truncate(old_len);
1876             }
1877
1878             fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1879                 // Record the introduction of 'a in `for<'a> ...`.
1880                 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1881                     // Introduce lifetimes one at a time so that we can handle
1882                     // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1883                     let lt_name = hir::LifetimeName::Param(param.name);
1884                     self.currently_bound_lifetimes.push(lt_name);
1885                 }
1886
1887                 hir::intravisit::walk_generic_param(self, param);
1888             }
1889
1890             fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1891                 let name = match lifetime.name {
1892                     hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1893                         if self.collect_elided_lifetimes {
1894                             // Use `'_` for both implicit and underscore lifetimes in
1895                             // `abstract type Foo<'_>: SomeTrait<'_>;`.
1896                             hir::LifetimeName::Underscore
1897                         } else {
1898                             return;
1899                         }
1900                     }
1901                     hir::LifetimeName::Param(_) => lifetime.name,
1902                     hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1903                 };
1904
1905                 if !self.currently_bound_lifetimes.contains(&name)
1906                     && !self.already_defined_lifetimes.contains(&name) {
1907                     self.already_defined_lifetimes.insert(name);
1908
1909                     self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1910                         hir_id: self.context.next_id(),
1911                         span: lifetime.span,
1912                         name,
1913                     }));
1914
1915                     let def_node_id = self.context.sess.next_node_id();
1916                     let hir_id =
1917                         self.context.lower_node_id_with_owner(def_node_id, self.exist_ty_id);
1918                     self.context.resolver.definitions().create_def_with_parent(
1919                         self.parent,
1920                         def_node_id,
1921                         DefPathData::LifetimeNs(name.ident().as_interned_str()),
1922                         Mark::root(),
1923                         lifetime.span);
1924
1925                     let (name, kind) = match name {
1926                         hir::LifetimeName::Underscore => (
1927                             hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)),
1928                             hir::LifetimeParamKind::Elided,
1929                         ),
1930                         hir::LifetimeName::Param(param_name) => (
1931                             param_name,
1932                             hir::LifetimeParamKind::Explicit,
1933                         ),
1934                         _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1935                     };
1936
1937                     self.output_lifetime_params.push(hir::GenericParam {
1938                         hir_id,
1939                         name,
1940                         span: lifetime.span,
1941                         pure_wrt_drop: false,
1942                         attrs: hir_vec![],
1943                         bounds: hir_vec![],
1944                         kind: hir::GenericParamKind::Lifetime { kind }
1945                     });
1946                 }
1947             }
1948         }
1949
1950         let mut lifetime_collector = ImplTraitLifetimeCollector {
1951             context: self,
1952             parent: parent_index,
1953             exist_ty_id,
1954             collect_elided_lifetimes: true,
1955             currently_bound_lifetimes: Vec::new(),
1956             already_defined_lifetimes: FxHashSet::default(),
1957             output_lifetimes: Vec::new(),
1958             output_lifetime_params: Vec::new(),
1959         };
1960
1961         for bound in bounds {
1962             hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1963         }
1964
1965         (
1966             lifetime_collector.output_lifetimes.into(),
1967             lifetime_collector.output_lifetime_params.into(),
1968         )
1969     }
1970
1971     fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
1972         hir::ForeignMod {
1973             abi: fm.abi,
1974             items: fm.items
1975                 .iter()
1976                 .map(|x| self.lower_foreign_item(x))
1977                 .collect(),
1978         }
1979     }
1980
1981     fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
1982         P(hir::GlobalAsm {
1983             asm: ga.asm,
1984             ctxt: ga.ctxt,
1985         })
1986     }
1987
1988     fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
1989         Spanned {
1990             node: hir::VariantKind {
1991                 ident: v.node.ident,
1992                 id: self.lower_node_id(v.node.id),
1993                 attrs: self.lower_attrs(&v.node.attrs),
1994                 data: self.lower_variant_data(&v.node.data),
1995                 disr_expr: v.node.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
1996             },
1997             span: v.span,
1998         }
1999     }
2000
2001     fn lower_qpath(
2002         &mut self,
2003         id: NodeId,
2004         qself: &Option<QSelf>,
2005         p: &Path,
2006         param_mode: ParamMode,
2007         mut itctx: ImplTraitContext<'_>,
2008     ) -> hir::QPath {
2009         let qself_position = qself.as_ref().map(|q| q.position);
2010         let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
2011
2012         let partial_res = self.resolver
2013             .get_partial_res(id)
2014             .unwrap_or_else(|| PartialRes::new(Res::Err));
2015
2016         let proj_start = p.segments.len() - partial_res.unresolved_segments();
2017         let path = P(hir::Path {
2018             res: self.lower_res(partial_res.base_res()),
2019             segments: p.segments[..proj_start]
2020                 .iter()
2021                 .enumerate()
2022                 .map(|(i, segment)| {
2023                     let param_mode = match (qself_position, param_mode) {
2024                         (Some(j), ParamMode::Optional) if i < j => {
2025                             // This segment is part of the trait path in a
2026                             // qualified path - one of `a`, `b` or `Trait`
2027                             // in `<X as a::b::Trait>::T::U::method`.
2028                             ParamMode::Explicit
2029                         }
2030                         _ => param_mode,
2031                     };
2032
2033                     // Figure out if this is a type/trait segment,
2034                     // which may need lifetime elision performed.
2035                     let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
2036                         krate: def_id.krate,
2037                         index: this.def_key(def_id).parent.expect("missing parent"),
2038                     };
2039                     let type_def_id = match partial_res.base_res() {
2040                         Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2041                             Some(parent_def_id(self, def_id))
2042                         }
2043                         Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2044                             Some(parent_def_id(self, def_id))
2045                         }
2046                         Res::Def(DefKind::Struct, def_id)
2047                         | Res::Def(DefKind::Union, def_id)
2048                         | Res::Def(DefKind::Enum, def_id)
2049                         | Res::Def(DefKind::TyAlias, def_id)
2050                         | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
2051                         {
2052                             Some(def_id)
2053                         }
2054                         _ => None,
2055                     };
2056                     let parenthesized_generic_args = match partial_res.base_res() {
2057                         // `a::b::Trait(Args)`
2058                         Res::Def(DefKind::Trait, _)
2059                             if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
2060                         // `a::b::Trait(Args)::TraitItem`
2061                         Res::Def(DefKind::Method, _)
2062                         | Res::Def(DefKind::AssocConst, _)
2063                         | Res::Def(DefKind::AssocTy, _)
2064                             if i + 2 == proj_start =>
2065                         {
2066                             ParenthesizedGenericArgs::Ok
2067                         }
2068                         // Avoid duplicated errors.
2069                         Res::Err => ParenthesizedGenericArgs::Ok,
2070                         // An error
2071                         Res::Def(DefKind::Struct, _)
2072                         | Res::Def(DefKind::Enum, _)
2073                         | Res::Def(DefKind::Union, _)
2074                         | Res::Def(DefKind::TyAlias, _)
2075                         | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
2076                         {
2077                             ParenthesizedGenericArgs::Err
2078                         }
2079                         // A warning for now, for compatibility reasons.
2080                         _ => ParenthesizedGenericArgs::Warn,
2081                     };
2082
2083                     let num_lifetimes = type_def_id.map_or(0, |def_id| {
2084                         if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
2085                             return n;
2086                         }
2087                         assert!(!def_id.is_local());
2088                         let item_generics =
2089                             self.cstore.item_generics_cloned_untracked(def_id, self.sess);
2090                         let n = item_generics.own_counts().lifetimes;
2091                         self.type_def_lifetime_params.insert(def_id, n);
2092                         n
2093                     });
2094                     self.lower_path_segment(
2095                         p.span,
2096                         segment,
2097                         param_mode,
2098                         num_lifetimes,
2099                         parenthesized_generic_args,
2100                         itctx.reborrow(),
2101                         None,
2102                     )
2103                 })
2104                 .collect(),
2105             span: p.span,
2106         });
2107
2108         // Simple case, either no projections, or only fully-qualified.
2109         // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
2110         if partial_res.unresolved_segments() == 0 {
2111             return hir::QPath::Resolved(qself, path);
2112         }
2113
2114         // Create the innermost type that we're projecting from.
2115         let mut ty = if path.segments.is_empty() {
2116             // If the base path is empty that means there exists a
2117             // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
2118             qself.expect("missing QSelf for <T>::...")
2119         } else {
2120             // Otherwise, the base path is an implicit `Self` type path,
2121             // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
2122             // `<I as Iterator>::Item::default`.
2123             let new_id = self.next_id();
2124             P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
2125         };
2126
2127         // Anything after the base path are associated "extensions",
2128         // out of which all but the last one are associated types,
2129         // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
2130         // * base path is `std::vec::Vec<T>`
2131         // * "extensions" are `IntoIter`, `Item` and `clone`
2132         // * type nodes are:
2133         //   1. `std::vec::Vec<T>` (created above)
2134         //   2. `<std::vec::Vec<T>>::IntoIter`
2135         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
2136         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
2137         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
2138             let segment = P(self.lower_path_segment(
2139                 p.span,
2140                 segment,
2141                 param_mode,
2142                 0,
2143                 ParenthesizedGenericArgs::Warn,
2144                 itctx.reborrow(),
2145                 None,
2146             ));
2147             let qpath = hir::QPath::TypeRelative(ty, segment);
2148
2149             // It's finished, return the extension of the right node type.
2150             if i == p.segments.len() - 1 {
2151                 return qpath;
2152             }
2153
2154             // Wrap the associated extension in another type node.
2155             let new_id = self.next_id();
2156             ty = P(self.ty_path(new_id, p.span, qpath));
2157         }
2158
2159         // We should've returned in the for loop above.
2160         span_bug!(
2161             p.span,
2162             "lower_qpath: no final extension segment in {}..{}",
2163             proj_start,
2164             p.segments.len()
2165         )
2166     }
2167
2168     fn lower_path_extra(
2169         &mut self,
2170         res: Res,
2171         p: &Path,
2172         param_mode: ParamMode,
2173         explicit_owner: Option<NodeId>,
2174     ) -> hir::Path {
2175         hir::Path {
2176             res,
2177             segments: p.segments
2178                 .iter()
2179                 .map(|segment| {
2180                     self.lower_path_segment(
2181                         p.span,
2182                         segment,
2183                         param_mode,
2184                         0,
2185                         ParenthesizedGenericArgs::Err,
2186                         ImplTraitContext::disallowed(),
2187                         explicit_owner,
2188                     )
2189                 })
2190                 .collect(),
2191             span: p.span,
2192         }
2193     }
2194
2195     fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
2196         let res = self.expect_full_res(id);
2197         let res = self.lower_res(res);
2198         self.lower_path_extra(res, p, param_mode, None)
2199     }
2200
2201     fn lower_path_segment(
2202         &mut self,
2203         path_span: Span,
2204         segment: &PathSegment,
2205         param_mode: ParamMode,
2206         expected_lifetimes: usize,
2207         parenthesized_generic_args: ParenthesizedGenericArgs,
2208         itctx: ImplTraitContext<'_>,
2209         explicit_owner: Option<NodeId>,
2210     ) -> hir::PathSegment {
2211         let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
2212             let msg = "parenthesized type parameters may only be used with a `Fn` trait";
2213             match **generic_args {
2214                 GenericArgs::AngleBracketed(ref data) => {
2215                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
2216                 }
2217                 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
2218                     ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
2219                     ParenthesizedGenericArgs::Warn => {
2220                         self.sess.buffer_lint(
2221                             PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
2222                             CRATE_NODE_ID,
2223                             data.span,
2224                             msg.into(),
2225                         );
2226                         (hir::GenericArgs::none(), true)
2227                     }
2228                     ParenthesizedGenericArgs::Err => {
2229                         let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
2230                         err.span_label(data.span, "only `Fn` traits may use parentheses");
2231                         if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
2232                             // Do not suggest going from `Trait()` to `Trait<>`
2233                             if data.inputs.len() > 0 {
2234                                 err.span_suggestion(
2235                                     data.span,
2236                                     "use angle brackets instead",
2237                                     format!("<{}>", &snippet[1..snippet.len() - 1]),
2238                                     Applicability::MaybeIncorrect,
2239                                 );
2240                             }
2241                         };
2242                         err.emit();
2243                         (
2244                             self.lower_angle_bracketed_parameter_data(
2245                                 &data.as_angle_bracketed_args(),
2246                                 param_mode,
2247                                 itctx
2248                             ).0,
2249                             false,
2250                         )
2251                     }
2252                 },
2253             }
2254         } else {
2255             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
2256         };
2257
2258         let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
2259             GenericArg::Lifetime(_) => true,
2260             _ => false,
2261         });
2262         let first_generic_span = generic_args.args.iter().map(|a| a.span())
2263             .chain(generic_args.bindings.iter().map(|b| b.span)).next();
2264         if !generic_args.parenthesized && !has_lifetimes {
2265             generic_args.args =
2266                 self.elided_path_lifetimes(path_span, expected_lifetimes)
2267                     .into_iter()
2268                     .map(|lt| GenericArg::Lifetime(lt))
2269                     .chain(generic_args.args.into_iter())
2270                 .collect();
2271             if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
2272                 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
2273                 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
2274                 let no_bindings = generic_args.bindings.is_empty();
2275                 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
2276                     // If there are no (non-implicit) generic args or associated type
2277                     // bindings, our suggestion includes the angle brackets.
2278                     (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
2279                 } else {
2280                     // Otherwise (sorry, this is kind of gross) we need to infer the
2281                     // place to splice in the `'_, ` from the generics that do exist.
2282                     let first_generic_span = first_generic_span
2283                         .expect("already checked that non-lifetime args or bindings exist");
2284                     (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
2285                 };
2286                 match self.anonymous_lifetime_mode {
2287                     // In create-parameter mode we error here because we don't want to support
2288                     // deprecated impl elision in new features like impl elision and `async fn`,
2289                     // both of which work using the `CreateParameter` mode:
2290                     //
2291                     //     impl Foo for std::cell::Ref<u32> // note lack of '_
2292                     //     async fn foo(_: std::cell::Ref<u32>) { ... }
2293                     AnonymousLifetimeMode::CreateParameter => {
2294                         let mut err = struct_span_err!(
2295                             self.sess,
2296                             path_span,
2297                             E0726,
2298                             "implicit elided lifetime not allowed here"
2299                         );
2300                         crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
2301                             &self.sess,
2302                             &mut err,
2303                             expected_lifetimes,
2304                             path_span,
2305                             incl_angl_brckt,
2306                             insertion_sp,
2307                             suggestion,
2308                         );
2309                         err.emit();
2310                     }
2311                     AnonymousLifetimeMode::PassThrough |
2312                     AnonymousLifetimeMode::ReportError |
2313                     AnonymousLifetimeMode::Replace(_) => {
2314                         self.sess.buffer_lint_with_diagnostic(
2315                             ELIDED_LIFETIMES_IN_PATHS,
2316                             CRATE_NODE_ID,
2317                             path_span,
2318                             "hidden lifetime parameters in types are deprecated",
2319                             builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
2320                                 expected_lifetimes,
2321                                 path_span,
2322                                 incl_angl_brckt,
2323                                 insertion_sp,
2324                                 suggestion,
2325                             )
2326                         );
2327                     }
2328                 }
2329             }
2330         }
2331
2332         let res = self.expect_full_res(segment.id);
2333         let id = if let Some(owner) = explicit_owner {
2334             self.lower_node_id_with_owner(segment.id, owner)
2335         } else {
2336             self.lower_node_id(segment.id)
2337         };
2338         debug!(
2339             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
2340             segment.ident, segment.id, id,
2341         );
2342
2343         hir::PathSegment::new(
2344             segment.ident,
2345             Some(id),
2346             Some(self.lower_res(res)),
2347             generic_args,
2348             infer_args,
2349         )
2350     }
2351
2352     fn lower_angle_bracketed_parameter_data(
2353         &mut self,
2354         data: &AngleBracketedArgs,
2355         param_mode: ParamMode,
2356         mut itctx: ImplTraitContext<'_>,
2357     ) -> (hir::GenericArgs, bool) {
2358         let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2359         let has_non_lt_args = args.iter().any(|arg| match arg {
2360             ast::GenericArg::Lifetime(_) => false,
2361             ast::GenericArg::Type(_) => true,
2362             ast::GenericArg::Const(_) => true,
2363         });
2364         (
2365             hir::GenericArgs {
2366                 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2367                 bindings: constraints.iter()
2368                     .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2369                     .collect(),
2370                 parenthesized: false,
2371             },
2372             !has_non_lt_args && param_mode == ParamMode::Optional
2373         )
2374     }
2375
2376     fn lower_parenthesized_parameter_data(
2377         &mut self,
2378         data: &ParenthesizedArgs,
2379     ) -> (hir::GenericArgs, bool) {
2380         // Switch to `PassThrough` mode for anonymous lifetimes; this
2381         // means that we permit things like `&Ref<T>`, where `Ref` has
2382         // a hidden lifetime parameter. This is needed for backwards
2383         // compatibility, even in contexts like an impl header where
2384         // we generally don't permit such things (see #51008).
2385         self.with_anonymous_lifetime_mode(
2386             AnonymousLifetimeMode::PassThrough,
2387             |this| {
2388                 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2389                 let inputs = inputs
2390                     .iter()
2391                     .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2392                     .collect();
2393                 let mk_tup = |this: &mut Self, tys, span| {
2394                     hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2395                 };
2396                 (
2397                     hir::GenericArgs {
2398                         args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2399                         bindings: hir_vec![
2400                             hir::TypeBinding {
2401                                 hir_id: this.next_id(),
2402                                 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2403                                 kind: hir::TypeBindingKind::Equality {
2404                                     ty: output
2405                                         .as_ref()
2406                                         .map(|ty| this.lower_ty(
2407                                             &ty,
2408                                             ImplTraitContext::disallowed()
2409                                         ))
2410                                         .unwrap_or_else(||
2411                                             P(mk_tup(this, hir::HirVec::new(), span))
2412                                         ),
2413                                 },
2414                                 span: output.as_ref().map_or(span, |ty| ty.span),
2415                             }
2416                         ],
2417                         parenthesized: true,
2418                     },
2419                     false,
2420                 )
2421             }
2422         )
2423     }
2424
2425     fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2426         let mut ids = SmallVec::<[NodeId; 1]>::new();
2427         if self.sess.features_untracked().impl_trait_in_bindings {
2428             if let Some(ref ty) = l.ty {
2429                 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2430                 visitor.visit_ty(ty);
2431             }
2432         }
2433         let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2434         (hir::Local {
2435             hir_id: self.lower_node_id(l.id),
2436             ty: l.ty
2437                 .as_ref()
2438                 .map(|t| self.lower_ty(t,
2439                     if self.sess.features_untracked().impl_trait_in_bindings {
2440                         ImplTraitContext::Existential(Some(parent_def_id))
2441                     } else {
2442                         ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2443                     }
2444                 )),
2445             pat: self.lower_pat(&l.pat),
2446             init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2447             span: l.span,
2448             attrs: l.attrs.clone(),
2449             source: hir::LocalSource::Normal,
2450         }, ids)
2451     }
2452
2453     fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2454         match m {
2455             Mutability::Mutable => hir::MutMutable,
2456             Mutability::Immutable => hir::MutImmutable,
2457         }
2458     }
2459
2460     fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
2461         hir::Arg {
2462             hir_id: self.lower_node_id(arg.id),
2463             pat: self.lower_pat(&arg.pat),
2464         }
2465     }
2466
2467     fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2468         decl.inputs
2469             .iter()
2470             .map(|arg| match arg.pat.node {
2471                 PatKind::Ident(_, ident, _) => ident,
2472                 _ => Ident::new(kw::Invalid, arg.pat.span),
2473             })
2474             .collect()
2475     }
2476
2477     // Lowers a function declaration.
2478     //
2479     // `decl`: the unlowered (AST) function declaration.
2480     // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2481     //      given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2482     //      `make_ret_async` is also `Some`.
2483     // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2484     //      This guards against trait declarations and implementations where `impl Trait` is
2485     //      disallowed.
2486     // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2487     //      return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2488     //      return type `impl Trait` item.
2489     fn lower_fn_decl(
2490         &mut self,
2491         decl: &FnDecl,
2492         mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2493         impl_trait_return_allow: bool,
2494         make_ret_async: Option<NodeId>,
2495     ) -> P<hir::FnDecl> {
2496         let lt_mode = if make_ret_async.is_some() {
2497             // In `async fn`, argument-position elided lifetimes
2498             // must be transformed into fresh generic parameters so that
2499             // they can be applied to the existential return type.
2500             AnonymousLifetimeMode::CreateParameter
2501         } else {
2502             self.anonymous_lifetime_mode
2503         };
2504
2505         // Remember how many lifetimes were already around so that we can
2506         // only look at the lifetime parameters introduced by the arguments.
2507         let lifetime_count_before_args = self.lifetimes_to_define.len();
2508         let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2509             decl.inputs
2510                 .iter()
2511                 .map(|arg| {
2512                     if let Some((_, ibty)) = &mut in_band_ty_params {
2513                         this.lower_ty_direct(&arg.ty, ImplTraitContext::Universal(ibty))
2514                     } else {
2515                         this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed())
2516                     }
2517                 })
2518                 .collect::<HirVec<_>>()
2519         });
2520
2521         let output = if let Some(ret_id) = make_ret_async {
2522             // Calculate the `LtReplacement` to use for any return-position elided
2523             // lifetimes based on the elided lifetime parameters introduced in the args.
2524             let lt_replacement = get_elided_lt_replacement(
2525                 &self.lifetimes_to_define[lifetime_count_before_args..]
2526             );
2527             self.lower_async_fn_ret_ty(
2528                 &decl.output,
2529                 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2530                 ret_id,
2531                 lt_replacement,
2532             )
2533         } else {
2534             match decl.output {
2535                 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2536                     Some((def_id, _)) if impl_trait_return_allow => {
2537                         hir::Return(self.lower_ty(ty,
2538                             ImplTraitContext::Existential(Some(def_id))
2539                         ))
2540                     }
2541                     _ => {
2542                         hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2543                     }
2544                 },
2545                 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2546             }
2547         };
2548
2549         P(hir::FnDecl {
2550             inputs,
2551             output,
2552             c_variadic: decl.c_variadic,
2553             implicit_self: decl.inputs.get(0).map_or(
2554                 hir::ImplicitSelfKind::None,
2555                 |arg| {
2556                     let is_mutable_pat = match arg.pat.node {
2557                         PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2558                         PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2559                             mt == Mutability::Mutable,
2560                         _ => false,
2561                     };
2562
2563                     match arg.ty.node {
2564                         TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2565                         TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2566                         // Given we are only considering `ImplicitSelf` types, we needn't consider
2567                         // the case where we have a mutable pattern to a reference as that would
2568                         // no longer be an `ImplicitSelf`.
2569                         TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() &&
2570                             mt.mutbl == ast::Mutability::Mutable =>
2571                                 hir::ImplicitSelfKind::MutRef,
2572                         TyKind::Rptr(_, ref mt) if mt.ty.node.is_implicit_self() =>
2573                             hir::ImplicitSelfKind::ImmRef,
2574                         _ => hir::ImplicitSelfKind::None,
2575                     }
2576                 },
2577             ),
2578         })
2579     }
2580
2581     // Transforms `-> T` for `async fn` into `-> ExistTy { .. }`
2582     // combined with the following definition of `ExistTy`:
2583     //
2584     //     existential type ExistTy<generics_from_parent_fn>: Future<Output = T>;
2585     //
2586     // `inputs`: lowered types of arguments to the function (used to collect lifetimes)
2587     // `output`: unlowered output type (`T` in `-> T`)
2588     // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2589     // `exist_ty_node_id`: `NodeId` of the existential type that should be created
2590     // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2591     fn lower_async_fn_ret_ty(
2592         &mut self,
2593         output: &FunctionRetTy,
2594         fn_def_id: DefId,
2595         exist_ty_node_id: NodeId,
2596         elided_lt_replacement: LtReplacement,
2597     ) -> hir::FunctionRetTy {
2598         let span = output.span();
2599
2600         let exist_ty_span = self.mark_span_with_reason(
2601             CompilerDesugaringKind::Async,
2602             span,
2603             None,
2604         );
2605
2606         let exist_ty_def_index = self
2607             .resolver
2608             .definitions()
2609             .opt_def_index(exist_ty_node_id)
2610             .unwrap();
2611
2612         self.allocate_hir_id_counter(exist_ty_node_id);
2613
2614         let (exist_ty_id, lifetime_params) = self.with_hir_id_owner(exist_ty_node_id, |this| {
2615             let future_bound = this.with_anonymous_lifetime_mode(
2616                 AnonymousLifetimeMode::Replace(elided_lt_replacement),
2617                 |this| this.lower_async_fn_output_type_to_future_bound(
2618                     output,
2619                     fn_def_id,
2620                     span,
2621                 ),
2622             );
2623
2624             // Calculate all the lifetimes that should be captured
2625             // by the existential type. This should include all in-scope
2626             // lifetime parameters, including those defined in-band.
2627             //
2628             // Note: this must be done after lowering the output type,
2629             // as the output type may introduce new in-band lifetimes.
2630             let lifetime_params: Vec<(Span, ParamName)> =
2631                 this.in_scope_lifetimes
2632                     .iter().cloned()
2633                     .map(|ident| (ident.span, ParamName::Plain(ident)))
2634                     .chain(this.lifetimes_to_define.iter().cloned())
2635                     .collect();
2636
2637             let generic_params =
2638                 lifetime_params
2639                     .iter().cloned()
2640                     .map(|(span, hir_name)| {
2641                         this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index)
2642                     })
2643                     .collect();
2644
2645             let exist_ty_item = hir::ExistTy {
2646                 generics: hir::Generics {
2647                     params: generic_params,
2648                     where_clause: hir::WhereClause {
2649                         predicates: hir_vec![],
2650                         span,
2651                     },
2652                     span,
2653                 },
2654                 bounds: hir_vec![future_bound],
2655                 impl_trait_fn: Some(fn_def_id),
2656                 origin: hir::ExistTyOrigin::AsyncFn,
2657             };
2658
2659             trace!("exist ty from async fn def index: {:#?}", exist_ty_def_index);
2660             let exist_ty_id = this.generate_existential_type(
2661                 exist_ty_node_id,
2662                 exist_ty_item,
2663                 span,
2664                 exist_ty_span,
2665             );
2666
2667             (exist_ty_id, lifetime_params)
2668         });
2669
2670         let generic_args =
2671             lifetime_params
2672                 .iter().cloned()
2673                 .map(|(span, hir_name)| {
2674                     GenericArg::Lifetime(hir::Lifetime {
2675                         hir_id: self.next_id(),
2676                         span,
2677                         name: hir::LifetimeName::Param(hir_name),
2678                     })
2679                 })
2680                 .collect();
2681
2682         let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args);
2683
2684         hir::FunctionRetTy::Return(P(hir::Ty {
2685             node: exist_ty_ref,
2686             span,
2687             hir_id: self.next_id(),
2688         }))
2689     }
2690
2691     /// Transforms `-> T` into `Future<Output = T>`
2692     fn lower_async_fn_output_type_to_future_bound(
2693         &mut self,
2694         output: &FunctionRetTy,
2695         fn_def_id: DefId,
2696         span: Span,
2697     ) -> hir::GenericBound {
2698         // Compute the `T` in `Future<Output = T>` from the return type.
2699         let output_ty = match output {
2700             FunctionRetTy::Ty(ty) => {
2701                 self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id)))
2702             }
2703             FunctionRetTy::Default(ret_ty_span) => {
2704                 P(hir::Ty {
2705                     hir_id: self.next_id(),
2706                     node: hir::TyKind::Tup(hir_vec![]),
2707                     span: *ret_ty_span,
2708                 })
2709             }
2710         };
2711
2712         // "<Output = T>"
2713         let future_params = P(hir::GenericArgs {
2714             args: hir_vec![],
2715             bindings: hir_vec![hir::TypeBinding {
2716                 ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
2717                 kind: hir::TypeBindingKind::Equality {
2718                     ty: output_ty,
2719                 },
2720                 hir_id: self.next_id(),
2721                 span,
2722             }],
2723             parenthesized: false,
2724         });
2725
2726         // ::std::future::Future<future_params>
2727         let future_path =
2728             self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
2729
2730         hir::GenericBound::Trait(
2731             hir::PolyTraitRef {
2732                 trait_ref: hir::TraitRef {
2733                     path: future_path,
2734                     hir_ref_id: self.next_id(),
2735                 },
2736                 bound_generic_params: hir_vec![],
2737                 span,
2738             },
2739             hir::TraitBoundModifier::None,
2740         )
2741     }
2742
2743     fn lower_param_bound(
2744         &mut self,
2745         tpb: &GenericBound,
2746         itctx: ImplTraitContext<'_>,
2747     ) -> hir::GenericBound {
2748         match *tpb {
2749             GenericBound::Trait(ref ty, modifier) => {
2750                 hir::GenericBound::Trait(
2751                     self.lower_poly_trait_ref(ty, itctx),
2752                     self.lower_trait_bound_modifier(modifier),
2753                 )
2754             }
2755             GenericBound::Outlives(ref lifetime) => {
2756                 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2757             }
2758         }
2759     }
2760
2761     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2762         let span = l.ident.span;
2763         match l.ident {
2764             ident if ident.name == kw::StaticLifetime =>
2765                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2766             ident if ident.name == kw::UnderscoreLifetime =>
2767                 match self.anonymous_lifetime_mode {
2768                     AnonymousLifetimeMode::CreateParameter => {
2769                         let fresh_name = self.collect_fresh_in_band_lifetime(span);
2770                         self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2771                     }
2772
2773                     AnonymousLifetimeMode::PassThrough => {
2774                         self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2775                     }
2776
2777                     AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2778
2779                     AnonymousLifetimeMode::Replace(replacement) => {
2780                         let hir_id = self.lower_node_id(l.id);
2781                         self.replace_elided_lifetime(hir_id, span, replacement)
2782                     }
2783                 },
2784             ident => {
2785                 self.maybe_collect_in_band_lifetime(ident);
2786                 let param_name = ParamName::Plain(ident);
2787                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2788             }
2789         }
2790     }
2791
2792     fn new_named_lifetime(
2793         &mut self,
2794         id: NodeId,
2795         span: Span,
2796         name: hir::LifetimeName,
2797     ) -> hir::Lifetime {
2798         hir::Lifetime {
2799             hir_id: self.lower_node_id(id),
2800             span,
2801             name: name,
2802         }
2803     }
2804
2805     /// Replace a return-position elided lifetime with the elided lifetime
2806     /// from the arguments.
2807     fn replace_elided_lifetime(
2808         &mut self,
2809         hir_id: hir::HirId,
2810         span: Span,
2811         replacement: LtReplacement,
2812     ) -> hir::Lifetime {
2813         let multiple_or_none = match replacement {
2814             LtReplacement::Some(name) => {
2815                 return hir::Lifetime {
2816                     hir_id,
2817                     span,
2818                     name: hir::LifetimeName::Param(name),
2819                 };
2820             }
2821             LtReplacement::MultipleLifetimes => "multiple",
2822             LtReplacement::NoLifetimes => "none",
2823         };
2824
2825         let mut err = crate::middle::resolve_lifetime::report_missing_lifetime_specifiers(
2826             self.sess,
2827             span,
2828             1,
2829         );
2830         err.note(&format!(
2831             "return-position elided lifetimes require exactly one \
2832              input-position elided lifetime, found {}.", multiple_or_none));
2833         err.emit();
2834
2835         hir::Lifetime { hir_id, span, name: hir::LifetimeName::Error }
2836     }
2837
2838     fn lower_generic_params(
2839         &mut self,
2840         params: &[GenericParam],
2841         add_bounds: &NodeMap<Vec<GenericBound>>,
2842         mut itctx: ImplTraitContext<'_>,
2843     ) -> hir::HirVec<hir::GenericParam> {
2844         params.iter().map(|param| {
2845             self.lower_generic_param(param, add_bounds, itctx.reborrow())
2846         }).collect()
2847     }
2848
2849     fn lower_generic_param(&mut self,
2850                            param: &GenericParam,
2851                            add_bounds: &NodeMap<Vec<GenericBound>>,
2852                            mut itctx: ImplTraitContext<'_>)
2853                            -> hir::GenericParam {
2854         let mut bounds = self.with_anonymous_lifetime_mode(
2855             AnonymousLifetimeMode::ReportError,
2856             |this| this.lower_param_bounds(&param.bounds, itctx.reborrow()),
2857         );
2858
2859         let (name, kind) = match param.kind {
2860             GenericParamKind::Lifetime => {
2861                 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2862                 self.is_collecting_in_band_lifetimes = false;
2863
2864                 let lt = self.with_anonymous_lifetime_mode(
2865                     AnonymousLifetimeMode::ReportError,
2866                     |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2867                 );
2868                 let param_name = match lt.name {
2869                     hir::LifetimeName::Param(param_name) => param_name,
2870                     hir::LifetimeName::Implicit
2871                         | hir::LifetimeName::Underscore
2872                         | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2873                     hir::LifetimeName::Error => ParamName::Error,
2874                 };
2875
2876                 let kind = hir::GenericParamKind::Lifetime {
2877                     kind: hir::LifetimeParamKind::Explicit
2878                 };
2879
2880                 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2881
2882                 (param_name, kind)
2883             }
2884             GenericParamKind::Type { ref default, .. } => {
2885                 // Don't expose `Self` (recovered "keyword used as ident" parse error).
2886                 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
2887                 // Instead, use `gensym("Self")` to create a distinct name that looks the same.
2888                 let ident = if param.ident.name == kw::SelfUpper {
2889                     param.ident.gensym()
2890                 } else {
2891                     param.ident
2892                 };
2893
2894                 let add_bounds = add_bounds.get(&param.id).map_or(&[][..], |x| &x);
2895                 if !add_bounds.is_empty() {
2896                     let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2897                     bounds = bounds.into_iter()
2898                                    .chain(params)
2899                                    .collect();
2900                 }
2901
2902                 let kind = hir::GenericParamKind::Type {
2903                     default: default.as_ref().map(|x| {
2904                         self.lower_ty(x, ImplTraitContext::Existential(None))
2905                     }),
2906                     synthetic: param.attrs.iter()
2907                                           .filter(|attr| attr.check_name(sym::rustc_synthetic))
2908                                           .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2909                                           .next(),
2910                 };
2911
2912                 (hir::ParamName::Plain(ident), kind)
2913             }
2914             GenericParamKind::Const { ref ty } => {
2915                 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2916                     ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2917                 })
2918             }
2919         };
2920
2921         hir::GenericParam {
2922             hir_id: self.lower_node_id(param.id),
2923             name,
2924             span: param.ident.span,
2925             pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2926             attrs: self.lower_attrs(&param.attrs),
2927             bounds,
2928             kind,
2929         }
2930     }
2931
2932     fn lower_generics(
2933         &mut self,
2934         generics: &Generics,
2935         itctx: ImplTraitContext<'_>)
2936         -> hir::Generics
2937     {
2938         // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2939         // FIXME: this could probably be done with less rightward drift. It also looks like two
2940         // control paths where `report_error` is called are the only paths that advance to after the
2941         // match statement, so the error reporting could probably just be moved there.
2942         let mut add_bounds: NodeMap<Vec<_>> = Default::default();
2943         for pred in &generics.where_clause.predicates {
2944             if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2945                 'next_bound: for bound in &bound_pred.bounds {
2946                     if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
2947                         let report_error = |this: &mut Self| {
2948                             this.diagnostic().span_err(
2949                                 bound_pred.bounded_ty.span,
2950                                 "`?Trait` bounds are only permitted at the \
2951                                  point where a type parameter is declared",
2952                             );
2953                         };
2954                         // Check if the where clause type is a plain type parameter.
2955                         match bound_pred.bounded_ty.node {
2956                             TyKind::Path(None, ref path)
2957                                 if path.segments.len() == 1
2958                                     && bound_pred.bound_generic_params.is_empty() =>
2959                             {
2960                                 if let Some(Res::Def(DefKind::TyParam, def_id)) = self.resolver
2961                                     .get_partial_res(bound_pred.bounded_ty.id)
2962                                     .map(|d| d.base_res())
2963                                 {
2964                                     if let Some(node_id) =
2965                                         self.resolver.definitions().as_local_node_id(def_id)
2966                                     {
2967                                         for param in &generics.params {
2968                                             match param.kind {
2969                                                 GenericParamKind::Type { .. } => {
2970                                                     if node_id == param.id {
2971                                                         add_bounds.entry(param.id)
2972                                                             .or_default()
2973                                                             .push(bound.clone());
2974                                                         continue 'next_bound;
2975                                                     }
2976                                                 }
2977                                                 _ => {}
2978                                             }
2979                                         }
2980                                     }
2981                                 }
2982                                 report_error(self)
2983                             }
2984                             _ => report_error(self),
2985                         }
2986                     }
2987                 }
2988             }
2989         }
2990
2991         hir::Generics {
2992             params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2993             where_clause: self.lower_where_clause(&generics.where_clause),
2994             span: generics.span,
2995         }
2996     }
2997
2998     fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2999         self.with_anonymous_lifetime_mode(
3000             AnonymousLifetimeMode::ReportError,
3001             |this| {
3002                 hir::WhereClause {
3003                     predicates: wc.predicates
3004                         .iter()
3005                         .map(|predicate| this.lower_where_predicate(predicate))
3006                         .collect(),
3007                     span: wc.span,
3008                 }
3009             },
3010         )
3011     }
3012
3013     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
3014         match *pred {
3015             WherePredicate::BoundPredicate(WhereBoundPredicate {
3016                 ref bound_generic_params,
3017                 ref bounded_ty,
3018                 ref bounds,
3019                 span,
3020             }) => {
3021                 self.with_in_scope_lifetime_defs(
3022                     &bound_generic_params,
3023                     |this| {
3024                         hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
3025                             bound_generic_params: this.lower_generic_params(
3026                                 bound_generic_params,
3027                                 &NodeMap::default(),
3028                                 ImplTraitContext::disallowed(),
3029                             ),
3030                             bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()),
3031                             bounds: bounds
3032                                 .iter()
3033                                 .filter_map(|bound| match *bound {
3034                                     // Ignore `?Trait` bounds.
3035                                     // They were copied into type parameters already.
3036                                     GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
3037                                     _ => Some(this.lower_param_bound(
3038                                         bound,
3039                                         ImplTraitContext::disallowed(),
3040                                     )),
3041                                 })
3042                                 .collect(),
3043                             span,
3044                         })
3045                     },
3046                 )
3047             }
3048             WherePredicate::RegionPredicate(WhereRegionPredicate {
3049                 ref lifetime,
3050                 ref bounds,
3051                 span,
3052             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
3053                 span,
3054                 lifetime: self.lower_lifetime(lifetime),
3055                 bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3056             }),
3057             WherePredicate::EqPredicate(WhereEqPredicate {
3058                 id,
3059                 ref lhs_ty,
3060                 ref rhs_ty,
3061                 span,
3062             }) => {
3063                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
3064                     hir_id: self.lower_node_id(id),
3065                     lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()),
3066                     rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()),
3067                     span,
3068                 })
3069             },
3070         }
3071     }
3072
3073     fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
3074         match *vdata {
3075             VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
3076                 fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(),
3077                 recovered,
3078             ),
3079             VariantData::Tuple(ref fields, id) => {
3080                 hir::VariantData::Tuple(
3081                     fields
3082                         .iter()
3083                         .enumerate()
3084                         .map(|f| self.lower_struct_field(f))
3085                         .collect(),
3086                     self.lower_node_id(id),
3087                 )
3088             },
3089             VariantData::Unit(id) => {
3090                 hir::VariantData::Unit(self.lower_node_id(id))
3091             },
3092         }
3093     }
3094
3095     fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
3096         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
3097             hir::QPath::Resolved(None, path) => path.and_then(|path| path),
3098             qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
3099         };
3100         hir::TraitRef {
3101             path,
3102             hir_ref_id: self.lower_node_id(p.ref_id),
3103         }
3104     }
3105
3106     fn lower_poly_trait_ref(
3107         &mut self,
3108         p: &PolyTraitRef,
3109         mut itctx: ImplTraitContext<'_>,
3110     ) -> hir::PolyTraitRef {
3111         let bound_generic_params = self.lower_generic_params(
3112             &p.bound_generic_params,
3113             &NodeMap::default(),
3114             itctx.reborrow(),
3115         );
3116         let trait_ref = self.with_in_scope_lifetime_defs(
3117             &p.bound_generic_params,
3118             |this| this.lower_trait_ref(&p.trait_ref, itctx),
3119         );
3120
3121         hir::PolyTraitRef {
3122             bound_generic_params,
3123             trait_ref,
3124             span: p.span,
3125         }
3126     }
3127
3128     fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
3129         let ty = if let TyKind::Path(ref qself, ref path) = f.ty.node {
3130             let t = self.lower_path_ty(
3131                 &f.ty,
3132                 qself,
3133                 path,
3134                 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
3135                 ImplTraitContext::disallowed()
3136             );
3137             P(t)
3138         } else {
3139             self.lower_ty(&f.ty, ImplTraitContext::disallowed())
3140         };
3141         hir::StructField {
3142             span: f.span,
3143             hir_id: self.lower_node_id(f.id),
3144             ident: match f.ident {
3145                 Some(ident) => ident,
3146                 // FIXME(jseyfried): positional field hygiene.
3147                 None => Ident::new(sym::integer(index), f.span),
3148             },
3149             vis: self.lower_visibility(&f.vis, None),
3150             ty,
3151             attrs: self.lower_attrs(&f.attrs),
3152         }
3153     }
3154
3155     fn lower_field(&mut self, f: &Field) -> hir::Field {
3156         hir::Field {
3157             hir_id: self.next_id(),
3158             ident: f.ident,
3159             expr: P(self.lower_expr(&f.expr)),
3160             span: f.span,
3161             is_shorthand: f.is_shorthand,
3162         }
3163     }
3164
3165     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
3166         hir::MutTy {
3167             ty: self.lower_ty(&mt.ty, itctx),
3168             mutbl: self.lower_mutability(mt.mutbl),
3169         }
3170     }
3171
3172     fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
3173                           -> hir::GenericBounds {
3174         bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
3175     }
3176
3177     fn lower_block_with_stmts(
3178         &mut self,
3179         b: &Block,
3180         targeted_by_break: bool,
3181         mut stmts: Vec<hir::Stmt>,
3182     ) -> P<hir::Block> {
3183         let mut expr = None;
3184
3185         for (index, stmt) in b.stmts.iter().enumerate() {
3186             if index == b.stmts.len() - 1 {
3187                 if let StmtKind::Expr(ref e) = stmt.node {
3188                     expr = Some(P(self.lower_expr(e)));
3189                 } else {
3190                     stmts.extend(self.lower_stmt(stmt));
3191                 }
3192             } else {
3193                 stmts.extend(self.lower_stmt(stmt));
3194             }
3195         }
3196
3197         P(hir::Block {
3198             hir_id: self.lower_node_id(b.id),
3199             stmts: stmts.into(),
3200             expr,
3201             rules: self.lower_block_check_mode(&b.rules),
3202             span: b.span,
3203             targeted_by_break,
3204         })
3205     }
3206
3207     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
3208         self.lower_block_with_stmts(b, targeted_by_break, vec![])
3209     }
3210
3211     fn lower_maybe_async_body(
3212         &mut self,
3213         decl: &FnDecl,
3214         asyncness: IsAsync,
3215         body: &Block,
3216     ) -> hir::BodyId {
3217         let closure_id = match asyncness {
3218             IsAsync::Async { closure_id, .. } => closure_id,
3219             IsAsync::NotAsync => return self.lower_fn_body(&decl, |this| {
3220                 let body = this.lower_block(body, false);
3221                 this.expr_block(body, ThinVec::new())
3222             }),
3223         };
3224
3225         self.lower_body(|this| {
3226             let mut arguments: Vec<hir::Arg> = Vec::new();
3227             let mut statements: Vec<hir::Stmt> = Vec::new();
3228
3229             // Async function arguments are lowered into the closure body so that they are
3230             // captured and so that the drop order matches the equivalent non-async functions.
3231             //
3232             // from:
3233             //
3234             //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
3235             //       async move {
3236             //       }
3237             //     }
3238             //
3239             // into:
3240             //
3241             //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
3242             //       async move {
3243             //         let __arg2 = __arg2;
3244             //         let <pattern> = __arg2;
3245             //         let __arg1 = __arg1;
3246             //         let <pattern> = __arg1;
3247             //         let __arg0 = __arg0;
3248             //         let <pattern> = __arg0;
3249             //       }
3250             //     }
3251             //
3252             // If `<pattern>` is a simple ident, then it is lowered to a single
3253             // `let <pattern> = <pattern>;` statement as an optimization.
3254             for (index, argument) in decl.inputs.iter().enumerate() {
3255                 let argument = this.lower_arg(argument);
3256                 let span = argument.pat.span;
3257
3258                 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
3259                 // `let <pat> = __argN;` statement. In this case, we do not rename the argument.
3260                 let (ident, is_simple_argument) = match argument.pat.node {
3261                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _) =>
3262                         (ident, true),
3263                     _ => {
3264                         // Replace the ident for bindings that aren't simple.
3265                         let name = format!("__arg{}", index);
3266                         let ident = Ident::from_str(&name);
3267
3268                         (ident, false)
3269                     },
3270                 };
3271
3272                 let desugared_span =
3273                     this.mark_span_with_reason(CompilerDesugaringKind::Async, span, None);
3274
3275                 // Construct an argument representing `__argN: <ty>` to replace the argument of the
3276                 // async function.
3277                 //
3278                 // If this is the simple case, this argument will end up being the same as the
3279                 // original argument, but with a different pattern id.
3280                 let (new_argument_pat, new_argument_id) = this.pat_ident(desugared_span, ident);
3281                 let new_argument = hir::Arg {
3282                     hir_id: argument.hir_id,
3283                     pat: new_argument_pat,
3284                 };
3285
3286                 if is_simple_argument {
3287                     // If this is the simple case, then we only insert one statement that is
3288                     // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
3289                     // `HirId`s are densely assigned.
3290                     let expr = this.expr_ident(desugared_span, ident, new_argument_id);
3291                     let stmt = this.stmt_let_pat(
3292                         desugared_span, Some(P(expr)), argument.pat, hir::LocalSource::AsyncFn);
3293                     statements.push(stmt);
3294                 } else {
3295                     // If this is not the simple case, then we construct two statements:
3296                     //
3297                     // ```
3298                     // let __argN = __argN;
3299                     // let <pat> = __argN;
3300                     // ```
3301                     //
3302                     // The first statement moves the argument into the closure and thus ensures
3303                     // that the drop order is correct.
3304                     //
3305                     // The second statement creates the bindings that the user wrote.
3306
3307                     // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
3308                     // because the user may have specified a `ref mut` binding in the next
3309                     // statement.
3310                     let (move_pat, move_id) = this.pat_ident_binding_mode(
3311                         desugared_span, ident, hir::BindingAnnotation::Mutable);
3312                     let move_expr = this.expr_ident(desugared_span, ident, new_argument_id);
3313                     let move_stmt = this.stmt_let_pat(
3314                         desugared_span, Some(P(move_expr)), move_pat, hir::LocalSource::AsyncFn);
3315
3316                     // Construct the `let <pat> = __argN;` statement. We re-use the original
3317                     // argument's pattern so that `HirId`s are densely assigned.
3318                     let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
3319                     let pattern_stmt = this.stmt_let_pat(
3320                         desugared_span, Some(P(pattern_expr)), argument.pat,
3321                         hir::LocalSource::AsyncFn);
3322
3323                     statements.push(move_stmt);
3324                     statements.push(pattern_stmt);
3325                 };
3326
3327                 arguments.push(new_argument);
3328             }
3329
3330             let async_expr = this.make_async_expr(
3331                 CaptureBy::Value, closure_id, None, body.span,
3332                 |this| {
3333                     let body = this.lower_block_with_stmts(body, false, statements);
3334                     this.expr_block(body, ThinVec::new())
3335                 });
3336             (HirVec::from(arguments), this.expr(body.span, async_expr, ThinVec::new()))
3337         })
3338     }
3339
3340     fn lower_item_kind(
3341         &mut self,
3342         id: NodeId,
3343         ident: &mut Ident,
3344         attrs: &hir::HirVec<Attribute>,
3345         vis: &mut hir::Visibility,
3346         i: &ItemKind,
3347     ) -> hir::ItemKind {
3348         match *i {
3349             ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
3350             ItemKind::Use(ref use_tree) => {
3351                 // Start with an empty prefix.
3352                 let prefix = Path {
3353                     segments: vec![],
3354                     span: use_tree.span,
3355                 };
3356
3357                 self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs)
3358             }
3359             ItemKind::Static(ref t, m, ref e) => {
3360                 hir::ItemKind::Static(
3361                     self.lower_ty(
3362                         t,
3363                         if self.sess.features_untracked().impl_trait_in_bindings {
3364                             ImplTraitContext::Existential(None)
3365                         } else {
3366                             ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3367                         }
3368                     ),
3369                     self.lower_mutability(m),
3370                     self.lower_const_body(e),
3371                 )
3372             }
3373             ItemKind::Const(ref t, ref e) => {
3374                 hir::ItemKind::Const(
3375                     self.lower_ty(
3376                         t,
3377                         if self.sess.features_untracked().impl_trait_in_bindings {
3378                             ImplTraitContext::Existential(None)
3379                         } else {
3380                             ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
3381                         }
3382                     ),
3383                     self.lower_const_body(e)
3384                 )
3385             }
3386             ItemKind::Fn(ref decl, header, ref generics, ref body) => {
3387                 let fn_def_id = self.resolver.definitions().local_def_id(id);
3388                 self.with_new_scopes(|this| {
3389                     this.current_item = Some(ident.span);
3390
3391                     // Note: we don't need to change the return type from `T` to
3392                     // `impl Future<Output = T>` here because lower_body
3393                     // only cares about the input argument patterns in the function
3394                     // declaration (decl), not the return types.
3395                     let body_id = this.lower_maybe_async_body(&decl, header.asyncness.node, body);
3396
3397                     let (generics, fn_decl) = this.add_in_band_defs(
3398                         generics,
3399                         fn_def_id,
3400                         AnonymousLifetimeMode::PassThrough,
3401                         |this, idty| this.lower_fn_decl(
3402                             &decl,
3403                             Some((fn_def_id, idty)),
3404                             true,
3405                             header.asyncness.node.opt_return_id()
3406                         ),
3407                     );
3408
3409                     hir::ItemKind::Fn(
3410                         fn_decl,
3411                         this.lower_fn_header(header),
3412                         generics,
3413                         body_id,
3414                     )
3415                 })
3416             }
3417             ItemKind::Mod(ref m) => hir::ItemKind::Mod(self.lower_mod(m)),
3418             ItemKind::ForeignMod(ref nm) => hir::ItemKind::ForeignMod(self.lower_foreign_mod(nm)),
3419             ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)),
3420             ItemKind::Ty(ref t, ref generics) => hir::ItemKind::Ty(
3421                 self.lower_ty(t, ImplTraitContext::disallowed()),
3422                 self.lower_generics(generics, ImplTraitContext::disallowed()),
3423             ),
3424             ItemKind::Existential(ref b, ref generics) => hir::ItemKind::Existential(
3425                 hir::ExistTy {
3426                     generics: self.lower_generics(generics,
3427                         ImplTraitContext::Existential(None)),
3428                     bounds: self.lower_param_bounds(b,
3429                         ImplTraitContext::Existential(None)),
3430                     impl_trait_fn: None,
3431                     origin: hir::ExistTyOrigin::ExistentialType,
3432                 },
3433             ),
3434             ItemKind::Enum(ref enum_definition, ref generics) => {
3435                 hir::ItemKind::Enum(
3436                     hir::EnumDef {
3437                         variants: enum_definition
3438                             .variants
3439                             .iter()
3440                             .map(|x| self.lower_variant(x))
3441                             .collect(),
3442                     },
3443                     self.lower_generics(generics, ImplTraitContext::disallowed()),
3444                 )
3445             },
3446             ItemKind::Struct(ref struct_def, ref generics) => {
3447                 let struct_def = self.lower_variant_data(struct_def);
3448                 hir::ItemKind::Struct(
3449                     struct_def,
3450                     self.lower_generics(generics, ImplTraitContext::disallowed()),
3451                 )
3452             }
3453             ItemKind::Union(ref vdata, ref generics) => {
3454                 let vdata = self.lower_variant_data(vdata);
3455                 hir::ItemKind::Union(
3456                     vdata,
3457                     self.lower_generics(generics, ImplTraitContext::disallowed()),
3458                 )
3459             }
3460             ItemKind::Impl(
3461                 unsafety,
3462                 polarity,
3463                 defaultness,
3464                 ref ast_generics,
3465                 ref trait_ref,
3466                 ref ty,
3467                 ref impl_items,
3468             ) => {
3469                 let def_id = self.resolver.definitions().local_def_id(id);
3470
3471                 // Lower the "impl header" first. This ordering is important
3472                 // for in-band lifetimes! Consider `'a` here:
3473                 //
3474                 //     impl Foo<'a> for u32 {
3475                 //         fn method(&'a self) { .. }
3476                 //     }
3477                 //
3478                 // Because we start by lowering the `Foo<'a> for u32`
3479                 // part, we will add `'a` to the list of generics on
3480                 // the impl. When we then encounter it later in the
3481                 // method, it will not be considered an in-band
3482                 // lifetime to be added, but rather a reference to a
3483                 // parent lifetime.
3484                 let lowered_trait_impl_id = self.lower_node_id(id);
3485                 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
3486                     ast_generics,
3487                     def_id,
3488                     AnonymousLifetimeMode::CreateParameter,
3489                     |this, _| {
3490                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
3491                             this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
3492                         });
3493
3494                         if let Some(ref trait_ref) = trait_ref {
3495                             if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
3496                                 this.trait_impls.entry(def_id).or_default().push(
3497                                     lowered_trait_impl_id);
3498                             }
3499                         }
3500
3501                         let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
3502
3503                         (trait_ref, lowered_ty)
3504                     },
3505                 );
3506
3507                 let new_impl_items = self.with_in_scope_lifetime_defs(
3508                     &ast_generics.params,
3509                     |this| {
3510                         impl_items
3511                             .iter()
3512                             .map(|item| this.lower_impl_item_ref(item))
3513                             .collect()
3514                     },
3515                 );
3516
3517                 hir::ItemKind::Impl(
3518                     self.lower_unsafety(unsafety),
3519                     self.lower_impl_polarity(polarity),
3520                     self.lower_defaultness(defaultness, true /* [1] */),
3521                     generics,
3522                     trait_ref,
3523                     lowered_ty,
3524                     new_impl_items,
3525                 )
3526             }
3527             ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
3528                 let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
3529                 let items = items
3530                     .iter()
3531                     .map(|item| self.lower_trait_item_ref(item))
3532                     .collect();
3533                 hir::ItemKind::Trait(
3534                     self.lower_is_auto(is_auto),
3535                     self.lower_unsafety(unsafety),
3536                     self.lower_generics(generics, ImplTraitContext::disallowed()),
3537                     bounds,
3538                     items,
3539                 )
3540             }
3541             ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias(
3542                 self.lower_generics(generics, ImplTraitContext::disallowed()),
3543                 self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3544             ),
3545             ItemKind::MacroDef(..)
3546             | ItemKind::Mac(..) => bug!("`TyMac` should have been expanded by now"),
3547         }
3548
3549         // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
3550         //     not cause an assertion failure inside the `lower_defaultness` function.
3551     }
3552
3553     fn lower_use_tree(
3554         &mut self,
3555         tree: &UseTree,
3556         prefix: &Path,
3557         id: NodeId,
3558         vis: &mut hir::Visibility,
3559         ident: &mut Ident,
3560         attrs: &hir::HirVec<Attribute>,
3561     ) -> hir::ItemKind {
3562         debug!("lower_use_tree(tree={:?})", tree);
3563         debug!("lower_use_tree: vis = {:?}", vis);
3564
3565         let path = &tree.prefix;
3566         let segments = prefix
3567             .segments
3568             .iter()
3569             .chain(path.segments.iter())
3570             .cloned()
3571             .collect();
3572
3573         match tree.kind {
3574             UseTreeKind::Simple(rename, id1, id2) => {
3575                 *ident = tree.ident();
3576
3577                 // First, apply the prefix to the path.
3578                 let mut path = Path {
3579                     segments,
3580                     span: path.span,
3581                 };
3582
3583                 // Correctly resolve `self` imports.
3584                 if path.segments.len() > 1
3585                     && path.segments.last().unwrap().ident.name == kw::SelfLower
3586                 {
3587                     let _ = path.segments.pop();
3588                     if rename.is_none() {
3589                         *ident = path.segments.last().unwrap().ident;
3590                     }
3591                 }
3592
3593                 let mut resolutions = self.expect_full_res_from_use(id);
3594                 // We want to return *something* from this function, so hold onto the first item
3595                 // for later.
3596                 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
3597
3598                 // Here, we are looping over namespaces, if they exist for the definition
3599                 // being imported. We only handle type and value namespaces because we
3600                 // won't be dealing with macros in the rest of the compiler.
3601                 // Essentially a single `use` which imports two names is desugared into
3602                 // two imports.
3603                 for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
3604                     let ident = *ident;
3605                     let mut path = path.clone();
3606                     for seg in &mut path.segments {
3607                         seg.id = self.sess.next_node_id();
3608                     }
3609                     let span = path.span;
3610
3611                     self.with_hir_id_owner(new_node_id, |this| {
3612                         let new_id = this.lower_node_id(new_node_id);
3613                         let res = this.lower_res(res);
3614                         let path =
3615                             this.lower_path_extra(res, &path, ParamMode::Explicit, None);
3616                         let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
3617                         let vis = this.rebuild_vis(&vis);
3618
3619                         this.insert_item(
3620                             hir::Item {
3621                                 hir_id: new_id,
3622                                 ident,
3623                                 attrs: attrs.clone(),
3624                                 node: item,
3625                                 vis,
3626                                 span,
3627                             },
3628                         );
3629                     });
3630                 }
3631
3632                 let path =
3633                     P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None));
3634                 hir::ItemKind::Use(path, hir::UseKind::Single)
3635             }
3636             UseTreeKind::Glob => {
3637                 let path = P(self.lower_path(
3638                     id,
3639                     &Path {
3640                         segments,
3641                         span: path.span,
3642                     },
3643                     ParamMode::Explicit,
3644                 ));
3645                 hir::ItemKind::Use(path, hir::UseKind::Glob)
3646             }
3647             UseTreeKind::Nested(ref trees) => {
3648                 // Nested imports are desugared into simple imports.
3649                 // So, if we start with
3650                 //
3651                 // ```
3652                 // pub(x) use foo::{a, b};
3653                 // ```
3654                 //
3655                 // we will create three items:
3656                 //
3657                 // ```
3658                 // pub(x) use foo::a;
3659                 // pub(x) use foo::b;
3660                 // pub(x) use foo::{}; // <-- this is called the `ListStem`
3661                 // ```
3662                 //
3663                 // The first two are produced by recursively invoking
3664                 // `lower_use_tree` (and indeed there may be things
3665                 // like `use foo::{a::{b, c}}` and so forth).  They
3666                 // wind up being directly added to
3667                 // `self.items`. However, the structure of this
3668                 // function also requires us to return one item, and
3669                 // for that we return the `{}` import (called the
3670                 // `ListStem`).
3671
3672                 let prefix = Path {
3673                     segments,
3674                     span: prefix.span.to(path.span),
3675                 };
3676
3677                 // Add all the nested `PathListItem`s to the HIR.
3678                 for &(ref use_tree, id) in trees {
3679                     let new_hir_id = self.lower_node_id(id);
3680
3681                     let mut prefix = prefix.clone();
3682
3683                     // Give the segments new node-ids since they are being cloned.
3684                     for seg in &mut prefix.segments {
3685                         seg.id = self.sess.next_node_id();
3686                     }
3687
3688                     // Each `use` import is an item and thus are owners of the
3689                     // names in the path. Up to this point the nested import is
3690                     // the current owner, since we want each desugared import to
3691                     // own its own names, we have to adjust the owner before
3692                     // lowering the rest of the import.
3693                     self.with_hir_id_owner(id, |this| {
3694                         let mut vis = this.rebuild_vis(&vis);
3695                         let mut ident = *ident;
3696
3697                         let item = this.lower_use_tree(use_tree,
3698                                                        &prefix,
3699                                                        id,
3700                                                        &mut vis,
3701                                                        &mut ident,
3702                                                        attrs);
3703
3704                         this.insert_item(
3705                             hir::Item {
3706                                 hir_id: new_hir_id,
3707                                 ident,
3708                                 attrs: attrs.clone(),
3709                                 node: item,
3710                                 vis,
3711                                 span: use_tree.span,
3712                             },
3713                         );
3714                     });
3715                 }
3716
3717                 // Subtle and a bit hacky: we lower the privacy level
3718                 // of the list stem to "private" most of the time, but
3719                 // not for "restricted" paths. The key thing is that
3720                 // we don't want it to stay as `pub` (with no caveats)
3721                 // because that affects rustdoc and also the lints
3722                 // about `pub` items. But we can't *always* make it
3723                 // private -- particularly not for restricted paths --
3724                 // because it contains node-ids that would then be
3725                 // unused, failing the check that HirIds are "densely
3726                 // assigned".
3727                 match vis.node {
3728                     hir::VisibilityKind::Public |
3729                     hir::VisibilityKind::Crate(_) |
3730                     hir::VisibilityKind::Inherited => {
3731                         *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited);
3732                     }
3733                     hir::VisibilityKind::Restricted { .. } => {
3734                         // Do nothing here, as described in the comment on the match.
3735                     }
3736                 }
3737
3738                 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
3739                 let res = self.lower_res(res);
3740                 let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None));
3741                 hir::ItemKind::Use(path, hir::UseKind::ListStem)
3742             }
3743         }
3744     }
3745
3746     /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
3747     /// many times in the HIR tree; for each occurrence, we need to assign distinct
3748     /// `NodeId`s. (See, e.g., #56128.)
3749     fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path {
3750         debug!("rebuild_use_path(path = {:?})", path);
3751         let segments = path.segments.iter().map(|seg| hir::PathSegment {
3752             ident: seg.ident,
3753             hir_id: seg.hir_id.map(|_| self.next_id()),
3754             res: seg.res,
3755             args: None,
3756             infer_args: seg.infer_args,
3757         }).collect();
3758         hir::Path {
3759             span: path.span,
3760             res: path.res,
3761             segments,
3762         }
3763     }
3764
3765     fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility {
3766         let vis_kind = match vis.node {
3767             hir::VisibilityKind::Public => hir::VisibilityKind::Public,
3768             hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
3769             hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
3770             hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
3771                 hir::VisibilityKind::Restricted {
3772                     path: P(self.rebuild_use_path(path)),
3773                     hir_id: self.next_id(),
3774                 }
3775             }
3776         };
3777         respan(vis.span, vis_kind)
3778     }
3779
3780     fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
3781         let trait_item_def_id = self.resolver.definitions().local_def_id(i.id);
3782
3783         let (generics, node) = match i.node {
3784             TraitItemKind::Const(ref ty, ref default) => (
3785                 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3786                 hir::TraitItemKind::Const(
3787                     self.lower_ty(ty, ImplTraitContext::disallowed()),
3788                     default
3789                         .as_ref()
3790                         .map(|x| self.lower_const_body(x)),
3791                 ),
3792             ),
3793             TraitItemKind::Method(ref sig, None) => {
3794                 let names = self.lower_fn_args_to_names(&sig.decl);
3795                 let (generics, sig) = self.lower_method_sig(
3796                     &i.generics,
3797                     sig,
3798                     trait_item_def_id,
3799                     false,
3800                     None,
3801                 );
3802                 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Required(names)))
3803             }
3804             TraitItemKind::Method(ref sig, Some(ref body)) => {
3805                 let body_id = self.lower_fn_body(&sig.decl, |this| {
3806                     let body = this.lower_block(body, false);
3807                     this.expr_block(body, ThinVec::new())
3808                 });
3809                 let (generics, sig) = self.lower_method_sig(
3810                     &i.generics,
3811                     sig,
3812                     trait_item_def_id,
3813                     false,
3814                     None,
3815                 );
3816                 (generics, hir::TraitItemKind::Method(sig, hir::TraitMethod::Provided(body_id)))
3817             }
3818             TraitItemKind::Type(ref bounds, ref default) => {
3819                 let generics = self.lower_generics(&i.generics, ImplTraitContext::disallowed());
3820                 let node = hir::TraitItemKind::Type(
3821                     self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3822                     default
3823                         .as_ref()
3824                         .map(|x| self.lower_ty(x, ImplTraitContext::disallowed())),
3825                 );
3826
3827                 (generics, node)
3828             },
3829             TraitItemKind::Macro(..) => bug!("macro item shouldn't exist at this point"),
3830         };
3831
3832         hir::TraitItem {
3833             hir_id: self.lower_node_id(i.id),
3834             ident: i.ident,
3835             attrs: self.lower_attrs(&i.attrs),
3836             generics,
3837             node,
3838             span: i.span,
3839         }
3840     }
3841
3842     fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
3843         let (kind, has_default) = match i.node {
3844             TraitItemKind::Const(_, ref default) => {
3845                 (hir::AssocItemKind::Const, default.is_some())
3846             }
3847             TraitItemKind::Type(_, ref default) => {
3848                 (hir::AssocItemKind::Type, default.is_some())
3849             }
3850             TraitItemKind::Method(ref sig, ref default) => (
3851                 hir::AssocItemKind::Method {
3852                     has_self: sig.decl.has_self(),
3853                 },
3854                 default.is_some(),
3855             ),
3856             TraitItemKind::Macro(..) => unimplemented!(),
3857         };
3858         hir::TraitItemRef {
3859             id: hir::TraitItemId { hir_id: self.lower_node_id(i.id) },
3860             ident: i.ident,
3861             span: i.span,
3862             defaultness: self.lower_defaultness(Defaultness::Default, has_default),
3863             kind,
3864         }
3865     }
3866
3867     fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
3868         let impl_item_def_id = self.resolver.definitions().local_def_id(i.id);
3869
3870         let (generics, node) = match i.node {
3871             ImplItemKind::Const(ref ty, ref expr) => (
3872                 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3873                 hir::ImplItemKind::Const(
3874                     self.lower_ty(ty, ImplTraitContext::disallowed()),
3875                     self.lower_const_body(expr),
3876                 ),
3877             ),
3878             ImplItemKind::Method(ref sig, ref body) => {
3879                 self.current_item = Some(i.span);
3880                 let body_id = self.lower_maybe_async_body(
3881                     &sig.decl, sig.header.asyncness.node, body
3882                 );
3883                 let impl_trait_return_allow = !self.is_in_trait_impl;
3884                 let (generics, sig) = self.lower_method_sig(
3885                     &i.generics,
3886                     sig,
3887                     impl_item_def_id,
3888                     impl_trait_return_allow,
3889                     sig.header.asyncness.node.opt_return_id(),
3890                 );
3891
3892                 (generics, hir::ImplItemKind::Method(sig, body_id))
3893             }
3894             ImplItemKind::Type(ref ty) => (
3895                 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3896                 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::disallowed())),
3897             ),
3898             ImplItemKind::Existential(ref bounds) => (
3899                 self.lower_generics(&i.generics, ImplTraitContext::disallowed()),
3900                 hir::ImplItemKind::Existential(
3901                     self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
3902                 ),
3903             ),
3904             ImplItemKind::Macro(..) => bug!("`TyMac` should have been expanded by now"),
3905         };
3906
3907         hir::ImplItem {
3908             hir_id: self.lower_node_id(i.id),
3909             ident: i.ident,
3910             attrs: self.lower_attrs(&i.attrs),
3911             generics,
3912             vis: self.lower_visibility(&i.vis, None),
3913             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3914             node,
3915             span: i.span,
3916         }
3917
3918         // [1] since `default impl` is not yet implemented, this is always true in impls
3919     }
3920
3921     fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
3922         hir::ImplItemRef {
3923             id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) },
3924             ident: i.ident,
3925             span: i.span,
3926             vis: self.lower_visibility(&i.vis, Some(i.id)),
3927             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
3928             kind: match i.node {
3929                 ImplItemKind::Const(..) => hir::AssocItemKind::Const,
3930                 ImplItemKind::Type(..) => hir::AssocItemKind::Type,
3931                 ImplItemKind::Existential(..) => hir::AssocItemKind::Existential,
3932                 ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method {
3933                     has_self: sig.decl.has_self(),
3934                 },
3935                 ImplItemKind::Macro(..) => unimplemented!(),
3936             },
3937         }
3938
3939         // [1] since `default impl` is not yet implemented, this is always true in impls
3940     }
3941
3942     fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
3943         hir::Mod {
3944             inner: m.inner,
3945             item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
3946         }
3947     }
3948
3949     fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
3950         let node_ids = match i.node {
3951             ItemKind::Use(ref use_tree) => {
3952                 let mut vec = smallvec![i.id];
3953                 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
3954                 vec
3955             }
3956             ItemKind::MacroDef(..) => SmallVec::new(),
3957             ItemKind::Fn(..) |
3958             ItemKind::Impl(.., None, _, _) => smallvec![i.id],
3959             ItemKind::Static(ref ty, ..) => {
3960                 let mut ids = smallvec![i.id];
3961                 if self.sess.features_untracked().impl_trait_in_bindings {
3962                     let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3963                     visitor.visit_ty(ty);
3964                 }
3965                 ids
3966             },
3967             ItemKind::Const(ref ty, ..) => {
3968                 let mut ids = smallvec![i.id];
3969                 if self.sess.features_untracked().impl_trait_in_bindings {
3970                     let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
3971                     visitor.visit_ty(ty);
3972                 }
3973                 ids
3974             },
3975             _ => smallvec![i.id],
3976         };
3977
3978         node_ids.into_iter().map(|node_id| hir::ItemId {
3979             id: self.allocate_hir_id_counter(node_id)
3980         }).collect()
3981     }
3982
3983     fn lower_item_id_use_tree(&mut self,
3984                               tree: &UseTree,
3985                               base_id: NodeId,
3986                               vec: &mut SmallVec<[NodeId; 1]>)
3987     {
3988         match tree.kind {
3989             UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
3990                 vec.push(id);
3991                 self.lower_item_id_use_tree(nested, id, vec);
3992             },
3993             UseTreeKind::Glob => {}
3994             UseTreeKind::Simple(_, id1, id2) => {
3995                 for (_, &id) in self.expect_full_res_from_use(base_id)
3996                                     .skip(1)
3997                                     .zip([id1, id2].iter())
3998                 {
3999                     vec.push(id);
4000                 }
4001             },
4002         }
4003     }
4004
4005     pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
4006         let mut ident = i.ident;
4007         let mut vis = self.lower_visibility(&i.vis, None);
4008         let attrs = self.lower_attrs(&i.attrs);
4009         if let ItemKind::MacroDef(ref def) = i.node {
4010             if !def.legacy || attr::contains_name(&i.attrs, sym::macro_export) ||
4011                               attr::contains_name(&i.attrs, sym::rustc_doc_only_macro) {
4012                 let body = self.lower_token_stream(def.stream());
4013                 let hir_id = self.lower_node_id(i.id);
4014                 self.exported_macros.push(hir::MacroDef {
4015                     name: ident.name,
4016                     vis,
4017                     attrs,
4018                     hir_id,
4019                     span: i.span,
4020                     body,
4021                     legacy: def.legacy,
4022                 });
4023             }
4024             return None;
4025         }
4026
4027         let node = self.lower_item_kind(i.id, &mut ident, &attrs, &mut vis, &i.node);
4028
4029         Some(hir::Item {
4030             hir_id: self.lower_node_id(i.id),
4031             ident,
4032             attrs,
4033             node,
4034             vis,
4035             span: i.span,
4036         })
4037     }
4038
4039     fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
4040         let def_id = self.resolver.definitions().local_def_id(i.id);
4041         hir::ForeignItem {
4042             hir_id: self.lower_node_id(i.id),
4043             ident: i.ident,
4044             attrs: self.lower_attrs(&i.attrs),
4045             node: match i.node {
4046                 ForeignItemKind::Fn(ref fdec, ref generics) => {
4047                     let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
4048                         generics,
4049                         def_id,
4050                         AnonymousLifetimeMode::PassThrough,
4051                         |this, _| {
4052                             (
4053                                 // Disallow impl Trait in foreign items
4054                                 this.lower_fn_decl(fdec, None, false, None),
4055                                 this.lower_fn_args_to_names(fdec),
4056                             )
4057                         },
4058                     );
4059
4060                     hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
4061                 }
4062                 ForeignItemKind::Static(ref t, m) => {
4063                     hir::ForeignItemKind::Static(
4064                         self.lower_ty(t, ImplTraitContext::disallowed()), self.lower_mutability(m))
4065                 }
4066                 ForeignItemKind::Ty => hir::ForeignItemKind::Type,
4067                 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
4068             },
4069             vis: self.lower_visibility(&i.vis, None),
4070             span: i.span,
4071         }
4072     }
4073
4074     fn lower_method_sig(
4075         &mut self,
4076         generics: &Generics,
4077         sig: &MethodSig,
4078         fn_def_id: DefId,
4079         impl_trait_return_allow: bool,
4080         is_async: Option<NodeId>,
4081     ) -> (hir::Generics, hir::MethodSig) {
4082         let header = self.lower_fn_header(sig.header);
4083         let (generics, decl) = self.add_in_band_defs(
4084             generics,
4085             fn_def_id,
4086             AnonymousLifetimeMode::PassThrough,
4087             |this, idty| this.lower_fn_decl(
4088                 &sig.decl,
4089                 Some((fn_def_id, idty)),
4090                 impl_trait_return_allow,
4091                 is_async,
4092             ),
4093         );
4094         (generics, hir::MethodSig { header, decl })
4095     }
4096
4097     fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
4098         match a {
4099             IsAuto::Yes => hir::IsAuto::Yes,
4100             IsAuto::No => hir::IsAuto::No,
4101         }
4102     }
4103
4104     fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
4105         hir::FnHeader {
4106             unsafety: self.lower_unsafety(h.unsafety),
4107             asyncness: self.lower_asyncness(h.asyncness.node),
4108             constness: self.lower_constness(h.constness),
4109             abi: h.abi,
4110         }
4111     }
4112
4113     fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
4114         match u {
4115             Unsafety::Unsafe => hir::Unsafety::Unsafe,
4116             Unsafety::Normal => hir::Unsafety::Normal,
4117         }
4118     }
4119
4120     fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
4121         match c.node {
4122             Constness::Const => hir::Constness::Const,
4123             Constness::NotConst => hir::Constness::NotConst,
4124         }
4125     }
4126
4127     fn lower_asyncness(&mut self, a: IsAsync) -> hir::IsAsync {
4128         match a {
4129             IsAsync::Async { .. } => hir::IsAsync::Async,
4130             IsAsync::NotAsync => hir::IsAsync::NotAsync,
4131         }
4132     }
4133
4134     fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
4135         match u {
4136             UnOp::Deref => hir::UnDeref,
4137             UnOp::Not => hir::UnNot,
4138             UnOp::Neg => hir::UnNeg,
4139         }
4140     }
4141
4142     fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
4143         Spanned {
4144             node: match b.node {
4145                 BinOpKind::Add => hir::BinOpKind::Add,
4146                 BinOpKind::Sub => hir::BinOpKind::Sub,
4147                 BinOpKind::Mul => hir::BinOpKind::Mul,
4148                 BinOpKind::Div => hir::BinOpKind::Div,
4149                 BinOpKind::Rem => hir::BinOpKind::Rem,
4150                 BinOpKind::And => hir::BinOpKind::And,
4151                 BinOpKind::Or => hir::BinOpKind::Or,
4152                 BinOpKind::BitXor => hir::BinOpKind::BitXor,
4153                 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
4154                 BinOpKind::BitOr => hir::BinOpKind::BitOr,
4155                 BinOpKind::Shl => hir::BinOpKind::Shl,
4156                 BinOpKind::Shr => hir::BinOpKind::Shr,
4157                 BinOpKind::Eq => hir::BinOpKind::Eq,
4158                 BinOpKind::Lt => hir::BinOpKind::Lt,
4159                 BinOpKind::Le => hir::BinOpKind::Le,
4160                 BinOpKind::Ne => hir::BinOpKind::Ne,
4161                 BinOpKind::Ge => hir::BinOpKind::Ge,
4162                 BinOpKind::Gt => hir::BinOpKind::Gt,
4163             },
4164             span: b.span,
4165         }
4166     }
4167
4168     fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
4169         let node = match p.node {
4170             PatKind::Wild => hir::PatKind::Wild,
4171             PatKind::Ident(ref binding_mode, ident, ref sub) => {
4172                 match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
4173                     // `None` can occur in body-less function signatures
4174                     res @ None | res @ Some(Res::Local(_)) => {
4175                         let canonical_id = match res {
4176                             Some(Res::Local(id)) => id,
4177                             _ => p.id,
4178                         };
4179
4180                         hir::PatKind::Binding(
4181                             self.lower_binding_mode(binding_mode),
4182                             self.lower_node_id(canonical_id),
4183                             ident,
4184                             sub.as_ref().map(|x| self.lower_pat(x)),
4185                         )
4186                     }
4187                     Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
4188                         None,
4189                         P(hir::Path {
4190                             span: ident.span,
4191                             res: self.lower_res(res),
4192                             segments: hir_vec![hir::PathSegment::from_ident(ident)],
4193                         }),
4194                     )),
4195                 }
4196             }
4197             PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
4198             PatKind::TupleStruct(ref path, ref pats, ddpos) => {
4199                 let qpath = self.lower_qpath(
4200                     p.id,
4201                     &None,
4202                     path,
4203                     ParamMode::Optional,
4204                     ImplTraitContext::disallowed(),
4205                 );
4206                 hir::PatKind::TupleStruct(
4207                     qpath,
4208                     pats.iter().map(|x| self.lower_pat(x)).collect(),
4209                     ddpos,
4210                 )
4211             }
4212             PatKind::Path(ref qself, ref path) => {
4213                 let qpath = self.lower_qpath(
4214                     p.id,
4215                     qself,
4216                     path,
4217                     ParamMode::Optional,
4218                     ImplTraitContext::disallowed(),
4219                 );
4220                 hir::PatKind::Path(qpath)
4221             }
4222             PatKind::Struct(ref path, ref fields, etc) => {
4223                 let qpath = self.lower_qpath(
4224                     p.id,
4225                     &None,
4226                     path,
4227                     ParamMode::Optional,
4228                     ImplTraitContext::disallowed(),
4229                 );
4230
4231                 let fs = fields
4232                     .iter()
4233                     .map(|f| {
4234                         Spanned {
4235                             span: f.span,
4236                             node: hir::FieldPat {
4237                                 hir_id: self.next_id(),
4238                                 ident: f.node.ident,
4239                                 pat: self.lower_pat(&f.node.pat),
4240                                 is_shorthand: f.node.is_shorthand,
4241                             },
4242                         }
4243                     })
4244                     .collect();
4245                 hir::PatKind::Struct(qpath, fs, etc)
4246             }
4247             PatKind::Tuple(ref elts, ddpos) => {
4248                 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
4249             }
4250             PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
4251             PatKind::Ref(ref inner, mutbl) => {
4252                 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
4253             }
4254             PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
4255                 P(self.lower_expr(e1)),
4256                 P(self.lower_expr(e2)),
4257                 self.lower_range_end(end),
4258             ),
4259             PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
4260                 before.iter().map(|x| self.lower_pat(x)).collect(),
4261                 slice.as_ref().map(|x| self.lower_pat(x)),
4262                 after.iter().map(|x| self.lower_pat(x)).collect(),
4263             ),
4264             PatKind::Paren(ref inner) => return self.lower_pat(inner),
4265             PatKind::Mac(_) => panic!("Shouldn't exist here"),
4266         };
4267
4268         P(hir::Pat {
4269             hir_id: self.lower_node_id(p.id),
4270             node,
4271             span: p.span,
4272         })
4273     }
4274
4275     fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
4276         match *e {
4277             RangeEnd::Included(_) => hir::RangeEnd::Included,
4278             RangeEnd::Excluded => hir::RangeEnd::Excluded,
4279         }
4280     }
4281
4282     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
4283         self.with_new_scopes(|this| {
4284             hir::AnonConst {
4285                 hir_id: this.lower_node_id(c.id),
4286                 body: this.lower_const_body(&c.value),
4287             }
4288         })
4289     }
4290
4291     fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
4292         let kind = match e.node {
4293             ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
4294             ExprKind::Array(ref exprs) => {
4295                 hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect())
4296             }
4297             ExprKind::Repeat(ref expr, ref count) => {
4298                 let expr = P(self.lower_expr(expr));
4299                 let count = self.lower_anon_const(count);
4300                 hir::ExprKind::Repeat(expr, count)
4301             }
4302             ExprKind::Tup(ref elts) => {
4303                 hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect())
4304             }
4305             ExprKind::Call(ref f, ref args) => {
4306                 let f = P(self.lower_expr(f));
4307                 hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect())
4308             }
4309             ExprKind::MethodCall(ref seg, ref args) => {
4310                 let hir_seg = P(self.lower_path_segment(
4311                     e.span,
4312                     seg,
4313                     ParamMode::Optional,
4314                     0,
4315                     ParenthesizedGenericArgs::Err,
4316                     ImplTraitContext::disallowed(),
4317                     None,
4318                 ));
4319                 let args = args.iter().map(|x| self.lower_expr(x)).collect();
4320                 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
4321             }
4322             ExprKind::Binary(binop, ref lhs, ref rhs) => {
4323                 let binop = self.lower_binop(binop);
4324                 let lhs = P(self.lower_expr(lhs));
4325                 let rhs = P(self.lower_expr(rhs));
4326                 hir::ExprKind::Binary(binop, lhs, rhs)
4327             }
4328             ExprKind::Unary(op, ref ohs) => {
4329                 let op = self.lower_unop(op);
4330                 let ohs = P(self.lower_expr(ohs));
4331                 hir::ExprKind::Unary(op, ohs)
4332             }
4333             ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
4334             ExprKind::Cast(ref expr, ref ty) => {
4335                 let expr = P(self.lower_expr(expr));
4336                 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4337             }
4338             ExprKind::Type(ref expr, ref ty) => {
4339                 let expr = P(self.lower_expr(expr));
4340                 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
4341             }
4342             ExprKind::AddrOf(m, ref ohs) => {
4343                 let m = self.lower_mutability(m);
4344                 let ohs = P(self.lower_expr(ohs));
4345                 hir::ExprKind::AddrOf(m, ohs)
4346             }
4347             ExprKind::Let(ref pats, ref scrutinee) => {
4348                 // If we got here, the `let` expression is not allowed.
4349                 self.sess
4350                     .struct_span_err(e.span, "`let` expressions are not supported here")
4351                     .note("only supported directly in conditions of `if`- and `while`-expressions")
4352                     .note("as well as when nested within `&&` and parenthesis in those conditions")
4353                     .emit();
4354
4355                 // For better recovery, we emit:
4356                 // ```
4357                 // match scrutinee { pats => true, _ => false }
4358                 // ```
4359                 // While this doesn't fully match the user's intent, it has key advantages:
4360                 // 1. We can avoid using `abort_if_errors`.
4361                 // 2. We can typeck both `pats` and `scrutinee`.
4362                 // 3. `pats` is allowed to be refutable.
4363                 // 4. The return type of the block is `bool` which seems like what the user wanted.
4364                 let scrutinee = self.lower_expr(scrutinee);
4365                 let then_arm = {
4366                     let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4367                     let expr = self.expr_bool(e.span, true);
4368                     self.arm(pats, P(expr))
4369                 };
4370                 let else_arm = {
4371                     let pats = hir_vec![self.pat_wild(e.span)];
4372                     let expr = self.expr_bool(e.span, false);
4373                     self.arm(pats, P(expr))
4374                 };
4375                 hir::ExprKind::Match(
4376                     P(scrutinee),
4377                     vec![then_arm, else_arm].into(),
4378                     hir::MatchSource::Normal,
4379                 )
4380             }
4381             // FIXME(#53667): handle lowering of && and parens.
4382             ExprKind::If(ref cond, ref then, ref else_opt) => {
4383                 // `_ => else_block` where `else_block` is `{}` if there's `None`:
4384                 let else_pat = self.pat_wild(e.span);
4385                 let (else_expr, contains_else_clause) = match else_opt {
4386                     None => (self.expr_block_empty(e.span), false),
4387                     Some(els) => (self.lower_expr(els), true),
4388                 };
4389                 let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
4390
4391                 // Handle then + scrutinee:
4392                 let then_blk = self.lower_block(then, false);
4393                 let then_expr = self.expr_block(then_blk, ThinVec::new());
4394                 let (then_pats, scrutinee, desugar) = match cond.node {
4395                     // `<pat> => <then>`
4396                     ExprKind::Let(ref pats, ref scrutinee) => {
4397                         let scrutinee = self.lower_expr(scrutinee);
4398                         let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4399                         let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause };
4400                         (pats, scrutinee, desugar)
4401                     }
4402                     // `true => then`:
4403                     _ => {
4404                         // Lower condition:
4405                         let cond = self.lower_expr(cond);
4406                         // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
4407                         // to preserve drop semantics since `if cond { ... }`
4408                         // don't let temporaries live outside of `cond`.
4409                         let span_block = self.mark_span_with_reason(IfTemporary, cond.span, None);
4410                         // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
4411                         // to preserve drop semantics since `if cond { ... }` does not
4412                         // let temporaries live outside of `cond`.
4413                         let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
4414
4415                         let desugar = hir::MatchSource::IfDesugar { contains_else_clause };
4416                         let pats = hir_vec![self.pat_bool(e.span, true)];
4417                         (pats, cond, desugar)
4418                     }
4419                 };
4420                 let then_arm = self.arm(then_pats, P(then_expr));
4421
4422                 hir::ExprKind::Match(P(scrutinee), vec![then_arm, else_arm].into(), desugar)
4423             }
4424             // FIXME(#53667): handle lowering of && and parens.
4425             ExprKind::While(ref cond, ref body, opt_label) => {
4426                 // Desugar `ExprWhileLet`
4427                 // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
4428                 if let ExprKind::Let(ref pats, ref sub_expr) = cond.node {
4429                     // to:
4430                     //
4431                     //   [opt_ident]: loop {
4432                     //     match <sub_expr> {
4433                     //       <pat> => <body>,
4434                     //       _ => break
4435                     //     }
4436                     //   }
4437
4438                     // Note that the block AND the condition are evaluated in the loop scope.
4439                     // This is done to allow `break` from inside the condition of the loop.
4440                     let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
4441                         (
4442                             this.lower_block(body, false),
4443                             this.expr_break(e.span, ThinVec::new()),
4444                             this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
4445                         )
4446                     });
4447
4448                     // `<pat> => <body>`
4449                     let pat_arm = {
4450                         let body_expr = P(self.expr_block(body, ThinVec::new()));
4451                         let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
4452                         self.arm(pats, body_expr)
4453                     };
4454
4455                     // `_ => break`
4456                     let break_arm = {
4457                         let pat_under = self.pat_wild(e.span);
4458                         self.arm(hir_vec![pat_under], break_expr)
4459                     };
4460
4461                     // `match <sub_expr> { ... }`
4462                     let arms = hir_vec![pat_arm, break_arm];
4463                     let match_expr = self.expr(
4464                         sub_expr.span,
4465                         hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
4466                         ThinVec::new(),
4467                     );
4468
4469                     // `[opt_ident]: loop { ... }`
4470                     let loop_block = P(self.block_expr(P(match_expr)));
4471                     let loop_expr = hir::ExprKind::Loop(
4472                         loop_block,
4473                         self.lower_label(opt_label),
4474                         hir::LoopSource::WhileLet,
4475                     );
4476                     // Add attributes to the outer returned expr node.
4477                     loop_expr
4478                 } else {
4479                     self.with_loop_scope(e.id, |this| {
4480                         hir::ExprKind::While(
4481                             this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
4482                             this.lower_block(body, false),
4483                             this.lower_label(opt_label),
4484                         )
4485                     })
4486                 }
4487             }
4488             ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
4489                 hir::ExprKind::Loop(
4490                     this.lower_block(body, false),
4491                     this.lower_label(opt_label),
4492                     hir::LoopSource::Loop,
4493                 )
4494             }),
4495             ExprKind::TryBlock(ref body) => {
4496                 self.with_catch_scope(body.id, |this| {
4497                     let unstable_span = this.mark_span_with_reason(
4498                         CompilerDesugaringKind::TryBlock,
4499                         body.span,
4500                         this.allow_try_trait.clone(),
4501                     );
4502                     let mut block = this.lower_block(body, true).into_inner();
4503                     let tail = block.expr.take().map_or_else(
4504                         || {
4505                             let span = this.sess.source_map().end_point(unstable_span);
4506                             hir::Expr {
4507                                 span,
4508                                 node: hir::ExprKind::Tup(hir_vec![]),
4509                                 attrs: ThinVec::new(),
4510                                 hir_id: this.next_id(),
4511                             }
4512                         },
4513                         |x: P<hir::Expr>| x.into_inner(),
4514                     );
4515                     block.expr = Some(this.wrap_in_try_constructor(
4516                         sym::from_ok, tail, unstable_span));
4517                     hir::ExprKind::Block(P(block), None)
4518                 })
4519             }
4520             ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
4521                 P(self.lower_expr(expr)),
4522                 arms.iter().map(|x| self.lower_arm(x)).collect(),
4523                 hir::MatchSource::Normal,
4524             ),
4525             ExprKind::Async(capture_clause, closure_node_id, ref block) => {
4526                 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
4527                     this.with_new_scopes(|this| {
4528                         let block = this.lower_block(block, false);
4529                         this.expr_block(block, ThinVec::new())
4530                     })
4531                 })
4532             }
4533             ExprKind::Await(_origin, ref expr) => self.lower_await(e.span, expr),
4534             ExprKind::Closure(
4535                 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
4536             ) => {
4537                 if let IsAsync::Async { closure_id, .. } = asyncness {
4538                     let outer_decl = FnDecl {
4539                         inputs: decl.inputs.clone(),
4540                         output: FunctionRetTy::Default(fn_decl_span),
4541                         c_variadic: false,
4542                     };
4543                     // We need to lower the declaration outside the new scope, because we
4544                     // have to conserve the state of being inside a loop condition for the
4545                     // closure argument types.
4546                     let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
4547
4548                     self.with_new_scopes(|this| {
4549                         // FIXME(cramertj): allow `async` non-`move` closures with arguments.
4550                         if capture_clause == CaptureBy::Ref &&
4551                             !decl.inputs.is_empty()
4552                         {
4553                             struct_span_err!(
4554                                 this.sess,
4555                                 fn_decl_span,
4556                                 E0708,
4557                                 "`async` non-`move` closures with arguments \
4558                                 are not currently supported",
4559                             )
4560                                 .help("consider using `let` statements to manually capture \
4561                                        variables by reference before entering an \
4562                                        `async move` closure")
4563                                 .emit();
4564                         }
4565
4566                         // Transform `async |x: u8| -> X { ... }` into
4567                         // `|x: u8| future_from_generator(|| -> X { ... })`.
4568                         let body_id = this.lower_fn_body(&outer_decl, |this| {
4569                             let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4570                                 Some(&**ty)
4571                             } else { None };
4572                             let async_body = this.make_async_expr(
4573                                 capture_clause, closure_id, async_ret_ty, body.span,
4574                                 |this| {
4575                                     this.with_new_scopes(|this| this.lower_expr(body))
4576                                 });
4577                             this.expr(fn_decl_span, async_body, ThinVec::new())
4578                         });
4579                         hir::ExprKind::Closure(
4580                             this.lower_capture_clause(capture_clause),
4581                             fn_decl,
4582                             body_id,
4583                             fn_decl_span,
4584                             None,
4585                         )
4586                     })
4587                 } else {
4588                     // Lower outside new scope to preserve `is_in_loop_condition`.
4589                     let fn_decl = self.lower_fn_decl(decl, None, false, None);
4590
4591                     self.with_new_scopes(|this| {
4592                         this.current_item = Some(fn_decl_span);
4593                         let mut generator_kind = None;
4594                         let body_id = this.lower_fn_body(decl, |this| {
4595                             let e = this.lower_expr(body);
4596                             generator_kind = this.generator_kind;
4597                             e
4598                         });
4599                         let generator_option = this.generator_movability_for_fn(
4600                             &decl,
4601                             fn_decl_span,
4602                             generator_kind,
4603                             movability,
4604                         );
4605                         hir::ExprKind::Closure(
4606                             this.lower_capture_clause(capture_clause),
4607                             fn_decl,
4608                             body_id,
4609                             fn_decl_span,
4610                             generator_option,
4611                         )
4612                     })
4613                 }
4614             }
4615             ExprKind::Block(ref blk, opt_label) => {
4616                 hir::ExprKind::Block(self.lower_block(blk,
4617                                                       opt_label.is_some()),
4618                                                       self.lower_label(opt_label))
4619             }
4620             ExprKind::Assign(ref el, ref er) => {
4621                 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
4622             }
4623             ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
4624                 self.lower_binop(op),
4625                 P(self.lower_expr(el)),
4626                 P(self.lower_expr(er)),
4627             ),
4628             ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
4629             ExprKind::Index(ref el, ref er) => {
4630                 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
4631             }
4632             // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
4633             ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
4634                 let id = self.next_id();
4635                 let e1 = self.lower_expr(e1);
4636                 let e2 = self.lower_expr(e2);
4637                 self.expr_call_std_assoc_fn(
4638                     id,
4639                     e.span,
4640                     &[sym::ops, sym::RangeInclusive],
4641                     "new",
4642                     hir_vec![e1, e2],
4643                 )
4644             }
4645             ExprKind::Range(ref e1, ref e2, lims) => {
4646                 use syntax::ast::RangeLimits::*;
4647
4648                 let path = match (e1, e2, lims) {
4649                     (&None, &None, HalfOpen) => sym::RangeFull,
4650                     (&Some(..), &None, HalfOpen) => sym::RangeFrom,
4651                     (&None, &Some(..), HalfOpen) => sym::RangeTo,
4652                     (&Some(..), &Some(..), HalfOpen) => sym::Range,
4653                     (&None, &Some(..), Closed) => sym::RangeToInclusive,
4654                     (&Some(..), &Some(..), Closed) => unreachable!(),
4655                     (_, &None, Closed) => self.diagnostic()
4656                         .span_fatal(e.span, "inclusive range with no end")
4657                         .raise(),
4658                 };
4659
4660                 let fields = e1.iter()
4661                     .map(|e| ("start", e))
4662                     .chain(e2.iter().map(|e| ("end", e)))
4663                     .map(|(s, e)| {
4664                         let expr = P(self.lower_expr(&e));
4665                         let ident = Ident::new(Symbol::intern(s), e.span);
4666                         self.field(ident, expr, e.span)
4667                     })
4668                     .collect::<P<[hir::Field]>>();
4669
4670                 let is_unit = fields.is_empty();
4671                 let struct_path = [sym::ops, path];
4672                 let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
4673                 let struct_path = hir::QPath::Resolved(None, P(struct_path));
4674
4675                 return hir::Expr {
4676                     hir_id: self.lower_node_id(e.id),
4677                     node: if is_unit {
4678                         hir::ExprKind::Path(struct_path)
4679                     } else {
4680                         hir::ExprKind::Struct(P(struct_path), fields, None)
4681                     },
4682                     span: e.span,
4683                     attrs: e.attrs.clone(),
4684                 };
4685             }
4686             ExprKind::Path(ref qself, ref path) => {
4687                 let qpath = self.lower_qpath(
4688                     e.id,
4689                     qself,
4690                     path,
4691                     ParamMode::Optional,
4692                     ImplTraitContext::disallowed(),
4693                 );
4694                 hir::ExprKind::Path(qpath)
4695             }
4696             ExprKind::Break(opt_label, ref opt_expr) => {
4697                 let destination = if self.is_in_loop_condition && opt_label.is_none() {
4698                     hir::Destination {
4699                         label: None,
4700                         target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4701                     }
4702                 } else {
4703                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4704                 };
4705                 hir::ExprKind::Break(
4706                     destination,
4707                     opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
4708                 )
4709             }
4710             ExprKind::Continue(opt_label) => {
4711                 hir::ExprKind::Continue(if self.is_in_loop_condition && opt_label.is_none() {
4712                     hir::Destination {
4713                         label: None,
4714                         target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
4715                     }
4716                 } else {
4717                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
4718                 })
4719             }
4720             ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
4721             ExprKind::InlineAsm(ref asm) => {
4722                 let hir_asm = hir::InlineAsm {
4723                     inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
4724                     outputs: asm.outputs
4725                         .iter()
4726                         .map(|out| hir::InlineAsmOutput {
4727                             constraint: out.constraint.clone(),
4728                             is_rw: out.is_rw,
4729                             is_indirect: out.is_indirect,
4730                             span: out.expr.span,
4731                         })
4732                         .collect(),
4733                     asm: asm.asm.clone(),
4734                     asm_str_style: asm.asm_str_style,
4735                     clobbers: asm.clobbers.clone().into(),
4736                     volatile: asm.volatile,
4737                     alignstack: asm.alignstack,
4738                     dialect: asm.dialect,
4739                     ctxt: asm.ctxt,
4740                 };
4741                 let outputs = asm.outputs
4742                     .iter()
4743                     .map(|out| self.lower_expr(&out.expr))
4744                     .collect();
4745                 let inputs = asm.inputs
4746                     .iter()
4747                     .map(|&(_, ref input)| self.lower_expr(input))
4748                     .collect();
4749                 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
4750             }
4751             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
4752                 P(self.lower_qpath(
4753                     e.id,
4754                     &None,
4755                     path,
4756                     ParamMode::Optional,
4757                     ImplTraitContext::disallowed(),
4758                 )),
4759                 fields.iter().map(|x| self.lower_field(x)).collect(),
4760                 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
4761             ),
4762             ExprKind::Paren(ref ex) => {
4763                 let mut ex = self.lower_expr(ex);
4764                 // Include parens in span, but only if it is a super-span.
4765                 if e.span.contains(ex.span) {
4766                     ex.span = e.span;
4767                 }
4768                 // Merge attributes into the inner expression.
4769                 let mut attrs = e.attrs.clone();
4770                 attrs.extend::<Vec<_>>(ex.attrs.into());
4771                 ex.attrs = attrs;
4772                 return ex;
4773             }
4774
4775             ExprKind::Yield(ref opt_expr) => {
4776                 match self.generator_kind {
4777                     Some(hir::GeneratorKind::Gen) => {},
4778                     Some(hir::GeneratorKind::Async) => {
4779                         span_err!(
4780                             self.sess,
4781                             e.span,
4782                             E0727,
4783                             "`async` generators are not yet supported",
4784                         );
4785                         self.sess.abort_if_errors();
4786                     },
4787                     None => {
4788                         self.generator_kind = Some(hir::GeneratorKind::Gen);
4789                     }
4790                 }
4791                 let expr = opt_expr
4792                     .as_ref()
4793                     .map(|x| self.lower_expr(x))
4794                     .unwrap_or_else(|| self.expr_unit(e.span));
4795                 hir::ExprKind::Yield(P(expr), hir::YieldSource::Yield)
4796             }
4797
4798             ExprKind::Err => hir::ExprKind::Err,
4799
4800             // Desugar `ExprForLoop`
4801             // from: `[opt_ident]: for <pat> in <head> <body>`
4802             ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
4803                 // to:
4804                 //
4805                 //   {
4806                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
4807                 //       mut iter => {
4808                 //         [opt_ident]: loop {
4809                 //           let mut __next;
4810                 //           match ::std::iter::Iterator::next(&mut iter) {
4811                 //             ::std::option::Option::Some(val) => __next = val,
4812                 //             ::std::option::Option::None => break
4813                 //           };
4814                 //           let <pat> = __next;
4815                 //           StmtKind::Expr(<body>);
4816                 //         }
4817                 //       }
4818                 //     };
4819                 //     result
4820                 //   }
4821
4822                 // expand <head>
4823                 let mut head = self.lower_expr(head);
4824                 let head_sp = head.span;
4825                 let desugared_span = self.mark_span_with_reason(
4826                     CompilerDesugaringKind::ForLoop,
4827                     head_sp,
4828                     None,
4829                 );
4830                 head.span = desugared_span;
4831
4832                 let iter = Ident::with_empty_ctxt(sym::iter);
4833
4834                 let next_ident = Ident::with_empty_ctxt(sym::__next);
4835                 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
4836                     desugared_span,
4837                     next_ident,
4838                     hir::BindingAnnotation::Mutable,
4839                 );
4840
4841                 // `::std::option::Option::Some(val) => __next = val`
4842                 let pat_arm = {
4843                     let val_ident = Ident::with_empty_ctxt(sym::val);
4844                     let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
4845                     let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
4846                     let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
4847                     let assign = P(self.expr(
4848                         pat.span,
4849                         hir::ExprKind::Assign(next_expr, val_expr),
4850                         ThinVec::new(),
4851                     ));
4852                     let some_pat = self.pat_some(pat.span, val_pat);
4853                     self.arm(hir_vec![some_pat], assign)
4854                 };
4855
4856                 // `::std::option::Option::None => break`
4857                 let break_arm = {
4858                     let break_expr =
4859                         self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
4860                     let pat = self.pat_none(e.span);
4861                     self.arm(hir_vec![pat], break_expr)
4862                 };
4863
4864                 // `mut iter`
4865                 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
4866                     desugared_span,
4867                     iter,
4868                     hir::BindingAnnotation::Mutable
4869                 );
4870
4871                 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
4872                 let match_expr = {
4873                     let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
4874                     let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
4875                     let next_path = &[sym::iter, sym::Iterator, sym::next];
4876                     let next_expr = P(self.expr_call_std_path(
4877                         head_sp,
4878                         next_path,
4879                         hir_vec![ref_mut_iter],
4880                     ));
4881                     let arms = hir_vec![pat_arm, break_arm];
4882
4883                     P(self.expr(
4884                         head_sp,
4885                         hir::ExprKind::Match(
4886                             next_expr,
4887                             arms,
4888                             hir::MatchSource::ForLoopDesugar
4889                         ),
4890                         ThinVec::new(),
4891                     ))
4892                 };
4893                 let match_stmt = self.stmt(head_sp, hir::StmtKind::Expr(match_expr));
4894
4895                 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
4896
4897                 // `let mut __next`
4898                 let next_let = self.stmt_let_pat(
4899                     desugared_span,
4900                     None,
4901                     next_pat,
4902                     hir::LocalSource::ForLoopDesugar,
4903                 );
4904
4905                 // `let <pat> = __next`
4906                 let pat = self.lower_pat(pat);
4907                 let pat_let = self.stmt_let_pat(
4908                     head_sp,
4909                     Some(next_expr),
4910                     pat,
4911                     hir::LocalSource::ForLoopDesugar,
4912                 );
4913
4914                 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
4915                 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
4916                 let body_stmt = self.stmt(body.span, hir::StmtKind::Expr(body_expr));
4917
4918                 let loop_block = P(self.block_all(
4919                     e.span,
4920                     hir_vec![next_let, match_stmt, pat_let, body_stmt],
4921                     None,
4922                 ));
4923
4924                 // `[opt_ident]: loop { ... }`
4925                 let loop_expr = hir::ExprKind::Loop(
4926                     loop_block,
4927                     self.lower_label(opt_label),
4928                     hir::LoopSource::ForLoop,
4929                 );
4930                 let loop_expr = P(hir::Expr {
4931                     hir_id: self.lower_node_id(e.id),
4932                     node: loop_expr,
4933                     span: e.span,
4934                     attrs: ThinVec::new(),
4935                 });
4936
4937                 // `mut iter => { ... }`
4938                 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
4939
4940                 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
4941                 let into_iter_expr = {
4942                     let into_iter_path =
4943                         &[sym::iter, sym::IntoIterator, sym::into_iter];
4944                     P(self.expr_call_std_path(
4945                         head_sp,
4946                         into_iter_path,
4947                         hir_vec![head],
4948                     ))
4949                 };
4950
4951                 let match_expr = P(self.expr_match(
4952                     head_sp,
4953                     into_iter_expr,
4954                     hir_vec![iter_arm],
4955                     hir::MatchSource::ForLoopDesugar,
4956                 ));
4957
4958                 // This is effectively `{ let _result = ...; _result }`.
4959                 // The construct was introduced in #21984.
4960                 // FIXME(60253): Is this still necessary?
4961                 // Also, add the attributes to the outer returned expr node.
4962                 return self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
4963             }
4964
4965             // Desugar `ExprKind::Try`
4966             // from: `<expr>?`
4967             ExprKind::Try(ref sub_expr) => {
4968                 // into:
4969                 //
4970                 // match Try::into_result(<expr>) {
4971                 //     Ok(val) => #[allow(unreachable_code)] val,
4972                 //     Err(err) => #[allow(unreachable_code)]
4973                 //                 // If there is an enclosing `catch {...}`
4974                 //                 break 'catch_target Try::from_error(From::from(err)),
4975                 //                 // Otherwise
4976                 //                 return Try::from_error(From::from(err)),
4977                 // }
4978
4979                 let unstable_span = self.mark_span_with_reason(
4980                     CompilerDesugaringKind::QuestionMark,
4981                     e.span,
4982                     self.allow_try_trait.clone(),
4983                 );
4984                 let try_span = self.sess.source_map().end_point(e.span);
4985                 let try_span = self.mark_span_with_reason(
4986                     CompilerDesugaringKind::QuestionMark,
4987                     try_span,
4988                     self.allow_try_trait.clone(),
4989                 );
4990
4991                 // `Try::into_result(<expr>)`
4992                 let discr = {
4993                     // expand <expr>
4994                     let sub_expr = self.lower_expr(sub_expr);
4995
4996                     let path = &[sym::ops, sym::Try, sym::into_result];
4997                     P(self.expr_call_std_path(
4998                         unstable_span,
4999                         path,
5000                         hir_vec![sub_expr],
5001                     ))
5002                 };
5003
5004                 // `#[allow(unreachable_code)]`
5005                 let attr = {
5006                     // `allow(unreachable_code)`
5007                     let allow = {
5008                         let allow_ident = Ident::with_empty_ctxt(sym::allow).with_span_pos(e.span);
5009                         let uc_ident = Ident::with_empty_ctxt(sym::unreachable_code)
5010                             .with_span_pos(e.span);
5011                         let uc_nested = attr::mk_nested_word_item(uc_ident);
5012                         attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
5013                     };
5014                     attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
5015                 };
5016                 let attrs = vec![attr];
5017
5018                 // `Ok(val) => #[allow(unreachable_code)] val,`
5019                 let ok_arm = {
5020                     let val_ident = Ident::with_empty_ctxt(sym::val);
5021                     let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident);
5022                     let val_expr = P(self.expr_ident_with_attrs(
5023                         e.span,
5024                         val_ident,
5025                         val_pat_nid,
5026                         ThinVec::from(attrs.clone()),
5027                     ));
5028                     let ok_pat = self.pat_ok(e.span, val_pat);
5029
5030                     self.arm(hir_vec![ok_pat], val_expr)
5031                 };
5032
5033                 // `Err(err) => #[allow(unreachable_code)]
5034                 //              return Try::from_error(From::from(err)),`
5035                 let err_arm = {
5036                     let err_ident = Ident::with_empty_ctxt(sym::err);
5037                     let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
5038                     let from_expr = {
5039                         let from_path = &[sym::convert, sym::From, sym::from];
5040                         let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
5041                         self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
5042                     };
5043                     let from_err_expr =
5044                         self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
5045                     let thin_attrs = ThinVec::from(attrs);
5046                     let catch_scope = self.catch_scopes.last().map(|x| *x);
5047                     let ret_expr = if let Some(catch_node) = catch_scope {
5048                         let target_id = Ok(self.lower_node_id(catch_node));
5049                         P(self.expr(
5050                             try_span,
5051                             hir::ExprKind::Break(
5052                                 hir::Destination {
5053                                     label: None,
5054                                     target_id,
5055                                 },
5056                                 Some(from_err_expr),
5057                             ),
5058                             thin_attrs,
5059                         ))
5060                     } else {
5061                         P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
5062                     };
5063
5064                     let err_pat = self.pat_err(try_span, err_local);
5065                     self.arm(hir_vec![err_pat], ret_expr)
5066                 };
5067
5068                 hir::ExprKind::Match(
5069                     discr,
5070                     hir_vec![err_arm, ok_arm],
5071                     hir::MatchSource::TryDesugar,
5072                 )
5073             }
5074
5075             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
5076         };
5077
5078         hir::Expr {
5079             hir_id: self.lower_node_id(e.id),
5080             node: kind,
5081             span: e.span,
5082             attrs: e.attrs.clone(),
5083         }
5084     }
5085
5086     fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
5087         smallvec![match s.node {
5088             StmtKind::Local(ref l) => {
5089                 let (l, item_ids) = self.lower_local(l);
5090                 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
5091                     .into_iter()
5092                     .map(|item_id| {
5093                         let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
5094                         self.stmt(s.span, hir::StmtKind::Item(item_id))
5095                     })
5096                     .collect();
5097                 ids.push({
5098                     hir::Stmt {
5099                         hir_id: self.lower_node_id(s.id),
5100                         node: hir::StmtKind::Local(P(l)),
5101                         span: s.span,
5102                     }
5103                 });
5104                 return ids;
5105             },
5106             StmtKind::Item(ref it) => {
5107                 // Can only use the ID once.
5108                 let mut id = Some(s.id);
5109                 return self.lower_item_id(it)
5110                     .into_iter()
5111                     .map(|item_id| {
5112                         let hir_id = id.take()
5113                           .map(|id| self.lower_node_id(id))
5114                           .unwrap_or_else(|| self.next_id());
5115
5116                         hir::Stmt {
5117                             hir_id,
5118                             node: hir::StmtKind::Item(item_id),
5119                             span: s.span,
5120                         }
5121                     })
5122                     .collect();
5123             }
5124             StmtKind::Expr(ref e) => {
5125                 hir::Stmt {
5126                     hir_id: self.lower_node_id(s.id),
5127                     node: hir::StmtKind::Expr(P(self.lower_expr(e))),
5128                     span: s.span,
5129                 }
5130             },
5131             StmtKind::Semi(ref e) => {
5132                 hir::Stmt {
5133                     hir_id: self.lower_node_id(s.id),
5134                     node: hir::StmtKind::Semi(P(self.lower_expr(e))),
5135                     span: s.span,
5136                 }
5137             },
5138             StmtKind::Mac(..) => panic!("Shouldn't exist here"),
5139         }]
5140     }
5141
5142     fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
5143         match c {
5144             CaptureBy::Value => hir::CaptureByValue,
5145             CaptureBy::Ref => hir::CaptureByRef,
5146         }
5147     }
5148
5149     /// If an `explicit_owner` is given, this method allocates the `HirId` in
5150     /// the address space of that item instead of the item currently being
5151     /// lowered. This can happen during `lower_impl_item_ref()` where we need to
5152     /// lower a `Visibility` value although we haven't lowered the owning
5153     /// `ImplItem` in question yet.
5154     fn lower_visibility(
5155         &mut self,
5156         v: &Visibility,
5157         explicit_owner: Option<NodeId>,
5158     ) -> hir::Visibility {
5159         let node = match v.node {
5160             VisibilityKind::Public => hir::VisibilityKind::Public,
5161             VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
5162             VisibilityKind::Restricted { ref path, id } => {
5163                 debug!("lower_visibility: restricted path id = {:?}", id);
5164                 let lowered_id = if let Some(owner) = explicit_owner {
5165                     self.lower_node_id_with_owner(id, owner)
5166                 } else {
5167                     self.lower_node_id(id)
5168                 };
5169                 let res = self.expect_full_res(id);
5170                 let res = self.lower_res(res);
5171                 hir::VisibilityKind::Restricted {
5172                     path: P(self.lower_path_extra(
5173                         res,
5174                         path,
5175                         ParamMode::Explicit,
5176                         explicit_owner,
5177                     )),
5178                     hir_id: lowered_id,
5179                 }
5180             },
5181             VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
5182         };
5183         respan(v.span, node)
5184     }
5185
5186     fn lower_defaultness(&self, d: Defaultness, has_value: bool) -> hir::Defaultness {
5187         match d {
5188             Defaultness::Default => hir::Defaultness::Default {
5189                 has_value: has_value,
5190             },
5191             Defaultness::Final => {
5192                 assert!(has_value);
5193                 hir::Defaultness::Final
5194             }
5195         }
5196     }
5197
5198     fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
5199         match *b {
5200             BlockCheckMode::Default => hir::DefaultBlock,
5201             BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
5202         }
5203     }
5204
5205     fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
5206         match *b {
5207             BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
5208             BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
5209             BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
5210             BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
5211         }
5212     }
5213
5214     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
5215         match u {
5216             CompilerGenerated => hir::CompilerGenerated,
5217             UserProvided => hir::UserProvided,
5218         }
5219     }
5220
5221     fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
5222         match i {
5223             ImplPolarity::Positive => hir::ImplPolarity::Positive,
5224             ImplPolarity::Negative => hir::ImplPolarity::Negative,
5225         }
5226     }
5227
5228     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
5229         match f {
5230             TraitBoundModifier::None => hir::TraitBoundModifier::None,
5231             TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
5232         }
5233     }
5234
5235     // Helper methods for building HIR.
5236
5237     fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
5238         hir::Arm {
5239             hir_id: self.next_id(),
5240             attrs: hir_vec![],
5241             pats,
5242             guard: None,
5243             span: expr.span,
5244             body: expr,
5245         }
5246     }
5247
5248     fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
5249         hir::Field {
5250             hir_id: self.next_id(),
5251             ident,
5252             span,
5253             expr,
5254             is_shorthand: false,
5255         }
5256     }
5257
5258     fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
5259         let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
5260         P(self.expr(span, expr_break, attrs))
5261     }
5262
5263     fn expr_call(
5264         &mut self,
5265         span: Span,
5266         e: P<hir::Expr>,
5267         args: hir::HirVec<hir::Expr>,
5268     ) -> hir::Expr {
5269         self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
5270     }
5271
5272     // Note: associated functions must use `expr_call_std_path`.
5273     fn expr_call_std_path(
5274         &mut self,
5275         span: Span,
5276         path_components: &[Symbol],
5277         args: hir::HirVec<hir::Expr>,
5278     ) -> hir::Expr {
5279         let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
5280         self.expr_call(span, path, args)
5281     }
5282
5283     // Create an expression calling an associated function of an std type.
5284     //
5285     // Associated functions cannot be resolved through the normal `std_path` function,
5286     // as they are resolved differently and so cannot use `expr_call_std_path`.
5287     //
5288     // This function accepts the path component (`ty_path_components`) separately from
5289     // the name of the associated function (`assoc_fn_name`) in order to facilitate
5290     // separate resolution of the type and creation of a path referring to its associated
5291     // function.
5292     fn expr_call_std_assoc_fn(
5293         &mut self,
5294         ty_path_id: hir::HirId,
5295         span: Span,
5296         ty_path_components: &[Symbol],
5297         assoc_fn_name: &str,
5298         args: hir::HirVec<hir::Expr>,
5299     ) -> hir::ExprKind {
5300         let ty_path = P(self.std_path(span, ty_path_components, None, false));
5301         let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
5302         let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
5303         let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
5304         let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
5305         hir::ExprKind::Call(fn_expr, args)
5306     }
5307
5308     fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
5309         self.expr_ident_with_attrs(span, ident, binding, ThinVec::new())
5310     }
5311
5312     fn expr_ident_with_attrs(
5313         &mut self,
5314         span: Span,
5315         ident: Ident,
5316         binding: hir::HirId,
5317         attrs: ThinVec<Attribute>,
5318     ) -> hir::Expr {
5319         let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
5320             None,
5321             P(hir::Path {
5322                 span,
5323                 res: Res::Local(binding),
5324                 segments: hir_vec![hir::PathSegment::from_ident(ident)],
5325             }),
5326         ));
5327
5328         self.expr(span, expr_path, attrs)
5329     }
5330
5331     fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
5332         self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
5333     }
5334
5335     fn expr_std_path(
5336         &mut self,
5337         span: Span,
5338         components: &[Symbol],
5339         params: Option<P<hir::GenericArgs>>,
5340         attrs: ThinVec<Attribute>,
5341     ) -> hir::Expr {
5342         let path = self.std_path(span, components, params, true);
5343         self.expr(
5344             span,
5345             hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
5346             attrs,
5347         )
5348     }
5349
5350     /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
5351     ///
5352     /// In terms of drop order, it has the same effect as wrapping `expr` in
5353     /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
5354     ///
5355     /// The drop order can be important in e.g. `if expr { .. }`.
5356     fn expr_drop_temps(
5357         &mut self,
5358         span: Span,
5359         expr: P<hir::Expr>,
5360         attrs: ThinVec<Attribute>
5361     ) -> hir::Expr {
5362         self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
5363     }
5364
5365     fn expr_match(
5366         &mut self,
5367         span: Span,
5368         arg: P<hir::Expr>,
5369         arms: hir::HirVec<hir::Arm>,
5370         source: hir::MatchSource,
5371     ) -> hir::Expr {
5372         self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
5373     }
5374
5375     fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
5376         self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
5377     }
5378
5379     fn expr_unit(&mut self, sp: Span) -> hir::Expr {
5380         self.expr_tuple(sp, hir_vec![])
5381     }
5382
5383     fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
5384         self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
5385     }
5386
5387     fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec<Attribute>) -> hir::Expr {
5388         hir::Expr {
5389             hir_id: self.next_id(),
5390             node,
5391             span,
5392             attrs,
5393         }
5394     }
5395
5396     fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt {
5397         hir::Stmt { span, node, hir_id: self.next_id() }
5398     }
5399
5400     fn stmt_let_pat(
5401         &mut self,
5402         span: Span,
5403         init: Option<P<hir::Expr>>,
5404         pat: P<hir::Pat>,
5405         source: hir::LocalSource,
5406     ) -> hir::Stmt {
5407         let local = hir::Local {
5408             pat,
5409             ty: None,
5410             init,
5411             hir_id: self.next_id(),
5412             span,
5413             source,
5414             attrs: ThinVec::new()
5415         };
5416         self.stmt(span, hir::StmtKind::Local(P(local)))
5417     }
5418
5419     fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
5420         let blk = self.block_all(span, hir_vec![], None);
5421         self.expr_block(P(blk), ThinVec::new())
5422     }
5423
5424     fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
5425         self.block_all(expr.span, hir::HirVec::new(), Some(expr))
5426     }
5427
5428     fn block_all(
5429         &mut self,
5430         span: Span,
5431         stmts: hir::HirVec<hir::Stmt>,
5432         expr: Option<P<hir::Expr>>,
5433     ) -> hir::Block {
5434         hir::Block {
5435             stmts,
5436             expr,
5437             hir_id: self.next_id(),
5438             rules: hir::DefaultBlock,
5439             span,
5440             targeted_by_break: false,
5441         }
5442     }
5443
5444     fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
5445         let hir_id = self.next_id();
5446         let span = expr.span;
5447         self.expr(
5448             span,
5449             hir::ExprKind::Block(P(hir::Block {
5450                 stmts: hir_vec![],
5451                 expr: Some(expr),
5452                 hir_id,
5453                 rules: hir::UnsafeBlock(hir::CompilerGenerated),
5454                 span,
5455                 targeted_by_break: false,
5456             }), None),
5457             ThinVec::new(),
5458         )
5459     }
5460
5461     /// Constructs a `true` or `false` literal expression.
5462     fn expr_bool(&mut self, span: Span, val: bool) -> hir::Expr {
5463         let lit = Spanned { span, node: LitKind::Bool(val) };
5464         self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new())
5465     }
5466
5467     /// Constructs a `true` or `false` literal pattern.
5468     fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
5469         let expr = self.expr_bool(span, val);
5470         self.pat(span, hir::PatKind::Lit(P(expr)))
5471     }
5472
5473     fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5474         self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
5475     }
5476
5477     fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5478         self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
5479     }
5480
5481     fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
5482         self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
5483     }
5484
5485     fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
5486         self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
5487     }
5488
5489     fn pat_std_enum(
5490         &mut self,
5491         span: Span,
5492         components: &[Symbol],
5493         subpats: hir::HirVec<P<hir::Pat>>,
5494     ) -> P<hir::Pat> {
5495         let path = self.std_path(span, components, None, true);
5496         let qpath = hir::QPath::Resolved(None, P(path));
5497         let pt = if subpats.is_empty() {
5498             hir::PatKind::Path(qpath)
5499         } else {
5500             hir::PatKind::TupleStruct(qpath, subpats, None)
5501         };
5502         self.pat(span, pt)
5503     }
5504
5505     fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
5506         self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
5507     }
5508
5509     fn pat_ident_binding_mode(
5510         &mut self,
5511         span: Span,
5512         ident: Ident,
5513         bm: hir::BindingAnnotation,
5514     ) -> (P<hir::Pat>, hir::HirId) {
5515         let hir_id = self.next_id();
5516
5517         (
5518             P(hir::Pat {
5519                 hir_id,
5520                 node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
5521                 span,
5522             }),
5523             hir_id
5524         )
5525     }
5526
5527     fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
5528         self.pat(span, hir::PatKind::Wild)
5529     }
5530
5531     fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
5532         P(hir::Pat {
5533             hir_id: self.next_id(),
5534             node: pat,
5535             span,
5536         })
5537     }
5538
5539     /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
5540     /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
5541     /// The path is also resolved according to `is_value`.
5542     fn std_path(
5543         &mut self,
5544         span: Span,
5545         components: &[Symbol],
5546         params: Option<P<hir::GenericArgs>>,
5547         is_value: bool,
5548     ) -> hir::Path {
5549         let (path, res) = self.resolver
5550             .resolve_str_path(span, self.crate_root, components, is_value);
5551
5552         let mut segments: Vec<_> = path.segments.iter().map(|segment| {
5553             let res = self.expect_full_res(segment.id);
5554             hir::PathSegment {
5555                 ident: segment.ident,
5556                 hir_id: Some(self.lower_node_id(segment.id)),
5557                 res: Some(self.lower_res(res)),
5558                 infer_args: true,
5559                 args: None,
5560             }
5561         }).collect();
5562         segments.last_mut().unwrap().args = params;
5563
5564         hir::Path {
5565             span,
5566             res: res.map_id(|_| panic!("unexpected node_id")),
5567             segments: segments.into(),
5568         }
5569     }
5570
5571     fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
5572         let node = match qpath {
5573             hir::QPath::Resolved(None, path) => {
5574                 // Turn trait object paths into `TyKind::TraitObject` instead.
5575                 match path.res {
5576                     Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
5577                         let principal = hir::PolyTraitRef {
5578                             bound_generic_params: hir::HirVec::new(),
5579                             trait_ref: hir::TraitRef {
5580                                 path: path.and_then(|path| path),
5581                                 hir_ref_id: hir_id,
5582                             },
5583                             span,
5584                         };
5585
5586                         // The original ID is taken by the `PolyTraitRef`,
5587                         // so the `Ty` itself needs a different one.
5588                         hir_id = self.next_id();
5589                         hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
5590                     }
5591                     _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
5592                 }
5593             }
5594             _ => hir::TyKind::Path(qpath),
5595         };
5596         hir::Ty {
5597             hir_id,
5598             node,
5599             span,
5600         }
5601     }
5602
5603     /// Invoked to create the lifetime argument for a type `&T`
5604     /// with no explicit lifetime.
5605     fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
5606         match self.anonymous_lifetime_mode {
5607             // Intercept when we are in an impl header or async fn and introduce an in-band
5608             // lifetime.
5609             // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
5610             // `'f`.
5611             AnonymousLifetimeMode::CreateParameter => {
5612                 let fresh_name = self.collect_fresh_in_band_lifetime(span);
5613                 hir::Lifetime {
5614                     hir_id: self.next_id(),
5615                     span,
5616                     name: hir::LifetimeName::Param(fresh_name),
5617                 }
5618             }
5619
5620             AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5621
5622             AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5623
5624             AnonymousLifetimeMode::Replace(replacement) => {
5625                 self.new_replacement_lifetime(replacement, span)
5626             }
5627         }
5628     }
5629
5630     /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
5631     /// return a "error lifetime".
5632     fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
5633         let (id, msg, label) = match id {
5634             Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
5635
5636             None => (
5637                 self.sess.next_node_id(),
5638                 "`&` without an explicit lifetime name cannot be used here",
5639                 "explicit lifetime name needed here",
5640             ),
5641         };
5642
5643         let mut err = struct_span_err!(
5644             self.sess,
5645             span,
5646             E0637,
5647             "{}",
5648             msg,
5649         );
5650         err.span_label(span, label);
5651         err.emit();
5652
5653         self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5654     }
5655
5656     /// Invoked to create the lifetime argument(s) for a path like
5657     /// `std::cell::Ref<T>`; note that implicit lifetimes in these
5658     /// sorts of cases are deprecated. This may therefore report a warning or an
5659     /// error, depending on the mode.
5660     fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
5661         (0..count)
5662             .map(|_| self.elided_path_lifetime(span))
5663             .collect()
5664     }
5665
5666     fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
5667         match self.anonymous_lifetime_mode {
5668             AnonymousLifetimeMode::CreateParameter => {
5669                 // We should have emitted E0726 when processing this path above
5670                 self.sess.delay_span_bug(
5671                     span,
5672                     "expected 'implicit elided lifetime not allowed' error",
5673                 );
5674                 let id = self.sess.next_node_id();
5675                 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
5676             }
5677             // This is the normal case.
5678             AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
5679
5680             AnonymousLifetimeMode::Replace(replacement) => {
5681                 self.new_replacement_lifetime(replacement, span)
5682             }
5683
5684             AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
5685         }
5686     }
5687
5688     /// Invoked to create the lifetime argument(s) for an elided trait object
5689     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
5690     /// when the bound is written, even if it is written with `'_` like in
5691     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
5692     fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
5693         match self.anonymous_lifetime_mode {
5694             // NB. We intentionally ignore the create-parameter mode here.
5695             // and instead "pass through" to resolve-lifetimes, which will apply
5696             // the object-lifetime-defaulting rules. Elided object lifetime defaults
5697             // do not act like other elided lifetimes. In other words, given this:
5698             //
5699             //     impl Foo for Box<dyn Debug>
5700             //
5701             // we do not introduce a fresh `'_` to serve as the bound, but instead
5702             // ultimately translate to the equivalent of:
5703             //
5704             //     impl Foo for Box<dyn Debug + 'static>
5705             //
5706             // `resolve_lifetime` has the code to make that happen.
5707             AnonymousLifetimeMode::CreateParameter => {}
5708
5709             AnonymousLifetimeMode::ReportError => {
5710                 // ReportError applies to explicit use of `'_`.
5711             }
5712
5713             // This is the normal case.
5714             AnonymousLifetimeMode::PassThrough => {}
5715
5716             // We don't need to do any replacement here as this lifetime
5717             // doesn't refer to an elided lifetime elsewhere in the function
5718             // signature.
5719             AnonymousLifetimeMode::Replace(_) => {}
5720         }
5721
5722         self.new_implicit_lifetime(span)
5723     }
5724
5725     fn new_replacement_lifetime(
5726         &mut self,
5727         replacement: LtReplacement,
5728         span: Span,
5729     ) -> hir::Lifetime {
5730         let hir_id = self.next_id();
5731         self.replace_elided_lifetime(hir_id, span, replacement)
5732     }
5733
5734     fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
5735         hir::Lifetime {
5736             hir_id: self.next_id(),
5737             span,
5738             name: hir::LifetimeName::Implicit,
5739         }
5740     }
5741
5742     fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
5743         self.sess.buffer_lint_with_diagnostic(
5744             builtin::BARE_TRAIT_OBJECTS,
5745             id,
5746             span,
5747             "trait objects without an explicit `dyn` are deprecated",
5748             builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
5749         )
5750     }
5751
5752     fn wrap_in_try_constructor(
5753         &mut self,
5754         method: Symbol,
5755         e: hir::Expr,
5756         unstable_span: Span,
5757     ) -> P<hir::Expr> {
5758         let path = &[sym::ops, sym::Try, method];
5759         let from_err = P(self.expr_std_path(unstable_span, path, None,
5760                                             ThinVec::new()));
5761         P(self.expr_call(e.span, from_err, hir_vec![e]))
5762     }
5763
5764     fn lower_await(
5765         &mut self,
5766         await_span: Span,
5767         expr: &ast::Expr,
5768     ) -> hir::ExprKind {
5769         // to:
5770         //
5771         // {
5772         //     let mut pinned = <expr>;
5773         //     loop {
5774         //         match ::std::future::poll_with_tls_context(unsafe {
5775         //             ::std::pin::Pin::new_unchecked(&mut pinned)
5776         //         }) {
5777         //             ::std::task::Poll::Ready(result) => break result,
5778         //             ::std::task::Poll::Pending => {},
5779         //         }
5780         //         yield ();
5781         //     }
5782         // }
5783         match self.generator_kind {
5784             Some(hir::GeneratorKind::Async) => {},
5785             Some(hir::GeneratorKind::Gen) |
5786             None => {
5787                 let mut err = struct_span_err!(
5788                     self.sess,
5789                     await_span,
5790                     E0728,
5791                     "`await` is only allowed inside `async` functions and blocks"
5792                 );
5793                 err.span_label(await_span, "only allowed inside `async` functions and blocks");
5794                 if let Some(item_sp) = self.current_item {
5795                     err.span_label(item_sp, "this is not `async`");
5796                 }
5797                 err.emit();
5798             }
5799         }
5800         let span = self.mark_span_with_reason(
5801             CompilerDesugaringKind::Await,
5802             await_span,
5803             None,
5804         );
5805         let gen_future_span = self.mark_span_with_reason(
5806             CompilerDesugaringKind::Await,
5807             await_span,
5808             self.allow_gen_future.clone(),
5809         );
5810
5811         // let mut pinned = <expr>;
5812         let expr = P(self.lower_expr(expr));
5813         let pinned_ident = Ident::with_empty_ctxt(sym::pinned);
5814         let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
5815             span,
5816             pinned_ident,
5817             hir::BindingAnnotation::Mutable,
5818         );
5819         let pinned_let = self.stmt_let_pat(
5820             span,
5821             Some(expr),
5822             pinned_pat,
5823             hir::LocalSource::AwaitDesugar,
5824         );
5825
5826         // ::std::future::poll_with_tls_context(unsafe {
5827         //     ::std::pin::Pin::new_unchecked(&mut pinned)
5828         // })`
5829         let poll_expr = {
5830             let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
5831             let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
5832             let pin_ty_id = self.next_id();
5833             let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
5834                 pin_ty_id,
5835                 span,
5836                 &[sym::pin, sym::Pin],
5837                 "new_unchecked",
5838                 hir_vec![ref_mut_pinned],
5839             );
5840             let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
5841             let unsafe_expr = self.expr_unsafe(new_unchecked);
5842             P(self.expr_call_std_path(
5843                 gen_future_span,
5844                 &[sym::future, sym::poll_with_tls_context],
5845                 hir_vec![unsafe_expr],
5846             ))
5847         };
5848
5849         // `::std::task::Poll::Ready(result) => break result`
5850         let loop_node_id = self.sess.next_node_id();
5851         let loop_hir_id = self.lower_node_id(loop_node_id);
5852         let ready_arm = {
5853             let x_ident = Ident::with_empty_ctxt(sym::result);
5854             let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
5855             let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
5856             let ready_pat = self.pat_std_enum(
5857                 span,
5858                 &[sym::task, sym::Poll, sym::Ready],
5859                 hir_vec![x_pat],
5860             );
5861             let break_x = self.with_loop_scope(loop_node_id, |this| {
5862                 let expr_break = hir::ExprKind::Break(
5863                     this.lower_loop_destination(None),
5864                     Some(x_expr),
5865                 );
5866                 P(this.expr(await_span, expr_break, ThinVec::new()))
5867             });
5868             self.arm(hir_vec![ready_pat], break_x)
5869         };
5870
5871         // `::std::task::Poll::Pending => {}`
5872         let pending_arm = {
5873             let pending_pat = self.pat_std_enum(
5874                 span,
5875                 &[sym::task, sym::Poll, sym::Pending],
5876                 hir_vec![],
5877             );
5878             let empty_block = P(self.expr_block_empty(span));
5879             self.arm(hir_vec![pending_pat], empty_block)
5880         };
5881
5882         let match_stmt = {
5883             let match_expr = P(self.expr_match(
5884                 span,
5885                 poll_expr,
5886                 hir_vec![ready_arm, pending_arm],
5887                 hir::MatchSource::AwaitDesugar,
5888             ));
5889             self.stmt(span, hir::StmtKind::Expr(match_expr))
5890         };
5891
5892         let yield_stmt = {
5893             let unit = self.expr_unit(span);
5894             let yield_expr = P(self.expr(
5895                 span,
5896                 hir::ExprKind::Yield(P(unit), hir::YieldSource::Await),
5897                 ThinVec::new(),
5898             ));
5899             self.stmt(span, hir::StmtKind::Expr(yield_expr))
5900         };
5901
5902         let loop_block = P(self.block_all(
5903             span,
5904             hir_vec![match_stmt, yield_stmt],
5905             None,
5906         ));
5907
5908         let loop_expr = P(hir::Expr {
5909             hir_id: loop_hir_id,
5910             node: hir::ExprKind::Loop(
5911                 loop_block,
5912                 None,
5913                 hir::LoopSource::Loop,
5914             ),
5915             span,
5916             attrs: ThinVec::new(),
5917         });
5918
5919         hir::ExprKind::Block(
5920             P(self.block_all(span, hir_vec![pinned_let], Some(loop_expr))),
5921             None,
5922         )
5923     }
5924 }
5925
5926 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
5927     // Sorting by span ensures that we get things in order within a
5928     // file, and also puts the files in a sensible order.
5929     let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
5930     body_ids.sort_by_key(|b| bodies[b].value.span);
5931     body_ids
5932 }
5933
5934 /// Checks if the specified expression is a built-in range literal.
5935 /// (See: `LoweringContext::lower_expr()`).
5936 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
5937     use hir::{Path, QPath, ExprKind, TyKind};
5938
5939     // Returns whether the given path represents a (desugared) range,
5940     // either in std or core, i.e. has either a `::std::ops::Range` or
5941     // `::core::ops::Range` prefix.
5942     fn is_range_path(path: &Path) -> bool {
5943         let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect();
5944         let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
5945
5946         // "{{root}}" is the equivalent of `::` prefix in `Path`.
5947         if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
5948             (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
5949         } else {
5950             false
5951         }
5952     };
5953
5954     // Check whether a span corresponding to a range expression is a
5955     // range literal, rather than an explicit struct or `new()` call.
5956     fn is_lit(sess: &Session, span: &Span) -> bool {
5957         let source_map = sess.source_map();
5958         let end_point = source_map.end_point(*span);
5959
5960         if let Ok(end_string) = source_map.span_to_snippet(end_point) {
5961             !(end_string.ends_with("}") || end_string.ends_with(")"))
5962         } else {
5963             false
5964         }
5965     };
5966
5967     match expr.node {
5968         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
5969         ExprKind::Struct(ref qpath, _, _) => {
5970             if let QPath::Resolved(None, ref path) = **qpath {
5971                 return is_range_path(&path) && is_lit(sess, &expr.span);
5972             }
5973         }
5974
5975         // `..` desugars to its struct path.
5976         ExprKind::Path(QPath::Resolved(None, ref path)) => {
5977             return is_range_path(&path) && is_lit(sess, &expr.span);
5978         }
5979
5980         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
5981         ExprKind::Call(ref func, _) => {
5982             if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
5983                 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
5984                     let new_call = segment.ident.as_str() == "new";
5985                     return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;
5986                 }
5987             }
5988         }
5989
5990         _ => {}
5991     }
5992
5993     false
5994 }