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