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 #![recursion_limit = "256"]
38 use rustc_ast::token::{self, Token};
39 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream, TokenTree};
41 use rustc_ast::{self as ast, *};
42 use rustc_ast_pretty::pprust;
43 use rustc_data_structures::captures::Captures;
44 use rustc_data_structures::fx::FxHashSet;
45 use rustc_data_structures::sync::Lrc;
46 use rustc_errors::{struct_span_err, Applicability};
48 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
49 use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID};
50 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
51 use rustc_hir::intravisit;
52 use rustc_hir::{ConstArg, GenericArg, InferKind, ParamName};
53 use rustc_index::vec::{Idx, IndexVec};
54 use rustc_session::lint::builtin::BARE_TRAIT_OBJECTS;
55 use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
56 use rustc_session::utils::{FlattenNonterminals, NtToTokenstream};
57 use rustc_session::Session;
58 use rustc_span::edition::Edition;
59 use rustc_span::hygiene::ExpnId;
60 use rustc_span::source_map::{respan, CachingSourceMapView, DesugaringKind};
61 use rustc_span::symbol::{kw, sym, Ident, Symbol};
62 use rustc_span::{Span, DUMMY_SP};
64 use smallvec::SmallVec;
65 use std::collections::BTreeMap;
66 use tracing::{debug, trace};
68 macro_rules! arena_vec {
69 ($this:expr; $($x:expr),*) => ({
71 $this.arena.alloc_from_iter(std::array::IntoIter::new(a))
82 rustc_hir::arena_types!(rustc_arena::declare_arena, 'tcx);
84 struct LoweringContext<'a, 'hir: 'a> {
85 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
88 resolver: &'a mut dyn ResolverAstLowering,
90 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
91 /// if we don't have this function pointer. To avoid that dependency so that
92 /// `rustc_middle` is independent of the parser, we use dynamic dispatch here.
93 nt_to_tokenstream: NtToTokenstream,
95 /// Used to allocate HIR nodes.
96 arena: &'hir Arena<'hir>,
98 /// The items being lowered are collected here.
99 owners: IndexVec<LocalDefId, Option<hir::OwnerInfo<'hir>>>,
100 bodies: BTreeMap<hir::ItemLocalId, hir::Body<'hir>>,
101 attrs: BTreeMap<hir::ItemLocalId, &'hir [Attribute]>,
103 generator_kind: Option<hir::GeneratorKind>,
105 /// When inside an `async` context, this is the `HirId` of the
106 /// `task_context` local bound to the resume argument of the generator.
107 task_context: Option<hir::HirId>,
109 /// Used to get the current `fn`'s def span to point to when using `await`
110 /// outside of an `async fn`.
111 current_item: Option<Span>,
113 catch_scope: Option<NodeId>,
114 loop_scope: Option<NodeId>,
115 is_in_loop_condition: bool,
116 is_in_trait_impl: bool,
117 is_in_dyn_type: bool,
119 /// What to do when we encounter an "anonymous lifetime
120 /// reference". The term "anonymous" is meant to encompass both
121 /// `'_` lifetimes as well as fully elided cases where nothing is
122 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
123 anonymous_lifetime_mode: AnonymousLifetimeMode,
125 /// Used to create lifetime definitions from in-band lifetime usages.
126 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
127 /// When a named lifetime is encountered in a function or impl header and
128 /// has not been defined
129 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
130 /// to this list. The results of this list are then added to the list of
131 /// lifetime definitions in the corresponding impl or function generics.
132 lifetimes_to_define: Vec<(Span, ParamName)>,
134 /// `true` if in-band lifetimes are being collected. This is used to
135 /// indicate whether or not we're in a place where new lifetimes will result
136 /// in in-band lifetime definitions, such a function or an impl header,
137 /// including implicit lifetimes from `impl_header_lifetime_elision`.
138 is_collecting_in_band_lifetimes: bool,
140 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
141 /// When `is_collecting_in_band_lifetimes` is true, each lifetime is checked
142 /// against this list to see if it is already in-scope, or if a definition
143 /// needs to be created for it.
145 /// We always store a `normalize_to_macros_2_0()` version of the param-name in this
147 in_scope_lifetimes: Vec<ParamName>,
149 current_hir_id_owner: LocalDefId,
150 item_local_id_counter: hir::ItemLocalId,
151 node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
153 /// NodeIds that are lowered inside the current HIR owner.
154 local_node_ids: Vec<NodeId>,
156 allow_try_trait: Option<Lrc<[Symbol]>>,
157 allow_gen_future: Option<Lrc<[Symbol]>>,
160 pub trait ResolverAstLowering {
161 fn def_key(&mut self, id: DefId) -> DefKey;
163 fn def_span(&self, id: LocalDefId) -> Span;
165 fn item_generics_num_lifetimes(&self, def: DefId) -> usize;
167 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>>;
169 /// Obtains resolution for a `NodeId` with a single resolution.
170 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
172 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
173 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
175 /// Obtains resolution for a label with the given `NodeId`.
176 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
178 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
179 /// This should only return `None` during testing.
180 fn definitions(&mut self) -> &mut Definitions;
182 fn lint_buffer(&mut self) -> &mut LintBuffer;
184 fn next_node_id(&mut self) -> NodeId;
186 fn take_trait_map(&mut self, node: NodeId) -> Option<Vec<hir::TraitCandidate>>;
188 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
190 fn local_def_id(&self, node: NodeId) -> LocalDefId;
192 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
197 node_id: ast::NodeId,
204 struct LoweringHasher<'a> {
205 source_map: CachingSourceMapView<'a>,
206 resolver: &'a dyn ResolverAstLowering,
209 impl<'a> rustc_span::HashStableContext for LoweringHasher<'a> {
211 fn hash_spans(&self) -> bool {
216 fn def_span(&self, id: LocalDefId) -> Span {
217 self.resolver.def_span(id)
221 fn def_path_hash(&self, def_id: DefId) -> DefPathHash {
222 self.resolver.def_path_hash(def_id)
226 fn span_data_to_lines_and_cols(
228 span: &rustc_span::SpanData,
229 ) -> Option<(Lrc<rustc_span::SourceFile>, usize, rustc_span::BytePos, usize, rustc_span::BytePos)>
231 self.source_map.span_data_to_lines_and_cols(span)
235 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
236 /// and if so, what meaning it has.
238 enum ImplTraitContext<'b, 'a> {
239 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
240 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
241 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
243 /// Newly generated parameters should be inserted into the given `Vec`.
244 Universal(&'b mut Vec<hir::GenericParam<'a>>, LocalDefId),
246 /// Treat `impl Trait` as shorthand for a new opaque type.
247 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
248 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
250 ReturnPositionOpaqueTy {
251 /// `DefId` for the parent function, used to look up necessary
252 /// information later.
254 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
255 origin: hir::OpaqueTyOrigin,
257 /// Impl trait in type aliases.
258 TypeAliasesOpaqueTy {
259 /// Set of lifetimes that this opaque type can capture, if it uses
260 /// them. This includes lifetimes bound since we entered this context.
264 /// type A<'b> = impl for<'a> Trait<'a, Out = impl Sized + 'a>;
267 /// Here the inner opaque type captures `'a` because it uses it. It doesn't
268 /// need to capture `'b` because it already inherits the lifetime
269 /// parameter from `A`.
270 // FIXME(impl_trait): but `required_region_bounds` will ICE later
272 capturable_lifetimes: &'b mut FxHashSet<hir::LifetimeName>,
274 /// `impl Trait` is not accepted in this position.
275 Disallowed(ImplTraitPosition),
278 /// Position in which `impl Trait` is disallowed.
279 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
280 enum ImplTraitPosition {
281 /// Disallowed in `let` / `const` / `static` bindings.
284 /// All other positions.
288 impl<'a> ImplTraitContext<'_, 'a> {
290 fn disallowed() -> Self {
291 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
294 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
295 use self::ImplTraitContext::*;
297 Universal(params, parent) => Universal(params, *parent),
298 ReturnPositionOpaqueTy { fn_def_id, origin } => {
299 ReturnPositionOpaqueTy { fn_def_id: *fn_def_id, origin: *origin }
301 TypeAliasesOpaqueTy { capturable_lifetimes } => {
302 TypeAliasesOpaqueTy { capturable_lifetimes }
304 Disallowed(pos) => Disallowed(*pos),
309 pub fn lower_crate<'a, 'hir>(
312 resolver: &'a mut dyn ResolverAstLowering,
313 nt_to_tokenstream: NtToTokenstream,
314 arena: &'hir Arena<'hir>,
315 ) -> &'hir hir::Crate<'hir> {
316 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
318 let owners = IndexVec::from_fn_n(|_| None, resolver.definitions().def_index_count());
325 bodies: BTreeMap::new(),
326 attrs: BTreeMap::default(),
329 is_in_loop_condition: false,
330 is_in_trait_impl: false,
331 is_in_dyn_type: false,
332 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
333 current_hir_id_owner: CRATE_DEF_ID,
334 item_local_id_counter: hir::ItemLocalId::new(0),
335 node_id_to_hir_id: IndexVec::new(),
336 local_node_ids: Vec::new(),
337 generator_kind: None,
340 lifetimes_to_define: Vec::new(),
341 is_collecting_in_band_lifetimes: false,
342 in_scope_lifetimes: Vec::new(),
343 allow_try_trait: Some([sym::try_trait_v2][..].into()),
344 allow_gen_future: Some([sym::gen_future][..].into()),
349 #[derive(Copy, Clone, PartialEq)]
351 /// Any path in a type context.
353 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
355 /// The `module::Type` in `module::Type::method` in an expression.
359 enum ParenthesizedGenericArgs {
364 /// What to do when we encounter an **anonymous** lifetime
365 /// reference. Anonymous lifetime references come in two flavors. You
366 /// have implicit, or fully elided, references to lifetimes, like the
367 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
368 /// or `Ref<'_, T>`. These often behave the same, but not always:
370 /// - certain usages of implicit references are deprecated, like
371 /// `Ref<T>`, and we sometimes just give hard errors in those cases
373 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
374 /// the same as `Box<dyn Foo + '_>`.
376 /// We describe the effects of the various modes in terms of three cases:
378 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
379 /// of a `&` (e.g., the missing lifetime in something like `&T`)
380 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
381 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
382 /// elided bounds follow special rules. Note that this only covers
383 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
384 /// '_>` is a case of "modern" elision.
385 /// - **Deprecated** -- this covers cases like `Ref<T>`, where the lifetime
386 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
387 /// non-deprecated equivalent.
389 /// Currently, the handling of lifetime elision is somewhat spread out
390 /// between HIR lowering and -- as described below -- the
391 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
392 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
393 /// everything into HIR lowering.
394 #[derive(Copy, Clone, Debug)]
395 enum AnonymousLifetimeMode {
396 /// For **Modern** cases, create a new anonymous region parameter
397 /// and reference that.
399 /// For **Dyn Bound** cases, pass responsibility to
400 /// `resolve_lifetime` code.
402 /// For **Deprecated** cases, report an error.
405 /// Give a hard error when either `&` or `'_` is written. Used to
406 /// rule out things like `where T: Foo<'_>`. Does not imply an
407 /// error on default object bounds (e.g., `Box<dyn Foo>`).
410 /// Pass responsibility to `resolve_lifetime` code for all cases.
414 impl<'a, 'hir> LoweringContext<'a, 'hir> {
415 fn lower_crate(mut self, c: &Crate) -> &'hir hir::Crate<'hir> {
416 debug_assert_eq!(self.resolver.local_def_id(CRATE_NODE_ID), CRATE_DEF_ID);
418 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
420 self.with_hir_id_owner(CRATE_NODE_ID, |lctx| {
421 let module = lctx.lower_mod(&c.items, c.span);
422 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
423 hir::OwnerNode::Crate(lctx.arena.alloc(module))
426 let mut def_id_to_hir_id = IndexVec::default();
428 for (node_id, hir_id) in self.node_id_to_hir_id.into_iter_enumerated() {
429 if let Some(def_id) = self.resolver.opt_local_def_id(node_id) {
430 if def_id_to_hir_id.len() <= def_id.index() {
431 def_id_to_hir_id.resize(def_id.index() + 1, None);
433 def_id_to_hir_id[def_id] = hir_id;
437 self.resolver.definitions().init_def_id_to_hir_id_mapping(def_id_to_hir_id);
439 let krate = hir::Crate { owners: self.owners };
440 self.arena.alloc(krate)
443 fn create_stable_hashing_context(&self) -> LoweringHasher<'_> {
445 source_map: CachingSourceMapView::new(self.sess.source_map()),
446 resolver: self.resolver,
450 fn with_hir_id_owner(
453 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
455 let def_id = self.resolver.local_def_id(owner);
457 let current_attrs = std::mem::take(&mut self.attrs);
458 let current_bodies = std::mem::take(&mut self.bodies);
459 let current_node_ids = std::mem::take(&mut self.local_node_ids);
460 let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
461 let current_local_counter =
462 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
464 // Always allocate the first `HirId` for the owner itself.
465 let _old = self.node_id_to_hir_id.insert(owner, hir::HirId::make_owner(def_id));
466 debug_assert_eq!(_old, None);
467 self.local_node_ids.push(owner);
470 let info = self.make_owner_info(item);
472 self.attrs = current_attrs;
473 self.bodies = current_bodies;
474 self.local_node_ids = current_node_ids;
475 self.current_hir_id_owner = current_owner;
476 self.item_local_id_counter = current_local_counter;
478 let _old = self.owners.insert(def_id, info);
479 debug_assert!(_old.is_none());
484 fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> hir::OwnerInfo<'hir> {
485 let attrs = std::mem::take(&mut self.attrs);
486 let bodies = std::mem::take(&mut self.bodies);
487 let local_node_ids = std::mem::take(&mut self.local_node_ids);
488 let trait_map = local_node_ids
490 .filter_map(|node_id| {
491 let hir_id = self.node_id_to_hir_id[node_id]?;
492 let traits = self.resolver.take_trait_map(node_id)?;
493 Some((hir_id.local_id, traits.into_boxed_slice()))
497 #[cfg(debug_assertions)]
498 for (&id, attrs) in attrs.iter() {
499 // Verify that we do not store empty slices in the map.
500 if attrs.is_empty() {
501 panic!("Stored empty attributes for {:?}", id);
505 hir::OwnerInfo { node, attrs, bodies, trait_map }
508 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
509 /// the `LoweringContext`'s `NodeId => HirId` map.
510 /// Take care not to call this method if the resulting `HirId` is then not
511 /// actually used in the HIR, as that would trigger an assertion in the
512 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
513 /// properly. Calling the method twice with the same `NodeId` is fine though.
514 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
515 assert_ne!(ast_node_id, DUMMY_NODE_ID);
517 *self.node_id_to_hir_id.get_or_insert_with(ast_node_id, || {
518 // Generate a new `HirId`.
519 let owner = self.current_hir_id_owner;
520 let local_id = self.item_local_id_counter;
521 self.item_local_id_counter.increment_by(1);
522 self.local_node_ids.push(ast_node_id);
523 hir::HirId { owner, local_id }
527 fn next_id(&mut self) -> hir::HirId {
528 let node_id = self.resolver.next_node_id();
529 self.lower_node_id(node_id)
532 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
534 self.node_id_to_hir_id.get(id).copied().flatten().unwrap_or_else(|| {
535 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
540 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
541 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
542 if pr.unresolved_segments() != 0 {
543 panic!("path not fully resolved: {:?}", pr);
549 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
550 self.resolver.get_import_res(id).present_items()
553 fn diagnostic(&self) -> &rustc_errors::Handler {
554 self.sess.diagnostic()
557 /// Reuses the span but adds information like the kind of the desugaring and features that are
558 /// allowed inside this span.
559 fn mark_span_with_reason(
561 reason: DesugaringKind,
563 allow_internal_unstable: Option<Lrc<[Symbol]>>,
565 span.mark_with_reason(
566 allow_internal_unstable,
569 self.create_stable_hashing_context(),
573 fn with_anonymous_lifetime_mode<R>(
575 anonymous_lifetime_mode: AnonymousLifetimeMode,
576 op: impl FnOnce(&mut Self) -> R,
579 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
580 anonymous_lifetime_mode,
582 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
583 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
584 let result = op(self);
585 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
587 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
588 old_anonymous_lifetime_mode
593 /// Intercept all spans entering HIR.
594 /// Mark a span as relative to the current owning item.
595 fn lower_span(&self, span: Span) -> Span {
596 if self.sess.opts.debugging_opts.incremental_relative_spans {
597 span.with_parent(Some(self.current_hir_id_owner))
599 // Do not make spans relative when not using incremental compilation.
604 fn lower_ident(&self, ident: Ident) -> Ident {
605 Ident::new(ident.name, self.lower_span(ident.span))
608 /// Creates a new `hir::GenericParam` for every new lifetime and
609 /// type parameter encountered while evaluating `f`. Definitions
610 /// are created with the parent provided. If no `parent_id` is
611 /// provided, no definitions will be returned.
613 /// Presuming that in-band lifetimes are enabled, then
614 /// `self.anonymous_lifetime_mode` will be updated to match the
615 /// parameter while `f` is running (and restored afterwards).
616 fn collect_in_band_defs<T>(
618 parent_def_id: LocalDefId,
619 anonymous_lifetime_mode: AnonymousLifetimeMode,
620 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
621 ) -> (Vec<hir::GenericParam<'hir>>, T) {
622 assert!(!self.is_collecting_in_band_lifetimes);
623 assert!(self.lifetimes_to_define.is_empty());
624 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
626 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
627 self.is_collecting_in_band_lifetimes = true;
629 let (in_band_ty_params, res) = f(self);
631 self.is_collecting_in_band_lifetimes = false;
632 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
634 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
636 let params = lifetimes_to_define
638 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_def_id))
639 .chain(in_band_ty_params.into_iter())
645 /// Converts a lifetime into a new generic parameter.
646 fn lifetime_to_generic_param(
650 parent_def_id: LocalDefId,
651 ) -> hir::GenericParam<'hir> {
652 let node_id = self.resolver.next_node_id();
654 // Get the name we'll use to make the def-path. Note
655 // that collisions are ok here and this shouldn't
656 // really show up for end-user.
657 let (str_name, kind) = match hir_name {
658 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
659 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
660 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
663 // Add a definition for the in-band lifetime def.
664 self.resolver.create_def(
667 DefPathData::LifetimeNs(str_name),
669 span.with_parent(None),
673 hir_id: self.lower_node_id(node_id),
676 span: self.lower_span(span),
677 pure_wrt_drop: false,
678 kind: hir::GenericParamKind::Lifetime { kind },
682 /// When there is a reference to some lifetime `'a`, and in-band
683 /// lifetimes are enabled, then we want to push that lifetime into
684 /// the vector of names to define later. In that case, it will get
685 /// added to the appropriate generics.
686 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
687 if !self.is_collecting_in_band_lifetimes {
691 if !self.sess.features_untracked().in_band_lifetimes {
695 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
699 let hir_name = ParamName::Plain(ident);
701 if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
702 lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
707 self.lifetimes_to_define.push((ident.span, hir_name));
710 /// When we have either an elided or `'_` lifetime in an impl
711 /// header, we convert it to an in-band lifetime.
712 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
713 assert!(self.is_collecting_in_band_lifetimes);
714 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
715 let hir_name = ParamName::Fresh(index);
716 self.lifetimes_to_define.push((span, hir_name));
720 // Evaluates `f` with the lifetimes in `params` in-scope.
721 // This is used to track which lifetimes have already been defined, and
722 // which are new in-band lifetimes that need to have a definition created
724 fn with_in_scope_lifetime_defs<T>(
726 params: &[GenericParam],
727 f: impl FnOnce(&mut Self) -> T,
729 let old_len = self.in_scope_lifetimes.len();
730 let lt_def_names = params.iter().filter_map(|param| match param.kind {
731 GenericParamKind::Lifetime { .. } => {
732 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
736 self.in_scope_lifetimes.extend(lt_def_names);
740 self.in_scope_lifetimes.truncate(old_len);
744 /// Appends in-band lifetime defs and argument-position `impl
745 /// Trait` defs to the existing set of generics.
747 /// Presuming that in-band lifetimes are enabled, then
748 /// `self.anonymous_lifetime_mode` will be updated to match the
749 /// parameter while `f` is running (and restored afterwards).
750 fn add_in_band_defs<T>(
753 parent_def_id: LocalDefId,
754 anonymous_lifetime_mode: AnonymousLifetimeMode,
755 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
756 ) -> (hir::Generics<'hir>, T) {
757 let (in_band_defs, (mut lowered_generics, res)) =
758 self.with_in_scope_lifetime_defs(&generics.params, |this| {
759 this.collect_in_band_defs(parent_def_id, anonymous_lifetime_mode, |this| {
760 let mut params = Vec::new();
761 // Note: it is necessary to lower generics *before* calling `f`.
762 // When lowering `async fn`, there's a final step when lowering
763 // the return type that assumes that all in-scope lifetimes have
764 // already been added to either `in_scope_lifetimes` or
765 // `lifetimes_to_define`. If we swapped the order of these two,
766 // in-band-lifetimes introduced by generics or where-clauses
767 // wouldn't have been added yet.
768 let generics = this.lower_generics_mut(
770 ImplTraitContext::Universal(&mut params, this.current_hir_id_owner),
772 let res = f(this, &mut params);
773 (params, (generics, res))
777 lowered_generics.params.extend(in_band_defs);
779 let lowered_generics = lowered_generics.into_generics(self.arena);
780 (lowered_generics, res)
783 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
784 let was_in_dyn_type = self.is_in_dyn_type;
785 self.is_in_dyn_type = in_scope;
787 let result = f(self);
789 self.is_in_dyn_type = was_in_dyn_type;
794 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
795 let was_in_loop_condition = self.is_in_loop_condition;
796 self.is_in_loop_condition = false;
798 let catch_scope = self.catch_scope.take();
799 let loop_scope = self.loop_scope.take();
801 self.catch_scope = catch_scope;
802 self.loop_scope = loop_scope;
804 self.is_in_loop_condition = was_in_loop_condition;
809 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
810 if attrs.is_empty() {
813 debug_assert_eq!(id.owner, self.current_hir_id_owner);
814 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
815 debug_assert!(!ret.is_empty());
816 self.attrs.insert(id.local_id, ret);
821 fn lower_attr(&self, attr: &Attribute) -> Attribute {
822 // Note that we explicitly do not walk the path. Since we don't really
823 // lower attributes (we use the AST version) there is nowhere to keep
824 // the `HirId`s. We don't actually need HIR version of attributes anyway.
825 // Tokens are also not needed after macro expansion and parsing.
826 let kind = match attr.kind {
827 AttrKind::Normal(ref item, _) => AttrKind::Normal(
829 path: item.path.clone(),
830 args: self.lower_mac_args(&item.args),
835 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
838 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
841 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
842 debug_assert_eq!(id.owner, self.current_hir_id_owner);
843 debug_assert_eq!(target_id.owner, self.current_hir_id_owner);
844 if let Some(&a) = self.attrs.get(&target_id.local_id) {
845 debug_assert!(!a.is_empty());
846 self.attrs.insert(id.local_id, a);
850 fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
852 MacArgs::Empty => MacArgs::Empty,
853 MacArgs::Delimited(dspan, delim, ref tokens) => {
854 // This is either a non-key-value attribute, or a `macro_rules!` body.
855 // We either not have any nonterminals present (in the case of an attribute),
856 // or have tokens available for all nonterminals in the case of a nested
857 // `macro_rules`: e.g:
860 // macro_rules! outer {
862 // macro_rules! inner {
869 // In both cases, we don't want to synthesize any tokens
873 self.lower_token_stream(tokens.clone(), CanSynthesizeMissingTokens::No),
876 // This is an inert key-value attribute - it will never be visible to macros
877 // after it gets lowered to HIR. Therefore, we can synthesize tokens with fake
878 // spans to handle nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
879 MacArgs::Eq(eq_span, ref token) => {
880 // In valid code the value is always representable as a single literal token.
881 fn unwrap_single_token(sess: &Session, tokens: TokenStream, span: Span) -> Token {
882 if tokens.len() != 1 {
884 .delay_span_bug(span, "multiple tokens in key-value attribute's value");
886 match tokens.into_trees().next() {
887 Some(TokenTree::Token(token)) => token,
888 Some(TokenTree::Delimited(_, delim, tokens)) => {
889 if delim != token::NoDelim {
890 sess.diagnostic().delay_span_bug(
892 "unexpected delimiter in key-value attribute's value",
895 unwrap_single_token(sess, tokens, span)
897 None => Token::dummy(),
901 let tokens = FlattenNonterminals {
902 parse_sess: &self.sess.parse_sess,
903 synthesize_tokens: CanSynthesizeMissingTokens::Yes,
904 nt_to_tokenstream: self.nt_to_tokenstream,
906 .process_token(token.clone());
907 MacArgs::Eq(eq_span, unwrap_single_token(self.sess, tokens, token.span))
912 fn lower_token_stream(
915 synthesize_tokens: CanSynthesizeMissingTokens,
917 FlattenNonterminals {
918 parse_sess: &self.sess.parse_sess,
920 nt_to_tokenstream: self.nt_to_tokenstream,
922 .process_token_stream(tokens)
925 /// Given an associated type constraint like one of these:
928 /// T: Iterator<Item: Debug>
930 /// T: Iterator<Item = Debug>
934 /// returns a `hir::TypeBinding` representing `Item`.
935 fn lower_assoc_ty_constraint(
937 constraint: &AssocTyConstraint,
938 mut itctx: ImplTraitContext<'_, 'hir>,
939 ) -> hir::TypeBinding<'hir> {
940 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
942 // lower generic arguments of identifier in constraint
943 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
944 let gen_args_ctor = match gen_args {
945 GenericArgs::AngleBracketed(ref data) => {
946 self.lower_angle_bracketed_parameter_data(
953 GenericArgs::Parenthesized(ref data) => {
954 let mut err = self.sess.struct_span_err(
956 "parenthesized generic arguments cannot be used in associated type constraints"
958 // FIXME: try to write a suggestion here
960 self.lower_angle_bracketed_parameter_data(
961 &data.as_angle_bracketed_args(),
968 gen_args_ctor.into_generic_args(self)
970 self.arena.alloc(hir::GenericArgs::none())
973 let kind = match constraint.kind {
974 AssocTyConstraintKind::Equality { ref ty } => {
975 hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
977 AssocTyConstraintKind::Bound { ref bounds } => {
978 let mut capturable_lifetimes;
979 let mut parent_def_id = self.current_hir_id_owner;
980 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
981 let (desugar_to_impl_trait, itctx) = match itctx {
982 // We are in the return position:
984 // fn foo() -> impl Iterator<Item: Debug>
988 // fn foo() -> impl Iterator<Item = impl Debug>
989 ImplTraitContext::ReturnPositionOpaqueTy { .. }
990 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
992 // We are in the argument position, but within a dyn type:
994 // fn foo(x: dyn Iterator<Item: Debug>)
998 // fn foo(x: dyn Iterator<Item = impl Debug>)
999 ImplTraitContext::Universal(_, parent) if self.is_in_dyn_type => {
1000 parent_def_id = parent;
1004 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
1005 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
1006 // "impl trait context" to permit `impl Debug` in this position (it desugars
1007 // then to an opaque type).
1009 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
1010 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
1011 capturable_lifetimes = FxHashSet::default();
1014 ImplTraitContext::TypeAliasesOpaqueTy {
1015 capturable_lifetimes: &mut capturable_lifetimes,
1020 // We are in the parameter position, but not within a dyn type:
1022 // fn foo(x: impl Iterator<Item: Debug>)
1024 // so we leave it as is and this gets expanded in astconv to a bound like
1025 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1027 _ => (false, itctx),
1030 if desugar_to_impl_trait {
1031 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1032 // constructing the HIR for `impl bounds...` and then lowering that.
1034 let impl_trait_node_id = self.resolver.next_node_id();
1035 self.resolver.create_def(
1038 DefPathData::ImplTrait,
1043 self.with_dyn_type_scope(false, |this| {
1044 let node_id = this.resolver.next_node_id();
1045 let ty = this.lower_ty(
1048 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1049 span: this.lower_span(constraint.span),
1055 hir::TypeBindingKind::Equality { ty }
1058 // Desugar `AssocTy: Bounds` into a type binding where the
1059 // later desugars into a trait predicate.
1060 let bounds = self.lower_param_bounds(bounds, itctx);
1062 hir::TypeBindingKind::Constraint { bounds }
1068 hir_id: self.lower_node_id(constraint.id),
1069 ident: self.lower_ident(constraint.ident),
1072 span: self.lower_span(constraint.span),
1076 fn lower_generic_arg(
1078 arg: &ast::GenericArg,
1079 itctx: ImplTraitContext<'_, 'hir>,
1080 ) -> hir::GenericArg<'hir> {
1082 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1083 ast::GenericArg::Type(ty) => {
1085 TyKind::Infer if self.sess.features_untracked().generic_arg_infer => {
1086 return GenericArg::Infer(hir::InferArg {
1087 hir_id: self.lower_node_id(ty.id),
1088 span: self.lower_span(ty.span),
1089 kind: InferKind::Type,
1092 // We parse const arguments as path types as we cannot distinguish them during
1093 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1094 // type and value namespaces. If we resolved the path in the value namespace, we
1095 // transform it into a generic const argument.
1096 TyKind::Path(ref qself, ref path) => {
1097 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1098 let res = partial_res.base_res();
1099 if !res.matches_ns(Namespace::TypeNS) {
1101 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1105 // Construct an AnonConst where the expr is the "ty"'s path.
1107 let parent_def_id = self.current_hir_id_owner;
1108 let node_id = self.resolver.next_node_id();
1110 // Add a definition for the in-band const def.
1111 self.resolver.create_def(
1114 DefPathData::AnonConst,
1119 let span = self.lower_span(ty.span);
1120 let path_expr = Expr {
1122 kind: ExprKind::Path(qself.clone(), path.clone()),
1124 attrs: AttrVec::new(),
1128 let ct = self.with_new_scopes(|this| hir::AnonConst {
1129 hir_id: this.lower_node_id(node_id),
1130 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1132 return GenericArg::Const(ConstArg { value: ct, span });
1138 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1140 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1141 value: self.lower_anon_const(&ct),
1142 span: self.lower_span(ct.value.span),
1147 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1148 self.arena.alloc(self.lower_ty_direct(t, itctx))
1154 qself: &Option<QSelf>,
1156 param_mode: ParamMode,
1157 itctx: ImplTraitContext<'_, 'hir>,
1158 ) -> hir::Ty<'hir> {
1159 let id = self.lower_node_id(t.id);
1160 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1161 let ty = self.ty_path(id, t.span, qpath);
1162 if let hir::TyKind::TraitObject(..) = ty.kind {
1163 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1168 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1169 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1172 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1173 self.ty(span, hir::TyKind::Tup(tys))
1176 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1177 let kind = match t.kind {
1178 TyKind::Infer => hir::TyKind::Infer,
1179 TyKind::Err => hir::TyKind::Err,
1180 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1181 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1182 TyKind::Rptr(ref region, ref mt) => {
1183 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1184 let lifetime = match *region {
1185 Some(ref lt) => self.lower_lifetime(lt),
1186 None => self.elided_ref_lifetime(span),
1188 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1190 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1191 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1192 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1193 generic_params: this.lower_generic_params(
1195 ImplTraitContext::disallowed(),
1197 unsafety: this.lower_unsafety(f.unsafety),
1198 abi: this.lower_extern(f.ext),
1199 decl: this.lower_fn_decl(&f.decl, None, false, None),
1200 param_names: this.lower_fn_params_to_names(&f.decl),
1204 TyKind::Never => hir::TyKind::Never,
1205 TyKind::Tup(ref tys) => {
1206 hir::TyKind::Tup(self.arena.alloc_from_iter(
1207 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1210 TyKind::Paren(ref ty) => {
1211 return self.lower_ty_direct(ty, itctx);
1213 TyKind::Path(ref qself, ref path) => {
1214 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1216 TyKind::ImplicitSelf => {
1217 let res = self.expect_full_res(t.id);
1218 let res = self.lower_res(res);
1219 hir::TyKind::Path(hir::QPath::Resolved(
1221 self.arena.alloc(hir::Path {
1223 segments: arena_vec![self; hir::PathSegment::from_ident(
1224 Ident::with_dummy_span(kw::SelfUpper)
1226 span: self.lower_span(t.span),
1230 TyKind::Array(ref ty, ref length) => {
1231 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1233 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1234 TyKind::TraitObject(ref bounds, kind) => {
1235 let mut lifetime_bound = None;
1236 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1238 this.arena.alloc_from_iter(bounds.iter().filter_map(
1239 |bound| match *bound {
1240 GenericBound::Trait(
1242 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1243 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1244 // `~const ?Bound` will cause an error during AST validation
1245 // anyways, so treat it like `?Bound` as compilation proceeds.
1246 GenericBound::Trait(
1248 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1250 GenericBound::Outlives(ref lifetime) => {
1251 if lifetime_bound.is_none() {
1252 lifetime_bound = Some(this.lower_lifetime(lifetime));
1258 let lifetime_bound =
1259 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1260 (bounds, lifetime_bound)
1262 if kind != TraitObjectSyntax::Dyn {
1263 self.maybe_lint_bare_trait(t.span, t.id, false);
1265 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1267 TyKind::ImplTrait(def_node_id, ref bounds) => {
1270 ImplTraitContext::ReturnPositionOpaqueTy { fn_def_id, origin } => self
1271 .lower_opaque_impl_trait(
1277 |this| this.lower_param_bounds(bounds, itctx),
1279 ImplTraitContext::TypeAliasesOpaqueTy { ref capturable_lifetimes } => {
1280 // Reset capturable lifetimes, any nested impl trait
1281 // types will inherit lifetimes from this opaque type,
1282 // so don't need to capture them again.
1283 let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy {
1284 capturable_lifetimes: &mut FxHashSet::default(),
1286 self.lower_opaque_impl_trait(
1289 hir::OpaqueTyOrigin::TyAlias,
1291 Some(capturable_lifetimes),
1292 |this| this.lower_param_bounds(bounds, nested_itctx),
1295 ImplTraitContext::Universal(in_band_ty_params, parent_def_id) => {
1296 // Add a definition for the in-band `Param`.
1297 let def_id = self.resolver.local_def_id(def_node_id);
1299 let hir_bounds = self.lower_param_bounds(
1301 ImplTraitContext::Universal(in_band_ty_params, parent_def_id),
1303 // Set the name to `impl Bound1 + Bound2`.
1304 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1305 in_band_ty_params.push(hir::GenericParam {
1306 hir_id: self.lower_node_id(def_node_id),
1307 name: ParamName::Plain(self.lower_ident(ident)),
1308 pure_wrt_drop: false,
1310 span: self.lower_span(span),
1311 kind: hir::GenericParamKind::Type {
1313 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1317 hir::TyKind::Path(hir::QPath::Resolved(
1319 self.arena.alloc(hir::Path {
1320 span: self.lower_span(span),
1321 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1322 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
1326 ImplTraitContext::Disallowed(_) => {
1327 let mut err = struct_span_err!(
1331 "`impl Trait` not allowed outside of {}",
1332 "function and method return types",
1339 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1340 TyKind::CVarArgs => {
1341 self.sess.delay_span_bug(
1343 "`TyKind::CVarArgs` should have been handled elsewhere",
1349 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1352 fn lower_opaque_impl_trait(
1355 fn_def_id: Option<DefId>,
1356 origin: hir::OpaqueTyOrigin,
1357 opaque_ty_node_id: NodeId,
1358 capturable_lifetimes: Option<&FxHashSet<hir::LifetimeName>>,
1359 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1360 ) -> hir::TyKind<'hir> {
1362 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1363 fn_def_id, opaque_ty_node_id, span,
1366 // Make sure we know that some funky desugaring has been going on here.
1367 // This is a first: there is code in other places like for loop
1368 // desugaring that explicitly states that we don't want to track that.
1369 // Not tracking it makes lints in rustc and clippy very fragile, as
1370 // frequently opened issues show.
1371 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1373 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1375 let mut collected_lifetimes = Vec::new();
1376 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1377 let hir_bounds = lower_bounds(lctx);
1379 collected_lifetimes = lifetimes_from_impl_trait_bounds(
1382 capturable_lifetimes,
1386 lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(|&(name, span)| {
1387 let def_node_id = lctx.resolver.next_node_id();
1388 let hir_id = lctx.lower_node_id(def_node_id);
1389 lctx.resolver.create_def(
1392 DefPathData::LifetimeNs(name.ident().name),
1394 span.with_parent(None),
1397 let (name, kind) = match name {
1398 hir::LifetimeName::Underscore => (
1399 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1400 hir::LifetimeParamKind::Elided,
1402 hir::LifetimeName::Param(param_name) => {
1403 (param_name, hir::LifetimeParamKind::Explicit)
1405 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1412 pure_wrt_drop: false,
1414 kind: hir::GenericParamKind::Lifetime { kind },
1418 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1420 let opaque_ty_item = hir::OpaqueTy {
1421 generics: hir::Generics {
1422 params: lifetime_defs,
1423 where_clause: hir::WhereClause { predicates: &[], span: lctx.lower_span(span) },
1424 span: lctx.lower_span(span),
1427 impl_trait_fn: fn_def_id,
1431 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1432 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1436 self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(name, span)| {
1437 hir::GenericArg::Lifetime(hir::Lifetime { hir_id: self.next_id(), span, name })
1440 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1442 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1443 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1446 /// Registers a new opaque type with the proper `NodeId`s and
1447 /// returns the lowered node-ID for the opaque type.
1448 fn generate_opaque_type(
1450 opaque_ty_id: LocalDefId,
1451 opaque_ty_item: hir::OpaqueTy<'hir>,
1453 opaque_ty_span: Span,
1454 ) -> hir::OwnerNode<'hir> {
1455 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1456 // Generate an `type Foo = impl Trait;` declaration.
1457 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1458 let opaque_ty_item = hir::Item {
1459 def_id: opaque_ty_id,
1460 ident: Ident::invalid(),
1461 kind: opaque_ty_item_kind,
1462 vis: respan(self.lower_span(span.shrink_to_lo()), hir::VisibilityKind::Inherited),
1463 span: self.lower_span(opaque_ty_span),
1465 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1468 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1469 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1470 // as they are not explicit in HIR/Ty function signatures.
1471 // (instead, the `c_variadic` flag is set to `true`)
1472 let mut inputs = &decl.inputs[..];
1473 if decl.c_variadic() {
1474 inputs = &inputs[..inputs.len() - 1];
1476 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1477 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1478 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1482 // Lowers a function declaration.
1484 // `decl`: the unlowered (AST) function declaration.
1485 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1486 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1487 // `make_ret_async` is also `Some`.
1488 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1489 // This guards against trait declarations and implementations where `impl Trait` is
1491 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1492 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1493 // return type `impl Trait` item.
1497 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
1498 impl_trait_return_allow: bool,
1499 make_ret_async: Option<NodeId>,
1500 ) -> &'hir hir::FnDecl<'hir> {
1504 in_band_ty_params: {:?}, \
1505 impl_trait_return_allow: {}, \
1506 make_ret_async: {:?})",
1507 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
1509 let lt_mode = if make_ret_async.is_some() {
1510 // In `async fn`, argument-position elided lifetimes
1511 // must be transformed into fresh generic parameters so that
1512 // they can be applied to the opaque `impl Trait` return type.
1513 AnonymousLifetimeMode::CreateParameter
1515 self.anonymous_lifetime_mode
1518 let c_variadic = decl.c_variadic();
1520 // Remember how many lifetimes were already around so that we can
1521 // only look at the lifetime parameters introduced by the arguments.
1522 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1523 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1524 // as they are not explicit in HIR/Ty function signatures.
1525 // (instead, the `c_variadic` flag is set to `true`)
1526 let mut inputs = &decl.inputs[..];
1528 inputs = &inputs[..inputs.len() - 1];
1530 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1531 if let Some((_, ibty)) = &mut in_band_ty_params {
1532 this.lower_ty_direct(
1534 ImplTraitContext::Universal(ibty, this.current_hir_id_owner),
1537 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
1542 let output = if let Some(ret_id) = make_ret_async {
1543 self.lower_async_fn_ret_ty(
1545 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1550 FnRetTy::Ty(ref ty) => {
1551 let context = match in_band_ty_params {
1552 Some((def_id, _)) if impl_trait_return_allow => {
1553 ImplTraitContext::ReturnPositionOpaqueTy {
1555 origin: hir::OpaqueTyOrigin::FnReturn,
1558 _ => ImplTraitContext::disallowed(),
1560 hir::FnRetTy::Return(self.lower_ty(ty, context))
1562 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1566 self.arena.alloc(hir::FnDecl {
1570 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1571 use BindingMode::{ByRef, ByValue};
1572 let is_mutable_pat = matches!(
1574 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1578 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1579 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1580 // Given we are only considering `ImplicitSelf` types, we needn't consider
1581 // the case where we have a mutable pattern to a reference as that would
1582 // no longer be an `ImplicitSelf`.
1583 TyKind::Rptr(_, ref mt)
1584 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1586 hir::ImplicitSelfKind::MutRef
1588 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1589 hir::ImplicitSelfKind::ImmRef
1591 _ => hir::ImplicitSelfKind::None,
1597 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1598 // combined with the following definition of `OpaqueTy`:
1600 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1602 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1603 // `output`: unlowered output type (`T` in `-> T`)
1604 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1605 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1606 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1607 fn lower_async_fn_ret_ty(
1611 opaque_ty_node_id: NodeId,
1612 ) -> hir::FnRetTy<'hir> {
1614 "lower_async_fn_ret_ty(\
1617 opaque_ty_node_id={:?})",
1618 output, fn_def_id, opaque_ty_node_id,
1621 let span = output.span();
1623 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1625 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1627 // When we create the opaque type for this async fn, it is going to have
1628 // to capture all the lifetimes involved in the signature (including in the
1629 // return type). This is done by introducing lifetime parameters for:
1631 // - all the explicitly declared lifetimes from the impl and function itself;
1632 // - all the elided lifetimes in the fn arguments;
1633 // - all the elided lifetimes in the return type.
1635 // So for example in this snippet:
1638 // impl<'a> Foo<'a> {
1639 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1640 // // ^ '0 ^ '1 ^ '2
1641 // // elided lifetimes used below
1646 // we would create an opaque type like:
1649 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1652 // and we would then desugar `bar` to the equivalent of:
1655 // impl<'a> Foo<'a> {
1656 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1660 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1661 // this is because the elided lifetimes from the return type
1662 // should be figured out using the ordinary elision rules, and
1663 // this desugaring achieves that.
1665 // The variable `input_lifetimes_count` tracks the number of
1666 // lifetime parameters to the opaque type *not counting* those
1667 // lifetimes elided in the return type. This includes those
1668 // that are explicitly declared (`in_scope_lifetimes`) and
1669 // those elided lifetimes we found in the arguments (current
1670 // content of `lifetimes_to_define`). Next, we will process
1671 // the return type, which will cause `lifetimes_to_define` to
1673 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
1675 let mut lifetime_params = Vec::new();
1676 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1677 // We have to be careful to get elision right here. The
1678 // idea is that we create a lifetime parameter for each
1679 // lifetime in the return type. So, given a return type
1680 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1681 // Future<Output = &'1 [ &'2 u32 ]>`.
1683 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1684 // hence the elision takes place at the fn site.
1685 let future_bound = this
1686 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
1687 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1690 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1692 // Calculate all the lifetimes that should be captured
1693 // by the opaque type. This should include all in-scope
1694 // lifetime parameters, including those defined in-band.
1696 // Note: this must be done after lowering the output type,
1697 // as the output type may introduce new in-band lifetimes.
1698 lifetime_params = this
1702 .map(|name| (name.ident().span, name))
1703 .chain(this.lifetimes_to_define.iter().cloned())
1706 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
1707 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
1708 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
1710 let generic_params =
1711 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
1712 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_id)
1715 let opaque_ty_item = hir::OpaqueTy {
1716 generics: hir::Generics {
1717 params: generic_params,
1718 where_clause: hir::WhereClause { predicates: &[], span: this.lower_span(span) },
1719 span: this.lower_span(span),
1721 bounds: arena_vec![this; future_bound],
1722 impl_trait_fn: Some(fn_def_id),
1723 origin: hir::OpaqueTyOrigin::AsyncFn,
1726 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1727 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1730 // As documented above on the variable
1731 // `input_lifetimes_count`, we need to create the lifetime
1732 // arguments to our opaque type. Continuing with our example,
1733 // we're creating the type arguments for the return type:
1736 // Bar<'a, 'b, '0, '1, '_>
1739 // For the "input" lifetime parameters, we wish to create
1740 // references to the parameters themselves, including the
1741 // "implicit" ones created from parameter types (`'a`, `'b`,
1744 // For the "output" lifetime parameters, we just want to
1746 let mut generic_args = Vec::with_capacity(lifetime_params.len());
1747 generic_args.extend(lifetime_params[..input_lifetimes_count].iter().map(
1748 |&(span, hir_name)| {
1749 // Input lifetime like `'a` or `'1`:
1750 GenericArg::Lifetime(hir::Lifetime {
1751 hir_id: self.next_id(),
1752 span: self.lower_span(span),
1753 name: hir::LifetimeName::Param(hir_name),
1757 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
1758 // Output lifetime like `'_`.
1759 GenericArg::Lifetime(hir::Lifetime {
1760 hir_id: self.next_id(),
1761 span: self.lower_span(span),
1762 name: hir::LifetimeName::Implicit,
1764 let generic_args = self.arena.alloc_from_iter(generic_args);
1766 // Create the `Foo<...>` reference itself. Note that the `type
1767 // Foo = impl Trait` is, internally, created as a child of the
1768 // async fn, so the *type parameters* are inherited. It's
1769 // only the lifetime parameters that we must supply.
1771 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1772 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1773 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1776 /// Transforms `-> T` into `Future<Output = T>`.
1777 fn lower_async_fn_output_type_to_future_bound(
1782 ) -> hir::GenericBound<'hir> {
1783 // Compute the `T` in `Future<Output = T>` from the return type.
1784 let output_ty = match output {
1785 FnRetTy::Ty(ty) => {
1786 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1787 // `impl Future` opaque type that `async fn` implicitly
1789 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1791 origin: hir::OpaqueTyOrigin::FnReturn,
1793 self.lower_ty(ty, context)
1795 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1799 let future_args = self.arena.alloc(hir::GenericArgs {
1801 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1802 parenthesized: false,
1806 hir::GenericBound::LangItemTrait(
1807 // ::std::future::Future<future_params>
1808 hir::LangItem::Future,
1809 self.lower_span(span),
1815 fn lower_param_bound(
1818 itctx: ImplTraitContext<'_, 'hir>,
1819 ) -> hir::GenericBound<'hir> {
1821 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1822 self.lower_poly_trait_ref(p, itctx),
1823 self.lower_trait_bound_modifier(*modifier),
1825 GenericBound::Outlives(lifetime) => {
1826 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1831 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1832 let span = self.lower_span(l.ident.span);
1834 ident if ident.name == kw::StaticLifetime => {
1835 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
1837 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
1838 AnonymousLifetimeMode::CreateParameter => {
1839 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1840 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
1843 AnonymousLifetimeMode::PassThrough => {
1844 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1847 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
1850 self.maybe_collect_in_band_lifetime(ident);
1851 let param_name = ParamName::Plain(self.lower_ident(ident));
1852 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
1857 fn new_named_lifetime(
1861 name: hir::LifetimeName,
1862 ) -> hir::Lifetime {
1863 hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1866 fn lower_generic_params_mut<'s>(
1868 params: &'s [GenericParam],
1869 mut itctx: ImplTraitContext<'s, 'hir>,
1870 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1871 params.iter().map(move |param| self.lower_generic_param(param, itctx.reborrow()))
1874 fn lower_generic_params(
1876 params: &[GenericParam],
1877 itctx: ImplTraitContext<'_, 'hir>,
1878 ) -> &'hir [hir::GenericParam<'hir>] {
1879 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, itctx))
1882 fn lower_generic_param(
1884 param: &GenericParam,
1885 mut itctx: ImplTraitContext<'_, 'hir>,
1886 ) -> hir::GenericParam<'hir> {
1887 let bounds: Vec<_> = self
1888 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1889 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
1892 let (name, kind) = match param.kind {
1893 GenericParamKind::Lifetime => {
1894 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1895 self.is_collecting_in_band_lifetimes = false;
1898 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1899 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
1901 let param_name = match lt.name {
1902 hir::LifetimeName::Param(param_name) => param_name,
1903 hir::LifetimeName::Implicit
1904 | hir::LifetimeName::Underscore
1905 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
1906 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
1907 self.sess.diagnostic().span_bug(
1909 "object-lifetime-default should not occur here",
1912 hir::LifetimeName::Error => ParamName::Error,
1916 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
1918 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1922 GenericParamKind::Type { ref default, .. } => {
1923 let kind = hir::GenericParamKind::Type {
1924 default: default.as_ref().map(|x| {
1925 self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Other))
1930 .filter(|attr| attr.has_name(sym::rustc_synthetic))
1931 .map(|_| hir::SyntheticTyParamKind::FromAttr)
1935 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
1937 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1939 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1940 this.lower_ty(&ty, ImplTraitContext::disallowed())
1942 let default = default.as_ref().map(|def| self.lower_anon_const(def));
1944 hir::ParamName::Plain(self.lower_ident(param.ident)),
1945 hir::GenericParamKind::Const { ty, default },
1949 let name = match name {
1950 hir::ParamName::Plain(ident) => hir::ParamName::Plain(self.lower_ident(ident)),
1954 let hir_id = self.lower_node_id(param.id);
1955 self.lower_attrs(hir_id, ¶m.attrs);
1959 span: self.lower_span(param.ident.span),
1960 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
1961 bounds: self.arena.alloc_from_iter(bounds),
1969 itctx: ImplTraitContext<'_, 'hir>,
1970 ) -> hir::TraitRef<'hir> {
1971 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
1972 hir::QPath::Resolved(None, path) => path,
1973 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
1975 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
1978 fn lower_poly_trait_ref(
1981 mut itctx: ImplTraitContext<'_, 'hir>,
1982 ) -> hir::PolyTraitRef<'hir> {
1983 let bound_generic_params =
1984 self.lower_generic_params(&p.bound_generic_params, itctx.reborrow());
1986 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
1987 // Any impl Trait types defined within this scope can capture
1988 // lifetimes bound on this predicate.
1989 let lt_def_names = p.bound_generic_params.iter().filter_map(|param| match param.kind {
1990 GenericParamKind::Lifetime { .. } => Some(hir::LifetimeName::Param(
1991 ParamName::Plain(param.ident.normalize_to_macros_2_0()),
1995 if let ImplTraitContext::TypeAliasesOpaqueTy { ref mut capturable_lifetimes, .. } =
1998 capturable_lifetimes.extend(lt_def_names.clone());
2001 let res = this.lower_trait_ref(&p.trait_ref, itctx.reborrow());
2003 if let ImplTraitContext::TypeAliasesOpaqueTy { ref mut capturable_lifetimes, .. } =
2006 for param in lt_def_names {
2007 capturable_lifetimes.remove(¶m);
2013 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
2016 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
2017 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
2020 fn lower_param_bounds(
2022 bounds: &[GenericBound],
2023 itctx: ImplTraitContext<'_, 'hir>,
2024 ) -> hir::GenericBounds<'hir> {
2025 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2028 fn lower_param_bounds_mut<'s>(
2030 bounds: &'s [GenericBound],
2031 mut itctx: ImplTraitContext<'s, 'hir>,
2032 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2033 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2036 /// Lowers a block directly to an expression, presuming that it
2037 /// has no attributes and is not targeted by a `break`.
2038 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2039 let block = self.lower_block(b, false);
2040 self.expr_block(block, AttrVec::new())
2043 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2044 self.with_new_scopes(|this| hir::AnonConst {
2045 hir_id: this.lower_node_id(c.id),
2046 body: this.lower_const_body(c.value.span, Some(&c.value)),
2050 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2052 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2053 UserProvided => hir::UnsafeSource::UserProvided,
2057 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2059 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2060 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2062 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2063 // placeholder for compilation to proceed.
2064 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2065 hir::TraitBoundModifier::Maybe
2070 // Helper methods for building HIR.
2072 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2073 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2076 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2077 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2082 attrs: Option<&'hir [Attribute]>,
2084 init: Option<&'hir hir::Expr<'hir>>,
2085 pat: &'hir hir::Pat<'hir>,
2086 source: hir::LocalSource,
2087 ) -> hir::Stmt<'hir> {
2088 let hir_id = self.next_id();
2089 if let Some(a) = attrs {
2090 debug_assert!(!a.is_empty());
2091 self.attrs.insert(hir_id.local_id, a);
2093 let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2094 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2097 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2098 self.block_all(expr.span, &[], Some(expr))
2104 stmts: &'hir [hir::Stmt<'hir>],
2105 expr: Option<&'hir hir::Expr<'hir>>,
2106 ) -> &'hir hir::Block<'hir> {
2107 let blk = hir::Block {
2110 hir_id: self.next_id(),
2111 rules: hir::BlockCheckMode::DefaultBlock,
2112 span: self.lower_span(span),
2113 targeted_by_break: false,
2115 self.arena.alloc(blk)
2118 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2119 let field = self.single_pat_field(span, pat);
2120 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
2123 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2124 let field = self.single_pat_field(span, pat);
2125 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
2128 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2129 let field = self.single_pat_field(span, pat);
2130 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2133 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2134 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2137 fn single_pat_field(
2140 pat: &'hir hir::Pat<'hir>,
2141 ) -> &'hir [hir::PatField<'hir>] {
2142 let field = hir::PatField {
2143 hir_id: self.next_id(),
2144 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2145 is_shorthand: false,
2147 span: self.lower_span(span),
2149 arena_vec![self; field]
2152 fn pat_lang_item_variant(
2155 lang_item: hir::LangItem,
2156 fields: &'hir [hir::PatField<'hir>],
2157 ) -> &'hir hir::Pat<'hir> {
2158 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span));
2159 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2162 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2163 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2166 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2167 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2170 fn pat_ident_binding_mode(
2174 bm: hir::BindingAnnotation,
2175 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2176 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2177 (self.arena.alloc(pat), hir_id)
2180 fn pat_ident_binding_mode_mut(
2184 bm: hir::BindingAnnotation,
2185 ) -> (hir::Pat<'hir>, hir::HirId) {
2186 let hir_id = self.next_id();
2191 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2192 span: self.lower_span(span),
2193 default_binding_modes: true,
2199 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2200 self.arena.alloc(hir::Pat {
2201 hir_id: self.next_id(),
2203 span: self.lower_span(span),
2204 default_binding_modes: true,
2208 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2210 hir_id: self.next_id(),
2212 span: self.lower_span(span),
2213 default_binding_modes: false,
2219 mut hir_id: hir::HirId,
2221 qpath: hir::QPath<'hir>,
2222 ) -> hir::Ty<'hir> {
2223 let kind = match qpath {
2224 hir::QPath::Resolved(None, path) => {
2225 // Turn trait object paths into `TyKind::TraitObject` instead.
2227 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2228 let principal = hir::PolyTraitRef {
2229 bound_generic_params: &[],
2230 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2231 span: self.lower_span(span),
2234 // The original ID is taken by the `PolyTraitRef`,
2235 // so the `Ty` itself needs a different one.
2236 hir_id = self.next_id();
2237 hir::TyKind::TraitObject(
2238 arena_vec![self; principal],
2239 self.elided_dyn_bound(span),
2240 TraitObjectSyntax::None,
2243 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2246 _ => hir::TyKind::Path(qpath),
2249 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2252 /// Invoked to create the lifetime argument for a type `&T`
2253 /// with no explicit lifetime.
2254 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2255 match self.anonymous_lifetime_mode {
2256 // Intercept when we are in an impl header or async fn and introduce an in-band
2258 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2260 AnonymousLifetimeMode::CreateParameter => {
2261 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2263 hir_id: self.next_id(),
2264 span: self.lower_span(span),
2265 name: hir::LifetimeName::Param(fresh_name),
2269 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2271 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2275 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2276 /// return an "error lifetime".
2277 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2278 let (id, msg, label) = match id {
2279 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2282 self.resolver.next_node_id(),
2283 "`&` without an explicit lifetime name cannot be used here",
2284 "explicit lifetime name needed here",
2288 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2289 err.span_label(span, label);
2292 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2295 /// Invoked to create the lifetime argument(s) for a path like
2296 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2297 /// sorts of cases are deprecated. This may therefore report a warning or an
2298 /// error, depending on the mode.
2299 fn elided_path_lifetimes<'s>(
2303 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2304 (0..count).map(move |_| self.elided_path_lifetime(span))
2307 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
2308 match self.anonymous_lifetime_mode {
2309 AnonymousLifetimeMode::CreateParameter => {
2310 // We should have emitted E0726 when processing this path above
2312 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2313 let id = self.resolver.next_node_id();
2314 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2316 // `PassThrough` is the normal case.
2317 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2318 // is unsuitable here, as these can occur from missing lifetime parameters in a
2319 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2320 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2321 // later, at which point a suitable error will be emitted.
2322 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2323 self.new_implicit_lifetime(span)
2328 /// Invoked to create the lifetime argument(s) for an elided trait object
2329 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2330 /// when the bound is written, even if it is written with `'_` like in
2331 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2332 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2333 match self.anonymous_lifetime_mode {
2334 // NB. We intentionally ignore the create-parameter mode here.
2335 // and instead "pass through" to resolve-lifetimes, which will apply
2336 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2337 // do not act like other elided lifetimes. In other words, given this:
2339 // impl Foo for Box<dyn Debug>
2341 // we do not introduce a fresh `'_` to serve as the bound, but instead
2342 // ultimately translate to the equivalent of:
2344 // impl Foo for Box<dyn Debug + 'static>
2346 // `resolve_lifetime` has the code to make that happen.
2347 AnonymousLifetimeMode::CreateParameter => {}
2349 AnonymousLifetimeMode::ReportError => {
2350 // ReportError applies to explicit use of `'_`.
2353 // This is the normal case.
2354 AnonymousLifetimeMode::PassThrough => {}
2357 let r = hir::Lifetime {
2358 hir_id: self.next_id(),
2359 span: self.lower_span(span),
2360 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2362 debug!("elided_dyn_bound: r={:?}", r);
2366 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
2368 hir_id: self.next_id(),
2369 span: self.lower_span(span),
2370 name: hir::LifetimeName::Implicit,
2374 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
2375 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2376 // call site which do not have a macro backtrace. See #61963.
2377 let is_macro_callsite = self
2380 .span_to_snippet(span)
2381 .map(|snippet| snippet.starts_with("#["))
2383 if !is_macro_callsite {
2384 if span.edition() < Edition::Edition2021 {
2385 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2389 "trait objects without an explicit `dyn` are deprecated",
2390 BuiltinLintDiagnostics::BareTraitObject(span, is_global),
2393 let msg = "trait objects must include the `dyn` keyword";
2394 let label = "add `dyn` keyword before this trait";
2395 let mut err = struct_span_err!(self.sess, span, E0782, "{}", msg,);
2396 err.span_suggestion_verbose(
2397 span.shrink_to_lo(),
2399 String::from("dyn "),
2400 Applicability::MachineApplicable,
2408 /// Helper struct for delayed construction of GenericArgs.
2409 struct GenericArgsCtor<'hir> {
2410 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2411 bindings: &'hir [hir::TypeBinding<'hir>],
2412 parenthesized: bool,
2416 impl<'hir> GenericArgsCtor<'hir> {
2417 fn is_empty(&self) -> bool {
2418 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2421 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2422 let ga = hir::GenericArgs {
2423 args: this.arena.alloc_from_iter(self.args),
2424 bindings: self.bindings,
2425 parenthesized: self.parenthesized,
2426 span_ext: this.lower_span(self.span),
2428 this.arena.alloc(ga)
2432 fn lifetimes_from_impl_trait_bounds(
2433 opaque_ty_id: NodeId,
2434 bounds: hir::GenericBounds<'_>,
2435 lifetimes_to_include: Option<&FxHashSet<hir::LifetimeName>>,
2436 ) -> Vec<(hir::LifetimeName, Span)> {
2438 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
2440 opaque_ty_id, bounds,
2443 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
2444 // appear in the bounds, excluding lifetimes that are created within the bounds.
2445 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
2446 struct ImplTraitLifetimeCollector<'r> {
2447 collect_elided_lifetimes: bool,
2448 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2449 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
2450 lifetimes: Vec<(hir::LifetimeName, Span)>,
2451 lifetimes_to_include: Option<&'r FxHashSet<hir::LifetimeName>>,
2454 impl<'r, 'v> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r> {
2455 type Map = intravisit::ErasedMap<'v>;
2457 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
2458 intravisit::NestedVisitorMap::None
2461 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
2462 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2463 if parameters.parenthesized {
2464 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2465 self.collect_elided_lifetimes = false;
2466 intravisit::walk_generic_args(self, span, parameters);
2467 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2469 intravisit::walk_generic_args(self, span, parameters);
2473 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
2474 // Don't collect elided lifetimes used inside of `fn()` syntax.
2475 if let hir::TyKind::BareFn(_) = t.kind {
2476 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2477 self.collect_elided_lifetimes = false;
2479 // Record the "stack height" of `for<'a>` lifetime bindings
2480 // to be able to later fully undo their introduction.
2481 let old_len = self.currently_bound_lifetimes.len();
2482 intravisit::walk_ty(self, t);
2483 self.currently_bound_lifetimes.truncate(old_len);
2485 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2487 intravisit::walk_ty(self, t)
2491 fn visit_poly_trait_ref(
2493 trait_ref: &'v hir::PolyTraitRef<'v>,
2494 modifier: hir::TraitBoundModifier,
2496 // Record the "stack height" of `for<'a>` lifetime bindings
2497 // to be able to later fully undo their introduction.
2498 let old_len = self.currently_bound_lifetimes.len();
2499 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2500 self.currently_bound_lifetimes.truncate(old_len);
2503 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
2504 // Record the introduction of 'a in `for<'a> ...`.
2505 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2506 // Introduce lifetimes one at a time so that we can handle
2507 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
2508 let lt_name = hir::LifetimeName::Param(param.name);
2509 self.currently_bound_lifetimes.push(lt_name);
2512 intravisit::walk_generic_param(self, param);
2515 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2516 let name = match lifetime.name {
2517 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2518 if self.collect_elided_lifetimes {
2519 // Use `'_` for both implicit and underscore lifetimes in
2520 // `type Foo<'_> = impl SomeTrait<'_>;`.
2521 hir::LifetimeName::Underscore
2526 hir::LifetimeName::Param(_) => lifetime.name,
2528 // Refers to some other lifetime that is "in
2529 // scope" within the type.
2530 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
2532 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2535 if !self.currently_bound_lifetimes.contains(&name)
2536 && !self.already_defined_lifetimes.contains(&name)
2537 && self.lifetimes_to_include.map_or(true, |lifetimes| lifetimes.contains(&name))
2539 self.already_defined_lifetimes.insert(name);
2541 self.lifetimes.push((name, lifetime.span));
2546 let mut lifetime_collector = ImplTraitLifetimeCollector {
2547 collect_elided_lifetimes: true,
2548 currently_bound_lifetimes: Vec::new(),
2549 already_defined_lifetimes: FxHashSet::default(),
2550 lifetimes: Vec::new(),
2551 lifetimes_to_include,
2554 for bound in bounds {
2555 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
2558 lifetime_collector.lifetimes