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