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