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