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