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