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