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