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