]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering.rs
Rename PathParameter(s) to GenericArg(s)
[rust.git] / src / librustc / hir / lowering.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Lowers the AST to the HIR.
12 //!
13 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
14 //! much like a fold. Where lowering involves a bit more work things get more
15 //! interesting and there are some invariants you should know about. These mostly
16 //! concern spans and ids.
17 //!
18 //! Spans are assigned to AST nodes during parsing and then are modified during
19 //! expansion to indicate the origin of a node and the process it went through
20 //! being expanded. Ids are assigned to AST nodes just before lowering.
21 //!
22 //! For the simpler lowering steps, ids and spans should be preserved. Unlike
23 //! expansion we do not preserve the process of lowering in the spans, so spans
24 //! should not be modified here. When creating a new node (as opposed to
25 //! 'folding' an existing one), then you create a new id using `next_id()`.
26 //!
27 //! You must ensure that ids are unique. That means that you should only use the
28 //! id from an AST node in a single HIR node (you can assume that AST node ids
29 //! are unique). Every new node must have a unique id. Avoid cloning HIR nodes.
30 //! If you do, you must then set the new node's id to a fresh one.
31 //!
32 //! Spans are used for error messages and for tools to map semantics back to
33 //! source code. It is therefore not as important with spans as ids to be strict
34 //! about use (you can't break the compiler by screwing up a span). Obviously, a
35 //! HIR node can only have a single span. But multiple nodes can have the same
36 //! span and spans don't need to be kept in order, etc. Where code is preserved
37 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
38 //! new it is probably best to give a span for the whole AST node being lowered.
39 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
40 //! get confused if the spans from leaf AST nodes occur in multiple places
41 //! in the HIR, especially for multiple identifiers.
42
43 use dep_graph::DepGraph;
44 use hir;
45 use hir::HirVec;
46 use hir::map::{DefKey, DefPathData, Definitions};
47 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
48 use hir::def::{Def, PathResolution, PerNS};
49 use hir::GenericArg;
50 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES};
51 use middle::cstore::CrateStore;
52 use rustc_data_structures::indexed_vec::IndexVec;
53 use session::Session;
54 use util::common::FN_OUTPUT_NAME;
55 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
56
57 use std::collections::{BTreeMap, HashSet};
58 use std::fmt::Debug;
59 use std::iter;
60 use std::mem;
61 use syntax::attr;
62 use syntax::ast::*;
63 use syntax::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_generic_arg(&mut self,
1042                         p: &AngleBracketedParam,
1043                         itctx: ImplTraitContext)
1044                         -> GenericArg {
1045         match p {
1046             AngleBracketedParam::Lifetime(lt) => {
1047                 GenericArg::Lifetime(self.lower_lifetime(&lt))
1048             }
1049             AngleBracketedParam::Type(ty) => {
1050                 GenericArg::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_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
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_generic_args(self, span, parameters);
1331                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1332                 } else {
1333                     hir::intravisit::walk_generic_args(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 generic_args, infer_types) =
1688             if let Some(ref generic_args) = segment.parameters {
1689             let msg = "parenthesized parameters may only be used with a trait";
1690             match **generic_args {
1691                 GenericArgs::AngleBracketed(ref data) => {
1692                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1693                 }
1694                 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1695                     ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1696                     ParenthesizedGenericArgs::Warn => {
1697                         self.sess.buffer_lint(
1698                             PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1699                             CRATE_NODE_ID,
1700                             data.span,
1701                             msg.into(),
1702                         );
1703                         (hir::GenericArgs::none(), true)
1704                     }
1705                     ParenthesizedGenericArgs::Err => {
1706                         struct_span_err!(self.sess, data.span, E0214, "{}", msg)
1707                             .span_label(data.span, "only traits may use parentheses")
1708                             .emit();
1709                         (hir::GenericArgs::none(), true)
1710                     }
1711                 },
1712             }
1713         } else {
1714             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1715         };
1716
1717         if !generic_args.parenthesized && generic_args.lifetimes().count() == 0 {
1718             generic_args.parameters = (0..expected_lifetimes).map(|_| {
1719                 GenericArg::Lifetime(self.elided_lifetime(path_span))
1720             }).chain(generic_args.parameters.into_iter()).collect();
1721         }
1722
1723         hir::PathSegment::new(
1724             self.lower_ident(segment.identifier),
1725             generic_args,
1726             infer_types
1727         )
1728     }
1729
1730     fn lower_angle_bracketed_parameter_data(
1731         &mut self,
1732         data: &AngleBracketedParameterData,
1733         param_mode: ParamMode,
1734         itctx: ImplTraitContext,
1735     ) -> (hir::GenericArgs, bool) {
1736         let &AngleBracketedParameterData { ref parameters, ref bindings, .. } = data;
1737         (hir::GenericArgs {
1738             parameters: parameters.iter().map(|p| self.lower_generic_arg(p, itctx)).collect(),
1739             bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1740             parenthesized: false,
1741         },
1742         data.types().count() == 0 && param_mode == ParamMode::Optional)
1743     }
1744
1745     fn lower_parenthesized_parameter_data(
1746         &mut self,
1747         data: &ParenthesizedParameterData,
1748     ) -> (hir::PathParameters, bool) {
1749         // Switch to `PassThrough` mode for anonymous lifetimes: this
1750         // means that we permit things like `&Ref<T>`, where `Ref` has
1751         // a hidden lifetime parameter. This is needed for backwards
1752         // compatibility, even in contexts like an impl header where
1753         // we generally don't permit such things (see #51008).
1754         self.with_anonymous_lifetime_mode(
1755             AnonymousLifetimeMode::PassThrough,
1756             |this| {
1757                 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1758                 let &ParenthesizedParameterData {
1759                     ref inputs,
1760                     ref output,
1761                     span,
1762                 } = data;
1763                 let inputs = inputs
1764                     .iter()
1765                     .map(|ty| this.lower_ty(ty, DISALLOWED))
1766                     .collect();
1767                 let mk_tup = |this: &mut Self, tys, span| {
1768                     let LoweredNodeId { node_id, hir_id } = this.next_id();
1769                     P(hir::Ty {
1770                         node: hir::TyTup(tys),
1771                         id: node_id,
1772                         hir_id,
1773                         span,
1774                     })
1775                 };
1776
1777                 (
1778                     hir::GenericArgs {
1779                         parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1780                         bindings: hir_vec![
1781                             hir::TypeBinding {
1782                                 id: this.next_id().node_id,
1783                                 name: Symbol::intern(FN_OUTPUT_NAME),
1784                                 ty: output
1785                                     .as_ref()
1786                                     .map(|ty| this.lower_ty(&ty, DISALLOWED))
1787                                     .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1788                                 span: output.as_ref().map_or(span, |ty| ty.span),
1789                             }
1790                         ],
1791                         parenthesized: true,
1792                     },
1793                     false,
1794                 )
1795             }
1796         )
1797     }
1798
1799     fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1800         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1801         P(hir::Local {
1802             id: node_id,
1803             hir_id,
1804             ty: l.ty
1805                 .as_ref()
1806                 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1807             pat: self.lower_pat(&l.pat),
1808             init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1809             span: l.span,
1810             attrs: l.attrs.clone(),
1811             source: hir::LocalSource::Normal,
1812         })
1813     }
1814
1815     fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1816         match m {
1817             Mutability::Mutable => hir::MutMutable,
1818             Mutability::Immutable => hir::MutImmutable,
1819         }
1820     }
1821
1822     fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1823         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1824         hir::Arg {
1825             id: node_id,
1826             hir_id,
1827             pat: self.lower_pat(&arg.pat),
1828         }
1829     }
1830
1831     fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1832         decl.inputs
1833             .iter()
1834             .map(|arg| match arg.pat.node {
1835                 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1836                 _ => respan(arg.pat.span, keywords::Invalid.name()),
1837             })
1838             .collect()
1839     }
1840
1841     fn lower_fn_decl(
1842         &mut self,
1843         decl: &FnDecl,
1844         fn_def_id: Option<DefId>,
1845         impl_trait_return_allow: bool,
1846     ) -> P<hir::FnDecl> {
1847         // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1848         //       then impl Trait arguments are lowered into generic parameters on the given
1849         //       fn_def_id, otherwise impl Trait is disallowed. (for now)
1850         //
1851         //       Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1852         //       return positions as well. This guards against trait declarations and their impls
1853         //       where impl Trait is disallowed. (again for now)
1854         P(hir::FnDecl {
1855             inputs: decl.inputs
1856                 .iter()
1857                 .map(|arg| {
1858                     if let Some(def_id) = fn_def_id {
1859                         self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1860                     } else {
1861                         self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1862                     }
1863                 })
1864                 .collect(),
1865             output: match decl.output {
1866                 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1867                     Some(def_id) if impl_trait_return_allow => {
1868                         hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1869                     }
1870                     _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1871                 },
1872                 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1873             },
1874             variadic: decl.variadic,
1875             has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1876                 TyKind::ImplicitSelf => true,
1877                 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1878                 _ => false,
1879             }),
1880         })
1881     }
1882
1883     fn lower_ty_param_bound(
1884         &mut self,
1885         tpb: &TyParamBound,
1886         itctx: ImplTraitContext,
1887     ) -> hir::TyParamBound {
1888         match *tpb {
1889             TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1890                 self.lower_poly_trait_ref(ty, itctx),
1891                 self.lower_trait_bound_modifier(modifier),
1892             ),
1893             RegionTyParamBound(ref lifetime) => {
1894                 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1895             }
1896         }
1897     }
1898
1899     fn lower_ty_param(
1900         &mut self,
1901         tp: &TyParam,
1902         add_bounds: &[TyParamBound],
1903         itctx: ImplTraitContext,
1904     ) -> hir::TyParam {
1905         let mut name = self.lower_ident(tp.ident);
1906
1907         // Don't expose `Self` (recovered "keyword used as ident" parse error).
1908         // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1909         // Instead, use gensym("Self") to create a distinct name that looks the same.
1910         if name == keywords::SelfType.name() {
1911             name = Symbol::gensym("Self");
1912         }
1913
1914         let mut bounds = self.lower_bounds(&tp.bounds, itctx);
1915         if !add_bounds.is_empty() {
1916             bounds = bounds
1917                 .into_iter()
1918                 .chain(self.lower_bounds(add_bounds, itctx).into_iter())
1919                 .collect();
1920         }
1921
1922         hir::TyParam {
1923             id: self.lower_node_id(tp.id).node_id,
1924             name,
1925             bounds,
1926             default: tp.default
1927                 .as_ref()
1928                 .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
1929             span: tp.ident.span,
1930             pure_wrt_drop: attr::contains_name(&tp.attrs, "may_dangle"),
1931             synthetic: tp.attrs
1932                 .iter()
1933                 .filter(|attr| attr.check_name("rustc_synthetic"))
1934                 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
1935                 .nth(0),
1936             attrs: self.lower_attrs(&tp.attrs),
1937         }
1938     }
1939
1940     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1941         let span = l.ident.span;
1942         match self.lower_ident(l.ident) {
1943             x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1944             x if x == "'_" => match self.anonymous_lifetime_mode {
1945                 AnonymousLifetimeMode::CreateParameter => {
1946                     let fresh_name = self.collect_fresh_in_band_lifetime(span);
1947                     self.new_named_lifetime(l.id, span, fresh_name)
1948                 }
1949
1950                 AnonymousLifetimeMode::PassThrough => {
1951                     self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1952                 }
1953             },
1954             name => {
1955                 self.maybe_collect_in_band_lifetime(span, name);
1956                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1957             }
1958         }
1959     }
1960
1961     fn new_named_lifetime(
1962         &mut self,
1963         id: NodeId,
1964         span: Span,
1965         name: hir::LifetimeName,
1966     ) -> hir::Lifetime {
1967         hir::Lifetime {
1968             id: self.lower_node_id(id).node_id,
1969             span,
1970             name: name,
1971         }
1972     }
1973
1974     fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
1975         let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1976         self.is_collecting_in_band_lifetimes = false;
1977
1978         let def = hir::LifetimeDef {
1979             lifetime: self.lower_lifetime(&l.lifetime),
1980             bounds: l.bounds.iter().map(|l| self.lower_lifetime(l)).collect(),
1981             pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"),
1982             in_band: false,
1983         };
1984
1985         self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1986
1987         def
1988     }
1989
1990     fn lower_generic_params(
1991         &mut self,
1992         params: &Vec<GenericParam>,
1993         add_bounds: &NodeMap<Vec<TyParamBound>>,
1994         itctx: ImplTraitContext,
1995     ) -> hir::HirVec<hir::GenericParam> {
1996         params
1997             .iter()
1998             .map(|param| match *param {
1999                 GenericParam::Lifetime(ref lifetime_def) => {
2000                     hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def))
2001                 }
2002                 GenericParam::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param(
2003                     ty_param,
2004                     add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x),
2005                     itctx,
2006                 )),
2007             })
2008             .collect()
2009     }
2010
2011     fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Generics {
2012         // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2013         // FIXME: This could probably be done with less rightward drift. Also looks like two control
2014         //        paths where report_error is called are also the only paths that advance to after
2015         //        the match statement, so the error reporting could probably just be moved there.
2016         let mut add_bounds = NodeMap();
2017         for pred in &g.where_clause.predicates {
2018             if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2019                 'next_bound: for bound in &bound_pred.bounds {
2020                     if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2021                         let report_error = |this: &mut Self| {
2022                             this.diagnostic().span_err(
2023                                 bound_pred.bounded_ty.span,
2024                                 "`?Trait` bounds are only permitted at the \
2025                                  point where a type parameter is declared",
2026                             );
2027                         };
2028                         // Check if the where clause type is a plain type parameter.
2029                         match bound_pred.bounded_ty.node {
2030                             TyKind::Path(None, ref path)
2031                                 if path.segments.len() == 1
2032                                     && bound_pred.bound_generic_params.is_empty() =>
2033                             {
2034                                 if let Some(Def::TyParam(def_id)) = self.resolver
2035                                     .get_resolution(bound_pred.bounded_ty.id)
2036                                     .map(|d| d.base_def())
2037                                 {
2038                                     if let Some(node_id) =
2039                                         self.resolver.definitions().as_local_node_id(def_id)
2040                                     {
2041                                         for param in &g.params {
2042                                             if let GenericParam::Type(ref ty_param) = *param {
2043                                                 if node_id == ty_param.id {
2044                                                     add_bounds
2045                                                         .entry(ty_param.id)
2046                                                         .or_insert(Vec::new())
2047                                                         .push(bound.clone());
2048                                                     continue 'next_bound;
2049                                                 }
2050                                             }
2051                                         }
2052                                     }
2053                                 }
2054                                 report_error(self)
2055                             }
2056                             _ => report_error(self),
2057                         }
2058                     }
2059                 }
2060             }
2061         }
2062
2063         hir::Generics {
2064             params: self.lower_generic_params(&g.params, &add_bounds, itctx),
2065             where_clause: self.lower_where_clause(&g.where_clause),
2066             span: g.span,
2067         }
2068     }
2069
2070     fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2071         hir::WhereClause {
2072             id: self.lower_node_id(wc.id).node_id,
2073             predicates: wc.predicates
2074                 .iter()
2075                 .map(|predicate| self.lower_where_predicate(predicate))
2076                 .collect(),
2077         }
2078     }
2079
2080     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2081         match *pred {
2082             WherePredicate::BoundPredicate(WhereBoundPredicate {
2083                 ref bound_generic_params,
2084                 ref bounded_ty,
2085                 ref bounds,
2086                 span,
2087             }) => {
2088                 self.with_in_scope_lifetime_defs(
2089                     bound_generic_params.iter().filter_map(|p| match p {
2090                         GenericParam::Lifetime(ld) => Some(ld),
2091                         _ => None,
2092                     }),
2093                     |this| {
2094                         hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2095                             bound_generic_params: this.lower_generic_params(
2096                                 bound_generic_params,
2097                                 &NodeMap(),
2098                                 ImplTraitContext::Disallowed,
2099                             ),
2100                             bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2101                             bounds: bounds
2102                                 .iter()
2103                                 .filter_map(|bound| match *bound {
2104                                     // Ignore `?Trait` bounds.
2105                                     // Tthey were copied into type parameters already.
2106                                     TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2107                                     _ => Some(this.lower_ty_param_bound(
2108                                         bound,
2109                                         ImplTraitContext::Disallowed,
2110                                     )),
2111                                 })
2112                                 .collect(),
2113                             span,
2114                         })
2115                     },
2116                 )
2117             }
2118             WherePredicate::RegionPredicate(WhereRegionPredicate {
2119                 ref lifetime,
2120                 ref bounds,
2121                 span,
2122             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2123                 span,
2124                 lifetime: self.lower_lifetime(lifetime),
2125                 bounds: bounds
2126                     .iter()
2127                     .map(|bound| self.lower_lifetime(bound))
2128                     .collect(),
2129             }),
2130             WherePredicate::EqPredicate(WhereEqPredicate {
2131                 id,
2132                 ref lhs_ty,
2133                 ref rhs_ty,
2134                 span,
2135             }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2136                 id: self.lower_node_id(id).node_id,
2137                 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2138                 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2139                 span,
2140             }),
2141         }
2142     }
2143
2144     fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2145         match *vdata {
2146             VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2147                 fields
2148                     .iter()
2149                     .enumerate()
2150                     .map(|f| self.lower_struct_field(f))
2151                     .collect(),
2152                 self.lower_node_id(id).node_id,
2153             ),
2154             VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2155                 fields
2156                     .iter()
2157                     .enumerate()
2158                     .map(|f| self.lower_struct_field(f))
2159                     .collect(),
2160                 self.lower_node_id(id).node_id,
2161             ),
2162             VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2163         }
2164     }
2165
2166     fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2167         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2168             hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2169             qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2170         };
2171         hir::TraitRef {
2172             path,
2173             ref_id: self.lower_node_id(p.ref_id).node_id,
2174         }
2175     }
2176
2177     fn lower_poly_trait_ref(
2178         &mut self,
2179         p: &PolyTraitRef,
2180         itctx: ImplTraitContext,
2181     ) -> hir::PolyTraitRef {
2182         let bound_generic_params =
2183             self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2184         let trait_ref = self.with_parent_impl_lifetime_defs(
2185             &bound_generic_params
2186                 .iter()
2187                 .filter_map(|p| match *p {
2188                     hir::GenericParam::Lifetime(ref ld) => Some(ld.clone()),
2189                     _ => None,
2190                 })
2191                 .collect::<Vec<_>>(),
2192             |this| this.lower_trait_ref(&p.trait_ref, itctx),
2193         );
2194
2195         hir::PolyTraitRef {
2196             bound_generic_params,
2197             trait_ref,
2198             span: p.span,
2199         }
2200     }
2201
2202     fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2203         hir::StructField {
2204             span: f.span,
2205             id: self.lower_node_id(f.id).node_id,
2206             ident: match f.ident {
2207                 Some(ident) => ident,
2208                 // FIXME(jseyfried) positional field hygiene
2209                 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2210             },
2211             vis: self.lower_visibility(&f.vis, None),
2212             ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2213             attrs: self.lower_attrs(&f.attrs),
2214         }
2215     }
2216
2217     fn lower_field(&mut self, f: &Field) -> hir::Field {
2218         hir::Field {
2219             id: self.next_id().node_id,
2220             ident: f.ident,
2221             expr: P(self.lower_expr(&f.expr)),
2222             span: f.span,
2223             is_shorthand: f.is_shorthand,
2224         }
2225     }
2226
2227     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2228         hir::MutTy {
2229             ty: self.lower_ty(&mt.ty, itctx),
2230             mutbl: self.lower_mutability(mt.mutbl),
2231         }
2232     }
2233
2234     fn lower_bounds(
2235         &mut self,
2236         bounds: &[TyParamBound],
2237         itctx: ImplTraitContext,
2238     ) -> hir::TyParamBounds {
2239         bounds
2240             .iter()
2241             .map(|bound| self.lower_ty_param_bound(bound, itctx))
2242             .collect()
2243     }
2244
2245     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2246         let mut expr = None;
2247
2248         let mut stmts = vec![];
2249
2250         for (index, stmt) in b.stmts.iter().enumerate() {
2251             if index == b.stmts.len() - 1 {
2252                 if let StmtKind::Expr(ref e) = stmt.node {
2253                     expr = Some(P(self.lower_expr(e)));
2254                 } else {
2255                     stmts.extend(self.lower_stmt(stmt));
2256                 }
2257             } else {
2258                 stmts.extend(self.lower_stmt(stmt));
2259             }
2260         }
2261
2262         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2263
2264         P(hir::Block {
2265             id: node_id,
2266             hir_id,
2267             stmts: stmts.into(),
2268             expr,
2269             rules: self.lower_block_check_mode(&b.rules),
2270             span: b.span,
2271             targeted_by_break,
2272             recovered: b.recovered,
2273         })
2274     }
2275
2276     fn lower_item_kind(
2277         &mut self,
2278         id: NodeId,
2279         name: &mut Name,
2280         attrs: &hir::HirVec<Attribute>,
2281         vis: &mut hir::Visibility,
2282         i: &ItemKind,
2283     ) -> hir::Item_ {
2284         match *i {
2285             ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2286             ItemKind::Use(ref use_tree) => {
2287                 // Start with an empty prefix
2288                 let prefix = Path {
2289                     segments: vec![],
2290                     span: use_tree.span,
2291                 };
2292
2293                 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2294             }
2295             ItemKind::Static(ref t, m, ref e) => {
2296                 let value = self.lower_body(None, |this| this.lower_expr(e));
2297                 hir::ItemStatic(
2298                     self.lower_ty(t, ImplTraitContext::Disallowed),
2299                     self.lower_mutability(m),
2300                     value,
2301                 )
2302             }
2303             ItemKind::Const(ref t, ref e) => {
2304                 let value = self.lower_body(None, |this| this.lower_expr(e));
2305                 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2306             }
2307             ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2308                 let fn_def_id = self.resolver.definitions().local_def_id(id);
2309                 self.with_new_scopes(|this| {
2310                     let body_id = this.lower_body(Some(decl), |this| {
2311                         let body = this.lower_block(body, false);
2312                         this.expr_block(body, ThinVec::new())
2313                     });
2314                     let (generics, fn_decl) = this.add_in_band_defs(
2315                         generics,
2316                         fn_def_id,
2317                         AnonymousLifetimeMode::PassThrough,
2318                         |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2319                     );
2320
2321                     hir::ItemFn(
2322                         fn_decl,
2323                         this.lower_unsafety(unsafety),
2324                         this.lower_constness(constness),
2325                         abi,
2326                         generics,
2327                         body_id,
2328                     )
2329                 })
2330             }
2331             ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2332             ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2333             ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2334             ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2335                 self.lower_ty(t, ImplTraitContext::Disallowed),
2336                 self.lower_generics(generics, ImplTraitContext::Disallowed),
2337             ),
2338             ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2339                 hir::EnumDef {
2340                     variants: enum_definition
2341                         .variants
2342                         .iter()
2343                         .map(|x| self.lower_variant(x))
2344                         .collect(),
2345                 },
2346                 self.lower_generics(generics, ImplTraitContext::Disallowed),
2347             ),
2348             ItemKind::Struct(ref struct_def, ref generics) => {
2349                 let struct_def = self.lower_variant_data(struct_def);
2350                 hir::ItemStruct(
2351                     struct_def,
2352                     self.lower_generics(generics, ImplTraitContext::Disallowed),
2353                 )
2354             }
2355             ItemKind::Union(ref vdata, ref generics) => {
2356                 let vdata = self.lower_variant_data(vdata);
2357                 hir::ItemUnion(
2358                     vdata,
2359                     self.lower_generics(generics, ImplTraitContext::Disallowed),
2360                 )
2361             }
2362             ItemKind::Impl(
2363                 unsafety,
2364                 polarity,
2365                 defaultness,
2366                 ref ast_generics,
2367                 ref trait_ref,
2368                 ref ty,
2369                 ref impl_items,
2370             ) => {
2371                 let def_id = self.resolver.definitions().local_def_id(id);
2372
2373                 // Lower the "impl header" first. This ordering is important
2374                 // for in-band lifetimes! Consider `'a` here:
2375                 //
2376                 //     impl Foo<'a> for u32 {
2377                 //         fn method(&'a self) { .. }
2378                 //     }
2379                 //
2380                 // Because we start by lowering the `Foo<'a> for u32`
2381                 // part, we will add `'a` to the list of generics on
2382                 // the impl. When we then encounter it later in the
2383                 // method, it will not be considered an in-band
2384                 // lifetime to be added, but rather a reference to a
2385                 // parent lifetime.
2386                 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2387                     ast_generics,
2388                     def_id,
2389                     AnonymousLifetimeMode::CreateParameter,
2390                     |this| {
2391                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2392                             this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2393                         });
2394
2395                         if let Some(ref trait_ref) = trait_ref {
2396                             if let Def::Trait(def_id) = trait_ref.path.def {
2397                                 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2398                             }
2399                         }
2400
2401                         let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2402
2403                         (trait_ref, lowered_ty)
2404                     },
2405                 );
2406
2407                 let new_impl_items = self.with_in_scope_lifetime_defs(
2408                     ast_generics.params.iter().filter_map(|p| match p {
2409                         GenericParam::Lifetime(ld) => Some(ld),
2410                         _ => None,
2411                     }),
2412                     |this| {
2413                         impl_items
2414                             .iter()
2415                             .map(|item| this.lower_impl_item_ref(item))
2416                             .collect()
2417                     },
2418                 );
2419
2420                 hir::ItemImpl(
2421                     self.lower_unsafety(unsafety),
2422                     self.lower_impl_polarity(polarity),
2423                     self.lower_defaultness(defaultness, true /* [1] */),
2424                     generics,
2425                     trait_ref,
2426                     lowered_ty,
2427                     new_impl_items,
2428                 )
2429             }
2430             ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2431                 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2432                 let items = items
2433                     .iter()
2434                     .map(|item| self.lower_trait_item_ref(item))
2435                     .collect();
2436                 hir::ItemTrait(
2437                     self.lower_is_auto(is_auto),
2438                     self.lower_unsafety(unsafety),
2439                     self.lower_generics(generics, ImplTraitContext::Disallowed),
2440                     bounds,
2441                     items,
2442                 )
2443             }
2444             ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2445                 self.lower_generics(generics, ImplTraitContext::Disallowed),
2446                 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2447             ),
2448             ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2449         }
2450
2451         // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2452         //     not cause an assertion failure inside the `lower_defaultness` function
2453     }
2454
2455     fn lower_use_tree(
2456         &mut self,
2457         tree: &UseTree,
2458         prefix: &Path,
2459         id: NodeId,
2460         vis: &mut hir::Visibility,
2461         name: &mut Name,
2462         attrs: &hir::HirVec<Attribute>,
2463     ) -> hir::Item_ {
2464         let path = &tree.prefix;
2465
2466         match tree.kind {
2467             UseTreeKind::Simple(rename, id1, id2) => {
2468                 *name = tree.ident().name;
2469
2470                 // First apply the prefix to the path
2471                 let mut path = Path {
2472                     segments: prefix
2473                         .segments
2474                         .iter()
2475                         .chain(path.segments.iter())
2476                         .cloned()
2477                         .collect(),
2478                     span: path.span,
2479                 };
2480
2481                 // Correctly resolve `self` imports
2482                 if path.segments.len() > 1
2483                     && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2484                 {
2485                     let _ = path.segments.pop();
2486                     if rename.is_none() {
2487                         *name = path.segments.last().unwrap().ident.name;
2488                     }
2489                 }
2490
2491                 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2492                 let mut defs = self.expect_full_def_from_use(id);
2493                 // we want to return *something* from this function, so hang onto the first item
2494                 // for later
2495                 let mut ret_def = defs.next().unwrap_or(Def::Err);
2496
2497                 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2498                     let vis = vis.clone();
2499                     let name = name.clone();
2500                     let span = path.span;
2501                     self.resolver.definitions().create_def_with_parent(
2502                         parent_def_index,
2503                         new_node_id,
2504                         DefPathData::Misc,
2505                         DefIndexAddressSpace::High,
2506                         Mark::root(),
2507                         span);
2508                     self.allocate_hir_id_counter(new_node_id, &path);
2509
2510                     self.with_hir_id_owner(new_node_id, |this| {
2511                         let new_id = this.lower_node_id(new_node_id);
2512                         let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2513                         let item = hir::ItemUse(P(path), hir::UseKind::Single);
2514                         let vis = match vis {
2515                             hir::Visibility::Public => hir::Visibility::Public,
2516                             hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2517                             hir::Visibility::Inherited => hir::Visibility::Inherited,
2518                             hir::Visibility::Restricted { ref path, id: _ } => {
2519                                 hir::Visibility::Restricted {
2520                                     path: path.clone(),
2521                                     // We are allocating a new NodeId here
2522                                     id: this.next_id().node_id,
2523                                 }
2524                             }
2525                         };
2526
2527                         this.items.insert(
2528                             new_id.node_id,
2529                             hir::Item {
2530                                 id: new_id.node_id,
2531                                 hir_id: new_id.hir_id,
2532                                 name: name,
2533                                 attrs: attrs.clone(),
2534                                 node: item,
2535                                 vis,
2536                                 span,
2537                             },
2538                         );
2539                     });
2540                 }
2541
2542                 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2543                 hir::ItemUse(path, hir::UseKind::Single)
2544             }
2545             UseTreeKind::Glob => {
2546                 let path = P(self.lower_path(
2547                     id,
2548                     &Path {
2549                         segments: prefix
2550                             .segments
2551                             .iter()
2552                             .chain(path.segments.iter())
2553                             .cloned()
2554                             .collect(),
2555                         span: path.span,
2556                     },
2557                     ParamMode::Explicit,
2558                 ));
2559                 hir::ItemUse(path, hir::UseKind::Glob)
2560             }
2561             UseTreeKind::Nested(ref trees) => {
2562                 let prefix = Path {
2563                     segments: prefix
2564                         .segments
2565                         .iter()
2566                         .chain(path.segments.iter())
2567                         .cloned()
2568                         .collect(),
2569                     span: prefix.span.to(path.span),
2570                 };
2571
2572                 // Add all the nested PathListItems in the HIR
2573                 for &(ref use_tree, id) in trees {
2574                     self.allocate_hir_id_counter(id, &use_tree);
2575                     let LoweredNodeId {
2576                         node_id: new_id,
2577                         hir_id: new_hir_id,
2578                     } = self.lower_node_id(id);
2579
2580                     let mut vis = vis.clone();
2581                     let mut name = name.clone();
2582                     let item =
2583                         self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2584
2585                     self.with_hir_id_owner(new_id, |this| {
2586                         let vis = match vis {
2587                             hir::Visibility::Public => hir::Visibility::Public,
2588                             hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2589                             hir::Visibility::Inherited => hir::Visibility::Inherited,
2590                             hir::Visibility::Restricted { ref path, id: _ } => {
2591                                 hir::Visibility::Restricted {
2592                                     path: path.clone(),
2593                                     // We are allocating a new NodeId here
2594                                     id: this.next_id().node_id,
2595                                 }
2596                             }
2597                         };
2598
2599                         this.items.insert(
2600                             new_id,
2601                             hir::Item {
2602                                 id: new_id,
2603                                 hir_id: new_hir_id,
2604                                 name: name,
2605                                 attrs: attrs.clone(),
2606                                 node: item,
2607                                 vis,
2608                                 span: use_tree.span,
2609                             },
2610                         );
2611                     });
2612                 }
2613
2614                 // Privatize the degenerate import base, used only to check
2615                 // the stability of `use a::{};`, to avoid it showing up as
2616                 // a re-export by accident when `pub`, e.g. in documentation.
2617                 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2618                 *vis = hir::Inherited;
2619                 hir::ItemUse(path, hir::UseKind::ListStem)
2620             }
2621         }
2622     }
2623
2624     fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2625         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2626         let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2627
2628         let (generics, node) = match i.node {
2629             TraitItemKind::Const(ref ty, ref default) => (
2630                 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2631                 hir::TraitItemKind::Const(
2632                     self.lower_ty(ty, ImplTraitContext::Disallowed),
2633                     default
2634                         .as_ref()
2635                         .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2636                 ),
2637             ),
2638             TraitItemKind::Method(ref sig, None) => {
2639                 let names = self.lower_fn_args_to_names(&sig.decl);
2640                 self.add_in_band_defs(
2641                     &i.generics,
2642                     trait_item_def_id,
2643                     AnonymousLifetimeMode::PassThrough,
2644                     |this| {
2645                         hir::TraitItemKind::Method(
2646                             this.lower_method_sig(sig, trait_item_def_id, false),
2647                             hir::TraitMethod::Required(names),
2648                         )
2649                     },
2650                 )
2651             }
2652             TraitItemKind::Method(ref sig, Some(ref body)) => {
2653                 let body_id = self.lower_body(Some(&sig.decl), |this| {
2654                     let body = this.lower_block(body, false);
2655                     this.expr_block(body, ThinVec::new())
2656                 });
2657
2658                 self.add_in_band_defs(
2659                     &i.generics,
2660                     trait_item_def_id,
2661                     AnonymousLifetimeMode::PassThrough,
2662                     |this| {
2663                         hir::TraitItemKind::Method(
2664                             this.lower_method_sig(sig, trait_item_def_id, false),
2665                             hir::TraitMethod::Provided(body_id),
2666                         )
2667                     },
2668                 )
2669             }
2670             TraitItemKind::Type(ref bounds, ref default) => (
2671                 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2672                 hir::TraitItemKind::Type(
2673                     self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2674                     default
2675                         .as_ref()
2676                         .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2677                 ),
2678             ),
2679             TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2680         };
2681
2682         hir::TraitItem {
2683             id: node_id,
2684             hir_id,
2685             name: self.lower_ident(i.ident),
2686             attrs: self.lower_attrs(&i.attrs),
2687             generics,
2688             node,
2689             span: i.span,
2690         }
2691     }
2692
2693     fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2694         let (kind, has_default) = match i.node {
2695             TraitItemKind::Const(_, ref default) => {
2696                 (hir::AssociatedItemKind::Const, default.is_some())
2697             }
2698             TraitItemKind::Type(_, ref default) => {
2699                 (hir::AssociatedItemKind::Type, default.is_some())
2700             }
2701             TraitItemKind::Method(ref sig, ref default) => (
2702                 hir::AssociatedItemKind::Method {
2703                     has_self: sig.decl.has_self(),
2704                 },
2705                 default.is_some(),
2706             ),
2707             TraitItemKind::Macro(..) => unimplemented!(),
2708         };
2709         hir::TraitItemRef {
2710             id: hir::TraitItemId { node_id: i.id },
2711             name: self.lower_ident(i.ident),
2712             span: i.span,
2713             defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2714             kind,
2715         }
2716     }
2717
2718     fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2719         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2720         let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2721
2722         let (generics, node) = match i.node {
2723             ImplItemKind::Const(ref ty, ref expr) => {
2724                 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2725                 (
2726                     self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2727                     hir::ImplItemKind::Const(
2728                         self.lower_ty(ty, ImplTraitContext::Disallowed),
2729                         body_id,
2730                     ),
2731                 )
2732             }
2733             ImplItemKind::Method(ref sig, ref body) => {
2734                 let body_id = self.lower_body(Some(&sig.decl), |this| {
2735                     let body = this.lower_block(body, false);
2736                     this.expr_block(body, ThinVec::new())
2737                 });
2738                 let impl_trait_return_allow = !self.is_in_trait_impl;
2739
2740                 self.add_in_band_defs(
2741                     &i.generics,
2742                     impl_item_def_id,
2743                     AnonymousLifetimeMode::PassThrough,
2744                     |this| {
2745                         hir::ImplItemKind::Method(
2746                             this.lower_method_sig(
2747                                 sig,
2748                                 impl_item_def_id,
2749                                 impl_trait_return_allow,
2750                             ),
2751                             body_id,
2752                         )
2753                     },
2754                 )
2755             }
2756             ImplItemKind::Type(ref ty) => (
2757                 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2758                 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2759             ),
2760             ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2761         };
2762
2763         hir::ImplItem {
2764             id: node_id,
2765             hir_id,
2766             name: self.lower_ident(i.ident),
2767             attrs: self.lower_attrs(&i.attrs),
2768             generics,
2769             vis: self.lower_visibility(&i.vis, None),
2770             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2771             node,
2772             span: i.span,
2773         }
2774
2775         // [1] since `default impl` is not yet implemented, this is always true in impls
2776     }
2777
2778     fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2779         hir::ImplItemRef {
2780             id: hir::ImplItemId { node_id: i.id },
2781             name: self.lower_ident(i.ident),
2782             span: i.span,
2783             vis: self.lower_visibility(&i.vis, Some(i.id)),
2784             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2785             kind: match i.node {
2786                 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2787                 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2788                 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2789                     has_self: sig.decl.has_self(),
2790                 },
2791                 ImplItemKind::Macro(..) => unimplemented!(),
2792             },
2793         }
2794
2795         // [1] since `default impl` is not yet implemented, this is always true in impls
2796     }
2797
2798     fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2799         hir::Mod {
2800             inner: m.inner,
2801             item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2802         }
2803     }
2804
2805     fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2806         match i.node {
2807             ItemKind::Use(ref use_tree) => {
2808                 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2809                 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2810                 return vec;
2811             }
2812             ItemKind::MacroDef(..) => return SmallVector::new(),
2813             _ => {}
2814         }
2815         SmallVector::one(hir::ItemId { id: i.id })
2816     }
2817
2818     fn lower_item_id_use_tree(&mut self,
2819                               tree: &UseTree,
2820                               base_id: NodeId,
2821                               vec: &mut SmallVector<hir::ItemId>)
2822     {
2823         match tree.kind {
2824             UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2825                 vec.push(hir::ItemId { id });
2826                 self.lower_item_id_use_tree(nested, id, vec);
2827             },
2828             UseTreeKind::Glob => {}
2829             UseTreeKind::Simple(_, id1, id2) => {
2830                 for (_, &id) in self.expect_full_def_from_use(base_id)
2831                                     .skip(1)
2832                                     .zip([id1, id2].iter())
2833                 {
2834                     vec.push(hir::ItemId { id });
2835                 }
2836             },
2837         }
2838     }
2839
2840     pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2841         let mut name = i.ident.name;
2842         let mut vis = self.lower_visibility(&i.vis, None);
2843         let attrs = self.lower_attrs(&i.attrs);
2844         if let ItemKind::MacroDef(ref def) = i.node {
2845             if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2846                 let body = self.lower_token_stream(def.stream());
2847                 self.exported_macros.push(hir::MacroDef {
2848                     name,
2849                     vis,
2850                     attrs,
2851                     id: i.id,
2852                     span: i.span,
2853                     body,
2854                     legacy: def.legacy,
2855                 });
2856             }
2857             return None;
2858         }
2859
2860         let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2861
2862         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2863
2864         Some(hir::Item {
2865             id: node_id,
2866             hir_id,
2867             name,
2868             attrs,
2869             node,
2870             vis,
2871             span: i.span,
2872         })
2873     }
2874
2875     fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2876         let node_id = self.lower_node_id(i.id).node_id;
2877         let def_id = self.resolver.definitions().local_def_id(node_id);
2878         hir::ForeignItem {
2879             id: node_id,
2880             name: i.ident.name,
2881             attrs: self.lower_attrs(&i.attrs),
2882             node: match i.node {
2883                 ForeignItemKind::Fn(ref fdec, ref generics) => {
2884                     let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2885                         generics,
2886                         def_id,
2887                         AnonymousLifetimeMode::PassThrough,
2888                         |this| {
2889                             (
2890                                 // Disallow impl Trait in foreign items
2891                                 this.lower_fn_decl(fdec, None, false),
2892                                 this.lower_fn_args_to_names(fdec),
2893                             )
2894                         },
2895                     );
2896
2897                     hir::ForeignItemFn(fn_dec, fn_args, generics)
2898                 }
2899                 ForeignItemKind::Static(ref t, m) => {
2900                     hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2901                 }
2902                 ForeignItemKind::Ty => hir::ForeignItemType,
2903                 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2904             },
2905             vis: self.lower_visibility(&i.vis, None),
2906             span: i.span,
2907         }
2908     }
2909
2910     fn lower_method_sig(
2911         &mut self,
2912         sig: &MethodSig,
2913         fn_def_id: DefId,
2914         impl_trait_return_allow: bool,
2915     ) -> hir::MethodSig {
2916         hir::MethodSig {
2917             abi: sig.abi,
2918             unsafety: self.lower_unsafety(sig.unsafety),
2919             constness: self.lower_constness(sig.constness),
2920             decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2921         }
2922     }
2923
2924     fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2925         match a {
2926             IsAuto::Yes => hir::IsAuto::Yes,
2927             IsAuto::No => hir::IsAuto::No,
2928         }
2929     }
2930
2931     fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2932         match u {
2933             Unsafety::Unsafe => hir::Unsafety::Unsafe,
2934             Unsafety::Normal => hir::Unsafety::Normal,
2935         }
2936     }
2937
2938     fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2939         match c.node {
2940             Constness::Const => hir::Constness::Const,
2941             Constness::NotConst => hir::Constness::NotConst,
2942         }
2943     }
2944
2945     fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2946         match u {
2947             UnOp::Deref => hir::UnDeref,
2948             UnOp::Not => hir::UnNot,
2949             UnOp::Neg => hir::UnNeg,
2950         }
2951     }
2952
2953     fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2954         Spanned {
2955             node: match b.node {
2956                 BinOpKind::Add => hir::BiAdd,
2957                 BinOpKind::Sub => hir::BiSub,
2958                 BinOpKind::Mul => hir::BiMul,
2959                 BinOpKind::Div => hir::BiDiv,
2960                 BinOpKind::Rem => hir::BiRem,
2961                 BinOpKind::And => hir::BiAnd,
2962                 BinOpKind::Or => hir::BiOr,
2963                 BinOpKind::BitXor => hir::BiBitXor,
2964                 BinOpKind::BitAnd => hir::BiBitAnd,
2965                 BinOpKind::BitOr => hir::BiBitOr,
2966                 BinOpKind::Shl => hir::BiShl,
2967                 BinOpKind::Shr => hir::BiShr,
2968                 BinOpKind::Eq => hir::BiEq,
2969                 BinOpKind::Lt => hir::BiLt,
2970                 BinOpKind::Le => hir::BiLe,
2971                 BinOpKind::Ne => hir::BiNe,
2972                 BinOpKind::Ge => hir::BiGe,
2973                 BinOpKind::Gt => hir::BiGt,
2974             },
2975             span: b.span,
2976         }
2977     }
2978
2979     fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2980         let node = match p.node {
2981             PatKind::Wild => hir::PatKind::Wild,
2982             PatKind::Ident(ref binding_mode, ident, ref sub) => {
2983                 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
2984                     // `None` can occur in body-less function signatures
2985                     def @ None | def @ Some(Def::Local(_)) => {
2986                         let canonical_id = match def {
2987                             Some(Def::Local(id)) => id,
2988                             _ => p.id,
2989                         };
2990                         hir::PatKind::Binding(
2991                             self.lower_binding_mode(binding_mode),
2992                             canonical_id,
2993                             respan(ident.span, ident.name),
2994                             sub.as_ref().map(|x| self.lower_pat(x)),
2995                         )
2996                     }
2997                     Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
2998                         None,
2999                         P(hir::Path {
3000                             span: ident.span,
3001                             def,
3002                             segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3003                         }),
3004                     )),
3005                 }
3006             }
3007             PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3008             PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3009                 let qpath = self.lower_qpath(
3010                     p.id,
3011                     &None,
3012                     path,
3013                     ParamMode::Optional,
3014                     ImplTraitContext::Disallowed,
3015                 );
3016                 hir::PatKind::TupleStruct(
3017                     qpath,
3018                     pats.iter().map(|x| self.lower_pat(x)).collect(),
3019                     ddpos,
3020                 )
3021             }
3022             PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3023                 p.id,
3024                 qself,
3025                 path,
3026                 ParamMode::Optional,
3027                 ImplTraitContext::Disallowed,
3028             )),
3029             PatKind::Struct(ref path, ref fields, etc) => {
3030                 let qpath = self.lower_qpath(
3031                     p.id,
3032                     &None,
3033                     path,
3034                     ParamMode::Optional,
3035                     ImplTraitContext::Disallowed,
3036                 );
3037
3038                 let fs = fields
3039                     .iter()
3040                     .map(|f| Spanned {
3041                         span: f.span,
3042                         node: hir::FieldPat {
3043                             id: self.next_id().node_id,
3044                             ident: f.node.ident,
3045                             pat: self.lower_pat(&f.node.pat),
3046                             is_shorthand: f.node.is_shorthand,
3047                         },
3048                     })
3049                     .collect();
3050                 hir::PatKind::Struct(qpath, fs, etc)
3051             }
3052             PatKind::Tuple(ref elts, ddpos) => {
3053                 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3054             }
3055             PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3056             PatKind::Ref(ref inner, mutbl) => {
3057                 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3058             }
3059             PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3060                 P(self.lower_expr(e1)),
3061                 P(self.lower_expr(e2)),
3062                 self.lower_range_end(end),
3063             ),
3064             PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3065                 before.iter().map(|x| self.lower_pat(x)).collect(),
3066                 slice.as_ref().map(|x| self.lower_pat(x)),
3067                 after.iter().map(|x| self.lower_pat(x)).collect(),
3068             ),
3069             PatKind::Paren(ref inner) => return self.lower_pat(inner),
3070             PatKind::Mac(_) => panic!("Shouldn't exist here"),
3071         };
3072
3073         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3074         P(hir::Pat {
3075             id: node_id,
3076             hir_id,
3077             node,
3078             span: p.span,
3079         })
3080     }
3081
3082     fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3083         match *e {
3084             RangeEnd::Included(_) => hir::RangeEnd::Included,
3085             RangeEnd::Excluded => hir::RangeEnd::Excluded,
3086         }
3087     }
3088
3089     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3090         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3091
3092         hir::AnonConst {
3093             id: node_id,
3094             hir_id,
3095             body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3096         }
3097     }
3098
3099     fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3100         let kind = match e.node {
3101             ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3102             ExprKind::ObsoleteInPlace(..) => {
3103                 self.sess.abort_if_errors();
3104                 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3105             }
3106             ExprKind::Array(ref exprs) => {
3107                 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3108             }
3109             ExprKind::Repeat(ref expr, ref count) => {
3110                 let expr = P(self.lower_expr(expr));
3111                 let count = self.lower_anon_const(count);
3112                 hir::ExprRepeat(expr, count)
3113             }
3114             ExprKind::Tup(ref elts) => {
3115                 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3116             }
3117             ExprKind::Call(ref f, ref args) => {
3118                 let f = P(self.lower_expr(f));
3119                 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3120             }
3121             ExprKind::MethodCall(ref seg, ref args) => {
3122                 let hir_seg = self.lower_path_segment(
3123                     e.span,
3124                     seg,
3125                     ParamMode::Optional,
3126                     0,
3127                     ParenthesizedGenericArgs::Err,
3128                     ImplTraitContext::Disallowed,
3129                 );
3130                 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3131                 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3132             }
3133             ExprKind::Binary(binop, ref lhs, ref rhs) => {
3134                 let binop = self.lower_binop(binop);
3135                 let lhs = P(self.lower_expr(lhs));
3136                 let rhs = P(self.lower_expr(rhs));
3137                 hir::ExprBinary(binop, lhs, rhs)
3138             }
3139             ExprKind::Unary(op, ref ohs) => {
3140                 let op = self.lower_unop(op);
3141                 let ohs = P(self.lower_expr(ohs));
3142                 hir::ExprUnary(op, ohs)
3143             }
3144             ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3145             ExprKind::Cast(ref expr, ref ty) => {
3146                 let expr = P(self.lower_expr(expr));
3147                 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3148             }
3149             ExprKind::Type(ref expr, ref ty) => {
3150                 let expr = P(self.lower_expr(expr));
3151                 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3152             }
3153             ExprKind::AddrOf(m, ref ohs) => {
3154                 let m = self.lower_mutability(m);
3155                 let ohs = P(self.lower_expr(ohs));
3156                 hir::ExprAddrOf(m, ohs)
3157             }
3158             // More complicated than you might expect because the else branch
3159             // might be `if let`.
3160             ExprKind::If(ref cond, ref blk, ref else_opt) => {
3161                 let else_opt = else_opt.as_ref().map(|els| {
3162                     match els.node {
3163                         ExprKind::IfLet(..) => {
3164                             // wrap the if-let expr in a block
3165                             let span = els.span;
3166                             let els = P(self.lower_expr(els));
3167                             let LoweredNodeId { node_id, hir_id } = self.next_id();
3168                             let blk = P(hir::Block {
3169                                 stmts: hir_vec![],
3170                                 expr: Some(els),
3171                                 id: node_id,
3172                                 hir_id,
3173                                 rules: hir::DefaultBlock,
3174                                 span,
3175                                 targeted_by_break: false,
3176                                 recovered: blk.recovered,
3177                             });
3178                             P(self.expr_block(blk, ThinVec::new()))
3179                         }
3180                         _ => P(self.lower_expr(els)),
3181                     }
3182                 });
3183
3184                 let then_blk = self.lower_block(blk, false);
3185                 let then_expr = self.expr_block(then_blk, ThinVec::new());
3186
3187                 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3188             }
3189             ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3190                 hir::ExprWhile(
3191                     this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3192                     this.lower_block(body, false),
3193                     this.lower_label(opt_label),
3194                 )
3195             }),
3196             ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3197                 hir::ExprLoop(
3198                     this.lower_block(body, false),
3199                     this.lower_label(opt_label),
3200                     hir::LoopSource::Loop,
3201                 )
3202             }),
3203             ExprKind::Catch(ref body) => {
3204                 self.with_catch_scope(body.id, |this| {
3205                     let unstable_span =
3206                         this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3207                     let mut block = this.lower_block(body, true).into_inner();
3208                     let tail = block.expr.take().map_or_else(
3209                         || {
3210                             let LoweredNodeId { node_id, hir_id } = this.next_id();
3211                             let span = this.sess.codemap().end_point(unstable_span);
3212                             hir::Expr {
3213                                 id: node_id,
3214                                 span,
3215                                 node: hir::ExprTup(hir_vec![]),
3216                                 attrs: ThinVec::new(),
3217                                 hir_id,
3218                             }
3219                         },
3220                         |x: P<hir::Expr>| x.into_inner(),
3221                     );
3222                     block.expr = Some(this.wrap_in_try_constructor(
3223                         "from_ok", tail, unstable_span));
3224                     hir::ExprBlock(P(block), None)
3225                 })
3226             }
3227             ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3228                 P(self.lower_expr(expr)),
3229                 arms.iter().map(|x| self.lower_arm(x)).collect(),
3230                 hir::MatchSource::Normal,
3231             ),
3232             ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3233                 self.with_new_scopes(|this| {
3234                     let mut is_generator = false;
3235                     let body_id = this.lower_body(Some(decl), |this| {
3236                         let e = this.lower_expr(body);
3237                         is_generator = this.is_generator;
3238                         e
3239                     });
3240                     let generator_option = if is_generator {
3241                         if !decl.inputs.is_empty() {
3242                             span_err!(
3243                                 this.sess,
3244                                 fn_decl_span,
3245                                 E0628,
3246                                 "generators cannot have explicit arguments"
3247                             );
3248                             this.sess.abort_if_errors();
3249                         }
3250                         Some(match movability {
3251                             Movability::Movable => hir::GeneratorMovability::Movable,
3252                             Movability::Static => hir::GeneratorMovability::Static,
3253                         })
3254                     } else {
3255                         if movability == Movability::Static {
3256                             span_err!(
3257                                 this.sess,
3258                                 fn_decl_span,
3259                                 E0697,
3260                                 "closures cannot be static"
3261                             );
3262                         }
3263                         None
3264                     };
3265                     hir::ExprClosure(
3266                         this.lower_capture_clause(capture_clause),
3267                         this.lower_fn_decl(decl, None, false),
3268                         body_id,
3269                         fn_decl_span,
3270                         generator_option,
3271                     )
3272                 })
3273             }
3274             ExprKind::Block(ref blk, opt_label) => {
3275                 hir::ExprBlock(self.lower_block(blk,
3276                                                 opt_label.is_some()),
3277                                                 self.lower_label(opt_label))
3278             }
3279             ExprKind::Assign(ref el, ref er) => {
3280                 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3281             }
3282             ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3283                 self.lower_binop(op),
3284                 P(self.lower_expr(el)),
3285                 P(self.lower_expr(er)),
3286             ),
3287             ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3288             ExprKind::Index(ref el, ref er) => {
3289                 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3290             }
3291             // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3292             ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3293                 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3294                 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3295                 let id = self.next_id();
3296                 let e1 = self.lower_expr(e1);
3297                 let e2 = self.lower_expr(e2);
3298                 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3299                 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3300                 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3301                 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3302                 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3303                 hir::ExprCall(new, hir_vec![e1, e2])
3304             }
3305             ExprKind::Range(ref e1, ref e2, lims) => {
3306                 use syntax::ast::RangeLimits::*;
3307
3308                 let path = match (e1, e2, lims) {
3309                     (&None, &None, HalfOpen) => "RangeFull",
3310                     (&Some(..), &None, HalfOpen) => "RangeFrom",
3311                     (&None, &Some(..), HalfOpen) => "RangeTo",
3312                     (&Some(..), &Some(..), HalfOpen) => "Range",
3313                     (&None, &Some(..), Closed) => "RangeToInclusive",
3314                     (&Some(..), &Some(..), Closed) => unreachable!(),
3315                     (_, &None, Closed) => self.diagnostic()
3316                         .span_fatal(e.span, "inclusive range with no end")
3317                         .raise(),
3318                 };
3319
3320                 let fields = e1.iter()
3321                     .map(|e| ("start", e))
3322                     .chain(e2.iter().map(|e| ("end", e)))
3323                     .map(|(s, e)| {
3324                         let expr = P(self.lower_expr(&e));
3325                         let unstable_span =
3326                             self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3327                         let ident = Ident::new(Symbol::intern(s), unstable_span);
3328                         self.field(ident, expr, unstable_span)
3329                     })
3330                     .collect::<P<[hir::Field]>>();
3331
3332                 let is_unit = fields.is_empty();
3333                 let unstable_span =
3334                     self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3335                 let struct_path = iter::once("ops")
3336                     .chain(iter::once(path))
3337                     .collect::<Vec<_>>();
3338                 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3339                 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3340
3341                 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3342
3343                 return hir::Expr {
3344                     id: node_id,
3345                     hir_id,
3346                     node: if is_unit {
3347                         hir::ExprPath(struct_path)
3348                     } else {
3349                         hir::ExprStruct(struct_path, fields, None)
3350                     },
3351                     span: unstable_span,
3352                     attrs: e.attrs.clone(),
3353                 };
3354             }
3355             ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3356                 e.id,
3357                 qself,
3358                 path,
3359                 ParamMode::Optional,
3360                 ImplTraitContext::Disallowed,
3361             )),
3362             ExprKind::Break(opt_label, ref opt_expr) => {
3363                 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3364                     hir::Destination {
3365                         label: None,
3366                         target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3367                     }
3368                 } else {
3369                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3370                 };
3371                 hir::ExprBreak(
3372                     destination,
3373                     opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3374                 )
3375             }
3376             ExprKind::Continue(opt_label) => {
3377                 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3378                     hir::Destination {
3379                         label: None,
3380                         target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3381                     }
3382                 } else {
3383                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3384                 })
3385             }
3386             ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3387             ExprKind::InlineAsm(ref asm) => {
3388                 let hir_asm = hir::InlineAsm {
3389                     inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3390                     outputs: asm.outputs
3391                         .iter()
3392                         .map(|out| hir::InlineAsmOutput {
3393                             constraint: out.constraint.clone(),
3394                             is_rw: out.is_rw,
3395                             is_indirect: out.is_indirect,
3396                         })
3397                         .collect(),
3398                     asm: asm.asm.clone(),
3399                     asm_str_style: asm.asm_str_style,
3400                     clobbers: asm.clobbers.clone().into(),
3401                     volatile: asm.volatile,
3402                     alignstack: asm.alignstack,
3403                     dialect: asm.dialect,
3404                     ctxt: asm.ctxt,
3405                 };
3406                 let outputs = asm.outputs
3407                     .iter()
3408                     .map(|out| self.lower_expr(&out.expr))
3409                     .collect();
3410                 let inputs = asm.inputs
3411                     .iter()
3412                     .map(|&(_, ref input)| self.lower_expr(input))
3413                     .collect();
3414                 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3415             }
3416             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3417                 self.lower_qpath(
3418                     e.id,
3419                     &None,
3420                     path,
3421                     ParamMode::Optional,
3422                     ImplTraitContext::Disallowed,
3423                 ),
3424                 fields.iter().map(|x| self.lower_field(x)).collect(),
3425                 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3426             ),
3427             ExprKind::Paren(ref ex) => {
3428                 let mut ex = self.lower_expr(ex);
3429                 // include parens in span, but only if it is a super-span.
3430                 if e.span.contains(ex.span) {
3431                     ex.span = e.span;
3432                 }
3433                 // merge attributes into the inner expression.
3434                 let mut attrs = e.attrs.clone();
3435                 attrs.extend::<Vec<_>>(ex.attrs.into());
3436                 ex.attrs = attrs;
3437                 return ex;
3438             }
3439
3440             ExprKind::Yield(ref opt_expr) => {
3441                 self.is_generator = true;
3442                 let expr = opt_expr
3443                     .as_ref()
3444                     .map(|x| self.lower_expr(x))
3445                     .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3446                 hir::ExprYield(P(expr))
3447             }
3448
3449             // Desugar ExprIfLet
3450             // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3451             ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3452                 // to:
3453                 //
3454                 //   match <sub_expr> {
3455                 //     <pat> => <body>,
3456                 //     _ => [<else_opt> | ()]
3457                 //   }
3458
3459                 let mut arms = vec![];
3460
3461                 // `<pat> => <body>`
3462                 {
3463                     let body = self.lower_block(body, false);
3464                     let body_expr = P(self.expr_block(body, ThinVec::new()));
3465                     let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3466                     arms.push(self.arm(pats, body_expr));
3467                 }
3468
3469                 // _ => [<else_opt>|()]
3470                 {
3471                     let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3472                     let wildcard_pattern = self.pat_wild(e.span);
3473                     let body = if let Some(else_expr) = wildcard_arm {
3474                         P(self.lower_expr(else_expr))
3475                     } else {
3476                         self.expr_tuple(e.span, hir_vec![])
3477                     };
3478                     arms.push(self.arm(hir_vec![wildcard_pattern], body));
3479                 }
3480
3481                 let contains_else_clause = else_opt.is_some();
3482
3483                 let sub_expr = P(self.lower_expr(sub_expr));
3484
3485                 hir::ExprMatch(
3486                     sub_expr,
3487                     arms.into(),
3488                     hir::MatchSource::IfLetDesugar {
3489                         contains_else_clause,
3490                     },
3491                 )
3492             }
3493
3494             // Desugar ExprWhileLet
3495             // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3496             ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3497                 // to:
3498                 //
3499                 //   [opt_ident]: loop {
3500                 //     match <sub_expr> {
3501                 //       <pat> => <body>,
3502                 //       _ => break
3503                 //     }
3504                 //   }
3505
3506                 // Note that the block AND the condition are evaluated in the loop scope.
3507                 // This is done to allow `break` from inside the condition of the loop.
3508                 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3509                     (
3510                         this.lower_block(body, false),
3511                         this.expr_break(e.span, ThinVec::new()),
3512                         this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3513                     )
3514                 });
3515
3516                 // `<pat> => <body>`
3517                 let pat_arm = {
3518                     let body_expr = P(self.expr_block(body, ThinVec::new()));
3519                     let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3520                     self.arm(pats, body_expr)
3521                 };
3522
3523                 // `_ => break`
3524                 let break_arm = {
3525                     let pat_under = self.pat_wild(e.span);
3526                     self.arm(hir_vec![pat_under], break_expr)
3527                 };
3528
3529                 // `match <sub_expr> { ... }`
3530                 let arms = hir_vec![pat_arm, break_arm];
3531                 let match_expr = self.expr(
3532                     sub_expr.span,
3533                     hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3534                     ThinVec::new(),
3535                 );
3536
3537                 // `[opt_ident]: loop { ... }`
3538                 let loop_block = P(self.block_expr(P(match_expr)));
3539                 let loop_expr = hir::ExprLoop(
3540                     loop_block,
3541                     self.lower_label(opt_label),
3542                     hir::LoopSource::WhileLet,
3543                 );
3544                 // add attributes to the outer returned expr node
3545                 loop_expr
3546             }
3547
3548             // Desugar ExprForLoop
3549             // From: `[opt_ident]: for <pat> in <head> <body>`
3550             ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3551                 // to:
3552                 //
3553                 //   {
3554                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3555                 //       mut iter => {
3556                 //         [opt_ident]: loop {
3557                 //           let mut __next;
3558                 //           match ::std::iter::Iterator::next(&mut iter) {
3559                 //             ::std::option::Option::Some(val) => __next = val,
3560                 //             ::std::option::Option::None => break
3561                 //           };
3562                 //           let <pat> = __next;
3563                 //           StmtExpr(<body>);
3564                 //         }
3565                 //       }
3566                 //     };
3567                 //     result
3568                 //   }
3569
3570                 // expand <head>
3571                 let head = self.lower_expr(head);
3572                 let head_sp = head.span;
3573
3574                 let iter = self.str_to_ident("iter");
3575
3576                 let next_ident = self.str_to_ident("__next");
3577                 let next_pat = self.pat_ident_binding_mode(
3578                     pat.span,
3579                     next_ident,
3580                     hir::BindingAnnotation::Mutable,
3581                 );
3582
3583                 // `::std::option::Option::Some(val) => next = val`
3584                 let pat_arm = {
3585                     let val_ident = self.str_to_ident("val");
3586                     let val_pat = self.pat_ident(pat.span, val_ident);
3587                     let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3588                     let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3589                     let assign = P(self.expr(
3590                         pat.span,
3591                         hir::ExprAssign(next_expr, val_expr),
3592                         ThinVec::new(),
3593                     ));
3594                     let some_pat = self.pat_some(pat.span, val_pat);
3595                     self.arm(hir_vec![some_pat], assign)
3596                 };
3597
3598                 // `::std::option::Option::None => break`
3599                 let break_arm = {
3600                     let break_expr =
3601                         self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3602                     let pat = self.pat_none(e.span);
3603                     self.arm(hir_vec![pat], break_expr)
3604                 };
3605
3606                 // `mut iter`
3607                 let iter_pat =
3608                     self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3609
3610                 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3611                 let match_expr = {
3612                     let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3613                     let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3614                     let next_path = &["iter", "Iterator", "next"];
3615                     let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3616                     let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3617                     let arms = hir_vec![pat_arm, break_arm];
3618
3619                     P(self.expr(
3620                         head_sp,
3621                         hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3622                         ThinVec::new(),
3623                     ))
3624                 };
3625                 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3626
3627                 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3628
3629                 // `let mut __next`
3630                 let next_let =
3631                     self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3632
3633                 // `let <pat> = __next`
3634                 let pat = self.lower_pat(pat);
3635                 let pat_let = self.stmt_let_pat(
3636                     head_sp,
3637                     Some(next_expr),
3638                     pat,
3639                     hir::LocalSource::ForLoopDesugar,
3640                 );
3641
3642                 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3643                 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3644                 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3645
3646                 let loop_block = P(self.block_all(
3647                     e.span,
3648                     hir_vec![next_let, match_stmt, pat_let, body_stmt],
3649                     None,
3650                 ));
3651
3652                 // `[opt_ident]: loop { ... }`
3653                 let loop_expr = hir::ExprLoop(
3654                     loop_block,
3655                     self.lower_label(opt_label),
3656                     hir::LoopSource::ForLoop,
3657                 );
3658                 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3659                 let loop_expr = P(hir::Expr {
3660                     id: node_id,
3661                     hir_id,
3662                     node: loop_expr,
3663                     span: e.span,
3664                     attrs: ThinVec::new(),
3665                 });
3666
3667                 // `mut iter => { ... }`
3668                 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3669
3670                 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3671                 let into_iter_expr = {
3672                     let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3673                     let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3674                     P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3675                 };
3676
3677                 let match_expr = P(self.expr_match(
3678                     head_sp,
3679                     into_iter_expr,
3680                     hir_vec![iter_arm],
3681                     hir::MatchSource::ForLoopDesugar,
3682                 ));
3683
3684                 // `{ let _result = ...; _result }`
3685                 // underscore prevents an unused_variables lint if the head diverges
3686                 let result_ident = self.str_to_ident("_result");
3687                 let (let_stmt, let_stmt_binding) =
3688                     self.stmt_let(e.span, false, result_ident, match_expr);
3689
3690                 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3691                 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3692                 // add the attributes to the outer returned expr node
3693                 return self.expr_block(block, e.attrs.clone());
3694             }
3695
3696             // Desugar ExprKind::Try
3697             // From: `<expr>?`
3698             ExprKind::Try(ref sub_expr) => {
3699                 // to:
3700                 //
3701                 // match Try::into_result(<expr>) {
3702                 //     Ok(val) => #[allow(unreachable_code)] val,
3703                 //     Err(err) => #[allow(unreachable_code)]
3704                 //                 // If there is an enclosing `catch {...}`
3705                 //                 break 'catch_target Try::from_error(From::from(err)),
3706                 //                 // Otherwise
3707                 //                 return Try::from_error(From::from(err)),
3708                 // }
3709
3710                 let unstable_span =
3711                     self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3712
3713                 // Try::into_result(<expr>)
3714                 let discr = {
3715                     // expand <expr>
3716                     let sub_expr = self.lower_expr(sub_expr);
3717
3718                     let path = &["ops", "Try", "into_result"];
3719                     let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3720                     P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3721                 };
3722
3723                 // #[allow(unreachable_code)]
3724                 let attr = {
3725                     // allow(unreachable_code)
3726                     let allow = {
3727                         let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3728                         let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3729                         let uc_nested = attr::mk_nested_word_item(uc_ident);
3730                         attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3731                     };
3732                     attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3733                 };
3734                 let attrs = vec![attr];
3735
3736                 // Ok(val) => #[allow(unreachable_code)] val,
3737                 let ok_arm = {
3738                     let val_ident = self.str_to_ident("val");
3739                     let val_pat = self.pat_ident(e.span, val_ident);
3740                     let val_expr = P(self.expr_ident_with_attrs(
3741                         e.span,
3742                         val_ident,
3743                         val_pat.id,
3744                         ThinVec::from(attrs.clone()),
3745                     ));
3746                     let ok_pat = self.pat_ok(e.span, val_pat);
3747
3748                     self.arm(hir_vec![ok_pat], val_expr)
3749                 };
3750
3751                 // Err(err) => #[allow(unreachable_code)]
3752                 //             return Try::from_error(From::from(err)),
3753                 let err_arm = {
3754                     let err_ident = self.str_to_ident("err");
3755                     let err_local = self.pat_ident(e.span, err_ident);
3756                     let from_expr = {
3757                         let path = &["convert", "From", "from"];
3758                         let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3759                         let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3760
3761                         self.expr_call(e.span, from, hir_vec![err_expr])
3762                     };
3763                     let from_err_expr =
3764                         self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3765                     let thin_attrs = ThinVec::from(attrs);
3766                     let catch_scope = self.catch_scopes.last().map(|x| *x);
3767                     let ret_expr = if let Some(catch_node) = catch_scope {
3768                         P(self.expr(
3769                             e.span,
3770                             hir::ExprBreak(
3771                                 hir::Destination {
3772                                     label: None,
3773                                     target_id: Ok(catch_node),
3774                                 },
3775                                 Some(from_err_expr),
3776                             ),
3777                             thin_attrs,
3778                         ))
3779                     } else {
3780                         P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3781                     };
3782
3783                     let err_pat = self.pat_err(e.span, err_local);
3784                     self.arm(hir_vec![err_pat], ret_expr)
3785                 };
3786
3787                 hir::ExprMatch(
3788                     discr,
3789                     hir_vec![err_arm, ok_arm],
3790                     hir::MatchSource::TryDesugar,
3791                 )
3792             }
3793
3794             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3795         };
3796
3797         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3798
3799         hir::Expr {
3800             id: node_id,
3801             hir_id,
3802             node: kind,
3803             span: e.span,
3804             attrs: e.attrs.clone(),
3805         }
3806     }
3807
3808     fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3809         SmallVector::one(match s.node {
3810             StmtKind::Local(ref l) => Spanned {
3811                 node: hir::StmtDecl(
3812                     P(Spanned {
3813                         node: hir::DeclLocal(self.lower_local(l)),
3814                         span: s.span,
3815                     }),
3816                     self.lower_node_id(s.id).node_id,
3817                 ),
3818                 span: s.span,
3819             },
3820             StmtKind::Item(ref it) => {
3821                 // Can only use the ID once.
3822                 let mut id = Some(s.id);
3823                 return self.lower_item_id(it)
3824                     .into_iter()
3825                     .map(|item_id| Spanned {
3826                         node: hir::StmtDecl(
3827                             P(Spanned {
3828                                 node: hir::DeclItem(item_id),
3829                                 span: s.span,
3830                             }),
3831                             id.take()
3832                                 .map(|id| self.lower_node_id(id).node_id)
3833                                 .unwrap_or_else(|| self.next_id().node_id),
3834                         ),
3835                         span: s.span,
3836                     })
3837                     .collect();
3838             }
3839             StmtKind::Expr(ref e) => Spanned {
3840                 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3841                 span: s.span,
3842             },
3843             StmtKind::Semi(ref e) => Spanned {
3844                 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3845                 span: s.span,
3846             },
3847             StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3848         })
3849     }
3850
3851     fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3852         match c {
3853             CaptureBy::Value => hir::CaptureByValue,
3854             CaptureBy::Ref => hir::CaptureByRef,
3855         }
3856     }
3857
3858     /// If an `explicit_owner` is given, this method allocates the `HirId` in
3859     /// the address space of that item instead of the item currently being
3860     /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3861     /// lower a `Visibility` value although we haven't lowered the owning
3862     /// `ImplItem` in question yet.
3863     fn lower_visibility(
3864         &mut self,
3865         v: &Visibility,
3866         explicit_owner: Option<NodeId>,
3867     ) -> hir::Visibility {
3868         match v.node {
3869             VisibilityKind::Public => hir::Public,
3870             VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3871             VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3872                 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3873                 id: if let Some(owner) = explicit_owner {
3874                     self.lower_node_id_with_owner(id, owner).node_id
3875                 } else {
3876                     self.lower_node_id(id).node_id
3877                 },
3878             },
3879             VisibilityKind::Inherited => hir::Inherited,
3880         }
3881     }
3882
3883     fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3884         match d {
3885             Defaultness::Default => hir::Defaultness::Default {
3886                 has_value: has_value,
3887             },
3888             Defaultness::Final => {
3889                 assert!(has_value);
3890                 hir::Defaultness::Final
3891             }
3892         }
3893     }
3894
3895     fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3896         match *b {
3897             BlockCheckMode::Default => hir::DefaultBlock,
3898             BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3899         }
3900     }
3901
3902     fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3903         match *b {
3904             BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3905             BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3906             BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3907             BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3908         }
3909     }
3910
3911     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3912         match u {
3913             CompilerGenerated => hir::CompilerGenerated,
3914             UserProvided => hir::UserProvided,
3915         }
3916     }
3917
3918     fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3919         match i {
3920             ImplPolarity::Positive => hir::ImplPolarity::Positive,
3921             ImplPolarity::Negative => hir::ImplPolarity::Negative,
3922         }
3923     }
3924
3925     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3926         match f {
3927             TraitBoundModifier::None => hir::TraitBoundModifier::None,
3928             TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3929         }
3930     }
3931
3932     // Helper methods for building HIR.
3933
3934     fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3935         hir::Arm {
3936             attrs: hir_vec![],
3937             pats,
3938             guard: None,
3939             body: expr,
3940         }
3941     }
3942
3943     fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3944         hir::Field {
3945             id: self.next_id().node_id,
3946             ident,
3947             span,
3948             expr,
3949             is_shorthand: false,
3950         }
3951     }
3952
3953     fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3954         let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3955         P(self.expr(span, expr_break, attrs))
3956     }
3957
3958     fn expr_call(
3959         &mut self,
3960         span: Span,
3961         e: P<hir::Expr>,
3962         args: hir::HirVec<hir::Expr>,
3963     ) -> hir::Expr {
3964         self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3965     }
3966
3967     fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3968         self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3969     }
3970
3971     fn expr_ident_with_attrs(
3972         &mut self,
3973         span: Span,
3974         id: Name,
3975         binding: NodeId,
3976         attrs: ThinVec<Attribute>,
3977     ) -> hir::Expr {
3978         let expr_path = hir::ExprPath(hir::QPath::Resolved(
3979             None,
3980             P(hir::Path {
3981                 span,
3982                 def: Def::Local(binding),
3983                 segments: hir_vec![hir::PathSegment::from_name(id)],
3984             }),
3985         ));
3986
3987         self.expr(span, expr_path, attrs)
3988     }
3989
3990     fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
3991         self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
3992     }
3993
3994     fn expr_std_path(
3995         &mut self,
3996         span: Span,
3997         components: &[&str],
3998         attrs: ThinVec<Attribute>,
3999     ) -> hir::Expr {
4000         let path = self.std_path(span, components, true);
4001         self.expr(
4002             span,
4003             hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4004             attrs,
4005         )
4006     }
4007
4008     fn expr_match(
4009         &mut self,
4010         span: Span,
4011         arg: P<hir::Expr>,
4012         arms: hir::HirVec<hir::Arm>,
4013         source: hir::MatchSource,
4014     ) -> hir::Expr {
4015         self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4016     }
4017
4018     fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4019         self.expr(b.span, hir::ExprBlock(b, None), attrs)
4020     }
4021
4022     fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4023         P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4024     }
4025
4026     fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4027         let LoweredNodeId { node_id, hir_id } = self.next_id();
4028         hir::Expr {
4029             id: node_id,
4030             hir_id,
4031             node,
4032             span,
4033             attrs,
4034         }
4035     }
4036
4037     fn stmt_let_pat(
4038         &mut self,
4039         sp: Span,
4040         ex: Option<P<hir::Expr>>,
4041         pat: P<hir::Pat>,
4042         source: hir::LocalSource,
4043     ) -> hir::Stmt {
4044         let LoweredNodeId { node_id, hir_id } = self.next_id();
4045
4046         let local = P(hir::Local {
4047             pat,
4048             ty: None,
4049             init: ex,
4050             id: node_id,
4051             hir_id,
4052             span: sp,
4053             attrs: ThinVec::new(),
4054             source,
4055         });
4056         let decl = respan(sp, hir::DeclLocal(local));
4057         respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4058     }
4059
4060     fn stmt_let(
4061         &mut self,
4062         sp: Span,
4063         mutbl: bool,
4064         ident: Name,
4065         ex: P<hir::Expr>,
4066     ) -> (hir::Stmt, NodeId) {
4067         let pat = if mutbl {
4068             self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4069         } else {
4070             self.pat_ident(sp, ident)
4071         };
4072         let pat_id = pat.id;
4073         (
4074             self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4075             pat_id,
4076         )
4077     }
4078
4079     fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4080         self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4081     }
4082
4083     fn block_all(
4084         &mut self,
4085         span: Span,
4086         stmts: hir::HirVec<hir::Stmt>,
4087         expr: Option<P<hir::Expr>>,
4088     ) -> hir::Block {
4089         let LoweredNodeId { node_id, hir_id } = self.next_id();
4090
4091         hir::Block {
4092             stmts,
4093             expr,
4094             id: node_id,
4095             hir_id,
4096             rules: hir::DefaultBlock,
4097             span,
4098             targeted_by_break: false,
4099             recovered: false,
4100         }
4101     }
4102
4103     fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4104         self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4105     }
4106
4107     fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4108         self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4109     }
4110
4111     fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4112         self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4113     }
4114
4115     fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4116         self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4117     }
4118
4119     fn pat_std_enum(
4120         &mut self,
4121         span: Span,
4122         components: &[&str],
4123         subpats: hir::HirVec<P<hir::Pat>>,
4124     ) -> P<hir::Pat> {
4125         let path = self.std_path(span, components, true);
4126         let qpath = hir::QPath::Resolved(None, P(path));
4127         let pt = if subpats.is_empty() {
4128             hir::PatKind::Path(qpath)
4129         } else {
4130             hir::PatKind::TupleStruct(qpath, subpats, None)
4131         };
4132         self.pat(span, pt)
4133     }
4134
4135     fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4136         self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4137     }
4138
4139     fn pat_ident_binding_mode(
4140         &mut self,
4141         span: Span,
4142         name: Name,
4143         bm: hir::BindingAnnotation,
4144     ) -> P<hir::Pat> {
4145         let LoweredNodeId { node_id, hir_id } = self.next_id();
4146
4147         P(hir::Pat {
4148             id: node_id,
4149             hir_id,
4150             node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4151             span,
4152         })
4153     }
4154
4155     fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4156         self.pat(span, hir::PatKind::Wild)
4157     }
4158
4159     fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4160         let LoweredNodeId { node_id, hir_id } = self.next_id();
4161         P(hir::Pat {
4162             id: node_id,
4163             hir_id,
4164             node: pat,
4165             span,
4166         })
4167     }
4168
4169     /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4170     /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4171     /// The path is also resolved according to `is_value`.
4172     fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4173         self.resolver
4174             .resolve_str_path(span, self.crate_root, components, is_value)
4175     }
4176
4177     fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4178         let mut id = id;
4179         let node = match qpath {
4180             hir::QPath::Resolved(None, path) => {
4181                 // Turn trait object paths into `TyTraitObject` instead.
4182                 if let Def::Trait(_) = path.def {
4183                     let principal = hir::PolyTraitRef {
4184                         bound_generic_params: hir::HirVec::new(),
4185                         trait_ref: hir::TraitRef {
4186                             path: path.and_then(|path| path),
4187                             ref_id: id.node_id,
4188                         },
4189                         span,
4190                     };
4191
4192                     // The original ID is taken by the `PolyTraitRef`,
4193                     // so the `Ty` itself needs a different one.
4194                     id = self.next_id();
4195                     hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4196                 } else {
4197                     hir::TyPath(hir::QPath::Resolved(None, path))
4198                 }
4199             }
4200             _ => hir::TyPath(qpath),
4201         };
4202         P(hir::Ty {
4203             id: id.node_id,
4204             hir_id: id.hir_id,
4205             node,
4206             span,
4207         })
4208     }
4209
4210     /// Invoked to create the lifetime argument for a type `&T`
4211     /// with no explicit lifetime.
4212     fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4213         match self.anonymous_lifetime_mode {
4214             // Intercept when we are in an impl header and introduce an in-band lifetime.
4215             // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4216             // `'f`.
4217             AnonymousLifetimeMode::CreateParameter => {
4218                 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4219                 hir::Lifetime {
4220                     id: self.next_id().node_id,
4221                     span,
4222                     name: fresh_name,
4223                 }
4224             }
4225
4226             AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4227         }
4228     }
4229
4230     /// Invoked to create the lifetime argument(s) for a path like
4231     /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4232     /// sorts of cases are deprecated. This may therefore report a warning or an
4233     /// error, depending on the mode.
4234     fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4235         match self.anonymous_lifetime_mode {
4236             // NB. We intentionally ignore the create-parameter mode here
4237             // and instead "pass through" to resolve-lifetimes, which will then
4238             // report an error. This is because we don't want to support
4239             // impl elision for deprecated forms like
4240             //
4241             //     impl Foo for std::cell::Ref<u32> // note lack of '_
4242             AnonymousLifetimeMode::CreateParameter => {}
4243
4244             // This is the normal case.
4245             AnonymousLifetimeMode::PassThrough => {}
4246         }
4247
4248         (0..count)
4249             .map(|_| self.new_implicit_lifetime(span))
4250             .collect()
4251     }
4252
4253     /// Invoked to create the lifetime argument(s) for an elided trait object
4254     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4255     /// when the bound is written, even if it is written with `'_` like in
4256     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4257     fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4258         match self.anonymous_lifetime_mode {
4259             // NB. We intentionally ignore the create-parameter mode here.
4260             // and instead "pass through" to resolve-lifetimes, which will apply
4261             // the object-lifetime-defaulting rules. Elided object lifetime defaults
4262             // do not act like other elided lifetimes. In other words, given this:
4263             //
4264             //     impl Foo for Box<dyn Debug>
4265             //
4266             // we do not introduce a fresh `'_` to serve as the bound, but instead
4267             // ultimately translate to the equivalent of:
4268             //
4269             //     impl Foo for Box<dyn Debug + 'static>
4270             //
4271             // `resolve_lifetime` has the code to make that happen.
4272             AnonymousLifetimeMode::CreateParameter => {}
4273
4274             // This is the normal case.
4275             AnonymousLifetimeMode::PassThrough => {}
4276         }
4277
4278         self.new_implicit_lifetime(span)
4279     }
4280
4281     fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4282         hir::Lifetime {
4283             id: self.next_id().node_id,
4284             span,
4285             name: hir::LifetimeName::Implicit,
4286         }
4287     }
4288
4289     fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4290         self.sess.buffer_lint_with_diagnostic(
4291             builtin::BARE_TRAIT_OBJECTS,
4292             id,
4293             span,
4294             "trait objects without an explicit `dyn` are deprecated",
4295             builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4296         )
4297     }
4298
4299     fn wrap_in_try_constructor(
4300         &mut self,
4301         method: &'static str,
4302         e: hir::Expr,
4303         unstable_span: Span,
4304     ) -> P<hir::Expr> {
4305         let path = &["ops", "Try", method];
4306         let from_err = P(self.expr_std_path(unstable_span, path,
4307                                             ThinVec::new()));
4308         P(self.expr_call(e.span, from_err, hir_vec![e]))
4309     }
4310 }
4311
4312 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4313     // Sorting by span ensures that we get things in order within a
4314     // file, and also puts the files in a sensible order.
4315     let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4316     body_ids.sort_by_key(|b| bodies[b].value.span);
4317     body_ids
4318 }