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_arena::declare_arena;
46 use rustc_ast::ptr::P;
48 use rustc_ast::{self as ast, *};
49 use rustc_ast_pretty::pprust;
50 use rustc_data_structures::captures::Captures;
51 use rustc_data_structures::fingerprint::Fingerprint;
52 use rustc_data_structures::fx::FxHashMap;
53 use rustc_data_structures::sorted_map::SortedMap;
54 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
55 use rustc_data_structures::sync::Lrc;
56 use rustc_errors::{DiagnosticArgFromDisplay, Handler, StashKey};
58 use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
59 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
60 use rustc_hir::definitions::DefPathData;
61 use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate};
62 use rustc_index::vec::{Idx, IndexVec};
63 use rustc_middle::span_bug;
64 use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
65 use rustc_session::parse::feature_err;
66 use rustc_span::hygiene::MacroKind;
67 use rustc_span::source_map::DesugaringKind;
68 use rustc_span::symbol::{kw, sym, Ident, Symbol};
69 use rustc_span::{Span, DUMMY_SP};
71 use smallvec::SmallVec;
72 use std::collections::hash_map::Entry;
74 macro_rules! arena_vec {
75 ($this:expr; $($x:expr),*) => (
76 $this.arena.alloc_from_iter([$($x),*])
86 mod lifetime_collector;
90 struct LoweringContext<'a, 'hir> {
92 resolver: &'a mut ResolverAstLowering,
94 /// Used to allocate HIR nodes.
95 arena: &'hir hir::Arena<'hir>,
97 /// Used to allocate temporary AST nodes for use during lowering.
98 /// This allows us to create "fake" AST -- these nodes can sometimes
99 /// be allocated on the stack, but other times we need them to live longer
100 /// than the current stack frame, so they can be collected into vectors
101 /// and things like that.
102 ast_arena: &'a Arena<'static>,
104 /// Bodies inside the owner being lowered.
105 bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
106 /// Attributes inside the owner being lowered.
107 attrs: SortedMap<hir::ItemLocalId, &'hir [Attribute]>,
108 /// Collect items that were created by lowering the current owner.
109 children: Vec<(LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>)>,
111 generator_kind: Option<hir::GeneratorKind>,
113 /// When inside an `async` context, this is the `HirId` of the
114 /// `task_context` local bound to the resume argument of the generator.
115 task_context: Option<hir::HirId>,
117 /// Used to get the current `fn`'s def span to point to when using `await`
118 /// outside of an `async fn`.
119 current_item: Option<Span>,
121 catch_scope: Option<NodeId>,
122 loop_scope: Option<NodeId>,
123 is_in_loop_condition: bool,
124 is_in_trait_impl: bool,
125 is_in_dyn_type: bool,
127 current_hir_id_owner: hir::OwnerId,
128 item_local_id_counter: hir::ItemLocalId,
129 local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
130 trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
132 impl_trait_defs: Vec<hir::GenericParam<'hir>>,
133 impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
135 /// NodeIds that are lowered inside the current HIR owner.
136 node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
138 allow_try_trait: Option<Lrc<[Symbol]>>,
139 allow_gen_future: Option<Lrc<[Symbol]>>,
140 allow_into_future: Option<Lrc<[Symbol]>>,
142 /// Mapping from generics `def_id`s to TAIT generics `def_id`s.
143 /// For each captured lifetime (e.g., 'a), we create a new lifetime parameter that is a generic
144 /// defined on the TAIT, so we have type Foo<'a1> = ... and we establish a mapping in this
145 /// field from the original parameter 'a to the new parameter 'a1.
146 generics_def_id_map: Vec<FxHashMap<LocalDefId, LocalDefId>>,
150 [] tys: rustc_ast::Ty,
151 [] aba: rustc_ast::AngleBracketedArgs,
152 [] ptr: rustc_ast::PolyTraitRef,
153 // This _marker field is needed because `declare_arena` creates `Arena<'tcx>` and we need to
154 // use `'tcx`. If we don't have this we get a compile error.
155 [] _marker: std::marker::PhantomData<&'tcx ()>,
158 trait ResolverAstLoweringExt {
159 fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>>;
160 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
161 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
162 // Clones the resolution (if any) on 'source' and applies it
163 // to 'target'. Used when desugaring a `UseTreeKind::Nested` to
164 // multiple `UseTreeKind::Simple`s
165 fn clone_res(&mut self, source: NodeId, target: NodeId);
166 fn get_label_res(&self, id: NodeId) -> Option<NodeId>;
167 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
168 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>;
169 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
172 impl ResolverAstLoweringExt for ResolverAstLowering {
173 fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>> {
174 if let ExprKind::Path(None, path) = &expr.kind {
175 // Don't perform legacy const generics rewriting if the path already
176 // has generic arguments.
177 if path.segments.last().unwrap().args.is_some() {
181 if let Res::Def(DefKind::Fn, def_id) = self.partial_res_map.get(&expr.id)?.full_res()? {
182 // We only support cross-crate argument rewriting. Uses
183 // within the same crate should be updated to use the new
184 // const generics style.
185 if def_id.is_local() {
189 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
198 fn clone_res(&mut self, source: NodeId, target: NodeId) {
199 if let Some(res) = self.partial_res_map.get(&source) {
200 self.partial_res_map.insert(target, *res);
204 /// Obtains resolution for a `NodeId` with a single resolution.
205 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
206 self.partial_res_map.get(&id).copied()
209 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
210 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
211 self.import_res_map.get(&id).copied().unwrap_or_default()
214 /// Obtains resolution for a label with the given `NodeId`.
215 fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
216 self.label_res_map.get(&id).copied()
219 /// Obtains resolution for a lifetime with the given `NodeId`.
220 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
221 self.lifetimes_res_map.get(&id).copied()
224 /// Obtain the list of lifetimes parameters to add to an item.
226 /// Extra lifetime parameters should only be added in places that can appear
227 /// as a `binder` in `LifetimeRes`.
229 /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
230 /// should appear at the enclosing `PolyTraitRef`.
231 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
232 self.extra_lifetime_params_map.remove(&id).unwrap_or_default()
235 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind {
236 self.builtin_macro_kinds.get(&def_id).copied().unwrap_or(MacroKind::Bang)
240 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
241 /// and if so, what meaning it has.
242 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
243 enum ImplTraitContext {
244 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
245 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
246 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
248 /// Newly generated parameters should be inserted into the given `Vec`.
251 /// Treat `impl Trait` as shorthand for a new opaque type.
252 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
253 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
255 ReturnPositionOpaqueTy {
256 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
257 origin: hir::OpaqueTyOrigin,
260 /// Impl trait in type aliases.
262 /// `impl Trait` is not accepted in this position.
263 Disallowed(ImplTraitPosition),
266 /// Position in which `impl Trait` is disallowed.
267 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
268 enum ImplTraitPosition {
290 impl std::fmt::Display for ImplTraitPosition {
291 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
292 let name = match self {
293 ImplTraitPosition::Path => "path",
294 ImplTraitPosition::Variable => "variable binding",
295 ImplTraitPosition::Type => "type",
296 ImplTraitPosition::Trait => "trait",
297 ImplTraitPosition::AsyncBlock => "async block",
298 ImplTraitPosition::Bound => "bound",
299 ImplTraitPosition::Generic => "generic",
300 ImplTraitPosition::ExternFnParam => "`extern fn` param",
301 ImplTraitPosition::ClosureParam => "closure param",
302 ImplTraitPosition::PointerParam => "`fn` pointer param",
303 ImplTraitPosition::FnTraitParam => "`Fn` trait param",
304 ImplTraitPosition::TraitParam => "trait method param",
305 ImplTraitPosition::ImplParam => "`impl` method param",
306 ImplTraitPosition::ExternFnReturn => "`extern fn` return",
307 ImplTraitPosition::ClosureReturn => "closure return",
308 ImplTraitPosition::PointerReturn => "`fn` pointer return",
309 ImplTraitPosition::FnTraitReturn => "`Fn` trait return",
310 ImplTraitPosition::TraitReturn => "trait method return",
311 ImplTraitPosition::ImplReturn => "`impl` method return",
314 write!(f, "{}", name)
318 #[derive(Debug, PartialEq, Eq)]
330 fn param_impl_trait_allowed(&self) -> bool {
332 FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => true,
337 fn return_impl_trait_allowed(&self, tcx: TyCtxt<'_>) -> bool {
339 FnDeclKind::Fn | FnDeclKind::Inherent => true,
340 FnDeclKind::Impl if tcx.features().return_position_impl_trait_in_trait => true,
341 FnDeclKind::Trait if tcx.features().return_position_impl_trait_in_trait => true,
346 fn async_fn_allowed(&self, tcx: TyCtxt<'_>) -> bool {
348 FnDeclKind::Fn | FnDeclKind::Inherent => true,
349 FnDeclKind::Impl if tcx.features().async_fn_in_trait => true,
350 FnDeclKind::Trait if tcx.features().async_fn_in_trait => true,
356 #[derive(Copy, Clone)]
359 Crate(&'a ast::Crate),
361 AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
362 ForeignItem(&'a ast::ForeignItem),
366 node_id_to_def_id: &FxHashMap<NodeId, LocalDefId>,
368 ) -> IndexVec<LocalDefId, AstOwner<'a>> {
369 let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() };
370 indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner);
371 indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate);
372 visit::walk_crate(&mut indexer, krate);
373 return indexer.index;
375 struct Indexer<'s, 'a> {
376 node_id_to_def_id: &'s FxHashMap<NodeId, LocalDefId>,
377 index: IndexVec<LocalDefId, AstOwner<'a>>,
380 impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
381 fn visit_attribute(&mut self, _: &'a Attribute) {
382 // We do not want to lower expressions that appear in attributes,
383 // as they are not accessible to the rest of the HIR.
386 fn visit_item(&mut self, item: &'a ast::Item) {
387 let def_id = self.node_id_to_def_id[&item.id];
388 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
389 self.index[def_id] = AstOwner::Item(item);
390 visit::walk_item(self, item)
393 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
394 let def_id = self.node_id_to_def_id[&item.id];
395 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
396 self.index[def_id] = AstOwner::AssocItem(item, ctxt);
397 visit::walk_assoc_item(self, item, ctxt);
400 fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
401 let def_id = self.node_id_to_def_id[&item.id];
402 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
403 self.index[def_id] = AstOwner::ForeignItem(item);
404 visit::walk_foreign_item(self, item);
409 /// Compute the hash for the HIR of the full crate.
410 /// This hash will then be part of the crate_hash which is stored in the metadata.
413 owners: &IndexVec<LocalDefId, hir::MaybeOwner<&hir::OwnerInfo<'_>>>,
415 let mut hir_body_nodes: Vec<_> = owners
417 .filter_map(|(def_id, info)| {
418 let info = info.as_owner()?;
419 let def_path_hash = tcx.hir().def_path_hash(def_id);
420 Some((def_path_hash, info))
423 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
425 tcx.with_stable_hashing_context(|mut hcx| {
426 let mut stable_hasher = StableHasher::new();
427 hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
428 stable_hasher.finish()
432 pub fn lower_to_hir<'hir>(tcx: TyCtxt<'hir>, (): ()) -> hir::Crate<'hir> {
434 let krate = tcx.untracked_crate.steal();
435 let mut resolver = tcx.resolver_for_lowering(()).steal();
437 let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
438 let mut owners = IndexVec::from_fn_n(
439 |_| hir::MaybeOwner::Phantom,
440 tcx.definitions_untracked().def_index_count(),
443 let ast_arena = Arena::default();
445 for def_id in ast_index.indices() {
448 resolver: &mut resolver,
449 ast_arena: &ast_arena,
450 ast_index: &ast_index,
456 // Drop AST to free memory
457 std::mem::drop(ast_index);
458 sess.time("drop_ast", || std::mem::drop(krate));
460 // Discard hygiene data, which isn't required after lowering to HIR.
461 if !sess.opts.unstable_opts.keep_hygiene_data {
462 rustc_span::hygiene::clear_syntax_context_map();
465 let hir_hash = compute_hir_hash(tcx, &owners);
466 hir::Crate { owners, hir_hash }
469 #[derive(Copy, Clone, PartialEq, Debug)]
471 /// Any path in a type context.
473 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
475 /// The `module::Type` in `module::Type::method` in an expression.
479 enum ParenthesizedGenericArgs {
484 impl<'a, 'hir> LoweringContext<'a, 'hir> {
488 node_id: ast::NodeId,
492 debug_assert_ne!(node_id, ast::DUMMY_NODE_ID);
494 self.opt_local_def_id(node_id).is_none(),
495 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
498 self.tcx.hir().def_key(self.local_def_id(node_id)),
501 let def_id = self.tcx.at(span).create_def(parent, data).def_id();
503 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
504 self.resolver.node_id_to_def_id.insert(node_id, def_id);
509 fn next_node_id(&mut self) -> NodeId {
510 let start = self.resolver.next_node_id;
511 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
512 self.resolver.next_node_id = ast::NodeId::from_u32(next);
516 /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
517 /// resolver (if any).
518 fn orig_opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
519 self.resolver.node_id_to_def_id.get(&node).map(|local_def_id| *local_def_id)
522 fn orig_local_def_id(&self, node: NodeId) -> LocalDefId {
523 self.orig_opt_local_def_id(node)
524 .unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
527 /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
528 /// resolver (if any), after applying any remapping from `get_remapped_def_id`.
530 /// For example, in a function like `fn foo<'a>(x: &'a u32)`,
531 /// invoking with the id from the `ast::Lifetime` node found inside
532 /// the `&'a u32` type would return the `LocalDefId` of the
533 /// `'a` parameter declared on `foo`.
535 /// This function also applies remapping from `get_remapped_def_id`.
536 /// These are used when synthesizing opaque types from `-> impl Trait` return types and so forth.
537 /// For example, in a function like `fn foo<'a>() -> impl Debug + 'a`,
538 /// we would create an opaque type `type FooReturn<'a1> = impl Debug + 'a1`.
539 /// When lowering the `Debug + 'a` bounds, we add a remapping to map `'a` to `'a1`.
540 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
541 self.orig_opt_local_def_id(node).map(|local_def_id| self.get_remapped_def_id(local_def_id))
544 fn local_def_id(&self, node: NodeId) -> LocalDefId {
545 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
548 /// Get the previously recorded `to` local def id given the `from` local def id, obtained using
549 /// `generics_def_id_map` field.
550 fn get_remapped_def_id(&self, local_def_id: LocalDefId) -> LocalDefId {
551 // `generics_def_id_map` is a stack of mappings. As we go deeper in impl traits nesting we
552 // push new mappings, so we first need to get the latest (innermost) mappings, hence `iter().rev()`.
556 // `fn test<'a, 'b>() -> impl Trait<&'a u8, Ty = impl Sized + 'b> {}`
558 // We would end with a generics_def_id_map like:
560 // `[[fn#'b -> impl_trait#'b], [fn#'b -> impl_sized#'b]]`
562 // for the opaque type generated on `impl Sized + 'b`, we want the result to be: impl_sized#'b.
563 // So, if we were trying to find first from the start (outermost) would give the wrong result, impl_trait#'b.
564 self.generics_def_id_map
567 .find_map(|map| map.get(&local_def_id).map(|local_def_id| *local_def_id))
568 .unwrap_or(local_def_id)
571 /// Freshen the `LoweringContext` and ready it to lower a nested item.
572 /// The lowered item is registered into `self.children`.
574 /// This function sets up `HirId` lowering infrastructure,
575 /// and stashes the shared mutable state to avoid pollution by the closure.
576 #[instrument(level = "debug", skip(self, f))]
577 fn with_hir_id_owner(
580 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
582 let def_id = self.local_def_id(owner);
584 let current_attrs = std::mem::take(&mut self.attrs);
585 let current_bodies = std::mem::take(&mut self.bodies);
586 let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
587 let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
588 let current_trait_map = std::mem::take(&mut self.trait_map);
590 std::mem::replace(&mut self.current_hir_id_owner, hir::OwnerId { def_id });
591 let current_local_counter =
592 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
593 let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
594 let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
596 // Do not reset `next_node_id` and `node_id_to_def_id`:
597 // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
598 // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
600 // Always allocate the first `HirId` for the owner itself.
601 let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
602 debug_assert_eq!(_old, None);
605 debug_assert_eq!(def_id, item.def_id().def_id);
606 // `f` should have consumed all the elements in these vectors when constructing `item`.
607 debug_assert!(self.impl_trait_defs.is_empty());
608 debug_assert!(self.impl_trait_bounds.is_empty());
609 let info = self.make_owner_info(item);
611 self.attrs = current_attrs;
612 self.bodies = current_bodies;
613 self.node_id_to_local_id = current_node_ids;
614 self.local_id_to_def_id = current_id_to_def_id;
615 self.trait_map = current_trait_map;
616 self.current_hir_id_owner = current_owner;
617 self.item_local_id_counter = current_local_counter;
618 self.impl_trait_defs = current_impl_trait_defs;
619 self.impl_trait_bounds = current_impl_trait_bounds;
621 debug_assert!(self.children.iter().find(|(id, _)| id == &def_id).is_none());
622 self.children.push((def_id, hir::MaybeOwner::Owner(info)));
625 /// Installs the remapping `remap` in scope while `f` is being executed.
626 /// This causes references to the `LocalDefId` keys to be changed to
627 /// refer to the values instead.
629 /// The remapping is used when one piece of AST expands to multiple
630 /// pieces of HIR. For example, the function `fn foo<'a>(...) -> impl Debug + 'a`,
631 /// expands to both a function definition (`foo`) and a TAIT for the return value,
632 /// both of which have a lifetime parameter `'a`. The remapping allows us to
633 /// rewrite the `'a` in the return value to refer to the
634 /// `'a` declared on the TAIT, instead of the function.
635 fn with_remapping<R>(
637 remap: FxHashMap<LocalDefId, LocalDefId>,
638 f: impl FnOnce(&mut Self) -> R,
640 self.generics_def_id_map.push(remap);
642 self.generics_def_id_map.pop();
646 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
647 let attrs = std::mem::take(&mut self.attrs);
648 let mut bodies = std::mem::take(&mut self.bodies);
649 let local_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
650 let trait_map = std::mem::take(&mut self.trait_map);
652 #[cfg(debug_assertions)]
653 for (id, attrs) in attrs.iter() {
654 // Verify that we do not store empty slices in the map.
655 if attrs.is_empty() {
656 panic!("Stored empty attributes for {:?}", id);
660 bodies.sort_by_key(|(k, _)| *k);
661 let bodies = SortedMap::from_presorted_elements(bodies);
662 let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
663 let (nodes, parenting) =
664 index::index_hir(self.tcx.sess, &*self.tcx.definitions_untracked(), node, &bodies);
665 let nodes = hir::OwnerNodes {
666 hash_including_bodies,
673 let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
674 let mut stable_hasher = StableHasher::new();
675 attrs.hash_stable(&mut hcx, &mut stable_hasher);
676 stable_hasher.finish()
678 hir::AttributeMap { map: attrs, hash }
681 self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map })
684 /// Hash the HIR node twice, one deep and one shallow hash. This allows to differentiate
685 /// queries which depend on the full HIR tree and those which only depend on the item signature.
688 node: hir::OwnerNode<'hir>,
689 bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
690 ) -> (Fingerprint, Fingerprint) {
691 self.tcx.with_stable_hashing_context(|mut hcx| {
692 let mut stable_hasher = StableHasher::new();
693 hcx.with_hir_bodies(node.def_id(), bodies, |hcx| {
694 node.hash_stable(hcx, &mut stable_hasher)
696 let hash_including_bodies = stable_hasher.finish();
697 let mut stable_hasher = StableHasher::new();
698 hcx.without_hir_bodies(|hcx| node.hash_stable(hcx, &mut stable_hasher));
699 let hash_without_bodies = stable_hasher.finish();
700 (hash_including_bodies, hash_without_bodies)
704 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
705 /// the `LoweringContext`'s `NodeId => HirId` map.
706 /// Take care not to call this method if the resulting `HirId` is then not
707 /// actually used in the HIR, as that would trigger an assertion in the
708 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
709 /// properly. Calling the method twice with the same `NodeId` is fine though.
710 #[instrument(level = "debug", skip(self), ret)]
711 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
712 assert_ne!(ast_node_id, DUMMY_NODE_ID);
714 match self.node_id_to_local_id.entry(ast_node_id) {
715 Entry::Occupied(o) => {
716 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
718 Entry::Vacant(v) => {
719 // Generate a new `HirId`.
720 let owner = self.current_hir_id_owner;
721 let local_id = self.item_local_id_counter;
722 let hir_id = hir::HirId { owner, local_id };
725 self.item_local_id_counter.increment_by(1);
727 assert_ne!(local_id, hir::ItemLocalId::new(0));
728 if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
729 self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
730 self.local_id_to_def_id.insert(local_id, def_id);
733 if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
734 self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
742 /// Generate a new `HirId` without a backing `NodeId`.
743 #[instrument(level = "debug", skip(self), ret)]
744 fn next_id(&mut self) -> hir::HirId {
745 let owner = self.current_hir_id_owner;
746 let local_id = self.item_local_id_counter;
747 assert_ne!(local_id, hir::ItemLocalId::new(0));
748 self.item_local_id_counter.increment_by(1);
749 hir::HirId { owner, local_id }
752 #[instrument(level = "trace", skip(self))]
753 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
754 let res: Result<Res, ()> = res.apply_id(|id| {
755 let owner = self.current_hir_id_owner;
756 let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
757 Ok(hir::HirId { owner, local_id })
761 // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
762 // This can happen when trying to lower the return type `x` in erroneous code like
763 // async fn foo(x: u8) -> x {}
764 // In that case, `x` is lowered as a function parameter, and the return type is lowered as
765 // an opaque type as a synthesized HIR owner.
766 res.unwrap_or(Res::Err)
769 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
770 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
773 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
774 self.resolver.get_import_res(id).present_items()
777 fn diagnostic(&self) -> &Handler {
778 self.tcx.sess.diagnostic()
781 /// Reuses the span but adds information like the kind of the desugaring and features that are
782 /// allowed inside this span.
783 fn mark_span_with_reason(
785 reason: DesugaringKind,
787 allow_internal_unstable: Option<Lrc<[Symbol]>>,
789 self.tcx.with_stable_hashing_context(|hcx| {
790 span.mark_with_reason(allow_internal_unstable, reason, self.tcx.sess.edition(), hcx)
794 /// Intercept all spans entering HIR.
795 /// Mark a span as relative to the current owning item.
796 fn lower_span(&self, span: Span) -> Span {
797 if self.tcx.sess.opts.unstable_opts.incremental_relative_spans {
798 span.with_parent(Some(self.current_hir_id_owner.def_id))
800 // Do not make spans relative when not using incremental compilation.
805 fn lower_ident(&self, ident: Ident) -> Ident {
806 Ident::new(ident.name, self.lower_span(ident.span))
809 /// Converts a lifetime into a new generic parameter.
810 #[instrument(level = "debug", skip(self))]
811 fn lifetime_res_to_generic_param(
816 ) -> Option<hir::GenericParam<'hir>> {
817 let (name, kind) = match res {
818 LifetimeRes::Param { .. } => {
819 (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
821 LifetimeRes::Fresh { param, .. } => {
822 // Late resolution delegates to us the creation of the `LocalDefId`.
823 let _def_id = self.create_def(
824 self.current_hir_id_owner.def_id,
826 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
831 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
833 LifetimeRes::Static | LifetimeRes::Error => return None,
835 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
836 res, ident, ident.span
839 let hir_id = self.lower_node_id(node_id);
840 let def_id = self.local_def_id(node_id);
841 Some(hir::GenericParam {
845 span: self.lower_span(ident.span),
846 pure_wrt_drop: false,
847 kind: hir::GenericParamKind::Lifetime { kind },
852 /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
853 /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
854 /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
855 /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
856 /// parameters will be successful.
857 #[instrument(level = "debug", skip(self))]
859 fn lower_lifetime_binder(
862 generic_params: &[GenericParam],
863 ) -> &'hir [hir::GenericParam<'hir>] {
864 let mut generic_params: Vec<_> = self.lower_generic_params_mut(generic_params).collect();
865 let extra_lifetimes = self.resolver.take_extra_lifetime_params(binder);
866 debug!(?extra_lifetimes);
867 generic_params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
868 self.lifetime_res_to_generic_param(ident, node_id, res)
870 let generic_params = self.arena.alloc_from_iter(generic_params);
871 debug!(?generic_params);
876 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
877 let was_in_dyn_type = self.is_in_dyn_type;
878 self.is_in_dyn_type = in_scope;
880 let result = f(self);
882 self.is_in_dyn_type = was_in_dyn_type;
887 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
888 let was_in_loop_condition = self.is_in_loop_condition;
889 self.is_in_loop_condition = false;
891 let catch_scope = self.catch_scope.take();
892 let loop_scope = self.loop_scope.take();
894 self.catch_scope = catch_scope;
895 self.loop_scope = loop_scope;
897 self.is_in_loop_condition = was_in_loop_condition;
902 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
903 if attrs.is_empty() {
906 debug_assert_eq!(id.owner, self.current_hir_id_owner);
907 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
908 debug_assert!(!ret.is_empty());
909 self.attrs.insert(id.local_id, ret);
914 fn lower_attr(&self, attr: &Attribute) -> Attribute {
915 // Note that we explicitly do not walk the path. Since we don't really
916 // lower attributes (we use the AST version) there is nowhere to keep
917 // the `HirId`s. We don't actually need HIR version of attributes anyway.
918 // Tokens are also not needed after macro expansion and parsing.
919 let kind = match attr.kind {
920 AttrKind::Normal(ref normal) => AttrKind::Normal(P(NormalAttr {
922 path: normal.item.path.clone(),
923 args: self.lower_attr_args(&normal.item.args),
928 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
931 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
934 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
935 debug_assert_eq!(id.owner, self.current_hir_id_owner);
936 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
937 if let Some(&a) = self.attrs.get(&target_id.local_id) {
938 debug_assert!(!a.is_empty());
939 self.attrs.insert(id.local_id, a);
943 fn lower_attr_args(&self, args: &AttrArgs) -> AttrArgs {
945 AttrArgs::Empty => AttrArgs::Empty,
946 AttrArgs::Delimited(args) => AttrArgs::Delimited(self.lower_delim_args(args)),
947 // This is an inert key-value attribute - it will never be visible to macros
948 // after it gets lowered to HIR. Therefore, we can extract literals to handle
949 // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
950 AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => {
951 // In valid code the value always ends up as a single literal. Otherwise, a dummy
952 // literal suffices because the error is handled elsewhere.
953 let lit = if let ExprKind::Lit(token_lit) = expr.kind
954 && let Ok(lit) = MetaItemLit::from_token_lit(token_lit, expr.span)
959 token_lit: token::Lit::new(token::LitKind::Err, kw::Empty, None),
964 AttrArgs::Eq(*eq_span, AttrArgsEq::Hir(lit))
966 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
967 unreachable!("in literal form when lowering mac args eq: {:?}", lit)
972 fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
973 DelimArgs { dspan: args.dspan, delim: args.delim, tokens: args.tokens.flattened() }
976 /// Given an associated type constraint like one of these:
978 /// ```ignore (illustrative)
979 /// T: Iterator<Item: Debug>
981 /// T: Iterator<Item = Debug>
985 /// returns a `hir::TypeBinding` representing `Item`.
986 #[instrument(level = "debug", skip(self))]
987 fn lower_assoc_ty_constraint(
989 constraint: &AssocConstraint,
990 itctx: &ImplTraitContext,
991 ) -> hir::TypeBinding<'hir> {
992 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
993 // lower generic arguments of identifier in constraint
994 let gen_args = if let Some(gen_args) = &constraint.gen_args {
995 let gen_args_ctor = match gen_args {
996 GenericArgs::AngleBracketed(data) => {
997 self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
999 GenericArgs::Parenthesized(data) => {
1000 self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1001 let aba = self.ast_arena.aba.alloc(data.as_angle_bracketed_args());
1002 self.lower_angle_bracketed_parameter_data(aba, ParamMode::Explicit, itctx).0
1005 gen_args_ctor.into_generic_args(self)
1007 self.arena.alloc(hir::GenericArgs::none())
1009 let itctx_tait = &ImplTraitContext::TypeAliasesOpaqueTy;
1011 let kind = match &constraint.kind {
1012 AssocConstraintKind::Equality { term } => {
1013 let term = match term {
1014 Term::Ty(ty) => self.lower_ty(ty, itctx).into(),
1015 Term::Const(c) => self.lower_anon_const(c).into(),
1017 hir::TypeBindingKind::Equality { term }
1019 AssocConstraintKind::Bound { bounds } => {
1020 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1021 let (desugar_to_impl_trait, itctx) = match itctx {
1022 // We are in the return position:
1024 // fn foo() -> impl Iterator<Item: Debug>
1028 // fn foo() -> impl Iterator<Item = impl Debug>
1029 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1030 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
1032 // We are in the argument position, but within a dyn type:
1034 // fn foo(x: dyn Iterator<Item: Debug>)
1038 // fn foo(x: dyn Iterator<Item = impl Debug>)
1039 ImplTraitContext::Universal if self.is_in_dyn_type => (true, itctx),
1041 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1042 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1043 // "impl trait context" to permit `impl Debug` in this position (it desugars
1044 // then to an opaque type).
1046 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1047 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => (true, itctx_tait),
1049 // We are in the parameter position, but not within a dyn type:
1051 // fn foo(x: impl Iterator<Item: Debug>)
1053 // so we leave it as is and this gets expanded in astconv to a bound like
1054 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1056 _ => (false, itctx),
1059 if desugar_to_impl_trait {
1060 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1061 // constructing the HIR for `impl bounds...` and then lowering that.
1063 let impl_trait_node_id = self.next_node_id();
1065 self.with_dyn_type_scope(false, |this| {
1066 let node_id = this.next_node_id();
1067 let ty = this.ast_arena.tys.alloc(Ty {
1069 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1070 span: this.lower_span(constraint.span),
1073 let ty = this.lower_ty(ty, itctx);
1075 hir::TypeBindingKind::Equality { term: ty.into() }
1078 // Desugar `AssocTy: Bounds` into a type binding where the
1079 // later desugars into a trait predicate.
1080 let bounds = self.lower_param_bounds(bounds, itctx);
1082 hir::TypeBindingKind::Constraint { bounds }
1088 hir_id: self.lower_node_id(constraint.id),
1089 ident: self.lower_ident(constraint.ident),
1092 span: self.lower_span(constraint.span),
1096 fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1097 // Suggest removing empty parentheses: "Trait()" -> "Trait"
1098 let sub = if data.inputs.is_empty() {
1099 let parentheses_span =
1100 data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1101 AssocTyParenthesesSub::Empty { parentheses_span }
1103 // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1105 // Start of parameters to the 1st argument
1106 let open_param = data.inputs_span.shrink_to_lo().to(data
1112 // End of last argument to end of parameters
1114 data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1115 AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1117 self.tcx.sess.emit_err(AssocTyParentheses { span: data.span, sub });
1120 #[instrument(level = "debug", skip(self))]
1121 fn lower_generic_arg(
1123 arg: &ast::GenericArg,
1124 itctx: &ImplTraitContext,
1125 ) -> hir::GenericArg<'hir> {
1127 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1128 ast::GenericArg::Type(ty) => {
1130 TyKind::Infer if self.tcx.features().generic_arg_infer => {
1131 return GenericArg::Infer(hir::InferArg {
1132 hir_id: self.lower_node_id(ty.id),
1133 span: self.lower_span(ty.span),
1136 // We parse const arguments as path types as we cannot distinguish them during
1137 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1138 // type and value namespaces. If we resolved the path in the value namespace, we
1139 // transform it into a generic const argument.
1140 TyKind::Path(qself, path) => {
1141 if let Some(res) = self
1143 .get_partial_res(ty.id)
1144 .and_then(|partial_res| partial_res.full_res())
1146 if !res.matches_ns(Namespace::TypeNS) {
1148 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1152 // Construct an AnonConst where the expr is the "ty"'s path.
1154 let parent_def_id = self.current_hir_id_owner;
1155 let node_id = self.next_node_id();
1156 let span = self.lower_span(ty.span);
1158 // Add a definition for the in-band const def.
1159 let def_id = self.create_def(
1160 parent_def_id.def_id,
1162 DefPathData::AnonConst,
1166 let path_expr = Expr {
1168 kind: ExprKind::Path(qself.clone(), path.clone()),
1170 attrs: AttrVec::new(),
1174 let ct = self.with_new_scopes(|this| hir::AnonConst {
1176 hir_id: this.lower_node_id(node_id),
1177 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1179 return GenericArg::Const(ConstArg { value: ct, span });
1185 GenericArg::Type(self.lower_ty(&ty, itctx))
1187 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1188 value: self.lower_anon_const(&ct),
1189 span: self.lower_span(ct.value.span),
1194 #[instrument(level = "debug", skip(self))]
1195 fn lower_ty(&mut self, t: &Ty, itctx: &ImplTraitContext) -> &'hir hir::Ty<'hir> {
1196 self.arena.alloc(self.lower_ty_direct(t, itctx))
1202 qself: &Option<ptr::P<QSelf>>,
1204 param_mode: ParamMode,
1205 itctx: &ImplTraitContext,
1206 ) -> hir::Ty<'hir> {
1207 // Check whether we should interpret this as a bare trait object.
1208 // This check mirrors the one in late resolution. We only introduce this special case in
1209 // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1210 // The other cases when a qpath should be opportunistically made a trait object are handled
1213 && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1214 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1216 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1217 let poly_trait_ref = this.ast_arena.ptr.alloc(PolyTraitRef {
1218 bound_generic_params: vec![],
1219 trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1222 let bound = this.lower_poly_trait_ref(
1226 let bounds = this.arena.alloc_from_iter([bound]);
1227 let lifetime_bound = this.elided_dyn_bound(t.span);
1228 (bounds, lifetime_bound)
1230 let kind = hir::TyKind::TraitObject(bounds, &lifetime_bound, TraitObjectSyntax::None);
1231 return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1234 let id = self.lower_node_id(t.id);
1235 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1236 self.ty_path(id, t.span, qpath)
1239 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1240 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1243 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1244 self.ty(span, hir::TyKind::Tup(tys))
1247 fn lower_ty_direct(&mut self, t: &Ty, itctx: &ImplTraitContext) -> hir::Ty<'hir> {
1248 let kind = match &t.kind {
1249 TyKind::Infer => hir::TyKind::Infer,
1250 TyKind::Err => hir::TyKind::Err,
1251 TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1252 TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1253 TyKind::Rptr(region, mt) => {
1254 let region = region.unwrap_or_else(|| {
1255 let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1256 self.resolver.get_lifetime_res(t.id)
1258 debug_assert_eq!(start.plus(1), end);
1263 let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1264 Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1266 let lifetime = self.lower_lifetime(®ion);
1267 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1269 TyKind::BareFn(f) => {
1270 let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1271 hir::TyKind::BareFn(self.arena.alloc(hir::BareFnTy {
1273 unsafety: self.lower_unsafety(f.unsafety),
1274 abi: self.lower_extern(f.ext),
1275 decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1276 param_names: self.lower_fn_params_to_names(&f.decl),
1279 TyKind::Never => hir::TyKind::Never,
1280 TyKind::Tup(tys) => hir::TyKind::Tup(
1281 self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty_direct(ty, itctx))),
1283 TyKind::Paren(ty) => {
1284 return self.lower_ty_direct(ty, itctx);
1286 TyKind::Path(qself, path) => {
1287 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1289 TyKind::ImplicitSelf => {
1290 let hir_id = self.next_id();
1291 let res = self.expect_full_res(t.id);
1292 let res = self.lower_res(res);
1293 hir::TyKind::Path(hir::QPath::Resolved(
1295 self.arena.alloc(hir::Path {
1297 segments: arena_vec![self; hir::PathSegment::new(
1298 Ident::with_dummy_span(kw::SelfUpper),
1302 span: self.lower_span(t.span),
1306 TyKind::Array(ty, length) => {
1307 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1309 TyKind::Typeof(expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1310 TyKind::TraitObject(bounds, kind) => {
1311 let mut lifetime_bound = None;
1312 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1314 this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1315 GenericBound::Trait(
1317 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1318 ) => Some(this.lower_poly_trait_ref(ty, itctx)),
1319 // `~const ?Bound` will cause an error during AST validation
1320 // anyways, so treat it like `?Bound` as compilation proceeds.
1321 GenericBound::Trait(
1323 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1325 GenericBound::Outlives(lifetime) => {
1326 if lifetime_bound.is_none() {
1327 lifetime_bound = Some(this.lower_lifetime(lifetime));
1332 let lifetime_bound =
1333 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1334 (bounds, lifetime_bound)
1336 hir::TyKind::TraitObject(bounds, lifetime_bound, *kind)
1338 TyKind::ImplTrait(def_node_id, bounds) => {
1341 ImplTraitContext::ReturnPositionOpaqueTy { origin, in_trait } => self
1342 .lower_opaque_impl_trait(
1350 ImplTraitContext::TypeAliasesOpaqueTy => self.lower_opaque_impl_trait(
1352 hir::OpaqueTyOrigin::TyAlias,
1358 ImplTraitContext::Universal => {
1361 self.current_hir_id_owner.def_id,
1363 DefPathData::ImplTrait,
1366 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1367 let (param, bounds, path) =
1368 self.lower_generic_and_bounds(*def_node_id, span, ident, bounds);
1369 self.impl_trait_defs.push(param);
1370 if let Some(bounds) = bounds {
1371 self.impl_trait_bounds.push(bounds);
1375 ImplTraitContext::Disallowed(
1376 position @ (ImplTraitPosition::TraitReturn | ImplTraitPosition::ImplReturn),
1380 .create_feature_err(
1381 MisplacedImplTrait {
1383 position: DiagnosticArgFromDisplay(&position),
1385 sym::return_position_impl_trait_in_trait,
1390 ImplTraitContext::Disallowed(position) => {
1391 self.tcx.sess.emit_err(MisplacedImplTrait {
1393 position: DiagnosticArgFromDisplay(&position),
1399 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1400 TyKind::CVarArgs => {
1401 self.tcx.sess.delay_span_bug(
1403 "`TyKind::CVarArgs` should have been handled elsewhere",
1409 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1412 /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1413 /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1414 /// HIR type that references the TAIT.
1416 /// Given a function definition like:
1419 /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1424 /// we will create a TAIT definition in the HIR like
1427 /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1430 /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1433 /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1436 /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1437 /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1438 /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1439 /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1440 /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1441 #[instrument(level = "debug", skip(self), ret)]
1442 fn lower_opaque_impl_trait(
1445 origin: hir::OpaqueTyOrigin,
1446 opaque_ty_node_id: NodeId,
1447 bounds: &GenericBounds,
1449 itctx: &ImplTraitContext,
1450 ) -> hir::TyKind<'hir> {
1451 // Make sure we know that some funky desugaring has been going on here.
1452 // This is a first: there is code in other places like for loop
1453 // desugaring that explicitly states that we don't want to track that.
1454 // Not tracking it makes lints in rustc and clippy very fragile, as
1455 // frequently opened issues show.
1456 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1458 let opaque_ty_def_id = self.create_def(
1459 self.current_hir_id_owner.def_id,
1461 DefPathData::ImplTrait,
1464 debug!(?opaque_ty_def_id);
1466 // Contains the new lifetime definitions created for the TAIT (if any).
1467 let mut collected_lifetimes = Vec::new();
1469 // If this came from a TAIT (as opposed to a function that returns an RPIT), we only want
1470 // to capture the lifetimes that appear in the bounds. So visit the bounds to find out
1471 // exactly which ones those are.
1472 let lifetimes_to_remap = if origin == hir::OpaqueTyOrigin::TyAlias {
1473 // in a TAIT like `type Foo<'a> = impl Foo<'a>`, we don't keep all the lifetime parameters
1476 // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1477 // we only keep the lifetimes that appear in the `impl Debug` itself:
1478 lifetime_collector::lifetimes_in_bounds(&self.resolver, bounds)
1480 debug!(?lifetimes_to_remap);
1482 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1483 let mut new_remapping = FxHashMap::default();
1485 // If this opaque type is only capturing a subset of the lifetimes (those that appear
1486 // in bounds), then create the new lifetime parameters required and create a mapping
1487 // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1488 collected_lifetimes = lctx.create_lifetime_defs(
1490 &lifetimes_to_remap,
1493 debug!(?collected_lifetimes);
1494 debug!(?new_remapping);
1496 // Install the remapping from old to new (if any):
1497 lctx.with_remapping(new_remapping, |lctx| {
1498 // This creates HIR lifetime definitions as `hir::GenericParam`, in the given
1499 // example `type TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection
1500 // containing `&['x]`.
1501 let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1502 |&(new_node_id, lifetime)| {
1503 let hir_id = lctx.lower_node_id(new_node_id);
1504 debug_assert_ne!(lctx.opt_local_def_id(new_node_id), None);
1506 let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1507 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1510 hir::ParamName::Plain(lifetime.ident),
1511 hir::LifetimeParamKind::Explicit,
1517 def_id: lctx.local_def_id(new_node_id),
1519 span: lifetime.ident.span,
1520 pure_wrt_drop: false,
1521 kind: hir::GenericParamKind::Lifetime { kind },
1526 debug!(?lifetime_defs);
1528 // Then when we lower the param bounds, references to 'a are remapped to 'a1, so we
1529 // get back Debug + 'a1, which is suitable for use on the TAIT.
1530 let hir_bounds = lctx.lower_param_bounds(bounds, itctx);
1531 debug!(?hir_bounds);
1533 let opaque_ty_item = hir::OpaqueTy {
1534 generics: self.arena.alloc(hir::Generics {
1535 params: lifetime_defs,
1537 has_where_clause_predicates: false,
1538 where_clause_span: lctx.lower_span(span),
1539 span: lctx.lower_span(span),
1545 debug!(?opaque_ty_item);
1547 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1551 // This creates HIR lifetime arguments as `hir::GenericArg`, in the given example `type
1552 // TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection containing `&['x]`.
1554 self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(_, lifetime)| {
1555 let id = self.next_node_id();
1556 let l = self.new_named_lifetime(lifetime.id, id, lifetime.ident);
1557 hir::GenericArg::Lifetime(l)
1561 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1562 hir::TyKind::OpaqueDef(
1563 hir::ItemId { owner_id: hir::OwnerId { def_id: opaque_ty_def_id } },
1569 /// Registers a new opaque type with the proper `NodeId`s and
1570 /// returns the lowered node-ID for the opaque type.
1571 fn generate_opaque_type(
1573 opaque_ty_id: LocalDefId,
1574 opaque_ty_item: hir::OpaqueTy<'hir>,
1576 opaque_ty_span: Span,
1577 ) -> hir::OwnerNode<'hir> {
1578 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1579 // Generate an `type Foo = impl Trait;` declaration.
1580 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1581 let opaque_ty_item = hir::Item {
1582 owner_id: hir::OwnerId { def_id: opaque_ty_id },
1583 ident: Ident::empty(),
1584 kind: opaque_ty_item_kind,
1585 vis_span: self.lower_span(span.shrink_to_lo()),
1586 span: self.lower_span(opaque_ty_span),
1588 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1591 /// Given a `parent_def_id`, a list of `lifetimes_in_bounds and a `remapping` hash to be
1592 /// filled, this function creates new definitions for `Param` and `Fresh` lifetimes, inserts the
1593 /// new definition, adds it to the remapping with the definition of the given lifetime and
1594 /// returns a list of lifetimes to be lowered afterwards.
1595 fn create_lifetime_defs(
1597 parent_def_id: LocalDefId,
1598 lifetimes_in_bounds: &[Lifetime],
1599 remapping: &mut FxHashMap<LocalDefId, LocalDefId>,
1600 ) -> Vec<(NodeId, Lifetime)> {
1601 let mut result = Vec::new();
1603 for lifetime in lifetimes_in_bounds {
1604 let res = self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error);
1608 LifetimeRes::Param { param: old_def_id, binder: _ } => {
1609 if remapping.get(&old_def_id).is_none() {
1610 let node_id = self.next_node_id();
1612 let new_def_id = self.create_def(
1615 DefPathData::LifetimeNs(lifetime.ident.name),
1616 lifetime.ident.span,
1618 remapping.insert(old_def_id, new_def_id);
1620 result.push((node_id, *lifetime));
1624 LifetimeRes::Fresh { param, binder: _ } => {
1625 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1626 if let Some(old_def_id) = self.orig_opt_local_def_id(param) && remapping.get(&old_def_id).is_none() {
1627 let node_id = self.next_node_id();
1629 let new_def_id = self.create_def(
1632 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1633 lifetime.ident.span,
1635 remapping.insert(old_def_id, new_def_id);
1637 result.push((node_id, *lifetime));
1641 LifetimeRes::Static | LifetimeRes::Error => {}
1644 let bug_msg = format!(
1645 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1646 res, lifetime.ident, lifetime.ident.span
1648 span_bug!(lifetime.ident.span, "{}", bug_msg);
1656 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1657 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1658 // as they are not explicit in HIR/Ty function signatures.
1659 // (instead, the `c_variadic` flag is set to `true`)
1660 let mut inputs = &decl.inputs[..];
1661 if decl.c_variadic() {
1662 inputs = &inputs[..inputs.len() - 1];
1664 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1665 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1666 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1670 // Lowers a function declaration.
1672 // `decl`: the unlowered (AST) function declaration.
1673 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1674 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1675 // `make_ret_async` is also `Some`.
1676 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1677 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1678 // return type `impl Trait` item, and the `Span` points to the `async` keyword.
1679 #[instrument(level = "debug", skip(self))]
1686 make_ret_async: Option<(NodeId, Span)>,
1687 ) -> &'hir hir::FnDecl<'hir> {
1688 let c_variadic = decl.c_variadic();
1690 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1691 // as they are not explicit in HIR/Ty function signatures.
1692 // (instead, the `c_variadic` flag is set to `true`)
1693 let mut inputs = &decl.inputs[..];
1695 inputs = &inputs[..inputs.len() - 1];
1697 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1698 let itctx = if kind.param_impl_trait_allowed() {
1699 ImplTraitContext::Universal
1701 ImplTraitContext::Disallowed(match kind {
1702 FnDeclKind::Fn | FnDeclKind::Inherent => {
1703 unreachable!("fn should allow APIT")
1705 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1706 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1707 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1708 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1709 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1712 self.lower_ty_direct(¶m.ty, &itctx)
1715 let output = if let Some((ret_id, span)) = make_ret_async {
1716 if !kind.async_fn_allowed(self.tcx) {
1718 FnDeclKind::Trait | FnDeclKind::Impl => {
1721 .create_feature_err(
1722 TraitFnAsync { fn_span, span },
1723 sym::async_fn_in_trait,
1728 self.tcx.sess.emit_err(TraitFnAsync { fn_span, span });
1733 self.lower_async_fn_ret_ty(
1737 matches!(kind, FnDeclKind::Trait),
1740 match &decl.output {
1741 FnRetTy::Ty(ty) => {
1742 let mut context = if kind.return_impl_trait_allowed(self.tcx) {
1743 let fn_def_id = self.local_def_id(fn_node_id);
1744 ImplTraitContext::ReturnPositionOpaqueTy {
1745 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1746 in_trait: matches!(kind, FnDeclKind::Trait),
1749 ImplTraitContext::Disallowed(match kind {
1750 FnDeclKind::Fn | FnDeclKind::Inherent => {
1751 unreachable!("fn should allow in-band lifetimes")
1753 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1754 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1755 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1756 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1757 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1760 hir::FnRetTy::Return(self.lower_ty(ty, &mut context))
1762 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1766 self.arena.alloc(hir::FnDecl {
1770 lifetime_elision_allowed: self.resolver.lifetime_elision_allowed.contains(&fn_node_id),
1771 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1772 let is_mutable_pat = matches!(
1774 PatKind::Ident(hir::BindingAnnotation(_, Mutability::Mut), ..)
1777 match &arg.ty.kind {
1778 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1779 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1780 // Given we are only considering `ImplicitSelf` types, we needn't consider
1781 // the case where we have a mutable pattern to a reference as that would
1782 // no longer be an `ImplicitSelf`.
1783 TyKind::Rptr(_, mt) if mt.ty.kind.is_implicit_self() => match mt.mutbl {
1784 hir::Mutability::Not => hir::ImplicitSelfKind::ImmRef,
1785 hir::Mutability::Mut => hir::ImplicitSelfKind::MutRef,
1787 _ => hir::ImplicitSelfKind::None,
1793 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1794 // combined with the following definition of `OpaqueTy`:
1796 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1798 // `output`: unlowered output type (`T` in `-> T`)
1799 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1800 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1801 #[instrument(level = "debug", skip(self))]
1802 fn lower_async_fn_ret_ty(
1806 opaque_ty_node_id: NodeId,
1808 ) -> hir::FnRetTy<'hir> {
1809 let span = output.span();
1811 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1813 let fn_def_id = self.local_def_id(fn_node_id);
1815 let opaque_ty_def_id =
1816 self.create_def(fn_def_id, opaque_ty_node_id, DefPathData::ImplTrait, opaque_ty_span);
1818 // When we create the opaque type for this async fn, it is going to have
1819 // to capture all the lifetimes involved in the signature (including in the
1820 // return type). This is done by introducing lifetime parameters for:
1822 // - all the explicitly declared lifetimes from the impl and function itself;
1823 // - all the elided lifetimes in the fn arguments;
1824 // - all the elided lifetimes in the return type.
1826 // So for example in this snippet:
1829 // impl<'a> Foo<'a> {
1830 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1831 // // ^ '0 ^ '1 ^ '2
1832 // // elided lifetimes used below
1837 // we would create an opaque type like:
1840 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1843 // and we would then desugar `bar` to the equivalent of:
1846 // impl<'a> Foo<'a> {
1847 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1851 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1852 // this is because the elided lifetimes from the return type
1853 // should be figured out using the ordinary elision rules, and
1854 // this desugaring achieves that.
1856 // Calculate all the lifetimes that should be captured
1857 // by the opaque type. This should include all in-scope
1858 // lifetime parameters, including those defined in-band.
1860 // Contains the new lifetime definitions created for the TAIT (if any) generated for the
1862 let mut collected_lifetimes = Vec::new();
1863 let mut new_remapping = FxHashMap::default();
1865 let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1866 debug!(?extra_lifetime_params);
1867 for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1868 let outer_def_id = self.orig_local_def_id(outer_node_id);
1869 let inner_node_id = self.next_node_id();
1871 // Add a definition for the in scope lifetime def.
1872 let inner_def_id = self.create_def(
1875 DefPathData::LifetimeNs(ident.name),
1878 new_remapping.insert(outer_def_id, inner_def_id);
1880 let inner_res = match outer_res {
1881 // Input lifetime like `'a`:
1882 LifetimeRes::Param { param, .. } => {
1883 LifetimeRes::Param { param, binder: fn_node_id }
1885 // Input lifetime like `'1`:
1886 LifetimeRes::Fresh { param, .. } => {
1887 LifetimeRes::Fresh { param, binder: fn_node_id }
1889 LifetimeRes::Static | LifetimeRes::Error => continue,
1892 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1893 res, ident, ident.span
1898 let lifetime = Lifetime { id: outer_node_id, ident };
1899 collected_lifetimes.push((inner_node_id, lifetime, Some(inner_res)));
1902 debug!(?collected_lifetimes);
1904 // We only want to capture the lifetimes that appear in the bounds. So visit the bounds to
1905 // find out exactly which ones those are.
1906 // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1907 // we only keep the lifetimes that appear in the `impl Debug` itself:
1908 let lifetimes_to_remap = lifetime_collector::lifetimes_in_ret_ty(&self.resolver, output);
1909 debug!(?lifetimes_to_remap);
1911 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1912 // If this opaque type is only capturing a subset of the lifetimes (those that appear
1913 // in bounds), then create the new lifetime parameters required and create a mapping
1914 // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1915 collected_lifetimes.extend(
1916 this.create_lifetime_defs(
1918 &lifetimes_to_remap,
1922 .map(|(new_node_id, lifetime)| (new_node_id, lifetime, None)),
1924 debug!(?collected_lifetimes);
1925 debug!(?new_remapping);
1927 // Install the remapping from old to new (if any):
1928 this.with_remapping(new_remapping, |this| {
1929 // We have to be careful to get elision right here. The
1930 // idea is that we create a lifetime parameter for each
1931 // lifetime in the return type. So, given a return type
1932 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1933 // Future<Output = &'1 [ &'2 u32 ]>`.
1935 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1936 // hence the elision takes place at the fn site.
1937 let future_bound = this.lower_async_fn_output_type_to_future_bound(
1940 if in_trait && !this.tcx.features().return_position_impl_trait_in_trait {
1941 ImplTraitContext::Disallowed(ImplTraitPosition::TraitReturn)
1943 ImplTraitContext::ReturnPositionOpaqueTy {
1944 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1950 let generic_params = this.arena.alloc_from_iter(collected_lifetimes.iter().map(
1951 |&(new_node_id, lifetime, _)| {
1952 let hir_id = this.lower_node_id(new_node_id);
1953 debug_assert_ne!(this.opt_local_def_id(new_node_id), None);
1955 let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1956 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1959 hir::ParamName::Plain(lifetime.ident),
1960 hir::LifetimeParamKind::Explicit,
1966 def_id: this.local_def_id(new_node_id),
1968 span: lifetime.ident.span,
1969 pure_wrt_drop: false,
1970 kind: hir::GenericParamKind::Lifetime { kind },
1975 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1977 let opaque_ty_item = hir::OpaqueTy {
1978 generics: this.arena.alloc(hir::Generics {
1979 params: generic_params,
1981 has_where_clause_predicates: false,
1982 where_clause_span: this.lower_span(span),
1983 span: this.lower_span(span),
1985 bounds: arena_vec![this; future_bound],
1986 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1990 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1991 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1995 // As documented above, we need to create the lifetime
1996 // arguments to our opaque type. Continuing with our example,
1997 // we're creating the type arguments for the return type:
2000 // Bar<'a, 'b, '0, '1, '_>
2003 // For the "input" lifetime parameters, we wish to create
2004 // references to the parameters themselves, including the
2005 // "implicit" ones created from parameter types (`'a`, `'b`,
2008 // For the "output" lifetime parameters, we just want to
2010 let generic_args = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
2011 |(_, lifetime, res)| {
2012 let id = self.next_node_id();
2013 let res = res.unwrap_or(
2014 self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error),
2016 hir::GenericArg::Lifetime(self.new_named_lifetime_with_res(id, lifetime.ident, res))
2020 // Create the `Foo<...>` reference itself. Note that the `type
2021 // Foo = impl Trait` is, internally, created as a child of the
2022 // async fn, so the *type parameters* are inherited. It's
2023 // only the lifetime parameters that we must supply.
2024 let opaque_ty_ref = hir::TyKind::OpaqueDef(
2025 hir::ItemId { owner_id: hir::OwnerId { def_id: opaque_ty_def_id } },
2029 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2030 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2033 /// Transforms `-> T` into `Future<Output = T>`.
2034 fn lower_async_fn_output_type_to_future_bound(
2038 mut nested_impl_trait_context: ImplTraitContext,
2039 ) -> hir::GenericBound<'hir> {
2040 // Compute the `T` in `Future<Output = T>` from the return type.
2041 let output_ty = match output {
2042 FnRetTy::Ty(ty) => {
2043 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2044 // `impl Future` opaque type that `async fn` implicitly
2046 self.lower_ty(ty, &mut nested_impl_trait_context)
2048 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2052 let future_args = self.arena.alloc(hir::GenericArgs {
2054 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
2055 parenthesized: false,
2059 hir::GenericBound::LangItemTrait(
2060 // ::std::future::Future<future_params>
2061 hir::LangItem::Future,
2062 self.lower_span(span),
2068 #[instrument(level = "trace", skip(self))]
2069 fn lower_param_bound(
2072 itctx: &ImplTraitContext,
2073 ) -> hir::GenericBound<'hir> {
2075 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
2076 self.lower_poly_trait_ref(p, itctx),
2077 self.lower_trait_bound_modifier(*modifier),
2079 GenericBound::Outlives(lifetime) => {
2080 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2085 fn lower_lifetime(&mut self, l: &Lifetime) -> &'hir hir::Lifetime {
2086 let ident = self.lower_ident(l.ident);
2087 self.new_named_lifetime(l.id, l.id, ident)
2090 #[instrument(level = "debug", skip(self))]
2091 fn new_named_lifetime_with_res(
2096 ) -> &'hir hir::Lifetime {
2097 let res = match res {
2098 LifetimeRes::Param { param, .. } => {
2099 let param = self.get_remapped_def_id(param);
2100 hir::LifetimeName::Param(param)
2102 LifetimeRes::Fresh { param, .. } => {
2103 let param = self.local_def_id(param);
2104 hir::LifetimeName::Param(param)
2106 LifetimeRes::Infer => hir::LifetimeName::Infer,
2107 LifetimeRes::Static => hir::LifetimeName::Static,
2108 LifetimeRes::Error => hir::LifetimeName::Error,
2110 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
2111 res, ident, ident.span
2116 self.arena.alloc(hir::Lifetime {
2117 hir_id: self.lower_node_id(id),
2118 ident: self.lower_ident(ident),
2123 #[instrument(level = "debug", skip(self))]
2124 fn new_named_lifetime(
2129 ) -> &'hir hir::Lifetime {
2130 let res = self.resolver.get_lifetime_res(id).unwrap_or(LifetimeRes::Error);
2131 self.new_named_lifetime_with_res(new_id, ident, res)
2134 fn lower_generic_params_mut<'s>(
2136 params: &'s [GenericParam],
2137 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2138 params.iter().map(move |param| self.lower_generic_param(param))
2141 fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
2142 self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
2145 #[instrument(level = "trace", skip(self))]
2146 fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
2147 let (name, kind) = self.lower_generic_param_kind(param);
2149 let hir_id = self.lower_node_id(param.id);
2150 self.lower_attrs(hir_id, ¶m.attrs);
2153 def_id: self.local_def_id(param.id),
2155 span: self.lower_span(param.span()),
2156 pure_wrt_drop: self.tcx.sess.contains_name(¶m.attrs, sym::may_dangle),
2158 colon_span: param.colon_span.map(|s| self.lower_span(s)),
2162 fn lower_generic_param_kind(
2164 param: &GenericParam,
2165 ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2167 GenericParamKind::Lifetime => {
2168 // AST resolution emitted an error on those parameters, so we lower them using
2169 // `ParamName::Error`.
2171 if let Some(LifetimeRes::Error) = self.resolver.get_lifetime_res(param.id) {
2174 let ident = self.lower_ident(param.ident);
2175 ParamName::Plain(ident)
2178 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2182 GenericParamKind::Type { default, .. } => {
2183 let kind = hir::GenericParamKind::Type {
2184 default: default.as_ref().map(|x| {
2185 self.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2190 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2192 GenericParamKind::Const { ty, kw_span: _, default } => {
2193 let ty = self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
2194 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2196 hir::ParamName::Plain(self.lower_ident(param.ident)),
2197 hir::GenericParamKind::Const { ty, default },
2203 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: &ImplTraitContext) -> hir::TraitRef<'hir> {
2204 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2205 hir::QPath::Resolved(None, path) => path,
2206 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2208 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2211 #[instrument(level = "debug", skip(self))]
2212 fn lower_poly_trait_ref(
2215 itctx: &ImplTraitContext,
2216 ) -> hir::PolyTraitRef<'hir> {
2217 let bound_generic_params =
2218 self.lower_lifetime_binder(p.trait_ref.ref_id, &p.bound_generic_params);
2219 let trait_ref = self.lower_trait_ref(&p.trait_ref, itctx);
2220 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2223 fn lower_mt(&mut self, mt: &MutTy, itctx: &ImplTraitContext) -> hir::MutTy<'hir> {
2224 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2227 #[instrument(level = "debug", skip(self), ret)]
2228 fn lower_param_bounds(
2230 bounds: &[GenericBound],
2231 itctx: &ImplTraitContext,
2232 ) -> hir::GenericBounds<'hir> {
2233 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2236 fn lower_param_bounds_mut<'s>(
2238 bounds: &'s [GenericBound],
2239 itctx: &'s ImplTraitContext,
2240 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2241 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx))
2244 #[instrument(level = "debug", skip(self), ret)]
2245 fn lower_generic_and_bounds(
2250 bounds: &[GenericBound],
2251 ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2252 // Add a definition for the in-band `Param`.
2253 let def_id = self.local_def_id(node_id);
2255 // Set the name to `impl Bound1 + Bound2`.
2256 let param = hir::GenericParam {
2257 hir_id: self.lower_node_id(node_id),
2259 name: ParamName::Plain(self.lower_ident(ident)),
2260 pure_wrt_drop: false,
2261 span: self.lower_span(span),
2262 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2266 let preds = self.lower_generic_bound_predicate(
2269 &GenericParamKind::Type { default: None },
2271 &ImplTraitContext::Universal,
2272 hir::PredicateOrigin::ImplTrait,
2275 let hir_id = self.next_id();
2276 let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2277 let ty = hir::TyKind::Path(hir::QPath::Resolved(
2279 self.arena.alloc(hir::Path {
2280 span: self.lower_span(span),
2283 arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2290 /// Lowers a block directly to an expression, presuming that it
2291 /// has no attributes and is not targeted by a `break`.
2292 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2293 let block = self.lower_block(b, false);
2294 self.expr_block(block)
2297 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2298 match c.value.kind {
2299 ExprKind::Underscore => {
2300 if self.tcx.features().generic_arg_infer {
2301 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2304 &self.tcx.sess.parse_sess,
2305 sym::generic_arg_infer,
2307 "using `_` for array lengths is unstable",
2309 .stash(c.value.span, StashKey::UnderscoreForArrayLengths);
2310 hir::ArrayLen::Body(self.lower_anon_const(c))
2313 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2317 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2318 self.with_new_scopes(|this| hir::AnonConst {
2319 def_id: this.local_def_id(c.id),
2320 hir_id: this.lower_node_id(c.id),
2321 body: this.lower_const_body(c.value.span, Some(&c.value)),
2325 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2327 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2328 UserProvided => hir::UnsafeSource::UserProvided,
2332 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2334 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2335 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2337 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2338 // placeholder for compilation to proceed.
2339 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2340 hir::TraitBoundModifier::Maybe
2345 // Helper methods for building HIR.
2347 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2348 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2351 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2352 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2357 attrs: Option<&'hir [Attribute]>,
2359 init: Option<&'hir hir::Expr<'hir>>,
2360 pat: &'hir hir::Pat<'hir>,
2361 source: hir::LocalSource,
2362 ) -> hir::Stmt<'hir> {
2363 let hir_id = self.next_id();
2364 if let Some(a) = attrs {
2365 debug_assert!(!a.is_empty());
2366 self.attrs.insert(hir_id.local_id, a);
2368 let local = hir::Local {
2374 span: self.lower_span(span),
2377 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2380 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2381 self.block_all(expr.span, &[], Some(expr))
2387 stmts: &'hir [hir::Stmt<'hir>],
2388 expr: Option<&'hir hir::Expr<'hir>>,
2389 ) -> &'hir hir::Block<'hir> {
2390 let blk = hir::Block {
2393 hir_id: self.next_id(),
2394 rules: hir::BlockCheckMode::DefaultBlock,
2395 span: self.lower_span(span),
2396 targeted_by_break: false,
2398 self.arena.alloc(blk)
2401 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2402 let field = self.single_pat_field(span, pat);
2403 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2406 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2407 let field = self.single_pat_field(span, pat);
2408 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2411 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2412 let field = self.single_pat_field(span, pat);
2413 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2416 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2417 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2420 fn single_pat_field(
2423 pat: &'hir hir::Pat<'hir>,
2424 ) -> &'hir [hir::PatField<'hir>] {
2425 let field = hir::PatField {
2426 hir_id: self.next_id(),
2427 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2428 is_shorthand: false,
2430 span: self.lower_span(span),
2432 arena_vec![self; field]
2435 fn pat_lang_item_variant(
2438 lang_item: hir::LangItem,
2439 fields: &'hir [hir::PatField<'hir>],
2440 hir_id: Option<hir::HirId>,
2441 ) -> &'hir hir::Pat<'hir> {
2442 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2443 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2446 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2447 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::NONE)
2450 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2451 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::NONE)
2454 fn pat_ident_binding_mode(
2458 bm: hir::BindingAnnotation,
2459 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2460 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2461 (self.arena.alloc(pat), hir_id)
2464 fn pat_ident_binding_mode_mut(
2468 bm: hir::BindingAnnotation,
2469 ) -> (hir::Pat<'hir>, hir::HirId) {
2470 let hir_id = self.next_id();
2475 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2476 span: self.lower_span(span),
2477 default_binding_modes: true,
2483 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2484 self.arena.alloc(hir::Pat {
2485 hir_id: self.next_id(),
2487 span: self.lower_span(span),
2488 default_binding_modes: true,
2492 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2494 hir_id: self.next_id(),
2496 span: self.lower_span(span),
2497 default_binding_modes: false,
2503 mut hir_id: hir::HirId,
2505 qpath: hir::QPath<'hir>,
2506 ) -> hir::Ty<'hir> {
2507 let kind = match qpath {
2508 hir::QPath::Resolved(None, path) => {
2509 // Turn trait object paths into `TyKind::TraitObject` instead.
2511 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2512 let principal = hir::PolyTraitRef {
2513 bound_generic_params: &[],
2514 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2515 span: self.lower_span(span),
2518 // The original ID is taken by the `PolyTraitRef`,
2519 // so the `Ty` itself needs a different one.
2520 hir_id = self.next_id();
2521 hir::TyKind::TraitObject(
2522 arena_vec![self; principal],
2523 self.elided_dyn_bound(span),
2524 TraitObjectSyntax::None,
2527 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2530 _ => hir::TyKind::Path(qpath),
2533 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2536 /// Invoked to create the lifetime argument(s) for an elided trait object
2537 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2538 /// when the bound is written, even if it is written with `'_` like in
2539 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2540 fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
2541 let r = hir::Lifetime {
2542 hir_id: self.next_id(),
2543 ident: Ident::new(kw::Empty, self.lower_span(span)),
2544 res: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2546 debug!("elided_dyn_bound: r={:?}", r);
2551 /// Helper struct for delayed construction of GenericArgs.
2552 struct GenericArgsCtor<'hir> {
2553 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2554 bindings: &'hir [hir::TypeBinding<'hir>],
2555 parenthesized: bool,
2559 impl<'hir> GenericArgsCtor<'hir> {
2560 fn is_empty(&self) -> bool {
2561 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2564 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2565 let ga = hir::GenericArgs {
2566 args: this.arena.alloc_from_iter(self.args),
2567 bindings: self.bindings,
2568 parenthesized: self.parenthesized,
2569 span_ext: this.lower_span(self.span),
2571 this.arena.alloc(ga)