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