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