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