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