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