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