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