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(crate_visibility_modifier)]
34 #![feature(box_patterns)]
36 #![feature(never_type)]
37 #![recursion_limit = "256"]
38 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
40 use rustc_ast::token::{self, Token};
41 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream, TokenTree};
43 use rustc_ast::{self as ast, *};
44 use rustc_ast_pretty::pprust;
45 use rustc_data_structures::captures::Captures;
46 use rustc_data_structures::fingerprint::Fingerprint;
47 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
48 use rustc_data_structures::sorted_map::SortedMap;
49 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
50 use rustc_data_structures::sync::Lrc;
51 use rustc_errors::struct_span_err;
53 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
54 use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID};
55 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
56 use rustc_hir::intravisit;
57 use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate};
58 use rustc_index::vec::{Idx, IndexVec};
59 use rustc_query_system::ich::StableHashingContext;
60 use rustc_session::lint::LintBuffer;
61 use rustc_session::parse::feature_err;
62 use rustc_session::utils::{FlattenNonterminals, NtToTokenstream};
63 use rustc_session::Session;
64 use rustc_span::hygiene::{ExpnId, MacroKind};
65 use rustc_span::source_map::{respan, DesugaringKind};
66 use rustc_span::symbol::{kw, sym, Ident, Symbol};
67 use rustc_span::{Span, DUMMY_SP};
69 use smallvec::SmallVec;
70 use std::collections::hash_map::Entry;
71 use tracing::{debug, trace};
73 macro_rules! arena_vec {
74 ($this:expr; $($x:expr),*) => (
75 $this.arena.alloc_from_iter([$($x),*])
87 rustc_hir::arena_types!(rustc_arena::declare_arena);
89 struct LoweringContext<'a, 'hir: 'a> {
90 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
93 resolver: &'a mut dyn ResolverAstLowering,
95 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
96 /// if we don't have this function pointer. To avoid that dependency so that
97 /// `rustc_middle` is independent of the parser, we use dynamic dispatch here.
98 nt_to_tokenstream: NtToTokenstream,
100 /// Used to allocate HIR nodes.
101 arena: &'hir Arena<'hir>,
103 /// The items being lowered are collected here.
104 owners: IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
105 /// Bodies inside the owner being lowered.
106 bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
107 /// Attributes inside the owner being lowered.
108 attrs: SortedMap<hir::ItemLocalId, &'hir [Attribute]>,
110 generator_kind: Option<hir::GeneratorKind>,
112 /// When inside an `async` context, this is the `HirId` of the
113 /// `task_context` local bound to the resume argument of the generator.
114 task_context: Option<hir::HirId>,
116 /// Used to get the current `fn`'s def span to point to when using `await`
117 /// outside of an `async fn`.
118 current_item: Option<Span>,
120 catch_scope: Option<NodeId>,
121 loop_scope: Option<NodeId>,
122 is_in_loop_condition: bool,
123 is_in_trait_impl: bool,
124 is_in_dyn_type: bool,
126 /// What to do when we encounter an "anonymous lifetime
127 /// reference". The term "anonymous" is meant to encompass both
128 /// `'_` lifetimes as well as fully elided cases where nothing is
129 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
130 anonymous_lifetime_mode: AnonymousLifetimeMode,
132 /// Used to create lifetime definitions from in-band lifetime usages.
133 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
134 /// When a named lifetime is encountered in a function or impl header and
135 /// has not been defined
136 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
137 /// to this list. The results of this list are then added to the list of
138 /// lifetime definitions in the corresponding impl or function generics.
139 lifetimes_to_define: Vec<(Span, ParamName)>,
141 /// `true` if in-band lifetimes are being collected. This is used to
142 /// indicate whether or not we're in a place where new lifetimes will result
143 /// in in-band lifetime definitions, such a function or an impl header,
144 /// including implicit lifetimes from `impl_header_lifetime_elision`.
145 is_collecting_in_band_lifetimes: bool,
147 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
148 /// When `is_collecting_in_band_lifetimes` is true, each lifetime is checked
149 /// against this list to see if it is already in-scope, or if a definition
150 /// needs to be created for it.
152 /// We always store a `normalize_to_macros_2_0()` version of the param-name in this
154 in_scope_lifetimes: Vec<ParamName>,
156 current_hir_id_owner: LocalDefId,
157 item_local_id_counter: hir::ItemLocalId,
158 local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
159 trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
161 /// NodeIds that are lowered inside the current HIR owner.
162 node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
164 allow_try_trait: Option<Lrc<[Symbol]>>,
165 allow_gen_future: Option<Lrc<[Symbol]>>,
166 allow_into_future: Option<Lrc<[Symbol]>>,
169 pub trait ResolverAstLowering {
170 fn def_key(&mut self, id: DefId) -> DefKey;
172 fn def_span(&self, id: LocalDefId) -> Span;
174 fn item_generics_num_lifetimes(&self, def: DefId) -> usize;
176 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>>;
178 /// Obtains resolution for a `NodeId` with a single resolution.
179 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
181 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
182 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
184 /// Obtains resolution for a label with the given `NodeId`.
185 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
187 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
188 /// This should only return `None` during testing.
189 fn definitions(&mut self) -> &mut Definitions;
191 fn create_stable_hashing_context(&self) -> StableHashingContext<'_>;
193 fn lint_buffer(&mut self) -> &mut LintBuffer;
195 fn next_node_id(&mut self) -> NodeId;
197 fn take_trait_map(&mut self, node: NodeId) -> Option<Vec<hir::TraitCandidate>>;
199 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
201 fn local_def_id(&self, node: NodeId) -> LocalDefId;
203 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
208 node_id: ast::NodeId,
214 fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
217 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
218 /// and if so, what meaning it has.
220 enum ImplTraitContext<'b, 'a> {
221 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
222 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
223 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
225 /// Newly generated parameters should be inserted into the given `Vec`.
226 Universal(&'b mut Vec<hir::GenericParam<'a>>, LocalDefId),
228 /// Treat `impl Trait` as shorthand for a new opaque type.
229 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
230 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
232 ReturnPositionOpaqueTy {
233 /// `DefId` for the parent function, used to look up necessary
234 /// information later.
235 fn_def_id: LocalDefId,
236 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
237 origin: hir::OpaqueTyOrigin,
239 /// Impl trait in type aliases.
240 TypeAliasesOpaqueTy {
241 /// Set of lifetimes that this opaque type can capture, if it uses
242 /// them. This includes lifetimes bound since we entered this context.
246 /// type A<'b> = impl for<'a> Trait<'a, Out = impl Sized + 'a>;
249 /// Here the inner opaque type captures `'a` because it uses it. It doesn't
250 /// need to capture `'b` because it already inherits the lifetime
251 /// parameter from `A`.
252 // FIXME(impl_trait): but `required_region_bounds` will ICE later
254 capturable_lifetimes: &'b mut FxHashSet<hir::LifetimeName>,
256 /// `impl Trait` is not accepted in this position.
257 Disallowed(ImplTraitPosition),
260 /// Position in which `impl Trait` is disallowed.
261 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
262 enum ImplTraitPosition {
284 impl<'a> ImplTraitContext<'_, 'a> {
285 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
286 use self::ImplTraitContext::*;
288 Universal(params, parent) => Universal(params, *parent),
289 ReturnPositionOpaqueTy { fn_def_id, origin } => {
290 ReturnPositionOpaqueTy { fn_def_id: *fn_def_id, origin: *origin }
292 TypeAliasesOpaqueTy { capturable_lifetimes } => {
293 TypeAliasesOpaqueTy { capturable_lifetimes }
295 Disallowed(pos) => Disallowed(*pos),
300 impl std::fmt::Display for ImplTraitPosition {
301 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302 let name = match self {
303 ImplTraitPosition::Path => "path",
304 ImplTraitPosition::Variable => "variable binding",
305 ImplTraitPosition::Type => "type",
306 ImplTraitPosition::Trait => "trait",
307 ImplTraitPosition::AsyncBlock => "async block",
308 ImplTraitPosition::Bound => "bound",
309 ImplTraitPosition::Generic => "generic",
310 ImplTraitPosition::ExternFnParam => "`extern fn` param",
311 ImplTraitPosition::ClosureParam => "closure param",
312 ImplTraitPosition::PointerParam => "`fn` pointer param",
313 ImplTraitPosition::FnTraitParam => "`Fn` trait param",
314 ImplTraitPosition::TraitParam => "trait method param",
315 ImplTraitPosition::ImplParam => "`impl` method param",
316 ImplTraitPosition::ExternFnReturn => "`extern fn` return",
317 ImplTraitPosition::ClosureReturn => "closure return",
318 ImplTraitPosition::PointerReturn => "`fn` pointer return",
319 ImplTraitPosition::FnTraitReturn => "`Fn` trait return",
320 ImplTraitPosition::TraitReturn => "trait method return",
321 ImplTraitPosition::ImplReturn => "`impl` method return",
324 write!(f, "{}", name)
340 fn impl_trait_return_allowed(&self) -> bool {
342 FnDeclKind::Fn | FnDeclKind::Inherent => true,
348 pub fn lower_crate<'a, 'hir>(
351 resolver: &'a mut dyn ResolverAstLowering,
352 nt_to_tokenstream: NtToTokenstream,
353 arena: &'hir Arena<'hir>,
354 ) -> &'hir hir::Crate<'hir> {
355 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
358 IndexVec::from_fn_n(|_| hir::MaybeOwner::Phantom, resolver.definitions().def_index_count());
366 attrs: SortedMap::new(),
369 is_in_loop_condition: false,
370 is_in_trait_impl: false,
371 is_in_dyn_type: false,
372 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
373 current_hir_id_owner: CRATE_DEF_ID,
374 item_local_id_counter: hir::ItemLocalId::new(0),
375 node_id_to_local_id: FxHashMap::default(),
376 local_id_to_def_id: SortedMap::new(),
377 trait_map: FxHashMap::default(),
378 generator_kind: None,
381 lifetimes_to_define: Vec::new(),
382 is_collecting_in_band_lifetimes: false,
383 in_scope_lifetimes: Vec::new(),
384 allow_try_trait: Some([sym::try_trait_v2][..].into()),
385 allow_gen_future: Some([sym::gen_future][..].into()),
386 allow_into_future: Some([sym::into_future][..].into()),
391 #[derive(Copy, Clone, PartialEq)]
393 /// Any path in a type context.
395 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
397 /// The `module::Type` in `module::Type::method` in an expression.
401 enum ParenthesizedGenericArgs {
406 /// What to do when we encounter an **anonymous** lifetime
407 /// reference. Anonymous lifetime references come in two flavors. You
408 /// have implicit, or fully elided, references to lifetimes, like the
409 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
410 /// or `Ref<'_, T>`. These often behave the same, but not always:
412 /// - certain usages of implicit references are deprecated, like
413 /// `Ref<T>`, and we sometimes just give hard errors in those cases
415 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
416 /// the same as `Box<dyn Foo + '_>`.
418 /// We describe the effects of the various modes in terms of three cases:
420 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
421 /// of a `&` (e.g., the missing lifetime in something like `&T`)
422 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
423 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
424 /// elided bounds follow special rules. Note that this only covers
425 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
426 /// '_>` is a case of "modern" elision.
427 /// - **Deprecated** -- this covers cases like `Ref<T>`, where the lifetime
428 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
429 /// non-deprecated equivalent.
431 /// Currently, the handling of lifetime elision is somewhat spread out
432 /// between HIR lowering and -- as described below -- the
433 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
434 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
435 /// everything into HIR lowering.
436 #[derive(Copy, Clone, Debug)]
437 enum AnonymousLifetimeMode {
438 /// For **Modern** cases, create a new anonymous region parameter
439 /// and reference that.
441 /// For **Dyn Bound** cases, pass responsibility to
442 /// `resolve_lifetime` code.
444 /// For **Deprecated** cases, report an error.
447 /// Give a hard error when either `&` or `'_` is written. Used to
448 /// rule out things like `where T: Foo<'_>`. Does not imply an
449 /// error on default object bounds (e.g., `Box<dyn Foo>`).
452 /// Pass responsibility to `resolve_lifetime` code for all cases.
456 impl<'a, 'hir> LoweringContext<'a, 'hir> {
457 fn lower_crate(mut self, c: &Crate) -> &'hir hir::Crate<'hir> {
458 debug_assert_eq!(self.resolver.local_def_id(CRATE_NODE_ID), CRATE_DEF_ID);
460 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
462 self.with_hir_id_owner(CRATE_NODE_ID, |lctx| {
463 let module = lctx.lower_mod(&c.items, c.span);
464 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
465 hir::OwnerNode::Crate(lctx.arena.alloc(module))
468 let hir_hash = self.compute_hir_hash();
470 let krate = hir::Crate { owners: self.owners, hir_hash };
471 self.arena.alloc(krate)
474 /// Compute the hash for the HIR of the full crate.
475 /// This hash will then be part of the crate_hash which is stored in the metadata.
476 fn compute_hir_hash(&mut self) -> Fingerprint {
477 let definitions = self.resolver.definitions();
478 let mut hir_body_nodes: Vec<_> = self
481 .filter_map(|(def_id, info)| {
482 let info = info.as_owner()?;
483 let def_path_hash = definitions.def_path_hash(def_id);
484 Some((def_path_hash, info))
487 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
489 let mut stable_hasher = StableHasher::new();
490 let mut hcx = self.resolver.create_stable_hashing_context();
491 hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
492 stable_hasher.finish()
495 fn with_hir_id_owner(
498 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
500 let def_id = self.resolver.local_def_id(owner);
502 let current_attrs = std::mem::take(&mut self.attrs);
503 let current_bodies = std::mem::take(&mut self.bodies);
504 let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
505 let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id);
506 let current_trait_map = std::mem::take(&mut self.trait_map);
507 let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
508 let current_local_counter =
509 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
511 // Always allocate the first `HirId` for the owner itself.
512 let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
513 debug_assert_eq!(_old, None);
516 debug_assert_eq!(def_id, item.def_id());
517 let info = self.make_owner_info(item);
519 self.attrs = current_attrs;
520 self.bodies = current_bodies;
521 self.node_id_to_local_id = current_node_ids;
522 self.local_id_to_def_id = current_id_to_def_id;
523 self.trait_map = current_trait_map;
524 self.current_hir_id_owner = current_owner;
525 self.item_local_id_counter = current_local_counter;
527 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
528 self.owners[def_id] = hir::MaybeOwner::Owner(self.arena.alloc(info));
533 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> hir::OwnerInfo<'hir> {
534 let attrs = std::mem::take(&mut self.attrs);
535 let mut bodies = std::mem::take(&mut self.bodies);
537 #[cfg(debug_assertions)]
538 for (id, attrs) in attrs.iter() {
539 // Verify that we do not store empty slices in the map.
540 if attrs.is_empty() {
541 panic!("Stored empty attributes for {:?}", id);
545 bodies.sort_by_key(|(k, _)| *k);
546 let bodies = SortedMap::from_presorted_elements(bodies);
547 let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies);
548 let (nodes, parenting) =
549 index::index_hir(self.sess, self.resolver.definitions(), node, &bodies);
550 let nodes = hir::OwnerNodes {
551 hash_including_bodies,
555 local_id_to_def_id: std::mem::take(&mut self.local_id_to_def_id),
558 let mut hcx = self.resolver.create_stable_hashing_context();
559 let mut stable_hasher = StableHasher::new();
560 attrs.hash_stable(&mut hcx, &mut stable_hasher);
561 let hash = stable_hasher.finish();
562 hir::AttributeMap { map: attrs, hash }
565 hir::OwnerInfo { nodes, parenting, attrs, trait_map: std::mem::take(&mut self.trait_map) }
568 /// Hash the HIR node twice, one deep and one shallow hash. This allows to differentiate
569 /// queries which depend on the full HIR tree and those which only depend on the item signature.
572 node: hir::OwnerNode<'hir>,
573 bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
574 ) -> (Fingerprint, Fingerprint) {
575 let mut hcx = self.resolver.create_stable_hashing_context();
576 let mut stable_hasher = StableHasher::new();
577 hcx.with_hir_bodies(true, node.def_id(), bodies, |hcx| {
578 node.hash_stable(hcx, &mut stable_hasher)
580 let hash_including_bodies = stable_hasher.finish();
581 let mut stable_hasher = StableHasher::new();
582 hcx.with_hir_bodies(false, node.def_id(), bodies, |hcx| {
583 node.hash_stable(hcx, &mut stable_hasher)
585 let hash_without_bodies = stable_hasher.finish();
586 (hash_including_bodies, hash_without_bodies)
589 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
590 /// the `LoweringContext`'s `NodeId => HirId` map.
591 /// Take care not to call this method if the resulting `HirId` is then not
592 /// actually used in the HIR, as that would trigger an assertion in the
593 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
594 /// properly. Calling the method twice with the same `NodeId` is fine though.
595 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
596 assert_ne!(ast_node_id, DUMMY_NODE_ID);
598 match self.node_id_to_local_id.entry(ast_node_id) {
599 Entry::Occupied(o) => {
600 hir::HirId { owner: self.current_hir_id_owner, local_id: *o.get() }
602 Entry::Vacant(v) => {
603 // Generate a new `HirId`.
604 let owner = self.current_hir_id_owner;
605 let local_id = self.item_local_id_counter;
606 let hir_id = hir::HirId { owner, local_id };
609 self.item_local_id_counter.increment_by(1);
611 assert_ne!(local_id, hir::ItemLocalId::new(0));
612 if let Some(def_id) = self.resolver.opt_local_def_id(ast_node_id) {
613 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
614 if let o @ hir::MaybeOwner::Phantom = &mut self.owners[def_id] {
615 // Do not override a `MaybeOwner::Owner` that may already here.
616 *o = hir::MaybeOwner::NonOwner(hir_id);
618 self.local_id_to_def_id.insert(local_id, def_id);
621 if let Some(traits) = self.resolver.take_trait_map(ast_node_id) {
622 self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
630 fn next_id(&mut self) -> hir::HirId {
631 let node_id = self.resolver.next_node_id();
632 self.lower_node_id(node_id)
635 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
636 let res: Result<Res, ()> = res.apply_id(|id| {
637 let owner = self.current_hir_id_owner;
638 let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
639 Ok(hir::HirId { owner, local_id })
641 // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
642 // This can happen when trying to lower the return type `x` in erroneous code like
643 // async fn foo(x: u8) -> x {}
644 // In that case, `x` is lowered as a function parameter, and the return type is lowered as
645 // an opaque type as a synthetized HIR owner.
646 res.unwrap_or(Res::Err)
649 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
650 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
651 if pr.unresolved_segments() != 0 {
652 panic!("path not fully resolved: {:?}", pr);
658 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
659 self.resolver.get_import_res(id).present_items()
662 fn diagnostic(&self) -> &rustc_errors::Handler {
663 self.sess.diagnostic()
666 /// Reuses the span but adds information like the kind of the desugaring and features that are
667 /// allowed inside this span.
668 fn mark_span_with_reason(
670 reason: DesugaringKind,
672 allow_internal_unstable: Option<Lrc<[Symbol]>>,
674 span.mark_with_reason(
675 allow_internal_unstable,
678 self.resolver.create_stable_hashing_context(),
682 fn with_anonymous_lifetime_mode<R>(
684 anonymous_lifetime_mode: AnonymousLifetimeMode,
685 op: impl FnOnce(&mut Self) -> R,
688 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
689 anonymous_lifetime_mode,
691 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
692 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
693 let result = op(self);
694 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
696 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
697 old_anonymous_lifetime_mode
702 /// Intercept all spans entering HIR.
703 /// Mark a span as relative to the current owning item.
704 fn lower_span(&self, span: Span) -> Span {
705 if self.sess.opts.debugging_opts.incremental_relative_spans {
706 span.with_parent(Some(self.current_hir_id_owner))
708 // Do not make spans relative when not using incremental compilation.
713 fn lower_ident(&self, ident: Ident) -> Ident {
714 Ident::new(ident.name, self.lower_span(ident.span))
717 /// Creates a new `hir::GenericParam` for every new lifetime and
718 /// type parameter encountered while evaluating `f`. Definitions
719 /// are created with the parent provided. If no `parent_id` is
720 /// provided, no definitions will be returned.
722 /// Presuming that in-band lifetimes are enabled, then
723 /// `self.anonymous_lifetime_mode` will be updated to match the
724 /// parameter while `f` is running (and restored afterwards).
725 fn collect_in_band_defs<T>(
727 f: impl FnOnce(&mut Self) -> T,
728 ) -> (Vec<(Span, ParamName)>, T) {
729 let was_collecting = std::mem::replace(&mut self.is_collecting_in_band_lifetimes, true);
730 let len = self.lifetimes_to_define.len();
734 let lifetimes_to_define = self.lifetimes_to_define.split_off(len);
735 self.is_collecting_in_band_lifetimes = was_collecting;
736 (lifetimes_to_define, res)
739 /// Converts a lifetime into a new generic parameter.
740 fn lifetime_to_generic_param(
744 parent_def_id: LocalDefId,
745 ) -> hir::GenericParam<'hir> {
746 let node_id = self.resolver.next_node_id();
748 // Get the name we'll use to make the def-path. Note
749 // that collisions are ok here and this shouldn't
750 // really show up for end-user.
751 let (str_name, kind) = match hir_name {
752 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
753 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
754 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
757 // Add a definition for the in-band lifetime def.
758 self.resolver.create_def(
761 DefPathData::LifetimeNs(str_name),
763 span.with_parent(None),
767 hir_id: self.lower_node_id(node_id),
770 span: self.lower_span(span),
771 pure_wrt_drop: false,
772 kind: hir::GenericParamKind::Lifetime { kind },
776 /// When there is a reference to some lifetime `'a`, and in-band
777 /// lifetimes are enabled, then we want to push that lifetime into
778 /// the vector of names to define later. In that case, it will get
779 /// added to the appropriate generics.
780 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
781 if !self.is_collecting_in_band_lifetimes {
785 if !self.sess.features_untracked().in_band_lifetimes {
789 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
793 let hir_name = ParamName::Plain(ident);
795 if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
796 lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
801 self.lifetimes_to_define.push((ident.span, hir_name));
804 /// When we have either an elided or `'_` lifetime in an impl
805 /// header, we convert it to an in-band lifetime.
806 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
807 assert!(self.is_collecting_in_band_lifetimes);
808 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
809 let hir_name = ParamName::Fresh(index);
810 self.lifetimes_to_define.push((span, hir_name));
814 // Evaluates `f` with the lifetimes in `params` in-scope.
815 // This is used to track which lifetimes have already been defined, and
816 // which are new in-band lifetimes that need to have a definition created
818 fn with_in_scope_lifetime_defs<T>(
820 params: &[GenericParam],
821 f: impl FnOnce(&mut Self) -> T,
823 let old_len = self.in_scope_lifetimes.len();
824 let lt_def_names = params.iter().filter_map(|param| match param.kind {
825 GenericParamKind::Lifetime { .. } => {
826 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
830 self.in_scope_lifetimes.extend(lt_def_names);
834 self.in_scope_lifetimes.truncate(old_len);
838 /// Appends in-band lifetime defs and argument-position `impl
839 /// Trait` defs to the existing set of generics.
841 /// Presuming that in-band lifetimes are enabled, then
842 /// `self.anonymous_lifetime_mode` will be updated to match the
843 /// parameter while `f` is running (and restored afterwards).
844 fn add_in_band_defs<T>(
847 parent_def_id: LocalDefId,
848 anonymous_lifetime_mode: AnonymousLifetimeMode,
849 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
850 ) -> (hir::Generics<'hir>, T) {
851 let (lifetimes_to_define, (mut lowered_generics, impl_trait_defs, res)) = self
852 .collect_in_band_defs(|this| {
853 this.with_anonymous_lifetime_mode(anonymous_lifetime_mode, |this| {
854 this.with_in_scope_lifetime_defs(&generics.params, |this| {
855 let mut impl_trait_defs = Vec::new();
856 // Note: it is necessary to lower generics *before* calling `f`.
857 // When lowering `async fn`, there's a final step when lowering
858 // the return type that assumes that all in-scope lifetimes have
859 // already been added to either `in_scope_lifetimes` or
860 // `lifetimes_to_define`. If we swapped the order of these two,
861 // in-band-lifetimes introduced by generics or where-clauses
862 // wouldn't have been added yet.
863 let generics = this.lower_generics_mut(
865 ImplTraitContext::Universal(
866 &mut impl_trait_defs,
867 this.current_hir_id_owner,
870 let res = f(this, &mut impl_trait_defs);
871 (generics, impl_trait_defs, res)
876 lowered_generics.params.extend(
879 .map(|(span, hir_name)| {
880 self.lifetime_to_generic_param(span, hir_name, parent_def_id)
882 .chain(impl_trait_defs),
885 let lowered_generics = lowered_generics.into_generics(self.arena);
886 (lowered_generics, res)
889 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
890 let was_in_dyn_type = self.is_in_dyn_type;
891 self.is_in_dyn_type = in_scope;
893 let result = f(self);
895 self.is_in_dyn_type = was_in_dyn_type;
900 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
901 let was_in_loop_condition = self.is_in_loop_condition;
902 self.is_in_loop_condition = false;
904 let catch_scope = self.catch_scope.take();
905 let loop_scope = self.loop_scope.take();
907 self.catch_scope = catch_scope;
908 self.loop_scope = loop_scope;
910 self.is_in_loop_condition = was_in_loop_condition;
915 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
916 if attrs.is_empty() {
919 debug_assert_eq!(id.owner, self.current_hir_id_owner);
920 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
921 debug_assert!(!ret.is_empty());
922 self.attrs.insert(id.local_id, ret);
927 fn lower_attr(&self, attr: &Attribute) -> Attribute {
928 // Note that we explicitly do not walk the path. Since we don't really
929 // lower attributes (we use the AST version) there is nowhere to keep
930 // the `HirId`s. We don't actually need HIR version of attributes anyway.
931 // Tokens are also not needed after macro expansion and parsing.
932 let kind = match attr.kind {
933 AttrKind::Normal(ref item, _) => AttrKind::Normal(
935 path: item.path.clone(),
936 args: self.lower_mac_args(&item.args),
941 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
944 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
947 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
948 debug_assert_eq!(id.owner, self.current_hir_id_owner);
949 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
950 if let Some(&a) = self.attrs.get(&target_id.local_id) {
951 debug_assert!(!a.is_empty());
952 self.attrs.insert(id.local_id, a);
956 fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
958 MacArgs::Empty => MacArgs::Empty,
959 MacArgs::Delimited(dspan, delim, ref tokens) => {
960 // This is either a non-key-value attribute, or a `macro_rules!` body.
961 // We either not have any nonterminals present (in the case of an attribute),
962 // or have tokens available for all nonterminals in the case of a nested
963 // `macro_rules`: e.g:
966 // macro_rules! outer {
968 // macro_rules! inner {
975 // In both cases, we don't want to synthesize any tokens
979 self.lower_token_stream(tokens.clone(), CanSynthesizeMissingTokens::No),
982 // This is an inert key-value attribute - it will never be visible to macros
983 // after it gets lowered to HIR. Therefore, we can synthesize tokens with fake
984 // spans to handle nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
985 MacArgs::Eq(eq_span, ref token) => {
986 // In valid code the value is always representable as a single literal token.
987 fn unwrap_single_token(sess: &Session, tokens: TokenStream, span: Span) -> Token {
988 if tokens.len() != 1 {
990 .delay_span_bug(span, "multiple tokens in key-value attribute's value");
992 match tokens.into_trees().next() {
993 Some(TokenTree::Token(token)) => token,
994 Some(TokenTree::Delimited(_, delim, tokens)) => {
995 if delim != token::NoDelim {
996 sess.diagnostic().delay_span_bug(
998 "unexpected delimiter in key-value attribute's value",
1001 unwrap_single_token(sess, tokens, span)
1003 None => Token::dummy(),
1007 let tokens = FlattenNonterminals {
1008 parse_sess: &self.sess.parse_sess,
1009 synthesize_tokens: CanSynthesizeMissingTokens::Yes,
1010 nt_to_tokenstream: self.nt_to_tokenstream,
1012 .process_token(token.clone());
1013 MacArgs::Eq(eq_span, unwrap_single_token(self.sess, tokens, token.span))
1018 fn lower_token_stream(
1020 tokens: TokenStream,
1021 synthesize_tokens: CanSynthesizeMissingTokens,
1023 FlattenNonterminals {
1024 parse_sess: &self.sess.parse_sess,
1026 nt_to_tokenstream: self.nt_to_tokenstream,
1028 .process_token_stream(tokens)
1031 /// Given an associated type constraint like one of these:
1034 /// T: Iterator<Item: Debug>
1036 /// T: Iterator<Item = Debug>
1040 /// returns a `hir::TypeBinding` representing `Item`.
1041 fn lower_assoc_ty_constraint(
1043 constraint: &AssocConstraint,
1044 mut itctx: ImplTraitContext<'_, 'hir>,
1045 ) -> hir::TypeBinding<'hir> {
1046 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
1048 // lower generic arguments of identifier in constraint
1049 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
1050 let gen_args_ctor = match gen_args {
1051 GenericArgs::AngleBracketed(ref data) => {
1052 self.lower_angle_bracketed_parameter_data(
1054 ParamMode::Explicit,
1059 GenericArgs::Parenthesized(ref data) => {
1060 let mut err = self.sess.struct_span_err(
1062 "parenthesized generic arguments cannot be used in associated type constraints"
1064 // FIXME: try to write a suggestion here
1066 self.lower_angle_bracketed_parameter_data(
1067 &data.as_angle_bracketed_args(),
1068 ParamMode::Explicit,
1074 gen_args_ctor.into_generic_args(self)
1076 self.arena.alloc(hir::GenericArgs::none())
1079 let kind = match constraint.kind {
1080 AssocConstraintKind::Equality { ref term } => {
1081 let term = match term {
1082 Term::Ty(ref ty) => self.lower_ty(ty, itctx).into(),
1083 Term::Const(ref c) => self.lower_anon_const(c).into(),
1085 hir::TypeBindingKind::Equality { term }
1087 AssocConstraintKind::Bound { ref bounds } => {
1088 let mut capturable_lifetimes;
1089 let mut parent_def_id = self.current_hir_id_owner;
1090 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
1091 let (desugar_to_impl_trait, itctx) = match itctx {
1092 // We are in the return position:
1094 // fn foo() -> impl Iterator<Item: Debug>
1098 // fn foo() -> impl Iterator<Item = impl Debug>
1099 ImplTraitContext::ReturnPositionOpaqueTy { .. }
1100 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
1102 // We are in the argument position, but within a dyn type:
1104 // fn foo(x: dyn Iterator<Item: Debug>)
1108 // fn foo(x: dyn Iterator<Item = impl Debug>)
1109 ImplTraitContext::Universal(_, parent) if self.is_in_dyn_type => {
1110 parent_def_id = parent;
1114 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1115 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1116 // "impl trait context" to permit `impl Debug` in this position (it desugars
1117 // then to an opaque type).
1119 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1120 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1121 capturable_lifetimes = FxHashSet::default();
1124 ImplTraitContext::TypeAliasesOpaqueTy {
1125 capturable_lifetimes: &mut capturable_lifetimes,
1130 // We are in the parameter position, but not within a dyn type:
1132 // fn foo(x: impl Iterator<Item: Debug>)
1134 // so we leave it as is and this gets expanded in astconv to a bound like
1135 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1137 _ => (false, itctx),
1140 if desugar_to_impl_trait {
1141 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1142 // constructing the HIR for `impl bounds...` and then lowering that.
1144 let impl_trait_node_id = self.resolver.next_node_id();
1145 self.resolver.create_def(
1148 DefPathData::ImplTrait,
1153 self.with_dyn_type_scope(false, |this| {
1154 let node_id = this.resolver.next_node_id();
1155 let ty = this.lower_ty(
1158 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1159 span: this.lower_span(constraint.span),
1165 hir::TypeBindingKind::Equality { term: ty.into() }
1168 // Desugar `AssocTy: Bounds` into a type binding where the
1169 // later desugars into a trait predicate.
1170 let bounds = self.lower_param_bounds(bounds, itctx);
1172 hir::TypeBindingKind::Constraint { bounds }
1178 hir_id: self.lower_node_id(constraint.id),
1179 ident: self.lower_ident(constraint.ident),
1182 span: self.lower_span(constraint.span),
1186 fn lower_generic_arg(
1188 arg: &ast::GenericArg,
1189 itctx: ImplTraitContext<'_, 'hir>,
1190 ) -> hir::GenericArg<'hir> {
1192 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1193 ast::GenericArg::Type(ty) => {
1195 TyKind::Infer if self.sess.features_untracked().generic_arg_infer => {
1196 return GenericArg::Infer(hir::InferArg {
1197 hir_id: self.lower_node_id(ty.id),
1198 span: self.lower_span(ty.span),
1201 // We parse const arguments as path types as we cannot distinguish them during
1202 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1203 // type and value namespaces. If we resolved the path in the value namespace, we
1204 // transform it into a generic const argument.
1205 TyKind::Path(ref qself, ref path) => {
1206 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1207 let res = partial_res.base_res();
1208 if !res.matches_ns(Namespace::TypeNS) {
1210 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1214 // Construct an AnonConst where the expr is the "ty"'s path.
1216 let parent_def_id = self.current_hir_id_owner;
1217 let node_id = self.resolver.next_node_id();
1219 // Add a definition for the in-band const def.
1220 self.resolver.create_def(
1223 DefPathData::AnonConst,
1228 let span = self.lower_span(ty.span);
1229 let path_expr = Expr {
1231 kind: ExprKind::Path(qself.clone(), path.clone()),
1233 attrs: AttrVec::new(),
1237 let ct = self.with_new_scopes(|this| hir::AnonConst {
1238 hir_id: this.lower_node_id(node_id),
1239 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1241 return GenericArg::Const(ConstArg { value: ct, span });
1247 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1249 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1250 value: self.lower_anon_const(&ct),
1251 span: self.lower_span(ct.value.span),
1256 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1257 self.arena.alloc(self.lower_ty_direct(t, itctx))
1263 qself: &Option<QSelf>,
1265 param_mode: ParamMode,
1266 itctx: ImplTraitContext<'_, 'hir>,
1267 ) -> hir::Ty<'hir> {
1268 let id = self.lower_node_id(t.id);
1269 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1270 self.ty_path(id, t.span, qpath)
1273 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1274 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1277 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1278 self.ty(span, hir::TyKind::Tup(tys))
1281 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1282 let kind = match t.kind {
1283 TyKind::Infer => hir::TyKind::Infer,
1284 TyKind::Err => hir::TyKind::Err,
1285 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1286 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1287 TyKind::Rptr(ref region, ref mt) => {
1288 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1289 let lifetime = match *region {
1290 Some(ref lt) => self.lower_lifetime(lt),
1291 None => self.elided_ref_lifetime(span),
1293 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1295 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1296 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1297 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1298 generic_params: this.lower_generic_params(
1300 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1302 unsafety: this.lower_unsafety(f.unsafety),
1303 abi: this.lower_extern(f.ext),
1304 decl: this.lower_fn_decl(&f.decl, None, FnDeclKind::Pointer, None),
1305 param_names: this.lower_fn_params_to_names(&f.decl),
1309 TyKind::Never => hir::TyKind::Never,
1310 TyKind::Tup(ref tys) => {
1311 hir::TyKind::Tup(self.arena.alloc_from_iter(
1312 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1315 TyKind::Paren(ref ty) => {
1316 return self.lower_ty_direct(ty, itctx);
1318 TyKind::Path(ref qself, ref path) => {
1319 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1321 TyKind::ImplicitSelf => {
1322 let res = self.expect_full_res(t.id);
1323 let res = self.lower_res(res);
1324 hir::TyKind::Path(hir::QPath::Resolved(
1326 self.arena.alloc(hir::Path {
1328 segments: arena_vec![self; hir::PathSegment::from_ident(
1329 Ident::with_dummy_span(kw::SelfUpper)
1331 span: self.lower_span(t.span),
1335 TyKind::Array(ref ty, ref length) => {
1336 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_array_length(length))
1338 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1339 TyKind::TraitObject(ref bounds, kind) => {
1340 let mut lifetime_bound = None;
1341 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1343 this.arena.alloc_from_iter(bounds.iter().filter_map(
1344 |bound| match *bound {
1345 GenericBound::Trait(
1347 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1348 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1349 // `~const ?Bound` will cause an error during AST validation
1350 // anyways, so treat it like `?Bound` as compilation proceeds.
1351 GenericBound::Trait(
1353 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1355 GenericBound::Outlives(ref lifetime) => {
1356 if lifetime_bound.is_none() {
1357 lifetime_bound = Some(this.lower_lifetime(lifetime));
1363 let lifetime_bound =
1364 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1365 (bounds, lifetime_bound)
1367 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1369 TyKind::ImplTrait(def_node_id, ref bounds) => {
1372 ImplTraitContext::ReturnPositionOpaqueTy { fn_def_id, origin } => self
1373 .lower_opaque_impl_trait(
1379 |this| this.lower_param_bounds(bounds, itctx),
1381 ImplTraitContext::TypeAliasesOpaqueTy { ref capturable_lifetimes } => {
1382 // Reset capturable lifetimes, any nested impl trait
1383 // types will inherit lifetimes from this opaque type,
1384 // so don't need to capture them again.
1385 let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy {
1386 capturable_lifetimes: &mut FxHashSet::default(),
1388 self.lower_opaque_impl_trait(
1391 hir::OpaqueTyOrigin::TyAlias,
1393 Some(capturable_lifetimes),
1394 |this| this.lower_param_bounds(bounds, nested_itctx),
1397 ImplTraitContext::Universal(in_band_ty_params, parent_def_id) => {
1398 // Add a definition for the in-band `Param`.
1399 let def_id = self.resolver.local_def_id(def_node_id);
1401 let hir_bounds = self.lower_param_bounds(
1403 ImplTraitContext::Universal(in_band_ty_params, parent_def_id),
1405 // Set the name to `impl Bound1 + Bound2`.
1406 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1407 in_band_ty_params.push(hir::GenericParam {
1408 hir_id: self.lower_node_id(def_node_id),
1409 name: ParamName::Plain(self.lower_ident(ident)),
1410 pure_wrt_drop: false,
1412 span: self.lower_span(span),
1413 kind: hir::GenericParamKind::Type { default: None, synthetic: true },
1416 hir::TyKind::Path(hir::QPath::Resolved(
1418 self.arena.alloc(hir::Path {
1419 span: self.lower_span(span),
1420 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1421 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
1425 ImplTraitContext::Disallowed(position) => {
1426 let mut err = struct_span_err!(
1430 "`impl Trait` only allowed in function and inherent method return types, not in {}",
1438 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1439 TyKind::CVarArgs => {
1440 self.sess.delay_span_bug(
1442 "`TyKind::CVarArgs` should have been handled elsewhere",
1448 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1451 fn lower_opaque_impl_trait(
1454 fn_def_id: Option<LocalDefId>,
1455 origin: hir::OpaqueTyOrigin,
1456 opaque_ty_node_id: NodeId,
1457 capturable_lifetimes: Option<&FxHashSet<hir::LifetimeName>>,
1458 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1459 ) -> hir::TyKind<'hir> {
1461 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1462 fn_def_id, opaque_ty_node_id, span,
1465 // Make sure we know that some funky desugaring has been going on here.
1466 // This is a first: there is code in other places like for loop
1467 // desugaring that explicitly states that we don't want to track that.
1468 // Not tracking it makes lints in rustc and clippy very fragile, as
1469 // frequently opened issues show.
1470 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1472 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1474 let mut collected_lifetimes = Vec::new();
1475 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1476 let hir_bounds = lower_bounds(lctx);
1478 collected_lifetimes = lifetimes_from_impl_trait_bounds(
1481 capturable_lifetimes,
1485 lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(|&(name, span)| {
1486 let def_node_id = lctx.resolver.next_node_id();
1487 lctx.resolver.create_def(
1490 DefPathData::LifetimeNs(name.ident().name),
1492 span.with_parent(None),
1494 let hir_id = lctx.lower_node_id(def_node_id);
1496 let (name, kind) = match name {
1497 hir::LifetimeName::Underscore => (
1498 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1499 hir::LifetimeParamKind::Elided,
1501 hir::LifetimeName::Param(param_name) => {
1502 (param_name, hir::LifetimeParamKind::Explicit)
1504 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1511 pure_wrt_drop: false,
1513 kind: hir::GenericParamKind::Lifetime { kind },
1517 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1519 let opaque_ty_item = hir::OpaqueTy {
1520 generics: hir::Generics {
1521 params: lifetime_defs,
1522 where_clause: hir::WhereClause { predicates: &[], span: lctx.lower_span(span) },
1523 span: lctx.lower_span(span),
1529 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1530 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1534 self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(name, span)| {
1535 hir::GenericArg::Lifetime(hir::Lifetime { hir_id: self.next_id(), span, name })
1538 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1540 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1541 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1544 /// Registers a new opaque type with the proper `NodeId`s and
1545 /// returns the lowered node-ID for the opaque type.
1546 fn generate_opaque_type(
1548 opaque_ty_id: LocalDefId,
1549 opaque_ty_item: hir::OpaqueTy<'hir>,
1551 opaque_ty_span: Span,
1552 ) -> hir::OwnerNode<'hir> {
1553 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1554 // Generate an `type Foo = impl Trait;` declaration.
1555 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1556 let opaque_ty_item = hir::Item {
1557 def_id: opaque_ty_id,
1558 ident: Ident::empty(),
1559 kind: opaque_ty_item_kind,
1560 vis: respan(self.lower_span(span.shrink_to_lo()), hir::VisibilityKind::Inherited),
1561 span: self.lower_span(opaque_ty_span),
1563 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1566 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1567 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1568 // as they are not explicit in HIR/Ty function signatures.
1569 // (instead, the `c_variadic` flag is set to `true`)
1570 let mut inputs = &decl.inputs[..];
1571 if decl.c_variadic() {
1572 inputs = &inputs[..inputs.len() - 1];
1574 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1575 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1576 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1580 // Lowers a function declaration.
1582 // `decl`: the unlowered (AST) function declaration.
1583 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1584 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1585 // `make_ret_async` is also `Some`.
1586 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1587 // This guards against trait declarations and implementations where `impl Trait` is
1589 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1590 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1591 // return type `impl Trait` item.
1595 mut in_band_ty_params: Option<(LocalDefId, &mut Vec<hir::GenericParam<'hir>>)>,
1597 make_ret_async: Option<NodeId>,
1598 ) -> &'hir hir::FnDecl<'hir> {
1602 in_band_ty_params: {:?}, \
1604 make_ret_async: {:?})",
1605 decl, in_band_ty_params, kind, make_ret_async,
1607 let lt_mode = if make_ret_async.is_some() {
1608 // In `async fn`, argument-position elided lifetimes
1609 // must be transformed into fresh generic parameters so that
1610 // they can be applied to the opaque `impl Trait` return type.
1611 AnonymousLifetimeMode::CreateParameter
1613 self.anonymous_lifetime_mode
1616 let c_variadic = decl.c_variadic();
1618 // Remember how many lifetimes were already around so that we can
1619 // only look at the lifetime parameters introduced by the arguments.
1620 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1621 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1622 // as they are not explicit in HIR/Ty function signatures.
1623 // (instead, the `c_variadic` flag is set to `true`)
1624 let mut inputs = &decl.inputs[..];
1626 inputs = &inputs[..inputs.len() - 1];
1628 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1629 if let Some((_, ibty)) = &mut in_band_ty_params {
1630 this.lower_ty_direct(
1632 ImplTraitContext::Universal(ibty, this.current_hir_id_owner),
1635 this.lower_ty_direct(
1637 ImplTraitContext::Disallowed(match kind {
1638 FnDeclKind::Fn | FnDeclKind::Inherent => {
1639 unreachable!("fn should allow in-band lifetimes")
1641 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnParam,
1642 FnDeclKind::Closure => ImplTraitPosition::ClosureParam,
1643 FnDeclKind::Pointer => ImplTraitPosition::PointerParam,
1644 FnDeclKind::Trait => ImplTraitPosition::TraitParam,
1645 FnDeclKind::Impl => ImplTraitPosition::ImplParam,
1652 let output = if let Some(ret_id) = make_ret_async {
1653 self.lower_async_fn_ret_ty(
1655 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1660 FnRetTy::Ty(ref ty) => {
1661 let context = match in_band_ty_params {
1662 Some((def_id, _)) if kind.impl_trait_return_allowed() => {
1663 ImplTraitContext::ReturnPositionOpaqueTy {
1665 origin: hir::OpaqueTyOrigin::FnReturn(def_id),
1668 _ => ImplTraitContext::Disallowed(match kind {
1669 FnDeclKind::Fn | FnDeclKind::Inherent => {
1670 unreachable!("fn should allow in-band lifetimes")
1672 FnDeclKind::ExternFn => ImplTraitPosition::ExternFnReturn,
1673 FnDeclKind::Closure => ImplTraitPosition::ClosureReturn,
1674 FnDeclKind::Pointer => ImplTraitPosition::PointerReturn,
1675 FnDeclKind::Trait => ImplTraitPosition::TraitReturn,
1676 FnDeclKind::Impl => ImplTraitPosition::ImplReturn,
1679 hir::FnRetTy::Return(self.lower_ty(ty, context))
1681 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1685 self.arena.alloc(hir::FnDecl {
1689 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1690 use BindingMode::{ByRef, ByValue};
1691 let is_mutable_pat = matches!(
1693 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1697 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1698 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1699 // Given we are only considering `ImplicitSelf` types, we needn't consider
1700 // the case where we have a mutable pattern to a reference as that would
1701 // no longer be an `ImplicitSelf`.
1702 TyKind::Rptr(_, ref mt)
1703 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1705 hir::ImplicitSelfKind::MutRef
1707 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1708 hir::ImplicitSelfKind::ImmRef
1710 _ => hir::ImplicitSelfKind::None,
1716 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1717 // combined with the following definition of `OpaqueTy`:
1719 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1721 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1722 // `output`: unlowered output type (`T` in `-> T`)
1723 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1724 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1725 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1726 fn lower_async_fn_ret_ty(
1729 fn_def_id: LocalDefId,
1730 opaque_ty_node_id: NodeId,
1731 ) -> hir::FnRetTy<'hir> {
1733 "lower_async_fn_ret_ty(\
1736 opaque_ty_node_id={:?})",
1737 output, fn_def_id, opaque_ty_node_id,
1740 let span = output.span();
1742 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1744 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1746 // When we create the opaque type for this async fn, it is going to have
1747 // to capture all the lifetimes involved in the signature (including in the
1748 // return type). This is done by introducing lifetime parameters for:
1750 // - all the explicitly declared lifetimes from the impl and function itself;
1751 // - all the elided lifetimes in the fn arguments;
1752 // - all the elided lifetimes in the return type.
1754 // So for example in this snippet:
1757 // impl<'a> Foo<'a> {
1758 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1759 // // ^ '0 ^ '1 ^ '2
1760 // // elided lifetimes used below
1765 // we would create an opaque type like:
1768 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1771 // and we would then desugar `bar` to the equivalent of:
1774 // impl<'a> Foo<'a> {
1775 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1779 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1780 // this is because the elided lifetimes from the return type
1781 // should be figured out using the ordinary elision rules, and
1782 // this desugaring achieves that.
1784 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", self.in_scope_lifetimes);
1785 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", self.lifetimes_to_define);
1787 // Calculate all the lifetimes that should be captured
1788 // by the opaque type. This should include all in-scope
1789 // lifetime parameters, including those defined in-band.
1791 // `lifetime_params` is a vector of tuple (span, parameter name, lifetime name).
1793 // Input lifetime like `'a` or `'1`:
1794 let mut lifetime_params: Vec<_> = self
1798 .map(|name| (name.ident().span, name, hir::LifetimeName::Param(name)))
1800 self.lifetimes_to_define
1802 .map(|&(span, name)| (span, name, hir::LifetimeName::Param(name))),
1806 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1807 // We have to be careful to get elision right here. The
1808 // idea is that we create a lifetime parameter for each
1809 // lifetime in the return type. So, given a return type
1810 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1811 // Future<Output = &'1 [ &'2 u32 ]>`.
1813 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1814 // hence the elision takes place at the fn site.
1815 let (lifetimes_to_define, future_bound) =
1816 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
1817 this.collect_in_band_defs(|this| {
1818 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1821 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1822 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", lifetimes_to_define);
1824 lifetime_params.extend(
1825 // Output lifetime like `'_`:
1828 .map(|(span, name)| (span, name, hir::LifetimeName::Implicit(false))),
1830 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
1832 let generic_params =
1833 this.arena.alloc_from_iter(lifetime_params.iter().map(|&(span, hir_name, _)| {
1834 this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_id)
1837 let opaque_ty_item = hir::OpaqueTy {
1838 generics: hir::Generics {
1839 params: generic_params,
1840 where_clause: hir::WhereClause { predicates: &[], span: this.lower_span(span) },
1841 span: this.lower_span(span),
1843 bounds: arena_vec![this; future_bound],
1844 origin: hir::OpaqueTyOrigin::AsyncFn(fn_def_id),
1847 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1848 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1851 // As documented above on the variable
1852 // `input_lifetimes_count`, we need to create the lifetime
1853 // arguments to our opaque type. Continuing with our example,
1854 // we're creating the type arguments for the return type:
1857 // Bar<'a, 'b, '0, '1, '_>
1860 // For the "input" lifetime parameters, we wish to create
1861 // references to the parameters themselves, including the
1862 // "implicit" ones created from parameter types (`'a`, `'b`,
1865 // For the "output" lifetime parameters, we just want to
1868 self.arena.alloc_from_iter(lifetime_params.into_iter().map(|(span, _, name)| {
1869 GenericArg::Lifetime(hir::Lifetime {
1870 hir_id: self.next_id(),
1871 span: self.lower_span(span),
1876 // Create the `Foo<...>` reference itself. Note that the `type
1877 // Foo = impl Trait` is, internally, created as a child of the
1878 // async fn, so the *type parameters* are inherited. It's
1879 // only the lifetime parameters that we must supply.
1881 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1882 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1883 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1886 /// Transforms `-> T` into `Future<Output = T>`.
1887 fn lower_async_fn_output_type_to_future_bound(
1890 fn_def_id: LocalDefId,
1892 ) -> hir::GenericBound<'hir> {
1893 // Compute the `T` in `Future<Output = T>` from the return type.
1894 let output_ty = match output {
1895 FnRetTy::Ty(ty) => {
1896 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1897 // `impl Future` opaque type that `async fn` implicitly
1899 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1901 origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id),
1903 self.lower_ty(ty, context)
1905 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1909 let future_args = self.arena.alloc(hir::GenericArgs {
1911 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1912 parenthesized: false,
1916 hir::GenericBound::LangItemTrait(
1917 // ::std::future::Future<future_params>
1918 hir::LangItem::Future,
1919 self.lower_span(span),
1925 fn lower_param_bound(
1928 itctx: ImplTraitContext<'_, 'hir>,
1929 ) -> hir::GenericBound<'hir> {
1931 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1932 self.lower_poly_trait_ref(p, itctx),
1933 self.lower_trait_bound_modifier(*modifier),
1935 GenericBound::Outlives(lifetime) => {
1936 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1941 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1942 let span = self.lower_span(l.ident.span);
1944 ident if ident.name == kw::StaticLifetime => {
1945 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
1947 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
1948 AnonymousLifetimeMode::CreateParameter => {
1949 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1950 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
1953 AnonymousLifetimeMode::PassThrough => {
1954 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1957 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
1960 self.maybe_collect_in_band_lifetime(ident);
1961 let param_name = ParamName::Plain(self.lower_ident(ident));
1962 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
1967 fn new_named_lifetime(
1971 name: hir::LifetimeName,
1972 ) -> hir::Lifetime {
1973 hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1976 fn lower_generic_params_mut<'s>(
1978 params: &'s [GenericParam],
1979 mut itctx: ImplTraitContext<'s, 'hir>,
1980 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1981 params.iter().map(move |param| self.lower_generic_param(param, itctx.reborrow()))
1984 fn lower_generic_params(
1986 params: &[GenericParam],
1987 itctx: ImplTraitContext<'_, 'hir>,
1988 ) -> &'hir [hir::GenericParam<'hir>] {
1989 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, itctx))
1992 fn lower_generic_param(
1994 param: &GenericParam,
1995 mut itctx: ImplTraitContext<'_, 'hir>,
1996 ) -> hir::GenericParam<'hir> {
1997 let bounds: Vec<_> = self
1998 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1999 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
2002 let (name, kind) = match param.kind {
2003 GenericParamKind::Lifetime => {
2004 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
2005 self.is_collecting_in_band_lifetimes = false;
2008 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2009 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
2011 let param_name = match lt.name {
2012 hir::LifetimeName::Param(param_name) => param_name,
2013 hir::LifetimeName::Implicit(_)
2014 | hir::LifetimeName::Underscore
2015 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
2016 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
2017 self.sess.diagnostic().span_bug(
2019 "object-lifetime-default should not occur here",
2022 hir::LifetimeName::Error => ParamName::Error,
2026 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2028 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
2032 GenericParamKind::Type { ref default, .. } => {
2033 let kind = hir::GenericParamKind::Type {
2034 default: default.as_ref().map(|x| {
2035 self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2040 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2042 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2044 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
2045 this.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type))
2047 let default = default.as_ref().map(|def| self.lower_anon_const(def));
2049 hir::ParamName::Plain(self.lower_ident(param.ident)),
2050 hir::GenericParamKind::Const { ty, default },
2054 let name = match name {
2055 hir::ParamName::Plain(ident) => hir::ParamName::Plain(self.lower_ident(ident)),
2059 let hir_id = self.lower_node_id(param.id);
2060 self.lower_attrs(hir_id, ¶m.attrs);
2064 span: self.lower_span(param.ident.span),
2065 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
2066 bounds: self.arena.alloc_from_iter(bounds),
2074 itctx: ImplTraitContext<'_, 'hir>,
2075 ) -> hir::TraitRef<'hir> {
2076 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
2077 hir::QPath::Resolved(None, path) => path,
2078 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
2080 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2083 fn lower_poly_trait_ref(
2086 mut itctx: ImplTraitContext<'_, 'hir>,
2087 ) -> hir::PolyTraitRef<'hir> {
2088 let bound_generic_params =
2089 self.lower_generic_params(&p.bound_generic_params, itctx.reborrow());
2091 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
2092 // Any impl Trait types defined within this scope can capture
2093 // lifetimes bound on this predicate.
2094 let lt_def_names = p.bound_generic_params.iter().filter_map(|param| match param.kind {
2095 GenericParamKind::Lifetime { .. } => Some(hir::LifetimeName::Param(
2096 ParamName::Plain(param.ident.normalize_to_macros_2_0()),
2100 if let ImplTraitContext::TypeAliasesOpaqueTy { ref mut capturable_lifetimes, .. } =
2103 capturable_lifetimes.extend(lt_def_names.clone());
2106 let res = this.lower_trait_ref(&p.trait_ref, itctx.reborrow());
2108 if let ImplTraitContext::TypeAliasesOpaqueTy { ref mut capturable_lifetimes, .. } =
2111 for param in lt_def_names {
2112 capturable_lifetimes.remove(¶m);
2118 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2121 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2122 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2125 fn lower_param_bounds(
2127 bounds: &[GenericBound],
2128 itctx: ImplTraitContext<'_, 'hir>,
2129 ) -> hir::GenericBounds<'hir> {
2130 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2133 fn lower_param_bounds_mut<'s>(
2135 bounds: &'s [GenericBound],
2136 mut itctx: ImplTraitContext<'s, 'hir>,
2137 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2138 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2141 /// Lowers a block directly to an expression, presuming that it
2142 /// has no attributes and is not targeted by a `break`.
2143 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2144 let block = self.lower_block(b, false);
2145 self.expr_block(block, AttrVec::new())
2148 fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen {
2149 match c.value.kind {
2150 ExprKind::Underscore => {
2151 if self.sess.features_untracked().generic_arg_infer {
2152 hir::ArrayLen::Infer(self.lower_node_id(c.id), c.value.span)
2155 &self.sess.parse_sess,
2156 sym::generic_arg_infer,
2158 "using `_` for array lengths is unstable",
2161 hir::ArrayLen::Body(self.lower_anon_const(c))
2164 _ => hir::ArrayLen::Body(self.lower_anon_const(c)),
2168 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2169 self.with_new_scopes(|this| hir::AnonConst {
2170 hir_id: this.lower_node_id(c.id),
2171 body: this.lower_const_body(c.value.span, Some(&c.value)),
2175 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2177 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2178 UserProvided => hir::UnsafeSource::UserProvided,
2182 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2184 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2185 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2187 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2188 // placeholder for compilation to proceed.
2189 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2190 hir::TraitBoundModifier::Maybe
2195 // Helper methods for building HIR.
2197 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2198 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2201 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2202 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2207 attrs: Option<&'hir [Attribute]>,
2209 init: Option<&'hir hir::Expr<'hir>>,
2210 pat: &'hir hir::Pat<'hir>,
2211 source: hir::LocalSource,
2212 ) -> hir::Stmt<'hir> {
2213 let hir_id = self.next_id();
2214 if let Some(a) = attrs {
2215 debug_assert!(!a.is_empty());
2216 self.attrs.insert(hir_id.local_id, a);
2218 let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2219 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2222 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2223 self.block_all(expr.span, &[], Some(expr))
2229 stmts: &'hir [hir::Stmt<'hir>],
2230 expr: Option<&'hir hir::Expr<'hir>>,
2231 ) -> &'hir hir::Block<'hir> {
2232 let blk = hir::Block {
2235 hir_id: self.next_id(),
2236 rules: hir::BlockCheckMode::DefaultBlock,
2237 span: self.lower_span(span),
2238 targeted_by_break: false,
2240 self.arena.alloc(blk)
2243 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2244 let field = self.single_pat_field(span, pat);
2245 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field, None)
2248 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2249 let field = self.single_pat_field(span, pat);
2250 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field, None)
2253 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2254 let field = self.single_pat_field(span, pat);
2255 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field, None)
2258 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2259 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[], None)
2262 fn single_pat_field(
2265 pat: &'hir hir::Pat<'hir>,
2266 ) -> &'hir [hir::PatField<'hir>] {
2267 let field = hir::PatField {
2268 hir_id: self.next_id(),
2269 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2270 is_shorthand: false,
2272 span: self.lower_span(span),
2274 arena_vec![self; field]
2277 fn pat_lang_item_variant(
2280 lang_item: hir::LangItem,
2281 fields: &'hir [hir::PatField<'hir>],
2282 hir_id: Option<hir::HirId>,
2283 ) -> &'hir hir::Pat<'hir> {
2284 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id);
2285 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2288 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2289 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2292 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2293 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2296 fn pat_ident_binding_mode(
2300 bm: hir::BindingAnnotation,
2301 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2302 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2303 (self.arena.alloc(pat), hir_id)
2306 fn pat_ident_binding_mode_mut(
2310 bm: hir::BindingAnnotation,
2311 ) -> (hir::Pat<'hir>, hir::HirId) {
2312 let hir_id = self.next_id();
2317 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2318 span: self.lower_span(span),
2319 default_binding_modes: true,
2325 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2326 self.arena.alloc(hir::Pat {
2327 hir_id: self.next_id(),
2329 span: self.lower_span(span),
2330 default_binding_modes: true,
2334 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2336 hir_id: self.next_id(),
2338 span: self.lower_span(span),
2339 default_binding_modes: false,
2345 mut hir_id: hir::HirId,
2347 qpath: hir::QPath<'hir>,
2348 ) -> hir::Ty<'hir> {
2349 let kind = match qpath {
2350 hir::QPath::Resolved(None, path) => {
2351 // Turn trait object paths into `TyKind::TraitObject` instead.
2353 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2354 let principal = hir::PolyTraitRef {
2355 bound_generic_params: &[],
2356 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2357 span: self.lower_span(span),
2360 // The original ID is taken by the `PolyTraitRef`,
2361 // so the `Ty` itself needs a different one.
2362 hir_id = self.next_id();
2363 hir::TyKind::TraitObject(
2364 arena_vec![self; principal],
2365 self.elided_dyn_bound(span),
2366 TraitObjectSyntax::None,
2369 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2372 _ => hir::TyKind::Path(qpath),
2375 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2378 /// Invoked to create the lifetime argument for a type `&T`
2379 /// with no explicit lifetime.
2380 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2381 match self.anonymous_lifetime_mode {
2382 // Intercept when we are in an impl header or async fn and introduce an in-band
2384 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2386 AnonymousLifetimeMode::CreateParameter => {
2387 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2389 hir_id: self.next_id(),
2390 span: self.lower_span(span),
2391 name: hir::LifetimeName::Param(fresh_name),
2395 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2397 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span, false),
2401 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2402 /// return an "error lifetime".
2403 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2404 let (id, msg, label) = match id {
2405 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2408 self.resolver.next_node_id(),
2409 "`&` without an explicit lifetime name cannot be used here",
2410 "explicit lifetime name needed here",
2414 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2415 err.span_label(span, label);
2418 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2421 /// Invoked to create the lifetime argument(s) for a path like
2422 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2423 /// sorts of cases are deprecated. This may therefore report a warning or an
2424 /// error, depending on the mode.
2425 fn elided_path_lifetimes<'s>(
2429 param_mode: ParamMode,
2430 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2431 (0..count).map(move |_| self.elided_path_lifetime(span, param_mode))
2434 fn elided_path_lifetime(&mut self, span: Span, param_mode: ParamMode) -> hir::Lifetime {
2435 match self.anonymous_lifetime_mode {
2436 AnonymousLifetimeMode::CreateParameter => {
2437 // We should have emitted E0726 when processing this path above
2439 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2440 let id = self.resolver.next_node_id();
2441 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2443 // `PassThrough` is the normal case.
2444 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2445 // is unsuitable here, as these can occur from missing lifetime parameters in a
2446 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2447 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2448 // later, at which point a suitable error will be emitted.
2449 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2450 self.new_implicit_lifetime(span, param_mode == ParamMode::Explicit)
2455 /// Invoked to create the lifetime argument(s) for an elided trait object
2456 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2457 /// when the bound is written, even if it is written with `'_` like in
2458 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2459 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2460 match self.anonymous_lifetime_mode {
2461 // NB. We intentionally ignore the create-parameter mode here.
2462 // and instead "pass through" to resolve-lifetimes, which will apply
2463 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2464 // do not act like other elided lifetimes. In other words, given this:
2466 // impl Foo for Box<dyn Debug>
2468 // we do not introduce a fresh `'_` to serve as the bound, but instead
2469 // ultimately translate to the equivalent of:
2471 // impl Foo for Box<dyn Debug + 'static>
2473 // `resolve_lifetime` has the code to make that happen.
2474 AnonymousLifetimeMode::CreateParameter => {}
2476 AnonymousLifetimeMode::ReportError => {
2477 // ReportError applies to explicit use of `'_`.
2480 // This is the normal case.
2481 AnonymousLifetimeMode::PassThrough => {}
2484 let r = hir::Lifetime {
2485 hir_id: self.next_id(),
2486 span: self.lower_span(span),
2487 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2489 debug!("elided_dyn_bound: r={:?}", r);
2493 fn new_implicit_lifetime(&mut self, span: Span, missing: bool) -> hir::Lifetime {
2495 hir_id: self.next_id(),
2496 span: self.lower_span(span),
2497 name: hir::LifetimeName::Implicit(missing),
2502 /// Helper struct for delayed construction of GenericArgs.
2503 struct GenericArgsCtor<'hir> {
2504 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2505 bindings: &'hir [hir::TypeBinding<'hir>],
2506 parenthesized: bool,
2510 impl<'hir> GenericArgsCtor<'hir> {
2511 fn is_empty(&self) -> bool {
2512 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2515 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2516 let ga = hir::GenericArgs {
2517 args: this.arena.alloc_from_iter(self.args),
2518 bindings: self.bindings,
2519 parenthesized: self.parenthesized,
2520 span_ext: this.lower_span(self.span),
2522 this.arena.alloc(ga)
2526 #[tracing::instrument(level = "debug")]
2527 fn lifetimes_from_impl_trait_bounds(
2528 opaque_ty_id: NodeId,
2529 bounds: hir::GenericBounds<'_>,
2530 lifetimes_to_include: Option<&FxHashSet<hir::LifetimeName>>,
2531 ) -> Vec<(hir::LifetimeName, Span)> {
2532 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
2533 // appear in the bounds, excluding lifetimes that are created within the bounds.
2534 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
2535 struct ImplTraitLifetimeCollector<'r> {
2536 collect_elided_lifetimes: bool,
2537 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2538 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
2539 lifetimes: Vec<(hir::LifetimeName, Span)>,
2540 lifetimes_to_include: Option<&'r FxHashSet<hir::LifetimeName>>,
2543 impl<'r, 'v> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r> {
2544 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
2545 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2546 if parameters.parenthesized {
2547 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2548 self.collect_elided_lifetimes = false;
2549 intravisit::walk_generic_args(self, span, parameters);
2550 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2552 intravisit::walk_generic_args(self, span, parameters);
2556 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
2557 // Don't collect elided lifetimes used inside of `fn()` syntax.
2558 if let hir::TyKind::BareFn(_) = t.kind {
2559 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2560 self.collect_elided_lifetimes = false;
2562 // Record the "stack height" of `for<'a>` lifetime bindings
2563 // to be able to later fully undo their introduction.
2564 let old_len = self.currently_bound_lifetimes.len();
2565 intravisit::walk_ty(self, t);
2566 self.currently_bound_lifetimes.truncate(old_len);
2568 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2570 intravisit::walk_ty(self, t)
2574 fn visit_poly_trait_ref(
2576 trait_ref: &'v hir::PolyTraitRef<'v>,
2577 modifier: hir::TraitBoundModifier,
2579 // Record the "stack height" of `for<'a>` lifetime bindings
2580 // to be able to later fully undo their introduction.
2581 let old_len = self.currently_bound_lifetimes.len();
2582 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2583 self.currently_bound_lifetimes.truncate(old_len);
2586 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
2587 // Record the introduction of 'a in `for<'a> ...`.
2588 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2589 // Introduce lifetimes one at a time so that we can handle
2590 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
2591 let lt_name = hir::LifetimeName::Param(param.name);
2592 self.currently_bound_lifetimes.push(lt_name);
2595 intravisit::walk_generic_param(self, param);
2598 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2599 let name = match lifetime.name {
2600 hir::LifetimeName::Implicit(_) | hir::LifetimeName::Underscore => {
2601 if self.collect_elided_lifetimes {
2602 // Use `'_` for both implicit and underscore lifetimes in
2603 // `type Foo<'_> = impl SomeTrait<'_>;`.
2604 hir::LifetimeName::Underscore
2609 hir::LifetimeName::Param(_) => lifetime.name,
2611 // Refers to some other lifetime that is "in
2612 // scope" within the type.
2613 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
2615 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2618 if !self.currently_bound_lifetimes.contains(&name)
2619 && !self.already_defined_lifetimes.contains(&name)
2620 && self.lifetimes_to_include.map_or(true, |lifetimes| lifetimes.contains(&name))
2622 self.already_defined_lifetimes.insert(name);
2624 self.lifetimes.push((name, lifetime.span));
2629 let mut lifetime_collector = ImplTraitLifetimeCollector {
2630 collect_elided_lifetimes: true,
2631 currently_bound_lifetimes: Vec::new(),
2632 already_defined_lifetimes: FxHashSet::default(),
2633 lifetimes: Vec::new(),
2634 lifetimes_to_include,
2637 for bound in bounds {
2638 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
2641 lifetime_collector.lifetimes