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