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::node_id::NodeMap;
39 use rustc_ast::token::{self, Token};
40 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream, TokenTree};
42 use rustc_ast::{self as ast, *};
43 use rustc_ast_pretty::pprust;
44 use rustc_data_structures::captures::Captures;
45 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
46 use rustc_data_structures::sync::Lrc;
47 use rustc_errors::{struct_span_err, Applicability};
49 use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
50 use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID};
51 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
52 use rustc_hir::intravisit;
53 use rustc_hir::{ConstArg, GenericArg, InferKind, ParamName};
54 use rustc_index::vec::{Idx, IndexVec};
55 use rustc_session::lint::builtin::BARE_TRAIT_OBJECTS;
56 use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
57 use rustc_session::utils::{FlattenNonterminals, NtToTokenstream};
58 use rustc_session::Session;
59 use rustc_span::edition::Edition;
60 use rustc_span::hygiene::ExpnId;
61 use rustc_span::source_map::{respan, CachingSourceMapView, DesugaringKind};
62 use rustc_span::symbol::{kw, sym, Ident, Symbol};
63 use rustc_span::{Span, DUMMY_SP};
65 use smallvec::SmallVec;
66 use std::collections::BTreeMap;
67 use tracing::{debug, trace};
69 macro_rules! arena_vec {
70 ($this:expr; $($x:expr),*) => ({
72 $this.arena.alloc_from_iter(std::array::IntoIter::new(a))
83 rustc_hir::arena_types!(rustc_arena::declare_arena, 'tcx);
85 struct LoweringContext<'a, 'hir: 'a> {
86 /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes.
89 resolver: &'a mut dyn ResolverAstLowering,
91 /// HACK(Centril): there is a cyclic dependency between the parser and lowering
92 /// if we don't have this function pointer. To avoid that dependency so that
93 /// `rustc_middle` is independent of the parser, we use dynamic dispatch here.
94 nt_to_tokenstream: NtToTokenstream,
96 /// Used to allocate HIR nodes.
97 arena: &'hir Arena<'hir>,
99 /// The items being lowered are collected here.
100 owners: IndexVec<LocalDefId, Option<hir::OwnerNode<'hir>>>,
101 bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
103 generator_kind: Option<hir::GeneratorKind>,
105 attrs: BTreeMap<hir::HirId, &'hir [Attribute]>,
107 /// When inside an `async` context, this is the `HirId` of the
108 /// `task_context` local bound to the resume argument of the generator.
109 task_context: Option<hir::HirId>,
111 /// Used to get the current `fn`'s def span to point to when using `await`
112 /// outside of an `async fn`.
113 current_item: Option<Span>,
115 catch_scope: Option<NodeId>,
116 loop_scope: Option<NodeId>,
117 is_in_loop_condition: bool,
118 is_in_trait_impl: bool,
119 is_in_dyn_type: bool,
121 /// What to do when we encounter an "anonymous lifetime
122 /// reference". The term "anonymous" is meant to encompass both
123 /// `'_` lifetimes as well as fully elided cases where nothing is
124 /// written at all (e.g., `&T` or `std::cell::Ref<T>`).
125 anonymous_lifetime_mode: AnonymousLifetimeMode,
127 /// Used to create lifetime definitions from in-band lifetime usages.
128 /// e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
129 /// When a named lifetime is encountered in a function or impl header and
130 /// has not been defined
131 /// (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
132 /// to this list. The results of this list are then added to the list of
133 /// lifetime definitions in the corresponding impl or function generics.
134 lifetimes_to_define: Vec<(Span, ParamName)>,
136 /// `true` if in-band lifetimes are being collected. This is used to
137 /// indicate whether or not we're in a place where new lifetimes will result
138 /// in in-band lifetime definitions, such a function or an impl header,
139 /// including implicit lifetimes from `impl_header_lifetime_elision`.
140 is_collecting_in_band_lifetimes: bool,
142 /// Currently in-scope lifetimes defined in impl headers, fn headers, or HRTB.
143 /// When `is_collecting_in_band_lifetimes` is true, each lifetime is checked
144 /// against this list to see if it is already in-scope, or if a definition
145 /// needs to be created for it.
147 /// We always store a `normalize_to_macros_2_0()` version of the param-name in this
149 in_scope_lifetimes: Vec<ParamName>,
151 current_hir_id_owner: LocalDefId,
152 item_local_id_counter: hir::ItemLocalId,
153 node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
155 allow_try_trait: Option<Lrc<[Symbol]>>,
156 allow_gen_future: Option<Lrc<[Symbol]>>,
159 pub trait ResolverAstLowering {
160 fn def_key(&mut self, id: DefId) -> DefKey;
162 fn def_span(&self, id: LocalDefId) -> Span;
164 fn item_generics_num_lifetimes(&self, def: DefId) -> usize;
166 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>>;
168 /// Obtains resolution for a `NodeId` with a single resolution.
169 fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
171 /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
172 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
174 /// Obtains resolution for a label with the given `NodeId`.
175 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId>;
177 /// We must keep the set of definitions up to date as we add nodes that weren't in the AST.
178 /// This should only return `None` during testing.
179 fn definitions(&mut self) -> &mut Definitions;
181 fn lint_buffer(&mut self) -> &mut LintBuffer;
183 fn next_node_id(&mut self) -> NodeId;
185 fn take_trait_map(&mut self) -> NodeMap<Vec<hir::TraitCandidate>>;
187 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
189 fn local_def_id(&self, node: NodeId) -> LocalDefId;
191 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
196 node_id: ast::NodeId,
203 struct LoweringHasher<'a> {
204 source_map: CachingSourceMapView<'a>,
205 resolver: &'a dyn ResolverAstLowering,
208 impl<'a> rustc_span::HashStableContext for LoweringHasher<'a> {
210 fn hash_spans(&self) -> bool {
215 fn def_span(&self, id: LocalDefId) -> Span {
216 self.resolver.def_span(id)
220 fn def_path_hash(&self, def_id: DefId) -> DefPathHash {
221 self.resolver.def_path_hash(def_id)
225 fn span_data_to_lines_and_cols(
227 span: &rustc_span::SpanData,
228 ) -> Option<(Lrc<rustc_span::SourceFile>, usize, rustc_span::BytePos, usize, rustc_span::BytePos)>
230 self.source_map.span_data_to_lines_and_cols(span)
234 /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
235 /// and if so, what meaning it has.
237 enum ImplTraitContext<'b, 'a> {
238 /// Treat `impl Trait` as shorthand for a new universal generic parameter.
239 /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
240 /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
242 /// Newly generated parameters should be inserted into the given `Vec`.
243 Universal(&'b mut Vec<hir::GenericParam<'a>>, LocalDefId),
245 /// Treat `impl Trait` as shorthand for a new opaque type.
246 /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
247 /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
249 ReturnPositionOpaqueTy {
250 /// `DefId` for the parent function, used to look up necessary
251 /// information later.
253 /// Origin: Either OpaqueTyOrigin::FnReturn or OpaqueTyOrigin::AsyncFn,
254 origin: hir::OpaqueTyOrigin,
256 /// Impl trait in type aliases.
257 TypeAliasesOpaqueTy {
258 /// Set of lifetimes that this opaque type can capture, if it uses
259 /// them. This includes lifetimes bound since we entered this context.
263 /// type A<'b> = impl for<'a> Trait<'a, Out = impl Sized + 'a>;
266 /// Here the inner opaque type captures `'a` because it uses it. It doesn't
267 /// need to capture `'b` because it already inherits the lifetime
268 /// parameter from `A`.
269 // FIXME(impl_trait): but `required_region_bounds` will ICE later
271 capturable_lifetimes: &'b mut FxHashSet<hir::LifetimeName>,
273 /// `impl Trait` is not accepted in this position.
274 Disallowed(ImplTraitPosition),
277 /// Position in which `impl Trait` is disallowed.
278 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
279 enum ImplTraitPosition {
280 /// Disallowed in `let` / `const` / `static` bindings.
283 /// All other positions.
287 impl<'a> ImplTraitContext<'_, 'a> {
289 fn disallowed() -> Self {
290 ImplTraitContext::Disallowed(ImplTraitPosition::Other)
293 fn reborrow<'this>(&'this mut self) -> ImplTraitContext<'this, 'a> {
294 use self::ImplTraitContext::*;
296 Universal(params, parent) => Universal(params, *parent),
297 ReturnPositionOpaqueTy { fn_def_id, origin } => {
298 ReturnPositionOpaqueTy { fn_def_id: *fn_def_id, origin: *origin }
300 TypeAliasesOpaqueTy { capturable_lifetimes } => {
301 TypeAliasesOpaqueTy { capturable_lifetimes }
303 Disallowed(pos) => Disallowed(*pos),
308 pub fn lower_crate<'a, 'hir>(
311 resolver: &'a mut dyn ResolverAstLowering,
312 nt_to_tokenstream: NtToTokenstream,
313 arena: &'hir Arena<'hir>,
314 ) -> &'hir hir::Crate<'hir> {
315 let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering");
322 owners: IndexVec::default(),
323 bodies: BTreeMap::new(),
324 attrs: BTreeMap::default(),
327 is_in_loop_condition: false,
328 is_in_trait_impl: false,
329 is_in_dyn_type: false,
330 anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
331 current_hir_id_owner: CRATE_DEF_ID,
332 item_local_id_counter: hir::ItemLocalId::new(0),
333 node_id_to_hir_id: IndexVec::new(),
334 generator_kind: None,
337 lifetimes_to_define: Vec::new(),
338 is_collecting_in_band_lifetimes: false,
339 in_scope_lifetimes: Vec::new(),
340 allow_try_trait: Some([sym::try_trait_v2][..].into()),
341 allow_gen_future: Some([sym::gen_future][..].into()),
346 #[derive(Copy, Clone, PartialEq)]
348 /// Any path in a type context.
350 /// Path in a type definition, where the anonymous lifetime `'_` is not allowed.
352 /// The `module::Type` in `module::Type::method` in an expression.
356 enum ParenthesizedGenericArgs {
361 /// What to do when we encounter an **anonymous** lifetime
362 /// reference. Anonymous lifetime references come in two flavors. You
363 /// have implicit, or fully elided, references to lifetimes, like the
364 /// one in `&T` or `Ref<T>`, and you have `'_` lifetimes, like `&'_ T`
365 /// or `Ref<'_, T>`. These often behave the same, but not always:
367 /// - certain usages of implicit references are deprecated, like
368 /// `Ref<T>`, and we sometimes just give hard errors in those cases
370 /// - for object bounds there is a difference: `Box<dyn Foo>` is not
371 /// the same as `Box<dyn Foo + '_>`.
373 /// We describe the effects of the various modes in terms of three cases:
375 /// - **Modern** -- includes all uses of `'_`, but also the lifetime arg
376 /// of a `&` (e.g., the missing lifetime in something like `&T`)
377 /// - **Dyn Bound** -- if you have something like `Box<dyn Foo>`,
378 /// there is an elided lifetime bound (`Box<dyn Foo + 'X>`). These
379 /// elided bounds follow special rules. Note that this only covers
380 /// cases where *nothing* is written; the `'_` in `Box<dyn Foo +
381 /// '_>` is a case of "modern" elision.
382 /// - **Deprecated** -- this covers cases like `Ref<T>`, where the lifetime
383 /// parameter to ref is completely elided. `Ref<'_, T>` would be the modern,
384 /// non-deprecated equivalent.
386 /// Currently, the handling of lifetime elision is somewhat spread out
387 /// between HIR lowering and -- as described below -- the
388 /// `resolve_lifetime` module. Often we "fallthrough" to that code by generating
389 /// an "elided" or "underscore" lifetime name. In the future, we probably want to move
390 /// everything into HIR lowering.
391 #[derive(Copy, Clone, Debug)]
392 enum AnonymousLifetimeMode {
393 /// For **Modern** cases, create a new anonymous region parameter
394 /// and reference that.
396 /// For **Dyn Bound** cases, pass responsibility to
397 /// `resolve_lifetime` code.
399 /// For **Deprecated** cases, report an error.
402 /// Give a hard error when either `&` or `'_` is written. Used to
403 /// rule out things like `where T: Foo<'_>`. Does not imply an
404 /// error on default object bounds (e.g., `Box<dyn Foo>`).
407 /// Pass responsibility to `resolve_lifetime` code for all cases.
411 impl<'a, 'hir> LoweringContext<'a, 'hir> {
412 fn lower_crate(mut self, c: &Crate) -> &'hir hir::Crate<'hir> {
413 debug_assert_eq!(self.resolver.local_def_id(CRATE_NODE_ID), CRATE_DEF_ID);
415 visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
417 self.with_hir_id_owner(CRATE_NODE_ID, |lctx| {
418 let module = lctx.lower_mod(&c.items, c.span);
419 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
420 hir::OwnerNode::Crate(lctx.arena.alloc(module))
423 let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
424 for (k, v) in self.resolver.take_trait_map().into_iter() {
425 if let Some(Some(hir_id)) = self.node_id_to_hir_id.get(k) {
426 let map = trait_map.entry(hir_id.owner).or_default();
427 map.insert(hir_id.local_id, v.into_boxed_slice());
431 let mut def_id_to_hir_id = IndexVec::default();
433 for (node_id, hir_id) in self.node_id_to_hir_id.into_iter_enumerated() {
434 if let Some(def_id) = self.resolver.opt_local_def_id(node_id) {
435 if def_id_to_hir_id.len() <= def_id.index() {
436 def_id_to_hir_id.resize(def_id.index() + 1, None);
438 def_id_to_hir_id[def_id] = hir_id;
442 self.resolver.definitions().init_def_id_to_hir_id_mapping(def_id_to_hir_id);
444 #[cfg(debug_assertions)]
445 for (&id, attrs) in self.attrs.iter() {
446 // Verify that we do not store empty slices in the map.
447 if attrs.is_empty() {
448 panic!("Stored empty attributes for {:?}", id);
453 hir::Crate { owners: self.owners, bodies: self.bodies, trait_map, attrs: self.attrs };
454 self.arena.alloc(krate)
457 fn create_stable_hashing_context(&self) -> LoweringHasher<'_> {
459 source_map: CachingSourceMapView::new(self.sess.source_map()),
460 resolver: self.resolver,
464 fn with_hir_id_owner(
467 f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
469 let def_id = self.resolver.local_def_id(owner);
471 // Always allocate the first `HirId` for the owner itself.
472 let _old = self.node_id_to_hir_id.insert(owner, hir::HirId::make_owner(def_id));
473 debug_assert_eq!(_old, None);
475 let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
476 let current_local_counter =
477 std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
481 self.current_hir_id_owner = current_owner;
482 self.item_local_id_counter = current_local_counter;
484 let _old = self.owners.insert(def_id, item);
485 debug_assert!(_old.is_none());
490 /// This method allocates a new `HirId` for the given `NodeId` and stores it in
491 /// the `LoweringContext`'s `NodeId => HirId` map.
492 /// Take care not to call this method if the resulting `HirId` is then not
493 /// actually used in the HIR, as that would trigger an assertion in the
494 /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
495 /// properly. Calling the method twice with the same `NodeId` is fine though.
496 fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
497 assert_ne!(ast_node_id, DUMMY_NODE_ID);
499 *self.node_id_to_hir_id.get_or_insert_with(ast_node_id, || {
500 // Generate a new `HirId`.
501 let owner = self.current_hir_id_owner;
502 let local_id = self.item_local_id_counter;
503 self.item_local_id_counter.increment_by(1);
504 hir::HirId { owner, local_id }
508 fn next_id(&mut self) -> hir::HirId {
509 let node_id = self.resolver.next_node_id();
510 self.lower_node_id(node_id)
513 fn lower_res(&mut self, res: Res<NodeId>) -> Res {
515 self.node_id_to_hir_id.get(id).copied().flatten().unwrap_or_else(|| {
516 panic!("expected `NodeId` to be lowered already for res {:#?}", res);
521 fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
522 self.resolver.get_partial_res(id).map_or(Res::Err, |pr| {
523 if pr.unresolved_segments() != 0 {
524 panic!("path not fully resolved: {:?}", pr);
530 fn expect_full_res_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Res<NodeId>> {
531 self.resolver.get_import_res(id).present_items()
534 fn diagnostic(&self) -> &rustc_errors::Handler {
535 self.sess.diagnostic()
538 /// Reuses the span but adds information like the kind of the desugaring and features that are
539 /// allowed inside this span.
540 fn mark_span_with_reason(
542 reason: DesugaringKind,
544 allow_internal_unstable: Option<Lrc<[Symbol]>>,
546 span.mark_with_reason(
547 allow_internal_unstable,
550 self.create_stable_hashing_context(),
554 fn with_anonymous_lifetime_mode<R>(
556 anonymous_lifetime_mode: AnonymousLifetimeMode,
557 op: impl FnOnce(&mut Self) -> R,
560 "with_anonymous_lifetime_mode(anonymous_lifetime_mode={:?})",
561 anonymous_lifetime_mode,
563 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
564 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
565 let result = op(self);
566 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
568 "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}",
569 old_anonymous_lifetime_mode
574 /// Intercept all spans entering HIR.
575 /// Mark a span as relative to the current owning item.
576 fn lower_span(&self, span: Span) -> Span {
577 if self.sess.opts.debugging_opts.incremental_relative_spans {
578 span.with_parent(Some(self.current_hir_id_owner))
580 // Do not make spans relative when not using incremental compilation.
585 fn lower_ident(&self, ident: Ident) -> Ident {
586 Ident::new(ident.name, self.lower_span(ident.span))
589 /// Creates a new `hir::GenericParam` for every new lifetime and
590 /// type parameter encountered while evaluating `f`. Definitions
591 /// are created with the parent provided. If no `parent_id` is
592 /// provided, no definitions will be returned.
594 /// Presuming that in-band lifetimes are enabled, then
595 /// `self.anonymous_lifetime_mode` will be updated to match the
596 /// parameter while `f` is running (and restored afterwards).
597 fn collect_in_band_defs<T>(
599 parent_def_id: LocalDefId,
600 anonymous_lifetime_mode: AnonymousLifetimeMode,
601 f: impl FnOnce(&mut Self) -> (Vec<hir::GenericParam<'hir>>, T),
602 ) -> (Vec<hir::GenericParam<'hir>>, T) {
603 assert!(!self.is_collecting_in_band_lifetimes);
604 assert!(self.lifetimes_to_define.is_empty());
605 let old_anonymous_lifetime_mode = self.anonymous_lifetime_mode;
607 self.anonymous_lifetime_mode = anonymous_lifetime_mode;
608 self.is_collecting_in_band_lifetimes = true;
610 let (in_band_ty_params, res) = f(self);
612 self.is_collecting_in_band_lifetimes = false;
613 self.anonymous_lifetime_mode = old_anonymous_lifetime_mode;
615 let lifetimes_to_define = self.lifetimes_to_define.split_off(0);
617 let params = lifetimes_to_define
619 .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_def_id))
620 .chain(in_band_ty_params.into_iter())
626 /// Converts a lifetime into a new generic parameter.
627 fn lifetime_to_generic_param(
631 parent_def_id: LocalDefId,
632 ) -> hir::GenericParam<'hir> {
633 let node_id = self.resolver.next_node_id();
635 // Get the name we'll use to make the def-path. Note
636 // that collisions are ok here and this shouldn't
637 // really show up for end-user.
638 let (str_name, kind) = match hir_name {
639 ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand),
640 ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided),
641 ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error),
644 // Add a definition for the in-band lifetime def.
645 self.resolver.create_def(
648 DefPathData::LifetimeNs(str_name),
650 span.with_parent(None),
654 hir_id: self.lower_node_id(node_id),
657 span: self.lower_span(span),
658 pure_wrt_drop: false,
659 kind: hir::GenericParamKind::Lifetime { kind },
663 /// When there is a reference to some lifetime `'a`, and in-band
664 /// lifetimes are enabled, then we want to push that lifetime into
665 /// the vector of names to define later. In that case, it will get
666 /// added to the appropriate generics.
667 fn maybe_collect_in_band_lifetime(&mut self, ident: Ident) {
668 if !self.is_collecting_in_band_lifetimes {
672 if !self.sess.features_untracked().in_band_lifetimes {
676 if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
680 let hir_name = ParamName::Plain(ident);
682 if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
683 lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
688 self.lifetimes_to_define.push((ident.span, hir_name));
691 /// When we have either an elided or `'_` lifetime in an impl
692 /// header, we convert it to an in-band lifetime.
693 fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
694 assert!(self.is_collecting_in_band_lifetimes);
695 let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len();
696 let hir_name = ParamName::Fresh(index);
697 self.lifetimes_to_define.push((span, hir_name));
701 // Evaluates `f` with the lifetimes in `params` in-scope.
702 // This is used to track which lifetimes have already been defined, and
703 // which are new in-band lifetimes that need to have a definition created
705 fn with_in_scope_lifetime_defs<T>(
707 params: &[GenericParam],
708 f: impl FnOnce(&mut Self) -> T,
710 let old_len = self.in_scope_lifetimes.len();
711 let lt_def_names = params.iter().filter_map(|param| match param.kind {
712 GenericParamKind::Lifetime { .. } => {
713 Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
717 self.in_scope_lifetimes.extend(lt_def_names);
721 self.in_scope_lifetimes.truncate(old_len);
725 /// Appends in-band lifetime defs and argument-position `impl
726 /// Trait` defs to the existing set of generics.
728 /// Presuming that in-band lifetimes are enabled, then
729 /// `self.anonymous_lifetime_mode` will be updated to match the
730 /// parameter while `f` is running (and restored afterwards).
731 fn add_in_band_defs<T>(
734 parent_def_id: LocalDefId,
735 anonymous_lifetime_mode: AnonymousLifetimeMode,
736 f: impl FnOnce(&mut Self, &mut Vec<hir::GenericParam<'hir>>) -> T,
737 ) -> (hir::Generics<'hir>, T) {
738 let (in_band_defs, (mut lowered_generics, res)) =
739 self.with_in_scope_lifetime_defs(&generics.params, |this| {
740 this.collect_in_band_defs(parent_def_id, anonymous_lifetime_mode, |this| {
741 let mut params = Vec::new();
742 // Note: it is necessary to lower generics *before* calling `f`.
743 // When lowering `async fn`, there's a final step when lowering
744 // the return type that assumes that all in-scope lifetimes have
745 // already been added to either `in_scope_lifetimes` or
746 // `lifetimes_to_define`. If we swapped the order of these two,
747 // in-band-lifetimes introduced by generics or where-clauses
748 // wouldn't have been added yet.
749 let generics = this.lower_generics_mut(
751 ImplTraitContext::Universal(&mut params, this.current_hir_id_owner),
753 let res = f(this, &mut params);
754 (params, (generics, res))
758 lowered_generics.params.extend(in_band_defs);
760 let lowered_generics = lowered_generics.into_generics(self.arena);
761 (lowered_generics, res)
764 fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
765 let was_in_dyn_type = self.is_in_dyn_type;
766 self.is_in_dyn_type = in_scope;
768 let result = f(self);
770 self.is_in_dyn_type = was_in_dyn_type;
775 fn with_new_scopes<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
776 let was_in_loop_condition = self.is_in_loop_condition;
777 self.is_in_loop_condition = false;
779 let catch_scope = self.catch_scope.take();
780 let loop_scope = self.loop_scope.take();
782 self.catch_scope = catch_scope;
783 self.loop_scope = loop_scope;
785 self.is_in_loop_condition = was_in_loop_condition;
790 fn lower_attrs(&mut self, id: hir::HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> {
791 if attrs.is_empty() {
794 let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a)));
795 debug_assert!(!ret.is_empty());
796 self.attrs.insert(id, ret);
801 fn lower_attr(&self, attr: &Attribute) -> Attribute {
802 // Note that we explicitly do not walk the path. Since we don't really
803 // lower attributes (we use the AST version) there is nowhere to keep
804 // the `HirId`s. We don't actually need HIR version of attributes anyway.
805 // Tokens are also not needed after macro expansion and parsing.
806 let kind = match attr.kind {
807 AttrKind::Normal(ref item, _) => AttrKind::Normal(
809 path: item.path.clone(),
810 args: self.lower_mac_args(&item.args),
815 AttrKind::DocComment(comment_kind, data) => AttrKind::DocComment(comment_kind, data),
818 Attribute { kind, id: attr.id, style: attr.style, span: self.lower_span(attr.span) }
821 fn alias_attrs(&mut self, id: hir::HirId, target_id: hir::HirId) {
822 if let Some(&a) = self.attrs.get(&target_id) {
823 debug_assert!(!a.is_empty());
824 self.attrs.insert(id, a);
828 fn lower_mac_args(&self, args: &MacArgs) -> MacArgs {
830 MacArgs::Empty => MacArgs::Empty,
831 MacArgs::Delimited(dspan, delim, ref tokens) => {
832 // This is either a non-key-value attribute, or a `macro_rules!` body.
833 // We either not have any nonterminals present (in the case of an attribute),
834 // or have tokens available for all nonterminals in the case of a nested
835 // `macro_rules`: e.g:
838 // macro_rules! outer {
840 // macro_rules! inner {
847 // In both cases, we don't want to synthesize any tokens
851 self.lower_token_stream(tokens.clone(), CanSynthesizeMissingTokens::No),
854 // This is an inert key-value attribute - it will never be visible to macros
855 // after it gets lowered to HIR. Therefore, we can synthesize tokens with fake
856 // spans to handle nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
857 MacArgs::Eq(eq_span, ref token) => {
858 // In valid code the value is always representable as a single literal token.
859 fn unwrap_single_token(sess: &Session, tokens: TokenStream, span: Span) -> Token {
860 if tokens.len() != 1 {
862 .delay_span_bug(span, "multiple tokens in key-value attribute's value");
864 match tokens.into_trees().next() {
865 Some(TokenTree::Token(token)) => token,
866 Some(TokenTree::Delimited(_, delim, tokens)) => {
867 if delim != token::NoDelim {
868 sess.diagnostic().delay_span_bug(
870 "unexpected delimiter in key-value attribute's value",
873 unwrap_single_token(sess, tokens, span)
875 None => Token::dummy(),
879 let tokens = FlattenNonterminals {
880 parse_sess: &self.sess.parse_sess,
881 synthesize_tokens: CanSynthesizeMissingTokens::Yes,
882 nt_to_tokenstream: self.nt_to_tokenstream,
884 .process_token(token.clone());
885 MacArgs::Eq(eq_span, unwrap_single_token(self.sess, tokens, token.span))
890 fn lower_token_stream(
893 synthesize_tokens: CanSynthesizeMissingTokens,
895 FlattenNonterminals {
896 parse_sess: &self.sess.parse_sess,
898 nt_to_tokenstream: self.nt_to_tokenstream,
900 .process_token_stream(tokens)
903 /// Given an associated type constraint like one of these:
906 /// T: Iterator<Item: Debug>
908 /// T: Iterator<Item = Debug>
912 /// returns a `hir::TypeBinding` representing `Item`.
913 fn lower_assoc_ty_constraint(
915 constraint: &AssocTyConstraint,
916 mut itctx: ImplTraitContext<'_, 'hir>,
917 ) -> hir::TypeBinding<'hir> {
918 debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);
920 // lower generic arguments of identifier in constraint
921 let gen_args = if let Some(ref gen_args) = constraint.gen_args {
922 let gen_args_ctor = match gen_args {
923 GenericArgs::AngleBracketed(ref data) => {
924 self.lower_angle_bracketed_parameter_data(
931 GenericArgs::Parenthesized(ref data) => {
932 let mut err = self.sess.struct_span_err(
934 "parenthesized generic arguments cannot be used in associated type constraints"
936 // FIXME: try to write a suggestion here
938 self.lower_angle_bracketed_parameter_data(
939 &data.as_angle_bracketed_args(),
946 gen_args_ctor.into_generic_args(self)
948 self.arena.alloc(hir::GenericArgs::none())
951 let kind = match constraint.kind {
952 AssocTyConstraintKind::Equality { ref ty } => {
953 hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
955 AssocTyConstraintKind::Bound { ref bounds } => {
956 let mut capturable_lifetimes;
957 let mut parent_def_id = self.current_hir_id_owner;
958 // Piggy-back on the `impl Trait` context to figure out the correct behavior.
959 let (desugar_to_impl_trait, itctx) = match itctx {
960 // We are in the return position:
962 // fn foo() -> impl Iterator<Item: Debug>
966 // fn foo() -> impl Iterator<Item = impl Debug>
967 ImplTraitContext::ReturnPositionOpaqueTy { .. }
968 | ImplTraitContext::TypeAliasesOpaqueTy { .. } => (true, itctx),
970 // We are in the argument position, but within a dyn type:
972 // fn foo(x: dyn Iterator<Item: Debug>)
976 // fn foo(x: dyn Iterator<Item = impl Debug>)
977 ImplTraitContext::Universal(_, parent) if self.is_in_dyn_type => {
978 parent_def_id = parent;
982 // In `type Foo = dyn Iterator<Item: Debug>` we desugar to
983 // `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
984 // "impl trait context" to permit `impl Debug` in this position (it desugars
985 // then to an opaque type).
987 // FIXME: this is only needed until `impl Trait` is allowed in type aliases.
988 ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => {
989 capturable_lifetimes = FxHashSet::default();
992 ImplTraitContext::TypeAliasesOpaqueTy {
993 capturable_lifetimes: &mut capturable_lifetimes,
998 // We are in the parameter position, but not within a dyn type:
1000 // fn foo(x: impl Iterator<Item: Debug>)
1002 // so we leave it as is and this gets expanded in astconv to a bound like
1003 // `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
1005 _ => (false, itctx),
1008 if desugar_to_impl_trait {
1009 // Desugar `AssocTy: Bounds` into `AssocTy = impl Bounds`. We do this by
1010 // constructing the HIR for `impl bounds...` and then lowering that.
1012 let impl_trait_node_id = self.resolver.next_node_id();
1013 self.resolver.create_def(
1016 DefPathData::ImplTrait,
1021 self.with_dyn_type_scope(false, |this| {
1022 let node_id = this.resolver.next_node_id();
1023 let ty = this.lower_ty(
1026 kind: TyKind::ImplTrait(impl_trait_node_id, bounds.clone()),
1027 span: this.lower_span(constraint.span),
1033 hir::TypeBindingKind::Equality { ty }
1036 // Desugar `AssocTy: Bounds` into a type binding where the
1037 // later desugars into a trait predicate.
1038 let bounds = self.lower_param_bounds(bounds, itctx);
1040 hir::TypeBindingKind::Constraint { bounds }
1046 hir_id: self.lower_node_id(constraint.id),
1047 ident: self.lower_ident(constraint.ident),
1050 span: self.lower_span(constraint.span),
1054 fn lower_generic_arg(
1056 arg: &ast::GenericArg,
1057 itctx: ImplTraitContext<'_, 'hir>,
1058 ) -> hir::GenericArg<'hir> {
1060 ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
1061 ast::GenericArg::Type(ty) => {
1063 TyKind::Infer if self.sess.features_untracked().generic_arg_infer => {
1064 return GenericArg::Infer(hir::InferArg {
1065 hir_id: self.lower_node_id(ty.id),
1066 span: self.lower_span(ty.span),
1067 kind: InferKind::Type,
1070 // We parse const arguments as path types as we cannot distinguish them during
1071 // parsing. We try to resolve that ambiguity by attempting resolution in both the
1072 // type and value namespaces. If we resolved the path in the value namespace, we
1073 // transform it into a generic const argument.
1074 TyKind::Path(ref qself, ref path) => {
1075 if let Some(partial_res) = self.resolver.get_partial_res(ty.id) {
1076 let res = partial_res.base_res();
1077 if !res.matches_ns(Namespace::TypeNS) {
1079 "lower_generic_arg: Lowering type argument as const argument: {:?}",
1083 // Construct an AnonConst where the expr is the "ty"'s path.
1085 let parent_def_id = self.current_hir_id_owner;
1086 let node_id = self.resolver.next_node_id();
1088 // Add a definition for the in-band const def.
1089 self.resolver.create_def(
1092 DefPathData::AnonConst,
1097 let span = self.lower_span(ty.span);
1098 let path_expr = Expr {
1100 kind: ExprKind::Path(qself.clone(), path.clone()),
1102 attrs: AttrVec::new(),
1106 let ct = self.with_new_scopes(|this| hir::AnonConst {
1107 hir_id: this.lower_node_id(node_id),
1108 body: this.lower_const_body(path_expr.span, Some(&path_expr)),
1110 return GenericArg::Const(ConstArg { value: ct, span });
1116 GenericArg::Type(self.lower_ty_direct(&ty, itctx))
1118 ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg {
1119 value: self.lower_anon_const(&ct),
1120 span: self.lower_span(ct.value.span),
1125 fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'hir>) -> &'hir hir::Ty<'hir> {
1126 self.arena.alloc(self.lower_ty_direct(t, itctx))
1132 qself: &Option<QSelf>,
1134 param_mode: ParamMode,
1135 itctx: ImplTraitContext<'_, 'hir>,
1136 ) -> hir::Ty<'hir> {
1137 let id = self.lower_node_id(t.id);
1138 let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx);
1139 let ty = self.ty_path(id, t.span, qpath);
1140 if let hir::TyKind::TraitObject(..) = ty.kind {
1141 self.maybe_lint_bare_trait(t.span, t.id, qself.is_none() && path.is_global());
1146 fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1147 hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1150 fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1151 self.ty(span, hir::TyKind::Tup(tys))
1154 fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'hir>) -> hir::Ty<'hir> {
1155 let kind = match t.kind {
1156 TyKind::Infer => hir::TyKind::Infer,
1157 TyKind::Err => hir::TyKind::Err,
1158 TyKind::Slice(ref ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
1159 TyKind::Ptr(ref mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1160 TyKind::Rptr(ref region, ref mt) => {
1161 let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
1162 let lifetime = match *region {
1163 Some(ref lt) => self.lower_lifetime(lt),
1164 None => self.elided_ref_lifetime(span),
1166 hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx))
1168 TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| {
1169 this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
1170 hir::TyKind::BareFn(this.arena.alloc(hir::BareFnTy {
1171 generic_params: this.lower_generic_params(
1173 ImplTraitContext::disallowed(),
1175 unsafety: this.lower_unsafety(f.unsafety),
1176 abi: this.lower_extern(f.ext),
1177 decl: this.lower_fn_decl(&f.decl, None, false, None),
1178 param_names: this.lower_fn_params_to_names(&f.decl),
1182 TyKind::Never => hir::TyKind::Never,
1183 TyKind::Tup(ref tys) => {
1184 hir::TyKind::Tup(self.arena.alloc_from_iter(
1185 tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())),
1188 TyKind::Paren(ref ty) => {
1189 return self.lower_ty_direct(ty, itctx);
1191 TyKind::Path(ref qself, ref path) => {
1192 return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1194 TyKind::ImplicitSelf => {
1195 let res = self.expect_full_res(t.id);
1196 let res = self.lower_res(res);
1197 hir::TyKind::Path(hir::QPath::Resolved(
1199 self.arena.alloc(hir::Path {
1201 segments: arena_vec![self; hir::PathSegment::from_ident(
1202 Ident::with_dummy_span(kw::SelfUpper)
1204 span: self.lower_span(t.span),
1208 TyKind::Array(ref ty, ref length) => {
1209 hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length))
1211 TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)),
1212 TyKind::TraitObject(ref bounds, kind) => {
1213 let mut lifetime_bound = None;
1214 let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1216 this.arena.alloc_from_iter(bounds.iter().filter_map(
1217 |bound| match *bound {
1218 GenericBound::Trait(
1220 TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
1221 ) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
1222 // `~const ?Bound` will cause an error during AST validation
1223 // anyways, so treat it like `?Bound` as compilation proceeds.
1224 GenericBound::Trait(
1226 TraitBoundModifier::Maybe | TraitBoundModifier::MaybeConstMaybe,
1228 GenericBound::Outlives(ref lifetime) => {
1229 if lifetime_bound.is_none() {
1230 lifetime_bound = Some(this.lower_lifetime(lifetime));
1236 let lifetime_bound =
1237 lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1238 (bounds, lifetime_bound)
1240 if kind != TraitObjectSyntax::Dyn {
1241 self.maybe_lint_bare_trait(t.span, t.id, false);
1243 hir::TyKind::TraitObject(bounds, lifetime_bound, kind)
1245 TyKind::ImplTrait(def_node_id, ref bounds) => {
1248 ImplTraitContext::ReturnPositionOpaqueTy { fn_def_id, origin } => self
1249 .lower_opaque_impl_trait(
1255 |this| this.lower_param_bounds(bounds, itctx),
1257 ImplTraitContext::TypeAliasesOpaqueTy { ref capturable_lifetimes } => {
1258 // Reset capturable lifetimes, any nested impl trait
1259 // types will inherit lifetimes from this opaque type,
1260 // so don't need to capture them again.
1261 let nested_itctx = ImplTraitContext::TypeAliasesOpaqueTy {
1262 capturable_lifetimes: &mut FxHashSet::default(),
1264 self.lower_opaque_impl_trait(
1267 hir::OpaqueTyOrigin::TyAlias,
1269 Some(capturable_lifetimes),
1270 |this| this.lower_param_bounds(bounds, nested_itctx),
1273 ImplTraitContext::Universal(in_band_ty_params, parent_def_id) => {
1274 // Add a definition for the in-band `Param`.
1275 let def_id = self.resolver.local_def_id(def_node_id);
1277 let hir_bounds = self.lower_param_bounds(
1279 ImplTraitContext::Universal(in_band_ty_params, parent_def_id),
1281 // Set the name to `impl Bound1 + Bound2`.
1282 let ident = Ident::from_str_and_span(&pprust::ty_to_string(t), span);
1283 in_band_ty_params.push(hir::GenericParam {
1284 hir_id: self.lower_node_id(def_node_id),
1285 name: ParamName::Plain(self.lower_ident(ident)),
1286 pure_wrt_drop: false,
1288 span: self.lower_span(span),
1289 kind: hir::GenericParamKind::Type {
1291 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1295 hir::TyKind::Path(hir::QPath::Resolved(
1297 self.arena.alloc(hir::Path {
1298 span: self.lower_span(span),
1299 res: Res::Def(DefKind::TyParam, def_id.to_def_id()),
1300 segments: arena_vec![self; hir::PathSegment::from_ident(self.lower_ident(ident))],
1304 ImplTraitContext::Disallowed(_) => {
1305 let mut err = struct_span_err!(
1309 "`impl Trait` not allowed outside of {}",
1310 "function and method return types",
1317 TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
1318 TyKind::CVarArgs => {
1319 self.sess.delay_span_bug(
1321 "`TyKind::CVarArgs` should have been handled elsewhere",
1327 hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1330 fn lower_opaque_impl_trait(
1333 fn_def_id: Option<DefId>,
1334 origin: hir::OpaqueTyOrigin,
1335 opaque_ty_node_id: NodeId,
1336 capturable_lifetimes: Option<&FxHashSet<hir::LifetimeName>>,
1337 lower_bounds: impl FnOnce(&mut Self) -> hir::GenericBounds<'hir>,
1338 ) -> hir::TyKind<'hir> {
1340 "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})",
1341 fn_def_id, opaque_ty_node_id, span,
1344 // Make sure we know that some funky desugaring has been going on here.
1345 // This is a first: there is code in other places like for loop
1346 // desugaring that explicitly states that we don't want to track that.
1347 // Not tracking it makes lints in rustc and clippy very fragile, as
1348 // frequently opened issues show.
1349 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1351 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1353 let mut collected_lifetimes = Vec::new();
1354 self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
1355 let hir_bounds = lower_bounds(lctx);
1357 collected_lifetimes = lifetimes_from_impl_trait_bounds(
1360 capturable_lifetimes,
1364 lctx.arena.alloc_from_iter(collected_lifetimes.iter().map(|&(name, span)| {
1365 let def_node_id = lctx.resolver.next_node_id();
1366 let hir_id = lctx.lower_node_id(def_node_id);
1367 lctx.resolver.create_def(
1370 DefPathData::LifetimeNs(name.ident().name),
1372 span.with_parent(None),
1375 let (name, kind) = match name {
1376 hir::LifetimeName::Underscore => (
1377 hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
1378 hir::LifetimeParamKind::Elided,
1380 hir::LifetimeName::Param(param_name) => {
1381 (param_name, hir::LifetimeParamKind::Explicit)
1383 _ => panic!("expected `LifetimeName::Param` or `ParamName::Plain`"),
1390 pure_wrt_drop: false,
1392 kind: hir::GenericParamKind::Lifetime { kind },
1396 debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs);
1398 let opaque_ty_item = hir::OpaqueTy {
1399 generics: hir::Generics {
1400 params: lifetime_defs,
1401 where_clause: hir::WhereClause { predicates: &[], span: lctx.lower_span(span) },
1402 span: lctx.lower_span(span),
1405 impl_trait_fn: fn_def_id,
1409 trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
1410 lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1414 self.arena.alloc_from_iter(collected_lifetimes.into_iter().map(|(name, span)| {
1415 hir::GenericArg::Lifetime(hir::Lifetime { hir_id: self.next_id(), span, name })
1418 debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes);
1420 // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
1421 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes)
1424 /// Registers a new opaque type with the proper `NodeId`s and
1425 /// returns the lowered node-ID for the opaque type.
1426 fn generate_opaque_type(
1428 opaque_ty_id: LocalDefId,
1429 opaque_ty_item: hir::OpaqueTy<'hir>,
1431 opaque_ty_span: Span,
1432 ) -> hir::OwnerNode<'hir> {
1433 let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
1434 // Generate an `type Foo = impl Trait;` declaration.
1435 trace!("registering opaque type with id {:#?}", opaque_ty_id);
1436 let opaque_ty_item = hir::Item {
1437 def_id: opaque_ty_id,
1438 ident: Ident::invalid(),
1439 kind: opaque_ty_item_kind,
1440 vis: respan(self.lower_span(span.shrink_to_lo()), hir::VisibilityKind::Inherited),
1441 span: self.lower_span(opaque_ty_span),
1443 hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
1446 fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
1447 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1448 // as they are not explicit in HIR/Ty function signatures.
1449 // (instead, the `c_variadic` flag is set to `true`)
1450 let mut inputs = &decl.inputs[..];
1451 if decl.c_variadic() {
1452 inputs = &inputs[..inputs.len() - 1];
1454 self.arena.alloc_from_iter(inputs.iter().map(|param| match param.pat.kind {
1455 PatKind::Ident(_, ident, _) => self.lower_ident(ident),
1456 _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)),
1460 // Lowers a function declaration.
1462 // `decl`: the unlowered (AST) function declaration.
1463 // `fn_def_id`: if `Some`, impl Trait arguments are lowered into generic parameters on the
1464 // given DefId, otherwise impl Trait is disallowed. Must be `Some` if
1465 // `make_ret_async` is also `Some`.
1466 // `impl_trait_return_allow`: determines whether `impl Trait` can be used in return position.
1467 // This guards against trait declarations and implementations where `impl Trait` is
1469 // `make_ret_async`: if `Some`, converts `-> T` into `-> impl Future<Output = T>` in the
1470 // return type. This is used for `async fn` declarations. The `NodeId` is the ID of the
1471 // return type `impl Trait` item.
1475 mut in_band_ty_params: Option<(DefId, &mut Vec<hir::GenericParam<'hir>>)>,
1476 impl_trait_return_allow: bool,
1477 make_ret_async: Option<NodeId>,
1478 ) -> &'hir hir::FnDecl<'hir> {
1482 in_band_ty_params: {:?}, \
1483 impl_trait_return_allow: {}, \
1484 make_ret_async: {:?})",
1485 decl, in_band_ty_params, impl_trait_return_allow, make_ret_async,
1487 let lt_mode = if make_ret_async.is_some() {
1488 // In `async fn`, argument-position elided lifetimes
1489 // must be transformed into fresh generic parameters so that
1490 // they can be applied to the opaque `impl Trait` return type.
1491 AnonymousLifetimeMode::CreateParameter
1493 self.anonymous_lifetime_mode
1496 let c_variadic = decl.c_variadic();
1498 // Remember how many lifetimes were already around so that we can
1499 // only look at the lifetime parameters introduced by the arguments.
1500 let inputs = self.with_anonymous_lifetime_mode(lt_mode, |this| {
1501 // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1502 // as they are not explicit in HIR/Ty function signatures.
1503 // (instead, the `c_variadic` flag is set to `true`)
1504 let mut inputs = &decl.inputs[..];
1506 inputs = &inputs[..inputs.len() - 1];
1508 this.arena.alloc_from_iter(inputs.iter().map(|param| {
1509 if let Some((_, ibty)) = &mut in_band_ty_params {
1510 this.lower_ty_direct(
1512 ImplTraitContext::Universal(ibty, this.current_hir_id_owner),
1515 this.lower_ty_direct(¶m.ty, ImplTraitContext::disallowed())
1520 let output = if let Some(ret_id) = make_ret_async {
1521 self.lower_async_fn_ret_ty(
1523 in_band_ty_params.expect("`make_ret_async` but no `fn_def_id`").0,
1528 FnRetTy::Ty(ref ty) => {
1529 let context = match in_band_ty_params {
1530 Some((def_id, _)) if impl_trait_return_allow => {
1531 ImplTraitContext::ReturnPositionOpaqueTy {
1533 origin: hir::OpaqueTyOrigin::FnReturn,
1536 _ => ImplTraitContext::disallowed(),
1538 hir::FnRetTy::Return(self.lower_ty(ty, context))
1540 FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
1544 self.arena.alloc(hir::FnDecl {
1548 implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1549 use BindingMode::{ByRef, ByValue};
1550 let is_mutable_pat = matches!(
1552 PatKind::Ident(ByValue(Mutability::Mut) | ByRef(Mutability::Mut), ..)
1556 TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1557 TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1558 // Given we are only considering `ImplicitSelf` types, we needn't consider
1559 // the case where we have a mutable pattern to a reference as that would
1560 // no longer be an `ImplicitSelf`.
1561 TyKind::Rptr(_, ref mt)
1562 if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut =>
1564 hir::ImplicitSelfKind::MutRef
1566 TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => {
1567 hir::ImplicitSelfKind::ImmRef
1569 _ => hir::ImplicitSelfKind::None,
1575 // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1576 // combined with the following definition of `OpaqueTy`:
1578 // type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1580 // `inputs`: lowered types of parameters to the function (used to collect lifetimes)
1581 // `output`: unlowered output type (`T` in `-> T`)
1582 // `fn_def_id`: `DefId` of the parent function (used to create child impl trait definition)
1583 // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1584 // `elided_lt_replacement`: replacement for elided lifetimes in the return type
1585 fn lower_async_fn_ret_ty(
1589 opaque_ty_node_id: NodeId,
1590 ) -> hir::FnRetTy<'hir> {
1592 "lower_async_fn_ret_ty(\
1595 opaque_ty_node_id={:?})",
1596 output, fn_def_id, opaque_ty_node_id,
1599 let span = output.span();
1601 let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1603 let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
1605 // When we create the opaque type for this async fn, it is going to have
1606 // to capture all the lifetimes involved in the signature (including in the
1607 // return type). This is done by introducing lifetime parameters for:
1609 // - all the explicitly declared lifetimes from the impl and function itself;
1610 // - all the elided lifetimes in the fn arguments;
1611 // - all the elided lifetimes in the return type.
1613 // So for example in this snippet:
1616 // impl<'a> Foo<'a> {
1617 // async fn bar<'b>(&self, x: &'b Vec<f64>, y: &str) -> &u32 {
1618 // // ^ '0 ^ '1 ^ '2
1619 // // elided lifetimes used below
1624 // we would create an opaque type like:
1627 // type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1630 // and we would then desugar `bar` to the equivalent of:
1633 // impl<'a> Foo<'a> {
1634 // fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1638 // Note that the final parameter to `Bar` is `'_`, not `'2` --
1639 // this is because the elided lifetimes from the return type
1640 // should be figured out using the ordinary elision rules, and
1641 // this desugaring achieves that.
1643 // The variable `input_lifetimes_count` tracks the number of
1644 // lifetime parameters to the opaque type *not counting* those
1645 // lifetimes elided in the return type. This includes those
1646 // that are explicitly declared (`in_scope_lifetimes`) and
1647 // those elided lifetimes we found in the arguments (current
1648 // content of `lifetimes_to_define`). Next, we will process
1649 // the return type, which will cause `lifetimes_to_define` to
1651 let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
1653 let mut lifetime_params = Vec::new();
1654 self.with_hir_id_owner(opaque_ty_node_id, |this| {
1655 // We have to be careful to get elision right here. The
1656 // idea is that we create a lifetime parameter for each
1657 // lifetime in the return type. So, given a return type
1658 // like `async fn foo(..) -> &[&u32]`, we lower to `impl
1659 // Future<Output = &'1 [ &'2 u32 ]>`.
1661 // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and
1662 // hence the elision takes place at the fn site.
1663 let future_bound = this
1664 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| {
1665 this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span)
1668 debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
1670 // Calculate all the lifetimes that should be captured
1671 // by the opaque type. This should include all in-scope
1672 // lifetime parameters, including those defined in-band.
1674 // Note: this must be done after lowering the output type,
1675 // as the output type may introduce new in-band lifetimes.
1676 lifetime_params = this
1680 .map(|name| (name.ident().span, name))
1681 .chain(this.lifetimes_to_define.iter().cloned())
1684 debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes);
1685 debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define);
1686 debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
1688 let generic_params =
1689 this.arena.alloc_from_iter(lifetime_params.iter().map(|(span, hir_name)| {
1690 this.lifetime_to_generic_param(*span, *hir_name, opaque_ty_def_id)
1693 let opaque_ty_item = hir::OpaqueTy {
1694 generics: hir::Generics {
1695 params: generic_params,
1696 where_clause: hir::WhereClause { predicates: &[], span: this.lower_span(span) },
1697 span: this.lower_span(span),
1699 bounds: arena_vec![this; future_bound],
1700 impl_trait_fn: Some(fn_def_id),
1701 origin: hir::OpaqueTyOrigin::AsyncFn,
1704 trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
1705 this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
1708 // As documented above on the variable
1709 // `input_lifetimes_count`, we need to create the lifetime
1710 // arguments to our opaque type. Continuing with our example,
1711 // we're creating the type arguments for the return type:
1714 // Bar<'a, 'b, '0, '1, '_>
1717 // For the "input" lifetime parameters, we wish to create
1718 // references to the parameters themselves, including the
1719 // "implicit" ones created from parameter types (`'a`, `'b`,
1722 // For the "output" lifetime parameters, we just want to
1724 let mut generic_args = Vec::with_capacity(lifetime_params.len());
1725 generic_args.extend(lifetime_params[..input_lifetimes_count].iter().map(
1726 |&(span, hir_name)| {
1727 // Input lifetime like `'a` or `'1`:
1728 GenericArg::Lifetime(hir::Lifetime {
1729 hir_id: self.next_id(),
1730 span: self.lower_span(span),
1731 name: hir::LifetimeName::Param(hir_name),
1735 generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)|
1736 // Output lifetime like `'_`.
1737 GenericArg::Lifetime(hir::Lifetime {
1738 hir_id: self.next_id(),
1739 span: self.lower_span(span),
1740 name: hir::LifetimeName::Implicit,
1742 let generic_args = self.arena.alloc_from_iter(generic_args);
1744 // Create the `Foo<...>` reference itself. Note that the `type
1745 // Foo = impl Trait` is, internally, created as a child of the
1746 // async fn, so the *type parameters* are inherited. It's
1747 // only the lifetime parameters that we must supply.
1749 hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args);
1750 let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1751 hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1754 /// Transforms `-> T` into `Future<Output = T>`.
1755 fn lower_async_fn_output_type_to_future_bound(
1760 ) -> hir::GenericBound<'hir> {
1761 // Compute the `T` in `Future<Output = T>` from the return type.
1762 let output_ty = match output {
1763 FnRetTy::Ty(ty) => {
1764 // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1765 // `impl Future` opaque type that `async fn` implicitly
1767 let context = ImplTraitContext::ReturnPositionOpaqueTy {
1769 origin: hir::OpaqueTyOrigin::FnReturn,
1771 self.lower_ty(ty, context)
1773 FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1777 let future_args = self.arena.alloc(hir::GenericArgs {
1779 bindings: arena_vec![self; self.output_ty_binding(span, output_ty)],
1780 parenthesized: false,
1784 hir::GenericBound::LangItemTrait(
1785 // ::std::future::Future<future_params>
1786 hir::LangItem::Future,
1787 self.lower_span(span),
1793 fn lower_param_bound(
1796 itctx: ImplTraitContext<'_, 'hir>,
1797 ) -> hir::GenericBound<'hir> {
1799 GenericBound::Trait(p, modifier) => hir::GenericBound::Trait(
1800 self.lower_poly_trait_ref(p, itctx),
1801 self.lower_trait_bound_modifier(*modifier),
1803 GenericBound::Outlives(lifetime) => {
1804 hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
1809 fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
1810 let span = self.lower_span(l.ident.span);
1812 ident if ident.name == kw::StaticLifetime => {
1813 self.new_named_lifetime(l.id, span, hir::LifetimeName::Static)
1815 ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode {
1816 AnonymousLifetimeMode::CreateParameter => {
1817 let fresh_name = self.collect_fresh_in_band_lifetime(span);
1818 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
1821 AnonymousLifetimeMode::PassThrough => {
1822 self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore)
1825 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span),
1828 self.maybe_collect_in_band_lifetime(ident);
1829 let param_name = ParamName::Plain(self.lower_ident(ident));
1830 self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
1835 fn new_named_lifetime(
1839 name: hir::LifetimeName,
1840 ) -> hir::Lifetime {
1841 hir::Lifetime { hir_id: self.lower_node_id(id), span: self.lower_span(span), name }
1844 fn lower_generic_params_mut<'s>(
1846 params: &'s [GenericParam],
1847 mut itctx: ImplTraitContext<'s, 'hir>,
1848 ) -> impl Iterator<Item = hir::GenericParam<'hir>> + Captures<'a> + Captures<'s> {
1849 params.iter().map(move |param| self.lower_generic_param(param, itctx.reborrow()))
1852 fn lower_generic_params(
1854 params: &[GenericParam],
1855 itctx: ImplTraitContext<'_, 'hir>,
1856 ) -> &'hir [hir::GenericParam<'hir>] {
1857 self.arena.alloc_from_iter(self.lower_generic_params_mut(params, itctx))
1860 fn lower_generic_param(
1862 param: &GenericParam,
1863 mut itctx: ImplTraitContext<'_, 'hir>,
1864 ) -> hir::GenericParam<'hir> {
1865 let bounds: Vec<_> = self
1866 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1867 this.lower_param_bounds_mut(¶m.bounds, itctx.reborrow()).collect()
1870 let (name, kind) = match param.kind {
1871 GenericParamKind::Lifetime => {
1872 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
1873 self.is_collecting_in_band_lifetimes = false;
1876 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1877 this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident })
1879 let param_name = match lt.name {
1880 hir::LifetimeName::Param(param_name) => param_name,
1881 hir::LifetimeName::Implicit
1882 | hir::LifetimeName::Underscore
1883 | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
1884 hir::LifetimeName::ImplicitObjectLifetimeDefault => {
1885 self.sess.diagnostic().span_bug(
1887 "object-lifetime-default should not occur here",
1890 hir::LifetimeName::Error => ParamName::Error,
1894 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
1896 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
1900 GenericParamKind::Type { ref default, .. } => {
1901 let kind = hir::GenericParamKind::Type {
1902 default: default.as_ref().map(|x| {
1903 self.lower_ty(x, ImplTraitContext::Disallowed(ImplTraitPosition::Other))
1908 .filter(|attr| attr.has_name(sym::rustc_synthetic))
1909 .map(|_| hir::SyntheticTyParamKind::FromAttr)
1913 (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
1915 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1917 .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| {
1918 this.lower_ty(&ty, ImplTraitContext::disallowed())
1920 let default = default.as_ref().map(|def| self.lower_anon_const(def));
1922 hir::ParamName::Plain(self.lower_ident(param.ident)),
1923 hir::GenericParamKind::Const { ty, default },
1927 let name = match name {
1928 hir::ParamName::Plain(ident) => hir::ParamName::Plain(self.lower_ident(ident)),
1932 let hir_id = self.lower_node_id(param.id);
1933 self.lower_attrs(hir_id, ¶m.attrs);
1937 span: self.lower_span(param.ident.span),
1938 pure_wrt_drop: self.sess.contains_name(¶m.attrs, sym::may_dangle),
1939 bounds: self.arena.alloc_from_iter(bounds),
1947 itctx: ImplTraitContext<'_, 'hir>,
1948 ) -> hir::TraitRef<'hir> {
1949 let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
1950 hir::QPath::Resolved(None, path) => path,
1951 qpath => panic!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
1953 hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
1956 fn lower_poly_trait_ref(
1959 mut itctx: ImplTraitContext<'_, 'hir>,
1960 ) -> hir::PolyTraitRef<'hir> {
1961 let bound_generic_params =
1962 self.lower_generic_params(&p.bound_generic_params, itctx.reborrow());
1964 let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| {
1965 // Any impl Trait types defined within this scope can capture
1966 // lifetimes bound on this predicate.
1967 let lt_def_names = p.bound_generic_params.iter().filter_map(|param| match param.kind {
1968 GenericParamKind::Lifetime { .. } => Some(hir::LifetimeName::Param(
1969 ParamName::Plain(param.ident.normalize_to_macros_2_0()),
1973 if let ImplTraitContext::TypeAliasesOpaqueTy { ref mut capturable_lifetimes, .. } =
1976 capturable_lifetimes.extend(lt_def_names.clone());
1979 let res = this.lower_trait_ref(&p.trait_ref, itctx.reborrow());
1981 if let ImplTraitContext::TypeAliasesOpaqueTy { ref mut capturable_lifetimes, .. } =
1984 for param in lt_def_names {
1985 capturable_lifetimes.remove(¶m);
1991 hir::PolyTraitRef { bound_generic_params, trait_ref, span: self.lower_span(p.span) }
1994 fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'hir>) -> hir::MutTy<'hir> {
1995 hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl }
1998 fn lower_param_bounds(
2000 bounds: &[GenericBound],
2001 itctx: ImplTraitContext<'_, 'hir>,
2002 ) -> hir::GenericBounds<'hir> {
2003 self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx))
2006 fn lower_param_bounds_mut<'s>(
2008 bounds: &'s [GenericBound],
2009 mut itctx: ImplTraitContext<'s, 'hir>,
2010 ) -> impl Iterator<Item = hir::GenericBound<'hir>> + Captures<'s> + Captures<'a> {
2011 bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx.reborrow()))
2014 /// Lowers a block directly to an expression, presuming that it
2015 /// has no attributes and is not targeted by a `break`.
2016 fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2017 let block = self.lower_block(b, false);
2018 self.expr_block(block, AttrVec::new())
2021 fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst {
2022 self.with_new_scopes(|this| hir::AnonConst {
2023 hir_id: this.lower_node_id(c.id),
2024 body: this.lower_const_body(c.value.span, Some(&c.value)),
2028 fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2030 CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2031 UserProvided => hir::UnsafeSource::UserProvided,
2035 fn lower_trait_bound_modifier(&mut self, f: TraitBoundModifier) -> hir::TraitBoundModifier {
2037 TraitBoundModifier::None => hir::TraitBoundModifier::None,
2038 TraitBoundModifier::MaybeConst => hir::TraitBoundModifier::MaybeConst,
2040 // `MaybeConstMaybe` will cause an error during AST validation, but we need to pick a
2041 // placeholder for compilation to proceed.
2042 TraitBoundModifier::MaybeConstMaybe | TraitBoundModifier::Maybe => {
2043 hir::TraitBoundModifier::Maybe
2048 // Helper methods for building HIR.
2050 fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2051 hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2054 fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2055 self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2060 attrs: Option<&'hir [Attribute]>,
2062 init: Option<&'hir hir::Expr<'hir>>,
2063 pat: &'hir hir::Pat<'hir>,
2064 source: hir::LocalSource,
2065 ) -> hir::Stmt<'hir> {
2066 let hir_id = self.next_id();
2067 if let Some(a) = attrs {
2068 debug_assert!(!a.is_empty());
2069 self.attrs.insert(hir_id, a);
2071 let local = hir::Local { hir_id, init, pat, source, span: self.lower_span(span), ty: None };
2072 self.stmt(span, hir::StmtKind::Local(self.arena.alloc(local)))
2075 fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2076 self.block_all(expr.span, &[], Some(expr))
2082 stmts: &'hir [hir::Stmt<'hir>],
2083 expr: Option<&'hir hir::Expr<'hir>>,
2084 ) -> &'hir hir::Block<'hir> {
2085 let blk = hir::Block {
2088 hir_id: self.next_id(),
2089 rules: hir::BlockCheckMode::DefaultBlock,
2090 span: self.lower_span(span),
2091 targeted_by_break: false,
2093 self.arena.alloc(blk)
2096 fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2097 let field = self.single_pat_field(span, pat);
2098 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
2101 fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2102 let field = self.single_pat_field(span, pat);
2103 self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
2106 fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2107 let field = self.single_pat_field(span, pat);
2108 self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2111 fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2112 self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2115 fn single_pat_field(
2118 pat: &'hir hir::Pat<'hir>,
2119 ) -> &'hir [hir::PatField<'hir>] {
2120 let field = hir::PatField {
2121 hir_id: self.next_id(),
2122 ident: Ident::new(sym::integer(0), self.lower_span(span)),
2123 is_shorthand: false,
2125 span: self.lower_span(span),
2127 arena_vec![self; field]
2130 fn pat_lang_item_variant(
2133 lang_item: hir::LangItem,
2134 fields: &'hir [hir::PatField<'hir>],
2135 ) -> &'hir hir::Pat<'hir> {
2136 let qpath = hir::QPath::LangItem(lang_item, self.lower_span(span));
2137 self.pat(span, hir::PatKind::Struct(qpath, fields, false))
2140 fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2141 self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated)
2144 fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, hir::HirId) {
2145 self.pat_ident_binding_mode_mut(span, ident, hir::BindingAnnotation::Unannotated)
2148 fn pat_ident_binding_mode(
2152 bm: hir::BindingAnnotation,
2153 ) -> (&'hir hir::Pat<'hir>, hir::HirId) {
2154 let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2155 (self.arena.alloc(pat), hir_id)
2158 fn pat_ident_binding_mode_mut(
2162 bm: hir::BindingAnnotation,
2163 ) -> (hir::Pat<'hir>, hir::HirId) {
2164 let hir_id = self.next_id();
2169 kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2170 span: self.lower_span(span),
2171 default_binding_modes: true,
2177 fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2178 self.arena.alloc(hir::Pat {
2179 hir_id: self.next_id(),
2181 span: self.lower_span(span),
2182 default_binding_modes: true,
2186 fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2188 hir_id: self.next_id(),
2190 span: self.lower_span(span),
2191 default_binding_modes: false,
2197 mut hir_id: hir::HirId,
2199 qpath: hir::QPath<'hir>,
2200 ) -> hir::Ty<'hir> {
2201 let kind = match qpath {
2202 hir::QPath::Resolved(None, path) => {
2203 // Turn trait object paths into `TyKind::TraitObject` instead.
2205 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2206 let principal = hir::PolyTraitRef {
2207 bound_generic_params: &[],
2208 trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2209 span: self.lower_span(span),
2212 // The original ID is taken by the `PolyTraitRef`,
2213 // so the `Ty` itself needs a different one.
2214 hir_id = self.next_id();
2215 hir::TyKind::TraitObject(
2216 arena_vec![self; principal],
2217 self.elided_dyn_bound(span),
2218 TraitObjectSyntax::None,
2221 _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2224 _ => hir::TyKind::Path(qpath),
2227 hir::Ty { hir_id, kind, span: self.lower_span(span) }
2230 /// Invoked to create the lifetime argument for a type `&T`
2231 /// with no explicit lifetime.
2232 fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
2233 match self.anonymous_lifetime_mode {
2234 // Intercept when we are in an impl header or async fn and introduce an in-band
2236 // Hence `impl Foo for &u32` becomes `impl<'f> Foo for &'f u32` for some fresh
2238 AnonymousLifetimeMode::CreateParameter => {
2239 let fresh_name = self.collect_fresh_in_band_lifetime(span);
2241 hir_id: self.next_id(),
2242 span: self.lower_span(span),
2243 name: hir::LifetimeName::Param(fresh_name),
2247 AnonymousLifetimeMode::ReportError => self.new_error_lifetime(None, span),
2249 AnonymousLifetimeMode::PassThrough => self.new_implicit_lifetime(span),
2253 /// Report an error on illegal use of `'_` or a `&T` with no explicit lifetime;
2254 /// return an "error lifetime".
2255 fn new_error_lifetime(&mut self, id: Option<NodeId>, span: Span) -> hir::Lifetime {
2256 let (id, msg, label) = match id {
2257 Some(id) => (id, "`'_` cannot be used here", "`'_` is a reserved lifetime name"),
2260 self.resolver.next_node_id(),
2261 "`&` without an explicit lifetime name cannot be used here",
2262 "explicit lifetime name needed here",
2266 let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,);
2267 err.span_label(span, label);
2270 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2273 /// Invoked to create the lifetime argument(s) for a path like
2274 /// `std::cell::Ref<T>`; note that implicit lifetimes in these
2275 /// sorts of cases are deprecated. This may therefore report a warning or an
2276 /// error, depending on the mode.
2277 fn elided_path_lifetimes<'s>(
2281 ) -> impl Iterator<Item = hir::Lifetime> + Captures<'a> + Captures<'s> + Captures<'hir> {
2282 (0..count).map(move |_| self.elided_path_lifetime(span))
2285 fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime {
2286 match self.anonymous_lifetime_mode {
2287 AnonymousLifetimeMode::CreateParameter => {
2288 // We should have emitted E0726 when processing this path above
2290 .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error");
2291 let id = self.resolver.next_node_id();
2292 self.new_named_lifetime(id, span, hir::LifetimeName::Error)
2294 // `PassThrough` is the normal case.
2295 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
2296 // is unsuitable here, as these can occur from missing lifetime parameters in a
2297 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
2298 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
2299 // later, at which point a suitable error will be emitted.
2300 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
2301 self.new_implicit_lifetime(span)
2306 /// Invoked to create the lifetime argument(s) for an elided trait object
2307 /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2308 /// when the bound is written, even if it is written with `'_` like in
2309 /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2310 fn elided_dyn_bound(&mut self, span: Span) -> hir::Lifetime {
2311 match self.anonymous_lifetime_mode {
2312 // NB. We intentionally ignore the create-parameter mode here.
2313 // and instead "pass through" to resolve-lifetimes, which will apply
2314 // the object-lifetime-defaulting rules. Elided object lifetime defaults
2315 // do not act like other elided lifetimes. In other words, given this:
2317 // impl Foo for Box<dyn Debug>
2319 // we do not introduce a fresh `'_` to serve as the bound, but instead
2320 // ultimately translate to the equivalent of:
2322 // impl Foo for Box<dyn Debug + 'static>
2324 // `resolve_lifetime` has the code to make that happen.
2325 AnonymousLifetimeMode::CreateParameter => {}
2327 AnonymousLifetimeMode::ReportError => {
2328 // ReportError applies to explicit use of `'_`.
2331 // This is the normal case.
2332 AnonymousLifetimeMode::PassThrough => {}
2335 let r = hir::Lifetime {
2336 hir_id: self.next_id(),
2337 span: self.lower_span(span),
2338 name: hir::LifetimeName::ImplicitObjectLifetimeDefault,
2340 debug!("elided_dyn_bound: r={:?}", r);
2344 fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime {
2346 hir_id: self.next_id(),
2347 span: self.lower_span(span),
2348 name: hir::LifetimeName::Implicit,
2352 fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) {
2353 // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
2354 // call site which do not have a macro backtrace. See #61963.
2355 let is_macro_callsite = self
2358 .span_to_snippet(span)
2359 .map(|snippet| snippet.starts_with("#["))
2361 if !is_macro_callsite {
2362 if span.edition() < Edition::Edition2021 {
2363 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
2367 "trait objects without an explicit `dyn` are deprecated",
2368 BuiltinLintDiagnostics::BareTraitObject(span, is_global),
2371 let msg = "trait objects must include the `dyn` keyword";
2372 let label = "add `dyn` keyword before this trait";
2373 let mut err = struct_span_err!(self.sess, span, E0782, "{}", msg,);
2374 err.span_suggestion_verbose(
2375 span.shrink_to_lo(),
2377 String::from("dyn "),
2378 Applicability::MachineApplicable,
2386 /// Helper struct for delayed construction of GenericArgs.
2387 struct GenericArgsCtor<'hir> {
2388 args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2389 bindings: &'hir [hir::TypeBinding<'hir>],
2390 parenthesized: bool,
2394 impl<'hir> GenericArgsCtor<'hir> {
2395 fn is_empty(&self) -> bool {
2396 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
2399 fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2400 let ga = hir::GenericArgs {
2401 args: this.arena.alloc_from_iter(self.args),
2402 bindings: self.bindings,
2403 parenthesized: self.parenthesized,
2404 span_ext: this.lower_span(self.span),
2406 this.arena.alloc(ga)
2410 fn lifetimes_from_impl_trait_bounds(
2411 opaque_ty_id: NodeId,
2412 bounds: hir::GenericBounds<'_>,
2413 lifetimes_to_include: Option<&FxHashSet<hir::LifetimeName>>,
2414 ) -> Vec<(hir::LifetimeName, Span)> {
2416 "lifetimes_from_impl_trait_bounds(opaque_ty_id={:?}, \
2418 opaque_ty_id, bounds,
2421 // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
2422 // appear in the bounds, excluding lifetimes that are created within the bounds.
2423 // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
2424 struct ImplTraitLifetimeCollector<'r> {
2425 collect_elided_lifetimes: bool,
2426 currently_bound_lifetimes: Vec<hir::LifetimeName>,
2427 already_defined_lifetimes: FxHashSet<hir::LifetimeName>,
2428 lifetimes: Vec<(hir::LifetimeName, Span)>,
2429 lifetimes_to_include: Option<&'r FxHashSet<hir::LifetimeName>>,
2432 impl<'r, 'v> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r> {
2433 type Map = intravisit::ErasedMap<'v>;
2435 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
2436 intravisit::NestedVisitorMap::None
2439 fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) {
2440 // Don't collect elided lifetimes used inside of `Fn()` syntax.
2441 if parameters.parenthesized {
2442 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2443 self.collect_elided_lifetimes = false;
2444 intravisit::walk_generic_args(self, span, parameters);
2445 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2447 intravisit::walk_generic_args(self, span, parameters);
2451 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
2452 // Don't collect elided lifetimes used inside of `fn()` syntax.
2453 if let hir::TyKind::BareFn(_) = t.kind {
2454 let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
2455 self.collect_elided_lifetimes = false;
2457 // Record the "stack height" of `for<'a>` lifetime bindings
2458 // to be able to later fully undo their introduction.
2459 let old_len = self.currently_bound_lifetimes.len();
2460 intravisit::walk_ty(self, t);
2461 self.currently_bound_lifetimes.truncate(old_len);
2463 self.collect_elided_lifetimes = old_collect_elided_lifetimes;
2465 intravisit::walk_ty(self, t)
2469 fn visit_poly_trait_ref(
2471 trait_ref: &'v hir::PolyTraitRef<'v>,
2472 modifier: hir::TraitBoundModifier,
2474 // Record the "stack height" of `for<'a>` lifetime bindings
2475 // to be able to later fully undo their introduction.
2476 let old_len = self.currently_bound_lifetimes.len();
2477 intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
2478 self.currently_bound_lifetimes.truncate(old_len);
2481 fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) {
2482 // Record the introduction of 'a in `for<'a> ...`.
2483 if let hir::GenericParamKind::Lifetime { .. } = param.kind {
2484 // Introduce lifetimes one at a time so that we can handle
2485 // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
2486 let lt_name = hir::LifetimeName::Param(param.name);
2487 self.currently_bound_lifetimes.push(lt_name);
2490 intravisit::walk_generic_param(self, param);
2493 fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
2494 let name = match lifetime.name {
2495 hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
2496 if self.collect_elided_lifetimes {
2497 // Use `'_` for both implicit and underscore lifetimes in
2498 // `type Foo<'_> = impl SomeTrait<'_>;`.
2499 hir::LifetimeName::Underscore
2504 hir::LifetimeName::Param(_) => lifetime.name,
2506 // Refers to some other lifetime that is "in
2507 // scope" within the type.
2508 hir::LifetimeName::ImplicitObjectLifetimeDefault => return,
2510 hir::LifetimeName::Error | hir::LifetimeName::Static => return,
2513 if !self.currently_bound_lifetimes.contains(&name)
2514 && !self.already_defined_lifetimes.contains(&name)
2515 && self.lifetimes_to_include.map_or(true, |lifetimes| lifetimes.contains(&name))
2517 self.already_defined_lifetimes.insert(name);
2519 self.lifetimes.push((name, lifetime.span));
2524 let mut lifetime_collector = ImplTraitLifetimeCollector {
2525 collect_elided_lifetimes: true,
2526 currently_bound_lifetimes: Vec::new(),
2527 already_defined_lifetimes: FxHashSet::default(),
2528 lifetimes: Vec::new(),
2529 lifetimes_to_include,
2532 for bound in bounds {
2533 intravisit::walk_param_bound(&mut lifetime_collector, &bound);
2536 lifetime_collector.lifetimes