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