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