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