permit coercion in type ascription #78248
Labels
A-coercions
Area: implicit and explicit `expr as Type` coercions
A-type-system
Area: Type system
T-compiler
Relevant to the compiler team, which will review and decide on the PR/issue.
T-types
Relevant to the types team, which will review and decide on the PR/issue.
The current implementation of type ascription always equates the type of the expression with the required type (so
e: T
would forcee
to have typeT
). But the original plan was that type ascription would also permit coercions, so that one could do e.g.return x: &dyn Foo
and coercex
to the typedyn Foo
explicitly.The challenge is that we can't always permit coercions because that would be unsound. In particular it would cause problems in contexts where references are being created, such as
&mut (x: T)
. This is because the reference that results would actually referencex
, sincex: T
is defined to be a "place expression" just likex
is. The problem then is that if the type ofx
and the typeT
are not the same, this permits unsoundness:The fix proposed in the original RFC was to force coercion to do type equality in reference contexts. But rust-lang/rfcs#2623 proposed a simpler formulation. The idea is this: we already have a notion of coercion contexts where coercion can occur. If we are typing the expression E in a coercion context, and E is an ascription expression
E1: T
, then we coerce the type ofE1
toT
.To implement this, I think the idea would be to intercept the function
check_expr_coercable_to_type
and look to see if the expression is an ascription expression. If so, we would recursively invokecheck_expr_coercable_to_type
on the inner expression. This might be kind of a pain in terms of duplicating code, though, so it might be better to thread the info down tocheck_expr_with_expectation
or something like that (maybe add a new kind ofExpectation
).The text was updated successfully, but these errors were encountered: