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