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