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