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