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