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