]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering.rs
87ad4ace592386126c576547737e6f1ccbecc30b
[rust.git] / src / librustc / hir / lowering.rs
1 // ignore-tidy-filelength
2
3 //! Lowers the AST to the HIR.
4 //!
5 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
6 //! much like a fold. Where lowering involves a bit more work things get more
7 //! interesting and there are some invariants you should know about. These mostly
8 //! concern spans and IDs.
9 //!
10 //! Spans are assigned to AST nodes during parsing and then are modified during
11 //! expansion to indicate the origin of a node and the process it went through
12 //! being expanded. IDs are assigned to AST nodes just before lowering.
13 //!
14 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
15 //! expansion we do not preserve the process of lowering in the spans, so spans
16 //! should not be modified here. When creating a new node (as opposed to
17 //! 'folding' an existing one), then you create a new ID using `next_id()`.
18 //!
19 //! You must ensure that IDs are unique. That means that you should only use the
20 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
21 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
22 //! If you do, you must then set the new node's ID to a fresh one.
23 //!
24 //! Spans are used for error messages and for tools to map semantics back to
25 //! source code. It is therefore not as important with spans as IDs to be strict
26 //! about use (you can't break the compiler by screwing up a span). Obviously, a
27 //! HIR node can only have a single span. But multiple nodes can have the same
28 //! span and spans don't need to be kept in order, etc. Where code is preserved
29 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
30 //! new it is probably best to give a span for the whole AST node being lowered.
31 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
32 //! get confused if the spans from leaf AST nodes occur in multiple places
33 //! in the HIR, especially for multiple identifiers.
34
35 mod expr;
36 mod item;
37
38 use crate::dep_graph::DepGraph;
39 use crate::hir::{self, ParamName};
40 use crate::hir::HirVec;
41 use crate::hir::map::{DefKey, DefPathData, Definitions};
42 use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
43 use crate::hir::def::{Namespace, Res, DefKind, PartialRes, PerNS};
44 use crate::hir::{GenericArg, ConstArg};
45 use crate::hir::ptr::P;
46 use crate::lint;
47 use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
48                     ELIDED_LIFETIMES_IN_PATHS};
49 use crate::middle::cstore::CrateStore;
50 use crate::session::Session;
51 use crate::session::config::nightly_options;
52 use crate::util::common::FN_OUTPUT_NAME;
53 use crate::util::nodemap::{DefIdMap, NodeMap};
54 use errors::Applicability;
55 use rustc_data_structures::fx::FxHashSet;
56 use rustc_index::vec::IndexVec;
57 use rustc_data_structures::thin_vec::ThinVec;
58 use rustc_data_structures::sync::Lrc;
59
60 use std::collections::BTreeMap;
61 use std::mem;
62 use smallvec::SmallVec;
63 use syntax::attr;
64 use syntax::ast;
65 use syntax::ptr::P as AstP;
66 use syntax::ast::*;
67 use syntax::errors;
68 use syntax::print::pprust;
69 use syntax::token::{self, Nonterminal, Token};
70 use syntax::tokenstream::{TokenStream, TokenTree};
71 use syntax::sess::ParseSess;
72 use syntax::source_map::{respan, ExpnData, ExpnKind, DesugaringKind, Spanned};
73 use syntax::symbol::{kw, sym, Symbol};
74 use syntax::visit::{self, Visitor};
75 use syntax_pos::hygiene::ExpnId;
76 use syntax_pos::Span;
77
78 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
79
80 pub struct LoweringContext<'a> {
81     crate_root: Option<Symbol>,
82
83     /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
84     sess: &'a Session,
85
86     resolver: &'a mut dyn Resolver,
87
88     /// HACK(Centril): there is a cyclic dependency between the parser and lowering
89     /// if we don't have this function pointer. To avoid that dependency so that
90     /// librustc is independent of the parser, we use dynamic dispatch here.
91     nt_to_tokenstream: NtToTokenstream,
92
93     /// The items being lowered are collected here.
94     items: BTreeMap<hir::HirId, hir::Item>,
95
96     trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem>,
97     impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem>,
98     bodies: BTreeMap<hir::BodyId, hir::Body>,
99     exported_macros: Vec<hir::MacroDef>,
100     non_exported_macro_attrs: Vec<ast::Attribute>,
101
102     trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
103
104     modules: BTreeMap<hir::HirId, hir::ModuleItems>,
105
106     generator_kind: Option<hir::GeneratorKind>,
107
108     /// Used to get the current `fn`'s def span to point to when using `await`
109     /// outside of an `async fn`.
110     current_item: Option<Span>,
111
112     catch_scopes: Vec<NodeId>,
113     loop_scopes: Vec<NodeId>,
114     is_in_loop_condition: bool,
115     is_in_trait_impl: bool,
116     is_in_dyn_type: bool,
117
118     /// What to do when we encounter either an "anonymous lifetime
119     /// reference". The term "anonymous" is meant to encompass both
120     /// `'_` lifetimes as well as fully elided cases where nothing is
121     /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
122     anonymous_lifetime_mode: AnonymousLifetimeMode,
123
124     /// Used to create lifetime definitions from in-band lifetime usages.
125     /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
126     /// When a named lifetime is encountered in a function or impl header and
127     /// has not been defined
128     /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
129     /// to this list. The results of this list are then added to the list of
130     /// lifetime definitions in the corresponding impl or function generics.
131     lifetimes_to_define: Vec<(Span, ParamName)>,
132
133     /// `true` if in-band lifetimes are being collected. This is used to
134     /// indicate whether or not we're in a place where new lifetimes will result
135     /// in in-band lifetime definitions, such a function or an impl header,
136     /// including implicit lifetimes from `impl_header_lifetime_elision`.
137     is_collecting_in_band_lifetimes: bool,
138
139     /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
140     /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
141     /// against this list to see if it is already in-scope, or if a definition
142     /// needs to be created for it.
143     ///
144     /// We always store a `modern()` version of the param-name in this
145     /// vector.
146     in_scope_lifetimes: Vec<ParamName>,
147
148     current_module: hir::HirId,
149
150     type_def_lifetime_params: DefIdMap<usize>,
151
152     current_hir_id_owner: Vec<(DefIndex, u32)>,
153     item_local_id_counters: NodeMap<u32>,
154     node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
155
156     allow_try_trait: Option<Lrc<[Symbol]>>,
157     allow_gen_future: Option<Lrc<[Symbol]>>,
158 }
159
160 pub trait Resolver {
161     fn cstore(&self) -> &dyn CrateStore;
162
163     /// Obtains resolution for a `NodeId` with a single resolution.
164     fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
165
166     /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
167     fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
168
169     /// Obtains resolution for a label with the given `NodeId`.
170     fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
171
172     /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
173     /// This should only return `None` during testing.
174     fn definitions(&mut self) -> &mut Definitions;
175
176     /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
177     /// resolves it based on `is_value`.
178     fn resolve_str_path(
179         &mut self,
180         span: Span,
181         crate_root: Option<Symbol>,
182         components: &[Symbol],
183         ns: Namespace,
184     ) -> (ast::Path, Res<NodeId>);
185
186     fn lint_buffer(&mut self) -> &mut lint::LintBuffer;
187 }
188
189 type NtToTokenstream = fn(&Nonterminal, &ParseSess, Span) -> TokenStream;
190
191 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
192 /// and if so, what meaning it has.
193 #[derive(Debug)]
194 enum ImplTraitContext<'a> {
195     /// Treat `impl Trait` as shorthand for a new universal generic parameter.
196     /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
197     /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
198     ///
199     /// Newly generated parameters should be inserted into the given `Vec`.
200     Universal(&'a mut Vec<hir::GenericParam>),
201
202     /// Treat `impl Trait` as shorthand for a new opaque type.
203     /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
204     /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
205     ///
206     /// We optionally store a `DefId` for the parent item here so we can look up necessary
207     /// information later. It is `None` when no information about the context should be stored
208     /// (e.g., for consts and statics).
209     OpaqueTy(Option<DefId> /* fn def-ID */),
210
211     /// `impl Trait` is not accepted in this position.
212     Disallowed(ImplTraitPosition),
213 }
214
215 /// Position in which `impl Trait` is disallowed.
216 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
217 enum ImplTraitPosition {
218     /// Disallowed in `let` / `const` / `static` bindings.
219     Binding,
220
221     /// All other posiitons.
222     Other,
223 }
224
225 impl<'a> ImplTraitContext<'a> {
226     #[inline]
227     fn disallowed() -> Self {
228         ImplTraitContext::Disallowed(ImplTraitPosition::Other)
229     }
230
231     fn reborrow(&'b mut self) -> ImplTraitContext<'b> {
232         use self::ImplTraitContext::*;
233         match self {
234             Universal(params) => Universal(params),
235             OpaqueTy(fn_def_id) => OpaqueTy(*fn_def_id),
236             Disallowed(pos) => Disallowed(*pos),
237         }
238     }
239 }
240
241 pub fn lower_crate(
242     sess: &Session,
243     dep_graph: &DepGraph,
244     krate: &Crate,
245     resolver: &mut dyn Resolver,
246     nt_to_tokenstream: NtToTokenstream,
247 ) -> hir::Crate {
248     // We're constructing the HIR here; we don't care what we will
249     // read, since we haven't even constructed the *input* to
250     // incr. comp. yet.
251     dep_graph.assert_ignored();
252
253     let _prof_timer = sess.prof.generic_activity("hir_lowering");
254
255     LoweringContext {
256         crate_root: sess.parse_sess.injected_crate_name.try_get().copied(),
257         sess,
258         resolver,
259         nt_to_tokenstream,
260         items: BTreeMap::new(),
261         trait_items: BTreeMap::new(),
262         impl_items: BTreeMap::new(),
263         bodies: BTreeMap::new(),
264         trait_impls: BTreeMap::new(),
265         modules: BTreeMap::new(),
266         exported_macros: Vec::new(),
267         non_exported_macro_attrs: Vec::new(),
268         catch_scopes: Vec::new(),
269         loop_scopes: Vec::new(),
270         is_in_loop_condition: false,
271         is_in_trait_impl: false,
272         is_in_dyn_type: false,
273         anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
274         type_def_lifetime_params: Default::default(),
275         current_module: hir::CRATE_HIR_ID,
276         current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
277         item_local_id_counters: Default::default(),
278         node_id_to_hir_id: IndexVec::new(),
279         generator_kind: None,
280         current_item: None,
281         lifetimes_to_define: Vec::new(),
282         is_collecting_in_band_lifetimes: false,
283         in_scope_lifetimes: Vec::new(),
284         allow_try_trait: Some([sym::try_trait][..].into()),
285         allow_gen_future: Some([sym::gen_future][..].into()),
286     }.lower_crate(krate)
287 }
288
289 #[derive(Copy, Clone, PartialEq)]
290 enum ParamMode {
291     /// Any path in a type context.
292     Explicit,
293     /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
294     ExplicitNamed,
295     /// The `module::Type` in `module::Type::method` in an expression.
296     Optional,
297 }
298
299 enum ParenthesizedGenericArgs {
300     Ok,
301     Warn,
302     Err,
303 }
304
305 /// What to do when we encounter an **anonymous** lifetime
306 /// reference. Anonymous lifetime references come in two flavors. You
307 /// have implicit, or fully elided, references to lifetimes, like the
308 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
309 /// or `Ref<'_, T>`. These often behave the same, but not always:
310 ///
311 /// - certain usages of implicit references are deprecated, like
312 ///   `Ref<T>`, and we sometimes just give hard errors in those cases
313 ///   as well.
314 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
315 ///   the same as `Box<dyn Foo + '_>`.
316 ///
317 /// We describe the effects of the various modes in terms of three cases:
318 ///
319 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
320 ///   of a `&` (e.g., the missing lifetime in something like `&T`)
321 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
322 ///   there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
323 ///   elided bounds follow special rules. Note that this only covers
324 ///   cases where *nothing* is written; the `'_` in `Box<dyn Foo +
325 ///   '_>` is a case of "modern" elision.
326 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
327 ///   parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
328 ///   non-deprecated equivalent.
329 ///
330 /// Currently, the handling of lifetime elision is somewhat spread out
331 /// between HIR lowering and -- as described below -- the
332 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
333 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
334 /// everything into HIR lowering.
335 #[derive(Copy, Clone, Debug)]
336 enum AnonymousLifetimeMode {
337     /// For **Modern** cases, create a new anonymous region parameter
338     /// and reference that.
339     ///
340     /// For **Dyn Bound** cases, pass responsibility to
341     /// `resolve_lifetime` code.
342     ///
343     /// For **Deprecated** cases, report an error.
344     CreateParameter,
345
346     /// Give a hard error when either `&` or `'_` is written. Used to
347     /// rule out things like `where T: Foo<'_>`. Does not imply an
348     /// error on default object bounds (e.g., `Box<dyn Foo>`).
349     ReportError,
350
351     /// Pass responsibility to `resolve_lifetime` code for all cases.
352     PassThrough,
353 }
354
355 struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> }
356
357 impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> {
358     fn visit_ty(&mut self, ty: &'a Ty) {
359         match ty.kind {
360             | TyKind::Typeof(_)
361             | TyKind::BareFn(_)
362             => return,
363
364             TyKind::ImplTrait(id, _) => self.ids.push(id),
365             _ => {},
366         }
367         visit::walk_ty(self, ty);
368     }
369
370     fn visit_path_segment(
371         &mut self,
372         path_span: Span,
373         path_segment: &'v PathSegment,
374     ) {
375         if let Some(ref p) = path_segment.args {
376             if let GenericArgs::Parenthesized(_) = **p {
377                 return;
378             }
379         }
380         visit::walk_path_segment(self, path_span, path_segment)
381     }
382 }
383
384 impl<'a> LoweringContext<'a> {
385     fn lower_crate(mut self, c: &Crate) -> hir::Crate {
386         /// Full-crate AST visitor that inserts into a fresh
387         /// `LoweringContext` any information that may be
388         /// needed from arbitrary locations in the crate,
389         /// e.g., the number of lifetime generic parameters
390         /// declared for every type and trait definition.
391         struct MiscCollector<'tcx, 'interner> {
392             lctx: &'tcx mut LoweringContext<'interner>,
393             hir_id_owner: Option<NodeId>,
394         }
395
396         impl MiscCollector<'_, '_> {
397             fn allocate_use_tree_hir_id_counters(
398                 &mut self,
399                 tree: &UseTree,
400                 owner: DefIndex,
401             ) {
402                 match tree.kind {
403                     UseTreeKind::Simple(_, id1, id2) => {
404                         for &id in &[id1, id2] {
405                             self.lctx.resolver.definitions().create_def_with_parent(
406                                 owner,
407                                 id,
408                                 DefPathData::Misc,
409                                 ExpnId::root(),
410                                 tree.prefix.span,
411                             );
412                             self.lctx.allocate_hir_id_counter(id);
413                         }
414                     }
415                     UseTreeKind::Glob => (),
416                     UseTreeKind::Nested(ref trees) => {
417                         for &(ref use_tree, id) in trees {
418                             let hir_id = self.lctx.allocate_hir_id_counter(id);
419                             self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
420                         }
421                     }
422                 }
423             }
424
425             fn with_hir_id_owner<F, T>(&mut self, owner: Option<NodeId>, f: F) -> T
426             where
427                 F: FnOnce(&mut Self) -> T,
428             {
429                 let old = mem::replace(&mut self.hir_id_owner, owner);
430                 let r = f(self);
431                 self.hir_id_owner = old;
432                 r
433             }
434         }
435
436         impl<'tcx, 'interner> Visitor<'tcx> for MiscCollector<'tcx, 'interner> {
437             fn visit_pat(&mut self, p: &'tcx Pat) {
438                 if let PatKind::Paren(..) | PatKind::Rest = p.kind {
439                     // Doesn't generate a HIR node
440                 } else if let Some(owner) = self.hir_id_owner {
441                     self.lctx.lower_node_id_with_owner(p.id, owner);
442                 }
443
444                 visit::walk_pat(self, p)
445             }
446
447             fn visit_item(&mut self, item: &'tcx Item) {
448                 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
449
450                 match item.kind {
451                     ItemKind::Struct(_, ref generics)
452                     | ItemKind::Union(_, ref generics)
453                     | ItemKind::Enum(_, ref generics)
454                     | ItemKind::TyAlias(_, ref generics)
455                     | ItemKind::OpaqueTy(_, ref generics)
456                     | ItemKind::Trait(_, _, ref generics, ..) => {
457                         let def_id = self.lctx.resolver.definitions().local_def_id(item.id);
458                         let count = generics
459                             .params
460                             .iter()
461                             .filter(|param| match param.kind {
462                                 ast::GenericParamKind::Lifetime { .. } => true,
463                                 _ => false,
464                             })
465                             .count();
466                         self.lctx.type_def_lifetime_params.insert(def_id, count);
467                     }
468                     ItemKind::Use(ref use_tree) => {
469                         self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
470                     }
471                     _ => {}
472                 }
473
474                 self.with_hir_id_owner(Some(item.id), |this| {
475                     visit::walk_item(this, item);
476                 });
477             }
478
479             fn visit_trait_item(&mut self, item: &'tcx TraitItem) {
480                 self.lctx.allocate_hir_id_counter(item.id);
481
482                 match item.kind {
483                     TraitItemKind::Method(_, None) => {
484                         // Ignore patterns in trait methods without bodies
485                         self.with_hir_id_owner(None, |this| {
486                             visit::walk_trait_item(this, item)
487                         });
488                     }
489                     _ => self.with_hir_id_owner(Some(item.id), |this| {
490                         visit::walk_trait_item(this, item);
491                     })
492                 }
493             }
494
495             fn visit_impl_item(&mut self, item: &'tcx ImplItem) {
496                 self.lctx.allocate_hir_id_counter(item.id);
497                 self.with_hir_id_owner(Some(item.id), |this| {
498                     visit::walk_impl_item(this, item);
499                 });
500             }
501
502             fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
503                 // Ignore patterns in foreign items
504                 self.with_hir_id_owner(None, |this| {
505                     visit::walk_foreign_item(this, i)
506                 });
507             }
508
509             fn visit_ty(&mut self, t: &'tcx Ty) {
510                 match t.kind {
511                     // Mirrors the case in visit::walk_ty
512                     TyKind::BareFn(ref f) => {
513                         walk_list!(
514                             self,
515                             visit_generic_param,
516                             &f.generic_params
517                         );
518                         // Mirrors visit::walk_fn_decl
519                         for parameter in &f.decl.inputs {
520                             // We don't lower the ids of argument patterns
521                             self.with_hir_id_owner(None, |this| {
522                                 this.visit_pat(&parameter.pat);
523                             });
524                             self.visit_ty(&parameter.ty)
525                         }
526                         self.visit_fn_ret_ty(&f.decl.output)
527                     }
528                     _ => visit::walk_ty(self, t),
529                 }
530             }
531         }
532
533         self.lower_node_id(CRATE_NODE_ID);
534         debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == hir::CRATE_HIR_ID);
535
536         visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
537         visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
538
539         let module = self.lower_mod(&c.module);
540         let attrs = self.lower_attrs(&c.attrs);
541         let body_ids = body_ids(&self.bodies);
542
543         self.resolver
544             .definitions()
545             .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
546
547         hir::Crate {
548             module,
549             attrs,
550             span: c.span,
551             exported_macros: hir::HirVec::from(self.exported_macros),
552             non_exported_macro_attrs: hir::HirVec::from(self.non_exported_macro_attrs),
553             items: self.items,
554             trait_items: self.trait_items,
555             impl_items: self.impl_items,
556             bodies: self.bodies,
557             body_ids,
558             trait_impls: self.trait_impls,
559             modules: self.modules,
560         }
561     }
562
563     fn insert_item(&mut self, item: hir::Item) {
564         let id = item.hir_id;
565         // FIXME: Use `debug_asset-rt`.
566         assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
567         self.items.insert(id, item);
568         self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
569     }
570
571     fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
572         // Set up the counter if needed.
573         self.item_local_id_counters.entry(owner).or_insert(0);
574         // Always allocate the first `HirId` for the owner itself.
575         let lowered = self.lower_node_id_with_owner(owner, owner);
576         debug_assert_eq!(lowered.local_id.as_u32(), 0);
577         lowered
578     }
579
580     fn lower_node_id_generic<F>(&mut self, ast_node_id: NodeId, alloc_hir_id: F) -> hir::HirId
581     where
582         F: FnOnce(&mut Self) -> hir::HirId,
583     {
584         if ast_node_id == DUMMY_NODE_ID {
585             return hir::DUMMY_HIR_ID;
586         }
587
588         let min_size = ast_node_id.as_usize() + 1;
589
590         if min_size > self.node_id_to_hir_id.len() {
591             self.node_id_to_hir_id.resize(min_size, hir::DUMMY_HIR_ID);
592         }
593
594         let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
595
596         if existing_hir_id == hir::DUMMY_HIR_ID {
597             // Generate a new `HirId`.
598             let hir_id = alloc_hir_id(self);
599             self.node_id_to_hir_id[ast_node_id] = hir_id;
600
601             hir_id
602         } else {
603             existing_hir_id
604         }
605     }
606
607     fn with_hir_id_owner<F, T>(&mut self, owner: NodeId, f: F) -> T
608     where
609         F: FnOnce(&mut Self) -> T,
610     {
611         let counter = self.item_local_id_counters
612             .insert(owner, HIR_ID_COUNTER_LOCKED)
613             .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
614         let def_index = self.resolver.definitions().opt_def_index(owner).unwrap();
615         self.current_hir_id_owner.push((def_index, counter));
616         let ret = f(self);
617         let (new_def_index, new_counter) = self.current_hir_id_owner.pop().unwrap();
618
619         debug_assert!(def_index == new_def_index);
620         debug_assert!(new_counter >= counter);
621
622         let prev = self.item_local_id_counters
623             .insert(owner, new_counter)
624             .unwrap();
625         debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
626         ret
627     }
628
629     /// This method allocates a new `HirId` for the given `NodeId` and stores it in
630     /// the `LoweringContext`'s `NodeId => HirId` map.
631     /// Take care not to call this method if the resulting `HirId` is then not
632     /// actually used in the HIR, as that would trigger an assertion in the
633     /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
634     /// properly. Calling the method twice with the same `NodeId` is fine though.
635     fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
636         self.lower_node_id_generic(ast_node_id, |this| {
637             let &mut (def_index, ref mut local_id_counter) =
638                 this.current_hir_id_owner.last_mut().unwrap();
639             let local_id = *local_id_counter;
640             *local_id_counter += 1;
641             hir::HirId {
642                 owner: def_index,
643                 local_id: hir::ItemLocalId::from_u32(local_id),
644             }
645         })
646     }
647
648     fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
649         self.lower_node_id_generic(ast_node_id, |this| {
650             let local_id_counter = this
651                 .item_local_id_counters
652                 .get_mut(&owner)
653                 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
654             let local_id = *local_id_counter;
655
656             // We want to be sure not to modify the counter in the map while it
657             // is also on the stack. Otherwise we'll get lost updates when writing
658             // back from the stack to the map.
659             debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
660
661             *local_id_counter += 1;
662             let def_index = this
663                 .resolver
664                 .definitions()
665                 .opt_def_index(owner)
666                 .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \
667                          that do not belong to the current owner");
668
669             hir::HirId {
670                 owner: def_index,
671                 local_id: hir::ItemLocalId::from_u32(local_id),
672             }
673         })
674     }
675
676     fn next_id(&mut self) -> hir::HirId {
677         self.lower_node_id(self.sess.next_node_id())
678     }
679
680     fn lower_res(&mut self, res: Res<NodeId>) -> Res {
681         res.map_id(|id| {
682             self.lower_node_id_generic(id, |_| {
683                 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
684             })
685         })
686     }
687
688     fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
689         self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
690             if pr.unresolved_segments() != 0 {
691                 bug!("path not fully resolved: {:?}", pr);
692             }
693             pr.base_res()
694         })
695     }
696
697     fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
698         self.resolver.get_import_res(id).present_items()
699     }
700
701     fn diagnostic(&self) -> &errors::Handler {
702         self.sess.diagnostic()
703     }
704
705     /// Reuses the span but adds information like the kind of the desugaring and features that are
706     /// allowed inside this span.
707     fn mark_span_with_reason(
708         &self,
709         reason: DesugaringKind,
710         span: Span,
711         allow_internal_unstable: Option<Lrc<[Symbol]>>,
712     ) -> Span {
713         span.fresh_expansion(ExpnData {
714             allow_internal_unstable,
715             ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
716         })
717     }
718
719     fn with_anonymous_lifetime_mode<R>(
720         &mut self,
721         anonymous_lifetime_mode: AnonymousLifetimeMode,
722         op: impl FnOnce(&mut Self) -> R,
723     ) -> R {
724         debug!(
725             "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
726             anonymous_lifetime_mode,
727         );
728         let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
729         self.anonymous_lifetime_mode = anonymous_lifetime_mode;
730         let result = op(self);
731         self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
732         debug!("with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
733                old_anonymous_lifetime_mode);
734         result
735     }
736
737     /// Creates a new `hir::GenericParam` for every new lifetime and
738     /// type parameter encountered while evaluating `f`. Definitions
739     /// are created with the parent provided. If no `parent_id` is
740     /// provided, no definitions will be returned.
741     ///
742     /// Presuming that in-band lifetimes are enabled, then
743     /// `self.anonymous_lifetime_mode` will be updated to match the
744     /// parameter while `f` is running (and restored afterwards).
745     fn collect_in_band_defs<T, F>(
746         &mut self,
747         parent_id: DefId,
748         anonymous_lifetime_mode: AnonymousLifetimeMode,
749         f: F,
750     ) -> (Vec<hir::GenericParam>, T)
751     where
752         F: FnOnce(&mut LoweringContext<'_>) -> (Vec<hir::GenericParam>, T),
753     {
754         assert!(!self.is_collecting_in_band_lifetimes);
755         assert!(self.lifetimes_to_define.is_empty());
756         let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
757
758         self.anonymous_lifetime_mode = anonymous_lifetime_mode;
759         self.is_collecting_in_band_lifetimes = true;
760
761         let (in_band_ty_params, res) = f(self);
762
763         self.is_collecting_in_band_lifetimes = false;
764         self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
765
766         let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
767
768         let params = lifetimes_to_define
769             .into_iter()
770             .map(|(span, hir_name)| self.lifetime_to_generic_param(
771                 span, hir_name, parent_id.index,
772             ))
773             .chain(in_band_ty_params.into_iter())
774             .collect();
775
776         (params, res)
777     }
778
779     /// Converts a lifetime into a new generic parameter.
780     fn lifetime_to_generic_param(
781         &mut self,
782         span: Span,
783         hir_name: ParamName,
784         parent_index: DefIndex,
785     ) -> hir::GenericParam {
786         let node_id = self.sess.next_node_id();
787
788         // Get the name we'll use to make the def-path. Note
789         // that collisions are ok here and this shouldn't
790         // really show up for end-user.
791         let (str_name, kind) = match hir_name {
792             ParamName::Plain(ident) => (
793                 ident.name,
794                 hir::LifetimeParamKind::InBand,
795             ),
796             ParamName::Fresh(_) => (
797                 kw::UnderscoreLifetime,
798                 hir::LifetimeParamKind::Elided,
799             ),
800             ParamName::Error => (
801                 kw::UnderscoreLifetime,
802                 hir::LifetimeParamKind::Error,
803             ),
804         };
805
806         // Add a definition for the in-band lifetime def.
807         self.resolver.definitions().create_def_with_parent(
808             parent_index,
809             node_id,
810             DefPathData::LifetimeNs(str_name),
811             ExpnId::root(),
812             span,
813         );
814
815         hir::GenericParam {
816             hir_id: self.lower_node_id(node_id),
817             name: hir_name,
818             attrs: hir_vec![],
819             bounds: hir_vec![],
820             span,
821             pure_wrt_drop: false,
822             kind: hir::GenericParamKind::Lifetime { kind }
823         }
824     }
825
826     /// When there is a reference to some lifetime `'a`, and in-band
827     /// lifetimes are enabled, then we want to push that lifetime into
828     /// the vector of names to define later. In that case, it will get
829     /// added to the appropriate generics.
830     fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
831         if !self.is_collecting_in_band_lifetimes {
832             return;
833         }
834
835         if !self.sess.features_untracked().in_band_lifetimes {
836             return;
837         }
838
839         if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) {
840             return;
841         }
842
843         let hir_name = ParamName::Plain(ident);
844
845         if self.lifetimes_to_define.iter()
846                                    .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) {
847             return;
848         }
849
850         self.lifetimes_to_define.push((ident.span, hir_name));
851     }
852
853     /// When we have either an elided or `'_` lifetime in an impl
854     /// header, we convert it to an in-band lifetime.
855     fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
856         assert!(self.is_collecting_in_band_lifetimes);
857         let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
858         let hir_name = ParamName::Fresh(index);
859         self.lifetimes_to_define.push((span, hir_name));
860         hir_name
861     }
862
863     // Evaluates `f` with the lifetimes in `params` in-scope.
864     // This is used to track which lifetimes have already been defined, and
865     // which are new in-band lifetimes that need to have a definition created
866     // for them.
867     fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &[GenericParam], f: F) -> T
868     where
869         F: FnOnce(&mut LoweringContext<'_>) -> T,
870     {
871         let old_len = self.in_scope_lifetimes.len();
872         let lt_def_names = params.iter().filter_map(|param| match param.kind {
873             GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())),
874             _ => None,
875         });
876         self.in_scope_lifetimes.extend(lt_def_names);
877
878         let res = f(self);
879
880         self.in_scope_lifetimes.truncate(old_len);
881         res
882     }
883
884     /// Appends in-band lifetime defs and argument-position `impl
885     /// Trait` defs to the existing set of generics.
886     ///
887     /// Presuming that in-band lifetimes are enabled, then
888     /// `self.anonymous_lifetime_mode` will be updated to match the
889     /// parameter while `f` is running (and restored afterwards).
890     fn add_in_band_defs<F, T>(
891         &mut self,
892         generics: &Generics,
893         parent_id: DefId,
894         anonymous_lifetime_mode: AnonymousLifetimeMode,
895         f: F,
896     ) -> (hir::Generics, T)
897     where
898         F: FnOnce(&mut LoweringContext<'_>, &mut Vec<hir::GenericParam>) -> T,
899     {
900         let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
901             &generics.params,
902             |this| {
903                 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
904                     let mut params = Vec::new();
905                     // Note: it is necessary to lower generics *before* calling `f`.
906                     // When lowering `async fn`, there's a final step when lowering
907                     // the return type that assumes that all in-scope lifetimes have
908                     // already been added to either `in_scope_lifetimes` or
909                     // `lifetimes_to_define`. If we swapped the order of these two,
910                     // in-band-lifetimes introduced by generics or where-clauses
911                     // wouldn't have been added yet.
912                     let generics = this.lower_generics(
913                         generics,
914                         ImplTraitContext::Universal(&mut params),
915                     );
916                     let res = f(this, &mut params);
917                     (params, (generics, res))
918                 })
919             },
920         );
921
922         let mut lowered_params: Vec<_> = lowered_generics
923             .params
924             .into_iter()
925             .chain(in_band_defs)
926             .collect();
927
928         // FIXME(const_generics): the compiler doesn't always cope with
929         // unsorted generic parameters at the moment, so we make sure
930         // that they're ordered correctly here for now. (When we chain
931         // the `in_band_defs`, we might make the order unsorted.)
932         lowered_params.sort_by_key(|param| {
933             match param.kind {
934                 hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
935                 hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
936                 hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
937             }
938         });
939
940         lowered_generics.params = lowered_params.into();
941
942         (lowered_generics, res)
943     }
944
945     fn with_dyn_type_scope<T, F>(&mut self, in_scope: bool, f: F) -> T
946     where
947         F: FnOnce(&mut LoweringContext<'_>) -> T,
948     {
949         let was_in_dyn_type = self.is_in_dyn_type;
950         self.is_in_dyn_type = in_scope;
951
952         let result = f(self);
953
954         self.is_in_dyn_type = was_in_dyn_type;
955
956         result
957     }
958
959     fn with_new_scopes<T, F>(&mut self, f: F) -> T
960     where
961         F: FnOnce(&mut LoweringContext<'_>) -> T,
962     {
963         let was_in_loop_condition = self.is_in_loop_condition;
964         self.is_in_loop_condition = false;
965
966         let catch_scopes = mem::take(&mut self.catch_scopes);
967         let loop_scopes = mem::take(&mut self.loop_scopes);
968         let ret = f(self);
969         self.catch_scopes = catch_scopes;
970         self.loop_scopes = loop_scopes;
971
972         self.is_in_loop_condition = was_in_loop_condition;
973
974         ret
975     }
976
977     fn def_key(&mut self, id: DefId) -> DefKey {
978         if id.is_local() {
979             self.resolver.definitions().def_key(id.index)
980         } else {
981             self.resolver.cstore().def_key(id)
982         }
983     }
984
985     fn lower_attrs_extendable(&mut self, attrs: &[Attribute]) -> Vec<Attribute> {
986         attrs
987             .iter()
988             .map(|a| self.lower_attr(a))
989             .collect()
990     }
991
992     fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<Attribute> {
993         self.lower_attrs_extendable(attrs).into()
994     }
995
996     fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
997         // Note that we explicitly do not walk the path. Since we don't really
998         // lower attributes (we use the AST version) there is nowhere to keep
999         // the `HirId`s. We don't actually need HIR version of attributes anyway.
1000         let kind = match attr.kind {
1001             AttrKind::Normal(ref item) => {
1002                 AttrKind::Normal(AttrItem {
1003                     path: item.path.clone(),
1004                     tokens: self.lower_token_stream(item.tokens.clone()),
1005                 })
1006             }
1007             AttrKind::DocComment(comment) => AttrKind::DocComment(comment)
1008         };
1009
1010         Attribute {
1011             kind,
1012             id: attr.id,
1013             style: attr.style,
1014             span: attr.span,
1015         }
1016     }
1017
1018     fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1019         tokens
1020             .into_trees()
1021             .flat_map(|tree| self.lower_token_tree(tree).into_trees())
1022             .collect()
1023     }
1024
1025     fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1026         match tree {
1027             TokenTree::Token(token) => self.lower_token(token),
1028             TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
1029                 span,
1030                 delim,
1031                 self.lower_token_stream(tts),
1032             ).into(),
1033         }
1034     }
1035
1036     fn lower_token(&mut self, token: Token) -> TokenStream {
1037         match token.kind {
1038             token::Interpolated(nt) => {
1039                 let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span);
1040                 self.lower_token_stream(tts)
1041             }
1042             _ => TokenTree::Token(token).into(),
1043         }
1044     }
1045
1046     /// Given an associated type constraint like one of these:
1047     ///
1048     /// ```
1049     /// T: Iterator<Item: Debug>
1050     ///             ^^^^^^^^^^^
1051     /// T: Iterator<Item = Debug>
1052     ///             ^^^^^^^^^^^^
1053     /// ```
1054     ///
1055     /// returns a `hir::TypeBinding` representing `Item`.
1056     fn lower_assoc_ty_constraint(
1057         &mut self,
1058         constraint: &AssocTyConstraint,
1059         itctx: ImplTraitContext<'_>,
1060     ) -> hir::TypeBinding {
1061         debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1062
1063         let kind = match constraint.kind {
1064             AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality {
1065                 ty: self.lower_ty(ty, itctx)
1066             },
1067             AssocTyConstraintKind::Bound { ref bounds } => {
1068                 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1069                 let (desugar_to_impl_trait, itctx) = match itctx {
1070                     // We are in the return position:
1071                     //
1072                     //     fn foo() -> impl Iterator<Item: Debug>
1073                     //
1074                     // so desugar to
1075                     //
1076                     //     fn foo() -> impl Iterator<Item = impl Debug>
1077                     ImplTraitContext::OpaqueTy(_) => (true, itctx),
1078
1079                     // We are in the argument position, but within a dyn type:
1080                     //
1081                     //     fn foo(x: dyn Iterator<Item: Debug>)
1082                     //
1083                     // so desugar to
1084                     //
1085                     //     fn foo(x: dyn Iterator<Item = impl Debug>)
1086                     ImplTraitContext::Universal(_) if self.is_in_dyn_type => (true, itctx),
1087
1088                     // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1089                     // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1090                     // "impl trait context" to permit `impl Debug` in this position (it desugars
1091                     // then to an opaque type).
1092                     //
1093                     // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1094                     ImplTraitContext::Disallowed(_) if self.is_in_dyn_type =>
1095                         (true, ImplTraitContext::OpaqueTy(None)),
1096
1097                     // We are in the parameter position, but not within a dyn type:
1098                     //
1099                     //     fn foo(x: impl Iterator<Item: Debug>)
1100                     //
1101                     // so we leave it as is and this gets expanded in astconv to a bound like
1102                     // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1103                     // `impl Iterator`.
1104                     _ => (false, itctx),
1105                 };
1106
1107                 if desugar_to_impl_trait {
1108                     // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1109                     // constructing the HIR for `impl bounds...` and then lowering that.
1110
1111                     let impl_trait_node_id = self.sess.next_node_id();
1112                     let parent_def_index = self.current_hir_id_owner.last().unwrap().0;
1113                     self.resolver.definitions().create_def_with_parent(
1114                         parent_def_index,
1115                         impl_trait_node_id,
1116                         DefPathData::ImplTrait,
1117                         ExpnId::root(),
1118                         constraint.span,
1119                     );
1120
1121                     self.with_dyn_type_scope(false, |this| {
1122                         let ty = this.lower_ty(
1123                             &Ty {
1124                                 id: this.sess.next_node_id(),
1125                                 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1126                                 span: constraint.span,
1127                             },
1128                             itctx,
1129                         );
1130
1131                         hir::TypeBindingKind::Equality {
1132                             ty
1133                         }
1134                     })
1135                 } else {
1136                     // Desugar `AssocTy: Bounds` into a type binding where the
1137                     // later desugars into a trait predicate.
1138                     let bounds = self.lower_param_bounds(bounds, itctx);
1139
1140                     hir::TypeBindingKind::Constraint {
1141                         bounds
1142                     }
1143                 }
1144             }
1145         };
1146
1147         hir::TypeBinding {
1148             hir_id: self.lower_node_id(constraint.id),
1149             ident: constraint.ident,
1150             kind,
1151             span: constraint.span,
1152         }
1153     }
1154
1155     fn lower_generic_arg(&mut self,
1156                          arg: &ast::GenericArg,
1157                          itctx: ImplTraitContext<'_>)
1158                          -> hir::GenericArg {
1159         match arg {
1160             ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(&lt)),
1161             ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
1162             ast::GenericArg::Const(ct) => {
1163                 GenericArg::Const(ConstArg {
1164                     value: self.lower_anon_const(&ct),
1165                     span: ct.value.span,
1166                 })
1167             }
1168         }
1169     }
1170
1171     fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P<hir::Ty> {
1172         P(self.lower_ty_direct(t, itctx))
1173     }
1174
1175     fn lower_path_ty(
1176         &mut self,
1177         t: &Ty,
1178         qself: &Option<QSelf>,
1179         path: &Path,
1180         param_mode: ParamMode,
1181         itctx: ImplTraitContext<'_>
1182     ) -> hir::Ty {
1183         let id = self.lower_node_id(t.id);
1184         let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1185         let ty = self.ty_path(id, t.span, qpath);
1186         if let hir::TyKind::TraitObject(..) = ty.kind {
1187             self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1188         }
1189         ty
1190     }
1191
1192     fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty {
1193         let kind = match t.kind {
1194             TyKind::Infer => hir::TyKind::Infer,
1195             TyKind::Err => hir::TyKind::Err,
1196             TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1197             TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1198             TyKind::Rptr(ref region, ref mt) => {
1199                 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1200                 let lifetime = match *region {
1201                     Some(ref lt) => self.lower_lifetime(lt),
1202                     None => self.elided_ref_lifetime(span),
1203                 };
1204                 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1205             }
1206             TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
1207                 &f.generic_params,
1208                 |this| {
1209                     this.with_anonymous_lifetime_mode(
1210                         AnonymousLifetimeMode::PassThrough,
1211                         |this| {
1212                             hir::TyKind::BareFn(P(hir::BareFnTy {
1213                                 generic_params: this.lower_generic_params(
1214                                     &f.generic_params,
1215                                     &NodeMap::default(),
1216                                     ImplTraitContext::disallowed(),
1217                                 ),
1218                                 unsafety: this.lower_unsafety(f.unsafety),
1219                                 abi: this.lower_abi(f.abi),
1220                                 decl: this.lower_fn_decl(&f.decl, None, false, None),
1221                                 param_names: this.lower_fn_params_to_names(&f.decl),
1222                             }))
1223                         },
1224                     )
1225                 },
1226             ),
1227             TyKind::Never => hir::TyKind::Never,
1228             TyKind::Tup(ref tys) => {
1229                 hir::TyKind::Tup(tys.iter().map(|ty| {
1230                     self.lower_ty_direct(ty, itctx.reborrow())
1231                 }).collect())
1232             }
1233             TyKind::Paren(ref ty) => {
1234                 return self.lower_ty_direct(ty, itctx);
1235             }
1236             TyKind::Path(ref qself, ref path) => {
1237                 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1238             }
1239             TyKind::ImplicitSelf => {
1240                 let res = self.expect_full_res(t.id);
1241                 let res = self.lower_res(res);
1242                 hir::TyKind::Path(hir::QPath::Resolved(
1243                     None,
1244                     P(hir::Path {
1245                         res,
1246                         segments: hir_vec![hir::PathSegment::from_ident(
1247                             Ident::with_dummy_span(kw::SelfUpper)
1248                         )],
1249                         span: t.span,
1250                     }),
1251                 ))
1252             },
1253             TyKind::Array(ref ty, ref length) => {
1254                 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1255             }
1256             TyKind::Typeof(ref expr) => {
1257                 hir::TyKind::Typeof(self.lower_anon_const(expr))
1258             }
1259             TyKind::TraitObject(ref bounds, kind) => {
1260                 let mut lifetime_bound = None;
1261                 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1262                     let bounds = bounds
1263                         .iter()
1264                         .filter_map(|bound| match *bound {
1265                             GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
1266                                 Some(this.lower_poly_trait_ref(ty, itctx.reborrow()))
1267                             }
1268                             GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
1269                             GenericBound::Outlives(ref lifetime) => {
1270                                 if lifetime_bound.is_none() {
1271                                     lifetime_bound = Some(this.lower_lifetime(lifetime));
1272                                 }
1273                                 None
1274                             }
1275                         })
1276                         .collect();
1277                     let lifetime_bound =
1278                         lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1279                     (bounds, lifetime_bound)
1280                 });
1281                 if kind != TraitObjectSyntax::Dyn {
1282                     self.maybe_lint_bare_trait(t.span, t.id, false);
1283                 }
1284                 hir::TyKind::TraitObject(bounds, lifetime_bound)
1285             }
1286             TyKind::ImplTrait(def_node_id, ref bounds) => {
1287                 let span = t.span;
1288                 match itctx {
1289                     ImplTraitContext::OpaqueTy(fn_def_id) => {
1290                         self.lower_opaque_impl_trait(
1291                             span, fn_def_id, def_node_id,
1292                             |this| this.lower_param_bounds(bounds, itctx),
1293                         )
1294                     }
1295                     ImplTraitContext::Universal(in_band_ty_params) => {
1296                         // Add a definition for the in-band `Param`.
1297                         let def_index = self
1298                             .resolver
1299                             .definitions()
1300                             .opt_def_index(def_node_id)
1301                             .unwrap();
1302
1303                         let hir_bounds = self.lower_param_bounds(
1304                             bounds,
1305                             ImplTraitContext::Universal(in_band_ty_params),
1306                         );
1307                         // Set the name to `impl Bound1 + Bound2`.
1308                         let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1309                         in_band_ty_params.push(hir::GenericParam {
1310                             hir_id: self.lower_node_id(def_node_id),
1311                             name: ParamName::Plain(ident),
1312                             pure_wrt_drop: false,
1313                             attrs: hir_vec![],
1314                             bounds: hir_bounds,
1315                             span,
1316                             kind: hir::GenericParamKind::Type {
1317                                 default: None,
1318                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1319                             }
1320                         });
1321
1322                         hir::TyKind::Path(hir::QPath::Resolved(
1323                             None,
1324                             P(hir::Path {
1325                                 span,
1326                                 res: Res::Def(DefKind::TyParam, DefId::local(def_index)),
1327                                 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1328                             }),
1329                         ))
1330                     }
1331                     ImplTraitContext::Disallowed(pos) => {
1332                         let allowed_in = if self.sess.features_untracked()
1333                                                 .impl_trait_in_bindings {
1334                             "bindings or function and inherent method return types"
1335                         } else {
1336                             "function and inherent method return types"
1337                         };
1338                         let mut err = struct_span_err!(
1339                             self.sess,
1340                             t.span,
1341                             E0562,
1342                             "`impl Trait` not allowed outside of {}",
1343                             allowed_in,
1344                         );
1345                         if pos == ImplTraitPosition::Binding &&
1346                             nightly_options::is_nightly_build() {
1347                             help!(err,
1348                                   "add `#![feature(impl_trait_in_bindings)]` to the crate \
1349                                    attributes to enable");
1350                         }
1351                         err.emit();
1352                         hir::TyKind::Err
1353                     }
1354                 }
1355             }
1356             TyKind::Mac(_) => bug!("`TyKind::Mac` should have been expanded by now"),
1357             TyKind::CVarArgs => bug!("`TyKind::CVarArgs` should have been handled elsewhere"),
1358         };
1359
1360         hir::Ty {
1361             kind,
1362             span: t.span,
1363             hir_id: self.lower_node_id(t.id),
1364         }
1365     }
1366
1367     fn lower_opaque_impl_trait(
1368         &mut self,
1369         span: Span,
1370         fn_def_id: Option<DefId>,
1371         opaque_ty_node_id: NodeId,
1372         lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds,
1373     ) -> hir::TyKind {
1374         debug!(
1375             "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1376             fn_def_id,
1377             opaque_ty_node_id,
1378             span,
1379         );
1380
1381         // Make sure we know that some funky desugaring has been going on here.
1382         // This is a first: there is code in other places like for loop
1383         // desugaring that explicitly states that we don't want to track that.
1384         // Not tracking it makes lints in rustc and clippy very fragile, as
1385         // frequently opened issues show.
1386         let opaque_ty_span = self.mark_span_with_reason(
1387             DesugaringKind::OpaqueTy,
1388             span,
1389             None,
1390         );
1391
1392         let opaque_ty_def_index = self
1393             .resolver
1394             .definitions()
1395             .opt_def_index(opaque_ty_node_id)
1396             .unwrap();
1397
1398         self.allocate_hir_id_counter(opaque_ty_node_id);
1399
1400         let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1401
1402         let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1403             opaque_ty_node_id,
1404             opaque_ty_def_index,
1405             &hir_bounds,
1406         );
1407
1408         debug!(
1409             "lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,
1410         );
1411
1412         debug!(
1413             "lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,
1414         );
1415
1416         self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1417             let opaque_ty_item = hir::OpaqueTy {
1418                 generics: hir::Generics {
1419                     params: lifetime_defs,
1420                     where_clause: hir::WhereClause {
1421                         predicates: hir_vec![],
1422                         span,
1423                     },
1424                     span,
1425                 },
1426                 bounds: hir_bounds,
1427                 impl_trait_fn: fn_def_id,
1428                 origin: hir::OpaqueTyOrigin::FnReturn,
1429             };
1430
1431             trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_index);
1432             let opaque_ty_id = lctx.generate_opaque_type(
1433                 opaque_ty_node_id,
1434                 opaque_ty_item,
1435                 span,
1436                 opaque_ty_span,
1437             );
1438
1439             // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1440             hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes)
1441         })
1442     }
1443
1444     /// Registers a new opaque type with the proper `NodeId`s and
1445     /// returns the lowered node-ID for the opaque type.
1446     fn generate_opaque_type(
1447         &mut self,
1448         opaque_ty_node_id: NodeId,
1449         opaque_ty_item: hir::OpaqueTy,
1450         span: Span,
1451         opaque_ty_span: Span,
1452     ) -> hir::HirId {
1453         let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1454         let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1455         // Generate an `type Foo = impl Trait;` declaration.
1456         trace!("registering opaque type with id {:#?}", opaque_ty_id);
1457         let opaque_ty_item = hir::Item {
1458             hir_id: opaque_ty_id,
1459             ident: Ident::invalid(),
1460             attrs: Default::default(),
1461             kind: opaque_ty_item_kind,
1462             vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1463             span: opaque_ty_span,
1464         };
1465
1466         // Insert the item into the global item list. This usually happens
1467         // automatically for all AST items. But this opaque type item
1468         // does not actually exist in the AST.
1469         self.insert_item(opaque_ty_item);
1470         opaque_ty_id
1471     }
1472
1473     fn lifetimes_from_impl_trait_bounds(
1474         &mut self,
1475         opaque_ty_id: NodeId,
1476         parent_index: DefIndex,
1477         bounds: &hir::GenericBounds,
1478     ) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
1479         debug!(
1480             "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1481              parent_index={:?}, \
1482              bounds={:#?})",
1483             opaque_ty_id, parent_index, bounds,
1484         );
1485
1486         // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1487         // appear in the bounds, excluding lifetimes that are created within the bounds.
1488         // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1489         struct ImplTraitLifetimeCollector<'r, 'a> {
1490             context: &'r mut LoweringContext<'a>,
1491             parent: DefIndex,
1492             opaque_ty_id: NodeId,
1493             collect_elided_lifetimes: bool,
1494             currently_bound_lifetimes: Vec<hir::LifetimeName>,
1495             already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1496             output_lifetimes: Vec<hir::GenericArg>,
1497             output_lifetime_params: Vec<hir::GenericParam>,
1498         }
1499
1500         impl<'r, 'a, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
1501             fn nested_visit_map<'this>(
1502                 &'this mut self,
1503             ) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1504                 hir::intravisit::NestedVisitorMap::None
1505             }
1506
1507             fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
1508                 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1509                 if parameters.parenthesized {
1510                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1511                     self.collect_elided_lifetimes = false;
1512                     hir::intravisit::walk_generic_args(self, span, parameters);
1513                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1514                 } else {
1515                     hir::intravisit::walk_generic_args(self, span, parameters);
1516                 }
1517             }
1518
1519             fn visit_ty(&mut self, t: &'v hir::Ty) {
1520                 // Don't collect elided lifetimes used inside of `fn()` syntax.
1521                 if let hir::TyKind::BareFn(_) = t.kind {
1522                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1523                     self.collect_elided_lifetimes = false;
1524
1525                     // Record the "stack height" of `for<'a>` lifetime bindings
1526                     // to be able to later fully undo their introduction.
1527                     let old_len = self.currently_bound_lifetimes.len();
1528                     hir::intravisit::walk_ty(self, t);
1529                     self.currently_bound_lifetimes.truncate(old_len);
1530
1531                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1532                 } else {
1533                     hir::intravisit::walk_ty(self, t)
1534                 }
1535             }
1536
1537             fn visit_poly_trait_ref(
1538                 &mut self,
1539                 trait_ref: &'v hir::PolyTraitRef,
1540                 modifier: hir::TraitBoundModifier,
1541             ) {
1542                 // Record the "stack height" of `for<'a>` lifetime bindings
1543                 // to be able to later fully undo their introduction.
1544                 let old_len = self.currently_bound_lifetimes.len();
1545                 hir::intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1546                 self.currently_bound_lifetimes.truncate(old_len);
1547             }
1548
1549             fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
1550                 // Record the introduction of 'a in `for<'a> ...`.
1551                 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1552                     // Introduce lifetimes one at a time so that we can handle
1553                     // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1554                     let lt_name = hir::LifetimeName::Param(param.name);
1555                     self.currently_bound_lifetimes.push(lt_name);
1556                 }
1557
1558                 hir::intravisit::walk_generic_param(self, param);
1559             }
1560
1561             fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1562                 let name = match lifetime.name {
1563                     hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1564                         if self.collect_elided_lifetimes {
1565                             // Use `'_` for both implicit and underscore lifetimes in
1566                             // `type Foo<'_> = impl SomeTrait<'_>;`.
1567                             hir::LifetimeName::Underscore
1568                         } else {
1569                             return;
1570                         }
1571                     }
1572                     hir::LifetimeName::Param(_) => lifetime.name,
1573
1574                     // Refers to some other lifetime that is "in
1575                     // scope" within the type.
1576                     hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1577
1578                     hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1579                 };
1580
1581                 if !self.currently_bound_lifetimes.contains(&name)
1582                     && !self.already_defined_lifetimes.contains(&name) {
1583                     self.already_defined_lifetimes.insert(name);
1584
1585                     self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1586                         hir_id: self.context.next_id(),
1587                         span: lifetime.span,
1588                         name,
1589                     }));
1590
1591                     let def_node_id = self.context.sess.next_node_id();
1592                     let hir_id =
1593                         self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1594                     self.context.resolver.definitions().create_def_with_parent(
1595                         self.parent,
1596                         def_node_id,
1597                         DefPathData::LifetimeNs(name.ident().name),
1598                         ExpnId::root(),
1599                         lifetime.span);
1600
1601                     let (name, kind) = match name {
1602                         hir::LifetimeName::Underscore => (
1603                             hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1604                             hir::LifetimeParamKind::Elided,
1605                         ),
1606                         hir::LifetimeName::Param(param_name) => (
1607                             param_name,
1608                             hir::LifetimeParamKind::Explicit,
1609                         ),
1610                         _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1611                     };
1612
1613                     self.output_lifetime_params.push(hir::GenericParam {
1614                         hir_id,
1615                         name,
1616                         span: lifetime.span,
1617                         pure_wrt_drop: false,
1618                         attrs: hir_vec![],
1619                         bounds: hir_vec![],
1620                         kind: hir::GenericParamKind::Lifetime { kind }
1621                     });
1622                 }
1623             }
1624         }
1625
1626         let mut lifetime_collector = ImplTraitLifetimeCollector {
1627             context: self,
1628             parent: parent_index,
1629             opaque_ty_id,
1630             collect_elided_lifetimes: true,
1631             currently_bound_lifetimes: Vec::new(),
1632             already_defined_lifetimes: FxHashSet::default(),
1633             output_lifetimes: Vec::new(),
1634             output_lifetime_params: Vec::new(),
1635         };
1636
1637         for bound in bounds {
1638             hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1639         }
1640
1641         (
1642             lifetime_collector.output_lifetimes.into(),
1643             lifetime_collector.output_lifetime_params.into(),
1644         )
1645     }
1646
1647     fn lower_qpath(
1648         &mut self,
1649         id: NodeId,
1650         qself: &Option<QSelf>,
1651         p: &Path,
1652         param_mode: ParamMode,
1653         mut itctx: ImplTraitContext<'_>,
1654     ) -> hir::QPath {
1655         let qself_position = qself.as_ref().map(|q| q.position);
1656         let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
1657
1658         let partial_res = self.resolver
1659             .get_partial_res(id)
1660             .unwrap_or_else(|| PartialRes::new(Res::Err));
1661
1662         let proj_start = p.segments.len() - partial_res.unresolved_segments();
1663         let path = P(hir::Path {
1664             res: self.lower_res(partial_res.base_res()),
1665             segments: p.segments[..proj_start]
1666                 .iter()
1667                 .enumerate()
1668                 .map(|(i, segment)| {
1669                     let param_mode = match (qself_position, param_mode) {
1670                         (Some(j), ParamMode::Optional) if i < j => {
1671                             // This segment is part of the trait path in a
1672                             // qualified path - one of `a`, `b` or `Trait`
1673                             // in `<X as a::b::Trait>::T::U::method`.
1674                             ParamMode::Explicit
1675                         }
1676                         _ => param_mode,
1677                     };
1678
1679                     // Figure out if this is a type/trait segment,
1680                     // which may need lifetime elision performed.
1681                     let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
1682                         krate: def_id.krate,
1683                         index: this.def_key(def_id).parent.expect("missing parent"),
1684                     };
1685                     let type_def_id = match partial_res.base_res() {
1686                         Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1687                             Some(parent_def_id(self, def_id))
1688                         }
1689                         Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1690                             Some(parent_def_id(self, def_id))
1691                         }
1692                         Res::Def(DefKind::Struct, def_id)
1693                         | Res::Def(DefKind::Union, def_id)
1694                         | Res::Def(DefKind::Enum, def_id)
1695                         | Res::Def(DefKind::TyAlias, def_id)
1696                         | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start =>
1697                         {
1698                             Some(def_id)
1699                         }
1700                         _ => None,
1701                     };
1702                     let parenthesized_generic_args = match partial_res.base_res() {
1703                         // `a::b::Trait(Args)`
1704                         Res::Def(DefKind::Trait, _)
1705                             if i + 1 == proj_start => ParenthesizedGenericArgs::Ok,
1706                         // `a::b::Trait(Args)::TraitItem`
1707                         Res::Def(DefKind::Method, _)
1708                         | Res::Def(DefKind::AssocConst, _)
1709                         | Res::Def(DefKind::AssocTy, _)
1710                             if i + 2 == proj_start =>
1711                         {
1712                             ParenthesizedGenericArgs::Ok
1713                         }
1714                         // Avoid duplicated errors.
1715                         Res::Err => ParenthesizedGenericArgs::Ok,
1716                         // An error
1717                         Res::Def(DefKind::Struct, _)
1718                         | Res::Def(DefKind::Enum, _)
1719                         | Res::Def(DefKind::Union, _)
1720                         | Res::Def(DefKind::TyAlias, _)
1721                         | Res::Def(DefKind::Variant, _) if i + 1 == proj_start =>
1722                         {
1723                             ParenthesizedGenericArgs::Err
1724                         }
1725                         // A warning for now, for compatibility reasons.
1726                         _ => ParenthesizedGenericArgs::Warn,
1727                     };
1728
1729                     let num_lifetimes = type_def_id.map_or(0, |def_id| {
1730                         if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
1731                             return n;
1732                         }
1733                         assert!(!def_id.is_local());
1734                         let item_generics = self.resolver.cstore()
1735                             .item_generics_cloned_untracked(def_id, self.sess);
1736                         let n = item_generics.own_counts().lifetimes;
1737                         self.type_def_lifetime_params.insert(def_id, n);
1738                         n
1739                     });
1740                     self.lower_path_segment(
1741                         p.span,
1742                         segment,
1743                         param_mode,
1744                         num_lifetimes,
1745                         parenthesized_generic_args,
1746                         itctx.reborrow(),
1747                         None,
1748                     )
1749                 })
1750                 .collect(),
1751             span: p.span,
1752         });
1753
1754         // Simple case, either no projections, or only fully-qualified.
1755         // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
1756         if partial_res.unresolved_segments() == 0 {
1757             return hir::QPath::Resolved(qself, path);
1758         }
1759
1760         // Create the innermost type that we're projecting from.
1761         let mut ty = if path.segments.is_empty() {
1762             // If the base path is empty that means there exists a
1763             // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
1764             qself.expect("missing QSelf for <T>::...")
1765         } else {
1766             // Otherwise, the base path is an implicit `Self` type path,
1767             // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
1768             // `<I as Iterator>::Item::default`.
1769             let new_id = self.next_id();
1770             P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
1771         };
1772
1773         // Anything after the base path are associated "extensions",
1774         // out of which all but the last one are associated types,
1775         // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
1776         // * base path is `std::vec::Vec<T>`
1777         // * "extensions" are `IntoIter`, `Item` and `clone`
1778         // * type nodes are:
1779         //   1. `std::vec::Vec<T>` (created above)
1780         //   2. `<std::vec::Vec<T>>::IntoIter`
1781         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
1782         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
1783         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
1784             let segment = P(self.lower_path_segment(
1785                 p.span,
1786                 segment,
1787                 param_mode,
1788                 0,
1789                 ParenthesizedGenericArgs::Warn,
1790                 itctx.reborrow(),
1791                 None,
1792             ));
1793             let qpath = hir::QPath::TypeRelative(ty, segment);
1794
1795             // It's finished, return the extension of the right node type.
1796             if i == p.segments.len() - 1 {
1797                 return qpath;
1798             }
1799
1800             // Wrap the associated extension in another type node.
1801             let new_id = self.next_id();
1802             ty = P(self.ty_path(new_id, p.span, qpath));
1803         }
1804
1805         // We should've returned in the for loop above.
1806         span_bug!(
1807             p.span,
1808             "lower_qpath: no final extension segment in {}..{}",
1809             proj_start,
1810             p.segments.len()
1811         )
1812     }
1813
1814     fn lower_path_extra(
1815         &mut self,
1816         res: Res,
1817         p: &Path,
1818         param_mode: ParamMode,
1819         explicit_owner: Option<NodeId>,
1820     ) -> hir::Path {
1821         hir::Path {
1822             res,
1823             segments: p.segments
1824                 .iter()
1825                 .map(|segment| {
1826                     self.lower_path_segment(
1827                         p.span,
1828                         segment,
1829                         param_mode,
1830                         0,
1831                         ParenthesizedGenericArgs::Err,
1832                         ImplTraitContext::disallowed(),
1833                         explicit_owner,
1834                     )
1835                 })
1836                 .collect(),
1837             span: p.span,
1838         }
1839     }
1840
1841     fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path {
1842         let res = self.expect_full_res(id);
1843         let res = self.lower_res(res);
1844         self.lower_path_extra(res, p, param_mode, None)
1845     }
1846
1847     fn lower_path_segment(
1848         &mut self,
1849         path_span: Span,
1850         segment: &PathSegment,
1851         param_mode: ParamMode,
1852         expected_lifetimes: usize,
1853         parenthesized_generic_args: ParenthesizedGenericArgs,
1854         itctx: ImplTraitContext<'_>,
1855         explicit_owner: Option<NodeId>,
1856     ) -> hir::PathSegment {
1857         let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
1858             let msg = "parenthesized type parameters may only be used with a `Fn` trait";
1859             match **generic_args {
1860                 GenericArgs::AngleBracketed(ref data) => {
1861                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
1862                 }
1863                 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
1864                     ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
1865                     ParenthesizedGenericArgs::Warn => {
1866                         self.resolver.lint_buffer().buffer_lint(
1867                             PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
1868                             CRATE_NODE_ID,
1869                             data.span,
1870                             msg.into(),
1871                         );
1872                         (hir::GenericArgs::none(), true)
1873                     }
1874                     ParenthesizedGenericArgs::Err => {
1875                         let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
1876                         err.span_label(data.span, "only `Fn` traits may use parentheses");
1877                         if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
1878                             // Do not suggest going from `Trait()` to `Trait<>`
1879                             if data.inputs.len() > 0 {
1880                                 let split = snippet.find('(').unwrap();
1881                                 let trait_name = &snippet[0..split];
1882                                 let args = &snippet[split + 1 .. snippet.len() - 1];
1883                                 err.span_suggestion(
1884                                     data.span,
1885                                     "use angle brackets instead",
1886                                     format!("{}<{}>", trait_name, args),
1887                                     Applicability::MaybeIncorrect,
1888                                 );
1889                             }
1890                         };
1891                         err.emit();
1892                         (
1893                             self.lower_angle_bracketed_parameter_data(
1894                                 &data.as_angle_bracketed_args(),
1895                                 param_mode,
1896                                 itctx
1897                             ).0,
1898                             false,
1899                         )
1900                     }
1901                 },
1902             }
1903         } else {
1904             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
1905         };
1906
1907         let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
1908             GenericArg::Lifetime(_) => true,
1909             _ => false,
1910         });
1911         let first_generic_span = generic_args.args.iter().map(|a| a.span())
1912             .chain(generic_args.bindings.iter().map(|b| b.span)).next();
1913         if !generic_args.parenthesized && !has_lifetimes {
1914             generic_args.args =
1915                 self.elided_path_lifetimes(path_span, expected_lifetimes)
1916                     .into_iter()
1917                     .map(|lt| GenericArg::Lifetime(lt))
1918                     .chain(generic_args.args.into_iter())
1919                 .collect();
1920             if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
1921                 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
1922                 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
1923                 let no_bindings = generic_args.bindings.is_empty();
1924                 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
1925                     // If there are no (non-implicit) generic args or associated type
1926                     // bindings, our suggestion includes the angle brackets.
1927                     (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
1928                 } else {
1929                     // Otherwise (sorry, this is kind of gross) we need to infer the
1930                     // place to splice in the `'_, ` from the generics that do exist.
1931                     let first_generic_span = first_generic_span
1932                         .expect("already checked that non-lifetime args or bindings exist");
1933                     (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
1934                 };
1935                 match self.anonymous_lifetime_mode {
1936                     // In create-parameter mode we error here because we don't want to support
1937                     // deprecated impl elision in new features like impl elision and `async fn`,
1938                     // both of which work using the `CreateParameter` mode:
1939                     //
1940                     //     impl Foo for std::cell::Ref<u32> // note lack of '_
1941                     //     async fn foo(_: std::cell::Ref<u32>) { ... }
1942                     AnonymousLifetimeMode::CreateParameter => {
1943                         let mut err = struct_span_err!(
1944                             self.sess,
1945                             path_span,
1946                             E0726,
1947                             "implicit elided lifetime not allowed here"
1948                         );
1949                         crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
1950                             &self.sess,
1951                             &mut err,
1952                             expected_lifetimes,
1953                             path_span,
1954                             incl_angl_brckt,
1955                             insertion_sp,
1956                             suggestion,
1957                         );
1958                         err.emit();
1959                     }
1960                     AnonymousLifetimeMode::PassThrough |
1961                     AnonymousLifetimeMode::ReportError => {
1962                         self.resolver.lint_buffer().buffer_lint_with_diagnostic(
1963                             ELIDED_LIFETIMES_IN_PATHS,
1964                             CRATE_NODE_ID,
1965                             path_span,
1966                             "hidden lifetime parameters in types are deprecated",
1967                             builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1968                                 expected_lifetimes,
1969                                 path_span,
1970                                 incl_angl_brckt,
1971                                 insertion_sp,
1972                                 suggestion,
1973                             )
1974                         );
1975                     }
1976                 }
1977             }
1978         }
1979
1980         let res = self.expect_full_res(segment.id);
1981         let id = if let Some(owner) = explicit_owner {
1982             self.lower_node_id_with_owner(segment.id, owner)
1983         } else {
1984             self.lower_node_id(segment.id)
1985         };
1986         debug!(
1987             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
1988             segment.ident, segment.id, id,
1989         );
1990
1991         hir::PathSegment::new(
1992             segment.ident,
1993             Some(id),
1994             Some(self.lower_res(res)),
1995             generic_args,
1996             infer_args,
1997         )
1998     }
1999
2000     fn lower_angle_bracketed_parameter_data(
2001         &mut self,
2002         data: &AngleBracketedArgs,
2003         param_mode: ParamMode,
2004         mut itctx: ImplTraitContext<'_>,
2005     ) -> (hir::GenericArgs, bool) {
2006         let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
2007         let has_non_lt_args = args.iter().any(|arg| match arg {
2008             ast::GenericArg::Lifetime(_) => false,
2009             ast::GenericArg::Type(_) => true,
2010             ast::GenericArg::Const(_) => true,
2011         });
2012         (
2013             hir::GenericArgs {
2014                 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
2015                 bindings: constraints.iter()
2016                     .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow()))
2017                     .collect(),
2018                 parenthesized: false,
2019             },
2020             !has_non_lt_args && param_mode == ParamMode::Optional
2021         )
2022     }
2023
2024     fn lower_parenthesized_parameter_data(
2025         &mut self,
2026         data: &ParenthesizedArgs,
2027     ) -> (hir::GenericArgs, bool) {
2028         // Switch to `PassThrough` mode for anonymous lifetimes; this
2029         // means that we permit things like `&Ref<T>`, where `Ref` has
2030         // a hidden lifetime parameter. This is needed for backwards
2031         // compatibility, even in contexts like an impl header where
2032         // we generally don't permit such things (see #51008).
2033         self.with_anonymous_lifetime_mode(
2034             AnonymousLifetimeMode::PassThrough,
2035             |this| {
2036                 let &ParenthesizedArgs { ref inputs, ref output, span } = data;
2037                 let inputs = inputs
2038                     .iter()
2039                     .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed()))
2040                     .collect();
2041                 let mk_tup = |this: &mut Self, tys, span| {
2042                     hir::Ty { kind: hir::TyKind::Tup(tys), hir_id: this.next_id(), span }
2043                 };
2044                 (
2045                     hir::GenericArgs {
2046                         args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
2047                         bindings: hir_vec![
2048                             hir::TypeBinding {
2049                                 hir_id: this.next_id(),
2050                                 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2051                                 kind: hir::TypeBindingKind::Equality {
2052                                     ty: output
2053                                         .as_ref()
2054                                         .map(|ty| this.lower_ty(
2055                                             &ty,
2056                                             ImplTraitContext::disallowed()
2057                                         ))
2058                                         .unwrap_or_else(||
2059                                             P(mk_tup(this, hir::HirVec::new(), span))
2060                                         ),
2061                                 },
2062                                 span: output.as_ref().map_or(span, |ty| ty.span),
2063                             }
2064                         ],
2065                         parenthesized: true,
2066                     },
2067                     false,
2068                 )
2069             }
2070         )
2071     }
2072
2073     fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) {
2074         let mut ids = SmallVec::<[NodeId; 1]>::new();
2075         if self.sess.features_untracked().impl_trait_in_bindings {
2076             if let Some(ref ty) = l.ty {
2077                 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
2078                 visitor.visit_ty(ty);
2079             }
2080         }
2081         let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0);
2082         (hir::Local {
2083             hir_id: self.lower_node_id(l.id),
2084             ty: l.ty
2085                 .as_ref()
2086                 .map(|t| self.lower_ty(t,
2087                     if self.sess.features_untracked().impl_trait_in_bindings {
2088                         ImplTraitContext::OpaqueTy(Some(parent_def_id))
2089                     } else {
2090                         ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
2091                     }
2092                 )),
2093             pat: self.lower_pat(&l.pat),
2094             init: l.init.as_ref().map(|e| P(self.lower_expr(e))),
2095             span: l.span,
2096             attrs: l.attrs.clone(),
2097             source: hir::LocalSource::Normal,
2098         }, ids)
2099     }
2100
2101     fn lower_mutability(&mut self, m: Mutability) -> hir::Mutability {
2102         match m {
2103             Mutability::Mutable => hir::MutMutable,
2104             Mutability::Immutable => hir::MutImmutable,
2105         }
2106     }
2107
2108     fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<Ident> {
2109         // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2110         // as they are not explicit in HIR/Ty function signatures.
2111         // (instead, the `c_variadic` flag is set to `true`)
2112         let mut inputs = &decl.inputs[..];
2113         if decl.c_variadic() {
2114             inputs = &inputs[..inputs.len() - 1];
2115         }
2116         inputs
2117             .iter()
2118             .map(|param| match param.pat.kind {
2119                 PatKind::Ident(_, ident, _) => ident,
2120                 _ => Ident::new(kw::Invalid, param.pat.span),
2121             })
2122             .collect()
2123     }
2124
2125     // Lowers a function declaration.
2126     //
2127     // `decl`: the unlowered (AST) function declaration.
2128     // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
2129     //      given DefId, otherwise impl Trait is disallowed. Must be `Some` if
2130     //      `make_ret_async` is also `Some`.
2131     // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
2132     //      This guards against trait declarations and implementations where `impl Trait` is
2133     //      disallowed.
2134     // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
2135     //      return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
2136     //      return type `impl Trait` item.
2137     fn lower_fn_decl(
2138         &mut self,
2139         decl: &FnDecl,
2140         mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam>)>,
2141         impl_trait_return_allow: bool,
2142         make_ret_async: Option<NodeId>,
2143     ) -> P<hir::FnDecl> {
2144         let lt_mode = if make_ret_async.is_some() {
2145             // In `async fn`, argument-position elided lifetimes
2146             // must be transformed into fresh generic parameters so that
2147             // they can be applied to the opaque `impl Trait` return type.
2148             AnonymousLifetimeMode::CreateParameter
2149         } else {
2150             self.anonymous_lifetime_mode
2151         };
2152
2153         let c_variadic = decl.c_variadic();
2154
2155         // Remember how many lifetimes were already around so that we can
2156         // only look at the lifetime parameters introduced by the arguments.
2157         let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
2158             // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
2159             // as they are not explicit in HIR/Ty function signatures.
2160             // (instead, the `c_variadic` flag is set to `true`)
2161             let mut inputs = &decl.inputs[..];
2162             if c_variadic {
2163                 inputs = &inputs[..inputs.len() - 1];
2164             }
2165             inputs
2166                 .iter()
2167                 .map(|param| {
2168                     if let Some((_, ibty)) = &mut in_band_ty_params {
2169                         this.lower_ty_direct(&param.ty, ImplTraitContext::Universal(ibty))
2170                     } else {
2171                         this.lower_ty_direct(&param.ty, ImplTraitContext::disallowed())
2172                     }
2173                 })
2174                 .collect::<HirVec<_>>()
2175         });
2176
2177         let output = if let Some(ret_id) = make_ret_async {
2178             self.lower_async_fn_ret_ty(
2179                 &decl.output,
2180                 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
2181                 ret_id,
2182             )
2183         } else {
2184             match decl.output {
2185                 FunctionRetTy::Ty(ref ty) => match in_band_ty_params {
2186                     Some((def_id, _)) if impl_trait_return_allow => {
2187                         hir::Return(self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(def_id))))
2188                     }
2189                     _ => {
2190                         hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed()))
2191                     }
2192                 },
2193                 FunctionRetTy::Default(span) => hir::DefaultReturn(span),
2194             }
2195         };
2196
2197         P(hir::FnDecl {
2198             inputs,
2199             output,
2200             c_variadic,
2201             implicit_self: decl.inputs.get(0).map_or(
2202                 hir::ImplicitSelfKind::None,
2203                 |arg| {
2204                     let is_mutable_pat = match arg.pat.kind {
2205                         PatKind::Ident(BindingMode::ByValue(mt), _, _) |
2206                         PatKind::Ident(BindingMode::ByRef(mt), _, _) =>
2207                             mt == Mutability::Mutable,
2208                         _ => false,
2209                     };
2210
2211                     match arg.ty.kind {
2212                         TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2213                         TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2214                         // Given we are only considering `ImplicitSelf` types, we needn't consider
2215                         // the case where we have a mutable pattern to a reference as that would
2216                         // no longer be an `ImplicitSelf`.
2217                         TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() &&
2218                             mt.mutbl == ast::Mutability::Mutable =>
2219                                 hir::ImplicitSelfKind::MutRef,
2220                         TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() =>
2221                             hir::ImplicitSelfKind::ImmRef,
2222                         _ => hir::ImplicitSelfKind::None,
2223                     }
2224                 },
2225             ),
2226         })
2227     }
2228
2229     // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2230     // combined with the following definition of `OpaqueTy`:
2231     //
2232     //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2233     //
2234     // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
2235     // `output`: unlowered output type (`T` in `-> T`)
2236     // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
2237     // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2238     // `elided_lt_replacement`: replacement for elided lifetimes in the return type
2239     fn lower_async_fn_ret_ty(
2240         &mut self,
2241         output: &FunctionRetTy,
2242         fn_def_id: DefId,
2243         opaque_ty_node_id: NodeId,
2244     ) -> hir::FunctionRetTy {
2245         debug!(
2246             "lower_async_fn_ret_ty(\
2247              output={:?}, \
2248              fn_def_id={:?}, \
2249              opaque_ty_node_id={:?})",
2250             output, fn_def_id, opaque_ty_node_id,
2251         );
2252
2253         let span = output.span();
2254
2255         let opaque_ty_span = self.mark_span_with_reason(
2256             DesugaringKind::Async,
2257             span,
2258             None,
2259         );
2260
2261         let opaque_ty_def_index = self
2262             .resolver
2263             .definitions()
2264             .opt_def_index(opaque_ty_node_id)
2265             .unwrap();
2266
2267         self.allocate_hir_id_counter(opaque_ty_node_id);
2268
2269         // When we create the opaque type for this async fn, it is going to have
2270         // to capture all the lifetimes involved in the signature (including in the
2271         // return type). This is done by introducing lifetime parameters for:
2272         //
2273         // - all the explicitly declared lifetimes from the impl and function itself;
2274         // - all the elided lifetimes in the fn arguments;
2275         // - all the elided lifetimes in the return type.
2276         //
2277         // So for example in this snippet:
2278         //
2279         // ```rust
2280         // impl<'a> Foo<'a> {
2281         //   async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
2282         //   //               ^ '0                       ^ '1     ^ '2
2283         //   // elided lifetimes used below
2284         //   }
2285         // }
2286         // ```
2287         //
2288         // we would create an opaque type like:
2289         //
2290         // ```
2291         // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
2292         // ```
2293         //
2294         // and we would then desugar `bar` to the equivalent of:
2295         //
2296         // ```rust
2297         // impl<'a> Foo<'a> {
2298         //   fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
2299         // }
2300         // ```
2301         //
2302         // Note that the final parameter to `Bar` is `'_`, not `'2` --
2303         // this is because the elided lifetimes from the return type
2304         // should be figured out using the ordinary elision rules, and
2305         // this desugaring achieves that.
2306         //
2307         // The variable `input_lifetimes_count` tracks the number of
2308         // lifetime parameters to the opaque type *not counting* those
2309         // lifetimes elided in the return type. This includes those
2310         // that are explicitly declared (`in_scope_lifetimes`) and
2311         // those elided lifetimes we found in the arguments (current
2312         // content of `lifetimes_to_define`). Next, we will process
2313         // the return type, which will cause `lifetimes_to_define` to
2314         // grow.
2315         let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
2316
2317         let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
2318             // We have to be careful to get elision right here. The
2319             // idea is that we create a lifetime parameter for each
2320             // lifetime in the return type.  So, given a return type
2321             // like `async fn foo(..) -> &[&u32]`, we lower to `impl
2322             // Future<Output = &'1 [ &'2 u32 ]>`.
2323             //
2324             // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
2325             // hence the elision takes place at the fn site.
2326             let future_bound = this.with_anonymous_lifetime_mode(
2327                 AnonymousLifetimeMode::CreateParameter,
2328                 |this| this.lower_async_fn_output_type_to_future_bound(
2329                     output,
2330                     fn_def_id,
2331                     span,
2332                 ),
2333             );
2334
2335             debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
2336
2337             // Calculate all the lifetimes that should be captured
2338             // by the opaque type. This should include all in-scope
2339             // lifetime parameters, including those defined in-band.
2340             //
2341             // Note: this must be done after lowering the output type,
2342             // as the output type may introduce new in-band lifetimes.
2343             let lifetime_params: Vec<(Span, ParamName)> =
2344                 this.in_scope_lifetimes
2345                     .iter().cloned()
2346                     .map(|name| (name.ident().span, name))
2347                     .chain(this.lifetimes_to_define.iter().cloned())
2348                     .collect();
2349
2350             debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
2351             debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
2352             debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
2353
2354             let generic_params =
2355                 lifetime_params
2356                     .iter().cloned()
2357                     .map(|(span, hir_name)| {
2358                         this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_index)
2359                     })
2360                     .collect();
2361
2362             let opaque_ty_item = hir::OpaqueTy {
2363                 generics: hir::Generics {
2364                     params: generic_params,
2365                     where_clause: hir::WhereClause {
2366                         predicates: hir_vec![],
2367                         span,
2368                     },
2369                     span,
2370                 },
2371                 bounds: hir_vec![future_bound],
2372                 impl_trait_fn: Some(fn_def_id),
2373                 origin: hir::OpaqueTyOrigin::AsyncFn,
2374             };
2375
2376             trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index);
2377             let opaque_ty_id = this.generate_opaque_type(
2378                 opaque_ty_node_id,
2379                 opaque_ty_item,
2380                 span,
2381                 opaque_ty_span,
2382             );
2383
2384             (opaque_ty_id, lifetime_params)
2385         });
2386
2387         // As documented above on the variable
2388         // `input_lifetimes_count`, we need to create the lifetime
2389         // arguments to our opaque type. Continuing with our example,
2390         // we're creating the type arguments for the return type:
2391         //
2392         // ```
2393         // Bar<'a, 'b, '0, '1, '_>
2394         // ```
2395         //
2396         // For the "input" lifetime parameters, we wish to create
2397         // references to the parameters themselves, including the
2398         // "implicit" ones created from parameter types (`'a`, `'b`,
2399         // '`0`, `'1`).
2400         //
2401         // For the "output" lifetime parameters, we just want to
2402         // generate `'_`.
2403         let mut generic_args: Vec<_> =
2404             lifetime_params[..input_lifetimes_count]
2405             .iter()
2406             .map(|&(span, hir_name)| {
2407                 // Input lifetime like `'a` or `'1`:
2408                 GenericArg::Lifetime(hir::Lifetime {
2409                     hir_id: self.next_id(),
2410                     span,
2411                     name: hir::LifetimeName::Param(hir_name),
2412                 })
2413             })
2414             .collect();
2415         generic_args.extend(
2416             lifetime_params[input_lifetimes_count..]
2417             .iter()
2418             .map(|&(span, _)| {
2419                 // Output lifetime like `'_`.
2420                 GenericArg::Lifetime(hir::Lifetime {
2421                     hir_id: self.next_id(),
2422                     span,
2423                     name: hir::LifetimeName::Implicit,
2424                 })
2425             })
2426         );
2427
2428         // Create the `Foo<...>` refernece itself. Note that the `type
2429         // Foo = impl Trait` is, internally, created as a child of the
2430         // async fn, so the *type parameters* are inherited.  It's
2431         // only the lifetime parameters that we must supply.
2432         let opaque_ty_ref = hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, generic_args.into());
2433
2434         hir::FunctionRetTy::Return(P(hir::Ty {
2435             kind: opaque_ty_ref,
2436             span,
2437             hir_id: self.next_id(),
2438         }))
2439     }
2440
2441     /// Transforms `-> T` into `Future<Output = T>`
2442     fn lower_async_fn_output_type_to_future_bound(
2443         &mut self,
2444         output: &FunctionRetTy,
2445         fn_def_id: DefId,
2446         span: Span,
2447     ) -> hir::GenericBound {
2448         // Compute the `T` in `Future<Output = T>` from the return type.
2449         let output_ty = match output {
2450             FunctionRetTy::Ty(ty) => {
2451                 self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(fn_def_id)))
2452             }
2453             FunctionRetTy::Default(ret_ty_span) => {
2454                 P(hir::Ty {
2455                     hir_id: self.next_id(),
2456                     kind: hir::TyKind::Tup(hir_vec![]),
2457                     span: *ret_ty_span,
2458                 })
2459             }
2460         };
2461
2462         // "<Output = T>"
2463         let future_params = P(hir::GenericArgs {
2464             args: hir_vec![],
2465             bindings: hir_vec![hir::TypeBinding {
2466                 ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
2467                 kind: hir::TypeBindingKind::Equality {
2468                     ty: output_ty,
2469                 },
2470                 hir_id: self.next_id(),
2471                 span,
2472             }],
2473             parenthesized: false,
2474         });
2475
2476         // ::std::future::Future<future_params>
2477         let future_path =
2478             P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
2479
2480         hir::GenericBound::Trait(
2481             hir::PolyTraitRef {
2482                 trait_ref: hir::TraitRef {
2483                     path: future_path,
2484                     hir_ref_id: self.next_id(),
2485                 },
2486                 bound_generic_params: hir_vec![],
2487                 span,
2488             },
2489             hir::TraitBoundModifier::None,
2490         )
2491     }
2492
2493     fn lower_param_bound(
2494         &mut self,
2495         tpb: &GenericBound,
2496         itctx: ImplTraitContext<'_>,
2497     ) -> hir::GenericBound {
2498         match *tpb {
2499             GenericBound::Trait(ref ty, modifier) => {
2500                 hir::GenericBound::Trait(
2501                     self.lower_poly_trait_ref(ty, itctx),
2502                     self.lower_trait_bound_modifier(modifier),
2503                 )
2504             }
2505             GenericBound::Outlives(ref lifetime) => {
2506                 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2507             }
2508         }
2509     }
2510
2511     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2512         let span = l.ident.span;
2513         match l.ident {
2514             ident if ident.name == kw::StaticLifetime =>
2515                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static),
2516             ident if ident.name == kw::UnderscoreLifetime =>
2517                 match self.anonymous_lifetime_mode {
2518                     AnonymousLifetimeMode::CreateParameter => {
2519                         let fresh_name = self.collect_fresh_in_band_lifetime(span);
2520                         self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2521                     }
2522
2523                     AnonymousLifetimeMode::PassThrough => {
2524                         self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2525                     }
2526
2527                     AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2528                 },
2529             ident => {
2530                 self.maybe_collect_in_band_lifetime(ident);
2531                 let param_name = ParamName::Plain(ident);
2532                 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2533             }
2534         }
2535     }
2536
2537     fn new_named_lifetime(
2538         &mut self,
2539         id: NodeId,
2540         span: Span,
2541         name: hir::LifetimeName,
2542     ) -> hir::Lifetime {
2543         hir::Lifetime {
2544             hir_id: self.lower_node_id(id),
2545             span,
2546             name: name,
2547         }
2548     }
2549
2550     fn lower_generic_params(
2551         &mut self,
2552         params: &[GenericParam],
2553         add_bounds: &NodeMap<Vec<GenericBound>>,
2554         mut itctx: ImplTraitContext<'_>,
2555     ) -> hir::HirVec<hir::GenericParam> {
2556         params.iter().map(|param| {
2557             self.lower_generic_param(param, add_bounds, itctx.reborrow())
2558         }).collect()
2559     }
2560
2561     fn lower_generic_param(&mut self,
2562                            param: &GenericParam,
2563                            add_bounds: &NodeMap<Vec<GenericBound>>,
2564                            mut itctx: ImplTraitContext<'_>)
2565                            -> hir::GenericParam {
2566         let mut bounds = self.with_anonymous_lifetime_mode(
2567             AnonymousLifetimeMode::ReportError,
2568             |this| this.lower_param_bounds(&param.bounds, itctx.reborrow()),
2569         );
2570
2571         let (name, kind) = match param.kind {
2572             GenericParamKind::Lifetime => {
2573                 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2574                 self.is_collecting_in_band_lifetimes = false;
2575
2576                 let lt = self.with_anonymous_lifetime_mode(
2577                     AnonymousLifetimeMode::ReportError,
2578                     |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }),
2579                 );
2580                 let param_name = match lt.name {
2581                     hir::LifetimeName::Param(param_name) => param_name,
2582                     hir::LifetimeName::Implicit
2583                         | hir::LifetimeName::Underscore
2584                         | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2585                     hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2586                         span_bug!(
2587                             param.ident.span,
2588                             "object-lifetime-default should not occur here",
2589                         );
2590                     }
2591                     hir::LifetimeName::Error => ParamName::Error,
2592                 };
2593
2594                 let kind = hir::GenericParamKind::Lifetime {
2595                     kind: hir::LifetimeParamKind::Explicit
2596                 };
2597
2598                 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2599
2600                 (param_name, kind)
2601             }
2602             GenericParamKind::Type { ref default, .. } => {
2603                 let add_bounds = add_bounds.get(&param.id).map_or(&[][..], |x| &x);
2604                 if !add_bounds.is_empty() {
2605                     let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter();
2606                     bounds = bounds.into_iter()
2607                                    .chain(params)
2608                                    .collect();
2609                 }
2610
2611                 let kind = hir::GenericParamKind::Type {
2612                     default: default.as_ref().map(|x| {
2613                         self.lower_ty(x, ImplTraitContext::OpaqueTy(None))
2614                     }),
2615                     synthetic: param.attrs.iter()
2616                                           .filter(|attr| attr.check_name(sym::rustc_synthetic))
2617                                           .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2618                                           .next(),
2619                 };
2620
2621                 (hir::ParamName::Plain(param.ident), kind)
2622             }
2623             GenericParamKind::Const { ref ty } => {
2624                 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const {
2625                     ty: self.lower_ty(&ty, ImplTraitContext::disallowed()),
2626                 })
2627             }
2628         };
2629
2630         hir::GenericParam {
2631             hir_id: self.lower_node_id(param.id),
2632             name,
2633             span: param.ident.span,
2634             pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2635             attrs: self.lower_attrs(&param.attrs),
2636             bounds,
2637             kind,
2638         }
2639     }
2640
2641     fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
2642         let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2643             hir::QPath::Resolved(None, path) => path,
2644             qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2645         };
2646         hir::TraitRef {
2647             path,
2648             hir_ref_id: self.lower_node_id(p.ref_id),
2649         }
2650     }
2651
2652     fn lower_poly_trait_ref(
2653         &mut self,
2654         p: &PolyTraitRef,
2655         mut itctx: ImplTraitContext<'_>,
2656     ) -> hir::PolyTraitRef {
2657         let bound_generic_params = self.lower_generic_params(
2658             &p.bound_generic_params,
2659             &NodeMap::default(),
2660             itctx.reborrow(),
2661         );
2662         let trait_ref = self.with_in_scope_lifetime_defs(
2663             &p.bound_generic_params,
2664             |this| this.lower_trait_ref(&p.trait_ref, itctx),
2665         );
2666
2667         hir::PolyTraitRef {
2668             bound_generic_params,
2669             trait_ref,
2670             span: p.span,
2671         }
2672     }
2673
2674     fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy {
2675         hir::MutTy {
2676             ty: self.lower_ty(&mt.ty, itctx),
2677             mutbl: self.lower_mutability(mt.mutbl),
2678         }
2679     }
2680
2681     fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>)
2682                           -> hir::GenericBounds {
2683         bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
2684     }
2685
2686     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2687         let mut stmts = vec![];
2688         let mut expr = None;
2689
2690         for (index, stmt) in b.stmts.iter().enumerate() {
2691             if index == b.stmts.len() - 1 {
2692                 if let StmtKind::Expr(ref e) = stmt.kind {
2693                     expr = Some(P(self.lower_expr(e)));
2694                 } else {
2695                     stmts.extend(self.lower_stmt(stmt));
2696                 }
2697             } else {
2698                 stmts.extend(self.lower_stmt(stmt));
2699             }
2700         }
2701
2702         P(hir::Block {
2703             hir_id: self.lower_node_id(b.id),
2704             stmts: stmts.into(),
2705             expr,
2706             rules: self.lower_block_check_mode(&b.rules),
2707             span: b.span,
2708             targeted_by_break,
2709         })
2710     }
2711
2712     /// Lowers a block directly to an expression, presuming that it
2713     /// has no attributes and is not targeted by a `break`.
2714     fn lower_block_expr(&mut self, b: &Block) -> hir::Expr {
2715         let block = self.lower_block(b, false);
2716         self.expr_block(block, ThinVec::new())
2717     }
2718
2719     fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
2720         let node = match p.kind {
2721             PatKind::Wild => hir::PatKind::Wild,
2722             PatKind::Ident(ref binding_mode, ident, ref sub) => {
2723                 let lower_sub = |this: &mut Self| sub.as_ref().map(|x| this.lower_pat(x));
2724                 self.lower_pat_ident(p, binding_mode, ident, lower_sub)
2725             }
2726             PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))),
2727             PatKind::TupleStruct(ref path, ref pats) => {
2728                 let qpath = self.lower_qpath(
2729                     p.id,
2730                     &None,
2731                     path,
2732                     ParamMode::Optional,
2733                     ImplTraitContext::disallowed(),
2734                 );
2735                 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
2736                 hir::PatKind::TupleStruct(qpath, pats, ddpos)
2737             }
2738             PatKind::Or(ref pats) => {
2739                 hir::PatKind::Or(pats.iter().map(|x| self.lower_pat(x)).collect())
2740             }
2741             PatKind::Path(ref qself, ref path) => {
2742                 let qpath = self.lower_qpath(
2743                     p.id,
2744                     qself,
2745                     path,
2746                     ParamMode::Optional,
2747                     ImplTraitContext::disallowed(),
2748                 );
2749                 hir::PatKind::Path(qpath)
2750             }
2751             PatKind::Struct(ref path, ref fields, etc) => {
2752                 let qpath = self.lower_qpath(
2753                     p.id,
2754                     &None,
2755                     path,
2756                     ParamMode::Optional,
2757                     ImplTraitContext::disallowed(),
2758                 );
2759
2760                 let fs = fields
2761                     .iter()
2762                     .map(|f| hir::FieldPat {
2763                         hir_id: self.next_id(),
2764                         ident: f.ident,
2765                         pat: self.lower_pat(&f.pat),
2766                         is_shorthand: f.is_shorthand,
2767                         span: f.span,
2768                     })
2769                     .collect();
2770                 hir::PatKind::Struct(qpath, fs, etc)
2771             }
2772             PatKind::Tuple(ref pats) => {
2773                 let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
2774                 hir::PatKind::Tuple(pats, ddpos)
2775             }
2776             PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
2777             PatKind::Ref(ref inner, mutbl) => {
2778                 hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl))
2779             }
2780             PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
2781                 P(self.lower_expr(e1)),
2782                 P(self.lower_expr(e2)),
2783                 self.lower_range_end(end),
2784             ),
2785             PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
2786             PatKind::Rest => {
2787                 // If we reach here the `..` pattern is not semantically allowed.
2788                 self.ban_illegal_rest_pat(p.span)
2789             }
2790             PatKind::Paren(ref inner) => return self.lower_pat(inner),
2791             PatKind::Mac(_) => panic!("Shouldn't exist here"),
2792         };
2793
2794         self.pat_with_node_id_of(p, node)
2795     }
2796
2797     fn lower_pat_tuple(
2798         &mut self,
2799         pats: &[AstP<Pat>],
2800         ctx: &str,
2801     ) -> (HirVec<P<hir::Pat>>, Option<usize>) {
2802         let mut elems = Vec::with_capacity(pats.len());
2803         let mut rest = None;
2804
2805         let mut iter = pats.iter().enumerate();
2806         while let Some((idx, pat)) = iter.next() {
2807             // Interpret the first `..` pattern as a subtuple pattern.
2808             if pat.is_rest() {
2809                 rest = Some((idx, pat.span));
2810                 break;
2811             }
2812             // It was not a subslice pattern so lower it normally.
2813             elems.push(self.lower_pat(pat));
2814         }
2815
2816         while let Some((_, pat)) = iter.next() {
2817             // There was a previous subtuple pattern; make sure we don't allow more.
2818             if pat.is_rest() {
2819                 self.ban_extra_rest_pat(pat.span, rest.unwrap().1, ctx);
2820             } else {
2821                 elems.push(self.lower_pat(pat));
2822             }
2823         }
2824
2825         (elems.into(), rest.map(|(ddpos, _)| ddpos))
2826     }
2827
2828     fn lower_pat_slice(&mut self, pats: &[AstP<Pat>]) -> hir::PatKind {
2829         let mut before = Vec::new();
2830         let mut after = Vec::new();
2831         let mut slice = None;
2832         let mut prev_rest_span = None;
2833
2834         let mut iter = pats.iter();
2835         while let Some(pat) = iter.next() {
2836             // Interpret the first `((ref mut?)? x @)? ..` pattern as a subslice pattern.
2837             match pat.kind {
2838                 PatKind::Rest => {
2839                     prev_rest_span = Some(pat.span);
2840                     slice = Some(self.pat_wild_with_node_id_of(pat));
2841                     break;
2842                 },
2843                 PatKind::Ident(ref bm, ident, Some(ref sub)) if sub.is_rest() => {
2844                     prev_rest_span = Some(sub.span);
2845                     let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub));
2846                     let node = self.lower_pat_ident(pat, bm, ident, lower_sub);
2847                     slice = Some(self.pat_with_node_id_of(pat, node));
2848                     break;
2849                 },
2850                 _ => {}
2851             }
2852
2853             // It was not a subslice pattern so lower it normally.
2854             before.push(self.lower_pat(pat));
2855         }
2856
2857         while let Some(pat) = iter.next() {
2858             // There was a previous subslice pattern; make sure we don't allow more.
2859             let rest_span = match pat.kind {
2860                 PatKind::Rest => Some(pat.span),
2861                 PatKind::Ident(.., Some(ref sub)) if sub.is_rest() => {
2862                     // The `HirValidator` is merciless; add a `_` pattern to avoid ICEs.
2863                     after.push(self.pat_wild_with_node_id_of(pat));
2864                     Some(sub.span)
2865                 },
2866                 _ => None,
2867             };
2868             if let Some(rest_span) = rest_span {
2869                 self.ban_extra_rest_pat(rest_span, prev_rest_span.unwrap(), "slice");
2870             } else {
2871                 after.push(self.lower_pat(pat));
2872             }
2873         }
2874
2875         hir::PatKind::Slice(before.into(), slice, after.into())
2876     }
2877
2878     fn lower_pat_ident(
2879         &mut self,
2880         p: &Pat,
2881         binding_mode: &BindingMode,
2882         ident: Ident,
2883         lower_sub: impl FnOnce(&mut Self) -> Option<P<hir::Pat>>,
2884     ) -> hir::PatKind {
2885         match self.resolver.get_partial_res(p.id).map(|d| d.base_res()) {
2886             // `None` can occur in body-less function signatures
2887             res @ None | res @ Some(Res::Local(_)) => {
2888                 let canonical_id = match res {
2889                     Some(Res::Local(id)) => id,
2890                     _ => p.id,
2891                 };
2892
2893                 hir::PatKind::Binding(
2894                     self.lower_binding_mode(binding_mode),
2895                     self.lower_node_id(canonical_id),
2896                     ident,
2897                     lower_sub(self),
2898                 )
2899             }
2900             Some(res) => hir::PatKind::Path(hir::QPath::Resolved(
2901                 None,
2902                 P(hir::Path {
2903                     span: ident.span,
2904                     res: self.lower_res(res),
2905                     segments: hir_vec![hir::PathSegment::from_ident(ident)],
2906                 }),
2907             )),
2908         }
2909     }
2910
2911     fn pat_wild_with_node_id_of(&mut self, p: &Pat) -> P<hir::Pat> {
2912         self.pat_with_node_id_of(p, hir::PatKind::Wild)
2913     }
2914
2915     /// Construct a `Pat` with the `HirId` of `p.id` lowered.
2916     fn pat_with_node_id_of(&mut self, p: &Pat, kind: hir::PatKind) -> P<hir::Pat> {
2917         P(hir::Pat {
2918             hir_id: self.lower_node_id(p.id),
2919             kind,
2920             span: p.span,
2921         })
2922     }
2923
2924     /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
2925     fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
2926         self.diagnostic()
2927             .struct_span_err(sp, &format!("`..` can only be used once per {} pattern", ctx))
2928             .span_label(sp, &format!("can only be used once per {} pattern", ctx))
2929             .span_label(prev_sp, "previously used here")
2930             .emit();
2931     }
2932
2933     /// Used to ban the `..` pattern in places it shouldn't be semantically.
2934     fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind {
2935         self.diagnostic()
2936             .struct_span_err(sp, "`..` patterns are not allowed here")
2937             .note("only allowed in tuple, tuple struct, and slice patterns")
2938             .emit();
2939
2940         // We're not in a list context so `..` can be reasonably treated
2941         // as `_` because it should always be valid and roughly matches the
2942         // intent of `..` (notice that the rest of a single slot is that slot).
2943         hir::PatKind::Wild
2944     }
2945
2946     fn lower_range_end(&mut self, e: &RangeEnd) -> hir::RangeEnd {
2947         match *e {
2948             RangeEnd::Included(_) => hir::RangeEnd::Included,
2949             RangeEnd::Excluded => hir::RangeEnd::Excluded,
2950         }
2951     }
2952
2953     fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2954         self.with_new_scopes(|this| {
2955             hir::AnonConst {
2956                 hir_id: this.lower_node_id(c.id),
2957                 body: this.lower_const_body(&c.value),
2958             }
2959         })
2960     }
2961
2962     fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> {
2963         let kind = match s.kind {
2964             StmtKind::Local(ref l) => {
2965                 let (l, item_ids) = self.lower_local(l);
2966                 let mut ids: SmallVec<[hir::Stmt; 1]> = item_ids
2967                     .into_iter()
2968                     .map(|item_id| {
2969                         let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
2970                         self.stmt(s.span, hir::StmtKind::Item(item_id))
2971                     })
2972                     .collect();
2973                 ids.push({
2974                     hir::Stmt {
2975                         hir_id: self.lower_node_id(s.id),
2976                         kind: hir::StmtKind::Local(P(l)),
2977                         span: s.span,
2978                     }
2979                 });
2980                 return ids;
2981             },
2982             StmtKind::Item(ref it) => {
2983                 // Can only use the ID once.
2984                 let mut id = Some(s.id);
2985                 return self.lower_item_id(it)
2986                     .into_iter()
2987                     .map(|item_id| {
2988                         let hir_id = id.take()
2989                           .map(|id| self.lower_node_id(id))
2990                           .unwrap_or_else(|| self.next_id());
2991
2992                         hir::Stmt {
2993                             hir_id,
2994                             kind: hir::StmtKind::Item(item_id),
2995                             span: s.span,
2996                         }
2997                     })
2998                     .collect();
2999             }
3000             StmtKind::Expr(ref e) => hir::StmtKind::Expr(P(self.lower_expr(e))),
3001             StmtKind::Semi(ref e) => hir::StmtKind::Semi(P(self.lower_expr(e))),
3002             StmtKind::Mac(..) => panic!("shouldn't exist here"),
3003         };
3004         smallvec![hir::Stmt {
3005             hir_id: self.lower_node_id(s.id),
3006             kind,
3007             span: s.span,
3008         }]
3009     }
3010
3011     fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
3012         match *b {
3013             BlockCheckMode::Default => hir::DefaultBlock,
3014             BlockCheckMode::Unsafe(u) => hir::UnsafeBlock(self.lower_unsafe_source(u)),
3015         }
3016     }
3017
3018     fn lower_binding_mode(&mut self, b: &BindingMode) -> hir::BindingAnnotation {
3019         match *b {
3020             BindingMode::ByValue(Mutability::Immutable) => hir::BindingAnnotation::Unannotated,
3021             BindingMode::ByRef(Mutability::Immutable) => hir::BindingAnnotation::Ref,
3022             BindingMode::ByValue(Mutability::Mutable) => hir::BindingAnnotation::Mutable,
3023             BindingMode::ByRef(Mutability::Mutable) => hir::BindingAnnotation::RefMut,
3024         }
3025     }
3026
3027     fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3028         match u {
3029             CompilerGenerated => hir::CompilerGenerated,
3030             UserProvided => hir::UserProvided,
3031         }
3032     }
3033
3034     fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
3035         match f {
3036             TraitBoundModifier::None => hir::TraitBoundModifier::None,
3037             TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe,
3038         }
3039     }
3040
3041     // Helper methods for building HIR.
3042
3043     fn stmt(&mut self, span: Span, kind: hir::StmtKind) -> hir::Stmt {
3044         hir::Stmt { span, kind, hir_id: self.next_id() }
3045     }
3046
3047     fn stmt_expr(&mut self, span: Span, expr: hir::Expr) -> hir::Stmt {
3048         self.stmt(span, hir::StmtKind::Expr(P(expr)))
3049     }
3050
3051     fn stmt_let_pat(
3052         &mut self,
3053         attrs: ThinVec<Attribute>,
3054         span: Span,
3055         init: Option<P<hir::Expr>>,
3056         pat: P<hir::Pat>,
3057         source: hir::LocalSource,
3058     ) -> hir::Stmt {
3059         let local = hir::Local {
3060             attrs,
3061             hir_id: self.next_id(),
3062             init,
3063             pat,
3064             source,
3065             span,
3066             ty: None,
3067         };
3068         self.stmt(span, hir::StmtKind::Local(P(local)))
3069     }
3070
3071     fn block_expr(&mut self, expr: P<hir::Expr>) -> hir::Block {
3072         self.block_all(expr.span, hir::HirVec::new(), Some(expr))
3073     }
3074
3075     fn block_all(
3076         &mut self,
3077         span: Span,
3078         stmts: hir::HirVec<hir::Stmt>,
3079         expr: Option<P<hir::Expr>>,
3080     ) -> hir::Block {
3081         hir::Block {
3082             stmts,
3083             expr,
3084             hir_id: self.next_id(),
3085             rules: hir::DefaultBlock,
3086             span,
3087             targeted_by_break: false,
3088         }
3089     }
3090
3091     /// Constructs a `true` or `false` literal pattern.
3092     fn pat_bool(&mut self, span: Span, val: bool) -> P<hir::Pat> {
3093         let expr = self.expr_bool(span, val);
3094         self.pat(span, hir::PatKind::Lit(P(expr)))
3095     }
3096
3097     fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3098         self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
3099     }
3100
3101     fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3102         self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
3103     }
3104
3105     fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
3106         self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
3107     }
3108
3109     fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
3110         self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
3111     }
3112
3113     fn pat_std_enum(
3114         &mut self,
3115         span: Span,
3116         components: &[Symbol],
3117         subpats: hir::HirVec<P<hir::Pat>>,
3118     ) -> P<hir::Pat> {
3119         let path = self.std_path(span, components, None, true);
3120         let qpath = hir::QPath::Resolved(None, P(path));
3121         let pt = if subpats.is_empty() {
3122             hir::PatKind::Path(qpath)
3123         } else {
3124             hir::PatKind::TupleStruct(qpath, subpats, None)
3125         };
3126         self.pat(span, pt)
3127     }
3128
3129     fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<hir::Pat>, hir::HirId) {
3130         self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
3131     }
3132
3133     fn pat_ident_binding_mode(
3134         &mut self,
3135         span: Span,
3136         ident: Ident,
3137         bm: hir::BindingAnnotation,
3138     ) -> (P<hir::Pat>, hir::HirId) {
3139         let hir_id = self.next_id();
3140
3141         (
3142             P(hir::Pat {
3143                 hir_id,
3144                 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
3145                 span,
3146             }),
3147             hir_id
3148         )
3149     }
3150
3151     fn pat_wild(&mut self, span: Span) -> P<hir::Pat> {
3152         self.pat(span, hir::PatKind::Wild)
3153     }
3154
3155     fn pat(&mut self, span: Span, kind: hir::PatKind) -> P<hir::Pat> {
3156         P(hir::Pat {
3157             hir_id: self.next_id(),
3158             kind,
3159             span,
3160         })
3161     }
3162
3163     /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
3164     /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
3165     /// The path is also resolved according to `is_value`.
3166     fn std_path(
3167         &mut self,
3168         span: Span,
3169         components: &[Symbol],
3170         params: Option<P<hir::GenericArgs>>,
3171         is_value: bool,
3172     ) -> hir::Path {
3173         let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
3174         let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
3175
3176         let mut segments: Vec<_> = path.segments.iter().map(|segment| {
3177             let res = self.expect_full_res(segment.id);
3178             hir::PathSegment {
3179                 ident: segment.ident,
3180                 hir_id: Some(self.lower_node_id(segment.id)),
3181                 res: Some(self.lower_res(res)),
3182                 infer_args: true,
3183                 args: None,
3184             }
3185         }).collect();
3186         segments.last_mut().unwrap().args = params;
3187
3188         hir::Path {
3189             span,
3190             res: res.map_id(|_| panic!("unexpected `NodeId`")),
3191             segments: segments.into(),
3192         }
3193     }
3194
3195     fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty {
3196         let kind = match qpath {
3197             hir::QPath::Resolved(None, path) => {
3198                 // Turn trait object paths into `TyKind::TraitObject` instead.
3199                 match path.res {
3200                     Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
3201                         let principal = hir::PolyTraitRef {
3202                             bound_generic_params: hir::HirVec::new(),
3203                             trait_ref: hir::TraitRef {
3204                                 path,
3205                                 hir_ref_id: hir_id,
3206                             },
3207                             span,
3208                         };
3209
3210                         // The original ID is taken by the `PolyTraitRef`,
3211                         // so the `Ty` itself needs a different one.
3212                         hir_id = self.next_id();
3213                         hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span))
3214                     }
3215                     _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3216                 }
3217             }
3218             _ => hir::TyKind::Path(qpath),
3219         };
3220
3221         hir::Ty {
3222             hir_id,
3223             kind,
3224             span,
3225         }
3226     }
3227
3228     /// Invoked to create the lifetime argument for a type `&T`
3229     /// with no explicit lifetime.
3230     fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
3231         match self.anonymous_lifetime_mode {
3232             // Intercept when we are in an impl header or async fn and introduce an in-band
3233             // lifetime.
3234             // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
3235             // `'f`.
3236             AnonymousLifetimeMode::CreateParameter => {
3237                 let fresh_name = self.collect_fresh_in_band_lifetime(span);
3238                 hir::Lifetime {
3239                     hir_id: self.next_id(),
3240                     span,
3241                     name: hir::LifetimeName::Param(fresh_name),
3242                 }
3243             }
3244
3245             AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
3246
3247             AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
3248         }
3249     }
3250
3251     /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
3252     /// return a "error lifetime".
3253     fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
3254         let (id, msg, label) = match id {
3255             Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
3256
3257             None => (
3258                 self.sess.next_node_id(),
3259                 "`&` without an explicit lifetime name cannot be used here",
3260                 "explicit lifetime name needed here",
3261             ),
3262         };
3263
3264         let mut err = struct_span_err!(
3265             self.sess,
3266             span,
3267             E0637,
3268             "{}",
3269             msg,
3270         );
3271         err.span_label(span, label);
3272         err.emit();
3273
3274         self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3275     }
3276
3277     /// Invoked to create the lifetime argument(s) for a path like
3278     /// `std::cell::Ref<T>`; note that implicit lifetimes in these
3279     /// sorts of cases are deprecated. This may therefore report a warning or an
3280     /// error, depending on the mode.
3281     fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
3282         (0..count)
3283             .map(|_| self.elided_path_lifetime(span))
3284             .collect()
3285     }
3286
3287     fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
3288         match self.anonymous_lifetime_mode {
3289             AnonymousLifetimeMode::CreateParameter => {
3290                 // We should have emitted E0726 when processing this path above
3291                 self.sess.delay_span_bug(
3292                     span,
3293                     "expected 'implicit elided lifetime not allowed' error",
3294                 );
3295                 let id = self.sess.next_node_id();
3296                 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
3297             }
3298             // `PassThrough` is the normal case.
3299             // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
3300             // is unsuitable here, as these can occur from missing lifetime parameters in a
3301             // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
3302             // lifetime. Instead, we simply create an implicit lifetime, which will be checked
3303             // later, at which point a suitable error will be emitted.
3304           | AnonymousLifetimeMode::PassThrough
3305           | AnonymousLifetimeMode::ReportError => self.new_implicit_lifetime(span),
3306         }
3307     }
3308
3309     /// Invoked to create the lifetime argument(s) for an elided trait object
3310     /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3311     /// when the bound is written, even if it is written with `'_` like in
3312     /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3313     fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
3314         match self.anonymous_lifetime_mode {
3315             // NB. We intentionally ignore the create-parameter mode here.
3316             // and instead "pass through" to resolve-lifetimes, which will apply
3317             // the object-lifetime-defaulting rules. Elided object lifetime defaults
3318             // do not act like other elided lifetimes. In other words, given this:
3319             //
3320             //     impl Foo for Box<dyn Debug>
3321             //
3322             // we do not introduce a fresh `'_` to serve as the bound, but instead
3323             // ultimately translate to the equivalent of:
3324             //
3325             //     impl Foo for Box<dyn Debug + 'static>
3326             //
3327             // `resolve_lifetime` has the code to make that happen.
3328             AnonymousLifetimeMode::CreateParameter => {}
3329
3330             AnonymousLifetimeMode::ReportError => {
3331                 // ReportError applies to explicit use of `'_`.
3332             }
3333
3334             // This is the normal case.
3335             AnonymousLifetimeMode::PassThrough => {}
3336         }
3337
3338         let r = hir::Lifetime {
3339             hir_id: self.next_id(),
3340             span,
3341             name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
3342         };
3343         debug!("elided_dyn_bound: r={:?}", r);
3344         r
3345     }
3346
3347     fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
3348         hir::Lifetime {
3349             hir_id: self.next_id(),
3350             span,
3351             name: hir::LifetimeName::Implicit,
3352         }
3353     }
3354
3355     fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
3356         // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
3357         // call site which do not have a macro backtrace. See #61963.
3358         let is_macro_callsite = self.sess.source_map()
3359             .span_to_snippet(span)
3360             .map(|snippet| snippet.starts_with("#["))
3361             .unwrap_or(true);
3362         if !is_macro_callsite {
3363             self.resolver.lint_buffer().buffer_lint_with_diagnostic(
3364                 builtin::BARE_TRAIT_OBJECTS,
3365                 id,
3366                 span,
3367                 "trait objects without an explicit `dyn` are deprecated",
3368                 builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global),
3369             )
3370         }
3371     }
3372 }
3373
3374 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
3375     // Sorting by span ensures that we get things in order within a
3376     // file, and also puts the files in a sensible order.
3377     let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
3378     body_ids.sort_by_key(|b| bodies[b].value.span);
3379     body_ids
3380 }
3381
3382 /// Checks if the specified expression is a built-in range literal.
3383 /// (See: `LoweringContext::lower_expr()`).
3384 pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
3385     use hir::{Path, QPath, ExprKind, TyKind};
3386
3387     // Returns whether the given path represents a (desugared) range,
3388     // either in std or core, i.e. has either a `::std::ops::Range` or
3389     // `::core::ops::Range` prefix.
3390     fn is_range_path(path: &Path) -> bool {
3391         let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
3392         let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
3393
3394         // "{{root}}" is the equivalent of `::` prefix in `Path`.
3395         if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
3396             (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
3397         } else {
3398             false
3399         }
3400     };
3401
3402     // Check whether a span corresponding to a range expression is a
3403     // range literal, rather than an explicit struct or `new()` call.
3404     fn is_lit(sess: &Session, span: &Span) -> bool {
3405         let source_map = sess.source_map();
3406         let end_point = source_map.end_point(*span);
3407
3408         if let Ok(end_string) = source_map.span_to_snippet(end_point) {
3409             !(end_string.ends_with("}") || end_string.ends_with(")"))
3410         } else {
3411             false
3412         }
3413     };
3414
3415     match expr.kind {
3416         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
3417         ExprKind::Struct(ref qpath, _, _) => {
3418             if let QPath::Resolved(None, ref path) = **qpath {
3419                 return is_range_path(&path) && is_lit(sess, &expr.span);
3420             }
3421         }
3422
3423         // `..` desugars to its struct path.
3424         ExprKind::Path(QPath::Resolved(None, ref path)) => {
3425             return is_range_path(&path) && is_lit(sess, &expr.span);
3426         }
3427
3428         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
3429         ExprKind::Call(ref func, _) => {
3430             if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
3431                 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
3432                     let new_call = segment.ident.name == sym::new;
3433                     return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;
3434                 }
3435             }
3436         }
3437
3438         _ => {}
3439     }
3440
3441     false
3442 }