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)]
44 use rustc_ast::{self as ast, *};
45 use rustc_ast_pretty::pprust;
46 use rustc_data_structures::captures::Captures;
47 use rustc_data_structures::fingerprint::Fingerprint;
48 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
49 use rustc_data_structures::sorted_map::SortedMap;
50 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
51 use rustc_data_structures::sync::Lrc;
52 use rustc_errors::{struct_span_err, Applicability};
54 use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
55 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
56 use rustc_hir::definitions::{DefPathData, Definitions};
57 use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate};
58 use rustc_index::vec::{Idx, IndexVec};
59 use rustc_middle::ty::{ResolverAstLowering, ResolverOutputs};
60 use rustc_query_system::ich::StableHashingContext;
61 use rustc_session::cstore::CrateStoreDyn;
62 use rustc_session::parse::feature_err;
63 use rustc_session::Session;
64 use rustc_span::hygiene::MacroKind;
65 use rustc_span::source_map::DesugaringKind;
66 use rustc_span::symbol::{kw, sym, Ident, Symbol};
67 use rustc_span::{Span, DUMMY_SP};
69 use smallvec::SmallVec;
70 use std::collections::hash_map::Entry;
72 macro_rules! arena_vec {
73 ($this:expr; $($x:expr),*) => (
74 $this.arena.alloc_from_iter([$($x),*])
86 rustc_hir::arena_types!(rustc_arena::declare_arena);
88 struct LoweringContext<'a, 'hir: 'a> {
89 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
92 definitions: &'a mut Definitions,
93 cstore: &'a CrateStoreDyn,
94 resolutions: &'a ResolverOutputs,
95 resolver: &'a mut ResolverAstLowering,
97 /// Used to allocate HIR nodes.
98 arena: &'hir Arena<'hir>,
100 /// Bodies inside the owner being lowered.
101 bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
102 /// Attributes inside the owner being lowered.
103 attrs: SortedMap<hir::ItemLocalId, &'hir [Attribute]>,
104 /// Collect items that were created by lowering the current owner.
105 children: FxHashMap<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
107 generator_kind: Option<hir::GeneratorKind>,
109 /// When inside an `async` context, this is the `HirId` of the
110 /// `task_context` local bound to the resume argument of the generator.
111 task_context: Option<hir::HirId>,
113 /// Used to get the current `fn`'s def span to point to when using `await`
114 /// outside of an `async fn`.
115 current_item: Option<Span>,
117 catch_scope: Option<NodeId>,
118 loop_scope: Option<NodeId>,
119 is_in_loop_condition: bool,
120 is_in_trait_impl: bool,
121 is_in_dyn_type: bool,
123 /// Used to handle lifetimes appearing in impl-traits.
124 captured_lifetimes: Option<LifetimeCaptureContext>,
126 current_hir_id_owner: LocalDefId,
127 item_local_id_counter: hir::ItemLocalId,
128 local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
129 trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
131 impl_trait_defs: Vec<hir::GenericParam<'hir>>,
132 impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
134 /// NodeIds that are lowered inside the current HIR owner.
135 node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
137 allow_try_trait: Option<Lrc<[Symbol]>>,
138 allow_gen_future: Option<Lrc<[Symbol]>>,
139 allow_into_future: Option<Lrc<[Symbol]>>,
142 /// When we lower a lifetime, it is inserted in `captures`, and the resolution is modified so
143 /// to point to the lifetime parameter impl-trait will generate.
144 /// When traversing `for<...>` binders, they are inserted in `binders_to_ignore` so we know *not*
145 /// to rebind the introduced lifetimes.
147 struct LifetimeCaptureContext {
148 /// parent def_id for new definitions
149 parent_def_id: LocalDefId,
150 /// Set of lifetimes to rebind.
152 LocalDefId, // original parameter id
155 NodeId, // synthetized parameter id
156 ParamName, // parameter name
157 LifetimeRes, // original resolution
160 /// Traversed binders. The ids in this set should *not* be rebound.
161 binders_to_ignore: FxHashSet<NodeId>,
164 trait ResolverAstLoweringExt {
165 fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>>;
166 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
167 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
168 fn get_label_res(&self, id: NodeId) -> Option<NodeId>;
169 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
170 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>;
171 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
174 impl ResolverAstLoweringExt for ResolverAstLowering {
175 fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>> {
176 if let ExprKind::Path(None, path) = &expr.kind {
177 // Don't perform legacy const generics rewriting if the path already
178 // has generic arguments.
179 if path.segments.last().unwrap().args.is_some() {
183 let partial_res = self.partial_res_map.get(&expr.id)?;
184 if partial_res.unresolved_segments() != 0 {
188 if let Res::Def(DefKind::Fn, def_id) = partial_res.base_res() {
189 // We only support cross-crate argument rewriting. Uses
190 // within the same crate should be updated to use the new
191 // const generics style.
192 if def_id.is_local() {
196 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
205 /// Obtains resolution for a `NodeId` with a single resolution.
206 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
207 self.partial_res_map.get(&id).copied()
210 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
211 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
212 self.import_res_map.get(&id).copied().unwrap_or_default()
215 /// Obtains resolution for a label with the given `NodeId`.
216 fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
217 self.label_res_map.get(&id).copied()
220 /// Obtains resolution for a lifetime with the given `NodeId`.
221 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
222 self.lifetimes_res_map.get(&id).copied()
225 /// Obtain the list of lifetimes parameters to add to an item.
227 /// Extra lifetime parameters should only be added in places that can appear
228 /// as a `binder` in `LifetimeRes`.
230 /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
231 /// should appear at the enclosing `PolyTraitRef`.
232 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
233 self.extra_lifetime_params_map.remove(&id).unwrap_or_default()
236 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind {
237 self.builtin_macro_kinds.get(&def_id).copied().unwrap_or(MacroKind::Bang)
241 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
242 /// and if so, what meaning it has.
243 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
244 enum ImplTraitContext {
245 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
246 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
247 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
249 /// Newly generated parameters should be inserted into the given `Vec`.
252 /// Treat `impl Trait` as shorthand for a new opaque type.
253 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
254 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
256 ReturnPositionOpaqueTy {
257 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
258 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)
330 fn impl_trait_return_allowed(&self) -> bool {
332 FnDeclKind::Fn | FnDeclKind::Inherent => true,
338 #[derive(Copy, Clone)]
341 Crate(&'a ast::Crate),
343 AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
344 ForeignItem(&'a ast::ForeignItem),
348 node_id_to_def_id: &FxHashMap<NodeId, LocalDefId>,
350 ) -> IndexVec<LocalDefId, AstOwner<'a>> {
351 let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() };
352 indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner);
353 indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate);
354 visit::walk_crate(&mut indexer, krate);
355 return indexer.index;
357 struct Indexer<'s, 'a> {
358 node_id_to_def_id: &'s FxHashMap<NodeId, LocalDefId>,
359 index: IndexVec<LocalDefId, AstOwner<'a>>,
362 impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
363 fn visit_attribute(&mut self, _: &'a Attribute) {
364 // We do not want to lower expressions that appear in attributes,
365 // as they are not accessible to the rest of the HIR.
368 fn visit_item(&mut self, item: &'a ast::Item) {
369 let def_id = self.node_id_to_def_id[&item.id];
370 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
371 self.index[def_id] = AstOwner::Item(item);
372 visit::walk_item(self, item)
375 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
376 let def_id = self.node_id_to_def_id[&item.id];
377 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
378 self.index[def_id] = AstOwner::AssocItem(item, ctxt);
379 visit::walk_assoc_item(self, item, ctxt);
382 fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
383 let def_id = self.node_id_to_def_id[&item.id];
384 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
385 self.index[def_id] = AstOwner::ForeignItem(item);
386 visit::walk_foreign_item(self, item);
391 /// Compute the hash for the HIR of the full crate.
392 /// This hash will then be part of the crate_hash which is stored in the metadata.
395 definitions: &Definitions,
396 cstore: &CrateStoreDyn,
397 resolver: &ResolverOutputs,
398 owners: &IndexVec<LocalDefId, hir::MaybeOwner<&hir::OwnerInfo<'_>>>,
400 let mut hir_body_nodes: Vec<_> = owners
402 .filter_map(|(def_id, info)| {
403 let info = info.as_owner()?;
404 let def_path_hash = definitions.def_path_hash(def_id);
405 Some((def_path_hash, info))
408 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
410 let mut stable_hasher = StableHasher::new();
411 let mut hcx = StableHashingContext::new(sess, definitions, cstore, &resolver.source_span);
412 hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
413 stable_hasher.finish()
416 pub fn lower_crate<'hir>(
419 definitions: &mut Definitions,
420 cstore: &CrateStoreDyn,
421 resolutions: &ResolverOutputs,
422 mut resolver: ResolverAstLowering,
423 arena: &'hir Arena<'hir>,
424 ) -> &'hir hir::Crate<'hir> {
425 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
427 let ast_index = index_crate(&resolver.node_id_to_def_id, krate);
430 IndexVec::from_fn_n(|_| hir::MaybeOwner::Phantom, definitions.def_index_count());
432 for def_id in ast_index.indices() {
438 resolver: &mut resolver,
440 ast_index: &ast_index,
446 let hir_hash = compute_hir_hash(sess, definitions, cstore, resolutions, &owners);
447 let krate = hir::Crate { owners, hir_hash };
451 #[derive(Copy, Clone, PartialEq, Debug)]
453 /// Any path in a type context.
455 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
457 /// The `module::Type` in `module::Type::method` in an expression.
461 enum ParenthesizedGenericArgs {
466 impl<'a, 'hir> LoweringContext<'a, 'hir> {
467 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
468 StableHashingContext::new(
472 &self.resolutions.source_span,
479 node_id: ast::NodeId,
483 self.opt_local_def_id(node_id).is_none(),
484 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
487 self.definitions.def_key(self.local_def_id(node_id)),
490 let def_id = self.definitions.create_def(parent, data);
492 // Some things for which we allocate `LocalDefId`s don't correspond to
493 // anything in the AST, so they don't have a `NodeId`. For these cases
494 // we don't need a mapping from `NodeId` to `LocalDefId`.
495 if node_id != ast::DUMMY_NODE_ID {
496 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
497 self.resolver.node_id_to_def_id.insert(node_id, def_id);
503 fn next_node_id(&mut self) -> NodeId {
504 let start = self.resolver.next_node_id;
505 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
506 self.resolver.next_node_id = ast::NodeId::from_u32(next);
510 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
511 self.resolver.node_id_to_def_id.get(&node).copied()
514 fn local_def_id(&self, node: NodeId) -> LocalDefId {
515 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
518 #[instrument(level = "debug", skip(self, f))]
519 fn with_hir_id_owner(
522 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
524 let def_id = self.local_def_id(owner);
526 let current_attrs = std::mem::take(&mut self.attrs);
527 let current_bodies = std::mem::take(&mut self.bodies);
528 let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
529 let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
530 let current_trait_map = std::mem::take(&mut self.trait_map);
531 let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
532 let current_local_counter =
533 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
534 let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
535 let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
536 // Do not reset `next_node_id` and `node_id_to_def_id` as we want to refer to the
537 // subdefinitions' nodes.
539 // Always allocate the first `HirId` for the owner itself.
540 let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
541 debug_assert_eq!(_old, None);
544 debug_assert_eq!(def_id, item.def_id());
545 // `f` should have consumed all the elements in these vectors when constructing `item`.
546 debug_assert!(self.impl_trait_defs.is_empty());
547 debug_assert!(self.impl_trait_bounds.is_empty());
548 let info = self.make_owner_info(item);
550 self.attrs = current_attrs;
551 self.bodies = current_bodies;
552 self.node_id_to_local_id = current_node_ids;
553 self.local_id_to_def_id = current_id_to_def_id;
554 self.trait_map = current_trait_map;
555 self.current_hir_id_owner = current_owner;
556 self.item_local_id_counter = current_local_counter;
557 self.impl_trait_defs = current_impl_trait_defs;
558 self.impl_trait_bounds = current_impl_trait_bounds;
560 let _old = self.children.insert(def_id, hir::MaybeOwner::Owner(info));
561 debug_assert!(_old.is_none())
564 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
565 let attrs = std::mem::take(&mut self.attrs);
566 let mut bodies = std::mem::take(&mut self.bodies);
567 let local_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
568 let trait_map = std::mem::take(&mut self.trait_map);
570 #[cfg(debug_assertions)]
571 for (id, attrs) in attrs.iter() {
572 // Verify that we do not store empty slices in the map.
573 if attrs.is_empty() {
574 panic!("Stored empty attributes for {:?}", id);
578 bodies.sort_by_key(|(k, _)| *k);
579 let bodies = SortedMap::from_presorted_elements(bodies);
580 let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
581 let (nodes, parenting) = index::index_hir(self.sess, self.definitions, node, &bodies);
582 let nodes = hir::OwnerNodes {
583 hash_including_bodies,
590 let mut hcx = self.create_stable_hashing_context();
591 let mut stable_hasher = StableHasher::new();
592 attrs.hash_stable(&mut hcx, &mut stable_hasher);
593 let hash = stable_hasher.finish();
594 hir::AttributeMap { map: attrs, hash }
597 self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map })
600 /// Hash the HIR node twice, one deep and one shallow hash. This allows to differentiate
601 /// queries which depend on the full HIR tree and those which only depend on the item signature.
604 node: hir::OwnerNode<'hir>,
605 bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
606 ) -> (Fingerprint, Fingerprint) {
607 let mut hcx = self.create_stable_hashing_context();
608 let mut stable_hasher = StableHasher::new();
609 hcx.with_hir_bodies(true, node.def_id(), bodies, |hcx| {
610 node.hash_stable(hcx, &mut stable_hasher)
612 let hash_including_bodies = stable_hasher.finish();
613 let mut stable_hasher = StableHasher::new();
614 hcx.with_hir_bodies(false, node.def_id(), bodies, |hcx| {
615 node.hash_stable(hcx, &mut stable_hasher)
617 let hash_without_bodies = stable_hasher.finish();
618 (hash_including_bodies, hash_without_bodies)
621 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
622 /// the `LoweringContext`'s `NodeId => HirId` map.
623 /// Take care not to call this method if the resulting `HirId` is then not
624 /// actually used in the HIR, as that would trigger an assertion in the
625 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
626 /// properly. Calling the method twice with the same `NodeId` is fine though.
627 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
628 assert_ne!(ast_node_id, DUMMY_NODE_ID);
630 match self.node_id_to_local_id.entry(ast_node_id) {
631 Entry::Occupied(o) => {
632 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
634 Entry::Vacant(v) => {
635 // Generate a new `HirId`.
636 let owner = self.current_hir_id_owner;
637 let local_id = self.item_local_id_counter;
638 let hir_id = hir::HirId { owner, local_id };
641 self.item_local_id_counter.increment_by(1);
643 assert_ne!(local_id, hir::ItemLocalId::new(0));
644 if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
645 // Do not override a `MaybeOwner::Owner` that may already here.
646 self.children.entry(def_id).or_insert(hir::MaybeOwner::NonOwner(hir_id));
647 self.local_id_to_def_id.insert(local_id, def_id);
650 if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
651 self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
659 fn next_id(&mut self) -> hir::HirId {
660 let node_id = self.next_node_id();
661 self.lower_node_id(node_id)
664 #[instrument(level = "trace", skip(self))]
665 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
666 let res: Result<Res, ()> = res.apply_id(|id| {
667 let owner = self.current_hir_id_owner;
668 let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
669 Ok(hir::HirId { owner, local_id })
673 // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
674 // This can happen when trying to lower the return type `x` in erroneous code like
675 // async fn foo(x: u8) -> x {}
676 // In that case, `x` is lowered as a function parameter, and the return type is lowered as
677 // an opaque type as a synthesized HIR owner.
678 res.unwrap_or(Res::Err)
681 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
682 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
683 if pr.unresolved_segments() != 0 {
684 panic!("path not fully resolved: {:?}", pr);
690 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
691 self.resolver.get_import_res(id).present_items()
694 fn diagnostic(&self) -> &rustc_errors::Handler {
695 self.sess.diagnostic()
698 /// Reuses the span but adds information like the kind of the desugaring and features that are
699 /// allowed inside this span.
700 fn mark_span_with_reason(
702 reason: DesugaringKind,
704 allow_internal_unstable: Option<Lrc<[Symbol]>>,
706 span.mark_with_reason(
707 allow_internal_unstable,
710 self.create_stable_hashing_context(),
714 /// Intercept all spans entering HIR.
715 /// Mark a span as relative to the current owning item.
716 fn lower_span(&self, span: Span) -> Span {
717 if self.sess.opts.debugging_opts.incremental_relative_spans {
718 span.with_parent(Some(self.current_hir_id_owner))
720 // Do not make spans relative when not using incremental compilation.
725 fn lower_ident(&self, ident: Ident) -> Ident {
726 Ident::new(ident.name, self.lower_span(ident.span))
729 /// Converts a lifetime into a new generic parameter.
730 #[tracing::instrument(level = "debug", skip(self))]
731 fn lifetime_res_to_generic_param(
736 ) -> Option<hir::GenericParam<'hir>> {
737 let (name, kind) = match res {
738 LifetimeRes::Param { .. } => {
739 (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
741 LifetimeRes::Fresh { param, .. } => {
742 // Late resolution delegates to us the creation of the `LocalDefId`.
743 let _def_id = self.create_def(
744 self.current_hir_id_owner,
746 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
750 (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided)
752 LifetimeRes::Static | LifetimeRes::Error => return None,
754 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
755 res, ident, ident.span
758 let hir_id = self.lower_node_id(node_id);
759 Some(hir::GenericParam {
762 span: self.lower_span(ident.span),
763 pure_wrt_drop: false,
764 kind: hir::GenericParamKind::Lifetime { kind },
769 /// Setup lifetime capture for and impl-trait.
770 /// The captures will be added to `captures`.
771 fn while_capturing_lifetimes<T>(
773 parent_def_id: LocalDefId,
774 captures: &mut FxHashMap<LocalDefId, (Span, NodeId, ParamName, LifetimeRes)>,
775 f: impl FnOnce(&mut Self) -> T,
777 let lifetime_stash = std::mem::replace(
778 &mut self.captured_lifetimes,
779 Some(LifetimeCaptureContext {
781 captures: std::mem::take(captures),
782 binders_to_ignore: Default::default(),
788 let ctxt = std::mem::replace(&mut self.captured_lifetimes, lifetime_stash).unwrap();
789 *captures = ctxt.captures;
794 /// Register a binder to be ignored for lifetime capture.
795 #[tracing::instrument(level = "debug", skip(self, f))]
797 fn with_lifetime_binder<T>(
800 generic_params: &[GenericParam],
801 f: impl FnOnce(&mut Self, &'hir [hir::GenericParam<'hir>]) -> T,
803 let mut generic_params: Vec<_> = self.lower_generic_params_mut(generic_params).collect();
804 let extra_lifetimes = self.resolver.take_extra_lifetime_params(binder);
805 debug!(?extra_lifetimes);
806 generic_params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
807 self.lifetime_res_to_generic_param(ident, node_id, res)
809 let generic_params = self.arena.alloc_from_iter(generic_params);
810 debug!(?generic_params);
812 if let Some(ctxt) = &mut self.captured_lifetimes {
813 ctxt.binders_to_ignore.insert(binder);
815 let ret = f(self, generic_params);
816 if let Some(ctxt) = &mut self.captured_lifetimes {
817 ctxt.binders_to_ignore.remove(&binder);
822 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
823 let was_in_dyn_type = self.is_in_dyn_type;
824 self.is_in_dyn_type = in_scope;
826 let result = f(self);
828 self.is_in_dyn_type = was_in_dyn_type;
833 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
834 let was_in_loop_condition = self.is_in_loop_condition;
835 self.is_in_loop_condition = false;
837 let catch_scope = self.catch_scope.take();
838 let loop_scope = self.loop_scope.take();
840 self.catch_scope = catch_scope;
841 self.loop_scope = loop_scope;
843 self.is_in_loop_condition = was_in_loop_condition;
848 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
849 if attrs.is_empty() {
852 debug_assert_eq!(id.owner, self.current_hir_id_owner);
853 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
854 debug_assert!(!ret.is_empty());
855 self.attrs.insert(id.local_id, ret);
860 fn lower_attr(&self, attr: &Attribute) -> Attribute {
861 // Note that we explicitly do not walk the path. Since we don't really
862 // lower attributes (we use the AST version) there is nowhere to keep
863 // the `HirId`s. We don't actually need HIR version of attributes anyway.
864 // Tokens are also not needed after macro expansion and parsing.
865 let kind = match attr.kind {
866 AttrKind::Normal(ref item, _) => AttrKind::Normal(
868 path: item.path.clone(),
869 args: self.lower_mac_args(&item.args),
874 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
877 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
880 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
881 debug_assert_eq!(id.owner, self.current_hir_id_owner);
882 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
883 if let Some(&a) = self.attrs.get(&target_id.local_id) {
884 debug_assert!(!a.is_empty());
885 self.attrs.insert(id.local_id, a);
889 fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
891 MacArgs::Empty => MacArgs::Empty,
892 MacArgs::Delimited(dspan, delim, ref tokens) => {
893 // This is either a non-key-value attribute, or a `macro_rules!` body.
894 // We either not have any nonterminals present (in the case of an attribute),
895 // or have tokens available for all nonterminals in the case of a nested
896 // `macro_rules`: e.g:
899 // macro_rules! outer {
901 // macro_rules! inner {
908 // In both cases, we don't want to synthesize any tokens
909 MacArgs::Delimited(dspan, delim, tokens.flattened())
911 // This is an inert key-value attribute - it will never be visible to macros
912 // after it gets lowered to HIR. Therefore, we can extract literals to handle
913 // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
914 MacArgs::Eq(eq_span, MacArgsEq::Ast(ref expr)) => {
915 // In valid code the value always ends up as a single literal. Otherwise, a dummy
916 // literal suffices because the error is handled elsewhere.
917 let lit = if let ExprKind::Lit(lit) = &expr.kind {
921 token: token::Lit::new(token::LitKind::Err, kw::Empty, None),
922 kind: LitKind::Err(kw::Empty),
926 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit))
928 MacArgs::Eq(_, MacArgsEq::Hir(ref lit)) => {
929 unreachable!("in literal form when lowering mac args eq: {:?}", lit)
934 /// Given an associated type constraint like one of these:
936 /// ```ignore (illustrative)
937 /// T: Iterator<Item: Debug>
939 /// T: Iterator<Item = Debug>
943 /// returns a `hir::TypeBinding` representing `Item`.
944 #[instrument(level = "debug", skip(self))]
945 fn lower_assoc_ty_constraint(
947 constraint: &AssocConstraint,
948 itctx: ImplTraitContext,
949 ) -> hir::TypeBinding<'hir> {
950 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
951 // lower generic arguments of identifier in constraint
952 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
953 let gen_args_ctor = match gen_args {
954 GenericArgs::AngleBracketed(ref data) => {
955 self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
957 GenericArgs::Parenthesized(ref data) => {
958 self.emit_bad_parenthesized_trait_in_assoc_ty(data);
959 self.lower_angle_bracketed_parameter_data(
960 &data.as_angle_bracketed_args(),
967 gen_args_ctor.into_generic_args(self)
969 self.arena.alloc(hir::GenericArgs::none())
972 let kind = match constraint.kind {
973 AssocConstraintKind::Equality { ref term } => {
974 let term = match term {
975 Term::Ty(ref ty) => self.lower_ty(ty, itctx).into(),
976 Term::Const(ref c) => self.lower_anon_const(c).into(),
978 hir::TypeBindingKind::Equality { term }
980 AssocConstraintKind::Bound { ref bounds } => {
981 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
982 let (desugar_to_impl_trait, itctx) = match itctx {
983 // We are in the return position:
985 // fn foo() -> impl Iterator<Item: Debug>
989 // fn foo() -> impl Iterator<Item = impl Debug>
990 ImplTraitContext::ReturnPositionOpaqueTy { .. }
991 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
993 // We are in the argument position, but within a dyn type:
995 // fn foo(x: dyn Iterator<Item: Debug>)
999 // fn foo(x: dyn Iterator<Item = impl Debug>)
1000 ImplTraitContext::Universal if self.is_in_dyn_type => (true, itctx),
1002 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1003 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1004 // "impl trait context" to permit `impl Debug` in this position (it desugars
1005 // then to an opaque type).
1007 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1008 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1009 (true, ImplTraitContext::TypeAliasesOpaqueTy)
1012 // We are in the parameter position, but not within a dyn type:
1014 // fn foo(x: impl Iterator<Item: Debug>)
1016 // so we leave it as is and this gets expanded in astconv to a bound like
1017 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1019 _ => (false, itctx),
1022 if desugar_to_impl_trait {
1023 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1024 // constructing the HIR for `impl bounds...` and then lowering that.
1026 let parent_def_id = self.current_hir_id_owner;
1027 let impl_trait_node_id = self.next_node_id();
1028 self.create_def(parent_def_id, impl_trait_node_id, DefPathData::ImplTrait);
1030 self.with_dyn_type_scope(false, |this| {
1031 let node_id = this.next_node_id();
1032 let ty = this.lower_ty(
1035 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1036 span: this.lower_span(constraint.span),
1042 hir::TypeBindingKind::Equality { term: ty.into() }
1045 // Desugar `AssocTy: Bounds` into a type binding where the
1046 // later desugars into a trait predicate.
1047 let bounds = self.lower_param_bounds(bounds, itctx);
1049 hir::TypeBindingKind::Constraint { bounds }
1055 hir_id: self.lower_node_id(constraint.id),
1056 ident: self.lower_ident(constraint.ident),
1059 span: self.lower_span(constraint.span),
1063 fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1064 let mut err = self.sess.struct_span_err(
1066 "parenthesized generic arguments cannot be used in associated type constraints",
1068 // Suggest removing empty parentheses: "Trait()" -> "Trait"
1069 if data.inputs.is_empty() {
1070 let parentheses_span =
1071 data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1072 err.multipart_suggestion(
1073 "remove these parentheses",
1074 vec![(parentheses_span, String::new())],
1075 Applicability::MaybeIncorrect,
1078 // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1080 // Start of parameters to the 1st argument
1081 let open_param = data.inputs_span.shrink_to_lo().to(data
1087 // End of last argument to end of parameters
1089 data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1090 err.multipart_suggestion(
1091 &format!("use angle brackets instead",),
1092 vec![(open_param, String::from("<")), (close_param, String::from(">"))],
1093 Applicability::MaybeIncorrect,
1099 #[instrument(level = "debug", skip(self))]
1100 fn lower_generic_arg(
1102 arg: &ast::GenericArg,
1103 itctx: ImplTraitContext,
1104 ) -> hir::GenericArg<'hir> {
1106 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1107 ast::GenericArg::Type(ty) => {
1109 TyKind::Infer if self.sess.features_untracked().generic_arg_infer => {
1110 return GenericArg::Infer(hir::InferArg {
1111 hir_id: self.lower_node_id(ty.id),
1112 span: self.lower_span(ty.span),
1115 // We parse const arguments as path types as we cannot distinguish them during
1116 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1117 // type and value namespaces. If we resolved the path in the value namespace, we
1118 // transform it into a generic const argument.
1119 TyKind::Path(ref qself, ref path) => {
1120 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1121 let res = partial_res.base_res();
1122 if !res.matches_ns(Namespace::TypeNS) {
1124 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1128 // Construct an AnonConst where the expr is the "ty"'s path.
1130 let parent_def_id = self.current_hir_id_owner;
1131 let node_id = self.next_node_id();
1133 // Add a definition for the in-band const def.
1134 self.create_def(parent_def_id, node_id, DefPathData::AnonConst);
1136 let span = self.lower_span(ty.span);
1137 let path_expr = Expr {
1139 kind: ExprKind::Path(qself.clone(), path.clone()),
1141 attrs: AttrVec::new(),
1145 let ct = self.with_new_scopes(|this| hir::AnonConst {
1146 hir_id: this.lower_node_id(node_id),
1147 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1149 return GenericArg::Const(ConstArg { value: ct, span });
1155 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1157 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1158 value: self.lower_anon_const(&ct),
1159 span: self.lower_span(ct.value.span),
1164 #[instrument(level = "debug", skip(self))]
1165 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> &'hir hir::Ty<'hir> {
1166 self.arena.alloc(self.lower_ty_direct(t, itctx))
1172 qself: &Option<QSelf>,
1174 param_mode: ParamMode,
1175 itctx: ImplTraitContext,
1176 ) -> hir::Ty<'hir> {
1177 let id = self.lower_node_id(t.id);
1178 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1179 self.ty_path(id, t.span, qpath)
1182 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1183 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1186 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1187 self.ty(span, hir::TyKind::Tup(tys))
1190 fn lower_ty_direct(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty<'hir> {
1191 let kind = match t.kind {
1192 TyKind::Infer => hir::TyKind::Infer,
1193 TyKind::Err => hir::TyKind::Err,
1194 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1195 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1196 TyKind::Rptr(ref region, ref mt) => {
1197 let region = region.unwrap_or_else(|| {
1198 let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1199 self.resolver.get_lifetime_res(t.id)
1201 debug_assert_eq!(start.plus(1), end);
1206 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1207 Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1209 let lifetime = self.lower_lifetime(®ion);
1210 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1212 TyKind::BareFn(ref f) => {
1213 self.with_lifetime_binder(t.id, &f.generic_params, |this, generic_params| {
1214 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1216 unsafety: this.lower_unsafety(f.unsafety),
1217 abi: this.lower_extern(f.ext),
1218 decl: this.lower_fn_decl(&f.decl, None, FnDeclKind::Pointer, None),
1219 param_names: this.lower_fn_params_to_names(&f.decl),
1223 TyKind::Never => hir::TyKind::Never,
1224 TyKind::Tup(ref tys) => hir::TyKind::Tup(
1225 self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty_direct(ty, itctx))),
1227 TyKind::Paren(ref ty) => {
1228 return self.lower_ty_direct(ty, itctx);
1230 TyKind::Path(ref qself, ref path) => {
1231 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1233 TyKind::ImplicitSelf => {
1234 let res = self.expect_full_res(t.id);
1235 let res = self.lower_res(res);
1236 hir::TyKind::Path(hir::QPath::Resolved(
1238 self.arena.alloc(hir::Path {
1240 segments: arena_vec![self; hir::PathSegment::from_ident(
1241 Ident::with_dummy_span(kw::SelfUpper)
1243 span: self.lower_span(t.span),
1247 TyKind::Array(ref ty, ref length) => {
1248 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1250 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1251 TyKind::TraitObject(ref bounds, kind) => {
1252 let mut lifetime_bound = None;
1253 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1255 this.arena.alloc_from_iter(bounds.iter().filter_map(
1256 |bound| match *bound {
1257 GenericBound::Trait(
1259 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1260 ) => Some(this.lower_poly_trait_ref(ty, itctx)),
1261 // `~const ?Bound` will cause an error during AST validation
1262 // anyways, so treat it like `?Bound` as compilation proceeds.
1263 GenericBound::Trait(
1265 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1267 GenericBound::Outlives(ref lifetime) => {
1268 if lifetime_bound.is_none() {
1269 lifetime_bound = Some(this.lower_lifetime(lifetime));
1275 let lifetime_bound =
1276 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1277 (bounds, lifetime_bound)
1279 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1281 TyKind::ImplTrait(def_node_id, ref bounds) => {
1284 ImplTraitContext::ReturnPositionOpaqueTy { origin } => self
1285 .lower_opaque_impl_trait(span, origin, def_node_id, |this| {
1286 this.lower_param_bounds(bounds, itctx)
1288 ImplTraitContext::TypeAliasesOpaqueTy => {
1289 let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy;
1290 self.lower_opaque_impl_trait(
1292 hir::OpaqueTyOrigin::TyAlias,
1294 |this| this.lower_param_bounds(bounds, nested_itctx),
1297 ImplTraitContext::Universal => {
1299 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1300 let (param, bounds, path) =
1301 self.lower_generic_and_bounds(def_node_id, span, ident, bounds);
1302 self.impl_trait_defs.push(param);
1303 if let Some(bounds) = bounds {
1304 self.impl_trait_bounds.push(bounds);
1308 ImplTraitContext::Disallowed(position) => {
1309 let mut err = struct_span_err!(
1313 "`impl Trait` only allowed in function and inherent method return types, not in {}",
1321 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1322 TyKind::CVarArgs => {
1323 self.sess.delay_span_bug(
1325 "`TyKind::CVarArgs` should have been handled elsewhere",
1331 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1334 #[tracing::instrument(level = "debug", skip(self, lower_bounds))]
1335 fn lower_opaque_impl_trait(
1338 origin: hir::OpaqueTyOrigin,
1339 opaque_ty_node_id: NodeId,
1340 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1341 ) -> hir::TyKind<'hir> {
1342 // Make sure we know that some funky desugaring has been going on here.
1343 // This is a first: there is code in other places like for loop
1344 // desugaring that explicitly states that we don't want to track that.
1345 // Not tracking it makes lints in rustc and clippy very fragile, as
1346 // frequently opened issues show.
1347 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1349 let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1351 let mut collected_lifetimes = FxHashMap::default();
1352 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1353 let hir_bounds = if origin == hir::OpaqueTyOrigin::TyAlias {
1356 lctx.while_capturing_lifetimes(
1358 &mut collected_lifetimes,
1362 debug!(?collected_lifetimes);
1364 let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1365 |(_, &(span, p_id, p_name, _))| {
1366 let hir_id = lctx.lower_node_id(p_id);
1367 debug_assert_ne!(lctx.opt_local_def_id(p_id), None);
1369 let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1370 hir::LifetimeParamKind::Elided
1372 hir::LifetimeParamKind::Explicit
1379 pure_wrt_drop: false,
1380 kind: hir::GenericParamKind::Lifetime { kind },
1386 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1388 let opaque_ty_item = hir::OpaqueTy {
1389 generics: self.arena.alloc(hir::Generics {
1390 params: lifetime_defs,
1392 has_where_clause_predicates: false,
1393 where_clause_span: lctx.lower_span(span),
1394 span: lctx.lower_span(span),
1400 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1401 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1404 let lifetimes = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
1405 |(_, (span, _, p_name, res))| {
1406 let id = self.next_node_id();
1407 let ident = Ident::new(p_name.ident().name, span);
1408 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1409 hir::GenericArg::Lifetime(l)
1413 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1415 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1416 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1419 /// Registers a new opaque type with the proper `NodeId`s and
1420 /// returns the lowered node-ID for the opaque type.
1421 fn generate_opaque_type(
1423 opaque_ty_id: LocalDefId,
1424 opaque_ty_item: hir::OpaqueTy<'hir>,
1426 opaque_ty_span: Span,
1427 ) -> hir::OwnerNode<'hir> {
1428 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1429 // Generate an `type Foo = impl Trait;` declaration.
1430 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1431 let opaque_ty_item = hir::Item {
1432 def_id: opaque_ty_id,
1433 ident: Ident::empty(),
1434 kind: opaque_ty_item_kind,
1435 vis_span: self.lower_span(span.shrink_to_lo()),
1436 span: self.lower_span(opaque_ty_span),
1438 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1441 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1442 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1443 // as they are not explicit in HIR/Ty function signatures.
1444 // (instead, the `c_variadic` flag is set to `true`)
1445 let mut inputs = &decl.inputs[..];
1446 if decl.c_variadic() {
1447 inputs = &inputs[..inputs.len() - 1];
1449 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1450 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1451 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1455 // Lowers a function declaration.
1457 // `decl`: the unlowered (AST) function declaration.
1458 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1459 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1460 // `make_ret_async` is also `Some`.
1461 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1462 // This guards against trait declarations and implementations where `impl Trait` is
1464 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1465 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1466 // return type `impl Trait` item.
1467 #[tracing::instrument(level = "debug", skip(self))]
1471 fn_node_id: Option<NodeId>,
1473 make_ret_async: Option<NodeId>,
1474 ) -> &'hir hir::FnDecl<'hir> {
1475 let c_variadic = decl.c_variadic();
1477 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1478 // as they are not explicit in HIR/Ty function signatures.
1479 // (instead, the `c_variadic` flag is set to `true`)
1480 let mut inputs = &decl.inputs[..];
1482 inputs = &inputs[..inputs.len() - 1];
1484 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1485 if fn_node_id.is_some() {
1486 self.lower_ty_direct(¶m.ty, ImplTraitContext::Universal)
1488 self.lower_ty_direct(
1490 ImplTraitContext::Disallowed(match kind {
1491 FnDeclKind::Fn | FnDeclKind::Inherent => {
1492 unreachable!("fn should allow in-band lifetimes")
1494 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1495 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1496 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1497 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1498 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1504 let output = if let Some(ret_id) = make_ret_async {
1505 self.lower_async_fn_ret_ty(
1507 fn_node_id.expect("`make_ret_async` but no `fn_def_id`"),
1512 FnRetTy::Ty(ref ty) => {
1513 let context = match fn_node_id {
1514 Some(fn_node_id) if kind.impl_trait_return_allowed() => {
1515 let fn_def_id = self.local_def_id(fn_node_id);
1516 ImplTraitContext::ReturnPositionOpaqueTy {
1517 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1520 _ => ImplTraitContext::Disallowed(match kind {
1521 FnDeclKind::Fn | FnDeclKind::Inherent => {
1522 unreachable!("fn should allow in-band lifetimes")
1524 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1525 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1526 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1527 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1528 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1531 hir::FnRetTy::Return(self.lower_ty(ty, context))
1533 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1537 self.arena.alloc(hir::FnDecl {
1541 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1542 use BindingMode::{ByRef, ByValue};
1543 let is_mutable_pat = matches!(
1545 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1549 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1550 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1551 // Given we are only considering `ImplicitSelf` types, we needn't consider
1552 // the case where we have a mutable pattern to a reference as that would
1553 // no longer be an `ImplicitSelf`.
1554 TyKind::Rptr(_, ref mt)
1555 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1557 hir::ImplicitSelfKind::MutRef
1559 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1560 hir::ImplicitSelfKind::ImmRef
1562 _ => hir::ImplicitSelfKind::None,
1568 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1569 // combined with the following definition of `OpaqueTy`:
1571 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1573 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1574 // `output`: unlowered output type (`T` in `-> T`)
1575 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1576 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1577 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1578 #[tracing::instrument(level = "debug", skip(self))]
1579 fn lower_async_fn_ret_ty(
1583 opaque_ty_node_id: NodeId,
1584 ) -> hir::FnRetTy<'hir> {
1585 let span = output.span();
1587 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1589 let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1590 let fn_def_id = self.local_def_id(fn_node_id);
1592 // When we create the opaque type for this async fn, it is going to have
1593 // to capture all the lifetimes involved in the signature (including in the
1594 // return type). This is done by introducing lifetime parameters for:
1596 // - all the explicitly declared lifetimes from the impl and function itself;
1597 // - all the elided lifetimes in the fn arguments;
1598 // - all the elided lifetimes in the return type.
1600 // So for example in this snippet:
1603 // impl<'a> Foo<'a> {
1604 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1605 // // ^ '0 ^ '1 ^ '2
1606 // // elided lifetimes used below
1611 // we would create an opaque type like:
1614 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1617 // and we would then desugar `bar` to the equivalent of:
1620 // impl<'a> Foo<'a> {
1621 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1625 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1626 // this is because the elided lifetimes from the return type
1627 // should be figured out using the ordinary elision rules, and
1628 // this desugaring achieves that.
1630 // Calculate all the lifetimes that should be captured
1631 // by the opaque type. This should include all in-scope
1632 // lifetime parameters, including those defined in-band.
1634 let mut captures = FxHashMap::default();
1636 let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1637 debug!(?extra_lifetime_params);
1638 for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1639 let Ident { name, span } = ident;
1640 let outer_def_id = self.local_def_id(outer_node_id);
1641 let inner_node_id = self.next_node_id();
1643 // Add a definition for the in scope lifetime def.
1644 self.create_def(opaque_ty_def_id, inner_node_id, DefPathData::LifetimeNs(name));
1646 let (p_name, inner_res) = match outer_res {
1647 // Input lifetime like `'a`:
1648 LifetimeRes::Param { param, .. } => {
1649 (hir::ParamName::Plain(ident), LifetimeRes::Param { param, binder: fn_node_id })
1651 // Input lifetime like `'1`:
1652 LifetimeRes::Fresh { param, .. } => {
1653 (hir::ParamName::Fresh, LifetimeRes::Fresh { param, binder: fn_node_id })
1655 LifetimeRes::Static | LifetimeRes::Error => continue,
1657 panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span)
1661 captures.insert(outer_def_id, (span, inner_node_id, p_name, inner_res));
1666 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1668 this.while_capturing_lifetimes(opaque_ty_def_id, &mut captures, |this| {
1669 // We have to be careful to get elision right here. The
1670 // idea is that we create a lifetime parameter for each
1671 // lifetime in the return type. So, given a return type
1672 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1673 // Future<Output = &'1 [ &'2 u32 ]>`.
1675 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1676 // hence the elision takes place at the fn site.
1677 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1679 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1680 debug!("lower_async_fn_ret_ty: captures={:#?}", captures);
1682 let generic_params =
1683 this.arena.alloc_from_iter(captures.iter().map(|(_, &(span, p_id, p_name, _))| {
1684 let hir_id = this.lower_node_id(p_id);
1685 debug_assert_ne!(this.opt_local_def_id(p_id), None);
1687 let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1688 hir::LifetimeParamKind::Elided
1690 hir::LifetimeParamKind::Explicit
1697 pure_wrt_drop: false,
1698 kind: hir::GenericParamKind::Lifetime { kind },
1702 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1704 let opaque_ty_item = hir::OpaqueTy {
1705 generics: this.arena.alloc(hir::Generics {
1706 params: generic_params,
1708 has_where_clause_predicates: false,
1709 where_clause_span: this.lower_span(span),
1710 span: this.lower_span(span),
1712 bounds: arena_vec![this; future_bound],
1713 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1716 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1717 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1720 // As documented above, we need to create the lifetime
1721 // arguments to our opaque type. Continuing with our example,
1722 // we're creating the type arguments for the return type:
1725 // Bar<'a, 'b, '0, '1, '_>
1728 // For the "input" lifetime parameters, we wish to create
1729 // references to the parameters themselves, including the
1730 // "implicit" ones created from parameter types (`'a`, `'b`,
1733 // For the "output" lifetime parameters, we just want to
1736 self.arena.alloc_from_iter(captures.into_iter().map(|(_, (span, _, p_name, res))| {
1737 let id = self.next_node_id();
1738 let ident = Ident::new(p_name.ident().name, span);
1739 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1740 hir::GenericArg::Lifetime(l)
1743 // Create the `Foo<...>` reference itself. Note that the `type
1744 // Foo = impl Trait` is, internally, created as a child of the
1745 // async fn, so the *type parameters* are inherited. It's
1746 // only the lifetime parameters that we must supply.
1748 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1749 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1750 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1753 /// Transforms `-> T` into `Future<Output = T>`.
1754 fn lower_async_fn_output_type_to_future_bound(
1757 fn_def_id: LocalDefId,
1759 ) -> hir::GenericBound<'hir> {
1760 // Compute the `T` in `Future<Output = T>` from the return type.
1761 let output_ty = match output {
1762 FnRetTy::Ty(ty) => {
1763 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1764 // `impl Future` opaque type that `async fn` implicitly
1766 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1767 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1769 self.lower_ty(ty, context)
1771 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1775 let future_args = self.arena.alloc(hir::GenericArgs {
1777 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1778 parenthesized: false,
1782 hir::GenericBound::LangItemTrait(
1783 // ::std::future::Future<future_params>
1784 hir::LangItem::Future,
1785 self.lower_span(span),
1791 #[instrument(level = "trace", skip(self))]
1792 fn lower_param_bound(
1795 itctx: ImplTraitContext,
1796 ) -> hir::GenericBound<'hir> {
1798 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1799 self.lower_poly_trait_ref(p, itctx),
1800 self.lower_trait_bound_modifier(*modifier),
1802 GenericBound::Outlives(lifetime) => {
1803 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1808 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1809 let span = self.lower_span(l.ident.span);
1810 let ident = self.lower_ident(l.ident);
1811 let res = self.resolver.get_lifetime_res(l.id).unwrap_or(LifetimeRes::Error);
1812 self.new_named_lifetime_with_res(l.id, span, ident, res)
1815 #[tracing::instrument(level = "debug", skip(self))]
1816 fn new_named_lifetime_with_res(
1822 ) -> hir::Lifetime {
1823 debug!(?self.captured_lifetimes);
1824 let name = match res {
1825 LifetimeRes::Param { mut param, binder } => {
1826 debug_assert_ne!(ident.name, kw::UnderscoreLifetime);
1827 let p_name = ParamName::Plain(ident);
1828 if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() {
1829 if !captured_lifetimes.binders_to_ignore.contains(&binder) {
1830 match captured_lifetimes.captures.entry(param) {
1831 Entry::Occupied(o) => param = self.local_def_id(o.get().1),
1832 Entry::Vacant(v) => {
1833 let p_id = self.next_node_id();
1834 let p_def_id = self.create_def(
1835 captured_lifetimes.parent_def_id,
1837 DefPathData::LifetimeNs(p_name.ident().name),
1840 v.insert((span, p_id, p_name, res));
1846 self.captured_lifetimes = Some(captured_lifetimes);
1848 hir::LifetimeName::Param(param, p_name)
1850 LifetimeRes::Fresh { param, binder } => {
1851 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1852 let mut param = self.local_def_id(param);
1853 if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() {
1854 if !captured_lifetimes.binders_to_ignore.contains(&binder) {
1855 match captured_lifetimes.captures.entry(param) {
1856 Entry::Occupied(o) => param = self.local_def_id(o.get().1),
1857 Entry::Vacant(v) => {
1858 let p_id = self.next_node_id();
1859 let p_def_id = self.create_def(
1860 captured_lifetimes.parent_def_id,
1862 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1865 v.insert((span, p_id, ParamName::Fresh, res));
1871 self.captured_lifetimes = Some(captured_lifetimes);
1873 hir::LifetimeName::Param(param, ParamName::Fresh)
1875 LifetimeRes::Anonymous { binder, elided } => {
1876 let mut l_name = None;
1877 if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() {
1878 if !captured_lifetimes.binders_to_ignore.contains(&binder) {
1879 let p_id = self.next_node_id();
1880 let p_def_id = self.create_def(
1881 captured_lifetimes.parent_def_id,
1883 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1887 .insert(p_def_id, (span, p_id, ParamName::Fresh, res));
1888 l_name = Some(hir::LifetimeName::Param(p_def_id, ParamName::Fresh));
1890 self.captured_lifetimes = Some(captured_lifetimes);
1892 l_name.unwrap_or(if elided {
1893 hir::LifetimeName::Implicit
1895 hir::LifetimeName::Underscore
1898 LifetimeRes::Static => hir::LifetimeName::Static,
1899 LifetimeRes::Error => hir::LifetimeName::Error,
1900 res => panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span),
1902 debug!(?self.captured_lifetimes);
1904 hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1907 fn lower_generic_params_mut<'s>(
1909 params: &'s [GenericParam],
1910 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1911 params.iter().map(move |param| self.lower_generic_param(param))
1914 fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
1915 self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
1918 #[instrument(level = "trace", skip(self))]
1919 fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
1920 let (name, kind) = self.lower_generic_param_kind(param);
1922 let hir_id = self.lower_node_id(param.id);
1923 self.lower_attrs(hir_id, ¶m.attrs);
1927 span: self.lower_span(param.span()),
1928 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
1930 colon_span: param.colon_span.map(|s| self.lower_span(s)),
1934 fn lower_generic_param_kind(
1936 param: &GenericParam,
1937 ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
1939 GenericParamKind::Lifetime => {
1940 // AST resolution emitted an error on those parameters, so we lower them using
1941 // `ParamName::Error`.
1943 if let Some(LifetimeRes::Error) = self.resolver.get_lifetime_res(param.id) {
1946 let ident = self.lower_ident(param.ident);
1947 ParamName::Plain(ident)
1950 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
1954 GenericParamKind::Type { ref default, .. } => {
1955 let kind = hir::GenericParamKind::Type {
1956 default: default.as_ref().map(|x| {
1957 self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
1962 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
1964 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1965 let ty = self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
1966 let default = default.as_ref().map(|def| self.lower_anon_const(def));
1968 hir::ParamName::Plain(self.lower_ident(param.ident)),
1969 hir::GenericParamKind::Const { ty, default },
1975 fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext) -> hir::TraitRef<'hir> {
1976 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
1977 hir::QPath::Resolved(None, path) => path,
1978 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
1980 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
1983 #[tracing::instrument(level = "debug", skip(self))]
1984 fn lower_poly_trait_ref(
1987 itctx: ImplTraitContext,
1988 ) -> hir::PolyTraitRef<'hir> {
1989 self.with_lifetime_binder(
1991 &p.bound_generic_params,
1992 |this, bound_generic_params| {
1993 let trait_ref = this.lower_trait_ref(&p.trait_ref, itctx);
1994 hir::PolyTraitRef { bound_generic_params, trait_ref, span: this.lower_span(p.span) }
1999 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2000 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2003 fn lower_param_bounds(
2005 bounds: &[GenericBound],
2006 itctx: ImplTraitContext,
2007 ) -> hir::GenericBounds<'hir> {
2008 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2011 fn lower_param_bounds_mut<'s>(
2013 bounds: &'s [GenericBound],
2014 itctx: ImplTraitContext,
2015 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2016 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx))
2019 fn lower_generic_and_bounds(
2024 bounds: &[GenericBound],
2025 ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2026 // Add a definition for the in-band `Param`.
2027 let def_id = self.local_def_id(node_id);
2029 let hir_bounds = self.lower_param_bounds(bounds, ImplTraitContext::Universal);
2030 // Set the name to `impl Bound1 + Bound2`.
2031 let param = hir::GenericParam {
2032 hir_id: self.lower_node_id(node_id),
2033 name: ParamName::Plain(self.lower_ident(ident)),
2034 pure_wrt_drop: false,
2035 span: self.lower_span(span),
2036 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2040 let preds = self.lower_generic_bound_predicate(
2043 &GenericParamKind::Type { default: None },
2045 hir::PredicateOrigin::ImplTrait,
2048 let ty = hir::TyKind::Path(hir::QPath::Resolved(
2050 self.arena.alloc(hir::Path {
2051 span: self.lower_span(span),
2052 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
2053 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
2060 /// Lowers a block directly to an expression, presuming that it
2061 /// has no attributes and is not targeted by a `break`.
2062 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2063 let block = self.lower_block(b, false);
2064 self.expr_block(block, AttrVec::new())
2067 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2068 match c.value.kind {
2069 ExprKind::Underscore => {
2070 if self.sess.features_untracked().generic_arg_infer {
2071 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2074 &self.sess.parse_sess,
2075 sym::generic_arg_infer,
2077 "using `_` for array lengths is unstable",
2080 hir::ArrayLen::Body(self.lower_anon_const(c))
2083 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2087 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2088 self.with_new_scopes(|this| hir::AnonConst {
2089 hir_id: this.lower_node_id(c.id),
2090 body: this.lower_const_body(c.value.span, Some(&c.value)),
2094 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2096 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2097 UserProvided => hir::UnsafeSource::UserProvided,
2101 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2103 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2104 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2106 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2107 // placeholder for compilation to proceed.
2108 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2109 hir::TraitBoundModifier::Maybe
2114 // Helper methods for building HIR.
2116 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2117 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2120 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2121 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2126 attrs: Option<&'hir [Attribute]>,
2128 init: Option<&'hir hir::Expr<'hir>>,
2129 pat: &'hir hir::Pat<'hir>,
2130 source: hir::LocalSource,
2131 ) -> hir::Stmt<'hir> {
2132 let hir_id = self.next_id();
2133 if let Some(a) = attrs {
2134 debug_assert!(!a.is_empty());
2135 self.attrs.insert(hir_id.local_id, a);
2137 let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2138 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2141 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2142 self.block_all(expr.span, &[], Some(expr))
2148 stmts: &'hir [hir::Stmt<'hir>],
2149 expr: Option<&'hir hir::Expr<'hir>>,
2150 ) -> &'hir hir::Block<'hir> {
2151 let blk = hir::Block {
2154 hir_id: self.next_id(),
2155 rules: hir::BlockCheckMode::DefaultBlock,
2156 span: self.lower_span(span),
2157 targeted_by_break: false,
2159 self.arena.alloc(blk)
2162 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2163 let field = self.single_pat_field(span, pat);
2164 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2167 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2168 let field = self.single_pat_field(span, pat);
2169 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2172 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2173 let field = self.single_pat_field(span, pat);
2174 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2177 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2178 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2181 fn single_pat_field(
2184 pat: &'hir hir::Pat<'hir>,
2185 ) -> &'hir [hir::PatField<'hir>] {
2186 let field = hir::PatField {
2187 hir_id: self.next_id(),
2188 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2189 is_shorthand: false,
2191 span: self.lower_span(span),
2193 arena_vec![self; field]
2196 fn pat_lang_item_variant(
2199 lang_item: hir::LangItem,
2200 fields: &'hir [hir::PatField<'hir>],
2201 hir_id: Option<hir::HirId>,
2202 ) -> &'hir hir::Pat<'hir> {
2203 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2204 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2207 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2208 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2211 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2212 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2215 fn pat_ident_binding_mode(
2219 bm: hir::BindingAnnotation,
2220 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2221 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2222 (self.arena.alloc(pat), hir_id)
2225 fn pat_ident_binding_mode_mut(
2229 bm: hir::BindingAnnotation,
2230 ) -> (hir::Pat<'hir>, hir::HirId) {
2231 let hir_id = self.next_id();
2236 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2237 span: self.lower_span(span),
2238 default_binding_modes: true,
2244 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2245 self.arena.alloc(hir::Pat {
2246 hir_id: self.next_id(),
2248 span: self.lower_span(span),
2249 default_binding_modes: true,
2253 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2255 hir_id: self.next_id(),
2257 span: self.lower_span(span),
2258 default_binding_modes: false,
2264 mut hir_id: hir::HirId,
2266 qpath: hir::QPath<'hir>,
2267 ) -> hir::Ty<'hir> {
2268 let kind = match qpath {
2269 hir::QPath::Resolved(None, path) => {
2270 // Turn trait object paths into `TyKind::TraitObject` instead.
2272 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2273 let principal = hir::PolyTraitRef {
2274 bound_generic_params: &[],
2275 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2276 span: self.lower_span(span),
2279 // The original ID is taken by the `PolyTraitRef`,
2280 // so the `Ty` itself needs a different one.
2281 hir_id = self.next_id();
2282 hir::TyKind::TraitObject(
2283 arena_vec![self; principal],
2284 self.elided_dyn_bound(span),
2285 TraitObjectSyntax::None,
2288 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2291 _ => hir::TyKind::Path(qpath),
2294 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2297 /// Invoked to create the lifetime argument(s) for an elided trait object
2298 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2299 /// when the bound is written, even if it is written with `'_` like in
2300 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2301 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2302 let r = hir::Lifetime {
2303 hir_id: self.next_id(),
2304 span: self.lower_span(span),
2305 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2307 debug!("elided_dyn_bound: r={:?}", r);
2312 /// Helper struct for delayed construction of GenericArgs.
2313 struct GenericArgsCtor<'hir> {
2314 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2315 bindings: &'hir [hir::TypeBinding<'hir>],
2316 parenthesized: bool,
2320 impl<'hir> GenericArgsCtor<'hir> {
2321 fn is_empty(&self) -> bool {
2322 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2325 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2326 let ga = hir::GenericArgs {
2327 args: this.arena.alloc_from_iter(self.args),
2328 bindings: self.bindings,
2329 parenthesized: self.parenthesized,
2330 span_ext: this.lower_span(self.span),
2332 this.arena.alloc(ga)