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)]
36 #![feature(never_type)]
37 #![recursion_limit = "256"]
38 #![allow(rustc::potential_query_instability)]
39 #![deny(rustc::untranslatable_diagnostic)]
40 #![deny(rustc::diagnostic_outside_of_impl)]
45 use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait};
47 use rustc_ast::ptr::P;
49 use rustc_ast::{self as ast, *};
50 use rustc_ast_pretty::pprust;
51 use rustc_data_structures::captures::Captures;
52 use rustc_data_structures::fingerprint::Fingerprint;
53 use rustc_data_structures::fx::FxHashMap;
54 use rustc_data_structures::sorted_map::SortedMap;
55 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
56 use rustc_data_structures::sync::Lrc;
57 use rustc_errors::{DiagnosticArgFromDisplay, Handler, StashKey};
59 use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
60 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
61 use rustc_hir::definitions::DefPathData;
62 use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate};
63 use rustc_index::vec::{Idx, IndexVec};
64 use rustc_middle::span_bug;
65 use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
66 use rustc_session::parse::feature_err;
67 use rustc_span::hygiene::MacroKind;
68 use rustc_span::source_map::DesugaringKind;
69 use rustc_span::symbol::{kw, sym, Ident, Symbol};
70 use rustc_span::{Span, DUMMY_SP};
72 use smallvec::SmallVec;
73 use std::collections::hash_map::Entry;
75 macro_rules! arena_vec {
76 ($this:expr; $($x:expr),*) => (
77 $this.arena.alloc_from_iter([$($x),*])
87 mod lifetime_collector;
91 struct LoweringContext<'a, 'hir> {
93 resolver: &'a mut ResolverAstLowering,
95 /// Used to allocate HIR nodes.
96 arena: &'hir hir::Arena<'hir>,
98 /// Bodies inside the owner being lowered.
99 bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
100 /// Attributes inside the owner being lowered.
101 attrs: SortedMap<hir::ItemLocalId, &'hir [Attribute]>,
102 /// Collect items that were created by lowering the current owner.
103 children: FxHashMap<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
105 generator_kind: Option<hir::GeneratorKind>,
107 /// When inside an `async` context, this is the `HirId` of the
108 /// `task_context` local bound to the resume argument of the generator.
109 task_context: Option<hir::HirId>,
111 /// Used to get the current `fn`'s def span to point to when using `await`
112 /// outside of an `async fn`.
113 current_item: Option<Span>,
115 catch_scope: Option<NodeId>,
116 loop_scope: Option<NodeId>,
117 is_in_loop_condition: bool,
118 is_in_trait_impl: bool,
119 is_in_dyn_type: bool,
121 current_hir_id_owner: LocalDefId,
122 item_local_id_counter: hir::ItemLocalId,
123 local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
124 trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
126 impl_trait_defs: Vec<hir::GenericParam<'hir>>,
127 impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
129 /// NodeIds that are lowered inside the current HIR owner.
130 node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
132 allow_try_trait: Option<Lrc<[Symbol]>>,
133 allow_gen_future: Option<Lrc<[Symbol]>>,
134 allow_into_future: Option<Lrc<[Symbol]>>,
136 /// Mapping from generics `def_id`s to TAIT generics `def_id`s.
137 /// For each captured lifetime (e.g., 'a), we create a new lifetime parameter that is a generic
138 /// defined on the TAIT, so we have type Foo<'a1> = ... and we establish a mapping in this
139 /// field from the original parameter 'a to the new parameter 'a1.
140 generics_def_id_map: Vec<FxHashMap<LocalDefId, LocalDefId>>,
143 trait ResolverAstLoweringExt {
144 fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>>;
145 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
146 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
147 fn get_label_res(&self, id: NodeId) -> Option<NodeId>;
148 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
149 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>;
150 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
153 impl ResolverAstLoweringExt for ResolverAstLowering {
154 fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>> {
155 if let ExprKind::Path(None, path) = &expr.kind {
156 // Don't perform legacy const generics rewriting if the path already
157 // has generic arguments.
158 if path.segments.last().unwrap().args.is_some() {
162 let partial_res = self.partial_res_map.get(&expr.id)?;
163 if partial_res.unresolved_segments() != 0 {
167 if let Res::Def(DefKind::Fn, def_id) = partial_res.base_res() {
168 // We only support cross-crate argument rewriting. Uses
169 // within the same crate should be updated to use the new
170 // const generics style.
171 if def_id.is_local() {
175 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
184 /// Obtains resolution for a `NodeId` with a single resolution.
185 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
186 self.partial_res_map.get(&id).copied()
189 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
190 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
191 self.import_res_map.get(&id).copied().unwrap_or_default()
194 /// Obtains resolution for a label with the given `NodeId`.
195 fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
196 self.label_res_map.get(&id).copied()
199 /// Obtains resolution for a lifetime with the given `NodeId`.
200 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
201 self.lifetimes_res_map.get(&id).copied()
204 /// Obtain the list of lifetimes parameters to add to an item.
206 /// Extra lifetime parameters should only be added in places that can appear
207 /// as a `binder` in `LifetimeRes`.
209 /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
210 /// should appear at the enclosing `PolyTraitRef`.
211 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
212 self.extra_lifetime_params_map.remove(&id).unwrap_or_default()
215 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind {
216 self.builtin_macro_kinds.get(&def_id).copied().unwrap_or(MacroKind::Bang)
220 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
221 /// and if so, what meaning it has.
222 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
223 enum ImplTraitContext {
224 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
225 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
226 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
228 /// Newly generated parameters should be inserted into the given `Vec`.
231 /// Treat `impl Trait` as shorthand for a new opaque type.
232 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
233 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
235 ReturnPositionOpaqueTy {
236 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
237 origin: hir::OpaqueTyOrigin,
239 /// Impl trait in type aliases.
241 /// `impl Trait` is not accepted in this position.
242 Disallowed(ImplTraitPosition),
245 /// Position in which `impl Trait` is disallowed.
246 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
247 enum ImplTraitPosition {
269 impl std::fmt::Display for ImplTraitPosition {
270 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271 let name = match self {
272 ImplTraitPosition::Path => "path",
273 ImplTraitPosition::Variable => "variable binding",
274 ImplTraitPosition::Type => "type",
275 ImplTraitPosition::Trait => "trait",
276 ImplTraitPosition::AsyncBlock => "async block",
277 ImplTraitPosition::Bound => "bound",
278 ImplTraitPosition::Generic => "generic",
279 ImplTraitPosition::ExternFnParam => "`extern fn` param",
280 ImplTraitPosition::ClosureParam => "closure param",
281 ImplTraitPosition::PointerParam => "`fn` pointer param",
282 ImplTraitPosition::FnTraitParam => "`Fn` trait param",
283 ImplTraitPosition::TraitParam => "trait method param",
284 ImplTraitPosition::ImplParam => "`impl` method param",
285 ImplTraitPosition::ExternFnReturn => "`extern fn` return",
286 ImplTraitPosition::ClosureReturn => "closure return",
287 ImplTraitPosition::PointerReturn => "`fn` pointer return",
288 ImplTraitPosition::FnTraitReturn => "`Fn` trait return",
289 ImplTraitPosition::TraitReturn => "trait method return",
290 ImplTraitPosition::ImplReturn => "`impl` method return",
293 write!(f, "{}", name)
309 fn impl_trait_return_allowed(&self) -> bool {
311 FnDeclKind::Fn | FnDeclKind::Inherent => true,
317 #[derive(Copy, Clone)]
320 Crate(&'a ast::Crate),
322 AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
323 ForeignItem(&'a ast::ForeignItem),
327 node_id_to_def_id: &FxHashMap<NodeId, LocalDefId>,
329 ) -> IndexVec<LocalDefId, AstOwner<'a>> {
330 let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() };
331 indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner);
332 indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate);
333 visit::walk_crate(&mut indexer, krate);
334 return indexer.index;
336 struct Indexer<'s, 'a> {
337 node_id_to_def_id: &'s FxHashMap<NodeId, LocalDefId>,
338 index: IndexVec<LocalDefId, AstOwner<'a>>,
341 impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
342 fn visit_attribute(&mut self, _: &'a Attribute) {
343 // We do not want to lower expressions that appear in attributes,
344 // as they are not accessible to the rest of the HIR.
347 fn visit_item(&mut self, item: &'a ast::Item) {
348 let def_id = self.node_id_to_def_id[&item.id];
349 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
350 self.index[def_id] = AstOwner::Item(item);
351 visit::walk_item(self, item)
354 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
355 let def_id = self.node_id_to_def_id[&item.id];
356 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
357 self.index[def_id] = AstOwner::AssocItem(item, ctxt);
358 visit::walk_assoc_item(self, item, ctxt);
361 fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
362 let def_id = self.node_id_to_def_id[&item.id];
363 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
364 self.index[def_id] = AstOwner::ForeignItem(item);
365 visit::walk_foreign_item(self, item);
370 /// Compute the hash for the HIR of the full crate.
371 /// This hash will then be part of the crate_hash which is stored in the metadata.
374 owners: &IndexVec<LocalDefId, hir::MaybeOwner<&hir::OwnerInfo<'_>>>,
376 let mut hir_body_nodes: Vec<_> = owners
378 .filter_map(|(def_id, info)| {
379 let info = info.as_owner()?;
380 let def_path_hash = tcx.hir().def_path_hash(def_id);
381 Some((def_path_hash, info))
384 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
386 tcx.with_stable_hashing_context(|mut hcx| {
387 let mut stable_hasher = StableHasher::new();
388 hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
389 stable_hasher.finish()
393 pub fn lower_to_hir<'hir>(tcx: TyCtxt<'hir>, (): ()) -> hir::Crate<'hir> {
395 let krate = tcx.untracked_crate.steal();
396 let mut resolver = tcx.resolver_for_lowering(()).steal();
398 let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
399 let mut owners = IndexVec::from_fn_n(
400 |_| hir::MaybeOwner::Phantom,
401 tcx.definitions_untracked().def_index_count(),
404 for def_id in ast_index.indices() {
407 resolver: &mut resolver,
408 ast_index: &ast_index,
414 // Drop AST to free memory
415 std::mem::drop(ast_index);
416 sess.time("drop_ast", || std::mem::drop(krate));
418 // Discard hygiene data, which isn't required after lowering to HIR.
419 if !sess.opts.unstable_opts.keep_hygiene_data {
420 rustc_span::hygiene::clear_syntax_context_map();
423 let hir_hash = compute_hir_hash(tcx, &owners);
424 hir::Crate { owners, hir_hash }
427 #[derive(Copy, Clone, PartialEq, Debug)]
429 /// Any path in a type context.
431 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
433 /// The `module::Type` in `module::Type::method` in an expression.
437 enum ParenthesizedGenericArgs {
442 impl<'a, 'hir> LoweringContext<'a, 'hir> {
446 node_id: ast::NodeId,
449 debug_assert_ne!(node_id, ast::DUMMY_NODE_ID);
451 self.opt_local_def_id(node_id).is_none(),
452 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
455 self.tcx.hir().def_key(self.local_def_id(node_id)),
458 let def_id = self.tcx.create_def(parent, data);
460 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
461 self.resolver.node_id_to_def_id.insert(node_id, def_id);
466 fn next_node_id(&mut self) -> NodeId {
467 let start = self.resolver.next_node_id;
468 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
469 self.resolver.next_node_id = ast::NodeId::from_u32(next);
473 /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
474 /// resolver (if any), after applying any remapping from `get_remapped_def_id`.
476 /// For example, in a function like `fn foo<'a>(x: &'a u32)`,
477 /// invoking with the id from the `ast::Lifetime` node found inside
478 /// the `&'a u32` type would return the `LocalDefId` of the
479 /// `'a` parameter declared on `foo`.
481 /// This function also applies remapping from `get_remapped_def_id`.
482 /// These are used when synthesizing opaque types from `-> impl Trait` return types and so forth.
483 /// For example, in a function like `fn foo<'a>() -> impl Debug + 'a`,
484 /// we would create an opaque type `type FooReturn<'a1> = impl Debug + 'a1`.
485 /// When lowering the `Debug + 'a` bounds, we add a remapping to map `'a` to `'a1`.
486 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
490 .map(|local_def_id| self.get_remapped_def_id(*local_def_id))
493 fn local_def_id(&self, node: NodeId) -> LocalDefId {
494 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
497 /// Get the previously recorded `to` local def id given the `from` local def id, obtained using
498 /// `generics_def_id_map` field.
499 fn get_remapped_def_id(&self, mut local_def_id: LocalDefId) -> LocalDefId {
500 // `generics_def_id_map` is a stack of mappings. As we go deeper in impl traits nesting we
501 // push new mappings so we need to try first the latest mappings, hence `iter().rev()`.
505 // `fn test<'a, 'b>() -> impl Trait<&'a u8, Ty = impl Sized + 'b> {}`
507 // We would end with a generics_def_id_map like:
509 // `[[fn#'b -> impl_trait#'b], [fn#'b -> impl_sized#'b]]`
511 // for the opaque type generated on `impl Sized + 'b`, We want the result to be:
512 // impl_sized#'b, so iterating forward is the wrong thing to do.
513 for map in self.generics_def_id_map.iter().rev() {
514 if let Some(r) = map.get(&local_def_id) {
515 debug!("def_id_remapper: remapping from `{local_def_id:?}` to `{r:?}`");
518 debug!("def_id_remapper: no remapping for `{local_def_id:?}` found in map");
525 /// Freshen the `LoweringContext` and ready it to lower a nested item.
526 /// The lowered item is registered into `self.children`.
528 /// This function sets up `HirId` lowering infrastructure,
529 /// and stashes the shared mutable state to avoid pollution by the closure.
530 #[instrument(level = "debug", skip(self, f))]
531 fn with_hir_id_owner(
534 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
536 let def_id = self.local_def_id(owner);
538 let current_attrs = std::mem::take(&mut self.attrs);
539 let current_bodies = std::mem::take(&mut self.bodies);
540 let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
541 let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
542 let current_trait_map = std::mem::take(&mut self.trait_map);
543 let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
544 let current_local_counter =
545 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
546 let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
547 let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
549 // Do not reset `next_node_id` and `node_id_to_def_id`:
550 // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
551 // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
553 // Always allocate the first `HirId` for the owner itself.
554 let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
555 debug_assert_eq!(_old, None);
558 debug_assert_eq!(def_id, item.def_id());
559 // `f` should have consumed all the elements in these vectors when constructing `item`.
560 debug_assert!(self.impl_trait_defs.is_empty());
561 debug_assert!(self.impl_trait_bounds.is_empty());
562 let info = self.make_owner_info(item);
564 self.attrs = current_attrs;
565 self.bodies = current_bodies;
566 self.node_id_to_local_id = current_node_ids;
567 self.local_id_to_def_id = current_id_to_def_id;
568 self.trait_map = current_trait_map;
569 self.current_hir_id_owner = current_owner;
570 self.item_local_id_counter = current_local_counter;
571 self.impl_trait_defs = current_impl_trait_defs;
572 self.impl_trait_bounds = current_impl_trait_bounds;
574 let _old = self.children.insert(def_id, hir::MaybeOwner::Owner(info));
575 debug_assert!(_old.is_none())
578 /// Installs the remapping `remap` in scope while `f` is being executed.
579 /// This causes references to the `LocalDefId` keys to be changed to
580 /// refer to the values instead.
582 /// The remapping is used when one piece of AST expands to multiple
583 /// pieces of HIR. For example, the function `fn foo<'a>(...) -> impl Debug + 'a`,
584 /// expands to both a function definition (`foo`) and a TAIT for the return value,
585 /// both of which have a lifetime parameter `'a`. The remapping allows us to
586 /// rewrite the `'a` in the return value to refer to the
587 /// `'a` declared on the TAIT, instead of the function.
588 fn with_remapping<R>(
590 remap: FxHashMap<LocalDefId, LocalDefId>,
591 f: impl FnOnce(&mut Self) -> R,
593 self.generics_def_id_map.push(remap);
595 self.generics_def_id_map.pop();
599 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
600 let attrs = std::mem::take(&mut self.attrs);
601 let mut bodies = std::mem::take(&mut self.bodies);
602 let local_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
603 let trait_map = std::mem::take(&mut self.trait_map);
605 #[cfg(debug_assertions)]
606 for (id, attrs) in attrs.iter() {
607 // Verify that we do not store empty slices in the map.
608 if attrs.is_empty() {
609 panic!("Stored empty attributes for {:?}", id);
613 bodies.sort_by_key(|(k, _)| *k);
614 let bodies = SortedMap::from_presorted_elements(bodies);
615 let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
616 let (nodes, parenting) =
617 index::index_hir(self.tcx.sess, &*self.tcx.definitions_untracked(), node, &bodies);
618 let nodes = hir::OwnerNodes {
619 hash_including_bodies,
626 let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
627 let mut stable_hasher = StableHasher::new();
628 attrs.hash_stable(&mut hcx, &mut stable_hasher);
629 stable_hasher.finish()
631 hir::AttributeMap { map: attrs, hash }
634 self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map })
637 /// Hash the HIR node twice, one deep and one shallow hash. This allows to differentiate
638 /// queries which depend on the full HIR tree and those which only depend on the item signature.
641 node: hir::OwnerNode<'hir>,
642 bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
643 ) -> (Fingerprint, Fingerprint) {
644 self.tcx.with_stable_hashing_context(|mut hcx| {
645 let mut stable_hasher = StableHasher::new();
646 hcx.with_hir_bodies(node.def_id(), bodies, |hcx| {
647 node.hash_stable(hcx, &mut stable_hasher)
649 let hash_including_bodies = stable_hasher.finish();
650 let mut stable_hasher = StableHasher::new();
651 hcx.without_hir_bodies(|hcx| node.hash_stable(hcx, &mut stable_hasher));
652 let hash_without_bodies = stable_hasher.finish();
653 (hash_including_bodies, hash_without_bodies)
657 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
658 /// the `LoweringContext`'s `NodeId => HirId` map.
659 /// Take care not to call this method if the resulting `HirId` is then not
660 /// actually used in the HIR, as that would trigger an assertion in the
661 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
662 /// properly. Calling the method twice with the same `NodeId` is fine though.
663 #[instrument(level = "debug", skip(self), ret)]
664 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
665 assert_ne!(ast_node_id, DUMMY_NODE_ID);
667 match self.node_id_to_local_id.entry(ast_node_id) {
668 Entry::Occupied(o) => {
669 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
671 Entry::Vacant(v) => {
672 // Generate a new `HirId`.
673 let owner = self.current_hir_id_owner;
674 let local_id = self.item_local_id_counter;
675 let hir_id = hir::HirId { owner, local_id };
678 self.item_local_id_counter.increment_by(1);
680 assert_ne!(local_id, hir::ItemLocalId::new(0));
681 if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
682 // Do not override a `MaybeOwner::Owner` that may already here.
683 self.children.entry(def_id).or_insert(hir::MaybeOwner::NonOwner(hir_id));
684 self.local_id_to_def_id.insert(local_id, def_id);
687 if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
688 self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
696 /// Generate a new `HirId` without a backing `NodeId`.
697 #[instrument(level = "debug", skip(self), ret)]
698 fn next_id(&mut self) -> hir::HirId {
699 let owner = self.current_hir_id_owner;
700 let local_id = self.item_local_id_counter;
701 assert_ne!(local_id, hir::ItemLocalId::new(0));
702 self.item_local_id_counter.increment_by(1);
703 hir::HirId { owner, local_id }
706 #[instrument(level = "trace", skip(self))]
707 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
708 let res: Result<Res, ()> = res.apply_id(|id| {
709 let owner = self.current_hir_id_owner;
710 let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
711 Ok(hir::HirId { owner, local_id })
715 // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
716 // This can happen when trying to lower the return type `x` in erroneous code like
717 // async fn foo(x: u8) -> x {}
718 // In that case, `x` is lowered as a function parameter, and the return type is lowered as
719 // an opaque type as a synthesized HIR owner.
720 res.unwrap_or(Res::Err)
723 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
724 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
725 if pr.unresolved_segments() != 0 {
726 panic!("path not fully resolved: {:?}", pr);
732 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
733 self.resolver.get_import_res(id).present_items()
736 fn diagnostic(&self) -> &Handler {
737 self.tcx.sess.diagnostic()
740 /// Reuses the span but adds information like the kind of the desugaring and features that are
741 /// allowed inside this span.
742 fn mark_span_with_reason(
744 reason: DesugaringKind,
746 allow_internal_unstable: Option<Lrc<[Symbol]>>,
748 self.tcx.with_stable_hashing_context(|hcx| {
749 span.mark_with_reason(allow_internal_unstable, reason, self.tcx.sess.edition(), hcx)
753 /// Intercept all spans entering HIR.
754 /// Mark a span as relative to the current owning item.
755 fn lower_span(&self, span: Span) -> Span {
756 if self.tcx.sess.opts.unstable_opts.incremental_relative_spans {
757 span.with_parent(Some(self.current_hir_id_owner))
759 // Do not make spans relative when not using incremental compilation.
764 fn lower_ident(&self, ident: Ident) -> Ident {
765 Ident::new(ident.name, self.lower_span(ident.span))
768 /// Converts a lifetime into a new generic parameter.
769 #[instrument(level = "debug", skip(self))]
770 fn lifetime_res_to_generic_param(
775 ) -> Option<hir::GenericParam<'hir>> {
776 let (name, kind) = match res {
777 LifetimeRes::Param { .. } => {
778 (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
780 LifetimeRes::Fresh { param, .. } => {
781 // Late resolution delegates to us the creation of the `LocalDefId`.
782 let _def_id = self.create_def(
783 self.current_hir_id_owner,
785 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
789 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
791 LifetimeRes::Static | LifetimeRes::Error => return None,
793 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
794 res, ident, ident.span
797 let hir_id = self.lower_node_id(node_id);
798 Some(hir::GenericParam {
801 span: self.lower_span(ident.span),
802 pure_wrt_drop: false,
803 kind: hir::GenericParamKind::Lifetime { kind },
808 /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
809 /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
810 /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
811 /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
812 /// parameters will be successful.
813 #[instrument(level = "debug", skip(self))]
815 fn lower_lifetime_binder(
818 generic_params: &[GenericParam],
819 ) -> &'hir [hir::GenericParam<'hir>] {
820 let mut generic_params: Vec<_> = self.lower_generic_params_mut(generic_params).collect();
821 let extra_lifetimes = self.resolver.take_extra_lifetime_params(binder);
822 debug!(?extra_lifetimes);
823 generic_params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
824 self.lifetime_res_to_generic_param(ident, node_id, res)
826 let generic_params = self.arena.alloc_from_iter(generic_params);
827 debug!(?generic_params);
832 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
833 let was_in_dyn_type = self.is_in_dyn_type;
834 self.is_in_dyn_type = in_scope;
836 let result = f(self);
838 self.is_in_dyn_type = was_in_dyn_type;
843 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
844 let was_in_loop_condition = self.is_in_loop_condition;
845 self.is_in_loop_condition = false;
847 let catch_scope = self.catch_scope.take();
848 let loop_scope = self.loop_scope.take();
850 self.catch_scope = catch_scope;
851 self.loop_scope = loop_scope;
853 self.is_in_loop_condition = was_in_loop_condition;
858 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
859 if attrs.is_empty() {
862 debug_assert_eq!(id.owner, self.current_hir_id_owner);
863 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
864 debug_assert!(!ret.is_empty());
865 self.attrs.insert(id.local_id, ret);
870 fn lower_attr(&self, attr: &Attribute) -> Attribute {
871 // Note that we explicitly do not walk the path. Since we don't really
872 // lower attributes (we use the AST version) there is nowhere to keep
873 // the `HirId`s. We don't actually need HIR version of attributes anyway.
874 // Tokens are also not needed after macro expansion and parsing.
875 let kind = match attr.kind {
876 AttrKind::Normal(ref normal) => AttrKind::Normal(P(NormalAttr {
878 path: normal.item.path.clone(),
879 args: self.lower_mac_args(&normal.item.args),
884 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
887 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
890 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
891 debug_assert_eq!(id.owner, self.current_hir_id_owner);
892 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
893 if let Some(&a) = self.attrs.get(&target_id.local_id) {
894 debug_assert!(!a.is_empty());
895 self.attrs.insert(id.local_id, a);
899 fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
901 MacArgs::Empty => MacArgs::Empty,
902 MacArgs::Delimited(dspan, delim, ref tokens) => {
903 // This is either a non-key-value attribute, or a `macro_rules!` body.
904 // We either not have any nonterminals present (in the case of an attribute),
905 // or have tokens available for all nonterminals in the case of a nested
906 // `macro_rules`: e.g:
909 // macro_rules! outer {
911 // macro_rules! inner {
918 // In both cases, we don't want to synthesize any tokens
919 MacArgs::Delimited(dspan, delim, tokens.flattened())
921 // This is an inert key-value attribute - it will never be visible to macros
922 // after it gets lowered to HIR. Therefore, we can extract literals to handle
923 // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
924 MacArgs::Eq(eq_span, MacArgsEq::Ast(ref expr)) => {
925 // In valid code the value always ends up as a single literal. Otherwise, a dummy
926 // literal suffices because the error is handled elsewhere.
927 let lit = if let ExprKind::Lit(lit) = &expr.kind {
931 token_lit: token::Lit::new(token::LitKind::Err, kw::Empty, None),
936 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit))
938 MacArgs::Eq(_, MacArgsEq::Hir(ref lit)) => {
939 unreachable!("in literal form when lowering mac args eq: {:?}", lit)
944 /// Given an associated type constraint like one of these:
946 /// ```ignore (illustrative)
947 /// T: Iterator<Item: Debug>
949 /// T: Iterator<Item = Debug>
953 /// returns a `hir::TypeBinding` representing `Item`.
954 #[instrument(level = "debug", skip(self))]
955 fn lower_assoc_ty_constraint(
957 constraint: &AssocConstraint,
958 itctx: &mut ImplTraitContext,
959 ) -> hir::TypeBinding<'hir> {
960 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
961 // lower generic arguments of identifier in constraint
962 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
963 let gen_args_ctor = match gen_args {
964 GenericArgs::AngleBracketed(ref data) => {
965 self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
967 GenericArgs::Parenthesized(ref data) => {
968 self.emit_bad_parenthesized_trait_in_assoc_ty(data);
969 self.lower_angle_bracketed_parameter_data(
970 &data.as_angle_bracketed_args(),
977 gen_args_ctor.into_generic_args(self)
979 self.arena.alloc(hir::GenericArgs::none())
981 let mut itctx_tait = ImplTraitContext::TypeAliasesOpaqueTy;
983 let kind = match constraint.kind {
984 AssocConstraintKind::Equality { ref term } => {
985 let term = match term {
986 Term::Ty(ref ty) => self.lower_ty(ty, itctx).into(),
987 Term::Const(ref c) => self.lower_anon_const(c).into(),
989 hir::TypeBindingKind::Equality { term }
991 AssocConstraintKind::Bound { ref bounds } => {
992 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
993 let (desugar_to_impl_trait, itctx) = match itctx {
994 // We are in the return position:
996 // fn foo() -> impl Iterator<Item: Debug>
1000 // fn foo() -> impl Iterator<Item = impl Debug>
1001 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1002 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
1004 // We are in the argument position, but within a dyn type:
1006 // fn foo(x: dyn Iterator<Item: Debug>)
1010 // fn foo(x: dyn Iterator<Item = impl Debug>)
1011 ImplTraitContext::Universal if self.is_in_dyn_type => (true, itctx),
1013 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1014 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1015 // "impl trait context" to permit `impl Debug` in this position (it desugars
1016 // then to an opaque type).
1018 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1019 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1020 (true, &mut itctx_tait)
1023 // We are in the parameter position, but not within a dyn type:
1025 // fn foo(x: impl Iterator<Item: Debug>)
1027 // so we leave it as is and this gets expanded in astconv to a bound like
1028 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1030 _ => (false, itctx),
1033 if desugar_to_impl_trait {
1034 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1035 // constructing the HIR for `impl bounds...` and then lowering that.
1037 let parent_def_id = self.current_hir_id_owner;
1038 let impl_trait_node_id = self.next_node_id();
1039 self.create_def(parent_def_id, impl_trait_node_id, DefPathData::ImplTrait);
1041 self.with_dyn_type_scope(false, |this| {
1042 let node_id = this.next_node_id();
1043 let ty = this.lower_ty(
1046 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1047 span: this.lower_span(constraint.span),
1053 hir::TypeBindingKind::Equality { term: ty.into() }
1056 // Desugar `AssocTy: Bounds` into a type binding where the
1057 // later desugars into a trait predicate.
1058 let bounds = self.lower_param_bounds(bounds, itctx);
1060 hir::TypeBindingKind::Constraint { bounds }
1066 hir_id: self.lower_node_id(constraint.id),
1067 ident: self.lower_ident(constraint.ident),
1070 span: self.lower_span(constraint.span),
1074 fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1075 // Suggest removing empty parentheses: "Trait()" -> "Trait"
1076 let sub = if data.inputs.is_empty() {
1077 let parentheses_span =
1078 data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1079 AssocTyParenthesesSub::Empty { parentheses_span }
1081 // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1083 // Start of parameters to the 1st argument
1084 let open_param = data.inputs_span.shrink_to_lo().to(data
1090 // End of last argument to end of parameters
1092 data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1093 AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1095 self.tcx.sess.emit_err(AssocTyParentheses { span: data.span, sub });
1098 #[instrument(level = "debug", skip(self))]
1099 fn lower_generic_arg(
1101 arg: &ast::GenericArg,
1102 itctx: &mut ImplTraitContext,
1103 ) -> hir::GenericArg<'hir> {
1105 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1106 ast::GenericArg::Type(ty) => {
1108 TyKind::Infer if self.tcx.features().generic_arg_infer => {
1109 return GenericArg::Infer(hir::InferArg {
1110 hir_id: self.lower_node_id(ty.id),
1111 span: self.lower_span(ty.span),
1114 // We parse const arguments as path types as we cannot distinguish them during
1115 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1116 // type and value namespaces. If we resolved the path in the value namespace, we
1117 // transform it into a generic const argument.
1118 TyKind::Path(ref qself, ref path) => {
1119 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1120 let res = partial_res.base_res();
1121 if !res.matches_ns(Namespace::TypeNS) {
1123 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1127 // Construct an AnonConst where the expr is the "ty"'s path.
1129 let parent_def_id = self.current_hir_id_owner;
1130 let node_id = self.next_node_id();
1132 // Add a definition for the in-band const def.
1133 self.create_def(parent_def_id, node_id, DefPathData::AnonConst);
1135 let span = self.lower_span(ty.span);
1136 let path_expr = Expr {
1138 kind: ExprKind::Path(qself.clone(), path.clone()),
1140 attrs: AttrVec::new(),
1144 let ct = self.with_new_scopes(|this| hir::AnonConst {
1145 hir_id: this.lower_node_id(node_id),
1146 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1148 return GenericArg::Const(ConstArg { value: ct, span });
1154 GenericArg::Type(self.lower_ty(&ty, itctx))
1156 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1157 value: self.lower_anon_const(&ct),
1158 span: self.lower_span(ct.value.span),
1163 #[instrument(level = "debug", skip(self))]
1164 fn lower_ty(&mut self, t: &Ty, itctx: &mut ImplTraitContext) -> &'hir hir::Ty<'hir> {
1165 self.arena.alloc(self.lower_ty_direct(t, itctx))
1171 qself: &Option<QSelf>,
1173 param_mode: ParamMode,
1174 itctx: &mut ImplTraitContext,
1175 ) -> hir::Ty<'hir> {
1176 // Check whether we should interpret this as a bare trait object.
1177 // This check mirrors the one in late resolution. We only introduce this special case in
1178 // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1179 // The other cases when a qpath should be opportunistically made a trait object are handled
1182 && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1183 && partial_res.unresolved_segments() == 0
1184 && let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = partial_res.base_res()
1186 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1187 let bound = this.lower_poly_trait_ref(
1189 bound_generic_params: vec![],
1190 trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1195 let bounds = this.arena.alloc_from_iter([bound]);
1196 let lifetime_bound = this.elided_dyn_bound(t.span);
1197 (bounds, lifetime_bound)
1199 let kind = hir::TyKind::TraitObject(bounds, lifetime_bound, TraitObjectSyntax::None);
1200 return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1203 let id = self.lower_node_id(t.id);
1204 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1205 self.ty_path(id, t.span, qpath)
1208 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1209 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1212 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1213 self.ty(span, hir::TyKind::Tup(tys))
1216 fn lower_ty_direct(&mut self, t: &Ty, itctx: &mut ImplTraitContext) -> hir::Ty<'hir> {
1217 let kind = match t.kind {
1218 TyKind::Infer => hir::TyKind::Infer,
1219 TyKind::Err => hir::TyKind::Err,
1220 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1221 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1222 TyKind::Rptr(ref region, ref mt) => {
1223 let region = region.unwrap_or_else(|| {
1224 let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1225 self.resolver.get_lifetime_res(t.id)
1227 debug_assert_eq!(start.plus(1), end);
1232 let span = self.tcx.sess.source_map().start_point(t.span);
1233 Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1235 let lifetime = self.lower_lifetime(®ion);
1236 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1238 TyKind::BareFn(ref f) => {
1239 let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1240 hir::TyKind::BareFn(self.arena.alloc(hir::BareFnTy {
1242 unsafety: self.lower_unsafety(f.unsafety),
1243 abi: self.lower_extern(f.ext),
1244 decl: self.lower_fn_decl(&f.decl, None, FnDeclKind::Pointer, None),
1245 param_names: self.lower_fn_params_to_names(&f.decl),
1248 TyKind::Never => hir::TyKind::Never,
1249 TyKind::Tup(ref tys) => hir::TyKind::Tup(
1250 self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty_direct(ty, itctx))),
1252 TyKind::Paren(ref ty) => {
1253 return self.lower_ty_direct(ty, itctx);
1255 TyKind::Path(ref qself, ref path) => {
1256 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1258 TyKind::ImplicitSelf => {
1259 let hir_id = self.lower_node_id(t.id);
1260 let res = self.expect_full_res(t.id);
1261 let res = self.lower_res(res);
1262 hir::TyKind::Path(hir::QPath::Resolved(
1264 self.arena.alloc(hir::Path {
1266 segments: arena_vec![self; hir::PathSegment::new(
1267 Ident::with_dummy_span(kw::SelfUpper),
1271 span: self.lower_span(t.span),
1275 TyKind::Array(ref ty, ref length) => {
1276 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1278 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1279 TyKind::TraitObject(ref bounds, kind) => {
1280 let mut lifetime_bound = None;
1281 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1283 this.arena.alloc_from_iter(bounds.iter().filter_map(
1284 |bound| match *bound {
1285 GenericBound::Trait(
1287 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1288 ) => Some(this.lower_poly_trait_ref(ty, itctx)),
1289 // `~const ?Bound` will cause an error during AST validation
1290 // anyways, so treat it like `?Bound` as compilation proceeds.
1291 GenericBound::Trait(
1293 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1295 GenericBound::Outlives(ref lifetime) => {
1296 if lifetime_bound.is_none() {
1297 lifetime_bound = Some(this.lower_lifetime(lifetime));
1303 let lifetime_bound =
1304 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1305 (bounds, lifetime_bound)
1307 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1309 TyKind::ImplTrait(def_node_id, ref bounds) => {
1312 ImplTraitContext::ReturnPositionOpaqueTy { origin } => {
1313 self.lower_opaque_impl_trait(span, *origin, def_node_id, bounds, itctx)
1315 ImplTraitContext::TypeAliasesOpaqueTy => {
1316 let mut nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy;
1317 self.lower_opaque_impl_trait(
1319 hir::OpaqueTyOrigin::TyAlias,
1325 ImplTraitContext::Universal => {
1327 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1328 let (param, bounds, path) =
1329 self.lower_generic_and_bounds(def_node_id, span, ident, bounds);
1330 self.impl_trait_defs.push(param);
1331 if let Some(bounds) = bounds {
1332 self.impl_trait_bounds.push(bounds);
1336 ImplTraitContext::Disallowed(position) => {
1337 self.tcx.sess.emit_err(MisplacedImplTrait {
1339 position: DiagnosticArgFromDisplay(&position),
1345 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1346 TyKind::CVarArgs => {
1347 self.tcx.sess.delay_span_bug(
1349 "`TyKind::CVarArgs` should have been handled elsewhere",
1355 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1358 /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1359 /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1360 /// HIR type that references the TAIT.
1362 /// Given a function definition like:
1365 /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1370 /// we will create a TAIT definition in the HIR like
1373 /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1376 /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1379 /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1382 /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1383 /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1384 /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1385 /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1386 /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1387 #[instrument(level = "debug", skip(self), ret)]
1388 fn lower_opaque_impl_trait(
1391 origin: hir::OpaqueTyOrigin,
1392 opaque_ty_node_id: NodeId,
1393 bounds: &GenericBounds,
1394 itctx: &mut ImplTraitContext,
1395 ) -> hir::TyKind<'hir> {
1396 // Make sure we know that some funky desugaring has been going on here.
1397 // This is a first: there is code in other places like for loop
1398 // desugaring that explicitly states that we don't want to track that.
1399 // Not tracking it makes lints in rustc and clippy very fragile, as
1400 // frequently opened issues show.
1401 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1403 let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1404 debug!(?opaque_ty_def_id);
1406 // Contains the new lifetime definitions created for the TAIT (if any).
1407 let mut collected_lifetimes = Vec::new();
1409 // If this came from a TAIT (as opposed to a function that returns an RPIT), we only want
1410 // to capture the lifetimes that appear in the bounds. So visit the bounds to find out
1411 // exactly which ones those are.
1412 let lifetimes_to_remap = if origin == hir::OpaqueTyOrigin::TyAlias {
1413 // in a TAIT like `type Foo<'a> = impl Foo<'a>`, we don't keep all the lifetime parameters
1416 // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1417 // we only keep the lifetimes that appear in the `impl Debug` itself:
1418 lifetime_collector::lifetimes_in_bounds(&self.resolver, bounds)
1420 debug!(?lifetimes_to_remap);
1422 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1423 let mut new_remapping = FxHashMap::default();
1425 // If this opaque type is only capturing a subset of the lifetimes (those that appear
1426 // in bounds), then create the new lifetime parameters required and create a mapping
1427 // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1428 collected_lifetimes = lctx.create_lifetime_defs(
1430 &lifetimes_to_remap,
1433 debug!(?collected_lifetimes);
1434 debug!(?new_remapping);
1436 // Install the remapping from old to new (if any):
1437 lctx.with_remapping(new_remapping, |lctx| {
1438 // This creates HIR lifetime definitions as `hir::GenericParam`, in the given
1439 // example `type TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection
1440 // containing `&['x]`.
1441 let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1442 |&(new_node_id, lifetime)| {
1443 let hir_id = lctx.lower_node_id(new_node_id);
1444 debug_assert_ne!(lctx.opt_local_def_id(new_node_id), None);
1446 let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1447 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1450 hir::ParamName::Plain(lifetime.ident),
1451 hir::LifetimeParamKind::Explicit,
1458 span: lifetime.ident.span,
1459 pure_wrt_drop: false,
1460 kind: hir::GenericParamKind::Lifetime { kind },
1465 debug!(?lifetime_defs);
1467 // Then when we lower the param bounds, references to 'a are remapped to 'a1, so we
1468 // get back Debug + 'a1, which is suitable for use on the TAIT.
1469 let hir_bounds = lctx.lower_param_bounds(bounds, itctx);
1470 debug!(?hir_bounds);
1472 let opaque_ty_item = hir::OpaqueTy {
1473 generics: self.arena.alloc(hir::Generics {
1474 params: lifetime_defs,
1476 has_where_clause_predicates: false,
1477 where_clause_span: lctx.lower_span(span),
1478 span: lctx.lower_span(span),
1483 debug!(?opaque_ty_item);
1485 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1489 // This creates HIR lifetime arguments as `hir::GenericArg`, in the given example `type
1490 // TestReturn<'a, T, 'x> = impl Debug + 'x`, it creates a collection containing `&['x]`.
1492 self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(_, lifetime)| {
1493 let id = self.next_node_id();
1494 let span = lifetime.ident.span;
1496 let ident = if lifetime.ident.name == kw::UnderscoreLifetime {
1497 Ident::with_dummy_span(kw::UnderscoreLifetime)
1502 let l = self.new_named_lifetime(lifetime.id, id, span, ident);
1503 hir::GenericArg::Lifetime(l)
1507 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1508 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1511 /// Registers a new opaque type with the proper `NodeId`s and
1512 /// returns the lowered node-ID for the opaque type.
1513 fn generate_opaque_type(
1515 opaque_ty_id: LocalDefId,
1516 opaque_ty_item: hir::OpaqueTy<'hir>,
1518 opaque_ty_span: Span,
1519 ) -> hir::OwnerNode<'hir> {
1520 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1521 // Generate an `type Foo = impl Trait;` declaration.
1522 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1523 let opaque_ty_item = hir::Item {
1524 def_id: opaque_ty_id,
1525 ident: Ident::empty(),
1526 kind: opaque_ty_item_kind,
1527 vis_span: self.lower_span(span.shrink_to_lo()),
1528 span: self.lower_span(opaque_ty_span),
1530 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1533 /// Given a `parent_def_id`, a list of `lifetimes_in_bounds and a `remapping` hash to be
1534 /// filled, this function creates new definitions for `Param` and `Fresh` lifetimes, inserts the
1535 /// new definition, adds it to the remapping with the definition of the given lifetime and
1536 /// returns a list of lifetimes to be lowered afterwards.
1537 fn create_lifetime_defs(
1539 parent_def_id: LocalDefId,
1540 lifetimes_in_bounds: &[Lifetime],
1541 remapping: &mut FxHashMap<LocalDefId, LocalDefId>,
1542 ) -> Vec<(NodeId, Lifetime)> {
1543 let mut result = Vec::new();
1545 for lifetime in lifetimes_in_bounds {
1546 let res = self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error);
1550 LifetimeRes::Param { param: old_def_id, binder: _ } => {
1551 if remapping.get(&old_def_id).is_none() {
1552 let node_id = self.next_node_id();
1554 let new_def_id = self.create_def(
1557 DefPathData::LifetimeNs(lifetime.ident.name),
1559 remapping.insert(old_def_id, new_def_id);
1561 result.push((node_id, *lifetime));
1565 LifetimeRes::Fresh { param, binder: _ } => {
1566 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1567 if let Some(old_def_id) = self.opt_local_def_id(param) && remapping.get(&old_def_id).is_none() {
1568 let node_id = self.next_node_id();
1570 let new_def_id = self.create_def(
1573 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1575 remapping.insert(old_def_id, new_def_id);
1577 result.push((node_id, *lifetime));
1581 LifetimeRes::Static | LifetimeRes::Error => {}
1584 let bug_msg = format!(
1585 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1586 res, lifetime.ident, lifetime.ident.span
1588 span_bug!(lifetime.ident.span, "{}", bug_msg);
1596 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1597 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1598 // as they are not explicit in HIR/Ty function signatures.
1599 // (instead, the `c_variadic` flag is set to `true`)
1600 let mut inputs = &decl.inputs[..];
1601 if decl.c_variadic() {
1602 inputs = &inputs[..inputs.len() - 1];
1604 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1605 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1606 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1610 // Lowers a function declaration.
1612 // `decl`: the unlowered (AST) function declaration.
1613 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1614 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1615 // `make_ret_async` is also `Some`.
1616 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1617 // This guards against trait declarations and implementations where `impl Trait` is
1619 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1620 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1621 // return type `impl Trait` item.
1622 #[instrument(level = "debug", skip(self))]
1626 fn_node_id: Option<NodeId>,
1628 make_ret_async: Option<NodeId>,
1629 ) -> &'hir hir::FnDecl<'hir> {
1630 let c_variadic = decl.c_variadic();
1632 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1633 // as they are not explicit in HIR/Ty function signatures.
1634 // (instead, the `c_variadic` flag is set to `true`)
1635 let mut inputs = &decl.inputs[..];
1637 inputs = &inputs[..inputs.len() - 1];
1639 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1640 if fn_node_id.is_some() {
1641 self.lower_ty_direct(¶m.ty, &mut ImplTraitContext::Universal)
1643 self.lower_ty_direct(
1645 &mut ImplTraitContext::Disallowed(match kind {
1646 FnDeclKind::Fn | FnDeclKind::Inherent => {
1647 unreachable!("fn should allow in-band lifetimes")
1649 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1650 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1651 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1652 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1653 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1659 let output = if let Some(ret_id) = make_ret_async {
1660 self.lower_async_fn_ret_ty(
1662 fn_node_id.expect("`make_ret_async` but no `fn_def_id`"),
1667 FnRetTy::Ty(ref ty) => {
1668 let mut context = match fn_node_id {
1669 Some(fn_node_id) if kind.impl_trait_return_allowed() => {
1670 let fn_def_id = self.local_def_id(fn_node_id);
1671 ImplTraitContext::ReturnPositionOpaqueTy {
1672 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1675 _ => ImplTraitContext::Disallowed(match kind {
1676 FnDeclKind::Fn | FnDeclKind::Inherent => {
1677 unreachable!("fn should allow in-band lifetimes")
1679 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1680 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1681 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1682 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1683 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1686 hir::FnRetTy::Return(self.lower_ty(ty, &mut context))
1688 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1692 self.arena.alloc(hir::FnDecl {
1696 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1697 let is_mutable_pat = matches!(
1699 PatKind::Ident(hir::BindingAnnotation(_, Mutability::Mut), ..)
1703 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1704 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1705 // Given we are only considering `ImplicitSelf` types, we needn't consider
1706 // the case where we have a mutable pattern to a reference as that would
1707 // no longer be an `ImplicitSelf`.
1708 TyKind::Rptr(_, ref mt)
1709 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1711 hir::ImplicitSelfKind::MutRef
1713 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1714 hir::ImplicitSelfKind::ImmRef
1716 _ => hir::ImplicitSelfKind::None,
1722 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1723 // combined with the following definition of `OpaqueTy`:
1725 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1727 // `output`: unlowered output type (`T` in `-> T`)
1728 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1729 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1730 #[instrument(level = "debug", skip(self))]
1731 fn lower_async_fn_ret_ty(
1735 opaque_ty_node_id: NodeId,
1736 ) -> hir::FnRetTy<'hir> {
1737 let span = output.span();
1739 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1741 let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1742 let fn_def_id = self.local_def_id(fn_node_id);
1744 // When we create the opaque type for this async fn, it is going to have
1745 // to capture all the lifetimes involved in the signature (including in the
1746 // return type). This is done by introducing lifetime parameters for:
1748 // - all the explicitly declared lifetimes from the impl and function itself;
1749 // - all the elided lifetimes in the fn arguments;
1750 // - all the elided lifetimes in the return type.
1752 // So for example in this snippet:
1755 // impl<'a> Foo<'a> {
1756 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1757 // // ^ '0 ^ '1 ^ '2
1758 // // elided lifetimes used below
1763 // we would create an opaque type like:
1766 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1769 // and we would then desugar `bar` to the equivalent of:
1772 // impl<'a> Foo<'a> {
1773 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1777 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1778 // this is because the elided lifetimes from the return type
1779 // should be figured out using the ordinary elision rules, and
1780 // this desugaring achieves that.
1782 // Calculate all the lifetimes that should be captured
1783 // by the opaque type. This should include all in-scope
1784 // lifetime parameters, including those defined in-band.
1786 // Contains the new lifetime definitions created for the TAIT (if any) generated for the
1788 let mut collected_lifetimes = Vec::new();
1789 let mut new_remapping = FxHashMap::default();
1791 let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1792 debug!(?extra_lifetime_params);
1793 for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1794 let outer_def_id = self.local_def_id(outer_node_id);
1795 let inner_node_id = self.next_node_id();
1797 // Add a definition for the in scope lifetime def.
1798 let inner_def_id = self.create_def(
1801 DefPathData::LifetimeNs(ident.name),
1803 new_remapping.insert(outer_def_id, inner_def_id);
1805 let inner_res = match outer_res {
1806 // Input lifetime like `'a`:
1807 LifetimeRes::Param { param, .. } => {
1808 LifetimeRes::Param { param, binder: fn_node_id }
1810 // Input lifetime like `'1`:
1811 LifetimeRes::Fresh { param, .. } => {
1812 LifetimeRes::Fresh { param, binder: fn_node_id }
1814 LifetimeRes::Static | LifetimeRes::Error => continue,
1817 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1818 res, ident, ident.span
1823 let lifetime = Lifetime { id: outer_node_id, ident };
1824 collected_lifetimes.push((inner_node_id, lifetime, Some(inner_res)));
1827 debug!(?collected_lifetimes);
1829 // We only want to capture the lifetimes that appear in the bounds. So visit the bounds to
1830 // find out exactly which ones those are.
1831 // in fn return position, like the `fn test<'a>() -> impl Debug + 'a` example,
1832 // we only keep the lifetimes that appear in the `impl Debug` itself:
1833 let lifetimes_to_remap = lifetime_collector::lifetimes_in_ret_ty(&self.resolver, output);
1834 debug!(?lifetimes_to_remap);
1836 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1837 // If this opaque type is only capturing a subset of the lifetimes (those that appear
1838 // in bounds), then create the new lifetime parameters required and create a mapping
1839 // from the old `'a` (on the function) to the new `'a` (on the opaque type).
1840 collected_lifetimes.extend(
1841 this.create_lifetime_defs(
1843 &lifetimes_to_remap,
1847 .map(|(new_node_id, lifetime)| (new_node_id, lifetime, None)),
1849 debug!(?collected_lifetimes);
1850 debug!(?new_remapping);
1852 // Install the remapping from old to new (if any):
1853 this.with_remapping(new_remapping, |this| {
1854 // We have to be careful to get elision right here. The
1855 // idea is that we create a lifetime parameter for each
1856 // lifetime in the return type. So, given a return type
1857 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1858 // Future<Output = &'1 [ &'2 u32 ]>`.
1860 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1861 // hence the elision takes place at the fn site.
1863 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span);
1865 let generic_params = this.arena.alloc_from_iter(collected_lifetimes.iter().map(
1866 |&(new_node_id, lifetime, _)| {
1867 let hir_id = this.lower_node_id(new_node_id);
1868 debug_assert_ne!(this.opt_local_def_id(new_node_id), None);
1870 let (name, kind) = if lifetime.ident.name == kw::UnderscoreLifetime {
1871 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
1874 hir::ParamName::Plain(lifetime.ident),
1875 hir::LifetimeParamKind::Explicit,
1882 span: lifetime.ident.span,
1883 pure_wrt_drop: false,
1884 kind: hir::GenericParamKind::Lifetime { kind },
1889 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1891 let opaque_ty_item = hir::OpaqueTy {
1892 generics: this.arena.alloc(hir::Generics {
1893 params: generic_params,
1895 has_where_clause_predicates: false,
1896 where_clause_span: this.lower_span(span),
1897 span: this.lower_span(span),
1899 bounds: arena_vec![this; future_bound],
1900 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1903 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1904 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1908 // As documented above, we need to create the lifetime
1909 // arguments to our opaque type. Continuing with our example,
1910 // we're creating the type arguments for the return type:
1913 // Bar<'a, 'b, '0, '1, '_>
1916 // For the "input" lifetime parameters, we wish to create
1917 // references to the parameters themselves, including the
1918 // "implicit" ones created from parameter types (`'a`, `'b`,
1921 // For the "output" lifetime parameters, we just want to
1923 let generic_args = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
1924 |(_, lifetime, res)| {
1925 let id = self.next_node_id();
1926 let span = lifetime.ident.span;
1928 let ident = if lifetime.ident.name == kw::UnderscoreLifetime {
1929 Ident::with_dummy_span(kw::UnderscoreLifetime)
1934 let res = res.unwrap_or(
1935 self.resolver.get_lifetime_res(lifetime.id).unwrap_or(LifetimeRes::Error),
1937 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1938 hir::GenericArg::Lifetime(l)
1942 // Create the `Foo<...>` reference itself. Note that the `type
1943 // Foo = impl Trait` is, internally, created as a child of the
1944 // async fn, so the *type parameters* are inherited. It's
1945 // only the lifetime parameters that we must supply.
1947 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1948 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1949 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1952 /// Transforms `-> T` into `Future<Output = T>`.
1953 fn lower_async_fn_output_type_to_future_bound(
1956 fn_def_id: LocalDefId,
1958 ) -> hir::GenericBound<'hir> {
1959 // Compute the `T` in `Future<Output = T>` from the return type.
1960 let output_ty = match output {
1961 FnRetTy::Ty(ty) => {
1962 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1963 // `impl Future` opaque type that `async fn` implicitly
1965 let mut context = ImplTraitContext::ReturnPositionOpaqueTy {
1966 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1968 self.lower_ty(ty, &mut context)
1970 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1974 let future_args = self.arena.alloc(hir::GenericArgs {
1976 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1977 parenthesized: false,
1981 hir::GenericBound::LangItemTrait(
1982 // ::std::future::Future<future_params>
1983 hir::LangItem::Future,
1984 self.lower_span(span),
1990 #[instrument(level = "trace", skip(self))]
1991 fn lower_param_bound(
1994 itctx: &mut ImplTraitContext,
1995 ) -> hir::GenericBound<'hir> {
1997 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1998 self.lower_poly_trait_ref(p, itctx),
1999 self.lower_trait_bound_modifier(*modifier),
2001 GenericBound::Outlives(lifetime) => {
2002 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
2007 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
2008 let span = self.lower_span(l.ident.span);
2009 let ident = self.lower_ident(l.ident);
2010 self.new_named_lifetime(l.id, l.id, span, ident)
2013 #[instrument(level = "debug", skip(self))]
2014 fn new_named_lifetime_with_res(
2020 ) -> hir::Lifetime {
2021 let name = match res {
2022 LifetimeRes::Param { param, .. } => {
2023 let p_name = ParamName::Plain(ident);
2024 let param = self.get_remapped_def_id(param);
2026 hir::LifetimeName::Param(param, p_name)
2028 LifetimeRes::Fresh { param, .. } => {
2029 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2030 let param = self.local_def_id(param);
2032 hir::LifetimeName::Param(param, ParamName::Fresh)
2034 LifetimeRes::Infer => hir::LifetimeName::Infer,
2035 LifetimeRes::Static => hir::LifetimeName::Static,
2036 LifetimeRes::Error => hir::LifetimeName::Error,
2037 res => panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span),
2041 hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
2044 #[instrument(level = "debug", skip(self))]
2045 fn new_named_lifetime(
2051 ) -> hir::Lifetime {
2052 let res = self.resolver.get_lifetime_res(id).unwrap_or(LifetimeRes::Error);
2053 self.new_named_lifetime_with_res(new_id, span, ident, res)
2056 fn lower_generic_params_mut<'s>(
2058 params: &'s [GenericParam],
2059 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
2060 params.iter().map(move |param| self.lower_generic_param(param))
2063 fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
2064 self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
2067 #[instrument(level = "trace", skip(self))]
2068 fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
2069 let (name, kind) = self.lower_generic_param_kind(param);
2071 let hir_id = self.lower_node_id(param.id);
2072 self.lower_attrs(hir_id, ¶m.attrs);
2076 span: self.lower_span(param.span()),
2077 pure_wrt_drop: self.tcx.sess.contains_name(¶m.attrs, sym::may_dangle),
2079 colon_span: param.colon_span.map(|s| self.lower_span(s)),
2083 fn lower_generic_param_kind(
2085 param: &GenericParam,
2086 ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2088 GenericParamKind::Lifetime => {
2089 // AST resolution emitted an error on those parameters, so we lower them using
2090 // `ParamName::Error`.
2092 if let Some(LifetimeRes::Error) = self.resolver.get_lifetime_res(param.id) {
2095 let ident = self.lower_ident(param.ident);
2096 ParamName::Plain(ident)
2099 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2103 GenericParamKind::Type { ref default, .. } => {
2104 let kind = hir::GenericParamKind::Type {
2105 default: default.as_ref().map(|x| {
2106 self.lower_ty(x, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2111 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2113 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2115 self.lower_ty(&ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
2116 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2118 hir::ParamName::Plain(self.lower_ident(param.ident)),
2119 hir::GenericParamKind::Const { ty, default },
2128 itctx: &mut ImplTraitContext,
2129 ) -> hir::TraitRef<'hir> {
2130 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2131 hir::QPath::Resolved(None, path) => path,
2132 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2134 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2137 #[instrument(level = "debug", skip(self))]
2138 fn lower_poly_trait_ref(
2141 itctx: &mut ImplTraitContext,
2142 ) -> hir::PolyTraitRef<'hir> {
2143 let bound_generic_params =
2144 self.lower_lifetime_binder(p.trait_ref.ref_id, &p.bound_generic_params);
2145 let trait_ref = self.lower_trait_ref(&p.trait_ref, itctx);
2146 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2149 fn lower_mt(&mut self, mt: &MutTy, itctx: &mut ImplTraitContext) -> hir::MutTy<'hir> {
2150 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2153 #[instrument(level = "debug", skip(self), ret)]
2154 fn lower_param_bounds(
2156 bounds: &[GenericBound],
2157 itctx: &mut ImplTraitContext,
2158 ) -> hir::GenericBounds<'hir> {
2159 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2162 fn lower_param_bounds_mut<'s, 'b>(
2164 bounds: &'s [GenericBound],
2165 itctx: &'b mut ImplTraitContext,
2166 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> + Captures<'b>
2168 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx))
2171 #[instrument(level = "debug", skip(self), ret)]
2172 fn lower_generic_and_bounds(
2177 bounds: &[GenericBound],
2178 ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2179 // Add a definition for the in-band `Param`.
2180 let def_id = self.local_def_id(node_id);
2182 // Set the name to `impl Bound1 + Bound2`.
2183 let param = hir::GenericParam {
2184 hir_id: self.lower_node_id(node_id),
2185 name: ParamName::Plain(self.lower_ident(ident)),
2186 pure_wrt_drop: false,
2187 span: self.lower_span(span),
2188 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2192 let preds = self.lower_generic_bound_predicate(
2195 &GenericParamKind::Type { default: None },
2197 &mut ImplTraitContext::Universal,
2198 hir::PredicateOrigin::ImplTrait,
2201 let hir_id = self.next_id();
2202 let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2203 let ty = hir::TyKind::Path(hir::QPath::Resolved(
2205 self.arena.alloc(hir::Path {
2206 span: self.lower_span(span),
2209 arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2216 /// Lowers a block directly to an expression, presuming that it
2217 /// has no attributes and is not targeted by a `break`.
2218 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2219 let block = self.lower_block(b, false);
2220 self.expr_block(block, AttrVec::new())
2223 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2224 match c.value.kind {
2225 ExprKind::Underscore => {
2226 if self.tcx.features().generic_arg_infer {
2227 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2230 &self.tcx.sess.parse_sess,
2231 sym::generic_arg_infer,
2233 "using `_` for array lengths is unstable",
2235 .stash(c.value.span, StashKey::UnderscoreForArrayLengths);
2236 hir::ArrayLen::Body(self.lower_anon_const(c))
2239 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2243 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2244 self.with_new_scopes(|this| hir::AnonConst {
2245 hir_id: this.lower_node_id(c.id),
2246 body: this.lower_const_body(c.value.span, Some(&c.value)),
2250 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2252 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2253 UserProvided => hir::UnsafeSource::UserProvided,
2257 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2259 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2260 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2262 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2263 // placeholder for compilation to proceed.
2264 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2265 hir::TraitBoundModifier::Maybe
2270 // Helper methods for building HIR.
2272 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2273 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2276 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2277 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2282 attrs: Option<&'hir [Attribute]>,
2284 init: Option<&'hir hir::Expr<'hir>>,
2285 pat: &'hir hir::Pat<'hir>,
2286 source: hir::LocalSource,
2287 ) -> hir::Stmt<'hir> {
2288 let hir_id = self.next_id();
2289 if let Some(a) = attrs {
2290 debug_assert!(!a.is_empty());
2291 self.attrs.insert(hir_id.local_id, a);
2293 let local = hir::Local {
2299 span: self.lower_span(span),
2302 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2305 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2306 self.block_all(expr.span, &[], Some(expr))
2312 stmts: &'hir [hir::Stmt<'hir>],
2313 expr: Option<&'hir hir::Expr<'hir>>,
2314 ) -> &'hir hir::Block<'hir> {
2315 let blk = hir::Block {
2318 hir_id: self.next_id(),
2319 rules: hir::BlockCheckMode::DefaultBlock,
2320 span: self.lower_span(span),
2321 targeted_by_break: false,
2323 self.arena.alloc(blk)
2326 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2327 let field = self.single_pat_field(span, pat);
2328 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2331 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2332 let field = self.single_pat_field(span, pat);
2333 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2336 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2337 let field = self.single_pat_field(span, pat);
2338 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2341 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2342 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2345 fn single_pat_field(
2348 pat: &'hir hir::Pat<'hir>,
2349 ) -> &'hir [hir::PatField<'hir>] {
2350 let field = hir::PatField {
2351 hir_id: self.next_id(),
2352 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2353 is_shorthand: false,
2355 span: self.lower_span(span),
2357 arena_vec![self; field]
2360 fn pat_lang_item_variant(
2363 lang_item: hir::LangItem,
2364 fields: &'hir [hir::PatField<'hir>],
2365 hir_id: Option<hir::HirId>,
2366 ) -> &'hir hir::Pat<'hir> {
2367 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2368 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2371 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2372 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::NONE)
2375 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2376 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::NONE)
2379 fn pat_ident_binding_mode(
2383 bm: hir::BindingAnnotation,
2384 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2385 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2386 (self.arena.alloc(pat), hir_id)
2389 fn pat_ident_binding_mode_mut(
2393 bm: hir::BindingAnnotation,
2394 ) -> (hir::Pat<'hir>, hir::HirId) {
2395 let hir_id = self.next_id();
2400 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2401 span: self.lower_span(span),
2402 default_binding_modes: true,
2408 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2409 self.arena.alloc(hir::Pat {
2410 hir_id: self.next_id(),
2412 span: self.lower_span(span),
2413 default_binding_modes: true,
2417 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2419 hir_id: self.next_id(),
2421 span: self.lower_span(span),
2422 default_binding_modes: false,
2428 mut hir_id: hir::HirId,
2430 qpath: hir::QPath<'hir>,
2431 ) -> hir::Ty<'hir> {
2432 let kind = match qpath {
2433 hir::QPath::Resolved(None, path) => {
2434 // Turn trait object paths into `TyKind::TraitObject` instead.
2436 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2437 let principal = hir::PolyTraitRef {
2438 bound_generic_params: &[],
2439 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2440 span: self.lower_span(span),
2443 // The original ID is taken by the `PolyTraitRef`,
2444 // so the `Ty` itself needs a different one.
2445 hir_id = self.next_id();
2446 hir::TyKind::TraitObject(
2447 arena_vec![self; principal],
2448 self.elided_dyn_bound(span),
2449 TraitObjectSyntax::None,
2452 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2455 _ => hir::TyKind::Path(qpath),
2458 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2461 /// Invoked to create the lifetime argument(s) for an elided trait object
2462 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2463 /// when the bound is written, even if it is written with `'_` like in
2464 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2465 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2466 let r = hir::Lifetime {
2467 hir_id: self.next_id(),
2468 span: self.lower_span(span),
2469 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2471 debug!("elided_dyn_bound: r={:?}", r);
2476 /// Helper struct for delayed construction of GenericArgs.
2477 struct GenericArgsCtor<'hir> {
2478 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2479 bindings: &'hir [hir::TypeBinding<'hir>],
2480 parenthesized: bool,
2484 impl<'hir> GenericArgsCtor<'hir> {
2485 fn is_empty(&self) -> bool {
2486 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2489 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2490 let ga = hir::GenericArgs {
2491 args: this.arena.alloc_from_iter(self.args),
2492 bindings: self.bindings,
2493 parenthesized: self.parenthesized,
2494 span_ext: this.lower_span(self.span),
2496 this.arena.alloc(ga)