Skip to content

permit coercion in type ascription #78248

Open
@nikomatsakis

Description

@nikomatsakis

The current implementation of type ascription always equates the type of the expression with the required type (so e: T would force e to have type T). But the original plan was that type ascription would also permit coercions, so that one could do e.g. return x: &dyn Foo and coerce x to the type dyn 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 reference x, since x: T is defined to be a "place expression" just like x is. The problem then is that if the type of x and the type T are not the same, this permits unsoundness:

let mut x: &'static u32 = &22;
let y = 44;
let p = &mut (x:&T); // here we coerce to a shorter lifetime
*p = &y;

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 of E1 to T.

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 invoke check_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 to check_expr_with_expectation or something like that (maybe add a new kind of Expectation).

Metadata

Metadata

Assignees

Labels

A-coercionsArea: implicit and explicit `expr as Type` coercionsA-type-systemArea: Type systemT-compilerRelevant 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.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions