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