Skip to content

Conversation

BobTheBuidler
Copy link
Contributor

This PR adds CastExpr support to constant_fold_expr since its just a noop

This comment has been minimized.

@BobTheBuidler BobTheBuidler changed the title [mypyc] feat: add CastExpr support to constant_fold_expr [1/1] feat: add CastExpr support to constant_fold_expr [1/1] Oct 2, 2025
Copy link
Collaborator

@JukkaL JukkaL left a comment

Choose a reason for hiding this comment

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

cast is supposed to raise a TypeError if the target type is not compatible, and it's also expected to change the type of the value. I think this needs to be more a bit more complex to fully preserve semantics. Do you have a real-world use case where this would help? If not, due to the subtleties I mentioned this may not be worth it.

@BobTheBuidler
Copy link
Contributor Author

BobTheBuidler commented Oct 2, 2025

Yes, I use a dependency that uses a bunch of NewType types that have chain inheritance

Example of shallow chain inheritance:

CoolString = NewType("CoolString", str)
SpecialString = NewType("SpecialString", CoolString)

so if you want to go from a str to a SpecialString, you have 2 choices:

my_sad_normal_string = ":("
special = SpecialString(CoolString(my_sad_normal_string))
my_sad_normal_string = ":("
special = cast(SpecialString, my_sad_normal_string)

I prefer the latter since its less verbose

Sometimes these casts take place when assigning values to Final vars, so imo they're a good candidate for folding. Even if nobody else cares, it definitely helps me personally! :D

What if we only constant fold in cases where we can ensure no type collisions?

easy logic would be to unwrap new types and ensure the base type matches, bail out in all other cases. This seems safe to do in all cases I can think of.

more advanced logic could probably be implemented to cover other cases. I think we could match on rprimitive type without risking safety, (with the exception of object_rprimitive, which we should bail on), but that might be unnecessary? I want to think about it a little more.

@BobTheBuidler
Copy link
Contributor Author

Let's put this on hold until #19982 is merged, so I can use the @folding_candidate decorator

@BobTheBuidler BobTheBuidler marked this pull request as draft October 2, 2025 19:53
@BobTheBuidler
Copy link
Contributor Author

Maybe its the case that this particular folding makes sense for mypyc but not for mypy itself

Copy link
Contributor

github-actions bot commented Oct 3, 2025

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants