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