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