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