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 impl_trait_allowed(&self, tcx: TyCtxt<'_>) -> bool {
332 FnDeclKind::Fn | FnDeclKind::Inherent => true,
333 FnDeclKind::Impl if tcx.features().return_position_impl_trait_in_trait => true,
334 FnDeclKind::Trait if tcx.features().return_position_impl_trait_in_trait => true,
339 fn async_fn_allowed(&self, tcx: TyCtxt<'_>) -> bool {
341 FnDeclKind::Fn | FnDeclKind::Inherent => true,
342 FnDeclKind::Impl if tcx.features().async_fn_in_trait => true,
343 FnDeclKind::Trait if tcx.features().async_fn_in_trait => true,
349 #[derive(Copy, Clone)]
352 Crate(&'a ast::Crate),
354 AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
355 ForeignItem(&'a ast::ForeignItem),
359 node_id_to_def_id: &FxHashMap<NodeId, LocalDefId>,
361 ) -> IndexVec<LocalDefId, AstOwner<'a>> {
362 let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() };
363 indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner);
364 indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate);
365 visit::walk_crate(&mut indexer, krate);
366 return indexer.index;
368 struct Indexer<'s, 'a> {
369 node_id_to_def_id: &'s FxHashMap<NodeId, LocalDefId>,
370 index: IndexVec<LocalDefId, AstOwner<'a>>,
373 impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
374 fn visit_attribute(&mut self, _: &'a Attribute) {
375 // We do not want to lower expressions that appear in attributes,
376 // as they are not accessible to the rest of the HIR.
379 fn visit_item(&mut self, item: &'a ast::Item) {
380 let def_id = self.node_id_to_def_id[&item.id];
381 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
382 self.index[def_id] = AstOwner::Item(item);
383 visit::walk_item(self, item)
386 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
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::AssocItem(item, ctxt);
390 visit::walk_assoc_item(self, item, ctxt);
393 fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
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::ForeignItem(item);
397 visit::walk_foreign_item(self, item);
402 /// Compute the hash for the HIR of the full crate.
403 /// This hash will then be part of the crate_hash which is stored in the metadata.
406 owners: &IndexVec<LocalDefId, hir::MaybeOwner<&hir::OwnerInfo<'_>>>,
408 let mut hir_body_nodes: Vec<_> = owners
410 .filter_map(|(def_id, info)| {
411 let info = info.as_owner()?;
412 let def_path_hash = tcx.hir().def_path_hash(def_id);
413 Some((def_path_hash, info))
416 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
418 tcx.with_stable_hashing_context(|mut hcx| {
419 let mut stable_hasher = StableHasher::new();
420 hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
421 stable_hasher.finish()
425 pub fn lower_to_hir<'hir>(tcx: TyCtxt<'hir>, (): ()) -> hir::Crate<'hir> {
427 let krate = tcx.untracked_crate.steal();
428 let mut resolver = tcx.resolver_for_lowering(()).steal();
430 let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
431 let mut owners = IndexVec::from_fn_n(
432 |_| hir::MaybeOwner::Phantom,
433 tcx.definitions_untracked().def_index_count(),
436 let ast_arena = Arena::default();
438 for def_id in ast_index.indices() {
441 resolver: &mut resolver,
442 ast_arena: &ast_arena,
443 ast_index: &ast_index,
449 // Drop AST to free memory
450 std::mem::drop(ast_index);
451 sess.time("drop_ast", || std::mem::drop(krate));
453 // Discard hygiene data, which isn't required after lowering to HIR.
454 if !sess.opts.unstable_opts.keep_hygiene_data {
455 rustc_span::hygiene::clear_syntax_context_map();
458 let hir_hash = compute_hir_hash(tcx, &owners);
459 hir::Crate { owners, hir_hash }
462 #[derive(Copy, Clone, PartialEq, Debug)]
464 /// Any path in a type context.
466 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
468 /// The `module::Type` in `module::Type::method` in an expression.
472 enum ParenthesizedGenericArgs {
477 impl<'a, 'hir> LoweringContext<'a, 'hir> {
481 node_id: ast::NodeId,
484 debug_assert_ne!(node_id, ast::DUMMY_NODE_ID);
486 self.opt_local_def_id(node_id).is_none(),
487 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
490 self.tcx.hir().def_key(self.local_def_id(node_id)),
493 let def_id = self.tcx.create_def(parent, data);
495 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
496 self.resolver.node_id_to_def_id.insert(node_id, def_id);
501 fn next_node_id(&mut self) -> NodeId {
502 let start = self.resolver.next_node_id;
503 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
504 self.resolver.next_node_id = ast::NodeId::from_u32(next);
508 /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
509 /// resolver (if any).
510 fn orig_opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
511 self.resolver.node_id_to_def_id.get(&node).map(|local_def_id| *local_def_id)
514 fn orig_local_def_id(&self, node: NodeId) -> LocalDefId {
515 self.orig_opt_local_def_id(node)
516 .unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
519 /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
520 /// resolver (if any), after applying any remapping from `get_remapped_def_id`.
522 /// For example, in a function like `fn foo<'a>(x: &'a u32)`,
523 /// invoking with the id from the `ast::Lifetime` node found inside
524 /// the `&'a u32` type would return the `LocalDefId` of the
525 /// `'a` parameter declared on `foo`.
527 /// This function also applies remapping from `get_remapped_def_id`.
528 /// These are used when synthesizing opaque types from `-> impl Trait` return types and so forth.
529 /// For example, in a function like `fn foo<'a>() -> impl Debug + 'a`,
530 /// we would create an opaque type `type FooReturn<'a1> = impl Debug + 'a1`.
531 /// When lowering the `Debug + 'a` bounds, we add a remapping to map `'a` to `'a1`.
532 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
533 self.orig_opt_local_def_id(node).map(|local_def_id| self.get_remapped_def_id(local_def_id))
536 fn local_def_id(&self, node: NodeId) -> LocalDefId {
537 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
540 /// Get the previously recorded `to` local def id given the `from` local def id, obtained using
541 /// `generics_def_id_map` field.
542 fn get_remapped_def_id(&self, local_def_id: LocalDefId) -> LocalDefId {
543 // `generics_def_id_map` is a stack of mappings. As we go deeper in impl traits nesting we
544 // push new mappings, so we first need to get the latest (innermost) mappings, hence `iter().rev()`.
548 // `fn test<'a, 'b>() -> impl Trait<&'a u8, Ty = impl Sized + 'b> {}`
550 // We would end with a generics_def_id_map like:
552 // `[[fn#'b -> impl_trait#'b], [fn#'b -> impl_sized#'b]]`
554 // for the opaque type generated on `impl Sized + 'b`, we want the result to be: impl_sized#'b.
555 // So, if we were trying to find first from the start (outermost) would give the wrong result, impl_trait#'b.
556 self.generics_def_id_map
559 .find_map(|map| map.get(&local_def_id).map(|local_def_id| *local_def_id))
560 .unwrap_or(local_def_id)
563 /// Freshen the `LoweringContext` and ready it to lower a nested item.
564 /// The lowered item is registered into `self.children`.
566 /// This function sets up `HirId` lowering infrastructure,
567 /// and stashes the shared mutable state to avoid pollution by the closure.
568 #[instrument(level = "debug", skip(self, f))]
569 fn with_hir_id_owner(
572 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
574 let def_id = self.local_def_id(owner);
576 let current_attrs = std::mem::take(&mut self.attrs);
577 let current_bodies = std::mem::take(&mut self.bodies);
578 let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
579 let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
580 let current_trait_map = std::mem::take(&mut self.trait_map);
582 std::mem::replace(&mut self.current_hir_id_owner, hir::OwnerId { def_id });
583 let current_local_counter =
584 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
585 let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
586 let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
588 // Do not reset `next_node_id` and `node_id_to_def_id`:
589 // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
590 // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
592 // Always allocate the first `HirId` for the owner itself.
593 let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
594 debug_assert_eq!(_old, None);
597 debug_assert_eq!(def_id, item.def_id().def_id);
598 // `f` should have consumed all the elements in these vectors when constructing `item`.
599 debug_assert!(self.impl_trait_defs.is_empty());
600 debug_assert!(self.impl_trait_bounds.is_empty());
601 let info = self.make_owner_info(item);
603 self.attrs = current_attrs;
604 self.bodies = current_bodies;
605 self.node_id_to_local_id = current_node_ids;
606 self.local_id_to_def_id = current_id_to_def_id;
607 self.trait_map = current_trait_map;
608 self.current_hir_id_owner = current_owner;
609 self.item_local_id_counter = current_local_counter;
610 self.impl_trait_defs = current_impl_trait_defs;
611 self.impl_trait_bounds = current_impl_trait_bounds;
613 debug_assert!(self.children.iter().find(|(id, _)| id == &def_id).is_none());
614 self.children.push((def_id, hir::MaybeOwner::Owner(info)));
617 /// Installs the remapping `remap` in scope while `f` is being executed.
618 /// This causes references to the `LocalDefId` keys to be changed to
619 /// refer to the values instead.
621 /// The remapping is used when one piece of AST expands to multiple
622 /// pieces of HIR. For example, the function `fn foo<'a>(...) -> impl Debug + 'a`,
623 /// expands to both a function definition (`foo`) and a TAIT for the return value,
624 /// both of which have a lifetime parameter `'a`. The remapping allows us to
625 /// rewrite the `'a` in the return value to refer to the
626 /// `'a` declared on the TAIT, instead of the function.
627 fn with_remapping<R>(
629 remap: FxHashMap<LocalDefId, LocalDefId>,
630 f: impl FnOnce(&mut Self) -> R,
632 self.generics_def_id_map.push(remap);
634 self.generics_def_id_map.pop();
638 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
639 let attrs = std::mem::take(&mut self.attrs);
640 let mut bodies = std::mem::take(&mut self.bodies);
641 let local_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
642 let trait_map = std::mem::take(&mut self.trait_map);
644 #[cfg(debug_assertions)]
645 for (id, attrs) in attrs.iter() {
646 // Verify that we do not store empty slices in the map.
647 if attrs.is_empty() {
648 panic!("Stored empty attributes for {:?}", id);
652 bodies.sort_by_key(|(k, _)| *k);
653 let bodies = SortedMap::from_presorted_elements(bodies);
654 let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
655 let (nodes, parenting) =
656 index::index_hir(self.tcx.sess, &*self.tcx.definitions_untracked(), node, &bodies);
657 let nodes = hir::OwnerNodes {
658 hash_including_bodies,
665 let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
666 let mut stable_hasher = StableHasher::new();
667 attrs.hash_stable(&mut hcx, &mut stable_hasher);
668 stable_hasher.finish()
670 hir::AttributeMap { map: attrs, hash }
673 self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map })
676 /// Hash the HIR node twice, one deep and one shallow hash. This allows to differentiate
677 /// queries which depend on the full HIR tree and those which only depend on the item signature.
680 node: hir::OwnerNode<'hir>,
681 bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
682 ) -> (Fingerprint, Fingerprint) {
683 self.tcx.with_stable_hashing_context(|mut hcx| {
684 let mut stable_hasher = StableHasher::new();
685 hcx.with_hir_bodies(node.def_id(), bodies, |hcx| {
686 node.hash_stable(hcx, &mut stable_hasher)
688 let hash_including_bodies = stable_hasher.finish();
689 let mut stable_hasher = StableHasher::new();
690 hcx.without_hir_bodies(|hcx| node.hash_stable(hcx, &mut stable_hasher));
691 let hash_without_bodies = stable_hasher.finish();
692 (hash_including_bodies, hash_without_bodies)
696 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
697 /// the `LoweringContext`'s `NodeId => HirId` map.
698 /// Take care not to call this method if the resulting `HirId` is then not
699 /// actually used in the HIR, as that would trigger an assertion in the
700 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
701 /// properly. Calling the method twice with the same `NodeId` is fine though.
702 #[instrument(level = "debug", skip(self), ret)]
703 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
704 assert_ne!(ast_node_id, DUMMY_NODE_ID);
706 match self.node_id_to_local_id.entry(ast_node_id) {
707 Entry::Occupied(o) => {
708 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
710 Entry::Vacant(v) => {
711 // Generate a new `HirId`.
712 let owner = self.current_hir_id_owner;
713 let local_id = self.item_local_id_counter;
714 let hir_id = hir::HirId { owner, local_id };
717 self.item_local_id_counter.increment_by(1);
719 assert_ne!(local_id, hir::ItemLocalId::new(0));
720 if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
721 self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
722 self.local_id_to_def_id.insert(local_id, def_id);
725 if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
726 self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
734 /// Generate a new `HirId` without a backing `NodeId`.
735 #[instrument(level = "debug", skip(self), ret)]
736 fn next_id(&mut self) -> hir::HirId {
737 let owner = self.current_hir_id_owner;
738 let local_id = self.item_local_id_counter;
739 assert_ne!(local_id, hir::ItemLocalId::new(0));
740 self.item_local_id_counter.increment_by(1);
741 hir::HirId { owner, local_id }
744 #[instrument(level = "trace", skip(self))]
745 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
746 let res: Result<Res, ()> = res.apply_id(|id| {
747 let owner = self.current_hir_id_owner;
748 let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
749 Ok(hir::HirId { owner, local_id })
753 // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
754 // This can happen when trying to lower the return type `x` in erroneous code like
755 // async fn foo(x: u8) -> x {}
756 // In that case, `x` is lowered as a function parameter, and the return type is lowered as
757 // an opaque type as a synthesized HIR owner.
758 res.unwrap_or(Res::Err)
761 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
762 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
765 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
766 self.resolver.get_import_res(id).present_items()
769 fn diagnostic(&self) -> &Handler {
770 self.tcx.sess.diagnostic()
773 /// Reuses the span but adds information like the kind of the desugaring and features that are
774 /// allowed inside this span.
775 fn mark_span_with_reason(
777 reason: DesugaringKind,
779 allow_internal_unstable: Option<Lrc<[Symbol]>>,
781 self.tcx.with_stable_hashing_context(|hcx| {
782 span.mark_with_reason(allow_internal_unstable, reason, self.tcx.sess.edition(), hcx)
786 /// Intercept all spans entering HIR.
787 /// Mark a span as relative to the current owning item.
788 fn lower_span(&self, span: Span) -> Span {
789 if self.tcx.sess.opts.unstable_opts.incremental_relative_spans {
790 span.with_parent(Some(self.current_hir_id_owner.def_id))
792 // Do not make spans relative when not using incremental compilation.
797 fn lower_ident(&self, ident: Ident) -> Ident {
798 Ident::new(ident.name, self.lower_span(ident.span))
801 /// Converts a lifetime into a new generic parameter.
802 #[instrument(level = "debug", skip(self))]
803 fn lifetime_res_to_generic_param(
808 ) -> Option<hir::GenericParam<'hir>> {
809 let (name, kind) = match res {
810 LifetimeRes::Param { .. } => {
811 (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
813 LifetimeRes::Fresh { param, .. } => {
814 // Late resolution delegates to us the creation of the `LocalDefId`.
815 let _def_id = self.create_def(
816 self.current_hir_id_owner.def_id,
818 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
822 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
824 LifetimeRes::Static | LifetimeRes::Error => return None,
826 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
827 res, ident, ident.span
830 let hir_id = self.lower_node_id(node_id);
831 let def_id = self.local_def_id(node_id);
832 Some(hir::GenericParam {
836 span: self.lower_span(ident.span),
837 pure_wrt_drop: false,
838 kind: hir::GenericParamKind::Lifetime { kind },
843 /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
844 /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
845 /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
846 /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
847 /// parameters will be successful.
848 #[instrument(level = "debug", skip(self))]
850 fn lower_lifetime_binder(
853 generic_params: &[GenericParam],
854 ) -> &'hir [hir::GenericParam<'hir>] {
855 let mut generic_params: Vec<_> = self.lower_generic_params_mut(generic_params).collect();
856 let extra_lifetimes = self.resolver.take_extra_lifetime_params(binder);
857 debug!(?extra_lifetimes);
858 generic_params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
859 self.lifetime_res_to_generic_param(ident, node_id, res)
861 let generic_params = self.arena.alloc_from_iter(generic_params);
862 debug!(?generic_params);
867 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
868 let was_in_dyn_type = self.is_in_dyn_type;
869 self.is_in_dyn_type = in_scope;
871 let result = f(self);
873 self.is_in_dyn_type = was_in_dyn_type;
878 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
879 let was_in_loop_condition = self.is_in_loop_condition;
880 self.is_in_loop_condition = false;
882 let catch_scope = self.catch_scope.take();
883 let loop_scope = self.loop_scope.take();
885 self.catch_scope = catch_scope;
886 self.loop_scope = loop_scope;
888 self.is_in_loop_condition = was_in_loop_condition;
893 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
894 if attrs.is_empty() {
897 debug_assert_eq!(id.owner, self.current_hir_id_owner);
898 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
899 debug_assert!(!ret.is_empty());
900 self.attrs.insert(id.local_id, ret);
905 fn lower_attr(&self, attr: &Attribute) -> Attribute {
906 // Note that we explicitly do not walk the path. Since we don't really
907 // lower attributes (we use the AST version) there is nowhere to keep
908 // the `HirId`s. We don't actually need HIR version of attributes anyway.
909 // Tokens are also not needed after macro expansion and parsing.
910 let kind = match attr.kind {
911 AttrKind::Normal(ref normal) => AttrKind::Normal(P(NormalAttr {
913 path: normal.item.path.clone(),
914 args: self.lower_attr_args(&normal.item.args),
919 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
922 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
925 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
926 debug_assert_eq!(id.owner, self.current_hir_id_owner);
927 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
928 if let Some(&a) = self.attrs.get(&target_id.local_id) {
929 debug_assert!(!a.is_empty());
930 self.attrs.insert(id.local_id, a);
934 fn lower_attr_args(&self, args: &AttrArgs) -> AttrArgs {
936 AttrArgs::Empty => AttrArgs::Empty,
937 AttrArgs::Delimited(args) => AttrArgs::Delimited(self.lower_delim_args(args)),
938 // This is an inert key-value attribute - it will never be visible to macros
939 // after it gets lowered to HIR. Therefore, we can extract literals to handle
940 // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
941 AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => {
942 // In valid code the value always ends up as a single literal. Otherwise, a dummy
943 // literal suffices because the error is handled elsewhere.
944 let lit = if let ExprKind::Lit(token_lit) = expr.kind {
945 match Lit::from_token_lit(token_lit, expr.span) {
948 token_lit: token::Lit::new(token::LitKind::Err, kw::Empty, None),
955 token_lit: token::Lit::new(token::LitKind::Err, kw::Empty, None),
960 AttrArgs::Eq(*eq_span, AttrArgsEq::Hir(lit))
962 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
963 unreachable!("in literal form when lowering mac args eq: {:?}", lit)
968 fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
969 DelimArgs { dspan: args.dspan, delim: args.delim, tokens: args.tokens.flattened() }
972 /// Given an associated type constraint like one of these:
974 /// ```ignore (illustrative)
975 /// T: Iterator<Item: Debug>
977 /// T: Iterator<Item = Debug>
981 /// returns a `hir::TypeBinding` representing `Item`.
982 #[instrument(level = "debug", skip(self))]
983 fn lower_assoc_ty_constraint(
985 constraint: &AssocConstraint,
986 itctx: &ImplTraitContext,
987 ) -> hir::TypeBinding<'hir> {
988 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
989 // lower generic arguments of identifier in constraint
990 let gen_args = if let Some(gen_args) = &constraint.gen_args {
991 let gen_args_ctor = match gen_args {
992 GenericArgs::AngleBracketed(data) => {
993 self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
995 GenericArgs::Parenthesized(data) => {
996 self.emit_bad_parenthesized_trait_in_assoc_ty(data);
997 let aba = self.ast_arena.aba.alloc(data.as_angle_bracketed_args());
998 self.lower_angle_bracketed_parameter_data(aba, ParamMode::Explicit, itctx).0
1001 gen_args_ctor.into_generic_args(self)
1003 self.arena.alloc(hir::GenericArgs::none())
1005 let itctx_tait = &ImplTraitContext::TypeAliasesOpaqueTy;
1007 let kind = match &constraint.kind {
1008 AssocConstraintKind::Equality { term } => {
1009 let term = match term {
1010 Term::Ty(ty) => self.lower_ty(ty, itctx).into(),
1011 Term::Const(c) => self.lower_anon_const(c).into(),
1013 hir::TypeBindingKind::Equality { term }
1015 AssocConstraintKind::Bound { bounds } => {
1016 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1017 let (desugar_to_impl_trait, itctx) = match itctx {
1018 // We are in the return position:
1020 // fn foo() -> impl Iterator<Item: Debug>
1024 // fn foo() -> impl Iterator<Item = impl Debug>
1025 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1026 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
1028 // We are in the argument position, but within a dyn type:
1030 // fn foo(x: dyn Iterator<Item: Debug>)
1034 // fn foo(x: dyn Iterator<Item = impl Debug>)
1035 ImplTraitContext::Universal if self.is_in_dyn_type => (true, itctx),
1037 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1038 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1039 // "impl trait context" to permit `impl Debug` in this position (it desugars
1040 // then to an opaque type).
1042 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1043 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => (true, itctx_tait),
1045 // We are in the parameter position, but not within a dyn type:
1047 // fn foo(x: impl Iterator<Item: Debug>)
1049 // so we leave it as is and this gets expanded in astconv to a bound like
1050 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1052 _ => (false, itctx),
1055 if desugar_to_impl_trait {
1056 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1057 // constructing the HIR for `impl bounds...` and then lowering that.
1059 let impl_trait_node_id = self.next_node_id();
1061 self.with_dyn_type_scope(false, |this| {
1062 let node_id = this.next_node_id();
1063 let ty = this.ast_arena.tys.alloc(Ty {
1065 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1066 span: this.lower_span(constraint.span),
1069 let ty = this.lower_ty(ty, itctx);
1071 hir::TypeBindingKind::Equality { term: ty.into() }
1074 // Desugar `AssocTy: Bounds` into a type binding where the
1075 // later desugars into a trait predicate.
1076 let bounds = self.lower_param_bounds(bounds, itctx);
1078 hir::TypeBindingKind::Constraint { bounds }
1084 hir_id: self.lower_node_id(constraint.id),
1085 ident: self.lower_ident(constraint.ident),
1088 span: self.lower_span(constraint.span),
1092 fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1093 // Suggest removing empty parentheses: "Trait()" -> "Trait"
1094 let sub = if data.inputs.is_empty() {
1095 let parentheses_span =
1096 data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1097 AssocTyParenthesesSub::Empty { parentheses_span }
1099 // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1101 // Start of parameters to the 1st argument
1102 let open_param = data.inputs_span.shrink_to_lo().to(data
1108 // End of last argument to end of parameters
1110 data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1111 AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1113 self.tcx.sess.emit_err(AssocTyParentheses { span: data.span, sub });
1116 #[instrument(level = "debug", skip(self))]
1117 fn lower_generic_arg(
1119 arg: &ast::GenericArg,
1120 itctx: &ImplTraitContext,
1121 ) -> hir::GenericArg<'hir> {
1123 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1124 ast::GenericArg::Type(ty) => {
1126 TyKind::Infer if self.tcx.features().generic_arg_infer => {
1127 return GenericArg::Infer(hir::InferArg {
1128 hir_id: self.lower_node_id(ty.id),
1129 span: self.lower_span(ty.span),
1132 // We parse const arguments as path types as we cannot distinguish them during
1133 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1134 // type and value namespaces. If we resolved the path in the value namespace, we
1135 // transform it into a generic const argument.
1136 TyKind::Path(qself, path) => {
1137 if let Some(res) = self
1139 .get_partial_res(ty.id)
1140 .and_then(|partial_res| partial_res.full_res())
1142 if !res.matches_ns(Namespace::TypeNS) {
1144 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1148 // Construct an AnonConst where the expr is the "ty"'s path.
1150 let parent_def_id = self.current_hir_id_owner;
1151 let node_id = self.next_node_id();
1153 // Add a definition for the in-band const def.
1154 let def_id = self.create_def(
1155 parent_def_id.def_id,
1157 DefPathData::AnonConst,
1160 let span = self.lower_span(ty.span);
1161 let path_expr = Expr {
1163 kind: ExprKind::Path(qself.clone(), path.clone()),
1165 attrs: AttrVec::new(),
1169 let ct = self.with_new_scopes(|this| hir::AnonConst {
1171 hir_id: this.lower_node_id(node_id),
1172 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1174 return GenericArg::Const(ConstArg { value: ct, span });
1180 GenericArg::Type(self.lower_ty(&ty, itctx))
1182 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1183 value: self.lower_anon_const(&ct),
1184 span: self.lower_span(ct.value.span),
1189 #[instrument(level = "debug", skip(self))]
1190 fn lower_ty(&mut self, t: &Ty, itctx: &ImplTraitContext) -> &'hir hir::Ty<'hir> {
1191 self.arena.alloc(self.lower_ty_direct(t, itctx))
1197 qself: &Option<ptr::P<QSelf>>,
1199 param_mode: ParamMode,
1200 itctx: &ImplTraitContext,
1201 ) -> hir::Ty<'hir> {
1202 // Check whether we should interpret this as a bare trait object.
1203 // This check mirrors the one in late resolution. We only introduce this special case in
1204 // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1205 // The other cases when a qpath should be opportunistically made a trait object are handled
1208 && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1209 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1211 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1212 let poly_trait_ref = this.ast_arena.ptr.alloc(PolyTraitRef {
1213 bound_generic_params: vec![],
1214 trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1217 let bound = this.lower_poly_trait_ref(
1221 let bounds = this.arena.alloc_from_iter([bound]);
1222 let lifetime_bound = this.elided_dyn_bound(t.span);
1223 (bounds, lifetime_bound)
1225 let kind = hir::TyKind::TraitObject(bounds, &lifetime_bound, TraitObjectSyntax::None);
1226 return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1229 let id = self.lower_node_id(t.id);
1230 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1231 self.ty_path(id, t.span, qpath)
1234 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1235 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1238 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1239 self.ty(span, hir::TyKind::Tup(tys))
1242 fn lower_ty_direct(&mut self, t: &Ty, itctx: &ImplTraitContext) -> hir::Ty<'hir> {
1243 let kind = match &t.kind {
1244 TyKind::Infer => hir::TyKind::Infer,
1245 TyKind::Err => hir::TyKind::Err,
1246 TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1247 TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1248 TyKind::Rptr(region, mt) => {
1249 let region = region.unwrap_or_else(|| {
1250 let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1251 self.resolver.get_lifetime_res(t.id)
1253 debug_assert_eq!(start.plus(1), end);
1258 let span = self.tcx.sess.source_map().start_point(t.span);
1259 Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1261 let lifetime = self.lower_lifetime(®ion);
1262 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1264 TyKind::BareFn(f) => {
1265 let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1266 hir::TyKind::BareFn(self.arena.alloc(hir::BareFnTy {
1268 unsafety: self.lower_unsafety(f.unsafety),
1269 abi: self.lower_extern(f.ext),
1270 decl: self.lower_fn_decl(&f.decl, None, t.span, FnDeclKind::Pointer, None),
1271 param_names: self.lower_fn_params_to_names(&f.decl),
1274 TyKind::Never => hir::TyKind::Never,
1275 TyKind::Tup(tys) => hir::TyKind::Tup(
1276 self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty_direct(ty, itctx))),
1278 TyKind::Paren(ty) => {
1279 return self.lower_ty_direct(ty, itctx);
1281 TyKind::Path(qself, path) => {
1282 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1284 TyKind::ImplicitSelf => {
1285 let hir_id = self.next_id();
1286 let res = self.expect_full_res(t.id);
1287 let res = self.lower_res(res);
1288 hir::TyKind::Path(hir::QPath::Resolved(
1290 self.arena.alloc(hir::Path {
1292 segments: arena_vec![self; hir::PathSegment::new(
1293 Ident::with_dummy_span(kw::SelfUpper),
1297 span: self.lower_span(t.span),
1301 TyKind::Array(ty, length) => {
1302 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1304 TyKind::Typeof(expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1305 TyKind::TraitObject(bounds, kind) => {
1306 let mut lifetime_bound = None;
1307 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1309 this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1310 GenericBound::Trait(
1312 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1313 ) => Some(this.lower_poly_trait_ref(ty, itctx)),
1314 // `~const ?Bound` will cause an error during AST validation
1315 // anyways, so treat it like `?Bound` as compilation proceeds.
1316 GenericBound::Trait(
1318 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1320 GenericBound::Outlives(lifetime) => {
1321 if lifetime_bound.is_none() {
1322 lifetime_bound = Some(this.lower_lifetime(lifetime));
1327 let lifetime_bound =
1328 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1329 (bounds, lifetime_bound)
1331 hir::TyKind::TraitObject(bounds, lifetime_bound, *kind)
1333 TyKind::ImplTrait(def_node_id, bounds) => {
1336 ImplTraitContext::ReturnPositionOpaqueTy { origin, in_trait } => self
1337 .lower_opaque_impl_trait(
1345 ImplTraitContext::TypeAliasesOpaqueTy => self.lower_opaque_impl_trait(
1347 hir::OpaqueTyOrigin::TyAlias,
1353 ImplTraitContext::Universal => {
1355 self.current_hir_id_owner.def_id,
1357 DefPathData::ImplTrait,
1360 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1361 let (param, bounds, path) =
1362 self.lower_generic_and_bounds(*def_node_id, span, ident, bounds);
1363 self.impl_trait_defs.push(param);
1364 if let Some(bounds) = bounds {
1365 self.impl_trait_bounds.push(bounds);
1369 ImplTraitContext::Disallowed(
1370 position @ (ImplTraitPosition::TraitReturn | ImplTraitPosition::ImplReturn),
1374 .create_feature_err(
1375 MisplacedImplTrait {
1377 position: DiagnosticArgFromDisplay(&position),
1379 sym::return_position_impl_trait_in_trait,
1384 ImplTraitContext::Disallowed(position) => {
1385 self.tcx.sess.emit_err(MisplacedImplTrait {
1387 position: DiagnosticArgFromDisplay(&position),
1393 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1394 TyKind::CVarArgs => {
1395 self.tcx.sess.delay_span_bug(
1397 "`TyKind::CVarArgs` should have been handled elsewhere",
1403 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1406 /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1407 /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1408 /// HIR type that references the TAIT.
1410 /// Given a function definition like:
1413 /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1418 /// we will create a TAIT definition in the HIR like
1421 /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1424 /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1427 /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1430 /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1431 /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1432 /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1433 /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1434 /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1435 #[instrument(level = "debug", skip(self), ret)]
1436 fn lower_opaque_impl_trait(
1439 origin: hir::OpaqueTyOrigin,
1440 opaque_ty_node_id: NodeId,
1441 bounds: &GenericBounds,
1443 itctx: &ImplTraitContext,
1444 ) -> hir::TyKind<'hir> {
1445 // Make sure we know that some funky desugaring has been going on here.
1446 // This is a first: there is code in other places like for loop
1447 // desugaring that explicitly states that we don't want to track that.
1448 // Not tracking it makes lints in rustc and clippy very fragile, as
1449 // frequently opened issues show.
1450 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1452 let opaque_ty_def_id = self.create_def(
1453 self.current_hir_id_owner.def_id,
1455 DefPathData::ImplTrait,
1457 debug!(?opaque_ty_def_id);
1459 // Contains the new lifetime definitions created for the TAIT (if any).
1460 let mut collected_lifetimes = Vec::new();
1462 // If this came from a TAIT (as opposed to a function that returns an RPIT), we only want
1463 // to capture the lifetimes that appear in the bounds. So visit the bounds to find out
1464 // exactly which ones those are.
1465 let lifetimes_to_remap = if origin == hir::OpaqueTyOrigin::TyAlias {
1466 // in a TAIT like `type Foo<'a> = impl Foo<'a>`, we don't keep all the lifetime parameters
1469 // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1470 // we only keep the lifetimes that appear in the `impl Debug` itself:
1471 lifetime_collector::lifetimes_in_bounds(&self.resolver, bounds)
1473 debug!(?lifetimes_to_remap);
1475 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1476 let mut new_remapping = FxHashMap::default();
1478 // If this opaque type is only capturing a subset of the lifetimes (those that appear
1479 // in bounds), then create the new lifetime parameters required and create a mapping
1480 // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1481 collected_lifetimes = lctx.create_lifetime_defs(
1483 &lifetimes_to_remap,
1486 debug!(?collected_lifetimes);
1487 debug!(?new_remapping);
1489 // Install the remapping from old to new (if any):
1490 lctx.with_remapping(new_remapping, |lctx| {
1491 // This creates HIR lifetime definitions as `hir::GenericParam`, in the given
1492 // example `type TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection
1493 // containing `&['x]`.
1494 let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1495 |&(new_node_id, lifetime)| {
1496 let hir_id = lctx.lower_node_id(new_node_id);
1497 debug_assert_ne!(lctx.opt_local_def_id(new_node_id), None);
1499 let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1500 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1503 hir::ParamName::Plain(lifetime.ident),
1504 hir::LifetimeParamKind::Explicit,
1510 def_id: lctx.local_def_id(new_node_id),
1512 span: lifetime.ident.span,
1513 pure_wrt_drop: false,
1514 kind: hir::GenericParamKind::Lifetime { kind },
1519 debug!(?lifetime_defs);
1521 // Then when we lower the param bounds, references to 'a are remapped to 'a1, so we
1522 // get back Debug + 'a1, which is suitable for use on the TAIT.
1523 let hir_bounds = lctx.lower_param_bounds(bounds, itctx);
1524 debug!(?hir_bounds);
1526 let opaque_ty_item = hir::OpaqueTy {
1527 generics: self.arena.alloc(hir::Generics {
1528 params: lifetime_defs,
1530 has_where_clause_predicates: false,
1531 where_clause_span: lctx.lower_span(span),
1532 span: lctx.lower_span(span),
1538 debug!(?opaque_ty_item);
1540 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1544 // This creates HIR lifetime arguments as `hir::GenericArg`, in the given example `type
1545 // TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection containing `&['x]`.
1547 self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(_, lifetime)| {
1548 let id = self.next_node_id();
1549 let span = lifetime.ident.span;
1551 let ident = if lifetime.ident.name == kw::UnderscoreLifetime {
1552 Ident::with_dummy_span(kw::UnderscoreLifetime)
1557 let l = self.new_named_lifetime(lifetime.id, id, span, ident);
1558 hir::GenericArg::Lifetime(l)
1562 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1563 hir::TyKind::OpaqueDef(
1564 hir::ItemId { owner_id: hir::OwnerId { def_id: opaque_ty_def_id } },
1570 /// Registers a new opaque type with the proper `NodeId`s and
1571 /// returns the lowered node-ID for the opaque type.
1572 fn generate_opaque_type(
1574 opaque_ty_id: LocalDefId,
1575 opaque_ty_item: hir::OpaqueTy<'hir>,
1577 opaque_ty_span: Span,
1578 ) -> hir::OwnerNode<'hir> {
1579 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1580 // Generate an `type Foo = impl Trait;` declaration.
1581 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1582 let opaque_ty_item = hir::Item {
1583 owner_id: hir::OwnerId { def_id: opaque_ty_id },
1584 ident: Ident::empty(),
1585 kind: opaque_ty_item_kind,
1586 vis_span: self.lower_span(span.shrink_to_lo()),
1587 span: self.lower_span(opaque_ty_span),
1589 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1592 /// Given a `parent_def_id`, a list of `lifetimes_in_bounds and a `remapping` hash to be
1593 /// filled, this function creates new definitions for `Param` and `Fresh` lifetimes, inserts the
1594 /// new definition, adds it to the remapping with the definition of the given lifetime and
1595 /// returns a list of lifetimes to be lowered afterwards.
1596 fn create_lifetime_defs(
1598 parent_def_id: LocalDefId,
1599 lifetimes_in_bounds: &[Lifetime],
1600 remapping: &mut FxHashMap<LocalDefId, LocalDefId>,
1601 ) -> Vec<(NodeId, Lifetime)> {
1602 let mut result = Vec::new();
1604 for lifetime in lifetimes_in_bounds {
1605 let res = self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error);
1609 LifetimeRes::Param { param: old_def_id, binder: _ } => {
1610 if remapping.get(&old_def_id).is_none() {
1611 let node_id = self.next_node_id();
1613 let new_def_id = self.create_def(
1616 DefPathData::LifetimeNs(lifetime.ident.name),
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),
1634 remapping.insert(old_def_id, new_def_id);
1636 result.push((node_id, *lifetime));
1640 LifetimeRes::Static | LifetimeRes::Error => {}
1643 let bug_msg = format!(
1644 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1645 res, lifetime.ident, lifetime.ident.span
1647 span_bug!(lifetime.ident.span, "{}", bug_msg);
1655 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1656 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1657 // as they are not explicit in HIR/Ty function signatures.
1658 // (instead, the `c_variadic` flag is set to `true`)
1659 let mut inputs = &decl.inputs[..];
1660 if decl.c_variadic() {
1661 inputs = &inputs[..inputs.len() - 1];
1663 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1664 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1665 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1669 // Lowers a function declaration.
1671 // `decl`: the unlowered (AST) function declaration.
1672 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1673 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1674 // `make_ret_async` is also `Some`.
1675 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1676 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1677 // return type `impl Trait` item, and the `Span` points to the `async` keyword.
1678 #[instrument(level = "debug", skip(self))]
1682 fn_node_id: Option<NodeId>,
1685 make_ret_async: Option<(NodeId, Span)>,
1686 ) -> &'hir hir::FnDecl<'hir> {
1687 let c_variadic = decl.c_variadic();
1689 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1690 // as they are not explicit in HIR/Ty function signatures.
1691 // (instead, the `c_variadic` flag is set to `true`)
1692 let mut inputs = &decl.inputs[..];
1694 inputs = &inputs[..inputs.len() - 1];
1696 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1697 if fn_node_id.is_some() {
1698 self.lower_ty_direct(¶m.ty, &ImplTraitContext::Universal)
1700 self.lower_ty_direct(
1702 &ImplTraitContext::Disallowed(match kind {
1703 FnDeclKind::Fn | FnDeclKind::Inherent => {
1704 unreachable!("fn should allow in-band lifetimes")
1706 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1707 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1708 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1709 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1710 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1716 let output = if let Some((ret_id, span)) = make_ret_async {
1717 if !kind.async_fn_allowed(self.tcx) {
1719 FnDeclKind::Trait | FnDeclKind::Impl => {
1722 .create_feature_err(
1723 TraitFnAsync { fn_span, span },
1724 sym::async_fn_in_trait,
1729 self.tcx.sess.emit_err(TraitFnAsync { fn_span, span });
1734 self.lower_async_fn_ret_ty(
1736 fn_node_id.expect("`make_ret_async` but no `fn_def_id`"),
1738 matches!(kind, FnDeclKind::Trait),
1741 match &decl.output {
1742 FnRetTy::Ty(ty) => {
1743 let mut context = match fn_node_id {
1744 Some(fn_node_id) if kind.impl_trait_allowed(self.tcx) => {
1745 let fn_def_id = self.local_def_id(fn_node_id);
1746 ImplTraitContext::ReturnPositionOpaqueTy {
1747 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1748 in_trait: matches!(kind, FnDeclKind::Trait),
1751 _ => ImplTraitContext::Disallowed(match kind {
1752 FnDeclKind::Fn | FnDeclKind::Inherent => {
1753 unreachable!("fn should allow in-band lifetimes")
1755 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1756 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1757 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1758 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1759 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1762 hir::FnRetTy::Return(self.lower_ty(ty, &mut context))
1764 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1768 self.arena.alloc(hir::FnDecl {
1772 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1773 let is_mutable_pat = matches!(
1775 PatKind::Ident(hir::BindingAnnotation(_, Mutability::Mut), ..)
1778 match &arg.ty.kind {
1779 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1780 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1781 // Given we are only considering `ImplicitSelf` types, we needn't consider
1782 // the case where we have a mutable pattern to a reference as that would
1783 // no longer be an `ImplicitSelf`.
1785 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1787 hir::ImplicitSelfKind::MutRef
1789 TyKind::Rptr(_, mt) if mt.ty.kind.is_implicit_self() => {
1790 hir::ImplicitSelfKind::ImmRef
1792 _ => hir::ImplicitSelfKind::None,
1798 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1799 // combined with the following definition of `OpaqueTy`:
1801 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1803 // `output`: unlowered output type (`T` in `-> T`)
1804 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1805 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1806 #[instrument(level = "debug", skip(self))]
1807 fn lower_async_fn_ret_ty(
1811 opaque_ty_node_id: NodeId,
1813 ) -> hir::FnRetTy<'hir> {
1814 let span = output.span();
1816 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1818 let fn_def_id = self.local_def_id(fn_node_id);
1820 let opaque_ty_def_id =
1821 self.create_def(fn_def_id, opaque_ty_node_id, DefPathData::ImplTrait);
1823 // When we create the opaque type for this async fn, it is going to have
1824 // to capture all the lifetimes involved in the signature (including in the
1825 // return type). This is done by introducing lifetime parameters for:
1827 // - all the explicitly declared lifetimes from the impl and function itself;
1828 // - all the elided lifetimes in the fn arguments;
1829 // - all the elided lifetimes in the return type.
1831 // So for example in this snippet:
1834 // impl<'a> Foo<'a> {
1835 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1836 // // ^ '0 ^ '1 ^ '2
1837 // // elided lifetimes used below
1842 // we would create an opaque type like:
1845 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1848 // and we would then desugar `bar` to the equivalent of:
1851 // impl<'a> Foo<'a> {
1852 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1856 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1857 // this is because the elided lifetimes from the return type
1858 // should be figured out using the ordinary elision rules, and
1859 // this desugaring achieves that.
1861 // Calculate all the lifetimes that should be captured
1862 // by the opaque type. This should include all in-scope
1863 // lifetime parameters, including those defined in-band.
1865 // Contains the new lifetime definitions created for the TAIT (if any) generated for the
1867 let mut collected_lifetimes = Vec::new();
1868 let mut new_remapping = FxHashMap::default();
1870 let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1871 debug!(?extra_lifetime_params);
1872 for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1873 let outer_def_id = self.orig_local_def_id(outer_node_id);
1874 let inner_node_id = self.next_node_id();
1876 // Add a definition for the in scope lifetime def.
1877 let inner_def_id = self.create_def(
1880 DefPathData::LifetimeNs(ident.name),
1882 new_remapping.insert(outer_def_id, inner_def_id);
1884 let inner_res = match outer_res {
1885 // Input lifetime like `'a`:
1886 LifetimeRes::Param { param, .. } => {
1887 LifetimeRes::Param { param, binder: fn_node_id }
1889 // Input lifetime like `'1`:
1890 LifetimeRes::Fresh { param, .. } => {
1891 LifetimeRes::Fresh { param, binder: fn_node_id }
1893 LifetimeRes::Static | LifetimeRes::Error => continue,
1896 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1897 res, ident, ident.span
1902 let lifetime = Lifetime { id: outer_node_id, ident };
1903 collected_lifetimes.push((inner_node_id, lifetime, Some(inner_res)));
1906 debug!(?collected_lifetimes);
1908 // We only want to capture the lifetimes that appear in the bounds. So visit the bounds to
1909 // find out exactly which ones those are.
1910 // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1911 // we only keep the lifetimes that appear in the `impl Debug` itself:
1912 let lifetimes_to_remap = lifetime_collector::lifetimes_in_ret_ty(&self.resolver, output);
1913 debug!(?lifetimes_to_remap);
1915 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1916 // If this opaque type is only capturing a subset of the lifetimes (those that appear
1917 // in bounds), then create the new lifetime parameters required and create a mapping
1918 // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1919 collected_lifetimes.extend(
1920 this.create_lifetime_defs(
1922 &lifetimes_to_remap,
1926 .map(|(new_node_id, lifetime)| (new_node_id, lifetime, None)),
1928 debug!(?collected_lifetimes);
1929 debug!(?new_remapping);
1931 // Install the remapping from old to new (if any):
1932 this.with_remapping(new_remapping, |this| {
1933 // We have to be careful to get elision right here. The
1934 // idea is that we create a lifetime parameter for each
1935 // lifetime in the return type. So, given a return type
1936 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1937 // Future<Output = &'1 [ &'2 u32 ]>`.
1939 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1940 // hence the elision takes place at the fn site.
1941 let future_bound = this.lower_async_fn_output_type_to_future_bound(
1944 if in_trait && !this.tcx.features().return_position_impl_trait_in_trait {
1945 ImplTraitContext::Disallowed(ImplTraitPosition::TraitReturn)
1947 ImplTraitContext::ReturnPositionOpaqueTy {
1948 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1954 let generic_params = this.arena.alloc_from_iter(collected_lifetimes.iter().map(
1955 |&(new_node_id, lifetime, _)| {
1956 let hir_id = this.lower_node_id(new_node_id);
1957 debug_assert_ne!(this.opt_local_def_id(new_node_id), None);
1959 let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1960 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1963 hir::ParamName::Plain(lifetime.ident),
1964 hir::LifetimeParamKind::Explicit,
1970 def_id: this.local_def_id(new_node_id),
1972 span: lifetime.ident.span,
1973 pure_wrt_drop: false,
1974 kind: hir::GenericParamKind::Lifetime { kind },
1979 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1981 let opaque_ty_item = hir::OpaqueTy {
1982 generics: this.arena.alloc(hir::Generics {
1983 params: generic_params,
1985 has_where_clause_predicates: false,
1986 where_clause_span: this.lower_span(span),
1987 span: this.lower_span(span),
1989 bounds: arena_vec![this; future_bound],
1990 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1994 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1995 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1999 // As documented above, we need to create the lifetime
2000 // arguments to our opaque type. Continuing with our example,
2001 // we're creating the type arguments for the return type:
2004 // Bar<'a, 'b, '0, '1, '_>
2007 // For the "input" lifetime parameters, we wish to create
2008 // references to the parameters themselves, including the
2009 // "implicit" ones created from parameter types (`'a`, `'b`,
2012 // For the "output" lifetime parameters, we just want to
2014 let generic_args = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
2015 |(_, lifetime, res)| {
2016 let id = self.next_node_id();
2017 let span = lifetime.ident.span;
2019 let ident = if lifetime.ident.name == kw::UnderscoreLifetime {
2020 Ident::with_dummy_span(kw::UnderscoreLifetime)
2025 let res = res.unwrap_or(
2026 self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error),
2028 hir::GenericArg::Lifetime(self.new_named_lifetime_with_res(id, span, ident, res))
2032 // Create the `Foo<...>` reference itself. Note that the `type
2033 // Foo = impl Trait` is, internally, created as a child of the
2034 // async fn, so the *type parameters* are inherited. It's
2035 // only the lifetime parameters that we must supply.
2036 let opaque_ty_ref = hir::TyKind::OpaqueDef(
2037 hir::ItemId { owner_id: hir::OwnerId { def_id: opaque_ty_def_id } },
2041 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2042 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2045 /// Transforms `-> T` into `Future<Output = T>`.
2046 fn lower_async_fn_output_type_to_future_bound(
2050 mut nested_impl_trait_context: ImplTraitContext,
2051 ) -> hir::GenericBound<'hir> {
2052 // Compute the `T` in `Future<Output = T>` from the return type.
2053 let output_ty = match output {
2054 FnRetTy::Ty(ty) => {
2055 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2056 // `impl Future` opaque type that `async fn` implicitly
2058 self.lower_ty(ty, &mut nested_impl_trait_context)
2060 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2064 let future_args = self.arena.alloc(hir::GenericArgs {
2066 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
2067 parenthesized: false,
2071 hir::GenericBound::LangItemTrait(
2072 // ::std::future::Future<future_params>
2073 hir::LangItem::Future,
2074 self.lower_span(span),
2080 #[instrument(level = "trace", skip(self))]
2081 fn lower_param_bound(
2084 itctx: &ImplTraitContext,
2085 ) -> hir::GenericBound<'hir> {
2087 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
2088 self.lower_poly_trait_ref(p, itctx),
2089 self.lower_trait_bound_modifier(*modifier),
2091 GenericBound::Outlives(lifetime) => {
2092 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2097 fn lower_lifetime(&mut self, l: &Lifetime) -> &'hir hir::Lifetime {
2098 let span = self.lower_span(l.ident.span);
2099 let ident = self.lower_ident(l.ident);
2100 self.new_named_lifetime(l.id, l.id, span, ident)
2103 #[instrument(level = "debug", skip(self))]
2104 fn new_named_lifetime_with_res(
2110 ) -> &'hir hir::Lifetime {
2111 let name = match res {
2112 LifetimeRes::Param { param, .. } => {
2113 let p_name = ParamName::Plain(ident);
2114 let param = self.get_remapped_def_id(param);
2116 hir::LifetimeName::Param(param, p_name)
2118 LifetimeRes::Fresh { param, .. } => {
2119 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2120 let param = self.local_def_id(param);
2122 hir::LifetimeName::Param(param, ParamName::Fresh)
2124 LifetimeRes::Infer => hir::LifetimeName::Infer,
2125 LifetimeRes::Static => hir::LifetimeName::Static,
2126 LifetimeRes::Error => hir::LifetimeName::Error,
2127 res => panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span),
2131 self.arena.alloc(hir::Lifetime {
2132 hir_id: self.lower_node_id(id),
2133 span: self.lower_span(span),
2138 #[instrument(level = "debug", skip(self))]
2139 fn new_named_lifetime(
2145 ) -> &'hir hir::Lifetime {
2146 let res = self.resolver.get_lifetime_res(id).unwrap_or(LifetimeRes::Error);
2147 self.new_named_lifetime_with_res(new_id, span, ident, res)
2150 fn lower_generic_params_mut<'s>(
2152 params: &'s [GenericParam],
2153 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2154 params.iter().map(move |param| self.lower_generic_param(param))
2157 fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
2158 self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
2161 #[instrument(level = "trace", skip(self))]
2162 fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
2163 let (name, kind) = self.lower_generic_param_kind(param);
2165 let hir_id = self.lower_node_id(param.id);
2166 self.lower_attrs(hir_id, ¶m.attrs);
2169 def_id: self.local_def_id(param.id),
2171 span: self.lower_span(param.span()),
2172 pure_wrt_drop: self.tcx.sess.contains_name(¶m.attrs, sym::may_dangle),
2174 colon_span: param.colon_span.map(|s| self.lower_span(s)),
2178 fn lower_generic_param_kind(
2180 param: &GenericParam,
2181 ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2183 GenericParamKind::Lifetime => {
2184 // AST resolution emitted an error on those parameters, so we lower them using
2185 // `ParamName::Error`.
2187 if let Some(LifetimeRes::Error) = self.resolver.get_lifetime_res(param.id) {
2190 let ident = self.lower_ident(param.ident);
2191 ParamName::Plain(ident)
2194 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2198 GenericParamKind::Type { default, .. } => {
2199 let kind = hir::GenericParamKind::Type {
2200 default: default.as_ref().map(|x| {
2201 self.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2206 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2208 GenericParamKind::Const { ty, kw_span: _, default } => {
2209 let ty = self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
2210 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2212 hir::ParamName::Plain(self.lower_ident(param.ident)),
2213 hir::GenericParamKind::Const { ty, default },
2219 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: &ImplTraitContext) -> hir::TraitRef<'hir> {
2220 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2221 hir::QPath::Resolved(None, path) => path,
2222 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2224 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2227 #[instrument(level = "debug", skip(self))]
2228 fn lower_poly_trait_ref(
2231 itctx: &ImplTraitContext,
2232 ) -> hir::PolyTraitRef<'hir> {
2233 let bound_generic_params =
2234 self.lower_lifetime_binder(p.trait_ref.ref_id, &p.bound_generic_params);
2235 let trait_ref = self.lower_trait_ref(&p.trait_ref, itctx);
2236 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2239 fn lower_mt(&mut self, mt: &MutTy, itctx: &ImplTraitContext) -> hir::MutTy<'hir> {
2240 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2243 #[instrument(level = "debug", skip(self), ret)]
2244 fn lower_param_bounds(
2246 bounds: &[GenericBound],
2247 itctx: &ImplTraitContext,
2248 ) -> hir::GenericBounds<'hir> {
2249 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2252 fn lower_param_bounds_mut<'s>(
2254 bounds: &'s [GenericBound],
2255 itctx: &'s ImplTraitContext,
2256 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2257 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx))
2260 #[instrument(level = "debug", skip(self), ret)]
2261 fn lower_generic_and_bounds(
2266 bounds: &[GenericBound],
2267 ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2268 // Add a definition for the in-band `Param`.
2269 let def_id = self.local_def_id(node_id);
2271 // Set the name to `impl Bound1 + Bound2`.
2272 let param = hir::GenericParam {
2273 hir_id: self.lower_node_id(node_id),
2275 name: ParamName::Plain(self.lower_ident(ident)),
2276 pure_wrt_drop: false,
2277 span: self.lower_span(span),
2278 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2282 let preds = self.lower_generic_bound_predicate(
2285 &GenericParamKind::Type { default: None },
2287 &ImplTraitContext::Universal,
2288 hir::PredicateOrigin::ImplTrait,
2291 let hir_id = self.next_id();
2292 let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2293 let ty = hir::TyKind::Path(hir::QPath::Resolved(
2295 self.arena.alloc(hir::Path {
2296 span: self.lower_span(span),
2299 arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2306 /// Lowers a block directly to an expression, presuming that it
2307 /// has no attributes and is not targeted by a `break`.
2308 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2309 let block = self.lower_block(b, false);
2310 self.expr_block(block, AttrVec::new())
2313 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2314 match c.value.kind {
2315 ExprKind::Underscore => {
2316 if self.tcx.features().generic_arg_infer {
2317 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2320 &self.tcx.sess.parse_sess,
2321 sym::generic_arg_infer,
2323 "using `_` for array lengths is unstable",
2325 .stash(c.value.span, StashKey::UnderscoreForArrayLengths);
2326 hir::ArrayLen::Body(self.lower_anon_const(c))
2329 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2333 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2334 self.with_new_scopes(|this| hir::AnonConst {
2335 def_id: this.local_def_id(c.id),
2336 hir_id: this.lower_node_id(c.id),
2337 body: this.lower_const_body(c.value.span, Some(&c.value)),
2341 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2343 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2344 UserProvided => hir::UnsafeSource::UserProvided,
2348 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2350 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2351 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2353 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2354 // placeholder for compilation to proceed.
2355 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2356 hir::TraitBoundModifier::Maybe
2361 // Helper methods for building HIR.
2363 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2364 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2367 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2368 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2373 attrs: Option<&'hir [Attribute]>,
2375 init: Option<&'hir hir::Expr<'hir>>,
2376 pat: &'hir hir::Pat<'hir>,
2377 source: hir::LocalSource,
2378 ) -> hir::Stmt<'hir> {
2379 let hir_id = self.next_id();
2380 if let Some(a) = attrs {
2381 debug_assert!(!a.is_empty());
2382 self.attrs.insert(hir_id.local_id, a);
2384 let local = hir::Local {
2390 span: self.lower_span(span),
2393 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2396 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2397 self.block_all(expr.span, &[], Some(expr))
2403 stmts: &'hir [hir::Stmt<'hir>],
2404 expr: Option<&'hir hir::Expr<'hir>>,
2405 ) -> &'hir hir::Block<'hir> {
2406 let blk = hir::Block {
2409 hir_id: self.next_id(),
2410 rules: hir::BlockCheckMode::DefaultBlock,
2411 span: self.lower_span(span),
2412 targeted_by_break: false,
2414 self.arena.alloc(blk)
2417 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2418 let field = self.single_pat_field(span, pat);
2419 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2422 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2423 let field = self.single_pat_field(span, pat);
2424 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2427 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2428 let field = self.single_pat_field(span, pat);
2429 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2432 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2433 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2436 fn single_pat_field(
2439 pat: &'hir hir::Pat<'hir>,
2440 ) -> &'hir [hir::PatField<'hir>] {
2441 let field = hir::PatField {
2442 hir_id: self.next_id(),
2443 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2444 is_shorthand: false,
2446 span: self.lower_span(span),
2448 arena_vec![self; field]
2451 fn pat_lang_item_variant(
2454 lang_item: hir::LangItem,
2455 fields: &'hir [hir::PatField<'hir>],
2456 hir_id: Option<hir::HirId>,
2457 ) -> &'hir hir::Pat<'hir> {
2458 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2459 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2462 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2463 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::NONE)
2466 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2467 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::NONE)
2470 fn pat_ident_binding_mode(
2474 bm: hir::BindingAnnotation,
2475 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2476 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2477 (self.arena.alloc(pat), hir_id)
2480 fn pat_ident_binding_mode_mut(
2484 bm: hir::BindingAnnotation,
2485 ) -> (hir::Pat<'hir>, hir::HirId) {
2486 let hir_id = self.next_id();
2491 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2492 span: self.lower_span(span),
2493 default_binding_modes: true,
2499 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2500 self.arena.alloc(hir::Pat {
2501 hir_id: self.next_id(),
2503 span: self.lower_span(span),
2504 default_binding_modes: true,
2508 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2510 hir_id: self.next_id(),
2512 span: self.lower_span(span),
2513 default_binding_modes: false,
2519 mut hir_id: hir::HirId,
2521 qpath: hir::QPath<'hir>,
2522 ) -> hir::Ty<'hir> {
2523 let kind = match qpath {
2524 hir::QPath::Resolved(None, path) => {
2525 // Turn trait object paths into `TyKind::TraitObject` instead.
2527 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2528 let principal = hir::PolyTraitRef {
2529 bound_generic_params: &[],
2530 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2531 span: self.lower_span(span),
2534 // The original ID is taken by the `PolyTraitRef`,
2535 // so the `Ty` itself needs a different one.
2536 hir_id = self.next_id();
2537 hir::TyKind::TraitObject(
2538 arena_vec![self; principal],
2539 self.elided_dyn_bound(span),
2540 TraitObjectSyntax::None,
2543 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2546 _ => hir::TyKind::Path(qpath),
2549 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2552 /// Invoked to create the lifetime argument(s) for an elided trait object
2553 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2554 /// when the bound is written, even if it is written with `'_` like in
2555 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2556 fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
2557 let r = hir::Lifetime {
2558 hir_id: self.next_id(),
2559 span: self.lower_span(span),
2560 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2562 debug!("elided_dyn_bound: r={:?}", r);
2567 /// Helper struct for delayed construction of GenericArgs.
2568 struct GenericArgsCtor<'hir> {
2569 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2570 bindings: &'hir [hir::TypeBinding<'hir>],
2571 parenthesized: bool,
2575 impl<'hir> GenericArgsCtor<'hir> {
2576 fn is_empty(&self) -> bool {
2577 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2580 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2581 let ga = hir::GenericArgs {
2582 args: this.arena.alloc_from_iter(self.args),
2583 bindings: self.bindings,
2584 parenthesized: self.parenthesized,
2585 span_ext: this.lower_span(self.span),
2587 this.arena.alloc(ga)