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