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