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