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