1 //! Lowers the AST to the HIR.
3 //! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4 //! much like a fold. Where lowering involves a bit more work things get more
5 //! interesting and there are some invariants you should know about. These mostly
6 //! concern spans and IDs.
8 //! Spans are assigned to AST nodes during parsing and then are modified during
9 //! expansion to indicate the origin of a node and the process it went through
10 //! being expanded. IDs are assigned to AST nodes just before lowering.
12 //! For the simpler lowering steps, IDs and spans should be preserved. Unlike
13 //! expansion we do not preserve the process of lowering in the spans, so spans
14 //! should not be modified here. When creating a new node (as opposed to
15 //! 'folding' an existing one), then you create a new ID using `next_id()`.
17 //! You must ensure that IDs are unique. That means that you should only use the
18 //! ID from an AST node in a single HIR node (you can assume that AST node-IDs
19 //! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
20 //! If you do, you must then set the new node's ID to a fresh one.
22 //! Spans are used for error messages and for tools to map semantics back to
23 //! source code. It is therefore not as important with spans as IDs to be strict
24 //! about use (you can't break the compiler by screwing up a span). Obviously, a
25 //! HIR node can only have a single span. But multiple nodes can have the same
26 //! span and spans don't need to be kept in order, etc. Where code is preserved
27 //! by lowering, it should have the same span as in the AST. Where HIR nodes are
28 //! new it is probably best to give a span for the whole AST node being lowered.
29 //! All nodes should have real spans, don't use dummy spans. Tools are likely to
30 //! get confused if the spans from leaf AST nodes occur in multiple places
31 //! in the HIR, especially for multiple identifiers.
33 #![feature(array_value_iter)]
34 #![feature(crate_visibility_modifier)]
35 #![feature(or_patterns)]
36 #![recursion_limit = "256"]
39 use rustc_ast::ast::*;
41 use rustc_ast::node_id::NodeMap;
42 use rustc_ast::token::{self, DelimToken, Nonterminal, Token};
43 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
44 use rustc_ast::visit::{self, AssocCtxt, Visitor};
45 use rustc_ast::walk_list;
46 use rustc_ast_pretty::pprust;
47 use rustc_data_structures::captures::Captures;
48 use rustc_data_structures::fx::FxHashSet;
49 use rustc_data_structures::sync::Lrc;
50 use rustc_errors::struct_span_err;
52 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
53 use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
54 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
55 use rustc_hir::intravisit;
56 use rustc_hir::{ConstArg, GenericArg, ParamName};
57 use rustc_index::vec::{Idx, IndexVec};
58 use rustc_session::config::nightly_options;
59 use rustc_session::lint::{builtin::BARE_TRAIT_OBJECTS, BuiltinLintDiagnostics, LintBuffer};
60 use rustc_session::parse::ParseSess;
61 use rustc_session::Session;
62 use rustc_span::hygiene::ExpnId;
63 use rustc_span::source_map::{respan, DesugaringKind, ExpnData, ExpnKind};
64 use rustc_span::symbol::{kw, sym, Ident, Symbol};
67 use tracing::{debug, trace};
68 use smallvec::{smallvec, SmallVec};
69 use std::collections::BTreeMap;
72 macro_rules! arena_vec {
73 ($this:expr; $($x:expr),*) => ({
75 $this.arena.alloc_from_iter(std::array::IntoIter::new(a))
84 const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
86 rustc_hir::arena_types!(rustc_arena::declare_arena, [], 'tcx);
88 struct LoweringContext<'a, 'hir: 'a> {
89 crate_root: Option<Symbol>,
91 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
94 resolver: &'a mut dyn ResolverAstLowering,
96 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
97 /// if we don't have this function pointer. To avoid that dependency so that
98 /// librustc_middle is independent of the parser, we use dynamic dispatch here.
99 nt_to_tokenstream: NtToTokenstream,
101 /// Used to allocate HIR nodes
102 arena: &'hir Arena<'hir>,
104 /// The items being lowered are collected here.
105 items: BTreeMap<hir::HirId, hir::Item<'hir>>,
107 trait_items: BTreeMap<hir::TraitItemId, hir::TraitItem<'hir>>,
108 impl_items: BTreeMap<hir::ImplItemId, hir::ImplItem<'hir>>,
109 bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
110 exported_macros: Vec<hir::MacroDef<'hir>>,
111 non_exported_macro_attrs: Vec<ast::Attribute>,
113 trait_impls: BTreeMap<DefId, Vec<hir::HirId>>,
115 modules: BTreeMap<hir::HirId, hir::ModuleItems>,
117 generator_kind: Option<hir::GeneratorKind>,
119 /// When inside an `async` context, this is the `HirId` of the
120 /// `task_context` local bound to the resume argument of the generator.
121 task_context: Option<hir::HirId>,
123 /// Used to get the current `fn`'s def span to point to when using `await`
124 /// outside of an `async fn`.
125 current_item: Option<Span>,
127 catch_scopes: Vec<NodeId>,
128 loop_scopes: Vec<NodeId>,
129 is_in_loop_condition: bool,
130 is_in_trait_impl: bool,
131 is_in_dyn_type: bool,
133 /// What to do when we encounter either an "anonymous lifetime
134 /// reference". The term "anonymous" is meant to encompass both
135 /// `'_` lifetimes as well as fully elided cases where nothing is
136 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
137 anonymous_lifetime_mode: AnonymousLifetimeMode,
139 /// Used to create lifetime definitions from in-band lifetime usages.
140 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
141 /// When a named lifetime is encountered in a function or impl header and
142 /// has not been defined
143 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
144 /// to this list. The results of this list are then added to the list of
145 /// lifetime definitions in the corresponding impl or function generics.
146 lifetimes_to_define: Vec<(Span, ParamName)>,
148 /// `true` if in-band lifetimes are being collected. This is used to
149 /// indicate whether or not we're in a place where new lifetimes will result
150 /// in in-band lifetime definitions, such a function or an impl header,
151 /// including implicit lifetimes from `impl_header_lifetime_elision`.
152 is_collecting_in_band_lifetimes: bool,
154 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
155 /// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked
156 /// against this list to see if it is already in-scope, or if a definition
157 /// needs to be created for it.
159 /// We always store a `normalize_to_macros_2_0()` version of the param-name in this
161 in_scope_lifetimes: Vec<ParamName>,
163 current_module: hir::HirId,
165 type_def_lifetime_params: DefIdMap<usize>,
167 current_hir_id_owner: Vec<(LocalDefId, u32)>,
168 item_local_id_counters: NodeMap<u32>,
169 node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
171 allow_try_trait: Option<Lrc<[Symbol]>>,
172 allow_gen_future: Option<Lrc<[Symbol]>>,
175 pub trait ResolverAstLowering {
176 fn def_key(&mut self, id: DefId) -> DefKey;
178 fn item_generics_num_lifetimes(&self, def: DefId, sess: &Session) -> usize;
180 /// Obtains resolution for a `NodeId` with a single resolution.
181 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes>;
183 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
184 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
186 /// Obtains resolution for a label with the given `NodeId`.
187 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
189 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
190 /// This should only return `None` during testing.
191 fn definitions(&mut self) -> &mut Definitions;
193 /// Given suffix `["b", "c", "d"]`, creates an AST path for `[::crate_root]::b::c::d` and
194 /// resolves it based on `is_value`.
198 crate_root: Option<Symbol>,
199 components: &[Symbol],
201 ) -> (ast::Path, Res<NodeId>);
203 fn lint_buffer(&mut self) -> &mut LintBuffer;
205 fn next_node_id(&mut self) -> NodeId;
207 fn trait_map(&self) -> &NodeMap<Vec<hir::TraitCandidate>>;
209 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
211 fn local_def_id(&self, node: NodeId) -> LocalDefId;
216 node_id: ast::NodeId,
223 type NtToTokenstream = fn(&Nonterminal, &ParseSess, Span) -> TokenStream;
225 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
226 /// and if so, what meaning it has.
228 enum ImplTraitContext<'b, 'a> {
229 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
230 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
231 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
233 /// Newly generated parameters should be inserted into the given `Vec`.
234 Universal(&'b mut Vec<hir::GenericParam<'a>>),
236 /// Treat `impl Trait` as shorthand for a new opaque type.
237 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
238 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
240 ReturnPositionOpaqueTy {
241 /// `DefId` for the parent function, used to look up necessary
242 /// information later.
244 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
245 origin: hir::OpaqueTyOrigin,
247 /// Impl trait in type aliases, consts and statics.
249 /// Set of lifetimes that this opaque type can capture, if it uses
250 /// them. This includes lifetimes bound since we entered this context.
253 /// type A<'b> = impl for<'a> Trait<'a, Out = impl Sized + 'a>;
255 /// the inner opaque type captures `'a` because it uses it. It doesn't
256 /// need to capture `'b` because it already inherits the lifetime
257 /// parameter from `A`.
258 // FIXME(impl_trait): but `required_region_bounds` will ICE later
260 capturable_lifetimes: &'b mut FxHashSet<hir::LifetimeName>,
261 /// Origin: Either OpaqueTyOrigin::Misc or OpaqueTyOrigin::Binding,
262 origin: hir::OpaqueTyOrigin,
264 /// `impl Trait` is not accepted in this position.
265 Disallowed(ImplTraitPosition),
268 /// Position in which `impl Trait` is disallowed.
269 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
270 enum ImplTraitPosition {
271 /// Disallowed in `let` / `const` / `static` bindings.
274 /// All other posiitons.
278 impl<'a> ImplTraitContext<'_, 'a> {
280 fn disallowed() -> Self {
281 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
284 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
285 use self::ImplTraitContext::*;
287 Universal(params) => Universal(params),
288 ReturnPositionOpaqueTy { fn_def_id, origin } => {
289 ReturnPositionOpaqueTy { fn_def_id: *fn_def_id, origin: *origin }
291 OtherOpaqueTy { capturable_lifetimes, origin } => {
292 OtherOpaqueTy { capturable_lifetimes, origin: *origin }
294 Disallowed(pos) => Disallowed(*pos),
299 pub fn lower_crate<'a, 'hir>(
302 resolver: &'a mut dyn ResolverAstLowering,
303 nt_to_tokenstream: NtToTokenstream,
304 arena: &'hir Arena<'hir>,
305 ) -> hir::Crate<'hir> {
306 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
309 crate_root: sess.parse_sess.injected_crate_name.get().copied(),
314 items: BTreeMap::new(),
315 trait_items: BTreeMap::new(),
316 impl_items: BTreeMap::new(),
317 bodies: BTreeMap::new(),
318 trait_impls: BTreeMap::new(),
319 modules: BTreeMap::new(),
320 exported_macros: Vec::new(),
321 non_exported_macro_attrs: Vec::new(),
322 catch_scopes: Vec::new(),
323 loop_scopes: Vec::new(),
324 is_in_loop_condition: false,
325 is_in_trait_impl: false,
326 is_in_dyn_type: false,
327 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
328 type_def_lifetime_params: Default::default(),
329 current_module: hir::CRATE_HIR_ID,
330 current_hir_id_owner: vec![(LocalDefId { local_def_index: CRATE_DEF_INDEX }, 0)],
331 item_local_id_counters: Default::default(),
332 node_id_to_hir_id: IndexVec::new(),
333 generator_kind: None,
336 lifetimes_to_define: Vec::new(),
337 is_collecting_in_band_lifetimes: false,
338 in_scope_lifetimes: Vec::new(),
339 allow_try_trait: Some([sym::try_trait][..].into()),
340 allow_gen_future: Some([sym::gen_future][..].into()),
345 #[derive(Copy, Clone, PartialEq)]
347 /// Any path in a type context.
349 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
351 /// The `module::Type` in `module::Type::method` in an expression.
355 enum ParenthesizedGenericArgs {
360 /// What to do when we encounter an **anonymous** lifetime
361 /// reference. Anonymous lifetime references come in two flavors. You
362 /// have implicit, or fully elided, references to lifetimes, like the
363 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
364 /// or `Ref<'_, T>`. These often behave the same, but not always:
366 /// - certain usages of implicit references are deprecated, like
367 /// `Ref<T>`, and we sometimes just give hard errors in those cases
369 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
370 /// the same as `Box<dyn Foo + '_>`.
372 /// We describe the effects of the various modes in terms of three cases:
374 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
375 /// of a `&` (e.g., the missing lifetime in something like `&T`)
376 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
377 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
378 /// elided bounds follow special rules. Note that this only covers
379 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
380 /// '_>` is a case of "modern" elision.
381 /// - **Deprecated** -- this coverse cases like `Ref<T>`, where the lifetime
382 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
383 /// non-deprecated equivalent.
385 /// Currently, the handling of lifetime elision is somewhat spread out
386 /// between HIR lowering and -- as described below -- the
387 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
388 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
389 /// everything into HIR lowering.
390 #[derive(Copy, Clone, Debug)]
391 enum AnonymousLifetimeMode {
392 /// For **Modern** cases, create a new anonymous region parameter
393 /// and reference that.
395 /// For **Dyn Bound** cases, pass responsibility to
396 /// `resolve_lifetime` code.
398 /// For **Deprecated** cases, report an error.
401 /// Give a hard error when either `&` or `'_` is written. Used to
402 /// rule out things like `where T: Foo<'_>`. Does not imply an
403 /// error on default object bounds (e.g., `Box<dyn Foo>`).
406 /// Pass responsibility to `resolve_lifetime` code for all cases.
410 struct ImplTraitTypeIdVisitor<'a> {
411 ids: &'a mut SmallVec<[NodeId; 1]>,
414 impl Visitor<'_> for ImplTraitTypeIdVisitor<'_> {
415 fn visit_ty(&mut self, ty: &Ty) {
417 TyKind::Typeof(_) | TyKind::BareFn(_) => return,
419 TyKind::ImplTrait(id, _) => self.ids.push(id),
422 visit::walk_ty(self, ty);
425 fn visit_path_segment(&mut self, path_span: Span, path_segment: &PathSegment) {
426 if let Some(ref p) = path_segment.args {
427 if let GenericArgs::Parenthesized(_) = **p {
431 visit::walk_path_segment(self, path_span, path_segment)
435 impl<'a, 'hir> LoweringContext<'a, 'hir> {
436 fn lower_crate(mut self, c: &Crate) -> hir::Crate<'hir> {
437 /// Full-crate AST visitor that inserts into a fresh
438 /// `LoweringContext` any information that may be
439 /// needed from arbitrary locations in the crate,
440 /// e.g., the number of lifetime generic parameters
441 /// declared for every type and trait definition.
442 struct MiscCollector<'tcx, 'lowering, 'hir> {
443 lctx: &'tcx mut LoweringContext<'lowering, 'hir>,
444 hir_id_owner: Option<NodeId>,
447 impl MiscCollector<'_, '_, '_> {
448 fn allocate_use_tree_hir_id_counters(&mut self, tree: &UseTree, owner: LocalDefId) {
450 UseTreeKind::Simple(_, id1, id2) => {
451 for &id in &[id1, id2] {
452 self.lctx.resolver.create_def(
459 self.lctx.allocate_hir_id_counter(id);
462 UseTreeKind::Glob => (),
463 UseTreeKind::Nested(ref trees) => {
464 for &(ref use_tree, id) in trees {
465 let hir_id = self.lctx.allocate_hir_id_counter(id);
466 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
472 fn with_hir_id_owner<T>(
474 owner: Option<NodeId>,
475 f: impl FnOnce(&mut Self) -> T,
477 let old = mem::replace(&mut self.hir_id_owner, owner);
479 self.hir_id_owner = old;
484 impl<'tcx> Visitor<'tcx> for MiscCollector<'tcx, '_, '_> {
485 fn visit_pat(&mut self, p: &'tcx Pat) {
486 if let PatKind::Paren(..) | PatKind::Rest = p.kind {
487 // Doesn't generate a HIR node
488 } else if let Some(owner) = self.hir_id_owner {
489 self.lctx.lower_node_id_with_owner(p.id, owner);
492 visit::walk_pat(self, p)
495 fn visit_item(&mut self, item: &'tcx Item) {
496 let hir_id = self.lctx.allocate_hir_id_counter(item.id);
499 ItemKind::Struct(_, ref generics)
500 | ItemKind::Union(_, ref generics)
501 | ItemKind::Enum(_, ref generics)
502 | ItemKind::TyAlias(_, ref generics, ..)
503 | ItemKind::Trait(_, _, ref generics, ..) => {
504 let def_id = self.lctx.resolver.local_def_id(item.id);
508 .filter(|param| match param.kind {
509 ast::GenericParamKind::Lifetime { .. } => true,
513 self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count);
515 ItemKind::Use(ref use_tree) => {
516 self.allocate_use_tree_hir_id_counters(use_tree, hir_id.owner);
521 self.with_hir_id_owner(Some(item.id), |this| {
522 visit::walk_item(this, item);
526 fn visit_assoc_item(&mut self, item: &'tcx AssocItem, ctxt: AssocCtxt) {
527 self.lctx.allocate_hir_id_counter(item.id);
528 let owner = match (&item.kind, ctxt) {
529 // Ignore patterns in trait methods without bodies.
530 (AssocItemKind::Fn(_, _, _, None), AssocCtxt::Trait) => None,
533 self.with_hir_id_owner(owner, |this| visit::walk_assoc_item(this, item, ctxt));
536 fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) {
537 // Ignore patterns in foreign items
538 self.with_hir_id_owner(None, |this| visit::walk_foreign_item(this, i));
541 fn visit_ty(&mut self, t: &'tcx Ty) {
543 // Mirrors the case in visit::walk_ty
544 TyKind::BareFn(ref f) => {
545 walk_list!(self, visit_generic_param, &f.generic_params);
546 // Mirrors visit::walk_fn_decl
547 for parameter in &f.decl.inputs {
548 // We don't lower the ids of argument patterns
549 self.with_hir_id_owner(None, |this| {
550 this.visit_pat(¶meter.pat);
552 self.visit_ty(¶meter.ty)
554 self.visit_fn_ret_ty(&f.decl.output)
556 _ => visit::walk_ty(self, t),
561 self.lower_node_id(CRATE_NODE_ID);
562 debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == Some(hir::CRATE_HIR_ID));
564 visit::walk_crate(&mut MiscCollector { lctx: &mut self, hir_id_owner: None }, c);
565 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
567 let module = self.lower_mod(&c.module);
568 let attrs = self.lower_attrs(&c.attrs);
569 let body_ids = body_ids(&self.bodies);
571 c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect();
577 .map(|(&k, v)| (self.node_id_to_hir_id[k].unwrap(), v.clone()))
580 let mut def_id_to_hir_id = IndexVec::default();
582 for (node_id, hir_id) in self.node_id_to_hir_id.into_iter_enumerated() {
583 if let Some(def_id) = self.resolver.opt_local_def_id(node_id) {
584 if def_id_to_hir_id.len() <= def_id.index() {
585 def_id_to_hir_id.resize(def_id.index() + 1, None);
587 def_id_to_hir_id[def_id] = hir_id;
591 self.resolver.definitions().init_def_id_to_hir_id_mapping(def_id_to_hir_id);
594 item: hir::CrateItem { module, attrs, span: c.span },
595 exported_macros: self.arena.alloc_from_iter(self.exported_macros),
596 non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
598 trait_items: self.trait_items,
599 impl_items: self.impl_items,
602 trait_impls: self.trait_impls,
603 modules: self.modules,
609 fn insert_item(&mut self, item: hir::Item<'hir>) {
610 let id = item.hir_id;
611 // FIXME: Use `debug_asset-rt`.
612 assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0));
613 self.items.insert(id, item);
614 self.modules.get_mut(&self.current_module).unwrap().items.insert(id);
617 fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
618 // Set up the counter if needed.
619 self.item_local_id_counters.entry(owner).or_insert(0);
620 // Always allocate the first `HirId` for the owner itself.
621 let lowered = self.lower_node_id_with_owner(owner, owner);
622 debug_assert_eq!(lowered.local_id.as_u32(), 0);
626 fn lower_node_id_generic(
629 alloc_hir_id: impl FnOnce(&mut Self) -> hir::HirId,
631 assert_ne!(ast_node_id, DUMMY_NODE_ID);
633 let min_size = ast_node_id.as_usize() + 1;
635 if min_size > self.node_id_to_hir_id.len() {
636 self.node_id_to_hir_id.resize(min_size, None);
639 if let Some(existing_hir_id) = self.node_id_to_hir_id[ast_node_id] {
642 // Generate a new `HirId`.
643 let hir_id = alloc_hir_id(self);
644 self.node_id_to_hir_id[ast_node_id] = Some(hir_id);
650 fn with_hir_id_owner<T>(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
652 .item_local_id_counters
653 .insert(owner, HIR_ID_COUNTER_LOCKED)
654 .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner));
655 let def_id = self.resolver.local_def_id(owner);
656 self.current_hir_id_owner.push((def_id, counter));
658 let (new_def_id, new_counter) = self.current_hir_id_owner.pop().unwrap();
660 debug_assert!(def_id == new_def_id);
661 debug_assert!(new_counter >= counter);
663 let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap();
664 debug_assert!(prev == HIR_ID_COUNTER_LOCKED);
668 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
669 /// the `LoweringContext`'s `NodeId => HirId` map.
670 /// Take care not to call this method if the resulting `HirId` is then not
671 /// actually used in the HIR, as that would trigger an assertion in the
672 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
673 /// properly. Calling the method twice with the same `NodeId` is fine though.
674 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
675 self.lower_node_id_generic(ast_node_id, |this| {
676 let &mut (owner, ref mut local_id_counter) =
677 this.current_hir_id_owner.last_mut().unwrap();
678 let local_id = *local_id_counter;
679 *local_id_counter += 1;
680 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
684 fn lower_node_id_with_owner(&mut self, ast_node_id: NodeId, owner: NodeId) -> hir::HirId {
685 self.lower_node_id_generic(ast_node_id, |this| {
686 let local_id_counter = this
687 .item_local_id_counters
689 .expect("called `lower_node_id_with_owner` before `allocate_hir_id_counter`");
690 let local_id = *local_id_counter;
692 // We want to be sure not to modify the counter in the map while it
693 // is also on the stack. Otherwise we'll get lost updates when writing
694 // back from the stack to the map.
695 debug_assert!(local_id != HIR_ID_COUNTER_LOCKED);
697 *local_id_counter += 1;
698 let owner = this.resolver.opt_local_def_id(owner).expect(
699 "you forgot to call `create_def` or are lowering node-IDs \
700 that do not belong to the current owner",
703 hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) }
707 fn next_id(&mut self) -> hir::HirId {
708 let node_id = self.resolver.next_node_id();
709 self.lower_node_id(node_id)
712 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
714 self.lower_node_id_generic(id, |_| {
715 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
720 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
721 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
722 if pr.unresolved_segments() != 0 {
723 panic!("path not fully resolved: {:?}", pr);
729 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
730 self.resolver.get_import_res(id).present_items()
733 fn diagnostic(&self) -> &rustc_errors::Handler {
734 self.sess.diagnostic()
737 /// Reuses the span but adds information like the kind of the desugaring and features that are
738 /// allowed inside this span.
739 fn mark_span_with_reason(
741 reason: DesugaringKind,
743 allow_internal_unstable: Option<Lrc<[Symbol]>>,
745 span.fresh_expansion(ExpnData {
746 allow_internal_unstable,
747 ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition(), None)
751 fn with_anonymous_lifetime_mode<R>(
753 anonymous_lifetime_mode: AnonymousLifetimeMode,
754 op: impl FnOnce(&mut Self) -> R,
757 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
758 anonymous_lifetime_mode,
760 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
761 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
762 let result = op(self);
763 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
765 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
766 old_anonymous_lifetime_mode
771 /// Creates a new `hir::GenericParam` for every new lifetime and
772 /// type parameter encountered while evaluating `f`. Definitions
773 /// are created with the parent provided. If no `parent_id` is
774 /// provided, no definitions will be returned.
776 /// Presuming that in-band lifetimes are enabled, then
777 /// `self.anonymous_lifetime_mode` will be updated to match the
778 /// parameter while `f` is running (and restored afterwards).
779 fn collect_in_band_defs<T>(
781 parent_def_id: LocalDefId,
782 anonymous_lifetime_mode: AnonymousLifetimeMode,
783 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
784 ) -> (Vec<hir::GenericParam<'hir>>, T) {
785 assert!(!self.is_collecting_in_band_lifetimes);
786 assert!(self.lifetimes_to_define.is_empty());
787 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
789 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
790 self.is_collecting_in_band_lifetimes = true;
792 let (in_band_ty_params, res) = f(self);
794 self.is_collecting_in_band_lifetimes = false;
795 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
797 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
799 let params = lifetimes_to_define
801 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_def_id))
802 .chain(in_band_ty_params.into_iter())
808 /// Converts a lifetime into a new generic parameter.
809 fn lifetime_to_generic_param(
813 parent_def_id: LocalDefId,
814 ) -> hir::GenericParam<'hir> {
815 let node_id = self.resolver.next_node_id();
817 // Get the name we'll use to make the def-path. Note
818 // that collisions are ok here and this shouldn't
819 // really show up for end-user.
820 let (str_name, kind) = match hir_name {
821 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
822 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
823 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
826 // Add a definition for the in-band lifetime def.
827 self.resolver.create_def(
830 DefPathData::LifetimeNs(str_name),
836 hir_id: self.lower_node_id(node_id),
841 pure_wrt_drop: false,
842 kind: hir::GenericParamKind::Lifetime { kind },
846 /// When there is a reference to some lifetime `'a`, and in-band
847 /// lifetimes are enabled, then we want to push that lifetime into
848 /// the vector of names to define later. In that case, it will get
849 /// added to the appropriate generics.
850 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
851 if !self.is_collecting_in_band_lifetimes {
855 if !self.sess.features_untracked().in_band_lifetimes {
859 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
863 let hir_name = ParamName::Plain(ident);
865 if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
866 lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
871 self.lifetimes_to_define.push((ident.span, hir_name));
874 /// When we have either an elided or `'_` lifetime in an impl
875 /// header, we convert it to an in-band lifetime.
876 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
877 assert!(self.is_collecting_in_band_lifetimes);
878 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
879 let hir_name = ParamName::Fresh(index);
880 self.lifetimes_to_define.push((span, hir_name));
884 // Evaluates `f` with the lifetimes in `params` in-scope.
885 // This is used to track which lifetimes have already been defined, and
886 // which are new in-band lifetimes that need to have a definition created
888 fn with_in_scope_lifetime_defs<T>(
890 params: &[GenericParam],
891 f: impl FnOnce(&mut Self) -> T,
893 let old_len = self.in_scope_lifetimes.len();
894 let lt_def_names = params.iter().filter_map(|param| match param.kind {
895 GenericParamKind::Lifetime { .. } => {
896 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
900 self.in_scope_lifetimes.extend(lt_def_names);
904 self.in_scope_lifetimes.truncate(old_len);
908 /// Appends in-band lifetime defs and argument-position `impl
909 /// Trait` defs to the existing set of generics.
911 /// Presuming that in-band lifetimes are enabled, then
912 /// `self.anonymous_lifetime_mode` will be updated to match the
913 /// parameter while `f` is running (and restored afterwards).
914 fn add_in_band_defs<T>(
917 parent_def_id: LocalDefId,
918 anonymous_lifetime_mode: AnonymousLifetimeMode,
919 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
920 ) -> (hir::Generics<'hir>, T) {
921 let (in_band_defs, (mut lowered_generics, res)) =
922 self.with_in_scope_lifetime_defs(&generics.params, |this| {
923 this.collect_in_band_defs(parent_def_id, anonymous_lifetime_mode, |this| {
924 let mut params = Vec::new();
925 // Note: it is necessary to lower generics *before* calling `f`.
926 // When lowering `async fn`, there's a final step when lowering
927 // the return type that assumes that all in-scope lifetimes have
928 // already been added to either `in_scope_lifetimes` or
929 // `lifetimes_to_define`. If we swapped the order of these two,
930 // in-band-lifetimes introduced by generics or where-clauses
931 // wouldn't have been added yet.
933 this.lower_generics_mut(generics, ImplTraitContext::Universal(&mut params));
934 let res = f(this, &mut params);
935 (params, (generics, res))
939 lowered_generics.params.extend(in_band_defs);
941 let lowered_generics = lowered_generics.into_generics(self.arena);
942 (lowered_generics, res)
945 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
946 let was_in_dyn_type = self.is_in_dyn_type;
947 self.is_in_dyn_type = in_scope;
949 let result = f(self);
951 self.is_in_dyn_type = was_in_dyn_type;
956 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
957 let was_in_loop_condition = self.is_in_loop_condition;
958 self.is_in_loop_condition = false;
960 let catch_scopes = mem::take(&mut self.catch_scopes);
961 let loop_scopes = mem::take(&mut self.loop_scopes);
963 self.catch_scopes = catch_scopes;
964 self.loop_scopes = loop_scopes;
966 self.is_in_loop_condition = was_in_loop_condition;
971 fn lower_attrs(&mut self, attrs: &[Attribute]) -> &'hir [Attribute] {
972 self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)))
975 fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
976 // Note that we explicitly do not walk the path. Since we don't really
977 // lower attributes (we use the AST version) there is nowhere to keep
978 // the `HirId`s. We don't actually need HIR version of attributes anyway.
979 let kind = match attr.kind {
980 AttrKind::Normal(ref item) => AttrKind::Normal(AttrItem {
981 path: item.path.clone(),
982 args: self.lower_mac_args(&item.args),
984 AttrKind::DocComment(comment) => AttrKind::DocComment(comment),
987 Attribute { kind, id: attr.id, style: attr.style, span: attr.span }
990 fn lower_mac_args(&mut self, args: &MacArgs) -> MacArgs {
992 MacArgs::Empty => MacArgs::Empty,
993 MacArgs::Delimited(dspan, delim, ref tokens) => {
994 MacArgs::Delimited(dspan, delim, self.lower_token_stream(tokens.clone()))
996 MacArgs::Eq(eq_span, ref tokens) => {
997 MacArgs::Eq(eq_span, self.lower_token_stream(tokens.clone()))
1002 fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream {
1003 tokens.into_trees().flat_map(|tree| self.lower_token_tree(tree).into_trees()).collect()
1006 fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream {
1008 TokenTree::Token(token) => self.lower_token(token),
1009 TokenTree::Delimited(span, delim, tts) => {
1010 TokenTree::Delimited(span, delim, self.lower_token_stream(tts)).into()
1015 fn lower_token(&mut self, token: Token) -> TokenStream {
1017 token::Interpolated(nt) => {
1018 let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span);
1019 TokenTree::Delimited(
1020 DelimSpan::from_single(token.span),
1021 DelimToken::NoDelim,
1022 self.lower_token_stream(tts),
1026 _ => TokenTree::Token(token).into(),
1030 /// Given an associated type constraint like one of these:
1033 /// T: Iterator<Item: Debug>
1035 /// T: Iterator<Item = Debug>
1039 /// returns a `hir::TypeBinding` representing `Item`.
1040 fn lower_assoc_ty_constraint(
1042 constraint: &AssocTyConstraint,
1043 itctx: ImplTraitContext<'_, 'hir>,
1044 ) -> hir::TypeBinding<'hir> {
1045 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1047 let kind = match constraint.kind {
1048 AssocTyConstraintKind::Equality { ref ty } => {
1049 hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
1051 AssocTyConstraintKind::Bound { ref bounds } => {
1052 let mut capturable_lifetimes;
1053 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1054 let (desugar_to_impl_trait, itctx) = match itctx {
1055 // We are in the return position:
1057 // fn foo() -> impl Iterator<Item: Debug>
1061 // fn foo() -> impl Iterator<Item = impl Debug>
1062 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1063 | ImplTraitContext::OtherOpaqueTy { .. } => (true, itctx),
1065 // We are in the argument position, but within a dyn type:
1067 // fn foo(x: dyn Iterator<Item: Debug>)
1071 // fn foo(x: dyn Iterator<Item = impl Debug>)
1072 ImplTraitContext::Universal(..) if self.is_in_dyn_type => (true, itctx),
1074 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1075 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1076 // "impl trait context" to permit `impl Debug` in this position (it desugars
1077 // then to an opaque type).
1079 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1080 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1081 capturable_lifetimes = FxHashSet::default();
1084 ImplTraitContext::OtherOpaqueTy {
1085 capturable_lifetimes: &mut capturable_lifetimes,
1086 origin: hir::OpaqueTyOrigin::Misc,
1091 // We are in the parameter position, but not within a dyn type:
1093 // fn foo(x: impl Iterator<Item: Debug>)
1095 // so we leave it as is and this gets expanded in astconv to a bound like
1096 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1098 _ => (false, itctx),
1101 if desugar_to_impl_trait {
1102 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1103 // constructing the HIR for `impl bounds...` and then lowering that.
1105 let impl_trait_node_id = self.resolver.next_node_id();
1106 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
1107 self.resolver.create_def(
1110 DefPathData::ImplTrait,
1115 self.with_dyn_type_scope(false, |this| {
1116 let node_id = this.resolver.next_node_id();
1117 let ty = this.lower_ty(
1120 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1121 span: constraint.span,
1126 hir::TypeBindingKind::Equality { ty }
1129 // Desugar `AssocTy: Bounds` into a type binding where the
1130 // later desugars into a trait predicate.
1131 let bounds = self.lower_param_bounds(bounds, itctx);
1133 hir::TypeBindingKind::Constraint { bounds }
1139 hir_id: self.lower_node_id(constraint.id),
1140 ident: constraint.ident,
1142 span: constraint.span,
1146 fn lower_generic_arg(
1148 arg: &ast::GenericArg,
1149 itctx: ImplTraitContext<'_, 'hir>,
1150 ) -> hir::GenericArg<'hir> {
1152 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1153 ast::GenericArg::Type(ty) => {
1154 // We parse const arguments as path types as we cannot distinguish them during
1155 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1156 // type and value namespaces. If we resolved the path in the value namespace, we
1157 // transform it into a generic const argument.
1158 if let TyKind::Path(ref qself, ref path) = ty.kind {
1159 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1160 let res = partial_res.base_res();
1161 if !res.matches_ns(Namespace::TypeNS) {
1163 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1167 // Construct a AnonConst where the expr is the "ty"'s path.
1169 let parent_def_id = self.current_hir_id_owner.last().unwrap().0;
1170 let node_id = self.resolver.next_node_id();
1172 // Add a definition for the in-band const def.
1173 self.resolver.create_def(
1176 DefPathData::AnonConst,
1181 let path_expr = Expr {
1183 kind: ExprKind::Path(qself.clone(), path.clone()),
1185 attrs: AttrVec::new(),
1189 let ct = self.with_new_scopes(|this| hir::AnonConst {
1190 hir_id: this.lower_node_id(node_id),
1191 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1193 return GenericArg::Const(ConstArg { value: ct, span: ty.span });
1197 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1199 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1200 value: self.lower_anon_const(&ct),
1201 span: ct.value.span,
1206 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1207 self.arena.alloc(self.lower_ty_direct(t, itctx))
1213 qself: &Option<QSelf>,
1215 param_mode: ParamMode,
1216 itctx: ImplTraitContext<'_, 'hir>,
1217 ) -> hir::Ty<'hir> {
1218 let id = self.lower_node_id(t.id);
1219 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1220 let ty = self.ty_path(id, t.span, qpath);
1221 if let hir::TyKind::TraitObject(..) = ty.kind {
1222 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1227 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1228 hir::Ty { hir_id: self.next_id(), kind, span }
1231 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1232 self.ty(span, hir::TyKind::Tup(tys))
1235 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1236 let kind = match t.kind {
1237 TyKind::Infer => hir::TyKind::Infer,
1238 TyKind::Err => hir::TyKind::Err,
1239 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1240 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1241 TyKind::Rptr(ref region, ref mt) => {
1242 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1243 let lifetime = match *region {
1244 Some(ref lt) => self.lower_lifetime(lt),
1245 None => self.elided_ref_lifetime(span),
1247 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1249 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1250 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1251 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1252 generic_params: this.lower_generic_params(
1254 &NodeMap::default(),
1255 ImplTraitContext::disallowed(),
1257 unsafety: this.lower_unsafety(f.unsafety),
1258 abi: this.lower_extern(f.ext),
1259 decl: this.lower_fn_decl(&f.decl, None, false, None),
1260 param_names: this.lower_fn_params_to_names(&f.decl),
1264 TyKind::Never => hir::TyKind::Never,
1265 TyKind::Tup(ref tys) => {
1266 hir::TyKind::Tup(self.arena.alloc_from_iter(
1267 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1270 TyKind::Paren(ref ty) => {
1271 return self.lower_ty_direct(ty, itctx);
1273 TyKind::Path(ref qself, ref path) => {
1274 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1276 TyKind::ImplicitSelf => {
1277 let res = self.expect_full_res(t.id);
1278 let res = self.lower_res(res);
1279 hir::TyKind::Path(hir::QPath::Resolved(
1281 self.arena.alloc(hir::Path {
1283 segments: arena_vec![self; hir::PathSegment::from_ident(
1284 Ident::with_dummy_span(kw::SelfUpper)
1290 TyKind::Array(ref ty, ref length) => {
1291 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1293 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1294 TyKind::TraitObject(ref bounds, kind) => {
1295 let mut lifetime_bound = None;
1296 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1298 this.arena.alloc_from_iter(bounds.iter().filter_map(
1299 |bound| match *bound {
1300 GenericBound::Trait(
1302 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1303 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1304 // `?const ?Bound` will cause an error during AST validation
1305 // anyways, so treat it like `?Bound` as compilation proceeds.
1306 GenericBound::Trait(
1308 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1310 GenericBound::Outlives(ref lifetime) => {
1311 if lifetime_bound.is_none() {
1312 lifetime_bound = Some(this.lower_lifetime(lifetime));
1318 let lifetime_bound =
1319 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1320 (bounds, lifetime_bound)
1322 if kind != TraitObjectSyntax::Dyn {
1323 self.maybe_lint_bare_trait(t.span, t.id, false);
1325 hir::TyKind::TraitObject(bounds, lifetime_bound)
1327 TyKind::ImplTrait(def_node_id, ref bounds) => {
1330 ImplTraitContext::ReturnPositionOpaqueTy { fn_def_id, origin } => self
1331 .lower_opaque_impl_trait(
1337 |this| this.lower_param_bounds(bounds, itctx),
1339 ImplTraitContext::OtherOpaqueTy { ref capturable_lifetimes, origin } => {
1340 // Reset capturable lifetimes, any nested impl trait
1341 // types will inherit lifetimes from this opaque type,
1342 // so don't need to capture them again.
1343 let nested_itctx = ImplTraitContext::OtherOpaqueTy {
1344 capturable_lifetimes: &mut FxHashSet::default(),
1347 self.lower_opaque_impl_trait(
1352 Some(capturable_lifetimes),
1353 |this| this.lower_param_bounds(bounds, nested_itctx),
1356 ImplTraitContext::Universal(in_band_ty_params) => {
1357 // Add a definition for the in-band `Param`.
1358 let def_id = self.resolver.local_def_id(def_node_id);
1360 let hir_bounds = self.lower_param_bounds(
1362 ImplTraitContext::Universal(in_band_ty_params),
1364 // Set the name to `impl Bound1 + Bound2`.
1365 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1366 in_band_ty_params.push(hir::GenericParam {
1367 hir_id: self.lower_node_id(def_node_id),
1368 name: ParamName::Plain(ident),
1369 pure_wrt_drop: false,
1373 kind: hir::GenericParamKind::Type {
1375 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1379 hir::TyKind::Path(hir::QPath::Resolved(
1381 self.arena.alloc(hir::Path {
1383 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1384 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1388 ImplTraitContext::Disallowed(pos) => {
1389 let allowed_in = if self.sess.features_untracked().impl_trait_in_bindings {
1390 "bindings or function and inherent method return types"
1392 "function and inherent method return types"
1394 let mut err = struct_span_err!(
1398 "`impl Trait` not allowed outside of {}",
1401 if pos == ImplTraitPosition::Binding && nightly_options::is_nightly_build()
1404 "add `#![feature(impl_trait_in_bindings)]` to the crate \
1405 attributes to enable",
1413 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1414 TyKind::CVarArgs => {
1415 self.sess.delay_span_bug(
1417 "`TyKind::CVarArgs` should have been handled elsewhere",
1423 hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) }
1426 fn lower_opaque_impl_trait(
1429 fn_def_id: Option<DefId>,
1430 origin: hir::OpaqueTyOrigin,
1431 opaque_ty_node_id: NodeId,
1432 capturable_lifetimes: Option<&FxHashSet<hir::LifetimeName>>,
1433 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1434 ) -> hir::TyKind<'hir> {
1436 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1437 fn_def_id, opaque_ty_node_id, span,
1440 // Make sure we know that some funky desugaring has been going on here.
1441 // This is a first: there is code in other places like for loop
1442 // desugaring that explicitly states that we don't want to track that.
1443 // Not tracking it makes lints in rustc and clippy very fragile, as
1444 // frequently opened issues show.
1445 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1447 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1449 self.allocate_hir_id_counter(opaque_ty_node_id);
1451 let hir_bounds = self.with_hir_id_owner(opaque_ty_node_id, lower_bounds);
1453 let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
1457 capturable_lifetimes,
1460 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1462 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1464 self.with_hir_id_owner(opaque_ty_node_id, move |lctx| {
1465 let opaque_ty_item = hir::OpaqueTy {
1466 generics: hir::Generics {
1467 params: lifetime_defs,
1468 where_clause: hir::WhereClause { predicates: &[], span },
1472 impl_trait_fn: fn_def_id,
1476 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1478 lctx.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span);
1480 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1481 hir::TyKind::OpaqueDef(hir::ItemId { id: opaque_ty_id }, lifetimes)
1485 /// Registers a new opaque type with the proper `NodeId`s and
1486 /// returns the lowered node-ID for the opaque type.
1487 fn generate_opaque_type(
1489 opaque_ty_node_id: NodeId,
1490 opaque_ty_item: hir::OpaqueTy<'hir>,
1492 opaque_ty_span: Span,
1494 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1495 let opaque_ty_id = self.lower_node_id(opaque_ty_node_id);
1496 // Generate an `type Foo = impl Trait;` declaration.
1497 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1498 let opaque_ty_item = hir::Item {
1499 hir_id: opaque_ty_id,
1500 ident: Ident::invalid(),
1501 attrs: Default::default(),
1502 kind: opaque_ty_item_kind,
1503 vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited),
1504 span: opaque_ty_span,
1507 // Insert the item into the global item list. This usually happens
1508 // automatically for all AST items. But this opaque type item
1509 // does not actually exist in the AST.
1510 self.insert_item(opaque_ty_item);
1514 fn lifetimes_from_impl_trait_bounds(
1516 opaque_ty_id: NodeId,
1517 parent_def_id: LocalDefId,
1518 bounds: hir::GenericBounds<'hir>,
1519 lifetimes_to_include: Option<&FxHashSet<hir::LifetimeName>>,
1520 ) -> (&'hir [hir::GenericArg<'hir>], &'hir [hir::GenericParam<'hir>]) {
1522 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
1523 parent_def_id={:?}, \
1525 opaque_ty_id, parent_def_id, bounds,
1528 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
1529 // appear in the bounds, excluding lifetimes that are created within the bounds.
1530 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
1531 struct ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1532 context: &'r mut LoweringContext<'a, 'hir>,
1534 opaque_ty_id: NodeId,
1535 collect_elided_lifetimes: bool,
1536 currently_bound_lifetimes: Vec<hir::LifetimeName>,
1537 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
1538 output_lifetimes: Vec<hir::GenericArg<'hir>>,
1539 output_lifetime_params: Vec<hir::GenericParam<'hir>>,
1540 lifetimes_to_include: Option<&'r FxHashSet<hir::LifetimeName>>,
1543 impl<'r, 'a, 'v, 'hir> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
1544 type Map = intravisit::ErasedMap<'v>;
1546 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1547 intravisit::NestedVisitorMap::None
1550 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
1551 // Don't collect elided lifetimes used inside of `Fn()` syntax.
1552 if parameters.parenthesized {
1553 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1554 self.collect_elided_lifetimes = false;
1555 intravisit::walk_generic_args(self, span, parameters);
1556 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1558 intravisit::walk_generic_args(self, span, parameters);
1562 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
1563 // Don't collect elided lifetimes used inside of `fn()` syntax.
1564 if let hir::TyKind::BareFn(_) = t.kind {
1565 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
1566 self.collect_elided_lifetimes = false;
1568 // Record the "stack height" of `for<'a>` lifetime bindings
1569 // to be able to later fully undo their introduction.
1570 let old_len = self.currently_bound_lifetimes.len();
1571 intravisit::walk_ty(self, t);
1572 self.currently_bound_lifetimes.truncate(old_len);
1574 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
1576 intravisit::walk_ty(self, t)
1580 fn visit_poly_trait_ref(
1582 trait_ref: &'v hir::PolyTraitRef<'v>,
1583 modifier: hir::TraitBoundModifier,
1585 // Record the "stack height" of `for<'a>` lifetime bindings
1586 // to be able to later fully undo their introduction.
1587 let old_len = self.currently_bound_lifetimes.len();
1588 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
1589 self.currently_bound_lifetimes.truncate(old_len);
1592 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
1593 // Record the introduction of 'a in `for<'a> ...`.
1594 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
1595 // Introduce lifetimes one at a time so that we can handle
1596 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
1597 let lt_name = hir::LifetimeName::Param(param.name);
1598 self.currently_bound_lifetimes.push(lt_name);
1601 intravisit::walk_generic_param(self, param);
1604 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
1605 let name = match lifetime.name {
1606 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
1607 if self.collect_elided_lifetimes {
1608 // Use `'_` for both implicit and underscore lifetimes in
1609 // `type Foo<'_> = impl SomeTrait<'_>;`.
1610 hir::LifetimeName::Underscore
1615 hir::LifetimeName::Param(_) => lifetime.name,
1617 // Refers to some other lifetime that is "in
1618 // scope" within the type.
1619 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
1621 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
1624 if !self.currently_bound_lifetimes.contains(&name)
1625 && !self.already_defined_lifetimes.contains(&name)
1626 && self.lifetimes_to_include.map_or(true, |lifetimes| lifetimes.contains(&name))
1628 self.already_defined_lifetimes.insert(name);
1630 self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime {
1631 hir_id: self.context.next_id(),
1632 span: lifetime.span,
1636 let def_node_id = self.context.resolver.next_node_id();
1638 self.context.lower_node_id_with_owner(def_node_id, self.opaque_ty_id);
1639 self.context.resolver.create_def(
1642 DefPathData::LifetimeNs(name.ident().name),
1647 let (name, kind) = match name {
1648 hir::LifetimeName::Underscore => (
1649 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1650 hir::LifetimeParamKind::Elided,
1652 hir::LifetimeName::Param(param_name) => {
1653 (param_name, hir::LifetimeParamKind::Explicit)
1655 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1658 self.output_lifetime_params.push(hir::GenericParam {
1661 span: lifetime.span,
1662 pure_wrt_drop: false,
1665 kind: hir::GenericParamKind::Lifetime { kind },
1671 let mut lifetime_collector = ImplTraitLifetimeCollector {
1673 parent: parent_def_id,
1675 collect_elided_lifetimes: true,
1676 currently_bound_lifetimes: Vec::new(),
1677 already_defined_lifetimes: FxHashSet::default(),
1678 output_lifetimes: Vec::new(),
1679 output_lifetime_params: Vec::new(),
1680 lifetimes_to_include,
1683 for bound in bounds {
1684 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
1687 let ImplTraitLifetimeCollector { output_lifetimes, output_lifetime_params, .. } =
1691 self.arena.alloc_from_iter(output_lifetimes),
1692 self.arena.alloc_from_iter(output_lifetime_params),
1696 fn lower_local(&mut self, l: &Local) -> (hir::Local<'hir>, SmallVec<[NodeId; 1]>) {
1697 let mut ids = SmallVec::<[NodeId; 1]>::new();
1698 if self.sess.features_untracked().impl_trait_in_bindings {
1699 if let Some(ref ty) = l.ty {
1700 let mut visitor = ImplTraitTypeIdVisitor { ids: &mut ids };
1701 visitor.visit_ty(ty);
1704 let ty = l.ty.as_ref().map(|t| {
1705 let mut capturable_lifetimes;
1708 if self.sess.features_untracked().impl_trait_in_bindings {
1709 capturable_lifetimes = FxHashSet::default();
1710 ImplTraitContext::OtherOpaqueTy {
1711 capturable_lifetimes: &mut capturable_lifetimes,
1712 origin: hir::OpaqueTyOrigin::Binding,
1715 ImplTraitContext::Disallowed(ImplTraitPosition::Binding)
1719 let init = l.init.as_ref().map(|e| self.lower_expr(e));
1722 hir_id: self.lower_node_id(l.id),
1724 pat: self.lower_pat(&l.pat),
1727 attrs: l.attrs.clone(),
1728 source: hir::LocalSource::Normal,
1734 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1735 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1736 // as they are not explicit in HIR/Ty function signatures.
1737 // (instead, the `c_variadic` flag is set to `true`)
1738 let mut inputs = &decl.inputs[..];
1739 if decl.c_variadic() {
1740 inputs = &inputs[..inputs.len() - 1];
1742 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1743 PatKind::Ident(_, ident, _) => ident,
1744 _ => Ident::new(kw::Invalid, param.pat.span),
1748 // Lowers a function declaration.
1750 // `decl`: the unlowered (AST) function declaration.
1751 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1752 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1753 // `make_ret_async` is also `Some`.
1754 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1755 // This guards against trait declarations and implementations where `impl Trait` is
1757 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1758 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1759 // return type `impl Trait` item.
1763 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
1764 impl_trait_return_allow: bool,
1765 make_ret_async: Option<NodeId>,
1766 ) -> &'hir hir::FnDecl<'hir> {
1770 in_band_ty_params: {:?}, \
1771 impl_trait_return_allow: {}, \
1772 make_ret_async: {:?})",
1773 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
1775 let lt_mode = if make_ret_async.is_some() {
1776 // In `async fn`, argument-position elided lifetimes
1777 // must be transformed into fresh generic parameters so that
1778 // they can be applied to the opaque `impl Trait` return type.
1779 AnonymousLifetimeMode::CreateParameter
1781 self.anonymous_lifetime_mode
1784 let c_variadic = decl.c_variadic();
1786 // Remember how many lifetimes were already around so that we can
1787 // only look at the lifetime parameters introduced by the arguments.
1788 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1789 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1790 // as they are not explicit in HIR/Ty function signatures.
1791 // (instead, the `c_variadic` flag is set to `true`)
1792 let mut inputs = &decl.inputs[..];
1794 inputs = &inputs[..inputs.len() - 1];
1796 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1797 if let Some((_, ibty)) = &mut in_band_ty_params {
1798 this.lower_ty_direct(¶m.ty, ImplTraitContext::Universal(ibty))
1800 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
1805 let output = if let Some(ret_id) = make_ret_async {
1806 self.lower_async_fn_ret_ty(
1808 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1813 FnRetTy::Ty(ref ty) => {
1814 let context = match in_band_ty_params {
1815 Some((def_id, _)) if impl_trait_return_allow => {
1816 ImplTraitContext::ReturnPositionOpaqueTy {
1818 origin: hir::OpaqueTyOrigin::FnReturn,
1821 _ => ImplTraitContext::disallowed(),
1823 hir::FnRetTy::Return(self.lower_ty(ty, context))
1825 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(span),
1829 self.arena.alloc(hir::FnDecl {
1833 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1834 let is_mutable_pat = match arg.pat.kind {
1835 PatKind::Ident(BindingMode::ByValue(mt) | BindingMode::ByRef(mt), _, _) => {
1836 mt == Mutability::Mut
1842 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1843 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1844 // Given we are only considering `ImplicitSelf` types, we needn't consider
1845 // the case where we have a mutable pattern to a reference as that would
1846 // no longer be an `ImplicitSelf`.
1847 TyKind::Rptr(_, ref mt)
1848 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1850 hir::ImplicitSelfKind::MutRef
1852 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1853 hir::ImplicitSelfKind::ImmRef
1855 _ => hir::ImplicitSelfKind::None,
1861 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1862 // combined with the following definition of `OpaqueTy`:
1864 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1866 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1867 // `output`: unlowered output type (`T` in `-> T`)
1868 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1869 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1870 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1871 fn lower_async_fn_ret_ty(
1875 opaque_ty_node_id: NodeId,
1876 ) -> hir::FnRetTy<'hir> {
1878 "lower_async_fn_ret_ty(\
1881 opaque_ty_node_id={:?})",
1882 output, fn_def_id, opaque_ty_node_id,
1885 let span = output.span();
1887 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1889 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1891 self.allocate_hir_id_counter(opaque_ty_node_id);
1893 // When we create the opaque type for this async fn, it is going to have
1894 // to capture all the lifetimes involved in the signature (including in the
1895 // return type). This is done by introducing lifetime parameters for:
1897 // - all the explicitly declared lifetimes from the impl and function itself;
1898 // - all the elided lifetimes in the fn arguments;
1899 // - all the elided lifetimes in the return type.
1901 // So for example in this snippet:
1904 // impl<'a> Foo<'a> {
1905 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1906 // // ^ '0 ^ '1 ^ '2
1907 // // elided lifetimes used below
1912 // we would create an opaque type like:
1915 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1918 // and we would then desugar `bar` to the equivalent of:
1921 // impl<'a> Foo<'a> {
1922 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1926 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1927 // this is because the elided lifetimes from the return type
1928 // should be figured out using the ordinary elision rules, and
1929 // this desugaring achieves that.
1931 // The variable `input_lifetimes_count` tracks the number of
1932 // lifetime parameters to the opaque type *not counting* those
1933 // lifetimes elided in the return type. This includes those
1934 // that are explicitly declared (`in_scope_lifetimes`) and
1935 // those elided lifetimes we found in the arguments (current
1936 // content of `lifetimes_to_define`). Next, we will process
1937 // the return type, which will cause `lifetimes_to_define` to
1939 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
1941 let (opaque_ty_id, lifetime_params) = self.with_hir_id_owner(opaque_ty_node_id, |this| {
1942 // We have to be careful to get elision right here. The
1943 // idea is that we create a lifetime parameter for each
1944 // lifetime in the return type. So, given a return type
1945 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1946 // Future<Output = &'1 [ &'2 u32 ]>`.
1948 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1949 // hence the elision takes place at the fn site.
1950 let future_bound = this
1951 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
1952 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1955 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1957 // Calculate all the lifetimes that should be captured
1958 // by the opaque type. This should include all in-scope
1959 // lifetime parameters, including those defined in-band.
1961 // Note: this must be done after lowering the output type,
1962 // as the output type may introduce new in-band lifetimes.
1963 let lifetime_params: Vec<(Span, ParamName)> = this
1967 .map(|name| (name.ident().span, name))
1968 .chain(this.lifetimes_to_define.iter().cloned())
1971 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
1972 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
1973 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
1975 let generic_params =
1976 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
1977 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_id)
1980 let opaque_ty_item = hir::OpaqueTy {
1981 generics: hir::Generics {
1982 params: generic_params,
1983 where_clause: hir::WhereClause { predicates: &[], span },
1986 bounds: arena_vec![this; future_bound],
1987 impl_trait_fn: Some(fn_def_id),
1988 origin: hir::OpaqueTyOrigin::AsyncFn,
1991 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1993 this.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span);
1995 (opaque_ty_id, lifetime_params)
1998 // As documented above on the variable
1999 // `input_lifetimes_count`, we need to create the lifetime
2000 // arguments to our opaque type. Continuing with our example,
2001 // we're creating the type arguments for the return type:
2004 // Bar<'a, 'b, '0, '1, '_>
2007 // For the "input" lifetime parameters, we wish to create
2008 // references to the parameters themselves, including the
2009 // "implicit" ones created from parameter types (`'a`, `'b`,
2012 // For the "output" lifetime parameters, we just want to
2014 let mut generic_args: Vec<_> = lifetime_params[..input_lifetimes_count]
2016 .map(|&(span, hir_name)| {
2017 // Input lifetime like `'a` or `'1`:
2018 GenericArg::Lifetime(hir::Lifetime {
2019 hir_id: self.next_id(),
2021 name: hir::LifetimeName::Param(hir_name),
2025 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
2026 // Output lifetime like `'_`.
2027 GenericArg::Lifetime(hir::Lifetime {
2028 hir_id: self.next_id(),
2030 name: hir::LifetimeName::Implicit,
2032 let generic_args = self.arena.alloc_from_iter(generic_args);
2034 // Create the `Foo<...>` reference itself. Note that the `type
2035 // Foo = impl Trait` is, internally, created as a child of the
2036 // async fn, so the *type parameters* are inherited. It's
2037 // only the lifetime parameters that we must supply.
2038 let opaque_ty_ref = hir::TyKind::OpaqueDef(hir::ItemId { id: opaque_ty_id }, generic_args);
2039 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2040 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2043 /// Transforms `-> T` into `Future<Output = T>`
2044 fn lower_async_fn_output_type_to_future_bound(
2049 ) -> hir::GenericBound<'hir> {
2050 // Compute the `T` in `Future<Output = T>` from the return type.
2051 let output_ty = match output {
2052 FnRetTy::Ty(ty) => {
2053 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2054 // `impl Future` opaque type that `async fn` implicitly
2056 let context = ImplTraitContext::ReturnPositionOpaqueTy {
2058 origin: hir::OpaqueTyOrigin::FnReturn,
2060 self.lower_ty(ty, context)
2062 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2066 let future_params = self.arena.alloc(hir::GenericArgs {
2068 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
2069 parenthesized: false,
2072 // ::std::future::Future<future_params>
2074 self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
2076 hir::GenericBound::Trait(
2078 trait_ref: hir::TraitRef { path: future_path, hir_ref_id: self.next_id() },
2079 bound_generic_params: &[],
2082 hir::TraitBoundModifier::None,
2086 fn lower_param_bound(
2089 itctx: ImplTraitContext<'_, 'hir>,
2090 ) -> hir::GenericBound<'hir> {
2092 GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
2093 self.lower_poly_trait_ref(ty, itctx),
2094 self.lower_trait_bound_modifier(modifier),
2096 GenericBound::Outlives(ref lifetime) => {
2097 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2102 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2103 let span = l.ident.span;
2105 ident if ident.name == kw::StaticLifetime => {
2106 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
2108 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
2109 AnonymousLifetimeMode::CreateParameter => {
2110 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2111 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
2114 AnonymousLifetimeMode::PassThrough => {
2115 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
2118 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
2121 self.maybe_collect_in_band_lifetime(ident);
2122 let param_name = ParamName::Plain(ident);
2123 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
2128 fn new_named_lifetime(
2132 name: hir::LifetimeName,
2133 ) -> hir::Lifetime {
2134 hir::Lifetime { hir_id: self.lower_node_id(id), span, name }
2137 fn lower_generic_params_mut<'s>(
2139 params: &'s [GenericParam],
2140 add_bounds: &'s NodeMap<Vec<GenericBound>>,
2141 mut itctx: ImplTraitContext<'s, 'hir>,
2142 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2145 .map(move |param| self.lower_generic_param(param, add_bounds, itctx.reborrow()))
2148 fn lower_generic_params(
2150 params: &[GenericParam],
2151 add_bounds: &NodeMap<Vec<GenericBound>>,
2152 itctx: ImplTraitContext<'_, 'hir>,
2153 ) -> &'hir [hir::GenericParam<'hir>] {
2154 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, add_bounds, itctx))
2157 fn lower_generic_param(
2159 param: &GenericParam,
2160 add_bounds: &NodeMap<Vec<GenericBound>>,
2161 mut itctx: ImplTraitContext<'_, 'hir>,
2162 ) -> hir::GenericParam<'hir> {
2163 let mut bounds: Vec<_> = self
2164 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2165 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
2168 let (name, kind) = match param.kind {
2169 GenericParamKind::Lifetime => {
2170 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2171 self.is_collecting_in_band_lifetimes = false;
2174 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2175 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2177 let param_name = match lt.name {
2178 hir::LifetimeName::Param(param_name) => param_name,
2179 hir::LifetimeName::Implicit
2180 | hir::LifetimeName::Underscore
2181 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2182 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2183 self.sess.diagnostic().span_bug(
2185 "object-lifetime-default should not occur here",
2188 hir::LifetimeName::Error => ParamName::Error,
2192 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2194 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2198 GenericParamKind::Type { ref default, .. } => {
2199 let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x);
2200 if !add_bounds.is_empty() {
2201 let params = self.lower_param_bounds_mut(add_bounds, itctx.reborrow());
2202 bounds.extend(params);
2205 let kind = hir::GenericParamKind::Type {
2206 default: default.as_ref().map(|x| {
2209 ImplTraitContext::OtherOpaqueTy {
2210 capturable_lifetimes: &mut FxHashSet::default(),
2211 origin: hir::OpaqueTyOrigin::Misc,
2218 .filter(|attr| attr.check_name(sym::rustc_synthetic))
2219 .map(|_| hir::SyntheticTyParamKind::ImplTrait)
2223 (hir::ParamName::Plain(param.ident), kind)
2225 GenericParamKind::Const { ref ty, kw_span: _ } => {
2227 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2228 this.lower_ty(&ty, ImplTraitContext::disallowed())
2231 (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const { ty })
2236 hir_id: self.lower_node_id(param.id),
2238 span: param.ident.span,
2239 pure_wrt_drop: attr::contains_name(¶m.attrs, sym::may_dangle),
2240 attrs: self.lower_attrs(¶m.attrs),
2241 bounds: self.arena.alloc_from_iter(bounds),
2249 itctx: ImplTraitContext<'_, 'hir>,
2250 ) -> hir::TraitRef<'hir> {
2251 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2252 hir::QPath::Resolved(None, path) => path,
2253 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2255 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2258 fn lower_poly_trait_ref(
2261 mut itctx: ImplTraitContext<'_, 'hir>,
2262 ) -> hir::PolyTraitRef<'hir> {
2263 let bound_generic_params = self.lower_generic_params(
2264 &p.bound_generic_params,
2265 &NodeMap::default(),
2269 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
2270 // Any impl Trait types defined within this scope can capture
2271 // lifetimes bound on this predicate.
2272 let lt_def_names = p.bound_generic_params.iter().filter_map(|param| match param.kind {
2273 GenericParamKind::Lifetime { .. } => Some(hir::LifetimeName::Param(
2274 ParamName::Plain(param.ident.normalize_to_macros_2_0()),
2278 if let ImplTraitContext::OtherOpaqueTy { ref mut capturable_lifetimes, .. } = itctx {
2279 capturable_lifetimes.extend(lt_def_names.clone());
2282 let res = this.lower_trait_ref(&p.trait_ref, itctx.reborrow());
2284 if let ImplTraitContext::OtherOpaqueTy { ref mut capturable_lifetimes, .. } = itctx {
2285 for param in lt_def_names {
2286 capturable_lifetimes.remove(¶m);
2292 hir::PolyTraitRef { bound_generic_params, trait_ref, span: p.span }
2295 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2296 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2299 fn lower_param_bounds(
2301 bounds: &[GenericBound],
2302 itctx: ImplTraitContext<'_, 'hir>,
2303 ) -> hir::GenericBounds<'hir> {
2304 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2307 fn lower_param_bounds_mut<'s>(
2309 bounds: &'s [GenericBound],
2310 mut itctx: ImplTraitContext<'s, 'hir>,
2311 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2312 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2315 fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> &'hir hir::Block<'hir> {
2316 self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break))
2319 fn lower_block_noalloc(&mut self, b: &Block, targeted_by_break: bool) -> hir::Block<'hir> {
2320 let mut stmts = vec![];
2321 let mut expr: Option<&'hir _> = None;
2323 for (index, stmt) in b.stmts.iter().enumerate() {
2324 if index == b.stmts.len() - 1 {
2325 if let StmtKind::Expr(ref e) = stmt.kind {
2326 expr = Some(self.lower_expr(e));
2328 stmts.extend(self.lower_stmt(stmt));
2331 stmts.extend(self.lower_stmt(stmt));
2336 hir_id: self.lower_node_id(b.id),
2337 stmts: self.arena.alloc_from_iter(stmts),
2339 rules: self.lower_block_check_mode(&b.rules),
2345 /// Lowers a block directly to an expression, presuming that it
2346 /// has no attributes and is not targeted by a `break`.
2347 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2348 let block = self.lower_block(b, false);
2349 self.expr_block(block, AttrVec::new())
2352 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2353 self.with_new_scopes(|this| hir::AnonConst {
2354 hir_id: this.lower_node_id(c.id),
2355 body: this.lower_const_body(c.value.span, Some(&c.value)),
2359 fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt<'hir>; 1]> {
2360 let kind = match s.kind {
2361 StmtKind::Local(ref l) => {
2362 let (l, item_ids) = self.lower_local(l);
2363 let mut ids: SmallVec<[hir::Stmt<'hir>; 1]> = item_ids
2366 let item_id = hir::ItemId { id: self.lower_node_id(item_id) };
2367 self.stmt(s.span, hir::StmtKind::Item(item_id))
2372 hir_id: self.lower_node_id(s.id),
2373 kind: hir::StmtKind::Local(self.arena.alloc(l)),
2379 StmtKind::Item(ref it) => {
2380 // Can only use the ID once.
2381 let mut id = Some(s.id);
2388 .map(|id| self.lower_node_id(id))
2389 .unwrap_or_else(|| self.next_id());
2391 hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span }
2395 StmtKind::Expr(ref e) => hir::StmtKind::Expr(self.lower_expr(e)),
2396 StmtKind::Semi(ref e) => hir::StmtKind::Semi(self.lower_expr(e)),
2397 StmtKind::Empty => return smallvec![],
2398 StmtKind::MacCall(..) => panic!("shouldn't exist here"),
2400 smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }]
2403 fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode {
2405 BlockCheckMode::Default => hir::BlockCheckMode::DefaultBlock,
2406 BlockCheckMode::Unsafe(u) => {
2407 hir::BlockCheckMode::UnsafeBlock(self.lower_unsafe_source(u))
2412 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2414 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2415 UserProvided => hir::UnsafeSource::UserProvided,
2419 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2421 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2422 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2424 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2425 // placeholder for compilation to proceed.
2426 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2427 hir::TraitBoundModifier::Maybe
2432 // Helper methods for building HIR.
2434 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2435 hir::Stmt { span, kind, hir_id: self.next_id() }
2438 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2439 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2446 init: Option<&'hir hir::Expr<'hir>>,
2447 pat: &'hir hir::Pat<'hir>,
2448 source: hir::LocalSource,
2449 ) -> hir::Stmt<'hir> {
2450 let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None };
2451 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2454 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2455 self.block_all(expr.span, &[], Some(expr))
2461 stmts: &'hir [hir::Stmt<'hir>],
2462 expr: Option<&'hir hir::Expr<'hir>>,
2463 ) -> &'hir hir::Block<'hir> {
2464 let blk = hir::Block {
2467 hir_id: self.next_id(),
2468 rules: hir::BlockCheckMode::DefaultBlock,
2470 targeted_by_break: false,
2472 self.arena.alloc(blk)
2475 /// Constructs a `true` or `false` literal pattern.
2476 fn pat_bool(&mut self, span: Span, val: bool) -> &'hir hir::Pat<'hir> {
2477 let expr = self.expr_bool(span, val);
2478 self.pat(span, hir::PatKind::Lit(expr))
2481 fn pat_ok(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2482 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], arena_vec![self; pat])
2485 fn pat_err(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2486 self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], arena_vec![self; pat])
2489 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2490 self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], arena_vec![self; pat])
2493 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2494 self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], &[])
2500 components: &[Symbol],
2501 subpats: &'hir [&'hir hir::Pat<'hir>],
2502 ) -> &'hir hir::Pat<'hir> {
2503 let path = self.std_path(span, components, None, true);
2504 let qpath = hir::QPath::Resolved(None, path);
2505 let pt = if subpats.is_empty() {
2506 hir::PatKind::Path(qpath)
2508 hir::PatKind::TupleStruct(qpath, subpats, None)
2513 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2514 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2517 fn pat_ident_binding_mode(
2521 bm: hir::BindingAnnotation,
2522 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2523 let hir_id = self.next_id();
2526 self.arena.alloc(hir::Pat {
2528 kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None),
2535 fn pat_wild(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2536 self.pat(span, hir::PatKind::Wild)
2539 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2540 self.arena.alloc(hir::Pat { hir_id: self.next_id(), kind, span })
2543 /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when
2544 /// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
2545 /// The path is also resolved according to `is_value`.
2549 components: &[Symbol],
2550 params: Option<&'hir hir::GenericArgs<'hir>>,
2552 ) -> &'hir hir::Path<'hir> {
2553 let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS };
2554 let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns);
2556 let mut segments: Vec<_> = path
2560 let res = self.expect_full_res(segment.id);
2562 ident: segment.ident,
2563 hir_id: Some(self.lower_node_id(segment.id)),
2564 res: Some(self.lower_res(res)),
2570 segments.last_mut().unwrap().args = params;
2572 self.arena.alloc(hir::Path {
2574 res: res.map_id(|_| panic!("unexpected `NodeId`")),
2575 segments: self.arena.alloc_from_iter(segments),
2581 mut hir_id: hir::HirId,
2583 qpath: hir::QPath<'hir>,
2584 ) -> hir::Ty<'hir> {
2585 let kind = match qpath {
2586 hir::QPath::Resolved(None, path) => {
2587 // Turn trait object paths into `TyKind::TraitObject` instead.
2589 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2590 let principal = hir::PolyTraitRef {
2591 bound_generic_params: &[],
2592 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2596 // The original ID is taken by the `PolyTraitRef`,
2597 // so the `Ty` itself needs a different one.
2598 hir_id = self.next_id();
2599 hir::TyKind::TraitObject(
2600 arena_vec![self; principal],
2601 self.elided_dyn_bound(span),
2604 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2607 _ => hir::TyKind::Path(qpath),
2610 hir::Ty { hir_id, kind, span }
2613 /// Invoked to create the lifetime argument for a type `&T`
2614 /// with no explicit lifetime.
2615 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2616 match self.anonymous_lifetime_mode {
2617 // Intercept when we are in an impl header or async fn and introduce an in-band
2619 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2621 AnonymousLifetimeMode::CreateParameter => {
2622 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2624 hir_id: self.next_id(),
2626 name: hir::LifetimeName::Param(fresh_name),
2630 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2632 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2636 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2637 /// return a "error lifetime".
2638 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2639 let (id, msg, label) = match id {
2640 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2643 self.resolver.next_node_id(),
2644 "`&` without an explicit lifetime name cannot be used here",
2645 "explicit lifetime name needed here",
2649 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2650 err.span_label(span, label);
2653 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2656 /// Invoked to create the lifetime argument(s) for a path like
2657 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2658 /// sorts of cases are deprecated. This may therefore report a warning or an
2659 /// error, depending on the mode.
2660 fn elided_path_lifetimes<'s>(
2664 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2665 (0..count).map(move |_| self.elided_path_lifetime(span))
2668 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
2669 match self.anonymous_lifetime_mode {
2670 AnonymousLifetimeMode::CreateParameter => {
2671 // We should have emitted E0726 when processing this path above
2673 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2674 let id = self.resolver.next_node_id();
2675 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2677 // `PassThrough` is the normal case.
2678 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2679 // is unsuitable here, as these can occur from missing lifetime parameters in a
2680 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2681 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2682 // later, at which point a suitable error will be emitted.
2683 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2684 self.new_implicit_lifetime(span)
2689 /// Invoked to create the lifetime argument(s) for an elided trait object
2690 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2691 /// when the bound is written, even if it is written with `'_` like in
2692 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2693 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2694 match self.anonymous_lifetime_mode {
2695 // NB. We intentionally ignore the create-parameter mode here.
2696 // and instead "pass through" to resolve-lifetimes, which will apply
2697 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2698 // do not act like other elided lifetimes. In other words, given this:
2700 // impl Foo for Box<dyn Debug>
2702 // we do not introduce a fresh `'_` to serve as the bound, but instead
2703 // ultimately translate to the equivalent of:
2705 // impl Foo for Box<dyn Debug + 'static>
2707 // `resolve_lifetime` has the code to make that happen.
2708 AnonymousLifetimeMode::CreateParameter => {}
2710 AnonymousLifetimeMode::ReportError => {
2711 // ReportError applies to explicit use of `'_`.
2714 // This is the normal case.
2715 AnonymousLifetimeMode::PassThrough => {}
2718 let r = hir::Lifetime {
2719 hir_id: self.next_id(),
2721 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2723 debug!("elided_dyn_bound: r={:?}", r);
2727 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
2728 hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit }
2731 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
2732 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2733 // call site which do not have a macro backtrace. See #61963.
2734 let is_macro_callsite = self
2737 .span_to_snippet(span)
2738 .map(|snippet| snippet.starts_with("#["))
2740 if !is_macro_callsite {
2741 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2745 "trait objects without an explicit `dyn` are deprecated",
2746 BuiltinLintDiagnostics::BareTraitObject(span, is_global),
2752 fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'_>>) -> Vec<hir::BodyId> {
2753 // Sorting by span ensures that we get things in order within a
2754 // file, and also puts the files in a sensible order.
2755 let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2756 body_ids.sort_by_key(|b| bodies[b].value.span);
2760 /// Helper struct for delayed construction of GenericArgs.
2761 struct GenericArgsCtor<'hir> {
2762 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2763 bindings: &'hir [hir::TypeBinding<'hir>],
2764 parenthesized: bool,
2767 impl<'hir> GenericArgsCtor<'hir> {
2768 fn is_empty(&self) -> bool {
2769 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2772 fn into_generic_args(self, arena: &'hir Arena<'hir>) -> hir::GenericArgs<'hir> {
2774 args: arena.alloc_from_iter(self.args),
2775 bindings: self.bindings,
2776 parenthesized: self.parenthesized,