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