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