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