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