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