Skip to content

refactor impl trait to model abstract type a bit better #44727

Closed
@nikomatsakis

Description

@nikomatsakis

After some discussion with @cramertj, I wanted to write up a rough idea for how to represent impl Trait in the HIR etc. The key idea is to move towards a place where we represent the abstract type that an impl Trait conceptually desugars to as a distinct "item" in the HIR.

Today, for each usage of impl Trait, we create a def-id, which basically represents the abstract type behind the impl Trait. However, in the HIR itself, we continue to mirror the syntax, so for example the variant for ImplTrait includes the bounds listed inline. This is not I think what we really want.

The refactoring then is to do the following:

  • Add to the hir::Crate a "abstract type" vector sort of like the list of bodies.
  • Add a hir::AbstractType struct that contains the following:
    • A scope (which is the def-id of some item)
    • A list of generics (types, lifetimes)
    • A list of bounds
  • Modify the ImplTrait variant of hir::Ty with to include a "list of substs" in some form (and not have bounds)
  • During HIR lowering:
    • track the generics that are in scope at any given item
    • when we encounter an impl trait, we create and push a hir::AbstractType:
      • scope is the enclosing item
      • clone the generics that are in scope to serve as the list of generics
      • move the list of bounds from the ast::Ty into the hir::AbstractType
    • generate the hir::ImplTrait(DefId, [T, 'a]) where the "substs" are references to all the lifetimse/types in scope (I'm not entirely sure how best to represent and synthesize those?)
  • If we do this right:
    • Region name resolution will basically just work, and in particular there is no need to worry about early- vs late-bound resolution.
    • When we add first class abstract types, they can build on this same data structure
      • we'll have to solve the unification problems of course =)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-trait-systemArea: Trait systemC-cleanupCategory: PRs that clean code up or issues documenting cleanup.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.WG-traitsWorking group: Traits, https://internals.rust-lang.org/t/announcing-traits-working-group/6804

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions