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