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), 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(crate_visibility_modifier)]
34 #![feature(box_patterns)]
36 #![feature(never_type)]
37 #![recursion_limit = "256"]
38 #![allow(rustc::potential_query_instability)]
40 use rustc_ast::token::{self, Token};
41 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream, TokenTree};
43 use rustc_ast::{self as ast, *};
44 use rustc_ast_pretty::pprust;
45 use rustc_data_structures::captures::Captures;
46 use rustc_data_structures::fingerprint::Fingerprint;
47 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
48 use rustc_data_structures::sorted_map::SortedMap;
49 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
50 use rustc_data_structures::sync::Lrc;
51 use rustc_errors::struct_span_err;
53 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
54 use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID};
55 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
56 use rustc_hir::intravisit;
57 use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate};
58 use rustc_index::vec::{Idx, IndexVec};
59 use rustc_query_system::ich::StableHashingContext;
60 use rustc_session::lint::LintBuffer;
61 use rustc_session::parse::feature_err;
62 use rustc_session::utils::{FlattenNonterminals, NtToTokenstream};
63 use rustc_session::Session;
64 use rustc_span::hygiene::{ExpnId, MacroKind};
65 use rustc_span::source_map::{respan, DesugaringKind};
66 use rustc_span::symbol::{kw, sym, Ident, Symbol};
67 use rustc_span::{Span, DUMMY_SP};
69 use smallvec::SmallVec;
70 use std::collections::hash_map::Entry;
71 use tracing::{debug, trace};
73 macro_rules! arena_vec {
74 ($this:expr; $($x:expr),*) => (
75 $this.arena.alloc_from_iter([$($x),*])
87 rustc_hir::arena_types!(rustc_arena::declare_arena);
89 struct LoweringContext<'a, 'hir: 'a> {
90 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
93 resolver: &'a mut dyn ResolverAstLowering,
95 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
96 /// if we don't have this function pointer. To avoid that dependency so that
97 /// `rustc_middle` is independent of the parser, we use dynamic dispatch here.
98 nt_to_tokenstream: NtToTokenstream,
100 /// Used to allocate HIR nodes.
101 arena: &'hir Arena<'hir>,
103 /// The items being lowered are collected here.
104 owners: IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
105 /// Bodies inside the owner being lowered.
106 bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
107 /// Attributes inside the owner being lowered.
108 attrs: SortedMap<hir::ItemLocalId, &'hir [Attribute]>,
110 generator_kind: Option<hir::GeneratorKind>,
112 /// When inside an `async` context, this is the `HirId` of the
113 /// `task_context` local bound to the resume argument of the generator.
114 task_context: Option<hir::HirId>,
116 /// Used to get the current `fn`'s def span to point to when using `await`
117 /// outside of an `async fn`.
118 current_item: Option<Span>,
120 catch_scope: Option<NodeId>,
121 loop_scope: Option<NodeId>,
122 is_in_loop_condition: bool,
123 is_in_trait_impl: bool,
124 is_in_dyn_type: bool,
126 /// What to do when we encounter an "anonymous lifetime
127 /// reference". The term "anonymous" is meant to encompass both
128 /// `'_` lifetimes as well as fully elided cases where nothing is
129 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
130 anonymous_lifetime_mode: AnonymousLifetimeMode,
132 /// Used to create lifetime definitions for anonymous lifetimes.
133 /// When an anonymous lifetime is encountered in a function or impl header and
134 /// requires to create a fresh lifetime parameter, it is added
135 /// to this list. The results of this list are then added to the list of
136 /// lifetime definitions in the corresponding impl or function generics.
137 lifetimes_to_define: Vec<(Span, NodeId)>,
139 /// If anonymous lifetimes are being collected, this field holds the parent
140 /// `LocalDefId` to create the fresh lifetime parameters' `LocalDefId`.
141 is_collecting_anonymous_lifetimes: Option<LocalDefId>,
143 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
144 /// We always store a `normalize_to_macros_2_0()` version of the param-name in this
146 in_scope_lifetimes: Vec<ParamName>,
148 current_hir_id_owner: LocalDefId,
149 item_local_id_counter: hir::ItemLocalId,
150 local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
151 trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
153 /// NodeIds that are lowered inside the current HIR owner.
154 node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
156 allow_try_trait: Option<Lrc<[Symbol]>>,
157 allow_gen_future: Option<Lrc<[Symbol]>>,
158 allow_into_future: Option<Lrc<[Symbol]>>,
161 pub trait ResolverAstLowering {
162 fn def_key(&mut self, id: DefId) -> DefKey;
164 fn def_span(&self, id: LocalDefId) -> Span;
166 fn item_generics_num_lifetimes(&self, def: DefId) -> usize;
168 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>>;
170 /// Obtains resolution for a `NodeId` with a single resolution.
171 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
173 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
174 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
176 /// Obtains resolution for a label with the given `NodeId`.
177 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
179 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
180 /// This should only return `None` during testing.
181 fn definitions(&mut self) -> &mut Definitions;
183 fn create_stable_hashing_context(&self) -> StableHashingContext<'_>;
185 fn lint_buffer(&mut self) -> &mut LintBuffer;
187 fn next_node_id(&mut self) -> NodeId;
189 fn take_trait_map(&mut self, node: NodeId) -> Option<Vec<hir::TraitCandidate>>;
191 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
193 fn local_def_id(&self, node: NodeId) -> LocalDefId;
195 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
200 node_id: ast::NodeId,
206 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
209 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
210 /// and if so, what meaning it has.
212 enum ImplTraitContext<'b, 'a> {
213 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
214 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
215 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
217 /// Newly generated parameters should be inserted into the given `Vec`.
218 Universal(&'b mut Vec<hir::GenericParam<'a>>, LocalDefId),
220 /// Treat `impl Trait` as shorthand for a new opaque type.
221 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
222 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
224 ReturnPositionOpaqueTy {
225 /// `DefId` for the parent function, used to look up necessary
226 /// information later.
227 fn_def_id: LocalDefId,
228 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
229 origin: hir::OpaqueTyOrigin,
231 /// Impl trait in type aliases.
232 TypeAliasesOpaqueTy {
233 /// Set of lifetimes that this opaque type can capture, if it uses
234 /// them. This includes lifetimes bound since we entered this context.
238 /// type A<'b> = impl for<'a> Trait<'a, Out = impl Sized + 'a>;
241 /// Here the inner opaque type captures `'a` because it uses it. It doesn't
242 /// need to capture `'b` because it already inherits the lifetime
243 /// parameter from `A`.
244 // FIXME(impl_trait): but `required_region_bounds` will ICE later
246 capturable_lifetimes: &'b mut FxHashSet<hir::LifetimeName>,
248 /// `impl Trait` is not accepted in this position.
249 Disallowed(ImplTraitPosition),
252 /// Position in which `impl Trait` is disallowed.
253 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
254 enum ImplTraitPosition {
276 impl<'a> ImplTraitContext<'_, 'a> {
277 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
278 use self::ImplTraitContext::*;
280 Universal(params, parent) => Universal(params, *parent),
281 ReturnPositionOpaqueTy { fn_def_id, origin } => {
282 ReturnPositionOpaqueTy { fn_def_id: *fn_def_id, origin: *origin }
284 TypeAliasesOpaqueTy { capturable_lifetimes } => {
285 TypeAliasesOpaqueTy { capturable_lifetimes }
287 Disallowed(pos) => Disallowed(*pos),
292 impl std::fmt::Display for ImplTraitPosition {
293 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294 let name = match self {
295 ImplTraitPosition::Path => "path",
296 ImplTraitPosition::Variable => "variable binding",
297 ImplTraitPosition::Type => "type",
298 ImplTraitPosition::Trait => "trait",
299 ImplTraitPosition::AsyncBlock => "async block",
300 ImplTraitPosition::Bound => "bound",
301 ImplTraitPosition::Generic => "generic",
302 ImplTraitPosition::ExternFnParam => "`extern fn` param",
303 ImplTraitPosition::ClosureParam => "closure param",
304 ImplTraitPosition::PointerParam => "`fn` pointer param",
305 ImplTraitPosition::FnTraitParam => "`Fn` trait param",
306 ImplTraitPosition::TraitParam => "trait method param",
307 ImplTraitPosition::ImplParam => "`impl` method param",
308 ImplTraitPosition::ExternFnReturn => "`extern fn` return",
309 ImplTraitPosition::ClosureReturn => "closure return",
310 ImplTraitPosition::PointerReturn => "`fn` pointer return",
311 ImplTraitPosition::FnTraitReturn => "`Fn` trait return",
312 ImplTraitPosition::TraitReturn => "trait method return",
313 ImplTraitPosition::ImplReturn => "`impl` method return",
316 write!(f, "{}", name)
332 fn impl_trait_return_allowed(&self) -> bool {
334 FnDeclKind::Fn | FnDeclKind::Inherent => true,
340 pub fn lower_crate<'a, 'hir>(
343 resolver: &'a mut dyn ResolverAstLowering,
344 nt_to_tokenstream: NtToTokenstream,
345 arena: &'hir Arena<'hir>,
346 ) -> &'hir hir::Crate<'hir> {
347 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
350 IndexVec::from_fn_n(|_| hir::MaybeOwner::Phantom, resolver.definitions().def_index_count());
358 attrs: SortedMap::new(),
361 is_in_loop_condition: false,
362 is_in_trait_impl: false,
363 is_in_dyn_type: false,
364 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
365 current_hir_id_owner: CRATE_DEF_ID,
366 item_local_id_counter: hir::ItemLocalId::new(0),
367 node_id_to_local_id: FxHashMap::default(),
368 local_id_to_def_id: SortedMap::new(),
369 trait_map: FxHashMap::default(),
370 generator_kind: None,
373 lifetimes_to_define: Vec::new(),
374 is_collecting_anonymous_lifetimes: None,
375 in_scope_lifetimes: Vec::new(),
376 allow_try_trait: Some([sym::try_trait_v2][..].into()),
377 allow_gen_future: Some([sym::gen_future][..].into()),
378 allow_into_future: Some([sym::into_future][..].into()),
383 #[derive(Copy, Clone, PartialEq)]
385 /// Any path in a type context.
387 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
389 /// The `module::Type` in `module::Type::method` in an expression.
393 enum ParenthesizedGenericArgs {
398 /// What to do when we encounter an **anonymous** lifetime
399 /// reference. Anonymous lifetime references come in two flavors. You
400 /// have implicit, or fully elided, references to lifetimes, like the
401 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
402 /// or `Ref<'_, T>`. These often behave the same, but not always:
404 /// - certain usages of implicit references are deprecated, like
405 /// `Ref<T>`, and we sometimes just give hard errors in those cases
407 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
408 /// the same as `Box<dyn Foo + '_>`.
410 /// We describe the effects of the various modes in terms of three cases:
412 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
413 /// of a `&` (e.g., the missing lifetime in something like `&T`)
414 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
415 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
416 /// elided bounds follow special rules. Note that this only covers
417 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
418 /// '_>` is a case of "modern" elision.
419 /// - **Deprecated** -- this covers cases like `Ref<T>`, where the lifetime
420 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
421 /// non-deprecated equivalent.
423 /// Currently, the handling of lifetime elision is somewhat spread out
424 /// between HIR lowering and -- as described below -- the
425 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
426 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
427 /// everything into HIR lowering.
428 #[derive(Copy, Clone, Debug)]
429 enum AnonymousLifetimeMode {
430 /// For **Modern** cases, create a new anonymous region parameter
431 /// and reference that.
433 /// For **Dyn Bound** cases, pass responsibility to
434 /// `resolve_lifetime` code.
436 /// For **Deprecated** cases, report an error.
439 /// Give a hard error when either `&` or `'_` is written. Used to
440 /// rule out things like `where T: Foo<'_>`. Does not imply an
441 /// error on default object bounds (e.g., `Box<dyn Foo>`).
444 /// Pass responsibility to `resolve_lifetime` code for all cases.
448 impl<'a, 'hir> LoweringContext<'a, 'hir> {
449 fn lower_crate(mut self, c: &Crate) -> &'hir hir::Crate<'hir> {
450 debug_assert_eq!(self.resolver.local_def_id(CRATE_NODE_ID), CRATE_DEF_ID);
452 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
454 self.with_hir_id_owner(CRATE_NODE_ID, |lctx| {
455 let module = lctx.lower_mod(&c.items, c.spans.inner_span);
456 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
457 hir::OwnerNode::Crate(lctx.arena.alloc(module))
460 let hir_hash = self.compute_hir_hash();
462 let krate = hir::Crate { owners: self.owners, hir_hash };
463 self.arena.alloc(krate)
466 /// Compute the hash for the HIR of the full crate.
467 /// This hash will then be part of the crate_hash which is stored in the metadata.
468 fn compute_hir_hash(&mut self) -> Fingerprint {
469 let definitions = self.resolver.definitions();
470 let mut hir_body_nodes: Vec<_> = self
473 .filter_map(|(def_id, info)| {
474 let info = info.as_owner()?;
475 let def_path_hash = definitions.def_path_hash(def_id);
476 Some((def_path_hash, info))
479 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
481 let mut stable_hasher = StableHasher::new();
482 let mut hcx = self.resolver.create_stable_hashing_context();
483 hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
484 stable_hasher.finish()
487 fn with_hir_id_owner(
490 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
492 let def_id = self.resolver.local_def_id(owner);
494 let current_attrs = std::mem::take(&mut self.attrs);
495 let current_bodies = std::mem::take(&mut self.bodies);
496 let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
497 let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
498 let current_trait_map = std::mem::take(&mut self.trait_map);
499 let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
500 let current_local_counter =
501 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
503 // Always allocate the first `HirId` for the owner itself.
504 let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
505 debug_assert_eq!(_old, None);
508 debug_assert_eq!(def_id, item.def_id());
509 let info = self.make_owner_info(item);
511 self.attrs = current_attrs;
512 self.bodies = current_bodies;
513 self.node_id_to_local_id = current_node_ids;
514 self.local_id_to_def_id = current_id_to_def_id;
515 self.trait_map = current_trait_map;
516 self.current_hir_id_owner = current_owner;
517 self.item_local_id_counter = current_local_counter;
519 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
520 self.owners[def_id] = hir::MaybeOwner::Owner(self.arena.alloc(info));
525 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> hir::OwnerInfo<'hir> {
526 let attrs = std::mem::take(&mut self.attrs);
527 let mut bodies = std::mem::take(&mut self.bodies);
529 #[cfg(debug_assertions)]
530 for (id, attrs) in attrs.iter() {
531 // Verify that we do not store empty slices in the map.
532 if attrs.is_empty() {
533 panic!("Stored empty attributes for {:?}", id);
537 bodies.sort_by_key(|(k, _)| *k);
538 let bodies = SortedMap::from_presorted_elements(bodies);
539 let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
540 let (nodes, parenting) =
541 index::index_hir(self.sess, self.resolver.definitions(), node, &bodies);
542 let nodes = hir::OwnerNodes {
543 hash_including_bodies,
547 local_id_to_def_id: std::mem::take(&mut self.local_id_to_def_id),
550 let mut hcx = self.resolver.create_stable_hashing_context();
551 let mut stable_hasher = StableHasher::new();
552 attrs.hash_stable(&mut hcx, &mut stable_hasher);
553 let hash = stable_hasher.finish();
554 hir::AttributeMap { map: attrs, hash }
557 hir::OwnerInfo { nodes, parenting, attrs, trait_map: std::mem::take(&mut self.trait_map) }
560 /// Hash the HIR node twice, one deep and one shallow hash. This allows to differentiate
561 /// queries which depend on the full HIR tree and those which only depend on the item signature.
564 node: hir::OwnerNode<'hir>,
565 bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
566 ) -> (Fingerprint, Fingerprint) {
567 let mut hcx = self.resolver.create_stable_hashing_context();
568 let mut stable_hasher = StableHasher::new();
569 hcx.with_hir_bodies(true, node.def_id(), bodies, |hcx| {
570 node.hash_stable(hcx, &mut stable_hasher)
572 let hash_including_bodies = stable_hasher.finish();
573 let mut stable_hasher = StableHasher::new();
574 hcx.with_hir_bodies(false, node.def_id(), bodies, |hcx| {
575 node.hash_stable(hcx, &mut stable_hasher)
577 let hash_without_bodies = stable_hasher.finish();
578 (hash_including_bodies, hash_without_bodies)
581 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
582 /// the `LoweringContext`'s `NodeId => HirId` map.
583 /// Take care not to call this method if the resulting `HirId` is then not
584 /// actually used in the HIR, as that would trigger an assertion in the
585 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
586 /// properly. Calling the method twice with the same `NodeId` is fine though.
587 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
588 assert_ne!(ast_node_id, DUMMY_NODE_ID);
590 match self.node_id_to_local_id.entry(ast_node_id) {
591 Entry::Occupied(o) => {
592 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
594 Entry::Vacant(v) => {
595 // Generate a new `HirId`.
596 let owner = self.current_hir_id_owner;
597 let local_id = self.item_local_id_counter;
598 let hir_id = hir::HirId { owner, local_id };
601 self.item_local_id_counter.increment_by(1);
603 assert_ne!(local_id, hir::ItemLocalId::new(0));
604 if let Some(def_id) = self.resolver.opt_local_def_id(ast_node_id) {
605 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
606 if let o @ hir::MaybeOwner::Phantom = &mut self.owners[def_id] {
607 // Do not override a `MaybeOwner::Owner` that may already here.
608 *o = hir::MaybeOwner::NonOwner(hir_id);
610 self.local_id_to_def_id.insert(local_id, def_id);
613 if let Some(traits) = self.resolver.take_trait_map(ast_node_id) {
614 self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
622 fn next_id(&mut self) -> hir::HirId {
623 let node_id = self.resolver.next_node_id();
624 self.lower_node_id(node_id)
627 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
628 let res: Result<Res, ()> = res.apply_id(|id| {
629 let owner = self.current_hir_id_owner;
630 let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
631 Ok(hir::HirId { owner, local_id })
633 // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
634 // This can happen when trying to lower the return type `x` in erroneous code like
635 // async fn foo(x: u8) -> x {}
636 // In that case, `x` is lowered as a function parameter, and the return type is lowered as
637 // an opaque type as a synthesized HIR owner.
638 res.unwrap_or(Res::Err)
641 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
642 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
643 if pr.unresolved_segments() != 0 {
644 panic!("path not fully resolved: {:?}", pr);
650 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
651 self.resolver.get_import_res(id).present_items()
654 fn diagnostic(&self) -> &rustc_errors::Handler {
655 self.sess.diagnostic()
658 /// Reuses the span but adds information like the kind of the desugaring and features that are
659 /// allowed inside this span.
660 fn mark_span_with_reason(
662 reason: DesugaringKind,
664 allow_internal_unstable: Option<Lrc<[Symbol]>>,
666 span.mark_with_reason(
667 allow_internal_unstable,
670 self.resolver.create_stable_hashing_context(),
674 fn with_anonymous_lifetime_mode<R>(
676 anonymous_lifetime_mode: AnonymousLifetimeMode,
677 op: impl FnOnce(&mut Self) -> R,
680 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
681 anonymous_lifetime_mode,
683 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
684 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
685 let result = op(self);
686 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
688 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
689 old_anonymous_lifetime_mode
694 /// Intercept all spans entering HIR.
695 /// Mark a span as relative to the current owning item.
696 fn lower_span(&self, span: Span) -> Span {
697 if self.sess.opts.debugging_opts.incremental_relative_spans {
698 span.with_parent(Some(self.current_hir_id_owner))
700 // Do not make spans relative when not using incremental compilation.
705 fn lower_ident(&self, ident: Ident) -> Ident {
706 Ident::new(ident.name, self.lower_span(ident.span))
709 /// Creates a new `hir::GenericParam` for every new lifetime and
710 /// type parameter encountered while evaluating `f`. Definitions
711 /// are created with the parent provided. If no `parent_id` is
712 /// provided, no definitions will be returned.
714 /// Presuming that in-band lifetimes are enabled, then
715 /// `self.anonymous_lifetime_mode` will be updated to match the
716 /// parameter while `f` is running (and restored afterwards).
717 fn collect_in_band_defs<T>(
719 parent_def_id: LocalDefId,
720 f: impl FnOnce(&mut Self) -> T,
721 ) -> (Vec<(Span, NodeId)>, T) {
723 std::mem::replace(&mut self.is_collecting_anonymous_lifetimes, Some(parent_def_id));
724 let len = self.lifetimes_to_define.len();
728 let lifetimes_to_define = self.lifetimes_to_define.split_off(len);
729 self.is_collecting_anonymous_lifetimes = was_collecting;
730 (lifetimes_to_define, res)
733 /// Converts a lifetime into a new generic parameter.
734 fn fresh_lifetime_to_generic_param(
738 ) -> hir::GenericParam<'hir> {
739 let hir_id = self.lower_node_id(node_id);
740 let def_id = self.resolver.local_def_id(node_id);
743 name: hir::ParamName::Fresh(def_id),
745 span: self.lower_span(span),
746 pure_wrt_drop: false,
747 kind: hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided },
751 /// When we have either an elided or `'_` lifetime in an impl
752 /// header, we convert it to an in-band lifetime.
753 fn collect_fresh_anonymous_lifetime(&mut self, span: Span) -> ParamName {
754 let Some(parent_def_id) = self.is_collecting_anonymous_lifetimes else { panic!() };
756 let node_id = self.resolver.next_node_id();
758 // Add a definition for the in-band lifetime def.
759 let param_def_id = self.resolver.create_def(
762 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
764 span.with_parent(None),
767 let hir_name = ParamName::Fresh(param_def_id);
768 self.lifetimes_to_define.push((span, node_id));
772 // Evaluates `f` with the lifetimes in `params` in-scope.
773 // This is used to track which lifetimes have already been defined, and
774 // which are new in-band lifetimes that need to have a definition created
776 fn with_in_scope_lifetime_defs<T>(
778 params: &[GenericParam],
779 f: impl FnOnce(&mut Self) -> T,
781 let old_len = self.in_scope_lifetimes.len();
782 let lt_def_names = params.iter().filter_map(|param| match param.kind {
783 GenericParamKind::Lifetime { .. } => {
784 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
788 self.in_scope_lifetimes.extend(lt_def_names);
792 self.in_scope_lifetimes.truncate(old_len);
796 /// Appends in-band lifetime defs and argument-position `impl
797 /// Trait` defs to the existing set of generics.
799 /// Presuming that in-band lifetimes are enabled, then
800 /// `self.anonymous_lifetime_mode` will be updated to match the
801 /// parameter while `f` is running (and restored afterwards).
802 fn add_in_band_defs<T>(
805 parent_def_id: LocalDefId,
806 anonymous_lifetime_mode: AnonymousLifetimeMode,
807 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
808 ) -> (hir::Generics<'hir>, T) {
809 let (lifetimes_to_define, (mut lowered_generics, impl_trait_defs, res)) = self
810 .collect_in_band_defs(parent_def_id, |this| {
811 this.with_anonymous_lifetime_mode(anonymous_lifetime_mode, |this| {
812 this.with_in_scope_lifetime_defs(&generics.params, |this| {
813 let mut impl_trait_defs = Vec::new();
814 // Note: it is necessary to lower generics *before* calling `f`.
815 // When lowering `async fn`, there's a final step when lowering
816 // the return type that assumes that all in-scope lifetimes have
817 // already been added to either `in_scope_lifetimes` or
818 // `lifetimes_to_define`. If we swapped the order of these two,
819 // in-band-lifetimes introduced by generics or where-clauses
820 // wouldn't have been added yet.
821 let generics = this.lower_generics_mut(
823 ImplTraitContext::Universal(
824 &mut impl_trait_defs,
825 this.current_hir_id_owner,
828 let res = f(this, &mut impl_trait_defs);
829 (generics, impl_trait_defs, res)
834 lowered_generics.params.extend(
837 .map(|(span, node_id)| self.fresh_lifetime_to_generic_param(span, node_id))
838 .chain(impl_trait_defs),
841 let lowered_generics = lowered_generics.into_generics(self.arena);
842 (lowered_generics, res)
845 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
846 let was_in_dyn_type = self.is_in_dyn_type;
847 self.is_in_dyn_type = in_scope;
849 let result = f(self);
851 self.is_in_dyn_type = was_in_dyn_type;
856 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
857 let was_in_loop_condition = self.is_in_loop_condition;
858 self.is_in_loop_condition = false;
860 let catch_scope = self.catch_scope.take();
861 let loop_scope = self.loop_scope.take();
863 self.catch_scope = catch_scope;
864 self.loop_scope = loop_scope;
866 self.is_in_loop_condition = was_in_loop_condition;
871 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
872 if attrs.is_empty() {
875 debug_assert_eq!(id.owner, self.current_hir_id_owner);
876 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
877 debug_assert!(!ret.is_empty());
878 self.attrs.insert(id.local_id, ret);
883 fn lower_attr(&self, attr: &Attribute) -> Attribute {
884 // Note that we explicitly do not walk the path. Since we don't really
885 // lower attributes (we use the AST version) there is nowhere to keep
886 // the `HirId`s. We don't actually need HIR version of attributes anyway.
887 // Tokens are also not needed after macro expansion and parsing.
888 let kind = match attr.kind {
889 AttrKind::Normal(ref item, _) => AttrKind::Normal(
891 path: item.path.clone(),
892 args: self.lower_mac_args(&item.args),
897 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
900 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
903 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
904 debug_assert_eq!(id.owner, self.current_hir_id_owner);
905 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
906 if let Some(&a) = self.attrs.get(&target_id.local_id) {
907 debug_assert!(!a.is_empty());
908 self.attrs.insert(id.local_id, a);
912 fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
914 MacArgs::Empty => MacArgs::Empty,
915 MacArgs::Delimited(dspan, delim, ref tokens) => {
916 // This is either a non-key-value attribute, or a `macro_rules!` body.
917 // We either not have any nonterminals present (in the case of an attribute),
918 // or have tokens available for all nonterminals in the case of a nested
919 // `macro_rules`: e.g:
922 // macro_rules! outer {
924 // macro_rules! inner {
931 // In both cases, we don't want to synthesize any tokens
935 self.lower_token_stream(tokens.clone(), CanSynthesizeMissingTokens::No),
938 // This is an inert key-value attribute - it will never be visible to macros
939 // after it gets lowered to HIR. Therefore, we can synthesize tokens with fake
940 // spans to handle nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
941 MacArgs::Eq(eq_span, ref token) => {
942 // In valid code the value is always representable as a single literal token.
943 fn unwrap_single_token(sess: &Session, tokens: TokenStream, span: Span) -> Token {
944 if tokens.len() != 1 {
946 .delay_span_bug(span, "multiple tokens in key-value attribute's value");
948 match tokens.into_trees().next() {
949 Some(TokenTree::Token(token)) => token,
950 Some(TokenTree::Delimited(_, delim, tokens)) => {
951 if delim != token::NoDelim {
952 sess.diagnostic().delay_span_bug(
954 "unexpected delimiter in key-value attribute's value",
957 unwrap_single_token(sess, tokens, span)
959 None => Token::dummy(),
963 let tokens = FlattenNonterminals {
964 parse_sess: &self.sess.parse_sess,
965 synthesize_tokens: CanSynthesizeMissingTokens::Yes,
966 nt_to_tokenstream: self.nt_to_tokenstream,
968 .process_token(token.clone());
969 MacArgs::Eq(eq_span, unwrap_single_token(self.sess, tokens, token.span))
974 fn lower_token_stream(
977 synthesize_tokens: CanSynthesizeMissingTokens,
979 FlattenNonterminals {
980 parse_sess: &self.sess.parse_sess,
982 nt_to_tokenstream: self.nt_to_tokenstream,
984 .process_token_stream(tokens)
987 /// Given an associated type constraint like one of these:
990 /// T: Iterator<Item: Debug>
992 /// T: Iterator<Item = Debug>
996 /// returns a `hir::TypeBinding` representing `Item`.
997 fn lower_assoc_ty_constraint(
999 constraint: &AssocConstraint,
1000 mut itctx: ImplTraitContext<'_, 'hir>,
1001 ) -> hir::TypeBinding<'hir> {
1002 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1004 // lower generic arguments of identifier in constraint
1005 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
1006 let gen_args_ctor = match gen_args {
1007 GenericArgs::AngleBracketed(ref data) => {
1008 self.lower_angle_bracketed_parameter_data(
1010 ParamMode::Explicit,
1015 GenericArgs::Parenthesized(ref data) => {
1016 let mut err = self.sess.struct_span_err(
1018 "parenthesized generic arguments cannot be used in associated type constraints"
1020 // FIXME: try to write a suggestion here
1022 self.lower_angle_bracketed_parameter_data(
1023 &data.as_angle_bracketed_args(),
1024 ParamMode::Explicit,
1030 gen_args_ctor.into_generic_args(self)
1032 self.arena.alloc(hir::GenericArgs::none())
1035 let kind = match constraint.kind {
1036 AssocConstraintKind::Equality { ref term } => {
1037 let term = match term {
1038 Term::Ty(ref ty) => self.lower_ty(ty, itctx).into(),
1039 Term::Const(ref c) => self.lower_anon_const(c).into(),
1041 hir::TypeBindingKind::Equality { term }
1043 AssocConstraintKind::Bound { ref bounds } => {
1044 let mut capturable_lifetimes;
1045 let mut parent_def_id = self.current_hir_id_owner;
1046 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1047 let (desugar_to_impl_trait, itctx) = match itctx {
1048 // We are in the return position:
1050 // fn foo() -> impl Iterator<Item: Debug>
1054 // fn foo() -> impl Iterator<Item = impl Debug>
1055 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1056 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
1058 // We are in the argument position, but within a dyn type:
1060 // fn foo(x: dyn Iterator<Item: Debug>)
1064 // fn foo(x: dyn Iterator<Item = impl Debug>)
1065 ImplTraitContext::Universal(_, parent) if self.is_in_dyn_type => {
1066 parent_def_id = parent;
1070 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1071 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1072 // "impl trait context" to permit `impl Debug` in this position (it desugars
1073 // then to an opaque type).
1075 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1076 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1077 capturable_lifetimes = FxHashSet::default();
1080 ImplTraitContext::TypeAliasesOpaqueTy {
1081 capturable_lifetimes: &mut capturable_lifetimes,
1086 // We are in the parameter position, but not within a dyn type:
1088 // fn foo(x: impl Iterator<Item: Debug>)
1090 // so we leave it as is and this gets expanded in astconv to a bound like
1091 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1093 _ => (false, itctx),
1096 if desugar_to_impl_trait {
1097 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1098 // constructing the HIR for `impl bounds...` and then lowering that.
1100 let impl_trait_node_id = self.resolver.next_node_id();
1101 self.resolver.create_def(
1104 DefPathData::ImplTrait,
1109 self.with_dyn_type_scope(false, |this| {
1110 let node_id = this.resolver.next_node_id();
1111 let ty = this.lower_ty(
1114 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1115 span: this.lower_span(constraint.span),
1121 hir::TypeBindingKind::Equality { term: ty.into() }
1124 // Desugar `AssocTy: Bounds` into a type binding where the
1125 // later desugars into a trait predicate.
1126 let bounds = self.lower_param_bounds(bounds, itctx);
1128 hir::TypeBindingKind::Constraint { bounds }
1134 hir_id: self.lower_node_id(constraint.id),
1135 ident: self.lower_ident(constraint.ident),
1138 span: self.lower_span(constraint.span),
1142 fn lower_generic_arg(
1144 arg: &ast::GenericArg,
1145 itctx: ImplTraitContext<'_, 'hir>,
1146 ) -> hir::GenericArg<'hir> {
1148 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1149 ast::GenericArg::Type(ty) => {
1151 TyKind::Infer if self.sess.features_untracked().generic_arg_infer => {
1152 return GenericArg::Infer(hir::InferArg {
1153 hir_id: self.lower_node_id(ty.id),
1154 span: self.lower_span(ty.span),
1157 // We parse const arguments as path types as we cannot distinguish them during
1158 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1159 // type and value namespaces. If we resolved the path in the value namespace, we
1160 // transform it into a generic const argument.
1161 TyKind::Path(ref qself, ref path) => {
1162 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1163 let res = partial_res.base_res();
1164 if !res.matches_ns(Namespace::TypeNS) {
1166 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1170 // Construct an AnonConst where the expr is the "ty"'s path.
1172 let parent_def_id = self.current_hir_id_owner;
1173 let node_id = self.resolver.next_node_id();
1175 // Add a definition for the in-band const def.
1176 self.resolver.create_def(
1179 DefPathData::AnonConst,
1184 let span = self.lower_span(ty.span);
1185 let path_expr = Expr {
1187 kind: ExprKind::Path(qself.clone(), path.clone()),
1189 attrs: AttrVec::new(),
1193 let ct = self.with_new_scopes(|this| hir::AnonConst {
1194 hir_id: this.lower_node_id(node_id),
1195 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1197 return GenericArg::Const(ConstArg { value: ct, span });
1203 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1205 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1206 value: self.lower_anon_const(&ct),
1207 span: self.lower_span(ct.value.span),
1212 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1213 self.arena.alloc(self.lower_ty_direct(t, itctx))
1219 qself: &Option<QSelf>,
1221 param_mode: ParamMode,
1222 itctx: ImplTraitContext<'_, 'hir>,
1223 ) -> hir::Ty<'hir> {
1224 let id = self.lower_node_id(t.id);
1225 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1226 self.ty_path(id, t.span, qpath)
1229 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1230 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1233 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1234 self.ty(span, hir::TyKind::Tup(tys))
1237 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1238 let kind = match t.kind {
1239 TyKind::Infer => hir::TyKind::Infer,
1240 TyKind::Err => hir::TyKind::Err,
1241 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1242 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1243 TyKind::Rptr(ref region, ref mt) => {
1244 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1245 let lifetime = match *region {
1246 Some(ref lt) => self.lower_lifetime(lt),
1247 None => self.elided_ref_lifetime(span),
1249 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1251 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1252 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1253 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1254 generic_params: this.lower_generic_params(
1256 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1258 unsafety: this.lower_unsafety(f.unsafety),
1259 abi: this.lower_extern(f.ext),
1260 decl: this.lower_fn_decl(&f.decl, None, FnDeclKind::Pointer, None),
1261 param_names: this.lower_fn_params_to_names(&f.decl),
1265 TyKind::Never => hir::TyKind::Never,
1266 TyKind::Tup(ref tys) => {
1267 hir::TyKind::Tup(self.arena.alloc_from_iter(
1268 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1271 TyKind::Paren(ref ty) => {
1272 return self.lower_ty_direct(ty, itctx);
1274 TyKind::Path(ref qself, ref path) => {
1275 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1277 TyKind::ImplicitSelf => {
1278 let res = self.expect_full_res(t.id);
1279 let res = self.lower_res(res);
1280 hir::TyKind::Path(hir::QPath::Resolved(
1282 self.arena.alloc(hir::Path {
1284 segments: arena_vec![self; hir::PathSegment::from_ident(
1285 Ident::with_dummy_span(kw::SelfUpper)
1287 span: self.lower_span(t.span),
1291 TyKind::Array(ref ty, ref length) => {
1292 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1294 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1295 TyKind::TraitObject(ref bounds, kind) => {
1296 let mut lifetime_bound = None;
1297 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1299 this.arena.alloc_from_iter(bounds.iter().filter_map(
1300 |bound| match *bound {
1301 GenericBound::Trait(
1303 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1304 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1305 // `~const ?Bound` will cause an error during AST validation
1306 // anyways, so treat it like `?Bound` as compilation proceeds.
1307 GenericBound::Trait(
1309 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1311 GenericBound::Outlives(ref lifetime) => {
1312 if lifetime_bound.is_none() {
1313 lifetime_bound = Some(this.lower_lifetime(lifetime));
1319 let lifetime_bound =
1320 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1321 (bounds, lifetime_bound)
1323 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1325 TyKind::ImplTrait(def_node_id, ref bounds) => {
1328 ImplTraitContext::ReturnPositionOpaqueTy { fn_def_id, origin } => self
1329 .lower_opaque_impl_trait(
1335 |this| this.lower_param_bounds(bounds, itctx),
1337 ImplTraitContext::TypeAliasesOpaqueTy { ref capturable_lifetimes } => {
1338 // Reset capturable lifetimes, any nested impl trait
1339 // types will inherit lifetimes from this opaque type,
1340 // so don't need to capture them again.
1341 let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy {
1342 capturable_lifetimes: &mut FxHashSet::default(),
1344 self.lower_opaque_impl_trait(
1347 hir::OpaqueTyOrigin::TyAlias,
1349 Some(capturable_lifetimes),
1350 |this| this.lower_param_bounds(bounds, nested_itctx),
1353 ImplTraitContext::Universal(in_band_ty_params, parent_def_id) => {
1354 // Add a definition for the in-band `Param`.
1355 let def_id = self.resolver.local_def_id(def_node_id);
1357 let hir_bounds = self.lower_param_bounds(
1359 ImplTraitContext::Universal(in_band_ty_params, parent_def_id),
1361 // Set the name to `impl Bound1 + Bound2`.
1362 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1363 in_band_ty_params.push(hir::GenericParam {
1364 hir_id: self.lower_node_id(def_node_id),
1365 name: ParamName::Plain(self.lower_ident(ident)),
1366 pure_wrt_drop: false,
1368 span: self.lower_span(span),
1369 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
1372 hir::TyKind::Path(hir::QPath::Resolved(
1374 self.arena.alloc(hir::Path {
1375 span: self.lower_span(span),
1376 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1377 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
1381 ImplTraitContext::Disallowed(position) => {
1382 let mut err = struct_span_err!(
1386 "`impl Trait` only allowed in function and inherent method return types, not in {}",
1394 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1395 TyKind::CVarArgs => {
1396 self.sess.delay_span_bug(
1398 "`TyKind::CVarArgs` should have been handled elsewhere",
1404 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1407 fn lower_opaque_impl_trait(
1410 fn_def_id: Option<LocalDefId>,
1411 origin: hir::OpaqueTyOrigin,
1412 opaque_ty_node_id: NodeId,
1413 capturable_lifetimes: Option<&FxHashSet<hir::LifetimeName>>,
1414 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1415 ) -> hir::TyKind<'hir> {
1417 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1418 fn_def_id, opaque_ty_node_id, span,
1421 // Make sure we know that some funky desugaring has been going on here.
1422 // This is a first: there is code in other places like for loop
1423 // desugaring that explicitly states that we don't want to track that.
1424 // Not tracking it makes lints in rustc and clippy very fragile, as
1425 // frequently opened issues show.
1426 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1428 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1430 let mut collected_lifetimes = Vec::new();
1431 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1432 let hir_bounds = lower_bounds(lctx);
1434 collected_lifetimes = lifetimes_from_impl_trait_bounds(
1437 capturable_lifetimes,
1441 lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(|&(name, span)| {
1442 let def_node_id = lctx.resolver.next_node_id();
1443 lctx.resolver.create_def(
1446 DefPathData::LifetimeNs(name.ident().name),
1448 span.with_parent(None),
1450 let hir_id = lctx.lower_node_id(def_node_id);
1452 let (name, kind) = match name {
1453 hir::LifetimeName::Underscore => (
1454 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1455 hir::LifetimeParamKind::Elided,
1457 hir::LifetimeName::Param(param_name) => {
1458 (param_name, hir::LifetimeParamKind::Explicit)
1460 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1467 pure_wrt_drop: false,
1469 kind: hir::GenericParamKind::Lifetime { kind },
1473 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1475 let opaque_ty_item = hir::OpaqueTy {
1476 generics: hir::Generics {
1477 params: lifetime_defs,
1478 where_clause: hir::WhereClause { predicates: &[], span: lctx.lower_span(span) },
1479 span: lctx.lower_span(span),
1485 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1486 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1490 self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(name, span)| {
1491 hir::GenericArg::Lifetime(hir::Lifetime { hir_id: self.next_id(), span, name })
1494 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1496 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1497 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1500 /// Registers a new opaque type with the proper `NodeId`s and
1501 /// returns the lowered node-ID for the opaque type.
1502 fn generate_opaque_type(
1504 opaque_ty_id: LocalDefId,
1505 opaque_ty_item: hir::OpaqueTy<'hir>,
1507 opaque_ty_span: Span,
1508 ) -> hir::OwnerNode<'hir> {
1509 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1510 // Generate an `type Foo = impl Trait;` declaration.
1511 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1512 let opaque_ty_item = hir::Item {
1513 def_id: opaque_ty_id,
1514 ident: Ident::empty(),
1515 kind: opaque_ty_item_kind,
1516 vis: respan(self.lower_span(span.shrink_to_lo()), hir::VisibilityKind::Inherited),
1517 span: self.lower_span(opaque_ty_span),
1519 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1522 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1523 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1524 // as they are not explicit in HIR/Ty function signatures.
1525 // (instead, the `c_variadic` flag is set to `true`)
1526 let mut inputs = &decl.inputs[..];
1527 if decl.c_variadic() {
1528 inputs = &inputs[..inputs.len() - 1];
1530 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1531 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1532 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1536 // Lowers a function declaration.
1538 // `decl`: the unlowered (AST) function declaration.
1539 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1540 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1541 // `make_ret_async` is also `Some`.
1542 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1543 // This guards against trait declarations and implementations where `impl Trait` is
1545 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1546 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1547 // return type `impl Trait` item.
1551 mut in_band_ty_params: Option<(LocalDefId, &mut Vec<hir::GenericParam<'hir>>)>,
1553 make_ret_async: Option<NodeId>,
1554 ) -> &'hir hir::FnDecl<'hir> {
1558 in_band_ty_params: {:?}, \
1560 make_ret_async: {:?})",
1561 decl, in_band_ty_params, kind, make_ret_async,
1563 let lt_mode = if make_ret_async.is_some() {
1564 // In `async fn`, argument-position elided lifetimes
1565 // must be transformed into fresh generic parameters so that
1566 // they can be applied to the opaque `impl Trait` return type.
1567 AnonymousLifetimeMode::CreateParameter
1569 self.anonymous_lifetime_mode
1572 let c_variadic = decl.c_variadic();
1574 // Remember how many lifetimes were already around so that we can
1575 // only look at the lifetime parameters introduced by the arguments.
1576 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1577 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1578 // as they are not explicit in HIR/Ty function signatures.
1579 // (instead, the `c_variadic` flag is set to `true`)
1580 let mut inputs = &decl.inputs[..];
1582 inputs = &inputs[..inputs.len() - 1];
1584 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1585 if let Some((_, ibty)) = &mut in_band_ty_params {
1586 this.lower_ty_direct(
1588 ImplTraitContext::Universal(ibty, this.current_hir_id_owner),
1591 this.lower_ty_direct(
1593 ImplTraitContext::Disallowed(match kind {
1594 FnDeclKind::Fn | FnDeclKind::Inherent => {
1595 unreachable!("fn should allow in-band lifetimes")
1597 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1598 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1599 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1600 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1601 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1608 let output = if let Some(ret_id) = make_ret_async {
1609 self.lower_async_fn_ret_ty(
1611 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1616 FnRetTy::Ty(ref ty) => {
1617 let context = match in_band_ty_params {
1618 Some((def_id, _)) if kind.impl_trait_return_allowed() => {
1619 ImplTraitContext::ReturnPositionOpaqueTy {
1621 origin: hir::OpaqueTyOrigin::FnReturn(def_id),
1624 _ => ImplTraitContext::Disallowed(match kind {
1625 FnDeclKind::Fn | FnDeclKind::Inherent => {
1626 unreachable!("fn should allow in-band lifetimes")
1628 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1629 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1630 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1631 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1632 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1635 hir::FnRetTy::Return(self.lower_ty(ty, context))
1637 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1641 self.arena.alloc(hir::FnDecl {
1645 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1646 use BindingMode::{ByRef, ByValue};
1647 let is_mutable_pat = matches!(
1649 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1653 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1654 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1655 // Given we are only considering `ImplicitSelf` types, we needn't consider
1656 // the case where we have a mutable pattern to a reference as that would
1657 // no longer be an `ImplicitSelf`.
1658 TyKind::Rptr(_, ref mt)
1659 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1661 hir::ImplicitSelfKind::MutRef
1663 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1664 hir::ImplicitSelfKind::ImmRef
1666 _ => hir::ImplicitSelfKind::None,
1672 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1673 // combined with the following definition of `OpaqueTy`:
1675 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1677 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1678 // `output`: unlowered output type (`T` in `-> T`)
1679 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1680 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1681 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1682 fn lower_async_fn_ret_ty(
1685 fn_def_id: LocalDefId,
1686 opaque_ty_node_id: NodeId,
1687 ) -> hir::FnRetTy<'hir> {
1689 "lower_async_fn_ret_ty(\
1692 opaque_ty_node_id={:?})",
1693 output, fn_def_id, opaque_ty_node_id,
1696 let span = output.span();
1698 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1700 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1702 // When we create the opaque type for this async fn, it is going to have
1703 // to capture all the lifetimes involved in the signature (including in the
1704 // return type). This is done by introducing lifetime parameters for:
1706 // - all the explicitly declared lifetimes from the impl and function itself;
1707 // - all the elided lifetimes in the fn arguments;
1708 // - all the elided lifetimes in the return type.
1710 // So for example in this snippet:
1713 // impl<'a> Foo<'a> {
1714 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1715 // // ^ '0 ^ '1 ^ '2
1716 // // elided lifetimes used below
1721 // we would create an opaque type like:
1724 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1727 // and we would then desugar `bar` to the equivalent of:
1730 // impl<'a> Foo<'a> {
1731 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1735 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1736 // this is because the elided lifetimes from the return type
1737 // should be figured out using the ordinary elision rules, and
1738 // this desugaring achieves that.
1740 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", self.in_scope_lifetimes);
1741 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", self.lifetimes_to_define);
1743 // Calculate all the lifetimes that should be captured
1744 // by the opaque type. This should include all in-scope
1745 // lifetime parameters, including those defined in-band.
1747 // `lifetime_params` is a vector of tuple (span, parameter name, lifetime name).
1749 // Input lifetime like `'a` or `'1`:
1750 let mut lifetime_params: Vec<_> = self
1754 .map(|name| (name.ident().span, hir::LifetimeName::Param(name)))
1755 .chain(self.lifetimes_to_define.iter().map(|&(span, node_id)| {
1756 let def_id = self.resolver.local_def_id(node_id);
1757 let name = hir::ParamName::Fresh(def_id);
1758 (span, hir::LifetimeName::Param(name))
1762 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1763 let mut generic_params: Vec<_> = lifetime_params
1765 .map(|&(span, name)| {
1766 // We can only get lifetime names from the outside.
1767 let hir::LifetimeName::Param(hir_name) = name else { panic!() };
1769 let node_id = this.resolver.next_node_id();
1771 // Add a definition for the in-band lifetime def.
1772 let def_id = this.resolver.create_def(
1775 DefPathData::LifetimeNs(hir_name.ident().name),
1777 span.with_parent(None),
1780 let (kind, name) = match hir_name {
1781 ParamName::Plain(ident) => {
1782 (hir::LifetimeParamKind::Explicit, hir::ParamName::Plain(ident))
1784 ParamName::Fresh(_) => {
1785 (hir::LifetimeParamKind::Elided, hir::ParamName::Fresh(def_id))
1787 ParamName::Error => (hir::LifetimeParamKind::Error, hir::ParamName::Error),
1791 hir_id: this.lower_node_id(node_id),
1794 span: this.lower_span(span),
1795 pure_wrt_drop: false,
1796 kind: hir::GenericParamKind::Lifetime { kind },
1801 // We have to be careful to get elision right here. The
1802 // idea is that we create a lifetime parameter for each
1803 // lifetime in the return type. So, given a return type
1804 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1805 // Future<Output = &'1 [ &'2 u32 ]>`.
1807 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1808 // hence the elision takes place at the fn site.
1809 let (lifetimes_to_define, future_bound) =
1810 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
1811 this.collect_in_band_defs(opaque_ty_def_id, |this| {
1812 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1815 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1816 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", lifetimes_to_define);
1818 // Output lifetime like `'_`:
1819 for (span, node_id) in lifetimes_to_define {
1820 let param = this.fresh_lifetime_to_generic_param(span, node_id);
1821 lifetime_params.push((span, hir::LifetimeName::Implicit(false)));
1822 generic_params.push(param);
1824 let generic_params = this.arena.alloc_from_iter(generic_params);
1825 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
1826 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1828 let opaque_ty_item = hir::OpaqueTy {
1829 generics: hir::Generics {
1830 params: generic_params,
1831 where_clause: hir::WhereClause { predicates: &[], span: this.lower_span(span) },
1832 span: this.lower_span(span),
1834 bounds: arena_vec![this; future_bound],
1835 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1838 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1839 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1842 // As documented above on the variable
1843 // `input_lifetimes_count`, we need to create the lifetime
1844 // arguments to our opaque type. Continuing with our example,
1845 // we're creating the type arguments for the return type:
1848 // Bar<'a, 'b, '0, '1, '_>
1851 // For the "input" lifetime parameters, we wish to create
1852 // references to the parameters themselves, including the
1853 // "implicit" ones created from parameter types (`'a`, `'b`,
1856 // For the "output" lifetime parameters, we just want to
1859 self.arena.alloc_from_iter(lifetime_params.into_iter().map(|(span, name)| {
1860 GenericArg::Lifetime(hir::Lifetime {
1861 hir_id: self.next_id(),
1862 span: self.lower_span(span),
1867 // Create the `Foo<...>` reference itself. Note that the `type
1868 // Foo = impl Trait` is, internally, created as a child of the
1869 // async fn, so the *type parameters* are inherited. It's
1870 // only the lifetime parameters that we must supply.
1872 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1873 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1874 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1877 /// Transforms `-> T` into `Future<Output = T>`.
1878 fn lower_async_fn_output_type_to_future_bound(
1881 fn_def_id: LocalDefId,
1883 ) -> hir::GenericBound<'hir> {
1884 // Compute the `T` in `Future<Output = T>` from the return type.
1885 let output_ty = match output {
1886 FnRetTy::Ty(ty) => {
1887 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1888 // `impl Future` opaque type that `async fn` implicitly
1890 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1892 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1894 self.lower_ty(ty, context)
1896 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1900 let future_args = self.arena.alloc(hir::GenericArgs {
1902 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1903 parenthesized: false,
1907 hir::GenericBound::LangItemTrait(
1908 // ::std::future::Future<future_params>
1909 hir::LangItem::Future,
1910 self.lower_span(span),
1916 fn lower_param_bound(
1919 itctx: ImplTraitContext<'_, 'hir>,
1920 ) -> hir::GenericBound<'hir> {
1922 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1923 self.lower_poly_trait_ref(p, itctx),
1924 self.lower_trait_bound_modifier(*modifier),
1926 GenericBound::Outlives(lifetime) => {
1927 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1932 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1933 let span = self.lower_span(l.ident.span);
1935 ident if ident.name == kw::StaticLifetime => {
1936 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
1938 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
1939 AnonymousLifetimeMode::CreateParameter => {
1940 let fresh_name = self.collect_fresh_anonymous_lifetime(span);
1941 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
1944 AnonymousLifetimeMode::PassThrough => {
1945 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1948 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
1951 let param_name = ParamName::Plain(self.lower_ident(ident));
1952 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
1957 fn new_named_lifetime(
1961 name: hir::LifetimeName,
1962 ) -> hir::Lifetime {
1963 hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1966 fn lower_generic_params_mut<'s>(
1968 params: &'s [GenericParam],
1969 mut itctx: ImplTraitContext<'s, 'hir>,
1970 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1971 params.iter().map(move |param| self.lower_generic_param(param, itctx.reborrow()))
1974 fn lower_generic_params(
1976 params: &[GenericParam],
1977 itctx: ImplTraitContext<'_, 'hir>,
1978 ) -> &'hir [hir::GenericParam<'hir>] {
1979 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, itctx))
1982 fn lower_generic_param(
1984 param: &GenericParam,
1985 mut itctx: ImplTraitContext<'_, 'hir>,
1986 ) -> hir::GenericParam<'hir> {
1987 let bounds: Vec<_> = self
1988 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1989 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
1992 let (name, kind) = match param.kind {
1993 GenericParamKind::Lifetime => {
1994 let was_collecting_in_band = self.is_collecting_anonymous_lifetimes;
1995 self.is_collecting_anonymous_lifetimes = None;
1998 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1999 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2001 let param_name = match lt.name {
2002 hir::LifetimeName::Param(param_name) => param_name,
2003 hir::LifetimeName::Implicit(_)
2004 | hir::LifetimeName::Underscore
2005 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2006 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2007 self.sess.diagnostic().span_bug(
2009 "object-lifetime-default should not occur here",
2012 hir::LifetimeName::Error => ParamName::Error,
2016 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2018 self.is_collecting_anonymous_lifetimes = was_collecting_in_band;
2022 GenericParamKind::Type { ref default, .. } => {
2023 let kind = hir::GenericParamKind::Type {
2024 default: default.as_ref().map(|x| {
2025 self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2030 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2032 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2034 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2035 this.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2037 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2039 hir::ParamName::Plain(self.lower_ident(param.ident)),
2040 hir::GenericParamKind::Const { ty, default },
2044 let name = match name {
2045 hir::ParamName::Plain(ident) => hir::ParamName::Plain(self.lower_ident(ident)),
2049 let hir_id = self.lower_node_id(param.id);
2050 self.lower_attrs(hir_id, ¶m.attrs);
2054 span: self.lower_span(param.ident.span),
2055 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
2056 bounds: self.arena.alloc_from_iter(bounds),
2064 itctx: ImplTraitContext<'_, 'hir>,
2065 ) -> hir::TraitRef<'hir> {
2066 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2067 hir::QPath::Resolved(None, path) => path,
2068 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2070 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2073 fn lower_poly_trait_ref(
2076 mut itctx: ImplTraitContext<'_, 'hir>,
2077 ) -> hir::PolyTraitRef<'hir> {
2078 let bound_generic_params =
2079 self.lower_generic_params(&p.bound_generic_params, itctx.reborrow());
2081 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
2082 // Any impl Trait types defined within this scope can capture
2083 // lifetimes bound on this predicate.
2084 let lt_def_names = p.bound_generic_params.iter().filter_map(|param| match param.kind {
2085 GenericParamKind::Lifetime { .. } => Some(hir::LifetimeName::Param(
2086 ParamName::Plain(param.ident.normalize_to_macros_2_0()),
2090 if let ImplTraitContext::TypeAliasesOpaqueTy { ref mut capturable_lifetimes } = itctx {
2091 capturable_lifetimes.extend(lt_def_names.clone());
2094 let res = this.lower_trait_ref(&p.trait_ref, itctx.reborrow());
2096 if let ImplTraitContext::TypeAliasesOpaqueTy { ref mut capturable_lifetimes } = itctx {
2097 for param in lt_def_names {
2098 capturable_lifetimes.remove(¶m);
2104 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2107 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2108 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2111 fn lower_param_bounds(
2113 bounds: &[GenericBound],
2114 itctx: ImplTraitContext<'_, 'hir>,
2115 ) -> hir::GenericBounds<'hir> {
2116 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2119 fn lower_param_bounds_mut<'s>(
2121 bounds: &'s [GenericBound],
2122 mut itctx: ImplTraitContext<'s, 'hir>,
2123 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2124 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2127 /// Lowers a block directly to an expression, presuming that it
2128 /// has no attributes and is not targeted by a `break`.
2129 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2130 let block = self.lower_block(b, false);
2131 self.expr_block(block, AttrVec::new())
2134 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2135 match c.value.kind {
2136 ExprKind::Underscore => {
2137 if self.sess.features_untracked().generic_arg_infer {
2138 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2141 &self.sess.parse_sess,
2142 sym::generic_arg_infer,
2144 "using `_` for array lengths is unstable",
2147 hir::ArrayLen::Body(self.lower_anon_const(c))
2150 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2154 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2155 self.with_new_scopes(|this| hir::AnonConst {
2156 hir_id: this.lower_node_id(c.id),
2157 body: this.lower_const_body(c.value.span, Some(&c.value)),
2161 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2163 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2164 UserProvided => hir::UnsafeSource::UserProvided,
2168 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2170 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2171 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2173 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2174 // placeholder for compilation to proceed.
2175 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2176 hir::TraitBoundModifier::Maybe
2181 // Helper methods for building HIR.
2183 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2184 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2187 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2188 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2193 attrs: Option<&'hir [Attribute]>,
2195 init: Option<&'hir hir::Expr<'hir>>,
2196 pat: &'hir hir::Pat<'hir>,
2197 source: hir::LocalSource,
2198 ) -> hir::Stmt<'hir> {
2199 let hir_id = self.next_id();
2200 if let Some(a) = attrs {
2201 debug_assert!(!a.is_empty());
2202 self.attrs.insert(hir_id.local_id, a);
2204 let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2205 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2208 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2209 self.block_all(expr.span, &[], Some(expr))
2215 stmts: &'hir [hir::Stmt<'hir>],
2216 expr: Option<&'hir hir::Expr<'hir>>,
2217 ) -> &'hir hir::Block<'hir> {
2218 let blk = hir::Block {
2221 hir_id: self.next_id(),
2222 rules: hir::BlockCheckMode::DefaultBlock,
2223 span: self.lower_span(span),
2224 targeted_by_break: false,
2226 self.arena.alloc(blk)
2229 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2230 let field = self.single_pat_field(span, pat);
2231 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2234 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2235 let field = self.single_pat_field(span, pat);
2236 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2239 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2240 let field = self.single_pat_field(span, pat);
2241 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2244 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2245 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2248 fn single_pat_field(
2251 pat: &'hir hir::Pat<'hir>,
2252 ) -> &'hir [hir::PatField<'hir>] {
2253 let field = hir::PatField {
2254 hir_id: self.next_id(),
2255 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2256 is_shorthand: false,
2258 span: self.lower_span(span),
2260 arena_vec![self; field]
2263 fn pat_lang_item_variant(
2266 lang_item: hir::LangItem,
2267 fields: &'hir [hir::PatField<'hir>],
2268 hir_id: Option<hir::HirId>,
2269 ) -> &'hir hir::Pat<'hir> {
2270 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2271 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2274 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2275 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2278 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2279 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2282 fn pat_ident_binding_mode(
2286 bm: hir::BindingAnnotation,
2287 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2288 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2289 (self.arena.alloc(pat), hir_id)
2292 fn pat_ident_binding_mode_mut(
2296 bm: hir::BindingAnnotation,
2297 ) -> (hir::Pat<'hir>, hir::HirId) {
2298 let hir_id = self.next_id();
2303 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2304 span: self.lower_span(span),
2305 default_binding_modes: true,
2311 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2312 self.arena.alloc(hir::Pat {
2313 hir_id: self.next_id(),
2315 span: self.lower_span(span),
2316 default_binding_modes: true,
2320 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2322 hir_id: self.next_id(),
2324 span: self.lower_span(span),
2325 default_binding_modes: false,
2331 mut hir_id: hir::HirId,
2333 qpath: hir::QPath<'hir>,
2334 ) -> hir::Ty<'hir> {
2335 let kind = match qpath {
2336 hir::QPath::Resolved(None, path) => {
2337 // Turn trait object paths into `TyKind::TraitObject` instead.
2339 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2340 let principal = hir::PolyTraitRef {
2341 bound_generic_params: &[],
2342 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2343 span: self.lower_span(span),
2346 // The original ID is taken by the `PolyTraitRef`,
2347 // so the `Ty` itself needs a different one.
2348 hir_id = self.next_id();
2349 hir::TyKind::TraitObject(
2350 arena_vec![self; principal],
2351 self.elided_dyn_bound(span),
2352 TraitObjectSyntax::None,
2355 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2358 _ => hir::TyKind::Path(qpath),
2361 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2364 /// Invoked to create the lifetime argument for a type `&T`
2365 /// with no explicit lifetime.
2366 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2367 match self.anonymous_lifetime_mode {
2368 // Intercept when we are in an impl header or async fn and introduce an in-band
2370 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2372 AnonymousLifetimeMode::CreateParameter => {
2373 let fresh_name = self.collect_fresh_anonymous_lifetime(span);
2375 hir_id: self.next_id(),
2376 span: self.lower_span(span),
2377 name: hir::LifetimeName::Param(fresh_name),
2381 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2383 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span, false),
2387 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2388 /// return an "error lifetime".
2389 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2390 let (id, msg, label) = match id {
2391 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2394 self.resolver.next_node_id(),
2395 "`&` without an explicit lifetime name cannot be used here",
2396 "explicit lifetime name needed here",
2400 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2401 err.span_label(span, label);
2404 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2407 /// Invoked to create the lifetime argument(s) for a path like
2408 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2409 /// sorts of cases are deprecated. This may therefore report a warning or an
2410 /// error, depending on the mode.
2411 fn elided_path_lifetimes<'s>(
2415 param_mode: ParamMode,
2416 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2417 (0..count).map(move |_| self.elided_path_lifetime(span, param_mode))
2420 fn elided_path_lifetime(&mut self, span: Span, param_mode: ParamMode) -> hir::Lifetime {
2421 match self.anonymous_lifetime_mode {
2422 AnonymousLifetimeMode::CreateParameter => {
2423 // We should have emitted E0726 when processing this path above
2425 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2426 let id = self.resolver.next_node_id();
2427 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2429 // `PassThrough` is the normal case.
2430 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2431 // is unsuitable here, as these can occur from missing lifetime parameters in a
2432 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2433 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2434 // later, at which point a suitable error will be emitted.
2435 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2436 self.new_implicit_lifetime(span, param_mode == ParamMode::Explicit)
2441 /// Invoked to create the lifetime argument(s) for an elided trait object
2442 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2443 /// when the bound is written, even if it is written with `'_` like in
2444 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2445 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2446 match self.anonymous_lifetime_mode {
2447 // NB. We intentionally ignore the create-parameter mode here.
2448 // and instead "pass through" to resolve-lifetimes, which will apply
2449 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2450 // do not act like other elided lifetimes. In other words, given this:
2452 // impl Foo for Box<dyn Debug>
2454 // we do not introduce a fresh `'_` to serve as the bound, but instead
2455 // ultimately translate to the equivalent of:
2457 // impl Foo for Box<dyn Debug + 'static>
2459 // `resolve_lifetime` has the code to make that happen.
2460 AnonymousLifetimeMode::CreateParameter => {}
2462 AnonymousLifetimeMode::ReportError => {
2463 // ReportError applies to explicit use of `'_`.
2466 // This is the normal case.
2467 AnonymousLifetimeMode::PassThrough => {}
2470 let r = hir::Lifetime {
2471 hir_id: self.next_id(),
2472 span: self.lower_span(span),
2473 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2475 debug!("elided_dyn_bound: r={:?}", r);
2479 fn new_implicit_lifetime(&mut self, span: Span, missing: bool) -> hir::Lifetime {
2481 hir_id: self.next_id(),
2482 span: self.lower_span(span),
2483 name: hir::LifetimeName::Implicit(missing),
2488 /// Helper struct for delayed construction of GenericArgs.
2489 struct GenericArgsCtor<'hir> {
2490 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2491 bindings: &'hir [hir::TypeBinding<'hir>],
2492 parenthesized: bool,
2496 impl<'hir> GenericArgsCtor<'hir> {
2497 fn is_empty(&self) -> bool {
2498 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2501 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2502 let ga = hir::GenericArgs {
2503 args: this.arena.alloc_from_iter(self.args),
2504 bindings: self.bindings,
2505 parenthesized: self.parenthesized,
2506 span_ext: this.lower_span(self.span),
2508 this.arena.alloc(ga)
2512 #[tracing::instrument(level = "debug")]
2513 fn lifetimes_from_impl_trait_bounds(
2514 opaque_ty_id: NodeId,
2515 bounds: hir::GenericBounds<'_>,
2516 lifetimes_to_include: Option<&FxHashSet<hir::LifetimeName>>,
2517 ) -> Vec<(hir::LifetimeName, Span)> {
2518 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
2519 // appear in the bounds, excluding lifetimes that are created within the bounds.
2520 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
2521 struct ImplTraitLifetimeCollector<'r> {
2522 collect_elided_lifetimes: bool,
2523 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2524 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
2525 lifetimes: Vec<(hir::LifetimeName, Span)>,
2526 lifetimes_to_include: Option<&'r FxHashSet<hir::LifetimeName>>,
2529 impl<'r, 'v> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r> {
2530 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
2531 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2532 if parameters.parenthesized {
2533 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2534 self.collect_elided_lifetimes = false;
2535 intravisit::walk_generic_args(self, span, parameters);
2536 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2538 intravisit::walk_generic_args(self, span, parameters);
2542 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
2543 // Don't collect elided lifetimes used inside of `fn()` syntax.
2544 if let hir::TyKind::BareFn(_) = t.kind {
2545 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2546 self.collect_elided_lifetimes = false;
2548 // Record the "stack height" of `for<'a>` lifetime bindings
2549 // to be able to later fully undo their introduction.
2550 let old_len = self.currently_bound_lifetimes.len();
2551 intravisit::walk_ty(self, t);
2552 self.currently_bound_lifetimes.truncate(old_len);
2554 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2556 intravisit::walk_ty(self, t)
2560 fn visit_poly_trait_ref(
2562 trait_ref: &'v hir::PolyTraitRef<'v>,
2563 modifier: hir::TraitBoundModifier,
2565 // Record the "stack height" of `for<'a>` lifetime bindings
2566 // to be able to later fully undo their introduction.
2567 let old_len = self.currently_bound_lifetimes.len();
2568 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2569 self.currently_bound_lifetimes.truncate(old_len);
2572 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
2573 // Record the introduction of 'a in `for<'a> ...`.
2574 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2575 // Introduce lifetimes one at a time so that we can handle
2576 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
2577 let lt_name = hir::LifetimeName::Param(param.name);
2578 self.currently_bound_lifetimes.push(lt_name);
2581 intravisit::walk_generic_param(self, param);
2584 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2585 let name = match lifetime.name {
2586 hir::LifetimeName::Implicit(_) | hir::LifetimeName::Underscore => {
2587 if self.collect_elided_lifetimes {
2588 // Use `'_` for both implicit and underscore lifetimes in
2589 // `type Foo<'_> = impl SomeTrait<'_>;`.
2590 hir::LifetimeName::Underscore
2595 hir::LifetimeName::Param(_) => lifetime.name,
2597 // Refers to some other lifetime that is "in
2598 // scope" within the type.
2599 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
2601 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2604 if !self.currently_bound_lifetimes.contains(&name)
2605 && !self.already_defined_lifetimes.contains(&name)
2606 && self.lifetimes_to_include.map_or(true, |lifetimes| lifetimes.contains(&name))
2608 self.already_defined_lifetimes.insert(name);
2610 self.lifetimes.push((name, lifetime.span));
2615 let mut lifetime_collector = ImplTraitLifetimeCollector {
2616 collect_elided_lifetimes: true,
2617 currently_bound_lifetimes: Vec::new(),
2618 already_defined_lifetimes: FxHashSet::default(),
2619 lifetimes: Vec::new(),
2620 lifetimes_to_include,
2623 for bound in bounds {
2624 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
2627 lifetime_collector.lifetimes