-
-
Notifications
You must be signed in to change notification settings - Fork 14.7k
permit coercion in type ascription #78248
Copy link
Copy link
Open
Labels
A-coercionsArea: implicit and explicit `expr as Type` coercionsArea: implicit and explicit `expr as Type` coercionsA-type-systemArea: Type systemArea: Type systemT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.Relevant to the types team, which will review and decide on the PR/issue.
Metadata
Metadata
Assignees
Labels
A-coercionsArea: implicit and explicit `expr as Type` coercionsArea: implicit and explicit `expr as Type` coercionsA-type-systemArea: Type systemArea: Type systemT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.Relevant to the types team, which will review and decide on the PR/issue.
Type
Fields
Give feedbackNo fields configured for issues without a type.
The current implementation of type ascription always equates the type of the expression with the required type (so
e: Twould forceeto have typeT). But the original plan was that type ascription would also permit coercions, so that one could do e.g.return x: &dyn Fooand coercexto the typedyn Fooexplicitly.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: Tis defined to be a "place expression" just likexis. The problem then is that if the type ofxand the typeTare 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 ofE1toT.To implement this, I think the idea would be to intercept the function
check_expr_coercable_to_typeand look to see if the expression is an ascription expression. If so, we would recursively invokecheck_expr_coercable_to_typeon 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_expectationor something like that (maybe add a new kind ofExpectation).