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)]
40 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream};
42 use rustc_ast::{self as ast, *};
43 use rustc_ast_pretty::pprust;
44 use rustc_data_structures::captures::Captures;
45 use rustc_data_structures::fingerprint::Fingerprint;
46 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
47 use rustc_data_structures::sorted_map::SortedMap;
48 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
49 use rustc_data_structures::sync::Lrc;
50 use rustc_errors::struct_span_err;
52 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
53 use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID};
54 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
55 use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate};
56 use rustc_index::vec::{Idx, IndexVec};
57 use rustc_query_system::ich::StableHashingContext;
58 use rustc_session::parse::feature_err;
59 use rustc_session::utils::{FlattenNonterminals, NtToTokenstream};
60 use rustc_session::Session;
61 use rustc_span::hygiene::{ExpnId, MacroKind};
62 use rustc_span::source_map::DesugaringKind;
63 use rustc_span::symbol::{kw, sym, Ident, Symbol};
64 use rustc_span::{Span, DUMMY_SP};
66 use smallvec::SmallVec;
67 use std::collections::hash_map::Entry;
68 use tracing::{debug, trace};
70 macro_rules! arena_vec {
71 ($this:expr; $($x:expr),*) => (
72 $this.arena.alloc_from_iter([$($x),*])
84 rustc_hir::arena_types!(rustc_arena::declare_arena);
86 struct LoweringContext<'a, 'hir: 'a> {
87 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
90 resolver: &'a mut dyn ResolverAstLowering,
92 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
93 /// if we don't have this function pointer. To avoid that dependency so that
94 /// `rustc_middle` is independent of the parser, we use dynamic dispatch here.
95 nt_to_tokenstream: NtToTokenstream,
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 /// NodeIds that are lowered inside the current HIR owner.
132 node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
134 allow_try_trait: Option<Lrc<[Symbol]>>,
135 allow_gen_future: Option<Lrc<[Symbol]>>,
136 allow_into_future: Option<Lrc<[Symbol]>>,
139 /// Resolution for a lifetime appearing in a type.
140 #[derive(Copy, Clone, Debug)]
141 pub enum LifetimeRes {
142 /// Successfully linked the lifetime to a generic parameter.
144 /// Id of the generic parameter that introduced it.
146 /// Id of the introducing place. That can be:
147 /// - an item's id, for the item's generic parameters;
148 /// - a TraitRef's ref_id, identifying the `for<...>` binder;
149 /// - a BareFn type's id;
150 /// - a Path's id when this path has parenthesized generic args.
152 /// This information is used for impl-trait lifetime captures, to know when to or not to
153 /// capture any given lifetime.
156 /// Created a generic parameter for an anonymous lifetime.
158 /// Id of the generic parameter that introduced it.
160 /// Id of the introducing place. See `Param`.
163 /// This variant is used for anonymous lifetimes that we did not resolve during
164 /// late resolution. Shifting the work to the HIR lifetime resolver.
166 /// Id of the introducing place. See `Param`.
168 /// Whether this lifetime was spelled or elided.
171 /// Explicit `'static` lifetime.
173 /// Resolution failure.
175 /// HACK: This is used to recover the NodeId of an elided lifetime.
176 ElidedAnchor { start: NodeId, end: NodeId },
179 /// When we lower a lifetime, it is inserted in `captures`, and the resolution is modified so
180 /// to point to the lifetime parameter impl-trait will generate.
181 /// When traversing `for<...>` binders, they are inserted in `binders_to_ignore` so we know *not*
182 /// to rebind the introduced lifetimes.
184 struct LifetimeCaptureContext {
185 /// parent def_id for new definitions
186 parent_def_id: LocalDefId,
187 /// Set of lifetimes to rebind.
189 LocalDefId, // original parameter id
192 NodeId, // synthetized parameter id
193 ParamName, // parameter name
194 LifetimeRes, // original resolution
197 /// Traversed binders. The ids in this set should *not* be rebound.
198 binders_to_ignore: FxHashSet<NodeId>,
201 pub trait ResolverAstLowering {
202 fn def_key(&self, id: DefId) -> DefKey;
204 fn def_span(&self, id: LocalDefId) -> Span;
206 fn item_generics_num_lifetimes(&self, def: DefId) -> usize;
208 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>>;
210 /// Obtains resolution for a `NodeId` with a single resolution.
211 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
213 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
214 fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
216 /// Obtains resolution for a label with the given `NodeId`.
217 fn get_label_res(&self, id: NodeId) -> Option<NodeId>;
219 /// Obtains resolution for a lifetime with the given `NodeId`.
220 fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
222 /// Obtain the list of lifetimes parameters to add to an item.
223 fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>;
225 fn create_stable_hashing_context(&self) -> StableHashingContext<'_>;
227 fn definitions(&self) -> &Definitions;
229 fn next_node_id(&mut self) -> NodeId;
231 fn take_trait_map(&mut self, node: NodeId) -> Option<Vec<hir::TraitCandidate>>;
233 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
235 fn local_def_id(&self, node: NodeId) -> LocalDefId;
237 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
242 node_id: ast::NodeId,
248 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
251 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
252 /// and if so, what meaning it has.
254 enum ImplTraitContext<'b, 'a> {
255 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
256 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
257 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
259 /// Newly generated parameters should be inserted into the given `Vec`.
260 Universal(&'b mut Vec<hir::GenericParam<'a>>, &'b mut Vec<hir::WherePredicate<'a>>, LocalDefId),
262 /// Treat `impl Trait` as shorthand for a new opaque type.
263 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
264 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
266 ReturnPositionOpaqueTy {
267 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
268 origin: hir::OpaqueTyOrigin,
270 /// Impl trait in type aliases.
272 /// `impl Trait` is not accepted in this position.
273 Disallowed(ImplTraitPosition),
276 /// Position in which `impl Trait` is disallowed.
277 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
278 enum ImplTraitPosition {
300 impl<'a> ImplTraitContext<'_, 'a> {
301 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
302 use self::ImplTraitContext::*;
304 Universal(params, bounds, parent) => Universal(params, bounds, *parent),
305 ReturnPositionOpaqueTy { origin } => ReturnPositionOpaqueTy { origin: *origin },
306 TypeAliasesOpaqueTy => TypeAliasesOpaqueTy,
307 Disallowed(pos) => Disallowed(*pos),
312 impl std::fmt::Display for ImplTraitPosition {
313 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314 let name = match self {
315 ImplTraitPosition::Path => "path",
316 ImplTraitPosition::Variable => "variable binding",
317 ImplTraitPosition::Type => "type",
318 ImplTraitPosition::Trait => "trait",
319 ImplTraitPosition::AsyncBlock => "async block",
320 ImplTraitPosition::Bound => "bound",
321 ImplTraitPosition::Generic => "generic",
322 ImplTraitPosition::ExternFnParam => "`extern fn` param",
323 ImplTraitPosition::ClosureParam => "closure param",
324 ImplTraitPosition::PointerParam => "`fn` pointer param",
325 ImplTraitPosition::FnTraitParam => "`Fn` trait param",
326 ImplTraitPosition::TraitParam => "trait method param",
327 ImplTraitPosition::ImplParam => "`impl` method param",
328 ImplTraitPosition::ExternFnReturn => "`extern fn` return",
329 ImplTraitPosition::ClosureReturn => "closure return",
330 ImplTraitPosition::PointerReturn => "`fn` pointer return",
331 ImplTraitPosition::FnTraitReturn => "`Fn` trait return",
332 ImplTraitPosition::TraitReturn => "trait method return",
333 ImplTraitPosition::ImplReturn => "`impl` method return",
336 write!(f, "{}", name)
352 fn impl_trait_return_allowed(&self) -> bool {
354 FnDeclKind::Fn | FnDeclKind::Inherent => true,
360 #[derive(Copy, Clone)]
363 Crate(&'a ast::Crate),
365 AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
366 ForeignItem(&'a ast::ForeignItem),
370 resolver: &dyn ResolverAstLowering,
372 ) -> IndexVec<LocalDefId, AstOwner<'a>> {
373 let mut indexer = Indexer { resolver, index: IndexVec::new() };
374 indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner);
375 indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate);
376 visit::walk_crate(&mut indexer, krate);
377 return indexer.index;
379 struct Indexer<'s, 'a> {
380 resolver: &'s dyn ResolverAstLowering,
381 index: IndexVec<LocalDefId, AstOwner<'a>>,
384 impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
385 fn visit_attribute(&mut self, _: &'a Attribute) {
386 // We do not want to lower expressions that appear in attributes,
387 // as they are not accessible to the rest of the HIR.
390 fn visit_item(&mut self, item: &'a ast::Item) {
391 let def_id = self.resolver.local_def_id(item.id);
392 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
393 self.index[def_id] = AstOwner::Item(item);
394 visit::walk_item(self, item)
397 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
398 let def_id = self.resolver.local_def_id(item.id);
399 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
400 self.index[def_id] = AstOwner::AssocItem(item, ctxt);
401 visit::walk_assoc_item(self, item, ctxt);
404 fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
405 let def_id = self.resolver.local_def_id(item.id);
406 self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
407 self.index[def_id] = AstOwner::ForeignItem(item);
408 visit::walk_foreign_item(self, item);
413 /// Compute the hash for the HIR of the full crate.
414 /// This hash will then be part of the crate_hash which is stored in the metadata.
416 resolver: &mut dyn ResolverAstLowering,
417 owners: &IndexVec<LocalDefId, hir::MaybeOwner<&hir::OwnerInfo<'_>>>,
419 let mut hir_body_nodes: Vec<_> = owners
421 .filter_map(|(def_id, info)| {
422 let info = info.as_owner()?;
423 let def_path_hash = resolver.definitions().def_path_hash(def_id);
424 Some((def_path_hash, info))
427 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
429 let mut stable_hasher = StableHasher::new();
430 let mut hcx = resolver.create_stable_hashing_context();
431 hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
432 stable_hasher.finish()
435 pub fn lower_crate<'a, 'hir>(
438 resolver: &'a mut dyn ResolverAstLowering,
439 nt_to_tokenstream: NtToTokenstream,
440 arena: &'hir Arena<'hir>,
441 ) -> &'hir hir::Crate<'hir> {
442 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
444 let ast_index = index_crate(resolver, krate);
447 IndexVec::from_fn_n(|_| hir::MaybeOwner::Phantom, resolver.definitions().def_index_count());
449 for def_id in ast_index.indices() {
455 ast_index: &ast_index,
461 let hir_hash = compute_hir_hash(resolver, &owners);
462 let krate = hir::Crate { owners, hir_hash };
466 #[derive(Copy, Clone, PartialEq)]
468 /// Any path in a type context.
470 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
472 /// The `module::Type` in `module::Type::method` in an expression.
476 enum ParenthesizedGenericArgs {
481 impl<'a, 'hir> LoweringContext<'a, 'hir> {
482 fn with_hir_id_owner(
485 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
487 let def_id = self.resolver.local_def_id(owner);
489 let current_attrs = std::mem::take(&mut self.attrs);
490 let current_bodies = std::mem::take(&mut self.bodies);
491 let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
492 let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
493 let current_trait_map = std::mem::take(&mut self.trait_map);
494 let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
495 let current_local_counter =
496 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
498 // Always allocate the first `HirId` for the owner itself.
499 let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
500 debug_assert_eq!(_old, None);
503 debug_assert_eq!(def_id, item.def_id());
504 let info = self.make_owner_info(item);
506 self.attrs = current_attrs;
507 self.bodies = current_bodies;
508 self.node_id_to_local_id = current_node_ids;
509 self.local_id_to_def_id = current_id_to_def_id;
510 self.trait_map = current_trait_map;
511 self.current_hir_id_owner = current_owner;
512 self.item_local_id_counter = current_local_counter;
514 let _old = self.children.insert(def_id, hir::MaybeOwner::Owner(info));
515 debug_assert!(_old.is_none())
518 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
519 let attrs = std::mem::take(&mut self.attrs);
520 let mut bodies = std::mem::take(&mut self.bodies);
521 let local_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
522 let trait_map = std::mem::take(&mut self.trait_map);
524 #[cfg(debug_assertions)]
525 for (id, attrs) in attrs.iter() {
526 // Verify that we do not store empty slices in the map.
527 if attrs.is_empty() {
528 panic!("Stored empty attributes for {:?}", id);
532 bodies.sort_by_key(|(k, _)| *k);
533 let bodies = SortedMap::from_presorted_elements(bodies);
534 let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
535 let (nodes, parenting) =
536 index::index_hir(self.sess, self.resolver.definitions(), node, &bodies);
537 let nodes = hir::OwnerNodes {
538 hash_including_bodies,
545 let mut hcx = self.resolver.create_stable_hashing_context();
546 let mut stable_hasher = StableHasher::new();
547 attrs.hash_stable(&mut hcx, &mut stable_hasher);
548 let hash = stable_hasher.finish();
549 hir::AttributeMap { map: attrs, hash }
552 self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map })
555 /// Hash the HIR node twice, one deep and one shallow hash. This allows to differentiate
556 /// queries which depend on the full HIR tree and those which only depend on the item signature.
559 node: hir::OwnerNode<'hir>,
560 bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
561 ) -> (Fingerprint, Fingerprint) {
562 let mut hcx = self.resolver.create_stable_hashing_context();
563 let mut stable_hasher = StableHasher::new();
564 hcx.with_hir_bodies(true, node.def_id(), bodies, |hcx| {
565 node.hash_stable(hcx, &mut stable_hasher)
567 let hash_including_bodies = stable_hasher.finish();
568 let mut stable_hasher = StableHasher::new();
569 hcx.with_hir_bodies(false, node.def_id(), bodies, |hcx| {
570 node.hash_stable(hcx, &mut stable_hasher)
572 let hash_without_bodies = stable_hasher.finish();
573 (hash_including_bodies, hash_without_bodies)
576 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
577 /// the `LoweringContext`'s `NodeId => HirId` map.
578 /// Take care not to call this method if the resulting `HirId` is then not
579 /// actually used in the HIR, as that would trigger an assertion in the
580 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
581 /// properly. Calling the method twice with the same `NodeId` is fine though.
582 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
583 assert_ne!(ast_node_id, DUMMY_NODE_ID);
585 match self.node_id_to_local_id.entry(ast_node_id) {
586 Entry::Occupied(o) => {
587 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
589 Entry::Vacant(v) => {
590 // Generate a new `HirId`.
591 let owner = self.current_hir_id_owner;
592 let local_id = self.item_local_id_counter;
593 let hir_id = hir::HirId { owner, local_id };
596 self.item_local_id_counter.increment_by(1);
598 assert_ne!(local_id, hir::ItemLocalId::new(0));
599 if let Some(def_id) = self.resolver.opt_local_def_id(ast_node_id) {
600 // Do not override a `MaybeOwner::Owner` that may already here.
601 self.children.entry(def_id).or_insert(hir::MaybeOwner::NonOwner(hir_id));
602 self.local_id_to_def_id.insert(local_id, def_id);
605 if let Some(traits) = self.resolver.take_trait_map(ast_node_id) {
606 self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
614 fn next_id(&mut self) -> hir::HirId {
615 let node_id = self.resolver.next_node_id();
616 self.lower_node_id(node_id)
619 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
620 let res: Result<Res, ()> = res.apply_id(|id| {
621 let owner = self.current_hir_id_owner;
622 let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
623 Ok(hir::HirId { owner, local_id })
625 // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
626 // This can happen when trying to lower the return type `x` in erroneous code like
627 // async fn foo(x: u8) -> x {}
628 // In that case, `x` is lowered as a function parameter, and the return type is lowered as
629 // an opaque type as a synthesized HIR owner.
630 res.unwrap_or(Res::Err)
633 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
634 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
635 if pr.unresolved_segments() != 0 {
636 panic!("path not fully resolved: {:?}", pr);
642 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
643 self.resolver.get_import_res(id).present_items()
646 fn diagnostic(&self) -> &rustc_errors::Handler {
647 self.sess.diagnostic()
650 /// Reuses the span but adds information like the kind of the desugaring and features that are
651 /// allowed inside this span.
652 fn mark_span_with_reason(
654 reason: DesugaringKind,
656 allow_internal_unstable: Option<Lrc<[Symbol]>>,
658 span.mark_with_reason(
659 allow_internal_unstable,
662 self.resolver.create_stable_hashing_context(),
666 /// Intercept all spans entering HIR.
667 /// Mark a span as relative to the current owning item.
668 fn lower_span(&self, span: Span) -> Span {
669 if self.sess.opts.debugging_opts.incremental_relative_spans {
670 span.with_parent(Some(self.current_hir_id_owner))
672 // Do not make spans relative when not using incremental compilation.
677 fn lower_ident(&self, ident: Ident) -> Ident {
678 Ident::new(ident.name, self.lower_span(ident.span))
681 /// Converts a lifetime into a new generic parameter.
682 fn lifetime_res_to_generic_param(
687 ) -> Option<hir::GenericParam<'hir>> {
688 let (name, kind) = match res {
689 LifetimeRes::Param { .. } => {
690 (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
692 LifetimeRes::Fresh { param, .. } => {
693 (hir::ParamName::Fresh(param), hir::LifetimeParamKind::Elided)
695 LifetimeRes::Static | LifetimeRes::Error => return None,
697 "Unexpected lifetime resolution {:?} for {:?} at {:?}",
698 res, ident, ident.span
701 let hir_id = self.lower_node_id(node_id);
702 Some(hir::GenericParam {
705 span: self.lower_span(ident.span),
706 pure_wrt_drop: false,
707 kind: hir::GenericParamKind::Lifetime { kind },
712 /// Creates a new `hir::GenericParam` for every new `Fresh` lifetime and
713 /// universal `impl Trait` type parameter encountered while evaluating `f`.
714 /// Definitions are created with the provided `parent_def_id`.
715 fn add_implicit_generics<T>(
718 parent_node_id: NodeId,
721 &mut Vec<hir::GenericParam<'hir>>,
722 &mut Vec<hir::WherePredicate<'hir>>,
724 ) -> (&'hir hir::Generics<'hir>, T) {
725 let mut impl_trait_defs = Vec::new();
726 let mut impl_trait_bounds = Vec::new();
727 let mut lowered_generics = self.lower_generics_mut(
729 ImplTraitContext::Universal(
730 &mut impl_trait_defs,
731 &mut impl_trait_bounds,
732 self.current_hir_id_owner,
735 let res = f(self, &mut impl_trait_defs, &mut impl_trait_bounds);
737 let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
738 lowered_generics.params.extend(
741 .filter_map(|(ident, node_id, res)| {
742 self.lifetime_res_to_generic_param(ident, node_id, res)
744 .chain(impl_trait_defs),
746 lowered_generics.predicates.extend(impl_trait_bounds);
748 let lowered_generics = lowered_generics.into_generics(self.arena);
749 (lowered_generics, res)
752 /// Setup lifetime capture for and impl-trait.
753 /// The captures will be added to `captures`.
754 fn while_capturing_lifetimes<T>(
756 parent_def_id: LocalDefId,
757 captures: &mut FxHashMap<LocalDefId, (Span, NodeId, ParamName, LifetimeRes)>,
758 f: impl FnOnce(&mut Self) -> T,
760 let lifetime_stash = std::mem::replace(
761 &mut self.captured_lifetimes,
762 Some(LifetimeCaptureContext {
764 captures: std::mem::take(captures),
765 binders_to_ignore: Default::default(),
771 let ctxt = std::mem::replace(&mut self.captured_lifetimes, lifetime_stash).unwrap();
772 *captures = ctxt.captures;
777 /// Register a binder to be ignored for lifetime capture.
778 #[tracing::instrument(level = "debug", skip(self, f))]
780 fn with_lifetime_binder<T>(&mut self, binder: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
781 if let Some(ctxt) = &mut self.captured_lifetimes {
782 ctxt.binders_to_ignore.insert(binder);
785 if let Some(ctxt) = &mut self.captured_lifetimes {
786 ctxt.binders_to_ignore.remove(&binder);
791 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
792 let was_in_dyn_type = self.is_in_dyn_type;
793 self.is_in_dyn_type = in_scope;
795 let result = f(self);
797 self.is_in_dyn_type = was_in_dyn_type;
802 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
803 let was_in_loop_condition = self.is_in_loop_condition;
804 self.is_in_loop_condition = false;
806 let catch_scope = self.catch_scope.take();
807 let loop_scope = self.loop_scope.take();
809 self.catch_scope = catch_scope;
810 self.loop_scope = loop_scope;
812 self.is_in_loop_condition = was_in_loop_condition;
817 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
818 if attrs.is_empty() {
821 debug_assert_eq!(id.owner, self.current_hir_id_owner);
822 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
823 debug_assert!(!ret.is_empty());
824 self.attrs.insert(id.local_id, ret);
829 fn lower_attr(&self, attr: &Attribute) -> Attribute {
830 // Note that we explicitly do not walk the path. Since we don't really
831 // lower attributes (we use the AST version) there is nowhere to keep
832 // the `HirId`s. We don't actually need HIR version of attributes anyway.
833 // Tokens are also not needed after macro expansion and parsing.
834 let kind = match attr.kind {
835 AttrKind::Normal(ref item, _) => AttrKind::Normal(
837 path: item.path.clone(),
838 args: self.lower_mac_args(&item.args),
843 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
846 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
849 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
850 debug_assert_eq!(id.owner, self.current_hir_id_owner);
851 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
852 if let Some(&a) = self.attrs.get(&target_id.local_id) {
853 debug_assert!(!a.is_empty());
854 self.attrs.insert(id.local_id, a);
858 fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
860 MacArgs::Empty => MacArgs::Empty,
861 MacArgs::Delimited(dspan, delim, ref tokens) => {
862 // This is either a non-key-value attribute, or a `macro_rules!` body.
863 // We either not have any nonterminals present (in the case of an attribute),
864 // or have tokens available for all nonterminals in the case of a nested
865 // `macro_rules`: e.g:
868 // macro_rules! outer {
870 // macro_rules! inner {
877 // In both cases, we don't want to synthesize any tokens
881 self.lower_token_stream(tokens.clone(), CanSynthesizeMissingTokens::No),
884 // This is an inert key-value attribute - it will never be visible to macros
885 // after it gets lowered to HIR. Therefore, we can extract literals to handle
886 // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
887 MacArgs::Eq(eq_span, MacArgsEq::Ast(ref expr)) => {
888 // In valid code the value always ends up as a single literal. Otherwise, a dummy
889 // literal suffices because the error is handled elsewhere.
890 let lit = if let ExprKind::Lit(lit) = &expr.kind {
894 token: token::Lit::new(token::LitKind::Err, kw::Empty, None),
895 kind: LitKind::Err(kw::Empty),
899 MacArgs::Eq(eq_span, MacArgsEq::Hir(lit))
901 MacArgs::Eq(_, MacArgsEq::Hir(ref lit)) => {
902 unreachable!("in literal form when lowering mac args eq: {:?}", lit)
907 fn lower_token_stream(
910 synthesize_tokens: CanSynthesizeMissingTokens,
912 FlattenNonterminals {
913 parse_sess: &self.sess.parse_sess,
915 nt_to_tokenstream: self.nt_to_tokenstream,
917 .process_token_stream(tokens)
920 /// Given an associated type constraint like one of these:
922 /// ```ignore (illustrative)
923 /// T: Iterator<Item: Debug>
925 /// T: Iterator<Item = Debug>
929 /// returns a `hir::TypeBinding` representing `Item`.
930 fn lower_assoc_ty_constraint(
932 constraint: &AssocConstraint,
933 mut itctx: ImplTraitContext<'_, 'hir>,
934 ) -> hir::TypeBinding<'hir> {
935 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
937 // lower generic arguments of identifier in constraint
938 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
939 let gen_args_ctor = match gen_args {
940 GenericArgs::AngleBracketed(ref data) => {
941 self.lower_angle_bracketed_parameter_data(
948 GenericArgs::Parenthesized(ref data) => {
949 let mut err = self.sess.struct_span_err(
951 "parenthesized generic arguments cannot be used in associated type constraints"
953 // FIXME: try to write a suggestion here
955 self.lower_angle_bracketed_parameter_data(
956 &data.as_angle_bracketed_args(),
963 gen_args_ctor.into_generic_args(self)
965 self.arena.alloc(hir::GenericArgs::none())
968 let kind = match constraint.kind {
969 AssocConstraintKind::Equality { ref term } => {
970 let term = match term {
971 Term::Ty(ref ty) => self.lower_ty(ty, itctx).into(),
972 Term::Const(ref c) => self.lower_anon_const(c).into(),
974 hir::TypeBindingKind::Equality { term }
976 AssocConstraintKind::Bound { ref bounds } => {
977 let mut parent_def_id = self.current_hir_id_owner;
978 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
979 let (desugar_to_impl_trait, itctx) = match itctx {
980 // We are in the return position:
982 // fn foo() -> impl Iterator<Item: Debug>
986 // fn foo() -> impl Iterator<Item = impl Debug>
987 ImplTraitContext::ReturnPositionOpaqueTy { .. }
988 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
990 // We are in the argument position, but within a dyn type:
992 // fn foo(x: dyn Iterator<Item: Debug>)
996 // fn foo(x: dyn Iterator<Item = impl Debug>)
997 ImplTraitContext::Universal(_, _, parent) if self.is_in_dyn_type => {
998 parent_def_id = parent;
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 impl_trait_node_id = self.resolver.next_node_id();
1027 self.resolver.create_def(
1030 DefPathData::ImplTrait,
1035 self.with_dyn_type_scope(false, |this| {
1036 let node_id = this.resolver.next_node_id();
1037 let ty = this.lower_ty(
1040 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1041 span: this.lower_span(constraint.span),
1047 hir::TypeBindingKind::Equality { term: ty.into() }
1050 // Desugar `AssocTy: Bounds` into a type binding where the
1051 // later desugars into a trait predicate.
1052 let bounds = self.lower_param_bounds(bounds, itctx);
1054 hir::TypeBindingKind::Constraint { bounds }
1060 hir_id: self.lower_node_id(constraint.id),
1061 ident: self.lower_ident(constraint.ident),
1064 span: self.lower_span(constraint.span),
1068 fn lower_generic_arg(
1070 arg: &ast::GenericArg,
1071 itctx: ImplTraitContext<'_, 'hir>,
1072 ) -> hir::GenericArg<'hir> {
1074 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1075 ast::GenericArg::Type(ty) => {
1077 TyKind::Infer if self.sess.features_untracked().generic_arg_infer => {
1078 return GenericArg::Infer(hir::InferArg {
1079 hir_id: self.lower_node_id(ty.id),
1080 span: self.lower_span(ty.span),
1083 // We parse const arguments as path types as we cannot distinguish them during
1084 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1085 // type and value namespaces. If we resolved the path in the value namespace, we
1086 // transform it into a generic const argument.
1087 TyKind::Path(ref qself, ref path) => {
1088 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1089 let res = partial_res.base_res();
1090 if !res.matches_ns(Namespace::TypeNS) {
1092 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1096 // Construct an AnonConst where the expr is the "ty"'s path.
1098 let parent_def_id = self.current_hir_id_owner;
1099 let node_id = self.resolver.next_node_id();
1101 // Add a definition for the in-band const def.
1102 self.resolver.create_def(
1105 DefPathData::AnonConst,
1110 let span = self.lower_span(ty.span);
1111 let path_expr = Expr {
1113 kind: ExprKind::Path(qself.clone(), path.clone()),
1115 attrs: AttrVec::new(),
1119 let ct = self.with_new_scopes(|this| hir::AnonConst {
1120 hir_id: this.lower_node_id(node_id),
1121 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1123 return GenericArg::Const(ConstArg { value: ct, span });
1129 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1131 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1132 value: self.lower_anon_const(&ct),
1133 span: self.lower_span(ct.value.span),
1138 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1139 self.arena.alloc(self.lower_ty_direct(t, itctx))
1145 qself: &Option<QSelf>,
1147 param_mode: ParamMode,
1148 itctx: ImplTraitContext<'_, 'hir>,
1149 ) -> hir::Ty<'hir> {
1150 let id = self.lower_node_id(t.id);
1151 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1152 self.ty_path(id, t.span, qpath)
1155 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1156 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1159 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1160 self.ty(span, hir::TyKind::Tup(tys))
1163 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1164 let kind = match t.kind {
1165 TyKind::Infer => hir::TyKind::Infer,
1166 TyKind::Err => hir::TyKind::Err,
1167 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1168 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1169 TyKind::Rptr(ref region, ref mt) => {
1170 let region = region.unwrap_or_else(|| {
1171 let Some(LifetimeRes::ElidedAnchor { start, end }) = self.resolver.get_lifetime_res(t.id) else {
1174 debug_assert_eq!(start.plus(1), end);
1175 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1177 ident: Ident::new(kw::UnderscoreLifetime, span),
1181 let lifetime = self.lower_lifetime(®ion);
1182 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1184 TyKind::BareFn(ref f) => self.with_lifetime_binder(t.id, |this| {
1185 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1186 generic_params: this.lower_generic_params(&f.generic_params),
1187 unsafety: this.lower_unsafety(f.unsafety),
1188 abi: this.lower_extern(f.ext),
1189 decl: this.lower_fn_decl(&f.decl, None, FnDeclKind::Pointer, None),
1190 param_names: this.lower_fn_params_to_names(&f.decl),
1193 TyKind::Never => hir::TyKind::Never,
1194 TyKind::Tup(ref tys) => {
1195 hir::TyKind::Tup(self.arena.alloc_from_iter(
1196 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1199 TyKind::Paren(ref ty) => {
1200 return self.lower_ty_direct(ty, itctx);
1202 TyKind::Path(ref qself, ref path) => {
1203 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1205 TyKind::ImplicitSelf => {
1206 let res = self.expect_full_res(t.id);
1207 let res = self.lower_res(res);
1208 hir::TyKind::Path(hir::QPath::Resolved(
1210 self.arena.alloc(hir::Path {
1212 segments: arena_vec![self; hir::PathSegment::from_ident(
1213 Ident::with_dummy_span(kw::SelfUpper)
1215 span: self.lower_span(t.span),
1219 TyKind::Array(ref ty, ref length) => {
1220 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1222 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1223 TyKind::TraitObject(ref bounds, kind) => {
1224 let mut lifetime_bound = None;
1225 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1227 this.arena.alloc_from_iter(bounds.iter().filter_map(
1228 |bound| match *bound {
1229 GenericBound::Trait(
1231 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1232 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1233 // `~const ?Bound` will cause an error during AST validation
1234 // anyways, so treat it like `?Bound` as compilation proceeds.
1235 GenericBound::Trait(
1237 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1239 GenericBound::Outlives(ref lifetime) => {
1240 if lifetime_bound.is_none() {
1241 lifetime_bound = Some(this.lower_lifetime(lifetime));
1247 let lifetime_bound =
1248 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1249 (bounds, lifetime_bound)
1251 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1253 TyKind::ImplTrait(def_node_id, ref bounds) => {
1256 ImplTraitContext::ReturnPositionOpaqueTy { origin } => self
1257 .lower_opaque_impl_trait(span, origin, def_node_id, |this| {
1258 this.lower_param_bounds(bounds, itctx)
1260 ImplTraitContext::TypeAliasesOpaqueTy => {
1261 let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy;
1262 self.lower_opaque_impl_trait(
1264 hir::OpaqueTyOrigin::TyAlias,
1266 |this| this.lower_param_bounds(bounds, nested_itctx),
1269 ImplTraitContext::Universal(
1274 // Add a definition for the in-band `Param`.
1275 let def_id = self.resolver.local_def_id(def_node_id);
1277 let hir_bounds = self.lower_param_bounds(
1279 ImplTraitContext::Universal(
1285 // Set the name to `impl Bound1 + Bound2`.
1286 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1287 in_band_ty_params.push(hir::GenericParam {
1288 hir_id: self.lower_node_id(def_node_id),
1289 name: ParamName::Plain(self.lower_ident(ident)),
1290 pure_wrt_drop: false,
1291 span: self.lower_span(span),
1292 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
1295 if let Some(preds) = self.lower_generic_bound_predicate(
1298 &GenericParamKind::Type { default: None },
1300 hir::PredicateOrigin::ImplTrait,
1302 in_band_ty_bounds.push(preds)
1305 hir::TyKind::Path(hir::QPath::Resolved(
1307 self.arena.alloc(hir::Path {
1308 span: self.lower_span(span),
1309 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1310 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
1314 ImplTraitContext::Disallowed(position) => {
1315 let mut err = struct_span_err!(
1319 "`impl Trait` only allowed in function and inherent method return types, not in {}",
1327 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1328 TyKind::CVarArgs => {
1329 self.sess.delay_span_bug(
1331 "`TyKind::CVarArgs` should have been handled elsewhere",
1337 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1340 #[tracing::instrument(level = "debug", skip(self, lower_bounds))]
1341 fn lower_opaque_impl_trait(
1344 origin: hir::OpaqueTyOrigin,
1345 opaque_ty_node_id: NodeId,
1346 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1347 ) -> hir::TyKind<'hir> {
1348 // Make sure we know that some funky desugaring has been going on here.
1349 // This is a first: there is code in other places like for loop
1350 // desugaring that explicitly states that we don't want to track that.
1351 // Not tracking it makes lints in rustc and clippy very fragile, as
1352 // frequently opened issues show.
1353 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1355 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1357 let mut collected_lifetimes = FxHashMap::default();
1358 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1359 let hir_bounds = if origin == hir::OpaqueTyOrigin::TyAlias {
1362 lctx.while_capturing_lifetimes(
1364 &mut collected_lifetimes,
1368 debug!(?collected_lifetimes);
1370 let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1371 |(_, &(span, p_id, p_name, _))| {
1372 let hir_id = lctx.lower_node_id(p_id);
1373 debug_assert_ne!(lctx.resolver.opt_local_def_id(p_id), None);
1375 let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1376 hir::LifetimeParamKind::Elided
1378 hir::LifetimeParamKind::Explicit
1385 pure_wrt_drop: false,
1386 kind: hir::GenericParamKind::Lifetime { kind },
1392 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1394 let opaque_ty_item = hir::OpaqueTy {
1395 generics: self.arena.alloc(hir::Generics {
1396 params: lifetime_defs,
1398 has_where_clause: false,
1399 where_clause_span: lctx.lower_span(span),
1400 span: lctx.lower_span(span),
1406 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1407 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1410 let lifetimes = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
1411 |(_, (span, _, p_name, res))| {
1412 let id = self.resolver.next_node_id();
1413 let ident = Ident::new(p_name.ident().name, span);
1414 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1415 hir::GenericArg::Lifetime(l)
1419 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1421 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1422 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1425 /// Registers a new opaque type with the proper `NodeId`s and
1426 /// returns the lowered node-ID for the opaque type.
1427 fn generate_opaque_type(
1429 opaque_ty_id: LocalDefId,
1430 opaque_ty_item: hir::OpaqueTy<'hir>,
1432 opaque_ty_span: Span,
1433 ) -> hir::OwnerNode<'hir> {
1434 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1435 // Generate an `type Foo = impl Trait;` declaration.
1436 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1437 let opaque_ty_item = hir::Item {
1438 def_id: opaque_ty_id,
1439 ident: Ident::empty(),
1440 kind: opaque_ty_item_kind,
1441 vis_span: self.lower_span(span.shrink_to_lo()),
1442 span: self.lower_span(opaque_ty_span),
1444 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1447 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1448 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1449 // as they are not explicit in HIR/Ty function signatures.
1450 // (instead, the `c_variadic` flag is set to `true`)
1451 let mut inputs = &decl.inputs[..];
1452 if decl.c_variadic() {
1453 inputs = &inputs[..inputs.len() - 1];
1455 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1456 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1457 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1461 // Lowers a function declaration.
1463 // `decl`: the unlowered (AST) function declaration.
1464 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1465 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1466 // `make_ret_async` is also `Some`.
1467 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1468 // This guards against trait declarations and implementations where `impl Trait` is
1470 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1471 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1472 // return type `impl Trait` item.
1476 mut in_band_ty_params: Option<(
1478 &mut Vec<hir::GenericParam<'hir>>,
1479 &mut Vec<hir::WherePredicate<'hir>>,
1482 make_ret_async: Option<NodeId>,
1483 ) -> &'hir hir::FnDecl<'hir> {
1487 in_band_ty_params: {:?}, \
1489 make_ret_async: {:?})",
1490 decl, in_band_ty_params, kind, make_ret_async,
1493 let c_variadic = decl.c_variadic();
1495 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1496 // as they are not explicit in HIR/Ty function signatures.
1497 // (instead, the `c_variadic` flag is set to `true`)
1498 let mut inputs = &decl.inputs[..];
1500 inputs = &inputs[..inputs.len() - 1];
1502 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1503 if let Some((_, ibty, ibpb)) = &mut in_band_ty_params {
1504 self.lower_ty_direct(
1506 ImplTraitContext::Universal(ibty, ibpb, self.current_hir_id_owner),
1509 self.lower_ty_direct(
1511 ImplTraitContext::Disallowed(match kind {
1512 FnDeclKind::Fn | FnDeclKind::Inherent => {
1513 unreachable!("fn should allow in-band lifetimes")
1515 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1516 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1517 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1518 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1519 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1525 let output = if let Some(ret_id) = make_ret_async {
1526 self.lower_async_fn_ret_ty(
1528 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1533 FnRetTy::Ty(ref ty) => {
1534 let context = match in_band_ty_params {
1535 Some((node_id, _, _)) if kind.impl_trait_return_allowed() => {
1536 let fn_def_id = self.resolver.local_def_id(node_id);
1537 ImplTraitContext::ReturnPositionOpaqueTy {
1538 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1541 _ => ImplTraitContext::Disallowed(match kind {
1542 FnDeclKind::Fn | FnDeclKind::Inherent => {
1543 unreachable!("fn should allow in-band lifetimes")
1545 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1546 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1547 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1548 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1549 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1552 hir::FnRetTy::Return(self.lower_ty(ty, context))
1554 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1558 self.arena.alloc(hir::FnDecl {
1562 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1563 use BindingMode::{ByRef, ByValue};
1564 let is_mutable_pat = matches!(
1566 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1570 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1571 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1572 // Given we are only considering `ImplicitSelf` types, we needn't consider
1573 // the case where we have a mutable pattern to a reference as that would
1574 // no longer be an `ImplicitSelf`.
1575 TyKind::Rptr(_, ref mt)
1576 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1578 hir::ImplicitSelfKind::MutRef
1580 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1581 hir::ImplicitSelfKind::ImmRef
1583 _ => hir::ImplicitSelfKind::None,
1589 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1590 // combined with the following definition of `OpaqueTy`:
1592 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1594 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1595 // `output`: unlowered output type (`T` in `-> T`)
1596 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1597 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1598 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1599 #[tracing::instrument(level = "debug", skip(self))]
1600 fn lower_async_fn_ret_ty(
1604 opaque_ty_node_id: NodeId,
1605 ) -> hir::FnRetTy<'hir> {
1606 let span = output.span();
1608 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1610 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1611 let fn_def_id = self.resolver.local_def_id(fn_node_id);
1613 // When we create the opaque type for this async fn, it is going to have
1614 // to capture all the lifetimes involved in the signature (including in the
1615 // return type). This is done by introducing lifetime parameters for:
1617 // - all the explicitly declared lifetimes from the impl and function itself;
1618 // - all the elided lifetimes in the fn arguments;
1619 // - all the elided lifetimes in the return type.
1621 // So for example in this snippet:
1624 // impl<'a> Foo<'a> {
1625 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1626 // // ^ '0 ^ '1 ^ '2
1627 // // elided lifetimes used below
1632 // we would create an opaque type like:
1635 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1638 // and we would then desugar `bar` to the equivalent of:
1641 // impl<'a> Foo<'a> {
1642 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1646 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1647 // this is because the elided lifetimes from the return type
1648 // should be figured out using the ordinary elision rules, and
1649 // this desugaring achieves that.
1651 // Calculate all the lifetimes that should be captured
1652 // by the opaque type. This should include all in-scope
1653 // lifetime parameters, including those defined in-band.
1655 let mut captures = FxHashMap::default();
1657 let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1658 debug!(?extra_lifetime_params);
1659 for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1660 let Ident { name, span } = ident;
1661 let outer_def_id = self.resolver.local_def_id(outer_node_id);
1662 let inner_node_id = self.resolver.next_node_id();
1664 // Add a definition for the in scope lifetime def.
1665 self.resolver.create_def(
1668 DefPathData::LifetimeNs(name),
1670 span.with_parent(None),
1673 let (p_name, inner_res) = match outer_res {
1674 // Input lifetime like `'a`:
1675 LifetimeRes::Param { param, .. } => {
1676 (hir::ParamName::Plain(ident), LifetimeRes::Param { param, binder: fn_node_id })
1678 // Input lifetime like `'1`:
1679 LifetimeRes::Fresh { param, .. } => (
1680 hir::ParamName::Fresh(outer_def_id),
1681 LifetimeRes::Fresh { param, binder: fn_node_id },
1683 LifetimeRes::Static | LifetimeRes::Error => continue,
1685 panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span)
1689 captures.insert(outer_def_id, (span, inner_node_id, p_name, inner_res));
1694 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1696 this.while_capturing_lifetimes(opaque_ty_def_id, &mut captures, |this| {
1697 // We have to be careful to get elision right here. The
1698 // idea is that we create a lifetime parameter for each
1699 // lifetime in the return type. So, given a return type
1700 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1701 // Future<Output = &'1 [ &'2 u32 ]>`.
1703 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1704 // hence the elision takes place at the fn site.
1705 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1707 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1708 debug!("lower_async_fn_ret_ty: captures={:#?}", captures);
1710 let generic_params =
1711 this.arena.alloc_from_iter(captures.iter().map(|(_, &(span, p_id, p_name, _))| {
1712 let hir_id = this.lower_node_id(p_id);
1713 debug_assert_ne!(this.resolver.opt_local_def_id(p_id), None);
1715 let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1716 hir::LifetimeParamKind::Elided
1718 hir::LifetimeParamKind::Explicit
1725 pure_wrt_drop: false,
1726 kind: hir::GenericParamKind::Lifetime { kind },
1730 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1732 let opaque_ty_item = hir::OpaqueTy {
1733 generics: this.arena.alloc(hir::Generics {
1734 params: generic_params,
1736 has_where_clause: false,
1737 where_clause_span: this.lower_span(span),
1738 span: this.lower_span(span),
1740 bounds: arena_vec![this; future_bound],
1741 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1744 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1745 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1748 // As documented above, we need to create the lifetime
1749 // arguments to our opaque type. Continuing with our example,
1750 // we're creating the type arguments for the return type:
1753 // Bar<'a, 'b, '0, '1, '_>
1756 // For the "input" lifetime parameters, we wish to create
1757 // references to the parameters themselves, including the
1758 // "implicit" ones created from parameter types (`'a`, `'b`,
1761 // For the "output" lifetime parameters, we just want to
1764 self.arena.alloc_from_iter(captures.into_iter().map(|(_, (span, _, p_name, res))| {
1765 let id = self.resolver.next_node_id();
1766 let ident = Ident::new(p_name.ident().name, span);
1767 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1768 hir::GenericArg::Lifetime(l)
1771 // Create the `Foo<...>` reference itself. Note that the `type
1772 // Foo = impl Trait` is, internally, created as a child of the
1773 // async fn, so the *type parameters* are inherited. It's
1774 // only the lifetime parameters that we must supply.
1776 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1777 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1778 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1781 /// Transforms `-> T` into `Future<Output = T>`.
1782 fn lower_async_fn_output_type_to_future_bound(
1785 fn_def_id: LocalDefId,
1787 ) -> hir::GenericBound<'hir> {
1788 // Compute the `T` in `Future<Output = T>` from the return type.
1789 let output_ty = match output {
1790 FnRetTy::Ty(ty) => {
1791 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1792 // `impl Future` opaque type that `async fn` implicitly
1794 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1795 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1797 self.lower_ty(ty, context)
1799 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1803 let future_args = self.arena.alloc(hir::GenericArgs {
1805 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1806 parenthesized: false,
1810 hir::GenericBound::LangItemTrait(
1811 // ::std::future::Future<future_params>
1812 hir::LangItem::Future,
1813 self.lower_span(span),
1819 fn lower_param_bound(
1822 itctx: ImplTraitContext<'_, 'hir>,
1823 ) -> hir::GenericBound<'hir> {
1825 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1826 self.lower_poly_trait_ref(p, itctx),
1827 self.lower_trait_bound_modifier(*modifier),
1829 GenericBound::Outlives(lifetime) => {
1830 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1835 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1836 let span = self.lower_span(l.ident.span);
1837 let ident = self.lower_ident(l.ident);
1840 .get_lifetime_res(l.id)
1841 .unwrap_or_else(|| panic!("Missing resolution for lifetime {:?} at {:?}", l, span));
1842 self.new_named_lifetime_with_res(l.id, span, ident, res)
1845 #[tracing::instrument(level = "debug", skip(self))]
1846 fn new_named_lifetime_with_res(
1852 ) -> hir::Lifetime {
1853 debug!(?self.captured_lifetimes);
1854 let name = match res {
1855 LifetimeRes::Param { param, binder } => {
1856 debug_assert_ne!(ident.name, kw::UnderscoreLifetime);
1857 let p_name = ParamName::Plain(ident);
1858 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1859 &mut self.captured_lifetimes
1860 && !binders_to_ignore.contains(&binder)
1862 match captures.entry(param) {
1863 Entry::Occupied(_) => {}
1864 Entry::Vacant(v) => {
1865 let p_id = self.resolver.next_node_id();
1866 self.resolver.create_def(
1869 DefPathData::LifetimeNs(p_name.ident().name),
1871 span.with_parent(None),
1874 v.insert((span, p_id, p_name, res));
1878 hir::LifetimeName::Param(p_name)
1880 LifetimeRes::Fresh { mut param, binder } => {
1881 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1882 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1883 &mut self.captured_lifetimes
1884 && !binders_to_ignore.contains(&binder)
1886 match captures.entry(param) {
1887 Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1),
1888 Entry::Vacant(v) => {
1889 let p_id = self.resolver.next_node_id();
1890 let p_def_id = self.resolver.create_def(
1893 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1895 span.with_parent(None),
1898 let p_name = ParamName::Fresh(param);
1899 v.insert((span, p_id, p_name, res));
1904 let p_name = ParamName::Fresh(param);
1905 hir::LifetimeName::Param(p_name)
1907 LifetimeRes::Anonymous { binder, elided } => {
1908 let l_name = if elided {
1909 hir::LifetimeName::Implicit
1911 hir::LifetimeName::Underscore
1913 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1914 &mut self.captured_lifetimes
1915 && !binders_to_ignore.contains(&binder)
1917 let p_id = self.resolver.next_node_id();
1918 let p_def_id = self.resolver.create_def(
1921 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1923 span.with_parent(None),
1925 let p_name = ParamName::Fresh(p_def_id);
1926 captures.insert(p_def_id, (span, p_id, p_name, res));
1927 hir::LifetimeName::Param(p_name)
1932 LifetimeRes::Static => hir::LifetimeName::Static,
1933 LifetimeRes::Error => hir::LifetimeName::Error,
1934 res => panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span),
1936 debug!(?self.captured_lifetimes);
1937 hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1940 fn lower_generic_params_mut<'s>(
1942 params: &'s [GenericParam],
1943 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1944 params.iter().map(move |param| self.lower_generic_param(param))
1947 fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
1948 self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
1951 fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
1952 let (name, kind) = match param.kind {
1953 GenericParamKind::Lifetime => {
1954 let param_name = if param.ident.name == kw::StaticLifetime
1955 || param.ident.name == kw::UnderscoreLifetime
1959 let ident = self.lower_ident(param.ident);
1960 ParamName::Plain(ident)
1963 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
1967 GenericParamKind::Type { ref default, .. } => {
1968 let kind = hir::GenericParamKind::Type {
1969 default: default.as_ref().map(|x| {
1970 self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
1975 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
1977 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1978 let ty = self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
1979 let default = default.as_ref().map(|def| self.lower_anon_const(def));
1981 hir::ParamName::Plain(self.lower_ident(param.ident)),
1982 hir::GenericParamKind::Const { ty, default },
1986 let name = match name {
1987 hir::ParamName::Plain(ident) => hir::ParamName::Plain(self.lower_ident(ident)),
1991 let hir_id = self.lower_node_id(param.id);
1992 self.lower_attrs(hir_id, ¶m.attrs);
1996 span: self.lower_span(param.span()),
1997 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
1999 colon_span: param.colon_span.map(|s| self.lower_span(s)),
2006 itctx: ImplTraitContext<'_, 'hir>,
2007 ) -> hir::TraitRef<'hir> {
2008 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2009 hir::QPath::Resolved(None, path) => path,
2010 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2012 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2015 #[tracing::instrument(level = "debug", skip(self))]
2016 fn lower_poly_trait_ref(
2019 mut itctx: ImplTraitContext<'_, 'hir>,
2020 ) -> hir::PolyTraitRef<'hir> {
2021 let bound_generic_params = self.lower_generic_params(&p.bound_generic_params);
2023 let trait_ref = self.with_lifetime_binder(p.trait_ref.ref_id, |this| {
2024 this.lower_trait_ref(&p.trait_ref, itctx.reborrow())
2027 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2030 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2031 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2034 fn lower_param_bounds(
2036 bounds: &[GenericBound],
2037 itctx: ImplTraitContext<'_, 'hir>,
2038 ) -> hir::GenericBounds<'hir> {
2039 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2042 fn lower_param_bounds_mut<'s>(
2044 bounds: &'s [GenericBound],
2045 mut itctx: ImplTraitContext<'s, 'hir>,
2046 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2047 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2050 /// Lowers a block directly to an expression, presuming that it
2051 /// has no attributes and is not targeted by a `break`.
2052 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2053 let block = self.lower_block(b, false);
2054 self.expr_block(block, AttrVec::new())
2057 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2058 match c.value.kind {
2059 ExprKind::Underscore => {
2060 if self.sess.features_untracked().generic_arg_infer {
2061 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2064 &self.sess.parse_sess,
2065 sym::generic_arg_infer,
2067 "using `_` for array lengths is unstable",
2070 hir::ArrayLen::Body(self.lower_anon_const(c))
2073 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2077 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2078 self.with_new_scopes(|this| hir::AnonConst {
2079 hir_id: this.lower_node_id(c.id),
2080 body: this.lower_const_body(c.value.span, Some(&c.value)),
2084 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2086 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2087 UserProvided => hir::UnsafeSource::UserProvided,
2091 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2093 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2094 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2096 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2097 // placeholder for compilation to proceed.
2098 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2099 hir::TraitBoundModifier::Maybe
2104 // Helper methods for building HIR.
2106 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2107 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2110 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2111 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2116 attrs: Option<&'hir [Attribute]>,
2118 init: Option<&'hir hir::Expr<'hir>>,
2119 pat: &'hir hir::Pat<'hir>,
2120 source: hir::LocalSource,
2121 ) -> hir::Stmt<'hir> {
2122 let hir_id = self.next_id();
2123 if let Some(a) = attrs {
2124 debug_assert!(!a.is_empty());
2125 self.attrs.insert(hir_id.local_id, a);
2127 let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2128 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2131 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2132 self.block_all(expr.span, &[], Some(expr))
2138 stmts: &'hir [hir::Stmt<'hir>],
2139 expr: Option<&'hir hir::Expr<'hir>>,
2140 ) -> &'hir hir::Block<'hir> {
2141 let blk = hir::Block {
2144 hir_id: self.next_id(),
2145 rules: hir::BlockCheckMode::DefaultBlock,
2146 span: self.lower_span(span),
2147 targeted_by_break: false,
2149 self.arena.alloc(blk)
2152 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2153 let field = self.single_pat_field(span, pat);
2154 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2157 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2158 let field = self.single_pat_field(span, pat);
2159 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2162 fn pat_some(&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::OptionSome, field, None)
2167 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2168 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2171 fn single_pat_field(
2174 pat: &'hir hir::Pat<'hir>,
2175 ) -> &'hir [hir::PatField<'hir>] {
2176 let field = hir::PatField {
2177 hir_id: self.next_id(),
2178 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2179 is_shorthand: false,
2181 span: self.lower_span(span),
2183 arena_vec![self; field]
2186 fn pat_lang_item_variant(
2189 lang_item: hir::LangItem,
2190 fields: &'hir [hir::PatField<'hir>],
2191 hir_id: Option<hir::HirId>,
2192 ) -> &'hir hir::Pat<'hir> {
2193 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2194 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2197 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2198 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2201 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2202 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2205 fn pat_ident_binding_mode(
2209 bm: hir::BindingAnnotation,
2210 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2211 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2212 (self.arena.alloc(pat), hir_id)
2215 fn pat_ident_binding_mode_mut(
2219 bm: hir::BindingAnnotation,
2220 ) -> (hir::Pat<'hir>, hir::HirId) {
2221 let hir_id = self.next_id();
2226 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2227 span: self.lower_span(span),
2228 default_binding_modes: true,
2234 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2235 self.arena.alloc(hir::Pat {
2236 hir_id: self.next_id(),
2238 span: self.lower_span(span),
2239 default_binding_modes: true,
2243 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2245 hir_id: self.next_id(),
2247 span: self.lower_span(span),
2248 default_binding_modes: false,
2254 mut hir_id: hir::HirId,
2256 qpath: hir::QPath<'hir>,
2257 ) -> hir::Ty<'hir> {
2258 let kind = match qpath {
2259 hir::QPath::Resolved(None, path) => {
2260 // Turn trait object paths into `TyKind::TraitObject` instead.
2262 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2263 let principal = hir::PolyTraitRef {
2264 bound_generic_params: &[],
2265 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2266 span: self.lower_span(span),
2269 // The original ID is taken by the `PolyTraitRef`,
2270 // so the `Ty` itself needs a different one.
2271 hir_id = self.next_id();
2272 hir::TyKind::TraitObject(
2273 arena_vec![self; principal],
2274 self.elided_dyn_bound(span),
2275 TraitObjectSyntax::None,
2278 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2281 _ => hir::TyKind::Path(qpath),
2284 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2287 /// Invoked to create the lifetime argument(s) for an elided trait object
2288 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2289 /// when the bound is written, even if it is written with `'_` like in
2290 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2291 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2292 let r = hir::Lifetime {
2293 hir_id: self.next_id(),
2294 span: self.lower_span(span),
2295 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2297 debug!("elided_dyn_bound: r={:?}", r);
2302 /// Helper struct for delayed construction of GenericArgs.
2303 struct GenericArgsCtor<'hir> {
2304 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2305 bindings: &'hir [hir::TypeBinding<'hir>],
2306 parenthesized: bool,
2310 impl<'hir> GenericArgsCtor<'hir> {
2311 fn is_empty(&self) -> bool {
2312 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2315 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2316 let ga = hir::GenericArgs {
2317 args: this.arena.alloc_from_iter(self.args),
2318 bindings: self.bindings,
2319 parenthesized: self.parenthesized,
2320 span_ext: this.lower_span(self.span),
2322 this.arena.alloc(ga)