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