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