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(box_patterns)]
34 #![feature(let_chains)]
35 #![feature(never_type)]
36 #![recursion_limit = "256"]
37 #![deny(rustc::untranslatable_diagnostic)]
38 #![deny(rustc::diagnostic_outside_of_impl)]
43 use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait, TraitFnAsync};
45 use rustc_ast::ptr::P;
47 use rustc_ast::{self as ast, *};
48 use rustc_ast_pretty::pprust;
49 use rustc_data_structures::captures::Captures;
50 use rustc_data_structures::fingerprint::Fingerprint;
51 use rustc_data_structures::fx::FxHashMap;
52 use rustc_data_structures::sorted_map::SortedMap;
53 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
54 use rustc_data_structures::sync::Lrc;
55 use rustc_errors::{DiagnosticArgFromDisplay, Handler, StashKey};
57 use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
58 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
59 use rustc_hir::definitions::DefPathData;
60 use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate};
61 use rustc_index::vec::{Idx, IndexVec};
62 use rustc_middle::span_bug;
63 use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
64 use rustc_session::parse::feature_err;
65 use rustc_span::hygiene::MacroKind;
66 use rustc_span::source_map::DesugaringKind;
67 use rustc_span::symbol::{kw, sym, Ident, Symbol};
68 use rustc_span::{Span, DUMMY_SP};
70 use smallvec::SmallVec;
71 use std::collections::hash_map::Entry;
73 macro_rules! arena_vec {
74 ($this:expr; $($x:expr),*) => (
75 $this.arena.alloc_from_iter([$($x),*])
85 mod lifetime_collector;
89 struct LoweringContext<'a, 'hir> {
91 resolver: &'a mut ResolverAstLowering,
93 /// Used to allocate HIR nodes.
94 arena: &'hir hir::Arena<'hir>,
96 /// Bodies inside the owner being lowered.
97 bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
98 /// Attributes inside the owner being lowered.
99 attrs: SortedMap<hir::ItemLocalId, &'hir [Attribute]>,
100 /// Collect items that were created by lowering the current owner.
101 children: Vec<(LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>)>,
103 generator_kind: Option<hir::GeneratorKind>,
105 /// When inside an `async` context, this is the `HirId` of the
106 /// `task_context` local bound to the resume argument of the generator.
107 task_context: Option<hir::HirId>,
109 /// Used to get the current `fn`'s def span to point to when using `await`
110 /// outside of an `async fn`.
111 current_item: Option<Span>,
113 catch_scope: Option<NodeId>,
114 loop_scope: Option<NodeId>,
115 is_in_loop_condition: bool,
116 is_in_trait_impl: bool,
117 is_in_dyn_type: bool,
119 current_hir_id_owner: hir::OwnerId,
120 item_local_id_counter: hir::ItemLocalId,
121 local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
122 trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
124 impl_trait_defs: Vec<hir::GenericParam<'hir>>,
125 impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
127 /// NodeIds that are lowered inside the current HIR owner.
128 node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
130 allow_try_trait: Option<Lrc<[Symbol]>>,
131 allow_gen_future: Option<Lrc<[Symbol]>>,
132 allow_into_future: Option<Lrc<[Symbol]>>,
134 /// Mapping from generics `def_id`s to TAIT generics `def_id`s.
135 /// For each captured lifetime (e.g., 'a), we create a new lifetime parameter that is a generic
136 /// defined on the TAIT, so we have type Foo<'a1> = ... and we establish a mapping in this
137 /// field from the original parameter 'a to the new parameter 'a1.
138 generics_def_id_map: Vec<FxHashMap<LocalDefId, LocalDefId>>,
141 trait ResolverAstLoweringExt {
142 fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>>;
143 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
144 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
145 // Clones the resolution (if any) on 'source' and applies it
146 // to 'target'. Used when desugaring a `UseTreeKind::Nested` to
147 // multiple `UseTreeKind::Simple`s
148 fn clone_res(&mut self, source: NodeId, target: NodeId);
149 fn get_label_res(&self, id: NodeId) -> Option<NodeId>;
150 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
151 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>;
152 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
155 impl ResolverAstLoweringExt for ResolverAstLowering {
156 fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>> {
157 if let ExprKind::Path(None, path) = &expr.kind {
158 // Don't perform legacy const generics rewriting if the path already
159 // has generic arguments.
160 if path.segments.last().unwrap().args.is_some() {
164 if let Res::Def(DefKind::Fn, def_id) = self.partial_res_map.get(&expr.id)?.full_res()? {
165 // We only support cross-crate argument rewriting. Uses
166 // within the same crate should be updated to use the new
167 // const generics style.
168 if def_id.is_local() {
172 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
181 fn clone_res(&mut self, source: NodeId, target: NodeId) {
182 if let Some(res) = self.partial_res_map.get(&source) {
183 self.partial_res_map.insert(target, *res);
187 /// Obtains resolution for a `NodeId` with a single resolution.
188 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
189 self.partial_res_map.get(&id).copied()
192 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
193 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
194 self.import_res_map.get(&id).copied().unwrap_or_default()
197 /// Obtains resolution for a label with the given `NodeId`.
198 fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
199 self.label_res_map.get(&id).copied()
202 /// Obtains resolution for a lifetime with the given `NodeId`.
203 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
204 self.lifetimes_res_map.get(&id).copied()
207 /// Obtain the list of lifetimes parameters to add to an item.
209 /// Extra lifetime parameters should only be added in places that can appear
210 /// as a `binder` in `LifetimeRes`.
212 /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
213 /// should appear at the enclosing `PolyTraitRef`.
214 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
215 self.extra_lifetime_params_map.remove(&id).unwrap_or_default()
218 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind {
219 self.builtin_macro_kinds.get(&def_id).copied().unwrap_or(MacroKind::Bang)
223 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
224 /// and if so, what meaning it has.
225 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
226 enum ImplTraitContext {
227 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
228 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
229 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
231 /// Newly generated parameters should be inserted into the given `Vec`.
234 /// Treat `impl Trait` as shorthand for a new opaque type.
235 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
236 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
238 ReturnPositionOpaqueTy {
239 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
240 origin: hir::OpaqueTyOrigin,
243 /// Impl trait in type aliases.
245 /// `impl Trait` is unstably accepted in this position.
246 FeatureGated(ImplTraitPosition, Symbol),
247 /// `impl Trait` is not accepted in this position.
248 Disallowed(ImplTraitPosition),
251 /// Position in which `impl Trait` is disallowed.
252 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
253 enum ImplTraitPosition {
275 impl std::fmt::Display for ImplTraitPosition {
276 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
277 let name = match self {
278 ImplTraitPosition::Path => "path",
279 ImplTraitPosition::Variable => "variable binding",
280 ImplTraitPosition::Type => "type",
281 ImplTraitPosition::Trait => "trait",
282 ImplTraitPosition::AsyncBlock => "async block",
283 ImplTraitPosition::Bound => "bound",
284 ImplTraitPosition::Generic => "generic",
285 ImplTraitPosition::ExternFnParam => "`extern fn` param",
286 ImplTraitPosition::ClosureParam => "closure param",
287 ImplTraitPosition::PointerParam => "`fn` pointer param",
288 ImplTraitPosition::FnTraitParam => "`Fn` trait param",
289 ImplTraitPosition::TraitParam => "trait method param",
290 ImplTraitPosition::ImplParam => "`impl` method param",
291 ImplTraitPosition::ExternFnReturn => "`extern fn` return",
292 ImplTraitPosition::ClosureReturn => "closure return",
293 ImplTraitPosition::PointerReturn => "`fn` pointer return",
294 ImplTraitPosition::FnTraitReturn => "`Fn` trait return",
295 ImplTraitPosition::TraitReturn => "trait method return",
296 ImplTraitPosition::ImplReturn => "`impl` method return",
303 #[derive(Debug, PartialEq, Eq)]
315 fn param_impl_trait_allowed(&self) -> bool {
317 FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => true,
322 fn return_impl_trait_allowed(&self, tcx: TyCtxt<'_>) -> bool {
324 FnDeclKind::Fn | FnDeclKind::Inherent => true,
325 FnDeclKind::Impl if tcx.features().return_position_impl_trait_in_trait => true,
326 FnDeclKind::Trait if tcx.features().return_position_impl_trait_in_trait => true,
331 fn async_fn_allowed(&self, tcx: TyCtxt<'_>) -> bool {
333 FnDeclKind::Fn | FnDeclKind::Inherent => true,
334 FnDeclKind::Impl if tcx.features().async_fn_in_trait => true,
335 FnDeclKind::Trait if tcx.features().async_fn_in_trait => true,
341 #[derive(Copy, Clone)]
344 Crate(&'a ast::Crate),
346 AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
347 ForeignItem(&'a ast::ForeignItem),
351 node_id_to_def_id: &FxHashMap<NodeId, LocalDefId>,
353 ) -> IndexVec<LocalDefId, AstOwner<'a>> {
354 let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() };
355 indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner);
356 indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate);
357 visit::walk_crate(&mut indexer, krate);
358 return indexer.index;
360 struct Indexer<'s, 'a> {
361 node_id_to_def_id: &'s FxHashMap<NodeId, LocalDefId>,
362 index: IndexVec<LocalDefId, AstOwner<'a>>,
365 impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
366 fn visit_attribute(&mut self, _: &'a Attribute) {
367 // We do not want to lower expressions that appear in attributes,
368 // as they are not accessible to the rest of the HIR.
371 fn visit_item(&mut self, item: &'a ast::Item) {
372 let def_id = self.node_id_to_def_id[&item.id];
373 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
374 self.index[def_id] = AstOwner::Item(item);
375 visit::walk_item(self, item)
378 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
379 let def_id = self.node_id_to_def_id[&item.id];
380 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
381 self.index[def_id] = AstOwner::AssocItem(item, ctxt);
382 visit::walk_assoc_item(self, item, ctxt);
385 fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
386 let def_id = self.node_id_to_def_id[&item.id];
387 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
388 self.index[def_id] = AstOwner::ForeignItem(item);
389 visit::walk_foreign_item(self, item);
394 /// Compute the hash for the HIR of the full crate.
395 /// This hash will then be part of the crate_hash which is stored in the metadata.
398 owners: &IndexVec<LocalDefId, hir::MaybeOwner<&hir::OwnerInfo<'_>>>,
400 let mut hir_body_nodes: Vec<_> = owners
402 .filter_map(|(def_id, info)| {
403 let info = info.as_owner()?;
404 let def_path_hash = tcx.hir().def_path_hash(def_id);
405 Some((def_path_hash, info))
408 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
410 tcx.with_stable_hashing_context(|mut hcx| {
411 let mut stable_hasher = StableHasher::new();
412 hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
413 stable_hasher.finish()
417 pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> {
419 let (mut resolver, krate) = tcx.resolver_for_lowering(()).steal();
421 let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
422 let mut owners = IndexVec::from_fn_n(
423 |_| hir::MaybeOwner::Phantom,
424 tcx.definitions_untracked().def_index_count(),
427 for def_id in ast_index.indices() {
430 resolver: &mut resolver,
431 ast_index: &ast_index,
437 // Drop AST to free memory
439 sess.time("drop_ast", || drop(krate));
441 // Discard hygiene data, which isn't required after lowering to HIR.
442 if !sess.opts.unstable_opts.keep_hygiene_data {
443 rustc_span::hygiene::clear_syntax_context_map();
446 let hir_hash = compute_hir_hash(tcx, &owners);
447 hir::Crate { owners, hir_hash }
450 #[derive(Copy, Clone, PartialEq, Debug)]
452 /// Any path in a type context.
454 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
456 /// The `module::Type` in `module::Type::method` in an expression.
460 enum ParenthesizedGenericArgs {
465 impl<'a, 'hir> LoweringContext<'a, 'hir> {
469 node_id: ast::NodeId,
473 debug_assert_ne!(node_id, ast::DUMMY_NODE_ID);
475 self.opt_local_def_id(node_id).is_none(),
476 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
479 self.tcx.hir().def_key(self.local_def_id(node_id)),
482 let def_id = self.tcx.at(span).create_def(parent, data).def_id();
484 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
485 self.resolver.node_id_to_def_id.insert(node_id, def_id);
490 fn next_node_id(&mut self) -> NodeId {
491 let start = self.resolver.next_node_id;
492 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
493 self.resolver.next_node_id = ast::NodeId::from_u32(next);
497 /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
498 /// resolver (if any).
499 fn orig_opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
500 self.resolver.node_id_to_def_id.get(&node).map(|local_def_id| *local_def_id)
503 fn orig_local_def_id(&self, node: NodeId) -> LocalDefId {
504 self.orig_opt_local_def_id(node)
505 .unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
508 /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
509 /// resolver (if any), after applying any remapping from `get_remapped_def_id`.
511 /// For example, in a function like `fn foo<'a>(x: &'a u32)`,
512 /// invoking with the id from the `ast::Lifetime` node found inside
513 /// the `&'a u32` type would return the `LocalDefId` of the
514 /// `'a` parameter declared on `foo`.
516 /// This function also applies remapping from `get_remapped_def_id`.
517 /// These are used when synthesizing opaque types from `-> impl Trait` return types and so forth.
518 /// For example, in a function like `fn foo<'a>() -> impl Debug + 'a`,
519 /// we would create an opaque type `type FooReturn<'a1> = impl Debug + 'a1`.
520 /// When lowering the `Debug + 'a` bounds, we add a remapping to map `'a` to `'a1`.
521 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
522 self.orig_opt_local_def_id(node).map(|local_def_id| self.get_remapped_def_id(local_def_id))
525 fn local_def_id(&self, node: NodeId) -> LocalDefId {
526 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
529 /// Get the previously recorded `to` local def id given the `from` local def id, obtained using
530 /// `generics_def_id_map` field.
531 fn get_remapped_def_id(&self, local_def_id: LocalDefId) -> LocalDefId {
532 // `generics_def_id_map` is a stack of mappings. As we go deeper in impl traits nesting we
533 // push new mappings, so we first need to get the latest (innermost) mappings, hence `iter().rev()`.
537 // `fn test<'a, 'b>() -> impl Trait<&'a u8, Ty = impl Sized + 'b> {}`
539 // We would end with a generics_def_id_map like:
541 // `[[fn#'b -> impl_trait#'b], [fn#'b -> impl_sized#'b]]`
543 // for the opaque type generated on `impl Sized + 'b`, we want the result to be: impl_sized#'b.
544 // So, if we were trying to find first from the start (outermost) would give the wrong result, impl_trait#'b.
545 self.generics_def_id_map
548 .find_map(|map| map.get(&local_def_id).map(|local_def_id| *local_def_id))
549 .unwrap_or(local_def_id)
552 /// Freshen the `LoweringContext` and ready it to lower a nested item.
553 /// The lowered item is registered into `self.children`.
555 /// This function sets up `HirId` lowering infrastructure,
556 /// and stashes the shared mutable state to avoid pollution by the closure.
557 #[instrument(level = "debug", skip(self, f))]
558 fn with_hir_id_owner(
561 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
563 let def_id = self.local_def_id(owner);
565 let current_attrs = std::mem::take(&mut self.attrs);
566 let current_bodies = std::mem::take(&mut self.bodies);
567 let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
568 let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
569 let current_trait_map = std::mem::take(&mut self.trait_map);
571 std::mem::replace(&mut self.current_hir_id_owner, hir::OwnerId { def_id });
572 let current_local_counter =
573 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
574 let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
575 let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
577 // Do not reset `next_node_id` and `node_id_to_def_id`:
578 // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
579 // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
581 // Always allocate the first `HirId` for the owner itself.
582 let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
583 debug_assert_eq!(_old, None);
586 debug_assert_eq!(def_id, item.def_id().def_id);
587 // `f` should have consumed all the elements in these vectors when constructing `item`.
588 debug_assert!(self.impl_trait_defs.is_empty());
589 debug_assert!(self.impl_trait_bounds.is_empty());
590 let info = self.make_owner_info(item);
592 self.attrs = current_attrs;
593 self.bodies = current_bodies;
594 self.node_id_to_local_id = current_node_ids;
595 self.local_id_to_def_id = current_id_to_def_id;
596 self.trait_map = current_trait_map;
597 self.current_hir_id_owner = current_owner;
598 self.item_local_id_counter = current_local_counter;
599 self.impl_trait_defs = current_impl_trait_defs;
600 self.impl_trait_bounds = current_impl_trait_bounds;
602 debug_assert!(!self.children.iter().any(|(id, _)| id == &def_id));
603 self.children.push((def_id, hir::MaybeOwner::Owner(info)));
606 /// Installs the remapping `remap` in scope while `f` is being executed.
607 /// This causes references to the `LocalDefId` keys to be changed to
608 /// refer to the values instead.
610 /// The remapping is used when one piece of AST expands to multiple
611 /// pieces of HIR. For example, the function `fn foo<'a>(...) -> impl Debug + 'a`,
612 /// expands to both a function definition (`foo`) and a TAIT for the return value,
613 /// both of which have a lifetime parameter `'a`. The remapping allows us to
614 /// rewrite the `'a` in the return value to refer to the
615 /// `'a` declared on the TAIT, instead of the function.
616 fn with_remapping<R>(
618 remap: FxHashMap<LocalDefId, LocalDefId>,
619 f: impl FnOnce(&mut Self) -> R,
621 self.generics_def_id_map.push(remap);
623 self.generics_def_id_map.pop();
627 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
628 let attrs = std::mem::take(&mut self.attrs);
629 let mut bodies = std::mem::take(&mut self.bodies);
630 let local_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
631 let trait_map = std::mem::take(&mut self.trait_map);
633 #[cfg(debug_assertions)]
634 for (id, attrs) in attrs.iter() {
635 // Verify that we do not store empty slices in the map.
636 if attrs.is_empty() {
637 panic!("Stored empty attributes for {:?}", id);
641 bodies.sort_by_key(|(k, _)| *k);
642 let bodies = SortedMap::from_presorted_elements(bodies);
643 let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
644 let (nodes, parenting) =
645 index::index_hir(self.tcx.sess, &*self.tcx.definitions_untracked(), node, &bodies);
646 let nodes = hir::OwnerNodes {
647 hash_including_bodies,
654 let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
655 let mut stable_hasher = StableHasher::new();
656 attrs.hash_stable(&mut hcx, &mut stable_hasher);
657 stable_hasher.finish()
659 hir::AttributeMap { map: attrs, hash }
662 self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map })
665 /// Hash the HIR node twice, one deep and one shallow hash. This allows to differentiate
666 /// queries which depend on the full HIR tree and those which only depend on the item signature.
669 node: hir::OwnerNode<'hir>,
670 bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
671 ) -> (Fingerprint, Fingerprint) {
672 self.tcx.with_stable_hashing_context(|mut hcx| {
673 let mut stable_hasher = StableHasher::new();
674 hcx.with_hir_bodies(node.def_id(), bodies, |hcx| {
675 node.hash_stable(hcx, &mut stable_hasher)
677 let hash_including_bodies = stable_hasher.finish();
678 let mut stable_hasher = StableHasher::new();
679 hcx.without_hir_bodies(|hcx| node.hash_stable(hcx, &mut stable_hasher));
680 let hash_without_bodies = stable_hasher.finish();
681 (hash_including_bodies, hash_without_bodies)
685 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
686 /// the `LoweringContext`'s `NodeId => HirId` map.
687 /// Take care not to call this method if the resulting `HirId` is then not
688 /// actually used in the HIR, as that would trigger an assertion in the
689 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
690 /// properly. Calling the method twice with the same `NodeId` is fine though.
691 #[instrument(level = "debug", skip(self), ret)]
692 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
693 assert_ne!(ast_node_id, DUMMY_NODE_ID);
695 match self.node_id_to_local_id.entry(ast_node_id) {
696 Entry::Occupied(o) => {
697 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
699 Entry::Vacant(v) => {
700 // Generate a new `HirId`.
701 let owner = self.current_hir_id_owner;
702 let local_id = self.item_local_id_counter;
703 let hir_id = hir::HirId { owner, local_id };
706 self.item_local_id_counter.increment_by(1);
708 assert_ne!(local_id, hir::ItemLocalId::new(0));
709 if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
710 self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
711 self.local_id_to_def_id.insert(local_id, def_id);
714 if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
715 self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
723 /// Generate a new `HirId` without a backing `NodeId`.
724 #[instrument(level = "debug", skip(self), ret)]
725 fn next_id(&mut self) -> hir::HirId {
726 let owner = self.current_hir_id_owner;
727 let local_id = self.item_local_id_counter;
728 assert_ne!(local_id, hir::ItemLocalId::new(0));
729 self.item_local_id_counter.increment_by(1);
730 hir::HirId { owner, local_id }
733 #[instrument(level = "trace", skip(self))]
734 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
735 let res: Result<Res, ()> = res.apply_id(|id| {
736 let owner = self.current_hir_id_owner;
737 let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
738 Ok(hir::HirId { owner, local_id })
742 // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
743 // This can happen when trying to lower the return type `x` in erroneous code like
744 // async fn foo(x: u8) -> x {}
745 // In that case, `x` is lowered as a function parameter, and the return type is lowered as
746 // an opaque type as a synthesized HIR owner.
747 res.unwrap_or(Res::Err)
750 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
751 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
754 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
755 self.resolver.get_import_res(id).present_items()
758 fn diagnostic(&self) -> &Handler {
759 self.tcx.sess.diagnostic()
762 /// Reuses the span but adds information like the kind of the desugaring and features that are
763 /// allowed inside this span.
764 fn mark_span_with_reason(
766 reason: DesugaringKind,
768 allow_internal_unstable: Option<Lrc<[Symbol]>>,
770 self.tcx.with_stable_hashing_context(|hcx| {
771 span.mark_with_reason(allow_internal_unstable, reason, self.tcx.sess.edition(), hcx)
775 /// Intercept all spans entering HIR.
776 /// Mark a span as relative to the current owning item.
777 fn lower_span(&self, span: Span) -> Span {
778 if self.tcx.sess.opts.incremental_relative_spans() {
779 span.with_parent(Some(self.current_hir_id_owner.def_id))
781 // Do not make spans relative when not using incremental compilation.
786 fn lower_ident(&self, ident: Ident) -> Ident {
787 Ident::new(ident.name, self.lower_span(ident.span))
790 /// Converts a lifetime into a new generic parameter.
791 #[instrument(level = "debug", skip(self))]
792 fn lifetime_res_to_generic_param(
797 ) -> Option<hir::GenericParam<'hir>> {
798 let (name, kind) = match res {
799 LifetimeRes::Param { .. } => {
800 (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
802 LifetimeRes::Fresh { param, .. } => {
803 // Late resolution delegates to us the creation of the `LocalDefId`.
804 let _def_id = self.create_def(
805 self.current_hir_id_owner.def_id,
807 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
812 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
814 LifetimeRes::Static | LifetimeRes::Error => return None,
816 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
817 res, ident, ident.span
820 let hir_id = self.lower_node_id(node_id);
821 let def_id = self.local_def_id(node_id);
822 Some(hir::GenericParam {
826 span: self.lower_span(ident.span),
827 pure_wrt_drop: false,
828 kind: hir::GenericParamKind::Lifetime { kind },
833 /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
834 /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
835 /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
836 /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
837 /// parameters will be successful.
838 #[instrument(level = "debug", skip(self))]
840 fn lower_lifetime_binder(
843 generic_params: &[GenericParam],
844 ) -> &'hir [hir::GenericParam<'hir>] {
845 let mut generic_params: Vec<_> = self.lower_generic_params_mut(generic_params).collect();
846 let extra_lifetimes = self.resolver.take_extra_lifetime_params(binder);
847 debug!(?extra_lifetimes);
848 generic_params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
849 self.lifetime_res_to_generic_param(ident, node_id, res)
851 let generic_params = self.arena.alloc_from_iter(generic_params);
852 debug!(?generic_params);
857 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
858 let was_in_dyn_type = self.is_in_dyn_type;
859 self.is_in_dyn_type = in_scope;
861 let result = f(self);
863 self.is_in_dyn_type = was_in_dyn_type;
868 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
869 let was_in_loop_condition = self.is_in_loop_condition;
870 self.is_in_loop_condition = false;
872 let catch_scope = self.catch_scope.take();
873 let loop_scope = self.loop_scope.take();
875 self.catch_scope = catch_scope;
876 self.loop_scope = loop_scope;
878 self.is_in_loop_condition = was_in_loop_condition;
883 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
884 if attrs.is_empty() {
887 debug_assert_eq!(id.owner, self.current_hir_id_owner);
888 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
889 debug_assert!(!ret.is_empty());
890 self.attrs.insert(id.local_id, ret);
895 fn lower_attr(&self, attr: &Attribute) -> Attribute {
896 // Note that we explicitly do not walk the path. Since we don't really
897 // lower attributes (we use the AST version) there is nowhere to keep
898 // the `HirId`s. We don't actually need HIR version of attributes anyway.
899 // Tokens are also not needed after macro expansion and parsing.
900 let kind = match attr.kind {
901 AttrKind::Normal(ref normal) => AttrKind::Normal(P(NormalAttr {
903 path: normal.item.path.clone(),
904 args: self.lower_attr_args(&normal.item.args),
909 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
912 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
915 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
916 debug_assert_eq!(id.owner, self.current_hir_id_owner);
917 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
918 if let Some(&a) = self.attrs.get(&target_id.local_id) {
919 debug_assert!(!a.is_empty());
920 self.attrs.insert(id.local_id, a);
924 fn lower_attr_args(&self, args: &AttrArgs) -> AttrArgs {
926 AttrArgs::Empty => AttrArgs::Empty,
927 AttrArgs::Delimited(args) => AttrArgs::Delimited(self.lower_delim_args(args)),
928 // This is an inert key-value attribute - it will never be visible to macros
929 // after it gets lowered to HIR. Therefore, we can extract literals to handle
930 // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
931 AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => {
932 // In valid code the value always ends up as a single literal. Otherwise, a dummy
933 // literal suffices because the error is handled elsewhere.
934 let lit = if let ExprKind::Lit(token_lit) = expr.kind
935 && let Ok(lit) = MetaItemLit::from_token_lit(token_lit, expr.span)
946 AttrArgs::Eq(*eq_span, AttrArgsEq::Hir(lit))
948 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
949 unreachable!("in literal form when lowering mac args eq: {:?}", lit)
954 fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
955 DelimArgs { dspan: args.dspan, delim: args.delim, tokens: args.tokens.flattened() }
958 /// Given an associated type constraint like one of these:
960 /// ```ignore (illustrative)
961 /// T: Iterator<Item: Debug>
963 /// T: Iterator<Item = Debug>
967 /// returns a `hir::TypeBinding` representing `Item`.
968 #[instrument(level = "debug", skip(self))]
969 fn lower_assoc_ty_constraint(
971 constraint: &AssocConstraint,
972 itctx: &ImplTraitContext,
973 ) -> hir::TypeBinding<'hir> {
974 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
975 // lower generic arguments of identifier in constraint
976 let gen_args = if let Some(gen_args) = &constraint.gen_args {
977 let gen_args_ctor = match gen_args {
978 GenericArgs::AngleBracketed(data) => {
979 self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
981 GenericArgs::Parenthesized(data) => {
982 self.emit_bad_parenthesized_trait_in_assoc_ty(data);
983 self.lower_angle_bracketed_parameter_data(
984 &data.as_angle_bracketed_args(),
991 gen_args_ctor.into_generic_args(self)
993 self.arena.alloc(hir::GenericArgs::none())
995 let itctx_tait = &ImplTraitContext::TypeAliasesOpaqueTy;
997 let kind = match &constraint.kind {
998 AssocConstraintKind::Equality { term } => {
999 let term = match term {
1000 Term::Ty(ty) => self.lower_ty(ty, itctx).into(),
1001 Term::Const(c) => self.lower_anon_const(c).into(),
1003 hir::TypeBindingKind::Equality { term }
1005 AssocConstraintKind::Bound { bounds } => {
1006 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1007 let (desugar_to_impl_trait, itctx) = match itctx {
1008 // We are in the return position:
1010 // fn foo() -> impl Iterator<Item: Debug>
1014 // fn foo() -> impl Iterator<Item = impl Debug>
1015 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1016 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
1018 // We are in the argument position, but within a dyn type:
1020 // fn foo(x: dyn Iterator<Item: Debug>)
1024 // fn foo(x: dyn Iterator<Item = impl Debug>)
1025 ImplTraitContext::Universal if self.is_in_dyn_type => (true, itctx),
1027 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1028 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1029 // "impl trait context" to permit `impl Debug` in this position (it desugars
1030 // then to an opaque type).
1032 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1033 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => (true, itctx_tait),
1035 // We are in the parameter position, but not within a dyn type:
1037 // fn foo(x: impl Iterator<Item: Debug>)
1039 // so we leave it as is and this gets expanded in astconv to a bound like
1040 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1042 _ => (false, itctx),
1045 if desugar_to_impl_trait {
1046 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1047 // constructing the HIR for `impl bounds...` and then lowering that.
1049 let impl_trait_node_id = self.next_node_id();
1051 self.with_dyn_type_scope(false, |this| {
1052 let node_id = this.next_node_id();
1053 let ty = this.lower_ty(
1056 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1057 span: this.lower_span(constraint.span),
1063 hir::TypeBindingKind::Equality { term: ty.into() }
1066 // Desugar `AssocTy: Bounds` into a type binding where the
1067 // later desugars into a trait predicate.
1068 let bounds = self.lower_param_bounds(bounds, itctx);
1070 hir::TypeBindingKind::Constraint { bounds }
1076 hir_id: self.lower_node_id(constraint.id),
1077 ident: self.lower_ident(constraint.ident),
1080 span: self.lower_span(constraint.span),
1084 fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1085 // Suggest removing empty parentheses: "Trait()" -> "Trait"
1086 let sub = if data.inputs.is_empty() {
1087 let parentheses_span =
1088 data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1089 AssocTyParenthesesSub::Empty { parentheses_span }
1091 // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1093 // Start of parameters to the 1st argument
1094 let open_param = data.inputs_span.shrink_to_lo().to(data
1100 // End of last argument to end of parameters
1102 data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1103 AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1105 self.tcx.sess.emit_err(AssocTyParentheses { span: data.span, sub });
1108 #[instrument(level = "debug", skip(self))]
1109 fn lower_generic_arg(
1111 arg: &ast::GenericArg,
1112 itctx: &ImplTraitContext,
1113 ) -> hir::GenericArg<'hir> {
1115 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1116 ast::GenericArg::Type(ty) => {
1118 TyKind::Infer if self.tcx.features().generic_arg_infer => {
1119 return GenericArg::Infer(hir::InferArg {
1120 hir_id: self.lower_node_id(ty.id),
1121 span: self.lower_span(ty.span),
1124 // We parse const arguments as path types as we cannot distinguish them during
1125 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1126 // type and value namespaces. If we resolved the path in the value namespace, we
1127 // transform it into a generic const argument.
1128 TyKind::Path(qself, path) => {
1129 if let Some(res) = self
1131 .get_partial_res(ty.id)
1132 .and_then(|partial_res| partial_res.full_res())
1134 if !res.matches_ns(Namespace::TypeNS) {
1136 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1140 // Construct an AnonConst where the expr is the "ty"'s path.
1142 let parent_def_id = self.current_hir_id_owner;
1143 let node_id = self.next_node_id();
1144 let span = self.lower_span(ty.span);
1146 // Add a definition for the in-band const def.
1147 let def_id = self.create_def(
1148 parent_def_id.def_id,
1150 DefPathData::AnonConst,
1154 let path_expr = Expr {
1156 kind: ExprKind::Path(qself.clone(), path.clone()),
1158 attrs: AttrVec::new(),
1162 let ct = self.with_new_scopes(|this| hir::AnonConst {
1164 hir_id: this.lower_node_id(node_id),
1165 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1167 return GenericArg::Const(ConstArg { value: ct, span });
1173 GenericArg::Type(self.lower_ty(&ty, itctx))
1175 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1176 value: self.lower_anon_const(&ct),
1177 span: self.lower_span(ct.value.span),
1182 #[instrument(level = "debug", skip(self))]
1183 fn lower_ty(&mut self, t: &Ty, itctx: &ImplTraitContext) -> &'hir hir::Ty<'hir> {
1184 self.arena.alloc(self.lower_ty_direct(t, itctx))
1190 qself: &Option<ptr::P<QSelf>>,
1192 param_mode: ParamMode,
1193 itctx: &ImplTraitContext,
1194 ) -> hir::Ty<'hir> {
1195 // Check whether we should interpret this as a bare trait object.
1196 // This check mirrors the one in late resolution. We only introduce this special case in
1197 // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1198 // The other cases when a qpath should be opportunistically made a trait object are handled
1201 && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1202 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1204 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1205 let bound = this.lower_poly_trait_ref(
1207 bound_generic_params: vec![],
1208 trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1213 let bounds = this.arena.alloc_from_iter([bound]);
1214 let lifetime_bound = this.elided_dyn_bound(t.span);
1215 (bounds, lifetime_bound)
1217 let kind = hir::TyKind::TraitObject(bounds, &lifetime_bound, TraitObjectSyntax::None);
1218 return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1221 let id = self.lower_node_id(t.id);
1222 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1223 self.ty_path(id, t.span, qpath)
1226 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1227 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1230 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1231 self.ty(span, hir::TyKind::Tup(tys))
1234 fn lower_ty_direct(&mut self, t: &Ty, itctx: &ImplTraitContext) -> hir::Ty<'hir> {
1235 let kind = match &t.kind {
1236 TyKind::Infer => hir::TyKind::Infer,
1237 TyKind::Err => hir::TyKind::Err,
1238 TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1239 TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1240 TyKind::Ref(region, mt) => {
1241 let region = region.unwrap_or_else(|| {
1242 let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1243 self.resolver.get_lifetime_res(t.id)
1245 debug_assert_eq!(start.plus(1), end);
1250 let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1251 Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1253 let lifetime = self.lower_lifetime(®ion);
1254 hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
1256 TyKind::BareFn(f) => {
1257 let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1258 hir::TyKind::BareFn(self.arena.alloc(hir::BareFnTy {
1260 unsafety: self.lower_unsafety(f.unsafety),
1261 abi: self.lower_extern(f.ext),
1262 decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1263 param_names: self.lower_fn_params_to_names(&f.decl),
1266 TyKind::Never => hir::TyKind::Never,
1267 TyKind::Tup(tys) => hir::TyKind::Tup(
1268 self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty_direct(ty, itctx))),
1270 TyKind::Paren(ty) => {
1271 return self.lower_ty_direct(ty, itctx);
1273 TyKind::Path(qself, path) => {
1274 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1276 TyKind::ImplicitSelf => {
1277 let hir_id = self.next_id();
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::new(
1285 Ident::with_dummy_span(kw::SelfUpper),
1289 span: self.lower_span(t.span),
1293 TyKind::Array(ty, length) => {
1294 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1296 TyKind::Typeof(expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1297 TyKind::TraitObject(bounds, kind) => {
1298 let mut lifetime_bound = None;
1299 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1301 this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1302 GenericBound::Trait(
1304 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1305 ) => Some(this.lower_poly_trait_ref(ty, itctx)),
1306 // `~const ?Bound` will cause an error during AST validation
1307 // anyways, so treat it like `?Bound` as compilation proceeds.
1308 GenericBound::Trait(
1310 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1312 GenericBound::Outlives(lifetime) => {
1313 if lifetime_bound.is_none() {
1314 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, bounds) => {
1328 ImplTraitContext::ReturnPositionOpaqueTy { origin, in_trait } => self
1329 .lower_opaque_impl_trait(
1337 ImplTraitContext::TypeAliasesOpaqueTy => self.lower_opaque_impl_trait(
1339 hir::OpaqueTyOrigin::TyAlias,
1345 ImplTraitContext::Universal => {
1348 self.current_hir_id_owner.def_id,
1350 DefPathData::ImplTrait,
1353 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1354 let (param, bounds, path) =
1355 self.lower_generic_and_bounds(*def_node_id, span, ident, bounds);
1356 self.impl_trait_defs.push(param);
1357 if let Some(bounds) = bounds {
1358 self.impl_trait_bounds.push(bounds);
1362 ImplTraitContext::FeatureGated(position, feature) => {
1365 .create_feature_err(
1366 MisplacedImplTrait {
1368 position: DiagnosticArgFromDisplay(position),
1375 ImplTraitContext::Disallowed(position) => {
1376 self.tcx.sess.emit_err(MisplacedImplTrait {
1378 position: DiagnosticArgFromDisplay(position),
1384 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1385 TyKind::CVarArgs => {
1386 self.tcx.sess.delay_span_bug(
1388 "`TyKind::CVarArgs` should have been handled elsewhere",
1394 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1397 /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1398 /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1399 /// HIR type that references the TAIT.
1401 /// Given a function definition like:
1404 /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1409 /// we will create a TAIT definition in the HIR like
1412 /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1415 /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1418 /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1421 /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1422 /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1423 /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1424 /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1425 /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1426 #[instrument(level = "debug", skip(self), ret)]
1427 fn lower_opaque_impl_trait(
1430 origin: hir::OpaqueTyOrigin,
1431 opaque_ty_node_id: NodeId,
1432 bounds: &GenericBounds,
1434 itctx: &ImplTraitContext,
1435 ) -> hir::TyKind<'hir> {
1436 // Make sure we know that some funky desugaring has been going on here.
1437 // This is a first: there is code in other places like for loop
1438 // desugaring that explicitly states that we don't want to track that.
1439 // Not tracking it makes lints in rustc and clippy very fragile, as
1440 // frequently opened issues show.
1441 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1443 let opaque_ty_def_id = self.create_def(
1444 self.current_hir_id_owner.def_id,
1446 DefPathData::ImplTrait,
1449 debug!(?opaque_ty_def_id);
1451 // Contains the new lifetime definitions created for the TAIT (if any).
1452 let mut collected_lifetimes = Vec::new();
1454 // If this came from a TAIT (as opposed to a function that returns an RPIT), we only want
1455 // to capture the lifetimes that appear in the bounds. So visit the bounds to find out
1456 // exactly which ones those are.
1457 let lifetimes_to_remap = if origin == hir::OpaqueTyOrigin::TyAlias {
1458 // in a TAIT like `type Foo<'a> = impl Foo<'a>`, we don't keep all the lifetime parameters
1461 // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1462 // we only keep the lifetimes that appear in the `impl Debug` itself:
1463 lifetime_collector::lifetimes_in_bounds(&self.resolver, bounds)
1465 debug!(?lifetimes_to_remap);
1467 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1468 let mut new_remapping = FxHashMap::default();
1470 // If this opaque type is only capturing a subset of the lifetimes (those that appear
1471 // in bounds), then create the new lifetime parameters required and create a mapping
1472 // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1473 collected_lifetimes = lctx.create_lifetime_defs(
1475 &lifetimes_to_remap,
1478 debug!(?collected_lifetimes);
1479 debug!(?new_remapping);
1481 // Install the remapping from old to new (if any):
1482 lctx.with_remapping(new_remapping, |lctx| {
1483 // This creates HIR lifetime definitions as `hir::GenericParam`, in the given
1484 // example `type TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection
1485 // containing `&['x]`.
1486 let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1487 |&(new_node_id, lifetime)| {
1488 let hir_id = lctx.lower_node_id(new_node_id);
1489 debug_assert_ne!(lctx.opt_local_def_id(new_node_id), None);
1491 let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1492 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1495 hir::ParamName::Plain(lifetime.ident),
1496 hir::LifetimeParamKind::Explicit,
1502 def_id: lctx.local_def_id(new_node_id),
1504 span: lifetime.ident.span,
1505 pure_wrt_drop: false,
1506 kind: hir::GenericParamKind::Lifetime { kind },
1511 debug!(?lifetime_defs);
1513 // Then when we lower the param bounds, references to 'a are remapped to 'a1, so we
1514 // get back Debug + 'a1, which is suitable for use on the TAIT.
1515 let hir_bounds = lctx.lower_param_bounds(bounds, itctx);
1516 debug!(?hir_bounds);
1518 let opaque_ty_item = hir::OpaqueTy {
1519 generics: self.arena.alloc(hir::Generics {
1520 params: lifetime_defs,
1522 has_where_clause_predicates: false,
1523 where_clause_span: lctx.lower_span(span),
1524 span: lctx.lower_span(span),
1530 debug!(?opaque_ty_item);
1532 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1536 // This creates HIR lifetime arguments as `hir::GenericArg`, in the given example `type
1537 // TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection containing `&['x]`.
1539 self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(_, lifetime)| {
1540 let id = self.next_node_id();
1541 let l = self.new_named_lifetime(lifetime.id, id, lifetime.ident);
1542 hir::GenericArg::Lifetime(l)
1546 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1547 hir::TyKind::OpaqueDef(
1548 hir::ItemId { owner_id: hir::OwnerId { def_id: opaque_ty_def_id } },
1554 /// Registers a new opaque type with the proper `NodeId`s and
1555 /// returns the lowered node-ID for the opaque type.
1556 fn generate_opaque_type(
1558 opaque_ty_id: LocalDefId,
1559 opaque_ty_item: hir::OpaqueTy<'hir>,
1561 opaque_ty_span: Span,
1562 ) -> hir::OwnerNode<'hir> {
1563 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1564 // Generate an `type Foo = impl Trait;` declaration.
1565 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1566 let opaque_ty_item = hir::Item {
1567 owner_id: hir::OwnerId { def_id: opaque_ty_id },
1568 ident: Ident::empty(),
1569 kind: opaque_ty_item_kind,
1570 vis_span: self.lower_span(span.shrink_to_lo()),
1571 span: self.lower_span(opaque_ty_span),
1573 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1576 /// Given a `parent_def_id`, a list of `lifetimes_in_bounds and a `remapping` hash to be
1577 /// filled, this function creates new definitions for `Param` and `Fresh` lifetimes, inserts the
1578 /// new definition, adds it to the remapping with the definition of the given lifetime and
1579 /// returns a list of lifetimes to be lowered afterwards.
1580 fn create_lifetime_defs(
1582 parent_def_id: LocalDefId,
1583 lifetimes_in_bounds: &[Lifetime],
1584 remapping: &mut FxHashMap<LocalDefId, LocalDefId>,
1585 ) -> Vec<(NodeId, Lifetime)> {
1586 let mut result = Vec::new();
1588 for lifetime in lifetimes_in_bounds {
1589 let res = self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error);
1593 LifetimeRes::Param { param: old_def_id, binder: _ } => {
1594 if remapping.get(&old_def_id).is_none() {
1595 let node_id = self.next_node_id();
1597 let new_def_id = self.create_def(
1600 DefPathData::LifetimeNs(lifetime.ident.name),
1601 lifetime.ident.span,
1603 remapping.insert(old_def_id, new_def_id);
1605 result.push((node_id, *lifetime));
1609 LifetimeRes::Fresh { param, binder: _ } => {
1610 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1611 if let Some(old_def_id) = self.orig_opt_local_def_id(param) && remapping.get(&old_def_id).is_none() {
1612 let node_id = self.next_node_id();
1614 let new_def_id = self.create_def(
1617 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1618 lifetime.ident.span,
1620 remapping.insert(old_def_id, new_def_id);
1622 result.push((node_id, *lifetime));
1626 LifetimeRes::Static | LifetimeRes::Error => {}
1629 let bug_msg = format!(
1630 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1631 res, lifetime.ident, lifetime.ident.span
1633 span_bug!(lifetime.ident.span, "{}", bug_msg);
1641 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1642 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1643 // as they are not explicit in HIR/Ty function signatures.
1644 // (instead, the `c_variadic` flag is set to `true`)
1645 let mut inputs = &decl.inputs[..];
1646 if decl.c_variadic() {
1647 inputs = &inputs[..inputs.len() - 1];
1649 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1650 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1651 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1655 // Lowers a function declaration.
1657 // `decl`: the unlowered (AST) function declaration.
1658 // `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given `NodeId`.
1659 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1660 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1661 // return type `impl Trait` item, and the `Span` points to the `async` keyword.
1662 #[instrument(level = "debug", skip(self))]
1669 make_ret_async: Option<(NodeId, Span)>,
1670 ) -> &'hir hir::FnDecl<'hir> {
1671 let c_variadic = decl.c_variadic();
1673 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1674 // as they are not explicit in HIR/Ty function signatures.
1675 // (instead, the `c_variadic` flag is set to `true`)
1676 let mut inputs = &decl.inputs[..];
1678 inputs = &inputs[..inputs.len() - 1];
1680 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1681 let itctx = if kind.param_impl_trait_allowed() {
1682 ImplTraitContext::Universal
1684 ImplTraitContext::Disallowed(match kind {
1685 FnDeclKind::Fn | FnDeclKind::Inherent => {
1686 unreachable!("fn should allow APIT")
1688 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1689 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1690 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1691 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1692 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1695 self.lower_ty_direct(¶m.ty, &itctx)
1698 let output = if let Some((ret_id, span)) = make_ret_async {
1699 if !kind.async_fn_allowed(self.tcx) {
1701 FnDeclKind::Trait | FnDeclKind::Impl => {
1704 .create_feature_err(
1705 TraitFnAsync { fn_span, span },
1706 sym::async_fn_in_trait,
1711 self.tcx.sess.emit_err(TraitFnAsync { fn_span, span });
1716 self.lower_async_fn_ret_ty(
1720 matches!(kind, FnDeclKind::Trait),
1723 match &decl.output {
1724 FnRetTy::Ty(ty) => {
1725 let context = if kind.return_impl_trait_allowed(self.tcx) {
1726 let fn_def_id = self.local_def_id(fn_node_id);
1727 ImplTraitContext::ReturnPositionOpaqueTy {
1728 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1729 in_trait: matches!(kind, FnDeclKind::Trait),
1732 let position = match kind {
1733 FnDeclKind::Fn | FnDeclKind::Inherent => {
1734 unreachable!("fn should allow in-band lifetimes")
1736 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1737 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1738 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1739 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1740 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1743 FnDeclKind::Trait | FnDeclKind::Impl => ImplTraitContext::FeatureGated(
1745 sym::return_position_impl_trait_in_trait,
1747 _ => ImplTraitContext::Disallowed(position),
1750 hir::FnRetTy::Return(self.lower_ty(ty, &context))
1752 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1756 self.arena.alloc(hir::FnDecl {
1760 lifetime_elision_allowed: self.resolver.lifetime_elision_allowed.contains(&fn_node_id),
1761 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1762 let is_mutable_pat = matches!(
1764 PatKind::Ident(hir::BindingAnnotation(_, Mutability::Mut), ..)
1767 match &arg.ty.kind {
1768 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1769 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1770 // Given we are only considering `ImplicitSelf` types, we needn't consider
1771 // the case where we have a mutable pattern to a reference as that would
1772 // no longer be an `ImplicitSelf`.
1773 TyKind::Ref(_, mt) if mt.ty.kind.is_implicit_self() => match mt.mutbl {
1774 hir::Mutability::Not => hir::ImplicitSelfKind::ImmRef,
1775 hir::Mutability::Mut => hir::ImplicitSelfKind::MutRef,
1777 _ => hir::ImplicitSelfKind::None,
1783 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1784 // combined with the following definition of `OpaqueTy`:
1786 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1788 // `output`: unlowered output type (`T` in `-> T`)
1789 // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
1790 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1791 #[instrument(level = "debug", skip(self))]
1792 fn lower_async_fn_ret_ty(
1796 opaque_ty_node_id: NodeId,
1798 ) -> hir::FnRetTy<'hir> {
1799 let span = output.span();
1801 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1803 let fn_def_id = self.local_def_id(fn_node_id);
1805 let opaque_ty_def_id =
1806 self.create_def(fn_def_id, opaque_ty_node_id, DefPathData::ImplTrait, opaque_ty_span);
1808 // When we create the opaque type for this async fn, it is going to have
1809 // to capture all the lifetimes involved in the signature (including in the
1810 // return type). This is done by introducing lifetime parameters for:
1812 // - all the explicitly declared lifetimes from the impl and function itself;
1813 // - all the elided lifetimes in the fn arguments;
1814 // - all the elided lifetimes in the return type.
1816 // So for example in this snippet:
1819 // impl<'a> Foo<'a> {
1820 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1821 // // ^ '0 ^ '1 ^ '2
1822 // // elided lifetimes used below
1827 // we would create an opaque type like:
1830 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1833 // and we would then desugar `bar` to the equivalent of:
1836 // impl<'a> Foo<'a> {
1837 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1841 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1842 // this is because the elided lifetimes from the return type
1843 // should be figured out using the ordinary elision rules, and
1844 // this desugaring achieves that.
1846 // Calculate all the lifetimes that should be captured
1847 // by the opaque type. This should include all in-scope
1848 // lifetime parameters, including those defined in-band.
1850 // Contains the new lifetime definitions created for the TAIT (if any) generated for the
1852 let mut collected_lifetimes = Vec::new();
1853 let mut new_remapping = FxHashMap::default();
1855 let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1856 debug!(?extra_lifetime_params);
1857 for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1858 let outer_def_id = self.orig_local_def_id(outer_node_id);
1859 let inner_node_id = self.next_node_id();
1861 // Add a definition for the in scope lifetime def.
1862 let inner_def_id = self.create_def(
1865 DefPathData::LifetimeNs(ident.name),
1868 new_remapping.insert(outer_def_id, inner_def_id);
1870 let inner_res = match outer_res {
1871 // Input lifetime like `'a`:
1872 LifetimeRes::Param { param, .. } => {
1873 LifetimeRes::Param { param, binder: fn_node_id }
1875 // Input lifetime like `'1`:
1876 LifetimeRes::Fresh { param, .. } => {
1877 LifetimeRes::Fresh { param, binder: fn_node_id }
1879 LifetimeRes::Static | LifetimeRes::Error => continue,
1882 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1883 res, ident, ident.span
1888 let lifetime = Lifetime { id: outer_node_id, ident };
1889 collected_lifetimes.push((inner_node_id, lifetime, Some(inner_res)));
1892 debug!(?collected_lifetimes);
1894 // We only want to capture the lifetimes that appear in the bounds. So visit the bounds to
1895 // find out exactly which ones those are.
1896 // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1897 // we only keep the lifetimes that appear in the `impl Debug` itself:
1898 let lifetimes_to_remap = lifetime_collector::lifetimes_in_ret_ty(&self.resolver, output);
1899 debug!(?lifetimes_to_remap);
1901 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1902 // If this opaque type is only capturing a subset of the lifetimes (those that appear
1903 // in bounds), then create the new lifetime parameters required and create a mapping
1904 // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1905 collected_lifetimes.extend(
1906 this.create_lifetime_defs(
1908 &lifetimes_to_remap,
1912 .map(|(new_node_id, lifetime)| (new_node_id, lifetime, None)),
1914 debug!(?collected_lifetimes);
1915 debug!(?new_remapping);
1917 // Install the remapping from old to new (if any):
1918 this.with_remapping(new_remapping, |this| {
1919 // We have to be careful to get elision right here. The
1920 // idea is that we create a lifetime parameter for each
1921 // lifetime in the return type. So, given a return type
1922 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1923 // Future<Output = &'1 [ &'2 u32 ]>`.
1925 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1926 // hence the elision takes place at the fn site.
1927 let future_bound = this.lower_async_fn_output_type_to_future_bound(
1930 if in_trait && !this.tcx.features().return_position_impl_trait_in_trait {
1931 ImplTraitContext::FeatureGated(
1932 ImplTraitPosition::TraitReturn,
1933 sym::return_position_impl_trait_in_trait,
1936 ImplTraitContext::ReturnPositionOpaqueTy {
1937 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1943 let generic_params = this.arena.alloc_from_iter(collected_lifetimes.iter().map(
1944 |&(new_node_id, lifetime, _)| {
1945 let hir_id = this.lower_node_id(new_node_id);
1946 debug_assert_ne!(this.opt_local_def_id(new_node_id), None);
1948 let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1949 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1952 hir::ParamName::Plain(lifetime.ident),
1953 hir::LifetimeParamKind::Explicit,
1959 def_id: this.local_def_id(new_node_id),
1961 span: lifetime.ident.span,
1962 pure_wrt_drop: false,
1963 kind: hir::GenericParamKind::Lifetime { kind },
1968 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1970 let opaque_ty_item = hir::OpaqueTy {
1971 generics: this.arena.alloc(hir::Generics {
1972 params: generic_params,
1974 has_where_clause_predicates: false,
1975 where_clause_span: this.lower_span(span),
1976 span: this.lower_span(span),
1978 bounds: arena_vec![this; future_bound],
1979 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1983 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1984 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1988 // As documented above, we need to create the lifetime
1989 // arguments to our opaque type. Continuing with our example,
1990 // we're creating the type arguments for the return type:
1993 // Bar<'a, 'b, '0, '1, '_>
1996 // For the "input" lifetime parameters, we wish to create
1997 // references to the parameters themselves, including the
1998 // "implicit" ones created from parameter types (`'a`, `'b`,
2001 // For the "output" lifetime parameters, we just want to
2003 let generic_args = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
2004 |(_, lifetime, res)| {
2005 let id = self.next_node_id();
2006 let res = res.unwrap_or(
2007 self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error),
2009 hir::GenericArg::Lifetime(self.new_named_lifetime_with_res(id, lifetime.ident, res))
2013 // Create the `Foo<...>` reference itself. Note that the `type
2014 // Foo = impl Trait` is, internally, created as a child of the
2015 // async fn, so the *type parameters* are inherited. It's
2016 // only the lifetime parameters that we must supply.
2017 let opaque_ty_ref = hir::TyKind::OpaqueDef(
2018 hir::ItemId { owner_id: hir::OwnerId { def_id: opaque_ty_def_id } },
2022 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2023 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2026 /// Transforms `-> T` into `Future<Output = T>`.
2027 fn lower_async_fn_output_type_to_future_bound(
2031 nested_impl_trait_context: ImplTraitContext,
2032 ) -> hir::GenericBound<'hir> {
2033 // Compute the `T` in `Future<Output = T>` from the return type.
2034 let output_ty = match output {
2035 FnRetTy::Ty(ty) => {
2036 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2037 // `impl Future` opaque type that `async fn` implicitly
2039 self.lower_ty(ty, &nested_impl_trait_context)
2041 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2045 let future_args = self.arena.alloc(hir::GenericArgs {
2047 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
2048 parenthesized: false,
2052 hir::GenericBound::LangItemTrait(
2053 // ::std::future::Future<future_params>
2054 hir::LangItem::Future,
2055 self.lower_span(span),
2061 #[instrument(level = "trace", skip(self))]
2062 fn lower_param_bound(
2065 itctx: &ImplTraitContext,
2066 ) -> hir::GenericBound<'hir> {
2068 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
2069 self.lower_poly_trait_ref(p, itctx),
2070 self.lower_trait_bound_modifier(*modifier),
2072 GenericBound::Outlives(lifetime) => {
2073 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2078 fn lower_lifetime(&mut self, l: &Lifetime) -> &'hir hir::Lifetime {
2079 let ident = self.lower_ident(l.ident);
2080 self.new_named_lifetime(l.id, l.id, ident)
2083 #[instrument(level = "debug", skip(self))]
2084 fn new_named_lifetime_with_res(
2089 ) -> &'hir hir::Lifetime {
2090 let res = match res {
2091 LifetimeRes::Param { param, .. } => {
2092 let param = self.get_remapped_def_id(param);
2093 hir::LifetimeName::Param(param)
2095 LifetimeRes::Fresh { param, .. } => {
2096 let param = self.local_def_id(param);
2097 hir::LifetimeName::Param(param)
2099 LifetimeRes::Infer => hir::LifetimeName::Infer,
2100 LifetimeRes::Static => hir::LifetimeName::Static,
2101 LifetimeRes::Error => hir::LifetimeName::Error,
2103 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
2104 res, ident, ident.span
2109 self.arena.alloc(hir::Lifetime {
2110 hir_id: self.lower_node_id(id),
2111 ident: self.lower_ident(ident),
2116 #[instrument(level = "debug", skip(self))]
2117 fn new_named_lifetime(
2122 ) -> &'hir hir::Lifetime {
2123 let res = self.resolver.get_lifetime_res(id).unwrap_or(LifetimeRes::Error);
2124 self.new_named_lifetime_with_res(new_id, ident, res)
2127 fn lower_generic_params_mut<'s>(
2129 params: &'s [GenericParam],
2130 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2131 params.iter().map(move |param| self.lower_generic_param(param))
2134 fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
2135 self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
2138 #[instrument(level = "trace", skip(self))]
2139 fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
2140 let (name, kind) = self.lower_generic_param_kind(param);
2142 let hir_id = self.lower_node_id(param.id);
2143 self.lower_attrs(hir_id, ¶m.attrs);
2146 def_id: self.local_def_id(param.id),
2148 span: self.lower_span(param.span()),
2149 pure_wrt_drop: self.tcx.sess.contains_name(¶m.attrs, sym::may_dangle),
2151 colon_span: param.colon_span.map(|s| self.lower_span(s)),
2155 fn lower_generic_param_kind(
2157 param: &GenericParam,
2158 ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2160 GenericParamKind::Lifetime => {
2161 // AST resolution emitted an error on those parameters, so we lower them using
2162 // `ParamName::Error`.
2164 if let Some(LifetimeRes::Error) = self.resolver.get_lifetime_res(param.id) {
2167 let ident = self.lower_ident(param.ident);
2168 ParamName::Plain(ident)
2171 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2175 GenericParamKind::Type { default, .. } => {
2176 let kind = hir::GenericParamKind::Type {
2177 default: default.as_ref().map(|x| {
2178 self.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2183 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2185 GenericParamKind::Const { ty, kw_span: _, default } => {
2186 let ty = self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
2187 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2189 hir::ParamName::Plain(self.lower_ident(param.ident)),
2190 hir::GenericParamKind::Const { ty, default },
2196 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: &ImplTraitContext) -> hir::TraitRef<'hir> {
2197 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2198 hir::QPath::Resolved(None, path) => path,
2199 qpath => panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2201 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2204 #[instrument(level = "debug", skip(self))]
2205 fn lower_poly_trait_ref(
2208 itctx: &ImplTraitContext,
2209 ) -> hir::PolyTraitRef<'hir> {
2210 let bound_generic_params =
2211 self.lower_lifetime_binder(p.trait_ref.ref_id, &p.bound_generic_params);
2212 let trait_ref = self.lower_trait_ref(&p.trait_ref, itctx);
2213 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2216 fn lower_mt(&mut self, mt: &MutTy, itctx: &ImplTraitContext) -> hir::MutTy<'hir> {
2217 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2220 #[instrument(level = "debug", skip(self), ret)]
2221 fn lower_param_bounds(
2223 bounds: &[GenericBound],
2224 itctx: &ImplTraitContext,
2225 ) -> hir::GenericBounds<'hir> {
2226 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2229 fn lower_param_bounds_mut<'s>(
2231 bounds: &'s [GenericBound],
2232 itctx: &'s ImplTraitContext,
2233 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2234 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx))
2237 #[instrument(level = "debug", skip(self), ret)]
2238 fn lower_generic_and_bounds(
2243 bounds: &[GenericBound],
2244 ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2245 // Add a definition for the in-band `Param`.
2246 let def_id = self.local_def_id(node_id);
2247 let span = self.lower_span(span);
2249 // Set the name to `impl Bound1 + Bound2`.
2250 let param = hir::GenericParam {
2251 hir_id: self.lower_node_id(node_id),
2253 name: ParamName::Plain(self.lower_ident(ident)),
2254 pure_wrt_drop: false,
2256 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2260 let preds = self.lower_generic_bound_predicate(
2263 &GenericParamKind::Type { default: None },
2265 /* colon_span */ None,
2267 &ImplTraitContext::Universal,
2268 hir::PredicateOrigin::ImplTrait,
2271 let hir_id = self.next_id();
2272 let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2273 let ty = hir::TyKind::Path(hir::QPath::Resolved(
2275 self.arena.alloc(hir::Path {
2279 arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2286 /// Lowers a block directly to an expression, presuming that it
2287 /// has no attributes and is not targeted by a `break`.
2288 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2289 let block = self.lower_block(b, false);
2290 self.expr_block(block)
2293 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2294 match c.value.kind {
2295 ExprKind::Underscore => {
2296 if self.tcx.features().generic_arg_infer {
2297 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2300 &self.tcx.sess.parse_sess,
2301 sym::generic_arg_infer,
2303 "using `_` for array lengths is unstable",
2305 .stash(c.value.span, StashKey::UnderscoreForArrayLengths);
2306 hir::ArrayLen::Body(self.lower_anon_const(c))
2309 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2313 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2314 self.with_new_scopes(|this| hir::AnonConst {
2315 def_id: this.local_def_id(c.id),
2316 hir_id: this.lower_node_id(c.id),
2317 body: this.lower_const_body(c.value.span, Some(&c.value)),
2321 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2323 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2324 UserProvided => hir::UnsafeSource::UserProvided,
2328 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2330 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2331 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2333 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2334 // placeholder for compilation to proceed.
2335 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2336 hir::TraitBoundModifier::Maybe
2341 // Helper methods for building HIR.
2343 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2344 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2347 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2348 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2353 attrs: Option<&'hir [Attribute]>,
2355 init: Option<&'hir hir::Expr<'hir>>,
2356 pat: &'hir hir::Pat<'hir>,
2357 source: hir::LocalSource,
2358 ) -> hir::Stmt<'hir> {
2359 let hir_id = self.next_id();
2360 if let Some(a) = attrs {
2361 debug_assert!(!a.is_empty());
2362 self.attrs.insert(hir_id.local_id, a);
2364 let local = hir::Local {
2370 span: self.lower_span(span),
2373 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2376 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2377 self.block_all(expr.span, &[], Some(expr))
2383 stmts: &'hir [hir::Stmt<'hir>],
2384 expr: Option<&'hir hir::Expr<'hir>>,
2385 ) -> &'hir hir::Block<'hir> {
2386 let blk = hir::Block {
2389 hir_id: self.next_id(),
2390 rules: hir::BlockCheckMode::DefaultBlock,
2391 span: self.lower_span(span),
2392 targeted_by_break: false,
2394 self.arena.alloc(blk)
2397 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2398 let field = self.single_pat_field(span, pat);
2399 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2402 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2403 let field = self.single_pat_field(span, pat);
2404 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2407 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2408 let field = self.single_pat_field(span, pat);
2409 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2412 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2413 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2416 fn single_pat_field(
2419 pat: &'hir hir::Pat<'hir>,
2420 ) -> &'hir [hir::PatField<'hir>] {
2421 let field = hir::PatField {
2422 hir_id: self.next_id(),
2423 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2424 is_shorthand: false,
2426 span: self.lower_span(span),
2428 arena_vec![self; field]
2431 fn pat_lang_item_variant(
2434 lang_item: hir::LangItem,
2435 fields: &'hir [hir::PatField<'hir>],
2436 hir_id: Option<hir::HirId>,
2437 ) -> &'hir hir::Pat<'hir> {
2438 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2439 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2442 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2443 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::NONE)
2446 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2447 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::NONE)
2450 fn pat_ident_binding_mode(
2454 bm: hir::BindingAnnotation,
2455 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2456 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2457 (self.arena.alloc(pat), hir_id)
2460 fn pat_ident_binding_mode_mut(
2464 bm: hir::BindingAnnotation,
2465 ) -> (hir::Pat<'hir>, hir::HirId) {
2466 let hir_id = self.next_id();
2471 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2472 span: self.lower_span(span),
2473 default_binding_modes: true,
2479 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2480 self.arena.alloc(hir::Pat {
2481 hir_id: self.next_id(),
2483 span: self.lower_span(span),
2484 default_binding_modes: true,
2488 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2490 hir_id: self.next_id(),
2492 span: self.lower_span(span),
2493 default_binding_modes: false,
2499 mut hir_id: hir::HirId,
2501 qpath: hir::QPath<'hir>,
2502 ) -> hir::Ty<'hir> {
2503 let kind = match qpath {
2504 hir::QPath::Resolved(None, path) => {
2505 // Turn trait object paths into `TyKind::TraitObject` instead.
2507 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2508 let principal = hir::PolyTraitRef {
2509 bound_generic_params: &[],
2510 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2511 span: self.lower_span(span),
2514 // The original ID is taken by the `PolyTraitRef`,
2515 // so the `Ty` itself needs a different one.
2516 hir_id = self.next_id();
2517 hir::TyKind::TraitObject(
2518 arena_vec![self; principal],
2519 self.elided_dyn_bound(span),
2520 TraitObjectSyntax::None,
2523 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2526 _ => hir::TyKind::Path(qpath),
2529 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2532 /// Invoked to create the lifetime argument(s) for an elided trait object
2533 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2534 /// when the bound is written, even if it is written with `'_` like in
2535 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2536 fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
2537 let r = hir::Lifetime {
2538 hir_id: self.next_id(),
2539 ident: Ident::new(kw::Empty, self.lower_span(span)),
2540 res: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2542 debug!("elided_dyn_bound: r={:?}", r);
2547 /// Helper struct for delayed construction of GenericArgs.
2548 struct GenericArgsCtor<'hir> {
2549 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2550 bindings: &'hir [hir::TypeBinding<'hir>],
2551 parenthesized: bool,
2555 impl<'hir> GenericArgsCtor<'hir> {
2556 fn is_empty(&self) -> bool {
2557 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2560 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2561 let ga = hir::GenericArgs {
2562 args: this.arena.alloc_from_iter(self.args),
2563 bindings: self.bindings,
2564 parenthesized: self.parenthesized,
2565 span_ext: this.lower_span(self.span),
2567 this.arena.alloc(ga)