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