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 id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1172 self.resolver.get_lifetime_res(t.id)
1174 debug_assert_eq!(start.plus(1), end);
1177 self.resolver.next_node_id()
1179 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1180 Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id }
1182 let lifetime = self.lower_lifetime(®ion);
1183 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1185 TyKind::BareFn(ref f) => self.with_lifetime_binder(t.id, |this| {
1186 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1187 generic_params: this.lower_generic_params(&f.generic_params),
1188 unsafety: this.lower_unsafety(f.unsafety),
1189 abi: this.lower_extern(f.ext),
1190 decl: this.lower_fn_decl(&f.decl, None, FnDeclKind::Pointer, None),
1191 param_names: this.lower_fn_params_to_names(&f.decl),
1194 TyKind::Never => hir::TyKind::Never,
1195 TyKind::Tup(ref tys) => {
1196 hir::TyKind::Tup(self.arena.alloc_from_iter(
1197 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1200 TyKind::Paren(ref ty) => {
1201 return self.lower_ty_direct(ty, itctx);
1203 TyKind::Path(ref qself, ref path) => {
1204 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1206 TyKind::ImplicitSelf => {
1207 let res = self.expect_full_res(t.id);
1208 let res = self.lower_res(res);
1209 hir::TyKind::Path(hir::QPath::Resolved(
1211 self.arena.alloc(hir::Path {
1213 segments: arena_vec![self; hir::PathSegment::from_ident(
1214 Ident::with_dummy_span(kw::SelfUpper)
1216 span: self.lower_span(t.span),
1220 TyKind::Array(ref ty, ref length) => {
1221 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1223 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1224 TyKind::TraitObject(ref bounds, kind) => {
1225 let mut lifetime_bound = None;
1226 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1228 this.arena.alloc_from_iter(bounds.iter().filter_map(
1229 |bound| match *bound {
1230 GenericBound::Trait(
1232 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1233 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1234 // `~const ?Bound` will cause an error during AST validation
1235 // anyways, so treat it like `?Bound` as compilation proceeds.
1236 GenericBound::Trait(
1238 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1240 GenericBound::Outlives(ref lifetime) => {
1241 if lifetime_bound.is_none() {
1242 lifetime_bound = Some(this.lower_lifetime(lifetime));
1248 let lifetime_bound =
1249 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1250 (bounds, lifetime_bound)
1252 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1254 TyKind::ImplTrait(def_node_id, ref bounds) => {
1257 ImplTraitContext::ReturnPositionOpaqueTy { origin } => self
1258 .lower_opaque_impl_trait(span, origin, def_node_id, |this| {
1259 this.lower_param_bounds(bounds, itctx)
1261 ImplTraitContext::TypeAliasesOpaqueTy => {
1262 let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy;
1263 self.lower_opaque_impl_trait(
1265 hir::OpaqueTyOrigin::TyAlias,
1267 |this| this.lower_param_bounds(bounds, nested_itctx),
1270 ImplTraitContext::Universal(
1275 // Add a definition for the in-band `Param`.
1276 let def_id = self.resolver.local_def_id(def_node_id);
1278 let hir_bounds = self.lower_param_bounds(
1280 ImplTraitContext::Universal(
1286 // Set the name to `impl Bound1 + Bound2`.
1287 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1288 in_band_ty_params.push(hir::GenericParam {
1289 hir_id: self.lower_node_id(def_node_id),
1290 name: ParamName::Plain(self.lower_ident(ident)),
1291 pure_wrt_drop: false,
1292 span: self.lower_span(span),
1293 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
1296 if let Some(preds) = self.lower_generic_bound_predicate(
1299 &GenericParamKind::Type { default: None },
1301 hir::PredicateOrigin::ImplTrait,
1303 in_band_ty_bounds.push(preds)
1306 hir::TyKind::Path(hir::QPath::Resolved(
1308 self.arena.alloc(hir::Path {
1309 span: self.lower_span(span),
1310 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1311 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
1315 ImplTraitContext::Disallowed(position) => {
1316 let mut err = struct_span_err!(
1320 "`impl Trait` only allowed in function and inherent method return types, not in {}",
1328 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1329 TyKind::CVarArgs => {
1330 self.sess.delay_span_bug(
1332 "`TyKind::CVarArgs` should have been handled elsewhere",
1338 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1341 #[tracing::instrument(level = "debug", skip(self, lower_bounds))]
1342 fn lower_opaque_impl_trait(
1345 origin: hir::OpaqueTyOrigin,
1346 opaque_ty_node_id: NodeId,
1347 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1348 ) -> hir::TyKind<'hir> {
1349 // Make sure we know that some funky desugaring has been going on here.
1350 // This is a first: there is code in other places like for loop
1351 // desugaring that explicitly states that we don't want to track that.
1352 // Not tracking it makes lints in rustc and clippy very fragile, as
1353 // frequently opened issues show.
1354 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1356 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1358 let mut collected_lifetimes = FxHashMap::default();
1359 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1360 let hir_bounds = if origin == hir::OpaqueTyOrigin::TyAlias {
1363 lctx.while_capturing_lifetimes(
1365 &mut collected_lifetimes,
1369 debug!(?collected_lifetimes);
1371 let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(
1372 |(_, &(span, p_id, p_name, _))| {
1373 let hir_id = lctx.lower_node_id(p_id);
1374 debug_assert_ne!(lctx.resolver.opt_local_def_id(p_id), None);
1376 let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1377 hir::LifetimeParamKind::Elided
1379 hir::LifetimeParamKind::Explicit
1386 pure_wrt_drop: false,
1387 kind: hir::GenericParamKind::Lifetime { kind },
1393 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1395 let opaque_ty_item = hir::OpaqueTy {
1396 generics: self.arena.alloc(hir::Generics {
1397 params: lifetime_defs,
1399 has_where_clause: false,
1400 where_clause_span: lctx.lower_span(span),
1401 span: lctx.lower_span(span),
1407 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1408 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1411 let lifetimes = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(
1412 |(_, (span, _, p_name, res))| {
1413 let id = self.resolver.next_node_id();
1414 let ident = Ident::new(p_name.ident().name, span);
1415 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1416 hir::GenericArg::Lifetime(l)
1420 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1422 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1423 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1426 /// Registers a new opaque type with the proper `NodeId`s and
1427 /// returns the lowered node-ID for the opaque type.
1428 fn generate_opaque_type(
1430 opaque_ty_id: LocalDefId,
1431 opaque_ty_item: hir::OpaqueTy<'hir>,
1433 opaque_ty_span: Span,
1434 ) -> hir::OwnerNode<'hir> {
1435 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1436 // Generate an `type Foo = impl Trait;` declaration.
1437 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1438 let opaque_ty_item = hir::Item {
1439 def_id: opaque_ty_id,
1440 ident: Ident::empty(),
1441 kind: opaque_ty_item_kind,
1442 vis_span: self.lower_span(span.shrink_to_lo()),
1443 span: self.lower_span(opaque_ty_span),
1445 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1448 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1449 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1450 // as they are not explicit in HIR/Ty function signatures.
1451 // (instead, the `c_variadic` flag is set to `true`)
1452 let mut inputs = &decl.inputs[..];
1453 if decl.c_variadic() {
1454 inputs = &inputs[..inputs.len() - 1];
1456 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1457 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1458 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1462 // Lowers a function declaration.
1464 // `decl`: the unlowered (AST) function declaration.
1465 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1466 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1467 // `make_ret_async` is also `Some`.
1468 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1469 // This guards against trait declarations and implementations where `impl Trait` is
1471 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1472 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1473 // return type `impl Trait` item.
1477 mut in_band_ty_params: Option<(
1479 &mut Vec<hir::GenericParam<'hir>>,
1480 &mut Vec<hir::WherePredicate<'hir>>,
1483 make_ret_async: Option<NodeId>,
1484 ) -> &'hir hir::FnDecl<'hir> {
1488 in_band_ty_params: {:?}, \
1490 make_ret_async: {:?})",
1491 decl, in_band_ty_params, kind, make_ret_async,
1494 let c_variadic = decl.c_variadic();
1496 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1497 // as they are not explicit in HIR/Ty function signatures.
1498 // (instead, the `c_variadic` flag is set to `true`)
1499 let mut inputs = &decl.inputs[..];
1501 inputs = &inputs[..inputs.len() - 1];
1503 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1504 if let Some((_, ibty, ibpb)) = &mut in_band_ty_params {
1505 self.lower_ty_direct(
1507 ImplTraitContext::Universal(ibty, ibpb, self.current_hir_id_owner),
1510 self.lower_ty_direct(
1512 ImplTraitContext::Disallowed(match kind {
1513 FnDeclKind::Fn | FnDeclKind::Inherent => {
1514 unreachable!("fn should allow in-band lifetimes")
1516 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1517 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1518 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1519 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1520 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1526 let output = if let Some(ret_id) = make_ret_async {
1527 self.lower_async_fn_ret_ty(
1529 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1534 FnRetTy::Ty(ref ty) => {
1535 let context = match in_band_ty_params {
1536 Some((node_id, _, _)) if kind.impl_trait_return_allowed() => {
1537 let fn_def_id = self.resolver.local_def_id(node_id);
1538 ImplTraitContext::ReturnPositionOpaqueTy {
1539 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1542 _ => ImplTraitContext::Disallowed(match kind {
1543 FnDeclKind::Fn | FnDeclKind::Inherent => {
1544 unreachable!("fn should allow in-band lifetimes")
1546 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1547 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1548 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1549 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1550 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1553 hir::FnRetTy::Return(self.lower_ty(ty, context))
1555 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1559 self.arena.alloc(hir::FnDecl {
1563 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1564 use BindingMode::{ByRef, ByValue};
1565 let is_mutable_pat = matches!(
1567 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1571 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1572 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1573 // Given we are only considering `ImplicitSelf` types, we needn't consider
1574 // the case where we have a mutable pattern to a reference as that would
1575 // no longer be an `ImplicitSelf`.
1576 TyKind::Rptr(_, ref mt)
1577 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1579 hir::ImplicitSelfKind::MutRef
1581 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1582 hir::ImplicitSelfKind::ImmRef
1584 _ => hir::ImplicitSelfKind::None,
1590 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1591 // combined with the following definition of `OpaqueTy`:
1593 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1595 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1596 // `output`: unlowered output type (`T` in `-> T`)
1597 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1598 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1599 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1600 #[tracing::instrument(level = "debug", skip(self))]
1601 fn lower_async_fn_ret_ty(
1605 opaque_ty_node_id: NodeId,
1606 ) -> hir::FnRetTy<'hir> {
1607 let span = output.span();
1609 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1611 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1612 let fn_def_id = self.resolver.local_def_id(fn_node_id);
1614 // When we create the opaque type for this async fn, it is going to have
1615 // to capture all the lifetimes involved in the signature (including in the
1616 // return type). This is done by introducing lifetime parameters for:
1618 // - all the explicitly declared lifetimes from the impl and function itself;
1619 // - all the elided lifetimes in the fn arguments;
1620 // - all the elided lifetimes in the return type.
1622 // So for example in this snippet:
1625 // impl<'a> Foo<'a> {
1626 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1627 // // ^ '0 ^ '1 ^ '2
1628 // // elided lifetimes used below
1633 // we would create an opaque type like:
1636 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1639 // and we would then desugar `bar` to the equivalent of:
1642 // impl<'a> Foo<'a> {
1643 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1647 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1648 // this is because the elided lifetimes from the return type
1649 // should be figured out using the ordinary elision rules, and
1650 // this desugaring achieves that.
1652 // Calculate all the lifetimes that should be captured
1653 // by the opaque type. This should include all in-scope
1654 // lifetime parameters, including those defined in-band.
1656 let mut captures = FxHashMap::default();
1658 let extra_lifetime_params = self.resolver.take_extra_lifetime_params(opaque_ty_node_id);
1659 debug!(?extra_lifetime_params);
1660 for (ident, outer_node_id, outer_res) in extra_lifetime_params {
1661 let Ident { name, span } = ident;
1662 let outer_def_id = self.resolver.local_def_id(outer_node_id);
1663 let inner_node_id = self.resolver.next_node_id();
1665 // Add a definition for the in scope lifetime def.
1666 self.resolver.create_def(
1669 DefPathData::LifetimeNs(name),
1671 span.with_parent(None),
1674 let (p_name, inner_res) = match outer_res {
1675 // Input lifetime like `'a`:
1676 LifetimeRes::Param { param, .. } => {
1677 (hir::ParamName::Plain(ident), LifetimeRes::Param { param, binder: fn_node_id })
1679 // Input lifetime like `'1`:
1680 LifetimeRes::Fresh { param, .. } => (
1681 hir::ParamName::Fresh(outer_def_id),
1682 LifetimeRes::Fresh { param, binder: fn_node_id },
1684 LifetimeRes::Static | LifetimeRes::Error => continue,
1686 panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span)
1690 captures.insert(outer_def_id, (span, inner_node_id, p_name, inner_res));
1695 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1697 this.while_capturing_lifetimes(opaque_ty_def_id, &mut captures, |this| {
1698 // We have to be careful to get elision right here. The
1699 // idea is that we create a lifetime parameter for each
1700 // lifetime in the return type. So, given a return type
1701 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1702 // Future<Output = &'1 [ &'2 u32 ]>`.
1704 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1705 // hence the elision takes place at the fn site.
1706 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1708 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1709 debug!("lower_async_fn_ret_ty: captures={:#?}", captures);
1711 let generic_params =
1712 this.arena.alloc_from_iter(captures.iter().map(|(_, &(span, p_id, p_name, _))| {
1713 let hir_id = this.lower_node_id(p_id);
1714 debug_assert_ne!(this.resolver.opt_local_def_id(p_id), None);
1716 let kind = if p_name.ident().name == kw::UnderscoreLifetime {
1717 hir::LifetimeParamKind::Elided
1719 hir::LifetimeParamKind::Explicit
1726 pure_wrt_drop: false,
1727 kind: hir::GenericParamKind::Lifetime { kind },
1731 debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);
1733 let opaque_ty_item = hir::OpaqueTy {
1734 generics: this.arena.alloc(hir::Generics {
1735 params: generic_params,
1737 has_where_clause: false,
1738 where_clause_span: this.lower_span(span),
1739 span: this.lower_span(span),
1741 bounds: arena_vec![this; future_bound],
1742 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1745 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1746 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1749 // As documented above, we need to create the lifetime
1750 // arguments to our opaque type. Continuing with our example,
1751 // we're creating the type arguments for the return type:
1754 // Bar<'a, 'b, '0, '1, '_>
1757 // For the "input" lifetime parameters, we wish to create
1758 // references to the parameters themselves, including the
1759 // "implicit" ones created from parameter types (`'a`, `'b`,
1762 // For the "output" lifetime parameters, we just want to
1765 self.arena.alloc_from_iter(captures.into_iter().map(|(_, (span, _, p_name, res))| {
1766 let id = self.resolver.next_node_id();
1767 let ident = Ident::new(p_name.ident().name, span);
1768 let l = self.new_named_lifetime_with_res(id, span, ident, res);
1769 hir::GenericArg::Lifetime(l)
1772 // Create the `Foo<...>` reference itself. Note that the `type
1773 // Foo = impl Trait` is, internally, created as a child of the
1774 // async fn, so the *type parameters* are inherited. It's
1775 // only the lifetime parameters that we must supply.
1777 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1778 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1779 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1782 /// Transforms `-> T` into `Future<Output = T>`.
1783 fn lower_async_fn_output_type_to_future_bound(
1786 fn_def_id: LocalDefId,
1788 ) -> hir::GenericBound<'hir> {
1789 // Compute the `T` in `Future<Output = T>` from the return type.
1790 let output_ty = match output {
1791 FnRetTy::Ty(ty) => {
1792 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1793 // `impl Future` opaque type that `async fn` implicitly
1795 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1796 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1798 self.lower_ty(ty, context)
1800 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1804 let future_args = self.arena.alloc(hir::GenericArgs {
1806 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1807 parenthesized: false,
1811 hir::GenericBound::LangItemTrait(
1812 // ::std::future::Future<future_params>
1813 hir::LangItem::Future,
1814 self.lower_span(span),
1820 fn lower_param_bound(
1823 itctx: ImplTraitContext<'_, 'hir>,
1824 ) -> hir::GenericBound<'hir> {
1826 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1827 self.lower_poly_trait_ref(p, itctx),
1828 self.lower_trait_bound_modifier(*modifier),
1830 GenericBound::Outlives(lifetime) => {
1831 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1836 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1837 let span = self.lower_span(l.ident.span);
1838 let ident = self.lower_ident(l.ident);
1839 let res = self.resolver.get_lifetime_res(l.id).unwrap_or(LifetimeRes::Error);
1840 self.new_named_lifetime_with_res(l.id, span, ident, res)
1843 #[tracing::instrument(level = "debug", skip(self))]
1844 fn new_named_lifetime_with_res(
1850 ) -> hir::Lifetime {
1851 debug!(?self.captured_lifetimes);
1852 let name = match res {
1853 LifetimeRes::Param { param, binder } => {
1854 debug_assert_ne!(ident.name, kw::UnderscoreLifetime);
1855 let p_name = ParamName::Plain(ident);
1856 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1857 &mut self.captured_lifetimes
1858 && !binders_to_ignore.contains(&binder)
1860 match captures.entry(param) {
1861 Entry::Occupied(_) => {}
1862 Entry::Vacant(v) => {
1863 let p_id = self.resolver.next_node_id();
1864 self.resolver.create_def(
1867 DefPathData::LifetimeNs(p_name.ident().name),
1869 span.with_parent(None),
1872 v.insert((span, p_id, p_name, res));
1876 hir::LifetimeName::Param(p_name)
1878 LifetimeRes::Fresh { mut param, binder } => {
1879 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1880 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1881 &mut self.captured_lifetimes
1882 && !binders_to_ignore.contains(&binder)
1884 match captures.entry(param) {
1885 Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1),
1886 Entry::Vacant(v) => {
1887 let p_id = self.resolver.next_node_id();
1888 let p_def_id = self.resolver.create_def(
1891 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1893 span.with_parent(None),
1896 let p_name = ParamName::Fresh(param);
1897 v.insert((span, p_id, p_name, res));
1902 let p_name = ParamName::Fresh(param);
1903 hir::LifetimeName::Param(p_name)
1905 LifetimeRes::Anonymous { binder, elided } => {
1906 let l_name = if elided {
1907 hir::LifetimeName::Implicit
1909 hir::LifetimeName::Underscore
1911 if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) =
1912 &mut self.captured_lifetimes
1913 && !binders_to_ignore.contains(&binder)
1915 let p_id = self.resolver.next_node_id();
1916 let p_def_id = self.resolver.create_def(
1919 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1921 span.with_parent(None),
1923 let p_name = ParamName::Fresh(p_def_id);
1924 captures.insert(p_def_id, (span, p_id, p_name, res));
1925 hir::LifetimeName::Param(p_name)
1930 LifetimeRes::Static => hir::LifetimeName::Static,
1931 LifetimeRes::Error => hir::LifetimeName::Error,
1932 res => panic!("Unexpected lifetime resolution {:?} for {:?} at {:?}", res, ident, span),
1934 debug!(?self.captured_lifetimes);
1935 hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1938 fn lower_generic_params_mut<'s>(
1940 params: &'s [GenericParam],
1941 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1942 params.iter().map(move |param| self.lower_generic_param(param))
1945 fn lower_generic_params(&mut self, params: &[GenericParam]) -> &'hir [hir::GenericParam<'hir>] {
1946 self.arena.alloc_from_iter(self.lower_generic_params_mut(params))
1949 fn lower_generic_param(&mut self, param: &GenericParam) -> hir::GenericParam<'hir> {
1950 let (name, kind) = match param.kind {
1951 GenericParamKind::Lifetime => {
1952 let param_name = if param.ident.name == kw::StaticLifetime
1953 || param.ident.name == kw::UnderscoreLifetime
1957 let ident = self.lower_ident(param.ident);
1958 ParamName::Plain(ident)
1961 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
1965 GenericParamKind::Type { ref default, .. } => {
1966 let kind = hir::GenericParamKind::Type {
1967 default: default.as_ref().map(|x| {
1968 self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
1973 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
1975 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1976 let ty = self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
1977 let default = default.as_ref().map(|def| self.lower_anon_const(def));
1979 hir::ParamName::Plain(self.lower_ident(param.ident)),
1980 hir::GenericParamKind::Const { ty, default },
1984 let name = match name {
1985 hir::ParamName::Plain(ident) => hir::ParamName::Plain(self.lower_ident(ident)),
1989 let hir_id = self.lower_node_id(param.id);
1990 self.lower_attrs(hir_id, ¶m.attrs);
1994 span: self.lower_span(param.span()),
1995 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
1997 colon_span: param.colon_span.map(|s| self.lower_span(s)),
2004 itctx: ImplTraitContext<'_, 'hir>,
2005 ) -> hir::TraitRef<'hir> {
2006 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2007 hir::QPath::Resolved(None, path) => path,
2008 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2010 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2013 #[tracing::instrument(level = "debug", skip(self))]
2014 fn lower_poly_trait_ref(
2017 mut itctx: ImplTraitContext<'_, 'hir>,
2018 ) -> hir::PolyTraitRef<'hir> {
2019 let bound_generic_params = self.lower_generic_params(&p.bound_generic_params);
2021 let trait_ref = self.with_lifetime_binder(p.trait_ref.ref_id, |this| {
2022 this.lower_trait_ref(&p.trait_ref, itctx.reborrow())
2025 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2028 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2029 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2032 fn lower_param_bounds(
2034 bounds: &[GenericBound],
2035 itctx: ImplTraitContext<'_, 'hir>,
2036 ) -> hir::GenericBounds<'hir> {
2037 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2040 fn lower_param_bounds_mut<'s>(
2042 bounds: &'s [GenericBound],
2043 mut itctx: ImplTraitContext<'s, 'hir>,
2044 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2045 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2048 /// Lowers a block directly to an expression, presuming that it
2049 /// has no attributes and is not targeted by a `break`.
2050 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2051 let block = self.lower_block(b, false);
2052 self.expr_block(block, AttrVec::new())
2055 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2056 match c.value.kind {
2057 ExprKind::Underscore => {
2058 if self.sess.features_untracked().generic_arg_infer {
2059 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2062 &self.sess.parse_sess,
2063 sym::generic_arg_infer,
2065 "using `_` for array lengths is unstable",
2068 hir::ArrayLen::Body(self.lower_anon_const(c))
2071 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2075 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2076 self.with_new_scopes(|this| hir::AnonConst {
2077 hir_id: this.lower_node_id(c.id),
2078 body: this.lower_const_body(c.value.span, Some(&c.value)),
2082 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2084 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2085 UserProvided => hir::UnsafeSource::UserProvided,
2089 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2091 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2092 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2094 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2095 // placeholder for compilation to proceed.
2096 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2097 hir::TraitBoundModifier::Maybe
2102 // Helper methods for building HIR.
2104 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2105 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2108 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2109 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2114 attrs: Option<&'hir [Attribute]>,
2116 init: Option<&'hir hir::Expr<'hir>>,
2117 pat: &'hir hir::Pat<'hir>,
2118 source: hir::LocalSource,
2119 ) -> hir::Stmt<'hir> {
2120 let hir_id = self.next_id();
2121 if let Some(a) = attrs {
2122 debug_assert!(!a.is_empty());
2123 self.attrs.insert(hir_id.local_id, a);
2125 let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2126 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2129 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2130 self.block_all(expr.span, &[], Some(expr))
2136 stmts: &'hir [hir::Stmt<'hir>],
2137 expr: Option<&'hir hir::Expr<'hir>>,
2138 ) -> &'hir hir::Block<'hir> {
2139 let blk = hir::Block {
2142 hir_id: self.next_id(),
2143 rules: hir::BlockCheckMode::DefaultBlock,
2144 span: self.lower_span(span),
2145 targeted_by_break: false,
2147 self.arena.alloc(blk)
2150 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2151 let field = self.single_pat_field(span, pat);
2152 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2155 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2156 let field = self.single_pat_field(span, pat);
2157 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2160 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2161 let field = self.single_pat_field(span, pat);
2162 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2165 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2166 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2169 fn single_pat_field(
2172 pat: &'hir hir::Pat<'hir>,
2173 ) -> &'hir [hir::PatField<'hir>] {
2174 let field = hir::PatField {
2175 hir_id: self.next_id(),
2176 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2177 is_shorthand: false,
2179 span: self.lower_span(span),
2181 arena_vec![self; field]
2184 fn pat_lang_item_variant(
2187 lang_item: hir::LangItem,
2188 fields: &'hir [hir::PatField<'hir>],
2189 hir_id: Option<hir::HirId>,
2190 ) -> &'hir hir::Pat<'hir> {
2191 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2192 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2195 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2196 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2199 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2200 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2203 fn pat_ident_binding_mode(
2207 bm: hir::BindingAnnotation,
2208 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2209 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2210 (self.arena.alloc(pat), hir_id)
2213 fn pat_ident_binding_mode_mut(
2217 bm: hir::BindingAnnotation,
2218 ) -> (hir::Pat<'hir>, hir::HirId) {
2219 let hir_id = self.next_id();
2224 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2225 span: self.lower_span(span),
2226 default_binding_modes: true,
2232 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2233 self.arena.alloc(hir::Pat {
2234 hir_id: self.next_id(),
2236 span: self.lower_span(span),
2237 default_binding_modes: true,
2241 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2243 hir_id: self.next_id(),
2245 span: self.lower_span(span),
2246 default_binding_modes: false,
2252 mut hir_id: hir::HirId,
2254 qpath: hir::QPath<'hir>,
2255 ) -> hir::Ty<'hir> {
2256 let kind = match qpath {
2257 hir::QPath::Resolved(None, path) => {
2258 // Turn trait object paths into `TyKind::TraitObject` instead.
2260 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2261 let principal = hir::PolyTraitRef {
2262 bound_generic_params: &[],
2263 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2264 span: self.lower_span(span),
2267 // The original ID is taken by the `PolyTraitRef`,
2268 // so the `Ty` itself needs a different one.
2269 hir_id = self.next_id();
2270 hir::TyKind::TraitObject(
2271 arena_vec![self; principal],
2272 self.elided_dyn_bound(span),
2273 TraitObjectSyntax::None,
2276 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2279 _ => hir::TyKind::Path(qpath),
2282 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2285 /// Invoked to create the lifetime argument(s) for an elided trait object
2286 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2287 /// when the bound is written, even if it is written with `'_` like in
2288 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2289 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2290 let r = hir::Lifetime {
2291 hir_id: self.next_id(),
2292 span: self.lower_span(span),
2293 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2295 debug!("elided_dyn_bound: r={:?}", r);
2300 /// Helper struct for delayed construction of GenericArgs.
2301 struct GenericArgsCtor<'hir> {
2302 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2303 bindings: &'hir [hir::TypeBinding<'hir>],
2304 parenthesized: bool,
2308 impl<'hir> GenericArgsCtor<'hir> {
2309 fn is_empty(&self) -> bool {
2310 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2313 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2314 let ga = hir::GenericArgs {
2315 args: this.arena.alloc_from_iter(self.args),
2316 bindings: self.bindings,
2317 parenthesized: self.parenthesized,
2318 span_ext: this.lower_span(self.span),
2320 this.arena.alloc(ga)