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