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