]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering.rs
Remove AngleBracketedArgs impl
[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::LifetimeDef(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::LifetimeDef(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         if !generic_args.parenthesized && generic_args.lifetimes().count() == 0 {
1735             generic_args.args =
1736                 self.elided_path_lifetimes(path_span, expected_lifetimes)
1737                     .into_iter()
1738                     .map(|lt| GenericArg::Lifetime(lt))
1739                     .chain(generic_args.args.into_iter())
1740                     .collect();
1741         }
1742
1743         hir::PathSegment::new(
1744             self.lower_ident(segment.ident),
1745             generic_args,
1746             infer_types,
1747         )
1748     }
1749
1750     fn lower_angle_bracketed_parameter_data(
1751         &mut self,
1752         data: &AngleBracketedArgs,
1753         param_mode: ParamMode,
1754         itctx: ImplTraitContext,
1755     ) -> (hir::GenericArgs, bool) {
1756         let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
1757         let has_types = args.iter().any(|arg| match arg {
1758             GenericArgAST::Type(_) => true,
1759             _ => false,
1760         });
1761         (hir::GenericArgs {
1762             args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
1763             bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
1764             parenthesized: false,
1765         },
1766         has_types && param_mode == ParamMode::Optional)
1767     }
1768
1769     fn lower_parenthesized_parameter_data(
1770         &mut self,
1771         data: &ParenthesizedParameterData,
1772     ) -> (hir::PathParameters, bool) {
1773         // Switch to `PassThrough` mode for anonymous lifetimes: this
1774         // means that we permit things like `&Ref<T>`, where `Ref` has
1775         // a hidden lifetime parameter. This is needed for backwards
1776         // compatibility, even in contexts like an impl header where
1777         // we generally don't permit such things (see #51008).
1778         self.with_anonymous_lifetime_mode(
1779             AnonymousLifetimeMode::PassThrough,
1780             |this| {
1781                 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
1782                 let &ParenthesizedParameterData { ref inputs, ref output, span } = data;
1783                 let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect();
1784                 let mk_tup = |this: &mut Self, tys, span| {
1785                     let LoweredNodeId { node_id, hir_id } = this.next_id();
1786                     P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span })
1787                 };
1788
1789                 (
1790                     hir::GenericArgs {
1791                         parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
1792                         bindings: hir_vec![
1793                             hir::TypeBinding {
1794                                 id: this.next_id().node_id,
1795                                 name: Symbol::intern(FN_OUTPUT_NAME),
1796                                 ty: output
1797                                     .as_ref()
1798                                     .map(|ty| this.lower_ty(&ty, DISALLOWED))
1799                                     .unwrap_or_else(|| mk_tup(this, hir::HirVec::new(), span)),
1800                                 span: output.as_ref().map_or(span, |ty| ty.span),
1801                             }
1802                         ],
1803                         parenthesized: true,
1804                     },
1805                     false,
1806                 )
1807             }
1808         )
1809     }
1810
1811     fn lower_local(&mut self, l: &Local) -> P<hir::Local> {
1812         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(l.id);
1813         P(hir::Local {
1814             id: node_id,
1815             hir_id,
1816             ty: l.ty
1817                 .as_ref()
1818                 .map(|t| self.lower_ty(t, ImplTraitContext::Disallowed)),
1819             pat: self.lower_pat(&l.pat),
1820             init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
1821             span: l.span,
1822             attrs: l.attrs.clone(),
1823             source: hir::LocalSource::Normal,
1824         })
1825     }
1826
1827     fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
1828         match m {
1829             Mutability::Mutable => hir::MutMutable,
1830             Mutability::Immutable => hir::MutImmutable,
1831         }
1832     }
1833
1834     fn lower_arg(&mut self, arg: &Arg) -> hir::Arg {
1835         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(arg.id);
1836         hir::Arg {
1837             id: node_id,
1838             hir_id,
1839             pat: self.lower_pat(&arg.pat),
1840         }
1841     }
1842
1843     fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Spanned<Name>> {
1844         decl.inputs
1845             .iter()
1846             .map(|arg| match arg.pat.node {
1847                 PatKind::Ident(_, ident, None) => respan(ident.span, ident.name),
1848                 _ => respan(arg.pat.span, keywords::Invalid.name()),
1849             })
1850             .collect()
1851     }
1852
1853     fn lower_fn_decl(
1854         &mut self,
1855         decl: &FnDecl,
1856         fn_def_id: Option<DefId>,
1857         impl_trait_return_allow: bool,
1858     ) -> P<hir::FnDecl> {
1859         // NOTE: The two last parameters here have to do with impl Trait. If fn_def_id is Some,
1860         //       then impl Trait arguments are lowered into generic parameters on the given
1861         //       fn_def_id, otherwise impl Trait is disallowed. (for now)
1862         //
1863         //       Furthermore, if impl_trait_return_allow is true, then impl Trait may be used in
1864         //       return positions as well. This guards against trait declarations and their impls
1865         //       where impl Trait is disallowed. (again for now)
1866         P(hir::FnDecl {
1867             inputs: decl.inputs
1868                 .iter()
1869                 .map(|arg| {
1870                     if let Some(def_id) = fn_def_id {
1871                         self.lower_ty(&arg.ty, ImplTraitContext::Universal(def_id))
1872                     } else {
1873                         self.lower_ty(&arg.ty, ImplTraitContext::Disallowed)
1874                     }
1875                 })
1876                 .collect(),
1877             output: match decl.output {
1878                 FunctionRetTy::Ty(ref ty) => match fn_def_id {
1879                     Some(def_id) if impl_trait_return_allow => {
1880                         hir::Return(self.lower_ty(ty, ImplTraitContext::Existential(def_id)))
1881                     }
1882                     _ => hir::Return(self.lower_ty(ty, ImplTraitContext::Disallowed)),
1883                 },
1884                 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
1885             },
1886             variadic: decl.variadic,
1887             has_implicit_self: decl.inputs.get(0).map_or(false, |arg| match arg.ty.node {
1888                 TyKind::ImplicitSelf => true,
1889                 TyKind::Rptr(_, ref mt) => mt.ty.node == TyKind::ImplicitSelf,
1890                 _ => false,
1891             }),
1892         })
1893     }
1894
1895     fn lower_ty_param_bound(
1896         &mut self,
1897         tpb: &TyParamBound,
1898         itctx: ImplTraitContext,
1899     ) -> hir::TyParamBound {
1900         match *tpb {
1901             TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
1902                 self.lower_poly_trait_ref(ty, itctx),
1903                 self.lower_trait_bound_modifier(modifier),
1904             ),
1905             RegionTyParamBound(ref lifetime) => {
1906                 hir::RegionTyParamBound(self.lower_lifetime(lifetime))
1907             }
1908         }
1909     }
1910
1911     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1912         let span = l.ident.span;
1913         match self.lower_ident(l.ident) {
1914             x if x == "'static" => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
1915             x if x == "'_" => match self.anonymous_lifetime_mode {
1916                 AnonymousLifetimeMode::CreateParameter => {
1917                     let fresh_name = self.collect_fresh_in_band_lifetime(span);
1918                     self.new_named_lifetime(l.id, span, fresh_name)
1919                 }
1920
1921                 AnonymousLifetimeMode::PassThrough => {
1922                     self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1923                 }
1924             },
1925             name => {
1926                 self.maybe_collect_in_band_lifetime(span, name);
1927                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
1928             }
1929         }
1930     }
1931
1932     fn new_named_lifetime(
1933         &mut self,
1934         id: NodeId,
1935         span: Span,
1936         name: hir::LifetimeName,
1937     ) -> hir::Lifetime {
1938         hir::Lifetime {
1939             id: self.lower_node_id(id).node_id,
1940             span,
1941             name: name,
1942         }
1943     }
1944
1945     fn lower_generic_param(&mut self,
1946                            param: &GenericParamAST,
1947                            add_bounds: &NodeMap<Vec<TyParamBound>>,
1948                            itctx: ImplTraitContext)
1949                            -> hir::GenericParam {
1950         match param.kind {
1951             GenericParamKindAST::Lifetime { ref bounds, ref lifetime, .. } => {
1952                 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1953                 self.is_collecting_in_band_lifetimes = false;
1954
1955                 let lifetime = self.lower_lifetime(lifetime);
1956                 let param = hir::GenericParam {
1957                     id: lifetime.id,
1958                     span: lifetime.span,
1959                     pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
1960                     kind: hir::GenericParamKind::Lifetime {
1961                         name: lifetime.name,
1962                         bounds: bounds.iter().map(|lt| self.lower_lifetime(lt)).collect(),
1963                         in_band: false,
1964                         lifetime_deprecated: lifetime,
1965                     }
1966                 };
1967
1968                 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1969
1970                 param
1971             }
1972             GenericParamKindAST::Type { ref bounds, ref default } => {
1973                 let mut name = self.lower_ident(param.ident);
1974
1975                 // Don't expose `Self` (recovered "keyword used as ident" parse error).
1976                 // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
1977                 // Instead, use gensym("Self") to create a distinct name that looks the same.
1978                 if name == keywords::SelfType.name() {
1979                     name = Symbol::gensym("Self");
1980                 }
1981
1982                 let mut bounds = self.lower_bounds(bounds, itctx);
1983                 let add_bounds = add_bounds.get(&param.id).map_or(&[][..], |x| &x);
1984                 if !add_bounds.is_empty() {
1985                     bounds = bounds
1986                         .into_iter()
1987                         .chain(self.lower_bounds(add_bounds, itctx).into_iter())
1988                         .collect();
1989                 }
1990
1991                 hir::GenericParam {
1992                     id: self.lower_node_id(param.id).node_id,
1993                     span: param.ident.span,
1994                     pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
1995                     kind: hir::GenericParamKind::Type {
1996                         name,
1997                         bounds,
1998                         default: default.as_ref().map(|x| {
1999                             self.lower_ty(x, ImplTraitContext::Disallowed)
2000                         }),
2001                         synthetic: param.attrs.iter()
2002                                               .filter(|attr| attr.check_name("rustc_synthetic"))
2003                                               .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2004                                               .nth(0),
2005                         attrs: self.lower_attrs(&param.attrs),
2006                     }
2007                 }
2008             }
2009         }
2010     }
2011
2012     fn lower_generic_params(
2013         &mut self,
2014         params: &Vec<GenericParamAST>,
2015         add_bounds: &NodeMap<Vec<TyParamBound>>,
2016         itctx: ImplTraitContext,
2017     ) -> hir::HirVec<hir::GenericParam> {
2018         params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
2019     }
2020
2021     fn lower_generics(
2022         &mut self,
2023         generics: &Generics,
2024         itctx: ImplTraitContext)
2025         -> hir::Generics
2026     {
2027         // Collect `?Trait` bounds in where clause and move them to parameter definitions.
2028         // FIXME: This could probably be done with less rightward drift. Also looks like two control
2029         //        paths where report_error is called are also the only paths that advance to after
2030         //        the match statement, so the error reporting could probably just be moved there.
2031         let mut add_bounds = NodeMap();
2032         for pred in &generics.where_clause.predicates {
2033             if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
2034                 'next_bound: for bound in &bound_pred.bounds {
2035                     if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
2036                         let report_error = |this: &mut Self| {
2037                             this.diagnostic().span_err(
2038                                 bound_pred.bounded_ty.span,
2039                                 "`?Trait` bounds are only permitted at the \
2040                                  point where a type parameter is declared",
2041                             );
2042                         };
2043                         // Check if the where clause type is a plain type parameter.
2044                         match bound_pred.bounded_ty.node {
2045                             TyKind::Path(None, ref path)
2046                                 if path.segments.len() == 1
2047                                     && bound_pred.bound_generic_params.is_empty() =>
2048                             {
2049                                 if let Some(Def::TyParam(def_id)) = self.resolver
2050                                     .get_resolution(bound_pred.bounded_ty.id)
2051                                     .map(|d| d.base_def())
2052                                 {
2053                                     if let Some(node_id) =
2054                                         self.resolver.definitions().as_local_node_id(def_id)
2055                                     {
2056                                         for param in &generics.params {
2057                                             match param.kind {
2058                                                 GenericParamKindAST::Type { .. } => {
2059                                                     if node_id == param.id {
2060                                                         add_bounds.entry(param.id)
2061                                                             .or_insert(Vec::new())
2062                                                             .push(bound.clone());
2063                                                         continue 'next_bound;
2064                                                     }
2065                                                 }
2066                                                 _ => {}
2067                                             }
2068                                         }
2069                                     }
2070                                 }
2071                                 report_error(self)
2072                             }
2073                             _ => report_error(self),
2074                         }
2075                     }
2076                 }
2077             }
2078         }
2079
2080         hir::Generics {
2081             params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
2082             where_clause: self.lower_where_clause(&generics.where_clause),
2083             span: generics.span,
2084         }
2085     }
2086
2087     fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause {
2088         hir::WhereClause {
2089             id: self.lower_node_id(wc.id).node_id,
2090             predicates: wc.predicates
2091                 .iter()
2092                 .map(|predicate| self.lower_where_predicate(predicate))
2093                 .collect(),
2094         }
2095     }
2096
2097     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate {
2098         match *pred {
2099             WherePredicate::BoundPredicate(WhereBoundPredicate {
2100                 ref bound_generic_params,
2101                 ref bounded_ty,
2102                 ref bounds,
2103                 span,
2104             }) => {
2105                 self.with_in_scope_lifetime_defs(
2106                     bound_generic_params.iter().filter_map(|param| match param.kind {
2107                         GenericParamKindAST::Lifetime { .. } => Some(param),
2108                         _ => None,
2109                     }),
2110                     |this| {
2111                         hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2112                             bound_generic_params: this.lower_generic_params(
2113                                 bound_generic_params,
2114                                 &NodeMap(),
2115                                 ImplTraitContext::Disallowed,
2116                             ),
2117                             bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::Disallowed),
2118                             bounds: bounds
2119                                 .iter()
2120                                 .filter_map(|bound| match *bound {
2121                                     // Ignore `?Trait` bounds.
2122                                     // Tthey were copied into type parameters already.
2123                                     TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
2124                                     _ => Some(this.lower_ty_param_bound(
2125                                         bound,
2126                                         ImplTraitContext::Disallowed,
2127                                     )),
2128                                 })
2129                                 .collect(),
2130                             span,
2131                         })
2132                     },
2133                 )
2134             }
2135             WherePredicate::RegionPredicate(WhereRegionPredicate {
2136                 ref lifetime,
2137                 ref bounds,
2138                 span,
2139             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2140                 span,
2141                 lifetime: self.lower_lifetime(lifetime),
2142                 bounds: bounds
2143                     .iter()
2144                     .map(|bound| self.lower_lifetime(bound))
2145                     .collect(),
2146             }),
2147             WherePredicate::EqPredicate(WhereEqPredicate {
2148                 id,
2149                 ref lhs_ty,
2150                 ref rhs_ty,
2151                 span,
2152             }) => hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2153                 id: self.lower_node_id(id).node_id,
2154                 lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::Disallowed),
2155                 rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::Disallowed),
2156                 span,
2157             }),
2158         }
2159     }
2160
2161     fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData {
2162         match *vdata {
2163             VariantData::Struct(ref fields, id) => hir::VariantData::Struct(
2164                 fields
2165                     .iter()
2166                     .enumerate()
2167                     .map(|f| self.lower_struct_field(f))
2168                     .collect(),
2169                 self.lower_node_id(id).node_id,
2170             ),
2171             VariantData::Tuple(ref fields, id) => hir::VariantData::Tuple(
2172                 fields
2173                     .iter()
2174                     .enumerate()
2175                     .map(|f| self.lower_struct_field(f))
2176                     .collect(),
2177                 self.lower_node_id(id).node_id,
2178             ),
2179             VariantData::Unit(id) => hir::VariantData::Unit(self.lower_node_id(id).node_id),
2180         }
2181     }
2182
2183     fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef {
2184         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2185             hir::QPath::Resolved(None, path) => path.and_then(|path| path),
2186             qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2187         };
2188         hir::TraitRef {
2189             path,
2190             ref_id: self.lower_node_id(p.ref_id).node_id,
2191         }
2192     }
2193
2194     fn lower_poly_trait_ref(
2195         &mut self,
2196         p: &PolyTraitRef,
2197         itctx: ImplTraitContext,
2198     ) -> hir::PolyTraitRef {
2199         let bound_generic_params =
2200             self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
2201         let trait_ref = self.with_parent_impl_lifetime_defs(
2202             &bound_generic_params
2203                 .iter()
2204                 .filter_map(|param| match param.kind {
2205                     hir::GenericParamKind::Lifetime { .. } => Some(param.clone()),
2206                     _ => None,
2207                 })
2208                 .collect::<Vec<_>>(),
2209             |this| this.lower_trait_ref(&p.trait_ref, itctx),
2210         );
2211
2212         hir::PolyTraitRef {
2213             bound_generic_params,
2214             trait_ref,
2215             span: p.span,
2216         }
2217     }
2218
2219     fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField {
2220         hir::StructField {
2221             span: f.span,
2222             id: self.lower_node_id(f.id).node_id,
2223             ident: match f.ident {
2224                 Some(ident) => ident,
2225                 // FIXME(jseyfried) positional field hygiene
2226                 None => Ident::new(Symbol::intern(&index.to_string()), f.span),
2227             },
2228             vis: self.lower_visibility(&f.vis, None),
2229             ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed),
2230             attrs: self.lower_attrs(&f.attrs),
2231         }
2232     }
2233
2234     fn lower_field(&mut self, f: &Field) -> hir::Field {
2235         hir::Field {
2236             id: self.next_id().node_id,
2237             ident: f.ident,
2238             expr: P(self.lower_expr(&f.expr)),
2239             span: f.span,
2240             is_shorthand: f.is_shorthand,
2241         }
2242     }
2243
2244     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
2245         hir::MutTy {
2246             ty: self.lower_ty(&mt.ty, itctx),
2247             mutbl: self.lower_mutability(mt.mutbl),
2248         }
2249     }
2250
2251     fn lower_bounds(
2252         &mut self,
2253         bounds: &[TyParamBound],
2254         itctx: ImplTraitContext,
2255     ) -> hir::TyParamBounds {
2256         bounds
2257             .iter()
2258             .map(|bound| self.lower_ty_param_bound(bound, itctx))
2259             .collect()
2260     }
2261
2262     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2263         let mut expr = None;
2264
2265         let mut stmts = vec![];
2266
2267         for (index, stmt) in b.stmts.iter().enumerate() {
2268             if index == b.stmts.len() - 1 {
2269                 if let StmtKind::Expr(ref e) = stmt.node {
2270                     expr = Some(P(self.lower_expr(e)));
2271                 } else {
2272                     stmts.extend(self.lower_stmt(stmt));
2273                 }
2274             } else {
2275                 stmts.extend(self.lower_stmt(stmt));
2276             }
2277         }
2278
2279         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(b.id);
2280
2281         P(hir::Block {
2282             id: node_id,
2283             hir_id,
2284             stmts: stmts.into(),
2285             expr,
2286             rules: self.lower_block_check_mode(&b.rules),
2287             span: b.span,
2288             targeted_by_break,
2289             recovered: b.recovered,
2290         })
2291     }
2292
2293     fn lower_item_kind(
2294         &mut self,
2295         id: NodeId,
2296         name: &mut Name,
2297         attrs: &hir::HirVec<Attribute>,
2298         vis: &mut hir::Visibility,
2299         i: &ItemKind,
2300     ) -> hir::Item_ {
2301         match *i {
2302             ItemKind::ExternCrate(orig_name) => hir::ItemExternCrate(orig_name),
2303             ItemKind::Use(ref use_tree) => {
2304                 // Start with an empty prefix
2305                 let prefix = Path {
2306                     segments: vec![],
2307                     span: use_tree.span,
2308                 };
2309
2310                 self.lower_use_tree(use_tree, &prefix, id, vis, name, attrs)
2311             }
2312             ItemKind::Static(ref t, m, ref e) => {
2313                 let value = self.lower_body(None, |this| this.lower_expr(e));
2314                 hir::ItemStatic(
2315                     self.lower_ty(t, ImplTraitContext::Disallowed),
2316                     self.lower_mutability(m),
2317                     value,
2318                 )
2319             }
2320             ItemKind::Const(ref t, ref e) => {
2321                 let value = self.lower_body(None, |this| this.lower_expr(e));
2322                 hir::ItemConst(self.lower_ty(t, ImplTraitContext::Disallowed), value)
2323             }
2324             ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
2325                 let fn_def_id = self.resolver.definitions().local_def_id(id);
2326                 self.with_new_scopes(|this| {
2327                     let body_id = this.lower_body(Some(decl), |this| {
2328                         let body = this.lower_block(body, false);
2329                         this.expr_block(body, ThinVec::new())
2330                     });
2331                     let (generics, fn_decl) = this.add_in_band_defs(
2332                         generics,
2333                         fn_def_id,
2334                         AnonymousLifetimeMode::PassThrough,
2335                         |this| this.lower_fn_decl(decl, Some(fn_def_id), true),
2336                     );
2337
2338                     hir::ItemFn(
2339                         fn_decl,
2340                         this.lower_unsafety(unsafety),
2341                         this.lower_constness(constness),
2342                         abi,
2343                         generics,
2344                         body_id,
2345                     )
2346                 })
2347             }
2348             ItemKind::Mod(ref m) => hir::ItemMod(self.lower_mod(m)),
2349             ItemKind::ForeignMod(ref nm) => hir::ItemForeignMod(self.lower_foreign_mod(nm)),
2350             ItemKind::GlobalAsm(ref ga) => hir::ItemGlobalAsm(self.lower_global_asm(ga)),
2351             ItemKind::Ty(ref t, ref generics) => hir::ItemTy(
2352                 self.lower_ty(t, ImplTraitContext::Disallowed),
2353                 self.lower_generics(generics, ImplTraitContext::Disallowed),
2354             ),
2355             ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemEnum(
2356                 hir::EnumDef {
2357                     variants: enum_definition
2358                         .variants
2359                         .iter()
2360                         .map(|x| self.lower_variant(x))
2361                         .collect(),
2362                 },
2363                 self.lower_generics(generics, ImplTraitContext::Disallowed),
2364             ),
2365             ItemKind::Struct(ref struct_def, ref generics) => {
2366                 let struct_def = self.lower_variant_data(struct_def);
2367                 hir::ItemStruct(
2368                     struct_def,
2369                     self.lower_generics(generics, ImplTraitContext::Disallowed),
2370                 )
2371             }
2372             ItemKind::Union(ref vdata, ref generics) => {
2373                 let vdata = self.lower_variant_data(vdata);
2374                 hir::ItemUnion(
2375                     vdata,
2376                     self.lower_generics(generics, ImplTraitContext::Disallowed),
2377                 )
2378             }
2379             ItemKind::Impl(
2380                 unsafety,
2381                 polarity,
2382                 defaultness,
2383                 ref ast_generics,
2384                 ref trait_ref,
2385                 ref ty,
2386                 ref impl_items,
2387             ) => {
2388                 let def_id = self.resolver.definitions().local_def_id(id);
2389
2390                 // Lower the "impl header" first. This ordering is important
2391                 // for in-band lifetimes! Consider `'a` here:
2392                 //
2393                 //     impl Foo<'a> for u32 {
2394                 //         fn method(&'a self) { .. }
2395                 //     }
2396                 //
2397                 // Because we start by lowering the `Foo<'a> for u32`
2398                 // part, we will add `'a` to the list of generics on
2399                 // the impl. When we then encounter it later in the
2400                 // method, it will not be considered an in-band
2401                 // lifetime to be added, but rather a reference to a
2402                 // parent lifetime.
2403                 let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs(
2404                     ast_generics,
2405                     def_id,
2406                     AnonymousLifetimeMode::CreateParameter,
2407                     |this| {
2408                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
2409                             this.lower_trait_ref(trait_ref, ImplTraitContext::Disallowed)
2410                         });
2411
2412                         if let Some(ref trait_ref) = trait_ref {
2413                             if let Def::Trait(def_id) = trait_ref.path.def {
2414                                 this.trait_impls.entry(def_id).or_insert(vec![]).push(id);
2415                             }
2416                         }
2417
2418                         let lowered_ty = this.lower_ty(ty, ImplTraitContext::Disallowed);
2419
2420                         (trait_ref, lowered_ty)
2421                     },
2422                 );
2423
2424                 let new_impl_items = self.with_in_scope_lifetime_defs(
2425                     ast_generics.params.iter().filter_map(|param| match param.kind {
2426                         GenericParamKindAST::Lifetime { .. } => Some(param),
2427                         _ => None,
2428                     }),
2429                     |this| {
2430                         impl_items
2431                             .iter()
2432                             .map(|item| this.lower_impl_item_ref(item))
2433                             .collect()
2434                     },
2435                 );
2436
2437                 hir::ItemImpl(
2438                     self.lower_unsafety(unsafety),
2439                     self.lower_impl_polarity(polarity),
2440                     self.lower_defaultness(defaultness, true /* [1] */),
2441                     generics,
2442                     trait_ref,
2443                     lowered_ty,
2444                     new_impl_items,
2445                 )
2446             }
2447             ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
2448                 let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
2449                 let items = items
2450                     .iter()
2451                     .map(|item| self.lower_trait_item_ref(item))
2452                     .collect();
2453                 hir::ItemTrait(
2454                     self.lower_is_auto(is_auto),
2455                     self.lower_unsafety(unsafety),
2456                     self.lower_generics(generics, ImplTraitContext::Disallowed),
2457                     bounds,
2458                     items,
2459                 )
2460             }
2461             ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
2462                 self.lower_generics(generics, ImplTraitContext::Disallowed),
2463                 self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2464             ),
2465             ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
2466         }
2467
2468         // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
2469         //     not cause an assertion failure inside the `lower_defaultness` function
2470     }
2471
2472     fn lower_use_tree(
2473         &mut self,
2474         tree: &UseTree,
2475         prefix: &Path,
2476         id: NodeId,
2477         vis: &mut hir::Visibility,
2478         name: &mut Name,
2479         attrs: &hir::HirVec<Attribute>,
2480     ) -> hir::Item_ {
2481         let path = &tree.prefix;
2482
2483         match tree.kind {
2484             UseTreeKind::Simple(rename, id1, id2) => {
2485                 *name = tree.ident().name;
2486
2487                 // First apply the prefix to the path
2488                 let mut path = Path {
2489                     segments: prefix
2490                         .segments
2491                         .iter()
2492                         .chain(path.segments.iter())
2493                         .cloned()
2494                         .collect(),
2495                     span: path.span,
2496                 };
2497
2498                 // Correctly resolve `self` imports
2499                 if path.segments.len() > 1
2500                     && path.segments.last().unwrap().ident.name == keywords::SelfValue.name()
2501                 {
2502                     let _ = path.segments.pop();
2503                     if rename.is_none() {
2504                         *name = path.segments.last().unwrap().ident.name;
2505                     }
2506                 }
2507
2508                 let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
2509                 let mut defs = self.expect_full_def_from_use(id);
2510                 // we want to return *something* from this function, so hang onto the first item
2511                 // for later
2512                 let mut ret_def = defs.next().unwrap_or(Def::Err);
2513
2514                 for (def, &new_node_id) in defs.zip([id1, id2].iter()) {
2515                     let vis = vis.clone();
2516                     let name = name.clone();
2517                     let span = path.span;
2518                     self.resolver.definitions().create_def_with_parent(
2519                         parent_def_index,
2520                         new_node_id,
2521                         DefPathData::Misc,
2522                         DefIndexAddressSpace::High,
2523                         Mark::root(),
2524                         span);
2525                     self.allocate_hir_id_counter(new_node_id, &path);
2526
2527                     self.with_hir_id_owner(new_node_id, |this| {
2528                         let new_id = this.lower_node_id(new_node_id);
2529                         let path = this.lower_path_extra(def, &path, None, ParamMode::Explicit);
2530                         let item = hir::ItemUse(P(path), hir::UseKind::Single);
2531                         let vis = match vis {
2532                             hir::Visibility::Public => hir::Visibility::Public,
2533                             hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2534                             hir::Visibility::Inherited => hir::Visibility::Inherited,
2535                             hir::Visibility::Restricted { ref path, id: _ } => {
2536                                 hir::Visibility::Restricted {
2537                                     path: path.clone(),
2538                                     // We are allocating a new NodeId here
2539                                     id: this.next_id().node_id,
2540                                 }
2541                             }
2542                         };
2543
2544                         this.items.insert(
2545                             new_id.node_id,
2546                             hir::Item {
2547                                 id: new_id.node_id,
2548                                 hir_id: new_id.hir_id,
2549                                 name: name,
2550                                 attrs: attrs.clone(),
2551                                 node: item,
2552                                 vis,
2553                                 span,
2554                             },
2555                         );
2556                     });
2557                 }
2558
2559                 let path = P(self.lower_path_extra(ret_def, &path, None, ParamMode::Explicit));
2560                 hir::ItemUse(path, hir::UseKind::Single)
2561             }
2562             UseTreeKind::Glob => {
2563                 let path = P(self.lower_path(
2564                     id,
2565                     &Path {
2566                         segments: prefix
2567                             .segments
2568                             .iter()
2569                             .chain(path.segments.iter())
2570                             .cloned()
2571                             .collect(),
2572                         span: path.span,
2573                     },
2574                     ParamMode::Explicit,
2575                 ));
2576                 hir::ItemUse(path, hir::UseKind::Glob)
2577             }
2578             UseTreeKind::Nested(ref trees) => {
2579                 let prefix = Path {
2580                     segments: prefix
2581                         .segments
2582                         .iter()
2583                         .chain(path.segments.iter())
2584                         .cloned()
2585                         .collect(),
2586                     span: prefix.span.to(path.span),
2587                 };
2588
2589                 // Add all the nested PathListItems in the HIR
2590                 for &(ref use_tree, id) in trees {
2591                     self.allocate_hir_id_counter(id, &use_tree);
2592                     let LoweredNodeId {
2593                         node_id: new_id,
2594                         hir_id: new_hir_id,
2595                     } = self.lower_node_id(id);
2596
2597                     let mut vis = vis.clone();
2598                     let mut name = name.clone();
2599                     let item =
2600                         self.lower_use_tree(use_tree, &prefix, new_id, &mut vis, &mut name, &attrs);
2601
2602                     self.with_hir_id_owner(new_id, |this| {
2603                         let vis = match vis {
2604                             hir::Visibility::Public => hir::Visibility::Public,
2605                             hir::Visibility::Crate(sugar) => hir::Visibility::Crate(sugar),
2606                             hir::Visibility::Inherited => hir::Visibility::Inherited,
2607                             hir::Visibility::Restricted { ref path, id: _ } => {
2608                                 hir::Visibility::Restricted {
2609                                     path: path.clone(),
2610                                     // We are allocating a new NodeId here
2611                                     id: this.next_id().node_id,
2612                                 }
2613                             }
2614                         };
2615
2616                         this.items.insert(
2617                             new_id,
2618                             hir::Item {
2619                                 id: new_id,
2620                                 hir_id: new_hir_id,
2621                                 name: name,
2622                                 attrs: attrs.clone(),
2623                                 node: item,
2624                                 vis,
2625                                 span: use_tree.span,
2626                             },
2627                         );
2628                     });
2629                 }
2630
2631                 // Privatize the degenerate import base, used only to check
2632                 // the stability of `use a::{};`, to avoid it showing up as
2633                 // a re-export by accident when `pub`, e.g. in documentation.
2634                 let path = P(self.lower_path(id, &prefix, ParamMode::Explicit));
2635                 *vis = hir::Inherited;
2636                 hir::ItemUse(path, hir::UseKind::ListStem)
2637             }
2638         }
2639     }
2640
2641     fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
2642         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2643         let trait_item_def_id = self.resolver.definitions().local_def_id(node_id);
2644
2645         let (generics, node) = match i.node {
2646             TraitItemKind::Const(ref ty, ref default) => (
2647                 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2648                 hir::TraitItemKind::Const(
2649                     self.lower_ty(ty, ImplTraitContext::Disallowed),
2650                     default
2651                         .as_ref()
2652                         .map(|x| self.lower_body(None, |this| this.lower_expr(x))),
2653                 ),
2654             ),
2655             TraitItemKind::Method(ref sig, None) => {
2656                 let names = self.lower_fn_args_to_names(&sig.decl);
2657                 self.add_in_band_defs(
2658                     &i.generics,
2659                     trait_item_def_id,
2660                     AnonymousLifetimeMode::PassThrough,
2661                     |this| {
2662                         hir::TraitItemKind::Method(
2663                             this.lower_method_sig(sig, trait_item_def_id, false),
2664                             hir::TraitMethod::Required(names),
2665                         )
2666                     },
2667                 )
2668             }
2669             TraitItemKind::Method(ref sig, Some(ref body)) => {
2670                 let body_id = self.lower_body(Some(&sig.decl), |this| {
2671                     let body = this.lower_block(body, false);
2672                     this.expr_block(body, ThinVec::new())
2673                 });
2674
2675                 self.add_in_band_defs(
2676                     &i.generics,
2677                     trait_item_def_id,
2678                     AnonymousLifetimeMode::PassThrough,
2679                     |this| {
2680                         hir::TraitItemKind::Method(
2681                             this.lower_method_sig(sig, trait_item_def_id, false),
2682                             hir::TraitMethod::Provided(body_id),
2683                         )
2684                     },
2685                 )
2686             }
2687             TraitItemKind::Type(ref bounds, ref default) => (
2688                 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2689                 hir::TraitItemKind::Type(
2690                     self.lower_bounds(bounds, ImplTraitContext::Disallowed),
2691                     default
2692                         .as_ref()
2693                         .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
2694                 ),
2695             ),
2696             TraitItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2697         };
2698
2699         hir::TraitItem {
2700             id: node_id,
2701             hir_id,
2702             name: self.lower_ident(i.ident),
2703             attrs: self.lower_attrs(&i.attrs),
2704             generics,
2705             node,
2706             span: i.span,
2707         }
2708     }
2709
2710     fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef {
2711         let (kind, has_default) = match i.node {
2712             TraitItemKind::Const(_, ref default) => {
2713                 (hir::AssociatedItemKind::Const, default.is_some())
2714             }
2715             TraitItemKind::Type(_, ref default) => {
2716                 (hir::AssociatedItemKind::Type, default.is_some())
2717             }
2718             TraitItemKind::Method(ref sig, ref default) => (
2719                 hir::AssociatedItemKind::Method {
2720                     has_self: sig.decl.has_self(),
2721                 },
2722                 default.is_some(),
2723             ),
2724             TraitItemKind::Macro(..) => unimplemented!(),
2725         };
2726         hir::TraitItemRef {
2727             id: hir::TraitItemId { node_id: i.id },
2728             name: self.lower_ident(i.ident),
2729             span: i.span,
2730             defaultness: self.lower_defaultness(Defaultness::Default, has_default),
2731             kind,
2732         }
2733     }
2734
2735     fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem {
2736         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2737         let impl_item_def_id = self.resolver.definitions().local_def_id(node_id);
2738
2739         let (generics, node) = match i.node {
2740             ImplItemKind::Const(ref ty, ref expr) => {
2741                 let body_id = self.lower_body(None, |this| this.lower_expr(expr));
2742                 (
2743                     self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2744                     hir::ImplItemKind::Const(
2745                         self.lower_ty(ty, ImplTraitContext::Disallowed),
2746                         body_id,
2747                     ),
2748                 )
2749             }
2750             ImplItemKind::Method(ref sig, ref body) => {
2751                 let body_id = self.lower_body(Some(&sig.decl), |this| {
2752                     let body = this.lower_block(body, false);
2753                     this.expr_block(body, ThinVec::new())
2754                 });
2755                 let impl_trait_return_allow = !self.is_in_trait_impl;
2756
2757                 self.add_in_band_defs(
2758                     &i.generics,
2759                     impl_item_def_id,
2760                     AnonymousLifetimeMode::PassThrough,
2761                     |this| {
2762                         hir::ImplItemKind::Method(
2763                             this.lower_method_sig(
2764                                 sig,
2765                                 impl_item_def_id,
2766                                 impl_trait_return_allow,
2767                             ),
2768                             body_id,
2769                         )
2770                     },
2771                 )
2772             }
2773             ImplItemKind::Type(ref ty) => (
2774                 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
2775                 hir::ImplItemKind::Type(self.lower_ty(ty, ImplTraitContext::Disallowed)),
2776             ),
2777             ImplItemKind::Macro(..) => panic!("Shouldn't exist any more"),
2778         };
2779
2780         hir::ImplItem {
2781             id: node_id,
2782             hir_id,
2783             name: self.lower_ident(i.ident),
2784             attrs: self.lower_attrs(&i.attrs),
2785             generics,
2786             vis: self.lower_visibility(&i.vis, None),
2787             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2788             node,
2789             span: i.span,
2790         }
2791
2792         // [1] since `default impl` is not yet implemented, this is always true in impls
2793     }
2794
2795     fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef {
2796         hir::ImplItemRef {
2797             id: hir::ImplItemId { node_id: i.id },
2798             name: self.lower_ident(i.ident),
2799             span: i.span,
2800             vis: self.lower_visibility(&i.vis, Some(i.id)),
2801             defaultness: self.lower_defaultness(i.defaultness, true /* [1] */),
2802             kind: match i.node {
2803                 ImplItemKind::Const(..) => hir::AssociatedItemKind::Const,
2804                 ImplItemKind::Type(..) => hir::AssociatedItemKind::Type,
2805                 ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method {
2806                     has_self: sig.decl.has_self(),
2807                 },
2808                 ImplItemKind::Macro(..) => unimplemented!(),
2809             },
2810         }
2811
2812         // [1] since `default impl` is not yet implemented, this is always true in impls
2813     }
2814
2815     fn lower_mod(&mut self, m: &Mod) -> hir::Mod {
2816         hir::Mod {
2817             inner: m.inner,
2818             item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(),
2819         }
2820     }
2821
2822     fn lower_item_id(&mut self, i: &Item) -> SmallVector<hir::ItemId> {
2823         match i.node {
2824             ItemKind::Use(ref use_tree) => {
2825                 let mut vec = SmallVector::one(hir::ItemId { id: i.id });
2826                 self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
2827                 return vec;
2828             }
2829             ItemKind::MacroDef(..) => return SmallVector::new(),
2830             _ => {}
2831         }
2832         SmallVector::one(hir::ItemId { id: i.id })
2833     }
2834
2835     fn lower_item_id_use_tree(&mut self,
2836                               tree: &UseTree,
2837                               base_id: NodeId,
2838                               vec: &mut SmallVector<hir::ItemId>)
2839     {
2840         match tree.kind {
2841             UseTreeKind::Nested(ref nested_vec) => for &(ref nested, id) in nested_vec {
2842                 vec.push(hir::ItemId { id });
2843                 self.lower_item_id_use_tree(nested, id, vec);
2844             },
2845             UseTreeKind::Glob => {}
2846             UseTreeKind::Simple(_, id1, id2) => {
2847                 for (_, &id) in self.expect_full_def_from_use(base_id)
2848                                     .skip(1)
2849                                     .zip([id1, id2].iter())
2850                 {
2851                     vec.push(hir::ItemId { id });
2852                 }
2853             },
2854         }
2855     }
2856
2857     pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item> {
2858         let mut name = i.ident.name;
2859         let mut vis = self.lower_visibility(&i.vis, None);
2860         let attrs = self.lower_attrs(&i.attrs);
2861         if let ItemKind::MacroDef(ref def) = i.node {
2862             if !def.legacy || attr::contains_name(&i.attrs, "macro_export") {
2863                 let body = self.lower_token_stream(def.stream());
2864                 self.exported_macros.push(hir::MacroDef {
2865                     name,
2866                     vis,
2867                     attrs,
2868                     id: i.id,
2869                     span: i.span,
2870                     body,
2871                     legacy: def.legacy,
2872                 });
2873             }
2874             return None;
2875         }
2876
2877         let node = self.lower_item_kind(i.id, &mut name, &attrs, &mut vis, &i.node);
2878
2879         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(i.id);
2880
2881         Some(hir::Item {
2882             id: node_id,
2883             hir_id,
2884             name,
2885             attrs,
2886             node,
2887             vis,
2888             span: i.span,
2889         })
2890     }
2891
2892     fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem {
2893         let node_id = self.lower_node_id(i.id).node_id;
2894         let def_id = self.resolver.definitions().local_def_id(node_id);
2895         hir::ForeignItem {
2896             id: node_id,
2897             name: i.ident.name,
2898             attrs: self.lower_attrs(&i.attrs),
2899             node: match i.node {
2900                 ForeignItemKind::Fn(ref fdec, ref generics) => {
2901                     let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
2902                         generics,
2903                         def_id,
2904                         AnonymousLifetimeMode::PassThrough,
2905                         |this| {
2906                             (
2907                                 // Disallow impl Trait in foreign items
2908                                 this.lower_fn_decl(fdec, None, false),
2909                                 this.lower_fn_args_to_names(fdec),
2910                             )
2911                         },
2912                     );
2913
2914                     hir::ForeignItemFn(fn_dec, fn_args, generics)
2915                 }
2916                 ForeignItemKind::Static(ref t, m) => {
2917                     hir::ForeignItemStatic(self.lower_ty(t, ImplTraitContext::Disallowed), m)
2918                 }
2919                 ForeignItemKind::Ty => hir::ForeignItemType,
2920                 ForeignItemKind::Macro(_) => panic!("shouldn't exist here"),
2921             },
2922             vis: self.lower_visibility(&i.vis, None),
2923             span: i.span,
2924         }
2925     }
2926
2927     fn lower_method_sig(
2928         &mut self,
2929         sig: &MethodSig,
2930         fn_def_id: DefId,
2931         impl_trait_return_allow: bool,
2932     ) -> hir::MethodSig {
2933         hir::MethodSig {
2934             abi: sig.abi,
2935             unsafety: self.lower_unsafety(sig.unsafety),
2936             constness: self.lower_constness(sig.constness),
2937             decl: self.lower_fn_decl(&sig.decl, Some(fn_def_id), impl_trait_return_allow),
2938         }
2939     }
2940
2941     fn lower_is_auto(&mut self, a: IsAuto) -> hir::IsAuto {
2942         match a {
2943             IsAuto::Yes => hir::IsAuto::Yes,
2944             IsAuto::No => hir::IsAuto::No,
2945         }
2946     }
2947
2948     fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety {
2949         match u {
2950             Unsafety::Unsafe => hir::Unsafety::Unsafe,
2951             Unsafety::Normal => hir::Unsafety::Normal,
2952         }
2953     }
2954
2955     fn lower_constness(&mut self, c: Spanned<Constness>) -> hir::Constness {
2956         match c.node {
2957             Constness::Const => hir::Constness::Const,
2958             Constness::NotConst => hir::Constness::NotConst,
2959         }
2960     }
2961
2962     fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
2963         match u {
2964             UnOp::Deref => hir::UnDeref,
2965             UnOp::Not => hir::UnNot,
2966             UnOp::Neg => hir::UnNeg,
2967         }
2968     }
2969
2970     fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
2971         Spanned {
2972             node: match b.node {
2973                 BinOpKind::Add => hir::BiAdd,
2974                 BinOpKind::Sub => hir::BiSub,
2975                 BinOpKind::Mul => hir::BiMul,
2976                 BinOpKind::Div => hir::BiDiv,
2977                 BinOpKind::Rem => hir::BiRem,
2978                 BinOpKind::And => hir::BiAnd,
2979                 BinOpKind::Or => hir::BiOr,
2980                 BinOpKind::BitXor => hir::BiBitXor,
2981                 BinOpKind::BitAnd => hir::BiBitAnd,
2982                 BinOpKind::BitOr => hir::BiBitOr,
2983                 BinOpKind::Shl => hir::BiShl,
2984                 BinOpKind::Shr => hir::BiShr,
2985                 BinOpKind::Eq => hir::BiEq,
2986                 BinOpKind::Lt => hir::BiLt,
2987                 BinOpKind::Le => hir::BiLe,
2988                 BinOpKind::Ne => hir::BiNe,
2989                 BinOpKind::Ge => hir::BiGe,
2990                 BinOpKind::Gt => hir::BiGt,
2991             },
2992             span: b.span,
2993         }
2994     }
2995
2996     fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2997         let node = match p.node {
2998             PatKind::Wild => hir::PatKind::Wild,
2999             PatKind::Ident(ref binding_mode, ident, ref sub) => {
3000                 match self.resolver.get_resolution(p.id).map(|d| d.base_def()) {
3001                     // `None` can occur in body-less function signatures
3002                     def @ None | def @ Some(Def::Local(_)) => {
3003                         let canonical_id = match def {
3004                             Some(Def::Local(id)) => id,
3005                             _ => p.id,
3006                         };
3007                         hir::PatKind::Binding(
3008                             self.lower_binding_mode(binding_mode),
3009                             canonical_id,
3010                             respan(ident.span, ident.name),
3011                             sub.as_ref().map(|x| self.lower_pat(x)),
3012                         )
3013                     }
3014                     Some(def) => hir::PatKind::Path(hir::QPath::Resolved(
3015                         None,
3016                         P(hir::Path {
3017                             span: ident.span,
3018                             def,
3019                             segments: hir_vec![hir::PathSegment::from_name(ident.name)],
3020                         }),
3021                     )),
3022                 }
3023             }
3024             PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
3025             PatKind::TupleStruct(ref path, ref pats, ddpos) => {
3026                 let qpath = self.lower_qpath(
3027                     p.id,
3028                     &None,
3029                     path,
3030                     ParamMode::Optional,
3031                     ImplTraitContext::Disallowed,
3032                 );
3033                 hir::PatKind::TupleStruct(
3034                     qpath,
3035                     pats.iter().map(|x| self.lower_pat(x)).collect(),
3036                     ddpos,
3037                 )
3038             }
3039             PatKind::Path(ref qself, ref path) => hir::PatKind::Path(self.lower_qpath(
3040                 p.id,
3041                 qself,
3042                 path,
3043                 ParamMode::Optional,
3044                 ImplTraitContext::Disallowed,
3045             )),
3046             PatKind::Struct(ref path, ref fields, etc) => {
3047                 let qpath = self.lower_qpath(
3048                     p.id,
3049                     &None,
3050                     path,
3051                     ParamMode::Optional,
3052                     ImplTraitContext::Disallowed,
3053                 );
3054
3055                 let fs = fields
3056                     .iter()
3057                     .map(|f| Spanned {
3058                         span: f.span,
3059                         node: hir::FieldPat {
3060                             id: self.next_id().node_id,
3061                             ident: f.node.ident,
3062                             pat: self.lower_pat(&f.node.pat),
3063                             is_shorthand: f.node.is_shorthand,
3064                         },
3065                     })
3066                     .collect();
3067                 hir::PatKind::Struct(qpath, fs, etc)
3068             }
3069             PatKind::Tuple(ref elts, ddpos) => {
3070                 hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos)
3071             }
3072             PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
3073             PatKind::Ref(ref inner, mutbl) => {
3074                 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
3075             }
3076             PatKind::Range(ref e1, ref e2, ref end) => hir::PatKind::Range(
3077                 P(self.lower_expr(e1)),
3078                 P(self.lower_expr(e2)),
3079                 self.lower_range_end(end),
3080             ),
3081             PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice(
3082                 before.iter().map(|x| self.lower_pat(x)).collect(),
3083                 slice.as_ref().map(|x| self.lower_pat(x)),
3084                 after.iter().map(|x| self.lower_pat(x)).collect(),
3085             ),
3086             PatKind::Paren(ref inner) => return self.lower_pat(inner),
3087             PatKind::Mac(_) => panic!("Shouldn't exist here"),
3088         };
3089
3090         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(p.id);
3091         P(hir::Pat {
3092             id: node_id,
3093             hir_id,
3094             node,
3095             span: p.span,
3096         })
3097     }
3098
3099     fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
3100         match *e {
3101             RangeEnd::Included(_) => hir::RangeEnd::Included,
3102             RangeEnd::Excluded => hir::RangeEnd::Excluded,
3103         }
3104     }
3105
3106     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
3107         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(c.id);
3108
3109         hir::AnonConst {
3110             id: node_id,
3111             hir_id,
3112             body: self.lower_body(None, |this| this.lower_expr(&c.value)),
3113         }
3114     }
3115
3116     fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
3117         let kind = match e.node {
3118             ExprKind::Box(ref inner) => hir::ExprBox(P(self.lower_expr(inner))),
3119             ExprKind::ObsoleteInPlace(..) => {
3120                 self.sess.abort_if_errors();
3121                 span_bug!(e.span, "encountered ObsoleteInPlace expr during lowering");
3122             }
3123             ExprKind::Array(ref exprs) => {
3124                 hir::ExprArray(exprs.iter().map(|x| self.lower_expr(x)).collect())
3125             }
3126             ExprKind::Repeat(ref expr, ref count) => {
3127                 let expr = P(self.lower_expr(expr));
3128                 let count = self.lower_anon_const(count);
3129                 hir::ExprRepeat(expr, count)
3130             }
3131             ExprKind::Tup(ref elts) => {
3132                 hir::ExprTup(elts.iter().map(|x| self.lower_expr(x)).collect())
3133             }
3134             ExprKind::Call(ref f, ref args) => {
3135                 let f = P(self.lower_expr(f));
3136                 hir::ExprCall(f, args.iter().map(|x| self.lower_expr(x)).collect())
3137             }
3138             ExprKind::MethodCall(ref seg, ref args) => {
3139                 let hir_seg = self.lower_path_segment(
3140                     e.span,
3141                     seg,
3142                     ParamMode::Optional,
3143                     0,
3144                     ParenthesizedGenericArgs::Err,
3145                     ImplTraitContext::Disallowed,
3146                 );
3147                 let args = args.iter().map(|x| self.lower_expr(x)).collect();
3148                 hir::ExprMethodCall(hir_seg, seg.ident.span, args)
3149             }
3150             ExprKind::Binary(binop, ref lhs, ref rhs) => {
3151                 let binop = self.lower_binop(binop);
3152                 let lhs = P(self.lower_expr(lhs));
3153                 let rhs = P(self.lower_expr(rhs));
3154                 hir::ExprBinary(binop, lhs, rhs)
3155             }
3156             ExprKind::Unary(op, ref ohs) => {
3157                 let op = self.lower_unop(op);
3158                 let ohs = P(self.lower_expr(ohs));
3159                 hir::ExprUnary(op, ohs)
3160             }
3161             ExprKind::Lit(ref l) => hir::ExprLit(P((**l).clone())),
3162             ExprKind::Cast(ref expr, ref ty) => {
3163                 let expr = P(self.lower_expr(expr));
3164                 hir::ExprCast(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3165             }
3166             ExprKind::Type(ref expr, ref ty) => {
3167                 let expr = P(self.lower_expr(expr));
3168                 hir::ExprType(expr, self.lower_ty(ty, ImplTraitContext::Disallowed))
3169             }
3170             ExprKind::AddrOf(m, ref ohs) => {
3171                 let m = self.lower_mutability(m);
3172                 let ohs = P(self.lower_expr(ohs));
3173                 hir::ExprAddrOf(m, ohs)
3174             }
3175             // More complicated than you might expect because the else branch
3176             // might be `if let`.
3177             ExprKind::If(ref cond, ref blk, ref else_opt) => {
3178                 let else_opt = else_opt.as_ref().map(|els| {
3179                     match els.node {
3180                         ExprKind::IfLet(..) => {
3181                             // wrap the if-let expr in a block
3182                             let span = els.span;
3183                             let els = P(self.lower_expr(els));
3184                             let LoweredNodeId { node_id, hir_id } = self.next_id();
3185                             let blk = P(hir::Block {
3186                                 stmts: hir_vec![],
3187                                 expr: Some(els),
3188                                 id: node_id,
3189                                 hir_id,
3190                                 rules: hir::DefaultBlock,
3191                                 span,
3192                                 targeted_by_break: false,
3193                                 recovered: blk.recovered,
3194                             });
3195                             P(self.expr_block(blk, ThinVec::new()))
3196                         }
3197                         _ => P(self.lower_expr(els)),
3198                     }
3199                 });
3200
3201                 let then_blk = self.lower_block(blk, false);
3202                 let then_expr = self.expr_block(then_blk, ThinVec::new());
3203
3204                 hir::ExprIf(P(self.lower_expr(cond)), P(then_expr), else_opt)
3205             }
3206             ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3207                 hir::ExprWhile(
3208                     this.with_loop_condition_scope(|this| P(this.lower_expr(cond))),
3209                     this.lower_block(body, false),
3210                     this.lower_label(opt_label),
3211                 )
3212             }),
3213             ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
3214                 hir::ExprLoop(
3215                     this.lower_block(body, false),
3216                     this.lower_label(opt_label),
3217                     hir::LoopSource::Loop,
3218                 )
3219             }),
3220             ExprKind::Catch(ref body) => {
3221                 self.with_catch_scope(body.id, |this| {
3222                     let unstable_span =
3223                         this.allow_internal_unstable(CompilerDesugaringKind::Catch, body.span);
3224                     let mut block = this.lower_block(body, true).into_inner();
3225                     let tail = block.expr.take().map_or_else(
3226                         || {
3227                             let LoweredNodeId { node_id, hir_id } = this.next_id();
3228                             let span = this.sess.codemap().end_point(unstable_span);
3229                             hir::Expr {
3230                                 id: node_id,
3231                                 span,
3232                                 node: hir::ExprTup(hir_vec![]),
3233                                 attrs: ThinVec::new(),
3234                                 hir_id,
3235                             }
3236                         },
3237                         |x: P<hir::Expr>| x.into_inner(),
3238                     );
3239                     block.expr = Some(this.wrap_in_try_constructor(
3240                         "from_ok", tail, unstable_span));
3241                     hir::ExprBlock(P(block), None)
3242                 })
3243             }
3244             ExprKind::Match(ref expr, ref arms) => hir::ExprMatch(
3245                 P(self.lower_expr(expr)),
3246                 arms.iter().map(|x| self.lower_arm(x)).collect(),
3247                 hir::MatchSource::Normal,
3248             ),
3249             ExprKind::Closure(capture_clause, movability, ref decl, ref body, fn_decl_span) => {
3250                 self.with_new_scopes(|this| {
3251                     let mut is_generator = false;
3252                     let body_id = this.lower_body(Some(decl), |this| {
3253                         let e = this.lower_expr(body);
3254                         is_generator = this.is_generator;
3255                         e
3256                     });
3257                     let generator_option = if is_generator {
3258                         if !decl.inputs.is_empty() {
3259                             span_err!(
3260                                 this.sess,
3261                                 fn_decl_span,
3262                                 E0628,
3263                                 "generators cannot have explicit arguments"
3264                             );
3265                             this.sess.abort_if_errors();
3266                         }
3267                         Some(match movability {
3268                             Movability::Movable => hir::GeneratorMovability::Movable,
3269                             Movability::Static => hir::GeneratorMovability::Static,
3270                         })
3271                     } else {
3272                         if movability == Movability::Static {
3273                             span_err!(
3274                                 this.sess,
3275                                 fn_decl_span,
3276                                 E0697,
3277                                 "closures cannot be static"
3278                             );
3279                         }
3280                         None
3281                     };
3282                     hir::ExprClosure(
3283                         this.lower_capture_clause(capture_clause),
3284                         this.lower_fn_decl(decl, None, false),
3285                         body_id,
3286                         fn_decl_span,
3287                         generator_option,
3288                     )
3289                 })
3290             }
3291             ExprKind::Block(ref blk, opt_label) => {
3292                 hir::ExprBlock(self.lower_block(blk,
3293                                                 opt_label.is_some()),
3294                                                 self.lower_label(opt_label))
3295             }
3296             ExprKind::Assign(ref el, ref er) => {
3297                 hir::ExprAssign(P(self.lower_expr(el)), P(self.lower_expr(er)))
3298             }
3299             ExprKind::AssignOp(op, ref el, ref er) => hir::ExprAssignOp(
3300                 self.lower_binop(op),
3301                 P(self.lower_expr(el)),
3302                 P(self.lower_expr(er)),
3303             ),
3304             ExprKind::Field(ref el, ident) => hir::ExprField(P(self.lower_expr(el)), ident),
3305             ExprKind::Index(ref el, ref er) => {
3306                 hir::ExprIndex(P(self.lower_expr(el)), P(self.lower_expr(er)))
3307             }
3308             // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
3309             ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
3310                 // FIXME: Use e.span directly after RangeInclusive::new() is stabilized in stage0.
3311                 let span = self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3312                 let id = self.next_id();
3313                 let e1 = self.lower_expr(e1);
3314                 let e2 = self.lower_expr(e2);
3315                 let ty_path = P(self.std_path(span, &["ops", "RangeInclusive"], false));
3316                 let ty = self.ty_path(id, span, hir::QPath::Resolved(None, ty_path));
3317                 let new_seg = P(hir::PathSegment::from_name(Symbol::intern("new")));
3318                 let new_path = hir::QPath::TypeRelative(ty, new_seg);
3319                 let new = P(self.expr(span, hir::ExprPath(new_path), ThinVec::new()));
3320                 hir::ExprCall(new, hir_vec![e1, e2])
3321             }
3322             ExprKind::Range(ref e1, ref e2, lims) => {
3323                 use syntax::ast::RangeLimits::*;
3324
3325                 let path = match (e1, e2, lims) {
3326                     (&None, &None, HalfOpen) => "RangeFull",
3327                     (&Some(..), &None, HalfOpen) => "RangeFrom",
3328                     (&None, &Some(..), HalfOpen) => "RangeTo",
3329                     (&Some(..), &Some(..), HalfOpen) => "Range",
3330                     (&None, &Some(..), Closed) => "RangeToInclusive",
3331                     (&Some(..), &Some(..), Closed) => unreachable!(),
3332                     (_, &None, Closed) => self.diagnostic()
3333                         .span_fatal(e.span, "inclusive range with no end")
3334                         .raise(),
3335                 };
3336
3337                 let fields = e1.iter()
3338                     .map(|e| ("start", e))
3339                     .chain(e2.iter().map(|e| ("end", e)))
3340                     .map(|(s, e)| {
3341                         let expr = P(self.lower_expr(&e));
3342                         let unstable_span =
3343                             self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3344                         let ident = Ident::new(Symbol::intern(s), unstable_span);
3345                         self.field(ident, expr, unstable_span)
3346                     })
3347                     .collect::<P<[hir::Field]>>();
3348
3349                 let is_unit = fields.is_empty();
3350                 let unstable_span =
3351                     self.allow_internal_unstable(CompilerDesugaringKind::DotFill, e.span);
3352                 let struct_path = iter::once("ops")
3353                     .chain(iter::once(path))
3354                     .collect::<Vec<_>>();
3355                 let struct_path = self.std_path(unstable_span, &struct_path, is_unit);
3356                 let struct_path = hir::QPath::Resolved(None, P(struct_path));
3357
3358                 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3359
3360                 return hir::Expr {
3361                     id: node_id,
3362                     hir_id,
3363                     node: if is_unit {
3364                         hir::ExprPath(struct_path)
3365                     } else {
3366                         hir::ExprStruct(struct_path, fields, None)
3367                     },
3368                     span: unstable_span,
3369                     attrs: e.attrs.clone(),
3370                 };
3371             }
3372             ExprKind::Path(ref qself, ref path) => hir::ExprPath(self.lower_qpath(
3373                 e.id,
3374                 qself,
3375                 path,
3376                 ParamMode::Optional,
3377                 ImplTraitContext::Disallowed,
3378             )),
3379             ExprKind::Break(opt_label, ref opt_expr) => {
3380                 let destination = if self.is_in_loop_condition && opt_label.is_none() {
3381                     hir::Destination {
3382                         label: None,
3383                         target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3384                     }
3385                 } else {
3386                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3387                 };
3388                 hir::ExprBreak(
3389                     destination,
3390                     opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
3391                 )
3392             }
3393             ExprKind::Continue(opt_label) => {
3394                 hir::ExprAgain(if self.is_in_loop_condition && opt_label.is_none() {
3395                     hir::Destination {
3396                         label: None,
3397                         target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
3398                     }
3399                 } else {
3400                     self.lower_loop_destination(opt_label.map(|label| (e.id, label)))
3401                 })
3402             }
3403             ExprKind::Ret(ref e) => hir::ExprRet(e.as_ref().map(|x| P(self.lower_expr(x)))),
3404             ExprKind::InlineAsm(ref asm) => {
3405                 let hir_asm = hir::InlineAsm {
3406                     inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
3407                     outputs: asm.outputs
3408                         .iter()
3409                         .map(|out| hir::InlineAsmOutput {
3410                             constraint: out.constraint.clone(),
3411                             is_rw: out.is_rw,
3412                             is_indirect: out.is_indirect,
3413                         })
3414                         .collect(),
3415                     asm: asm.asm.clone(),
3416                     asm_str_style: asm.asm_str_style,
3417                     clobbers: asm.clobbers.clone().into(),
3418                     volatile: asm.volatile,
3419                     alignstack: asm.alignstack,
3420                     dialect: asm.dialect,
3421                     ctxt: asm.ctxt,
3422                 };
3423                 let outputs = asm.outputs
3424                     .iter()
3425                     .map(|out| self.lower_expr(&out.expr))
3426                     .collect();
3427                 let inputs = asm.inputs
3428                     .iter()
3429                     .map(|&(_, ref input)| self.lower_expr(input))
3430                     .collect();
3431                 hir::ExprInlineAsm(P(hir_asm), outputs, inputs)
3432             }
3433             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprStruct(
3434                 self.lower_qpath(
3435                     e.id,
3436                     &None,
3437                     path,
3438                     ParamMode::Optional,
3439                     ImplTraitContext::Disallowed,
3440                 ),
3441                 fields.iter().map(|x| self.lower_field(x)).collect(),
3442                 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
3443             ),
3444             ExprKind::Paren(ref ex) => {
3445                 let mut ex = self.lower_expr(ex);
3446                 // include parens in span, but only if it is a super-span.
3447                 if e.span.contains(ex.span) {
3448                     ex.span = e.span;
3449                 }
3450                 // merge attributes into the inner expression.
3451                 let mut attrs = e.attrs.clone();
3452                 attrs.extend::<Vec<_>>(ex.attrs.into());
3453                 ex.attrs = attrs;
3454                 return ex;
3455             }
3456
3457             ExprKind::Yield(ref opt_expr) => {
3458                 self.is_generator = true;
3459                 let expr = opt_expr
3460                     .as_ref()
3461                     .map(|x| self.lower_expr(x))
3462                     .unwrap_or_else(|| self.expr(e.span, hir::ExprTup(hir_vec![]), ThinVec::new()));
3463                 hir::ExprYield(P(expr))
3464             }
3465
3466             // Desugar ExprIfLet
3467             // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
3468             ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
3469                 // to:
3470                 //
3471                 //   match <sub_expr> {
3472                 //     <pat> => <body>,
3473                 //     _ => [<else_opt> | ()]
3474                 //   }
3475
3476                 let mut arms = vec![];
3477
3478                 // `<pat> => <body>`
3479                 {
3480                     let body = self.lower_block(body, false);
3481                     let body_expr = P(self.expr_block(body, ThinVec::new()));
3482                     let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3483                     arms.push(self.arm(pats, body_expr));
3484                 }
3485
3486                 // _ => [<else_opt>|()]
3487                 {
3488                     let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p);
3489                     let wildcard_pattern = self.pat_wild(e.span);
3490                     let body = if let Some(else_expr) = wildcard_arm {
3491                         P(self.lower_expr(else_expr))
3492                     } else {
3493                         self.expr_tuple(e.span, hir_vec![])
3494                     };
3495                     arms.push(self.arm(hir_vec![wildcard_pattern], body));
3496                 }
3497
3498                 let contains_else_clause = else_opt.is_some();
3499
3500                 let sub_expr = P(self.lower_expr(sub_expr));
3501
3502                 hir::ExprMatch(
3503                     sub_expr,
3504                     arms.into(),
3505                     hir::MatchSource::IfLetDesugar {
3506                         contains_else_clause,
3507                     },
3508                 )
3509             }
3510
3511             // Desugar ExprWhileLet
3512             // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
3513             ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
3514                 // to:
3515                 //
3516                 //   [opt_ident]: loop {
3517                 //     match <sub_expr> {
3518                 //       <pat> => <body>,
3519                 //       _ => break
3520                 //     }
3521                 //   }
3522
3523                 // Note that the block AND the condition are evaluated in the loop scope.
3524                 // This is done to allow `break` from inside the condition of the loop.
3525                 let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| {
3526                     (
3527                         this.lower_block(body, false),
3528                         this.expr_break(e.span, ThinVec::new()),
3529                         this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))),
3530                     )
3531                 });
3532
3533                 // `<pat> => <body>`
3534                 let pat_arm = {
3535                     let body_expr = P(self.expr_block(body, ThinVec::new()));
3536                     let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect();
3537                     self.arm(pats, body_expr)
3538                 };
3539
3540                 // `_ => break`
3541                 let break_arm = {
3542                     let pat_under = self.pat_wild(e.span);
3543                     self.arm(hir_vec![pat_under], break_expr)
3544                 };
3545
3546                 // `match <sub_expr> { ... }`
3547                 let arms = hir_vec![pat_arm, break_arm];
3548                 let match_expr = self.expr(
3549                     sub_expr.span,
3550                     hir::ExprMatch(sub_expr, arms, hir::MatchSource::WhileLetDesugar),
3551                     ThinVec::new(),
3552                 );
3553
3554                 // `[opt_ident]: loop { ... }`
3555                 let loop_block = P(self.block_expr(P(match_expr)));
3556                 let loop_expr = hir::ExprLoop(
3557                     loop_block,
3558                     self.lower_label(opt_label),
3559                     hir::LoopSource::WhileLet,
3560                 );
3561                 // add attributes to the outer returned expr node
3562                 loop_expr
3563             }
3564
3565             // Desugar ExprForLoop
3566             // From: `[opt_ident]: for <pat> in <head> <body>`
3567             ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
3568                 // to:
3569                 //
3570                 //   {
3571                 //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
3572                 //       mut iter => {
3573                 //         [opt_ident]: loop {
3574                 //           let mut __next;
3575                 //           match ::std::iter::Iterator::next(&mut iter) {
3576                 //             ::std::option::Option::Some(val) => __next = val,
3577                 //             ::std::option::Option::None => break
3578                 //           };
3579                 //           let <pat> = __next;
3580                 //           StmtExpr(<body>);
3581                 //         }
3582                 //       }
3583                 //     };
3584                 //     result
3585                 //   }
3586
3587                 // expand <head>
3588                 let head = self.lower_expr(head);
3589                 let head_sp = head.span;
3590
3591                 let iter = self.str_to_ident("iter");
3592
3593                 let next_ident = self.str_to_ident("__next");
3594                 let next_pat = self.pat_ident_binding_mode(
3595                     pat.span,
3596                     next_ident,
3597                     hir::BindingAnnotation::Mutable,
3598                 );
3599
3600                 // `::std::option::Option::Some(val) => next = val`
3601                 let pat_arm = {
3602                     let val_ident = self.str_to_ident("val");
3603                     let val_pat = self.pat_ident(pat.span, val_ident);
3604                     let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat.id));
3605                     let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat.id));
3606                     let assign = P(self.expr(
3607                         pat.span,
3608                         hir::ExprAssign(next_expr, val_expr),
3609                         ThinVec::new(),
3610                     ));
3611                     let some_pat = self.pat_some(pat.span, val_pat);
3612                     self.arm(hir_vec![some_pat], assign)
3613                 };
3614
3615                 // `::std::option::Option::None => break`
3616                 let break_arm = {
3617                     let break_expr =
3618                         self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
3619                     let pat = self.pat_none(e.span);
3620                     self.arm(hir_vec![pat], break_expr)
3621                 };
3622
3623                 // `mut iter`
3624                 let iter_pat =
3625                     self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
3626
3627                 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
3628                 let match_expr = {
3629                     let iter = P(self.expr_ident(head_sp, iter, iter_pat.id));
3630                     let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
3631                     let next_path = &["iter", "Iterator", "next"];
3632                     let next_path = P(self.expr_std_path(head_sp, next_path, ThinVec::new()));
3633                     let next_expr = P(self.expr_call(head_sp, next_path, hir_vec![ref_mut_iter]));
3634                     let arms = hir_vec![pat_arm, break_arm];
3635
3636                     P(self.expr(
3637                         head_sp,
3638                         hir::ExprMatch(next_expr, arms, hir::MatchSource::ForLoopDesugar),
3639                         ThinVec::new(),
3640                     ))
3641                 };
3642                 let match_stmt = respan(head_sp, hir::StmtExpr(match_expr, self.next_id().node_id));
3643
3644                 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
3645
3646                 // `let mut __next`
3647                 let next_let =
3648                     self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
3649
3650                 // `let <pat> = __next`
3651                 let pat = self.lower_pat(pat);
3652                 let pat_let = self.stmt_let_pat(
3653                     head_sp,
3654                     Some(next_expr),
3655                     pat,
3656                     hir::LocalSource::ForLoopDesugar,
3657                 );
3658
3659                 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
3660                 let body_expr = P(self.expr_block(body_block, ThinVec::new()));
3661                 let body_stmt = respan(body.span, hir::StmtExpr(body_expr, self.next_id().node_id));
3662
3663                 let loop_block = P(self.block_all(
3664                     e.span,
3665                     hir_vec![next_let, match_stmt, pat_let, body_stmt],
3666                     None,
3667                 ));
3668
3669                 // `[opt_ident]: loop { ... }`
3670                 let loop_expr = hir::ExprLoop(
3671                     loop_block,
3672                     self.lower_label(opt_label),
3673                     hir::LoopSource::ForLoop,
3674                 );
3675                 let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3676                 let loop_expr = P(hir::Expr {
3677                     id: node_id,
3678                     hir_id,
3679                     node: loop_expr,
3680                     span: e.span,
3681                     attrs: ThinVec::new(),
3682                 });
3683
3684                 // `mut iter => { ... }`
3685                 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
3686
3687                 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
3688                 let into_iter_expr = {
3689                     let into_iter_path = &["iter", "IntoIterator", "into_iter"];
3690                     let into_iter = P(self.expr_std_path(head_sp, into_iter_path, ThinVec::new()));
3691                     P(self.expr_call(head_sp, into_iter, hir_vec![head]))
3692                 };
3693
3694                 let match_expr = P(self.expr_match(
3695                     head_sp,
3696                     into_iter_expr,
3697                     hir_vec![iter_arm],
3698                     hir::MatchSource::ForLoopDesugar,
3699                 ));
3700
3701                 // `{ let _result = ...; _result }`
3702                 // underscore prevents an unused_variables lint if the head diverges
3703                 let result_ident = self.str_to_ident("_result");
3704                 let (let_stmt, let_stmt_binding) =
3705                     self.stmt_let(e.span, false, result_ident, match_expr);
3706
3707                 let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
3708                 let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
3709                 // add the attributes to the outer returned expr node
3710                 return self.expr_block(block, e.attrs.clone());
3711             }
3712
3713             // Desugar ExprKind::Try
3714             // From: `<expr>?`
3715             ExprKind::Try(ref sub_expr) => {
3716                 // to:
3717                 //
3718                 // match Try::into_result(<expr>) {
3719                 //     Ok(val) => #[allow(unreachable_code)] val,
3720                 //     Err(err) => #[allow(unreachable_code)]
3721                 //                 // If there is an enclosing `catch {...}`
3722                 //                 break 'catch_target Try::from_error(From::from(err)),
3723                 //                 // Otherwise
3724                 //                 return Try::from_error(From::from(err)),
3725                 // }
3726
3727                 let unstable_span =
3728                     self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
3729
3730                 // Try::into_result(<expr>)
3731                 let discr = {
3732                     // expand <expr>
3733                     let sub_expr = self.lower_expr(sub_expr);
3734
3735                     let path = &["ops", "Try", "into_result"];
3736                     let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
3737                     P(self.expr_call(e.span, path, hir_vec![sub_expr]))
3738                 };
3739
3740                 // #[allow(unreachable_code)]
3741                 let attr = {
3742                     // allow(unreachable_code)
3743                     let allow = {
3744                         let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
3745                         let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
3746                         let uc_nested = attr::mk_nested_word_item(uc_ident);
3747                         attr::mk_list_item(e.span, allow_ident, vec![uc_nested])
3748                     };
3749                     attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow)
3750                 };
3751                 let attrs = vec![attr];
3752
3753                 // Ok(val) => #[allow(unreachable_code)] val,
3754                 let ok_arm = {
3755                     let val_ident = self.str_to_ident("val");
3756                     let val_pat = self.pat_ident(e.span, val_ident);
3757                     let val_expr = P(self.expr_ident_with_attrs(
3758                         e.span,
3759                         val_ident,
3760                         val_pat.id,
3761                         ThinVec::from(attrs.clone()),
3762                     ));
3763                     let ok_pat = self.pat_ok(e.span, val_pat);
3764
3765                     self.arm(hir_vec![ok_pat], val_expr)
3766                 };
3767
3768                 // Err(err) => #[allow(unreachable_code)]
3769                 //             return Try::from_error(From::from(err)),
3770                 let err_arm = {
3771                     let err_ident = self.str_to_ident("err");
3772                     let err_local = self.pat_ident(e.span, err_ident);
3773                     let from_expr = {
3774                         let path = &["convert", "From", "from"];
3775                         let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
3776                         let err_expr = self.expr_ident(e.span, err_ident, err_local.id);
3777
3778                         self.expr_call(e.span, from, hir_vec![err_expr])
3779                     };
3780                     let from_err_expr =
3781                         self.wrap_in_try_constructor("from_error", from_expr, unstable_span);
3782                     let thin_attrs = ThinVec::from(attrs);
3783                     let catch_scope = self.catch_scopes.last().map(|x| *x);
3784                     let ret_expr = if let Some(catch_node) = catch_scope {
3785                         P(self.expr(
3786                             e.span,
3787                             hir::ExprBreak(
3788                                 hir::Destination {
3789                                     label: None,
3790                                     target_id: Ok(catch_node),
3791                                 },
3792                                 Some(from_err_expr),
3793                             ),
3794                             thin_attrs,
3795                         ))
3796                     } else {
3797                         P(self.expr(e.span, hir::Expr_::ExprRet(Some(from_err_expr)), thin_attrs))
3798                     };
3799
3800                     let err_pat = self.pat_err(e.span, err_local);
3801                     self.arm(hir_vec![err_pat], ret_expr)
3802                 };
3803
3804                 hir::ExprMatch(
3805                     discr,
3806                     hir_vec![err_arm, ok_arm],
3807                     hir::MatchSource::TryDesugar,
3808                 )
3809             }
3810
3811             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
3812         };
3813
3814         let LoweredNodeId { node_id, hir_id } = self.lower_node_id(e.id);
3815
3816         hir::Expr {
3817             id: node_id,
3818             hir_id,
3819             node: kind,
3820             span: e.span,
3821             attrs: e.attrs.clone(),
3822         }
3823     }
3824
3825     fn lower_stmt(&mut self, s: &Stmt) -> SmallVector<hir::Stmt> {
3826         SmallVector::one(match s.node {
3827             StmtKind::Local(ref l) => Spanned {
3828                 node: hir::StmtDecl(
3829                     P(Spanned {
3830                         node: hir::DeclLocal(self.lower_local(l)),
3831                         span: s.span,
3832                     }),
3833                     self.lower_node_id(s.id).node_id,
3834                 ),
3835                 span: s.span,
3836             },
3837             StmtKind::Item(ref it) => {
3838                 // Can only use the ID once.
3839                 let mut id = Some(s.id);
3840                 return self.lower_item_id(it)
3841                     .into_iter()
3842                     .map(|item_id| Spanned {
3843                         node: hir::StmtDecl(
3844                             P(Spanned {
3845                                 node: hir::DeclItem(item_id),
3846                                 span: s.span,
3847                             }),
3848                             id.take()
3849                                 .map(|id| self.lower_node_id(id).node_id)
3850                                 .unwrap_or_else(|| self.next_id().node_id),
3851                         ),
3852                         span: s.span,
3853                     })
3854                     .collect();
3855             }
3856             StmtKind::Expr(ref e) => Spanned {
3857                 node: hir::StmtExpr(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3858                 span: s.span,
3859             },
3860             StmtKind::Semi(ref e) => Spanned {
3861                 node: hir::StmtSemi(P(self.lower_expr(e)), self.lower_node_id(s.id).node_id),
3862                 span: s.span,
3863             },
3864             StmtKind::Mac(..) => panic!("Shouldn't exist here"),
3865         })
3866     }
3867
3868     fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
3869         match c {
3870             CaptureBy::Value => hir::CaptureByValue,
3871             CaptureBy::Ref => hir::CaptureByRef,
3872         }
3873     }
3874
3875     /// If an `explicit_owner` is given, this method allocates the `HirId` in
3876     /// the address space of that item instead of the item currently being
3877     /// lowered. This can happen during `lower_impl_item_ref()` where we need to
3878     /// lower a `Visibility` value although we haven't lowered the owning
3879     /// `ImplItem` in question yet.
3880     fn lower_visibility(
3881         &mut self,
3882         v: &Visibility,
3883         explicit_owner: Option<NodeId>,
3884     ) -> hir::Visibility {
3885         match v.node {
3886             VisibilityKind::Public => hir::Public,
3887             VisibilityKind::Crate(sugar) => hir::Visibility::Crate(sugar),
3888             VisibilityKind::Restricted { ref path, id, .. } => hir::Visibility::Restricted {
3889                 path: P(self.lower_path(id, path, ParamMode::Explicit)),
3890                 id: if let Some(owner) = explicit_owner {
3891                     self.lower_node_id_with_owner(id, owner).node_id
3892                 } else {
3893                     self.lower_node_id(id).node_id
3894                 },
3895             },
3896             VisibilityKind::Inherited => hir::Inherited,
3897         }
3898     }
3899
3900     fn lower_defaultness(&mut self, d: Defaultness, has_value: bool) -> hir::Defaultness {
3901         match d {
3902             Defaultness::Default => hir::Defaultness::Default {
3903                 has_value: has_value,
3904             },
3905             Defaultness::Final => {
3906                 assert!(has_value);
3907                 hir::Defaultness::Final
3908             }
3909         }
3910     }
3911
3912     fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3913         match *b {
3914             BlockCheckMode::Default => hir::DefaultBlock,
3915             BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3916         }
3917     }
3918
3919     fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3920         match *b {
3921             BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3922             BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3923             BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3924             BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3925         }
3926     }
3927
3928     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3929         match u {
3930             CompilerGenerated => hir::CompilerGenerated,
3931             UserProvided => hir::UserProvided,
3932         }
3933     }
3934
3935     fn lower_impl_polarity(&mut self, i: ImplPolarity) -> hir::ImplPolarity {
3936         match i {
3937             ImplPolarity::Positive => hir::ImplPolarity::Positive,
3938             ImplPolarity::Negative => hir::ImplPolarity::Negative,
3939         }
3940     }
3941
3942     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3943         match f {
3944             TraitBoundModifier::None => hir::TraitBoundModifier::None,
3945             TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3946         }
3947     }
3948
3949     // Helper methods for building HIR.
3950
3951     fn arm(&mut self, pats: hir::HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
3952         hir::Arm {
3953             attrs: hir_vec![],
3954             pats,
3955             guard: None,
3956             body: expr,
3957         }
3958     }
3959
3960     fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
3961         hir::Field {
3962             id: self.next_id().node_id,
3963             ident,
3964             span,
3965             expr,
3966             is_shorthand: false,
3967         }
3968     }
3969
3970     fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
3971         let expr_break = hir::ExprBreak(self.lower_loop_destination(None), None);
3972         P(self.expr(span, expr_break, attrs))
3973     }
3974
3975     fn expr_call(
3976         &mut self,
3977         span: Span,
3978         e: P<hir::Expr>,
3979         args: hir::HirVec<hir::Expr>,
3980     ) -> hir::Expr {
3981         self.expr(span, hir::ExprCall(e, args), ThinVec::new())
3982     }
3983
3984     fn expr_ident(&mut self, span: Span, id: Name, binding: NodeId) -> hir::Expr {
3985         self.expr_ident_with_attrs(span, id, binding, ThinVec::new())
3986     }
3987
3988     fn expr_ident_with_attrs(
3989         &mut self,
3990         span: Span,
3991         id: Name,
3992         binding: NodeId,
3993         attrs: ThinVec<Attribute>,
3994     ) -> hir::Expr {
3995         let expr_path = hir::ExprPath(hir::QPath::Resolved(
3996             None,
3997             P(hir::Path {
3998                 span,
3999                 def: Def::Local(binding),
4000                 segments: hir_vec![hir::PathSegment::from_name(id)],
4001             }),
4002         ));
4003
4004         self.expr(span, expr_path, attrs)
4005     }
4006
4007     fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
4008         self.expr(span, hir::ExprAddrOf(hir::MutMutable, e), ThinVec::new())
4009     }
4010
4011     fn expr_std_path(
4012         &mut self,
4013         span: Span,
4014         components: &[&str],
4015         attrs: ThinVec<Attribute>,
4016     ) -> hir::Expr {
4017         let path = self.std_path(span, components, true);
4018         self.expr(
4019             span,
4020             hir::ExprPath(hir::QPath::Resolved(None, P(path))),
4021             attrs,
4022         )
4023     }
4024
4025     fn expr_match(
4026         &mut self,
4027         span: Span,
4028         arg: P<hir::Expr>,
4029         arms: hir::HirVec<hir::Arm>,
4030         source: hir::MatchSource,
4031     ) -> hir::Expr {
4032         self.expr(span, hir::ExprMatch(arg, arms, source), ThinVec::new())
4033     }
4034
4035     fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
4036         self.expr(b.span, hir::ExprBlock(b, None), attrs)
4037     }
4038
4039     fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> P<hir::Expr> {
4040         P(self.expr(sp, hir::ExprTup(exprs), ThinVec::new()))
4041     }
4042
4043     fn expr(&mut self, span: Span, node: hir::Expr_, attrs: ThinVec<Attribute>) -> hir::Expr {
4044         let LoweredNodeId { node_id, hir_id } = self.next_id();
4045         hir::Expr {
4046             id: node_id,
4047             hir_id,
4048             node,
4049             span,
4050             attrs,
4051         }
4052     }
4053
4054     fn stmt_let_pat(
4055         &mut self,
4056         sp: Span,
4057         ex: Option<P<hir::Expr>>,
4058         pat: P<hir::Pat>,
4059         source: hir::LocalSource,
4060     ) -> hir::Stmt {
4061         let LoweredNodeId { node_id, hir_id } = self.next_id();
4062
4063         let local = P(hir::Local {
4064             pat,
4065             ty: None,
4066             init: ex,
4067             id: node_id,
4068             hir_id,
4069             span: sp,
4070             attrs: ThinVec::new(),
4071             source,
4072         });
4073         let decl = respan(sp, hir::DeclLocal(local));
4074         respan(sp, hir::StmtDecl(P(decl), self.next_id().node_id))
4075     }
4076
4077     fn stmt_let(
4078         &mut self,
4079         sp: Span,
4080         mutbl: bool,
4081         ident: Name,
4082         ex: P<hir::Expr>,
4083     ) -> (hir::Stmt, NodeId) {
4084         let pat = if mutbl {
4085             self.pat_ident_binding_mode(sp, ident, hir::BindingAnnotation::Mutable)
4086         } else {
4087             self.pat_ident(sp, ident)
4088         };
4089         let pat_id = pat.id;
4090         (
4091             self.stmt_let_pat(sp, Some(ex), pat, hir::LocalSource::Normal),
4092             pat_id,
4093         )
4094     }
4095
4096     fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
4097         self.block_all(expr.span, hir::HirVec::new(), Some(expr))
4098     }
4099
4100     fn block_all(
4101         &mut self,
4102         span: Span,
4103         stmts: hir::HirVec<hir::Stmt>,
4104         expr: Option<P<hir::Expr>>,
4105     ) -> hir::Block {
4106         let LoweredNodeId { node_id, hir_id } = self.next_id();
4107
4108         hir::Block {
4109             stmts,
4110             expr,
4111             id: node_id,
4112             hir_id,
4113             rules: hir::DefaultBlock,
4114             span,
4115             targeted_by_break: false,
4116             recovered: false,
4117         }
4118     }
4119
4120     fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4121         self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
4122     }
4123
4124     fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4125         self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
4126     }
4127
4128     fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
4129         self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
4130     }
4131
4132     fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
4133         self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
4134     }
4135
4136     fn pat_std_enum(
4137         &mut self,
4138         span: Span,
4139         components: &[&str],
4140         subpats: hir::HirVec<P<hir::Pat>>,
4141     ) -> P<hir::Pat> {
4142         let path = self.std_path(span, components, true);
4143         let qpath = hir::QPath::Resolved(None, P(path));
4144         let pt = if subpats.is_empty() {
4145             hir::PatKind::Path(qpath)
4146         } else {
4147             hir::PatKind::TupleStruct(qpath, subpats, None)
4148         };
4149         self.pat(span, pt)
4150     }
4151
4152     fn pat_ident(&mut self, span: Span, name: Name) -> P<hir::Pat> {
4153         self.pat_ident_binding_mode(span, name, hir::BindingAnnotation::Unannotated)
4154     }
4155
4156     fn pat_ident_binding_mode(
4157         &mut self,
4158         span: Span,
4159         name: Name,
4160         bm: hir::BindingAnnotation,
4161     ) -> P<hir::Pat> {
4162         let LoweredNodeId { node_id, hir_id } = self.next_id();
4163
4164         P(hir::Pat {
4165             id: node_id,
4166             hir_id,
4167             node: hir::PatKind::Binding(bm, node_id, Spanned { span, node: name }, None),
4168             span,
4169         })
4170     }
4171
4172     fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
4173         self.pat(span, hir::PatKind::Wild)
4174     }
4175
4176     fn pat(&mut self, span: Span, pat: hir::PatKind) -> P<hir::Pat> {
4177         let LoweredNodeId { node_id, hir_id } = self.next_id();
4178         P(hir::Pat {
4179             id: node_id,
4180             hir_id,
4181             node: pat,
4182             span,
4183         })
4184     }
4185
4186     /// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
4187     /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
4188     /// The path is also resolved according to `is_value`.
4189     fn std_path(&mut self, span: Span, components: &[&str], is_value: bool) -> hir::Path {
4190         self.resolver
4191             .resolve_str_path(span, self.crate_root, components, is_value)
4192     }
4193
4194     fn ty_path(&mut self, id: LoweredNodeId, span: Span, qpath: hir::QPath) -> P<hir::Ty> {
4195         let mut id = id;
4196         let node = match qpath {
4197             hir::QPath::Resolved(None, path) => {
4198                 // Turn trait object paths into `TyTraitObject` instead.
4199                 if let Def::Trait(_) = path.def {
4200                     let principal = hir::PolyTraitRef {
4201                         bound_generic_params: hir::HirVec::new(),
4202                         trait_ref: hir::TraitRef {
4203                             path: path.and_then(|path| path),
4204                             ref_id: id.node_id,
4205                         },
4206                         span,
4207                     };
4208
4209                     // The original ID is taken by the `PolyTraitRef`,
4210                     // so the `Ty` itself needs a different one.
4211                     id = self.next_id();
4212                     hir::TyTraitObject(hir_vec![principal], self.elided_dyn_bound(span))
4213                 } else {
4214                     hir::TyPath(hir::QPath::Resolved(None, path))
4215                 }
4216             }
4217             _ => hir::TyPath(qpath),
4218         };
4219         P(hir::Ty {
4220             id: id.node_id,
4221             hir_id: id.hir_id,
4222             node,
4223             span,
4224         })
4225     }
4226
4227     /// Invoked to create the lifetime argument for a type `&T`
4228     /// with no explicit lifetime.
4229     fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
4230         match self.anonymous_lifetime_mode {
4231             // Intercept when we are in an impl header and introduce an in-band lifetime.
4232             // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
4233             // `'f`.
4234             AnonymousLifetimeMode::CreateParameter => {
4235                 let fresh_name = self.collect_fresh_in_band_lifetime(span);
4236                 hir::Lifetime {
4237                     id: self.next_id().node_id,
4238                     span,
4239                     name: fresh_name,
4240                 }
4241             }
4242
4243             AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
4244         }
4245     }
4246
4247     /// Invoked to create the lifetime argument(s) for a path like
4248     /// `std::cell::Ref<T>`; note that implicit lifetimes in these
4249     /// sorts of cases are deprecated. This may therefore report a warning or an
4250     /// error, depending on the mode.
4251     fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
4252         match self.anonymous_lifetime_mode {
4253             // NB. We intentionally ignore the create-parameter mode here
4254             // and instead "pass through" to resolve-lifetimes, which will then
4255             // report an error. This is because we don't want to support
4256             // impl elision for deprecated forms like
4257             //
4258             //     impl Foo for std::cell::Ref<u32> // note lack of '_
4259             AnonymousLifetimeMode::CreateParameter => {}
4260
4261             // This is the normal case.
4262             AnonymousLifetimeMode::PassThrough => {}
4263         }
4264
4265         (0..count)
4266             .map(|_| self.new_implicit_lifetime(span))
4267             .collect()
4268     }
4269
4270     /// Invoked to create the lifetime argument(s) for an elided trait object
4271     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
4272     /// when the bound is written, even if it is written with `'_` like in
4273     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
4274     fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
4275         match self.anonymous_lifetime_mode {
4276             // NB. We intentionally ignore the create-parameter mode here.
4277             // and instead "pass through" to resolve-lifetimes, which will apply
4278             // the object-lifetime-defaulting rules. Elided object lifetime defaults
4279             // do not act like other elided lifetimes. In other words, given this:
4280             //
4281             //     impl Foo for Box<dyn Debug>
4282             //
4283             // we do not introduce a fresh `'_` to serve as the bound, but instead
4284             // ultimately translate to the equivalent of:
4285             //
4286             //     impl Foo for Box<dyn Debug + 'static>
4287             //
4288             // `resolve_lifetime` has the code to make that happen.
4289             AnonymousLifetimeMode::CreateParameter => {}
4290
4291             // This is the normal case.
4292             AnonymousLifetimeMode::PassThrough => {}
4293         }
4294
4295         self.new_implicit_lifetime(span)
4296     }
4297
4298     fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
4299         hir::Lifetime {
4300             id: self.next_id().node_id,
4301             span,
4302             name: hir::LifetimeName::Implicit,
4303         }
4304     }
4305
4306     fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) {
4307         self.sess.buffer_lint_with_diagnostic(
4308             builtin::BARE_TRAIT_OBJECTS,
4309             id,
4310             span,
4311             "trait objects without an explicit `dyn` are deprecated",
4312             builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
4313         )
4314     }
4315
4316     fn wrap_in_try_constructor(
4317         &mut self,
4318         method: &'static str,
4319         e: hir::Expr,
4320         unstable_span: Span,
4321     ) -> P<hir::Expr> {
4322         let path = &["ops", "Try", method];
4323         let from_err = P(self.expr_std_path(unstable_span, path,
4324                                             ThinVec::new()));
4325         P(self.expr_call(e.span, from_err, hir_vec![e]))
4326     }
4327 }
4328
4329 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
4330     // Sorting by span ensures that we get things in order within a
4331     // file, and also puts the files in a sensible order.
4332     let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
4333     body_ids.sort_by_key(|b| bodies[b].value.span);
4334     body_ids
4335 }