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