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