www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 24335] New: Class Downcast

https://issues.dlang.org/show_bug.cgi?id=24335

          Issue ID: 24335
           Summary: Class Downcast
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: bugzilla digitalmars.com

deadalnix writes:

Currently, we use a linear algorithm to downcast and we reach this algorithm
via a call int he runtime. This prevent the optimizer from doing anything about
it, in addition to be slow. The problem is similar to 1/. The whole check can
be made trivial if we let the compiler prebake some data for us, namely an
array of primary parents. Let's see what it looks like in the first example,
when b is not final.

class A {}
class B : A {}

auto foo(A a) {
    return cast(B) a;
}
Which we can do as follow:

auto foo(A a) {
    // The primaries generated by the compiler for us.
    auto tidA = typeid(A);
    assert(tidA.primaries = [tidA]);
    auto tidB = typeid(B);
    assert(tidB.primaries = [tidA, tidB]);

    auto t = typeid(a);
    auto depth = tidB.primaries.length - 1;

    if (t.primary.length <= depth) {
        return null;
    }

    if (t.primary[depth] == tidB) {
        return a;
    }

    return null;
}

This is starting to look good, now we have general downcast in a form that is
not only really fast to perform, but also completely transparent to the
optimizer.

https://forum.dlang.org/post/hteuczyclxajakrisxjd forum.dlang.org

--
Jan 11