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