D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6316 - Regression(2.054): Class downcast is rejected in @safe code
Summary: Regression(2.054): Class downcast is rejected in @safe code
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords: patch, rejects-valid
Depends on:
Blocks:
 
Reported: 2011-07-14 06:30 UTC by Harry Vennik
Modified: 2011-07-15 16:19 UTC (History)
3 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Harry Vennik 2011-07-14 06:30:27 UTC
The D language specification does not forbid downcasting in @safe code, but the compiler rejects it. Downcasting is actually safe because such casts are checked run-time.

The minimal testcase is:

------- CODE -------
class A { }
class B : A { }

@safe void main()
{
    A a = new A();
    B b = cast(B) a;
}
----- END CODE -----


The above code is rejected by the compiler with the following message:
safe_downcast.d(7): Error: cast from safe_downcast.A to safe_downcast.B not allowed in safe code



Possible enhancement: make DMD issue a warning if the result of a downcast is not checked for null.
Comment 1 kennytm 2011-07-14 06:46:17 UTC
You should use std.conv.to, and then in Phobos the toImpl specialization

T toImpl(T, S)(S value)
    if (!isImplicitlyConvertible!(S, T) &&
        is(S : Object) && !is(typeof(value.opCast!T()) : T) &&
        is(T : Object) && !is(typeof(new T(value))))

should be made @trusted.