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