Skip to content

structural match for TypeId - #166205

Open
soqb wants to merge 7 commits into
rust-lang:mainfrom
soqb:typeid-structural-match
Open

soqb wants to merge 7 commits into
rust-lang:mainfrom
soqb:typeid-structural-match

Conversation

@soqb

@soqb soqb commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

View all comments

Supports StructuralPartialEq and ConstParamTy_ for std::any::TypeId, behind feature(type_id_structural_match).

Background

Needed this while doing something silly & experimental. See tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs for why I found this useful.

Not sure if this is really RFC-worthy. I am happy to write one quickly, but since I already had the branch ready, I thought I might as well make the PR. Happy to close this now if that is more appropriate.

Solution

The problem with putting TypeId into valtrees is provenance. Currently, TypeId stores pointers which are nothing more than integers at runtime, but are annotated with special type-specific provenance during CTFE, so that comptime shenanigans can recover the Ty from a TypeId.

To solve this, I just put a new variant on ValTreeKind, which keeps track of the Ty it is for. This was surprisingly easy to do, but is probably not a great precedent to set. If we do ever want TypeId in valtrees, I think this is all but unavoidable.

For valtree-to-pattern, the same approach as str is taken. Make references to the scrutinee and pattern constant and then compare them with PartialEq::eq.

The actual library impls are gated behind unstable_feature_bound. I don't think that causes problems here, but I'm not very familiar with how it works.

Problems

I'm not sure that I took the correct approach to symbol mangling. Currently, the bits of the hash are printed out as a u128, but that might not be appropriate stability-wise. I suppose the only other thing we can do is print out the actual type it represents, but I ran into issues with demangling that I had no idea how to solve.

@rustbot

rustbot commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

Some changes occurred in compiler/rustc_sanitizers

cc @rcvalle

Some changes occurred in match checking

cc @Nadrieril

Some changes occurred in match lowering

cc @Nadrieril

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri

Some changes occurred to the CTFE machinery

cc @RalfJung, @oli-obk, @lcnr

changes to the core type system

cc @lcnr

@rustbot rustbot added PG-exploit-mitigations Project group: Exploit mitigations S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Nov 19, 2026
@rustbot

rustbot commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

r? @dingxiangfei2009

rustbot has assigned @dingxiangfei2009.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler
  • compiler expanded to 79 candidates
  • Random selection from 19 candidates


let s: &[u8] = &[0; {
match TypeId::of::<u8>() {
A => 1,

@RalfJung RalfJung Nov 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The recommended pattern for non-structural-eq types is:

Suggested change
A => 1,
id if id == A => 1,

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry, i'm not sure what's being suggested here. as of this PR, TypeId: StructuralPartialEq so this match is legal.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am suggesting an alternative that avoids the need for this PR. :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, i see! well ConstParamTy_: StructuralPartialEq so that doesn't itself elide this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

although it's true that the unstable impls and const-patterns changes are somewhat orthogonal to the valtree change, since one can just feature(const_param_ty_unchecked) everything, and so it's possible this could be split out into two PRs.

@RalfJung

Copy link
Copy Markdown
Member

Thanks for the PR! However, a new ValTreeKind is too heavy a hammer for something "silly", I think.

///
/// Also stores an inner type which transparently contains some representation of the bits of the `TypeId`.
/// Currently, this is just `(u128,)` but this is not to be relied upon.
TypeId(I::Ty, I::Consts),

@RalfJung RalfJung Nov 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 2nd field is redundant, so if we did this I think we should not have a 2nd field here.

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unfortunately, this is not true since symbol mangling (among other things) wants something tangible. i would love not to need this, but i haven't found a working alternative.

@soqb

soqb commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

a new ValTreeKind is too heavy a hammer for something "silly", I think.

Is there a better way to preserve provenance through valtrees? I'm not massively comfortable with this solution either.

I completely agree that we shouldn't merge a PR based on the whim of one user (especially for something "silly"), but I have been imagining the feature has value in its own right.

Consider that the hammer is heavy, but the diff is small.

@rust-log-analyzer

This comment has been minimized.

@soqb
soqb force-pushed the typeid-structural-match branch from 0ec6c78 to 1178d3f Compare November 19, 2026 14:43
@theemathas

Copy link
Copy Markdown
Contributor

While an RFC isn't required, I do think that this probably should go through the ACP process.

@RalfJung

Copy link
Copy Markdown
Member

This is not a libs feature, so ACP doesn't apply. We could consider MCP.

@RalfJung

Copy link
Copy Markdown
Member

Consider that the hammer is heavy, but the diff is small.

The size of the diff is not always a good measure for the cost of a PR.

Let's see what @oli-obk and @BoxyUwU think.

@oli-obk

oli-obk commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

😄 fun! cc @yara-blue @Tess4552

I'll think about this next week

Comment on lines +13 to +20
macro_rules! arbitrary_const_value {
() => {
const {
enum Arbitrary {}
Value { disambiguator: TypeId::of::<Arbitrary>() }
}
}
}

@Nadrieril Nadrieril Nov 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do agree this is very cute, but this is also less powerful than I initially thought: since we get one fresh type per macro invocation, this is basically a glorified hash of the span of the macro call. One could hash the output of core::panic::Location::caller with basically the same results. So I wonder what you can actually use this for?

View changes since the review

@soqb soqb Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One could hash the output of core::panic::Location::caller with basically the same results.

not really... it should be called unique_const_value, i guess. for my use case, the equivalent of arbitrary_const_value is publicly-accessible and its uniqueness is relied upon for soundness: they are used to represent local variables, so two invocations being unexpectedly equal would introduce aliasing problems.

how would you implement the following soundly with Location::caller?

macro_rules! thing {
    () => {
        if const { arbitrary_const_value!() == arbitrary_const_value!() } {
            unsafe { unreachable_unchecked() } 
        }
    );
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the best i can conceive of without this feature is a proc macro which spits out a random number on every invocation, which uhh. no thanks.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how would you implement the following soundly with Location::caller?

Are you talking about hash collisions, or? I would just have arbitrary_const_value!() expand to a const block that calls Location::caller and hashes the result (well Hash is a trait so I guess this needs const traits oops). In fact you could hash your TypeId::of<LocalEnum>() too. Proc macro that returns a random value is also semantically equivalent as far as I'm concerned.

My question remains: what would you use this API for? I understand wanting a unique token generator when the token is unique every time a function is called; I'm less sure about a token that's unique per source location.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the Location version would reach the unreachable_unchecked expression since they would both evaluate to the same call site. that is not true of the TypeId version since the types would be distinct.

the only sound way to hash a TypeId is with Hash which is very much not const.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no worries! i take the point about PartialEq not saving you, it seems no-one is sure whether that's a reasonable concern or not. although note that here, it would be fine since the CTFE version of TypeId::eq just compares the actual compiler Ty values so the api in the playground above would be totally sound!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well fair, though PartialEq doesn't fully save you either since at runtime it's using a hash too. With your PR though it's using real types so you get true soundness guarantees, which is pleasant.

At the same time it is highly suspicious, because it means that valtree equality does not agree with PartialEq. So far that was a hard constraint that we imposed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it means that valtree equality does not agree with PartialEq

TypeId::eq defers to an intrinsic which, during const eval, will dig up and compare the Tys directly. this implementation is the only way valtree equality can exactly match PartialEq.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem is that it does not match runtime PartialEq.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does in practice tho? If there is a hash collision at codegen time, the build ices, so hash equality and type_id_eq are the same in behaviour

@Tess4552

Copy link
Copy Markdown
Contributor

As Ty's are interened could we not store the interned item hash from Ty as a valtree scalar? Would save on adding a ValTreeKind I think. Unsure how to handle symbol mangling using this approach though.

In regards to adding back StructuralPartialEq at runtime to TypeId, Are the concerns previously raised in #77125 still relevant?

@soqb

soqb commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

As Ty's are interened could we not store the interned item hash from Ty as a valtree scalar?

you mean the hash from out of the InternedSet hashtable itself? that would not be sufficient to lookup TypeIds. given the possibility of a collision, we must always fall back to Eq on hashtable lookups.

In regards to adding back StructuralPartialEq at runtime to TypeId, Are the concerns previously raised in #77125 still relevant?

i don't think so. we can commit to TypeId: StructuralPartialEq since this PR ensures that pattern matching always matches PartialEq1. whether we want to is a seperate language question, hence the need for the feature flag.

the comment you mention is from #77125 (aug '22), the (deliberate) removal of TypeId: StructuralPartialEq came in #103291 (may '23), and TypeId: const PartialEq came in #142789 (july '25). i think things have evolved quite significantly.

Footnotes

  1. note that runtime PartialEq::eq does not actually match const-eval PartialEq::eq, but they are the same "up to soundness", in the sense that if they disagree (i.e., a hash collision giving a runtime false-positive) then soundness will always be trivially exploitable in another way (<dyn Any>::downcast_ref, for example). ↩

@rust-bors

This comment has been minimized.

@soqb
soqb force-pushed the typeid-structural-match branch from 1178d3f to 46dfb64 Compare November 23, 2026 21:23
@rustbot

rustbot commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@Tess4552

Tess4552 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

A, I see, yes. Agree that adding a new variant to the Valtree makes sense if structural matching on TypeId is added.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

PG-exploit-mitigations Project group: Exploit mitigations S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants