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