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