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