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