summaryrefslogtreecommitdiff
path: root/libphobos/src/std/experimental/typecons.d
blob: 46e21e77e7a4ed35a33dd6f6b763bc8ae1444b16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
// Written in the D programming language.

/**
This module implements experimental additions/modifications to $(MREF std, typecons).

Use this module to test out new functionality for $(REF wrap, std, typecons)
which allows for a struct to be wrapped against an interface; the
implementation in $(MREF std, typecons) only allows for classes to use the wrap
functionality.

Source:    $(PHOBOSSRC std/experimental/typecons.d)

Copyright: Copyright the respective authors, 2008-
License:   $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors:   $(HTTP erdani.org, Andrei Alexandrescu),
           $(HTTP bartoszmilewski.wordpress.com, Bartosz Milewski),
           Don Clugston,
           Shin Fujishiro,
           Kenji Hara
 */
module std.experimental.typecons;

import std.meta; // : AliasSeq, allSatisfy;
import std.traits;

import std.typecons : Tuple, tuple, Bind, DerivedFunctionType, GetOverloadedMethods;

private
{
    pragma(mangle, "_d_toObject")
    extern(C) pure nothrow Object typecons_d_toObject(void* p);
}

/*
 * Avoids opCast operator overloading.
 */
private template dynamicCast(T)
if (is(T == class) || is(T == interface))
{
    @trusted
    T dynamicCast(S)(inout S source)
    if (is(S == class) || is(S == interface))
    {
        static if (is(Unqual!S : Unqual!T))
        {
            import std.traits : QualifierOf;
            alias Qual = QualifierOf!S; // SharedOf or MutableOf
            alias TmpT = Qual!(Unqual!T);
            inout(TmpT) tmp = source;   // bypass opCast by implicit conversion
            return *cast(T*)(&tmp);     // + variable pointer cast + dereference
        }
        else
        {
            return cast(T) typecons_d_toObject(*cast(void**)(&source));
        }
    }
}

@system unittest
{
    class C { @disable void opCast(T)(); }
    auto c = new C;
    static assert(!__traits(compiles, cast(Object) c));
    auto o = dynamicCast!Object(c);
    assert(c is o);

    interface I { @disable void opCast(T)(); Object instance(); }
    interface J { @disable void opCast(T)(); Object instance(); }
    class D : I, J { Object instance() { return this; } }
    I i = new D();
    static assert(!__traits(compiles, cast(J) i));
    J j = dynamicCast!J(i);
    assert(i.instance() is j.instance());
}

/*
 * Determines if the `Source` type satisfies all interface requirements of
 * `Targets`.
 */
private template implementsInterface(Source, Targets...)
if (Targets.length >= 1 && allSatisfy!(isMutable, Targets))
{
    import std.meta : staticMap;

    // strict upcast
    bool implementsInterface()()
    if (Targets.length == 1 && is(Source : Targets[0]))
    {
        return true;
    }
    // structural upcast
    template implementsInterface()
    if (!allSatisfy!(Bind!(isImplicitlyConvertible, Source), Targets))
    {
        auto implementsInterface()
        {
            return hasRequiredMethods!();
        }

        // list of FuncInfo
        alias TargetMembers = UniqMembers!(ConcatInterfaceMembers!Targets);
        // list of function symbols
        alias SourceMembers = GetOverloadedMethods!Source;

        // Check whether all of SourceMembers satisfy covariance target in
        // TargetMembers
        template hasRequiredMethods(size_t i = 0)
        {
            static if (i >= TargetMembers.length)
                enum hasRequiredMethods = true;
            else
            {
                enum foundFunc = findCovariantFunction!(TargetMembers[i], Source, SourceMembers);

                version (StdUnittest) {}
                else debug
                {
                    static if (foundFunc == -1)
                        pragma(msg, "Could not locate matching function for: ",
                               TargetMembers[i].stringof);
                }

                enum hasRequiredMethods =
                    foundFunc != -1 &&
                    hasRequiredMethods!(i + 1);
            }
        }
    }
}
// ditto
private template implementsInterface(Source, Targets...)
if (Targets.length >= 1 && !allSatisfy!(isMutable, Targets))
{
    import std.meta : staticMap;

    alias implementsInterface = .implementsInterface!(Source, staticMap!(Unqual, Targets));
}

@safe unittest
{
    interface Foo {
        void foo();
    }
    interface Bar {
        void bar();
    }
    interface FooBar : Foo, Bar {
        void foobar();
    }

    struct A {
        void foo() {}
    }
    struct B {
        void bar() {}
        void foobar() {}
    }
    class C {
        void foo() {}
        void bar() {}
    }
    struct D {
        void foo() {}
        void bar() {}
        void foobar() {}
    }
    // Implements interface
    static assert(implementsInterface!(A, Foo));
    static assert(implementsInterface!(A, const(Foo)));
    static assert(implementsInterface!(A, immutable(Foo)));
    // Doesn't implement interface
    static assert(!implementsInterface!(B, Foo));
    static assert(implementsInterface!(B, Bar));
    // Implements both interfaces
    static assert(implementsInterface!(C, Foo));
    static assert(implementsInterface!(C, Bar));
    static assert(implementsInterface!(C, Foo, Bar));
    static assert(implementsInterface!(C, Foo, const(Bar)));
    static assert(!implementsInterface!(A, Foo, Bar));
    static assert(!implementsInterface!(A, Foo, immutable(Bar)));
    // Implements inherited
    static assert(implementsInterface!(D, FooBar));
    static assert(!implementsInterface!(B, FooBar));
}

private enum isInterface(ConceptType) = is(ConceptType == interface);

///
template wrap(Targets...)
if (Targets.length >= 1 && allSatisfy!(isInterface, Targets))
{
    import std.meta : ApplyLeft, staticMap;

    version (StdDdoc)
    {
        /**
         * Wrap src in an anonymous class implementing $(D_PARAM Targets).
         *
         * wrap creates an internal wrapper class which implements the
         * interfaces in `Targets` using the methods of `src`, then returns a
         * GC-allocated instance of it.
         *
         * $(D_PARAM Source) can be either a `class` or a `struct`, but it must
         * $(I structurally conform) with all the $(D_PARAM Targets)
         * interfaces; i.e. it must provide concrete methods with compatible
         * signatures of those in $(D_PARAM Targets).
         *
         * If $(D_PARAM Source) is a `struct` then wrapping/unwrapping will
         * create a copy; it is not possible to affect the original `struct`
         * through the wrapper.
         *
         * The returned object additionally supports $(LREF unwrap).
         *
         * Note:
         * If $(D_PARAM Targets) has only one entry and $(D_PARAM Source) is a
         * class which explicitly implements it, wrap simply returns src
         * upcasted to `Targets[0]`.
         *
         * Bugs:
         * wrap does not support interfaces which take their own type as either
         * a parameter type or return type in any of its methods.
         *
         * See_Also: $(LREF unwrap) for examples
         */
        auto wrap(Source)(inout Source src)
            if (implementsInterface!(Source, Targets));
    }

    static if (!allSatisfy!(isMutable, Targets))
        alias wrap = .wrap!(staticMap!(Unqual, Targets));
    else
    {
        // strict upcast
        auto wrap(Source)(inout Source src)
        if (Targets.length == 1 && is(Source : Targets[0]))
        {
            alias T = Select!(is(Source == shared), shared Targets[0], Targets[0]);
            return dynamicCast!(inout T)(src);
        }

        // structural upcast
        template wrap(Source)
        if (!allSatisfy!(ApplyLeft!(isImplicitlyConvertible, Source), Targets))
        {
            auto wrap(inout Source src)
            {
                static assert(implementsInterface!(Source, Targets),
                              "Source "~Source.stringof~
                              " does not have structural conformance to "~
                              Targets.stringof);

                alias T = Select!(is(Source == shared), shared Impl, Impl);
                return new inout T(src);
            }

            // list of FuncInfo
            alias TargetMembers = UniqMembers!(ConcatInterfaceMembers!(Targets));
            // list of function symbols
            alias SourceMembers = GetOverloadedMethods!Source;

            static if (is(Source == class) || is(Source == interface))
                alias StructuralType = Object;
            else static if (is(Source == struct))
                alias StructuralType = Source;

            // Check whether all of SourceMembers satisfy covariance target in TargetMembers
            // Internal wrapper class
            final class Impl : Structural!StructuralType, Targets
            {
            private:
                Source _wrap_source;

                this(       inout Source s)        inout @safe pure nothrow { _wrap_source = s; }
                this(shared inout Source s) shared inout @safe pure nothrow { _wrap_source = s; }

                static if (is(Source == class) || is(Source == interface))
                {
                    // BUG: making private should work with NVI.
                    protected inout(Object) _wrap_getSource() inout @safe
                    {
                        return dynamicCast!(inout Object)(_wrap_source);
                    }
                }
                else
                {
                    // BUG: making private should work with NVI.
                    protected inout(Source) _wrap_getSource() inout @safe
                    {
                        return _wrap_source;
                    }
                }

                import std.conv : to;
                import core.lifetime : forward;
                template generateFun(size_t i)
                {
                    enum name = TargetMembers[i].name;
                    enum fa = functionAttributes!(TargetMembers[i].type);
                    static args(int num)()
                    {
                        string r;
                        bool first = true;
                        foreach (i; 0 .. num)
                        {
                            import std.conv : to;
                            r ~= (first ? "" : ", ") ~ " a" ~ (i+1).to!string;
                            first = false;
                        }
                        return r;
                    }
                    static if (fa & FunctionAttribute.property)
                    {
                        static if (Parameters!(TargetMembers[i].type).length == 0)
                            enum fbody = "_wrap_source."~name;
                        else
                            enum fbody = "_wrap_source."~name~" = a1";
                    }
                    else
                    {
                            enum fbody = "_wrap_source."~name~"("~args!(Parameters!(TargetMembers[i].type).length)~")";
                    }
                    enum generateFun =
                        "override "~wrapperSignature!(TargetMembers[i]) ~
                        "{ return "~fbody~"; }";
                }

            public:
                static foreach (i; 0 .. TargetMembers.length)
                    mixin(generateFun!i);
            }
        }
    }
}

// Build a signature that matches the provided function
// Each argument will be provided a name in the form a#
private template wrapperSignature(alias fun)
{
    enum name = fun.name;
    enum fa = functionAttributes!(fun.type);
    static @property stc()
    {
        string r;
        if (fa & FunctionAttribute.property)    r ~= "@property ";
        if (fa & FunctionAttribute.ref_)        r ~= "ref ";
        if (fa & FunctionAttribute.pure_)       r ~= "pure ";
        if (fa & FunctionAttribute.nothrow_)    r ~= "nothrow ";
        if (fa & FunctionAttribute.trusted)     r ~= "@trusted ";
        if (fa & FunctionAttribute.safe)        r ~= "@safe ";
        return r;
    }
    static @property mod()
    {
        alias type = AliasSeq!(fun.type)[0];
        string r;
        static if (is(type == immutable))       r ~= " immutable";
        else
        {
            static if (is(type == shared))      r ~= " shared";
            static if (is(type == const))       r ~= " const";
            else static if (is(type == inout))  r ~= " inout";
            //else  --> mutable
        }
        return r;
    }
    alias param = Parameters!(fun.type);
    static @property wrapperParameters()
    {
        string r;
        bool first = true;
        foreach (i, p; param)
        {
            import std.conv : to;
            r ~= (first ? "" : ", ") ~ p.stringof ~ " a" ~ (i+1).to!string;
            first = false;
        }
        return r;
    }

    enum wrapperSignature =
        stc~ReturnType!(fun.type).stringof ~ " "
        ~ name~"("~wrapperParameters~")"~mod;
}

@safe unittest
{
    interface M
    {
        void f1();
        void f2(string[] args, int count);
        void f3(string[] args, int count) pure const;
    }

    alias TargetMembers = UniqMembers!(ConcatInterfaceMembers!M);
    static assert(wrapperSignature!(TargetMembers[0]) == "void f1()"
                  , wrapperSignature!(TargetMembers[0]));

    static assert(wrapperSignature!(TargetMembers[1]) == "void f2(string[] a1, int a2)"
                  , wrapperSignature!(TargetMembers[1]));

    static assert(wrapperSignature!(TargetMembers[2]) == "pure void f3(string[] a1, int a2) const"
                  , wrapperSignature!(TargetMembers[2]));
}

// Internal class to support dynamic cross-casting
private interface Structural(T)
{
    inout(T) _wrap_getSource() inout @safe pure nothrow;
}

private string unwrapExceptionText(Source, Target)()
{
    return Target.stringof~ " not wrapped into "~ Source.stringof;
}

version (StdDdoc)
{
    /**
     * Extract object previously wrapped by $(LREF wrap).
     *
     * Params:
     *     Target = type of wrapped object
     *     src = wrapper object returned by $(LREF wrap)
     *
     * Returns: the wrapped object, or null if src is not a wrapper created
     * by $(LREF wrap) and $(D_PARAM Target) is a class
     *
     * Throws: $(REF ConvException, std, conv) when attempting to extract a
     * struct which is not the wrapped type
     *
     * See_also: $(LREF wrap)
     */
    public inout(Target) unwrap(Target, Source)(inout Source src);
}

///
@system unittest
{
    interface Quack
    {
        int quack();
        @property int height();
    }
    interface Flyer
    {
        @property int height();
    }
    class Duck : Quack
    {
        int quack() { return 1; }
        @property int height() { return 10; }
    }
    class Human
    {
        int quack() { return 2; }
        @property int height() { return 20; }
    }
    struct HumanStructure
    {
        int quack() { return 3; }
        @property int height() { return 30; }
    }

    Duck d1 = new Duck();
    Human h1 = new Human();
    HumanStructure hs1;

    interface Refreshable
    {
        int refresh();
    }
    // does not have structural conformance
    static assert(!__traits(compiles, d1.wrap!Refreshable));
    static assert(!__traits(compiles, h1.wrap!Refreshable));
    static assert(!__traits(compiles, hs1.wrap!Refreshable));

    // strict upcast
    Quack qd = d1.wrap!Quack;
    assert(qd is d1);
    assert(qd.quack() == 1);    // calls Duck.quack
    // strict downcast
    Duck d2 = qd.unwrap!Duck;
    assert(d2 is d1);

    // structural upcast
    Quack qh = h1.wrap!Quack;
    Quack qhs = hs1.wrap!Quack;
    assert(qh.quack() == 2);    // calls Human.quack
    assert(qhs.quack() == 3);    // calls HumanStructure.quack
    // structural downcast
    Human h2 = qh.unwrap!Human;
    HumanStructure hs2 = qhs.unwrap!HumanStructure;
    assert(h2 is h1);
    assert(hs2 is hs1);

    // structural upcast (two steps)
    Quack qx = h1.wrap!Quack;   // Human -> Quack
    Quack qxs = hs1.wrap!Quack;   // HumanStructure -> Quack
    Flyer fx = qx.wrap!Flyer;   // Quack -> Flyer
    Flyer fxs = qxs.wrap!Flyer;   // Quack -> Flyer
    assert(fx.height == 20);    // calls Human.height
    assert(fxs.height == 30);    // calls HumanStructure.height
    // strucural downcast (two steps)
    Quack qy = fx.unwrap!Quack; // Flyer -> Quack
    Quack qys = fxs.unwrap!Quack; // Flyer -> Quack
    Human hy = qy.unwrap!Human; // Quack -> Human
    HumanStructure hys = qys.unwrap!HumanStructure; // Quack -> HumanStructure
    assert(hy is h1);
    assert(hys is hs1);
    // strucural downcast (one step)
    Human hz = fx.unwrap!Human; // Flyer -> Human
    HumanStructure hzs = fxs.unwrap!HumanStructure; // Flyer -> HumanStructure
    assert(hz is h1);
    assert(hzs is hs1);
}

///
@system unittest
{
    import std.traits : functionAttributes, FunctionAttribute;
    interface A { int run(); }
    interface B { int stop(); @property int status(); }
    class X
    {
        int run() { return 1; }
        int stop() { return 2; }
        @property int status() { return 3; }
    }

    auto x = new X();
    auto ab = x.wrap!(A, B);
    A a = ab;
    B b = ab;
    assert(a.run() == 1);
    assert(b.stop() == 2);
    assert(b.status == 3);
    static assert(functionAttributes!(typeof(ab).status) & FunctionAttribute.property);
}

template unwrap(Target)
{
    static if (!isMutable!Target)
        alias unwrap = .unwrap!(Unqual!Target);
    else
    {
        // strict downcast
        auto unwrap(Source)(inout Source src)
        if (is(Target : Source))
        {
            alias T = Select!(is(Source == shared), shared Target, Target);
            return dynamicCast!(inout T)(src);
        }

        // structural downcast for struct target
        auto unwrap(Source)(inout Source src)
        if (is(Target == struct))
        {
            alias T = Select!(is(Source == shared), shared Target, Target);
            auto upCastSource = dynamicCast!Object(src);   // remove qualifier
            do
            {
                if (auto a = dynamicCast!(Structural!Object)(upCastSource))
                {
                    upCastSource = a._wrap_getSource();
                }
                else if (auto a = dynamicCast!(Structural!T)(upCastSource))
                {
                    return a._wrap_getSource();
                }
                else
                {
                    static if (hasMember!(Source, "_wrap_getSource"))
                        return unwrap!Target(src._wrap_getSource());
                    else
                        break;
                }
            } while (upCastSource);
            import std.conv : ConvException;
            throw new ConvException(unwrapExceptionText!(Source,Target));
        }
        // structural downcast for class target
        auto unwrap(Source)(inout Source src)
        if (!is(Target : Source) && !is(Target == struct))
        {
            alias T = Select!(is(Source == shared), shared Target, Target);
            Object upCastSource = dynamicCast!(Object)(src);   // remove qualifier
            do
            {
                // Unwrap classes
                if (auto a = dynamicCast!(Structural!Object)(upCastSource))
                {
                    if (auto d = dynamicCast!(inout T)(upCastSource = a._wrap_getSource()))
                        return d;
                }
                // Unwrap a structure of type T
                else if (auto a = dynamicCast!(Structural!T)(upCastSource))
                {
                    return a._wrap_getSource();
                }
                // Unwrap class that already inherited from interface
                else if (auto d = dynamicCast!(inout T)(upCastSource))
                {
                    return d;
                }
                // Recurse to find the struct Target within a wrapped tree
                else
                {
                    static if (hasMember!(Source, "_wrap_getSource"))
                        return unwrap!Target(src._wrap_getSource());
                    else
                        break;
                }
            } while (upCastSource);
            return null;
        }
    }
}

@system unittest
{
    // Validate const/immutable
    class A
    {
        int draw()              { return 1; }
        int draw(int v)         { return v; }

        int draw() const        { return 2; }
        int draw() shared       { return 3; }
        int draw() shared const { return 4; }
        int draw() immutable    { return 5; }
    }
    interface Drawable
    {
        int draw();
        int draw() const;
        int draw() shared;
        int draw() shared const;
        int draw() immutable;
    }
    interface Drawable2
    {
        int draw(int v);
    }

    auto ma = new A();
    auto sa = new shared A();
    auto ia = new immutable A();
    {
                     Drawable  md = ma.wrap!Drawable;
               const Drawable  cd = ma.wrap!Drawable;
              shared Drawable  sd = sa.wrap!Drawable;
        shared const Drawable scd = sa.wrap!Drawable;
           immutable Drawable  id = ia.wrap!Drawable;
        assert( md.draw() == 1);
        assert( cd.draw() == 2);
        assert( sd.draw() == 3);
        assert(scd.draw() == 4);
        assert( id.draw() == 5);
    }
    {
        Drawable2 d = ma.wrap!Drawable2;
        static assert(!__traits(compiles, d.draw()));
        assert(d.draw(10) == 10);
    }
}

// https://issues.dlang.org/show_bug.cgi?id=10377
@system unittest
{
    import std.algorithm, std.range;

    interface MyInputRange(T)
    {
        @property T front();
        void popFront();
        @property bool empty();
    }

    //auto o = iota(0,10,1).inputRangeObject();
    //pragma(msg, __traits(allMembers, typeof(o)));
    auto r = iota(0,10,1).inputRangeObject().wrap!(MyInputRange!int)();
    assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
}

// https://issues.dlang.org/show_bug.cgi?id=10536
@system unittest
{
    interface Interface
    {
        int foo();
    }
    class Pluggable
    {
        int foo() { return 1; }
        @disable void opCast(T, this X)();  // !
    }

    Interface i = new Pluggable().wrap!Interface;
    assert(i.foo() == 1);
}

// https://issues.dlang.org/show_bug.cgi?id=10538
@system unittest
{
    interface Interface
    {
        int foo();
        int bar(int);
    }
    class Pluggable
    {
        int opDispatch(string name, A...)(A args) { return 100; }
    }

    Interface i = wrap!Interface(new Pluggable());
    assert(i.foo() == 100);
    assert(i.bar(10) == 100);
}

// Concat all Targets function members into one tuple
private template ConcatInterfaceMembers(Targets...)
{
    static if (Targets.length == 0)
        alias ConcatInterfaceMembers = AliasSeq!();
    else static if (Targets.length == 1)
        alias ConcatInterfaceMembers
          = AliasSeq!(GetOverloadedMethods!(Targets[0]));
    else
        alias ConcatInterfaceMembers = AliasSeq!(
                GetOverloadedMethods!(Targets[0]),
                ConcatInterfaceMembers!(Targets[1..$]));
}
// Remove duplicated functions based on the identifier name and function type covariance
private template UniqMembers(members...)
{
    template FuncInfo(string s, F)
    {
        enum name = s;
        alias type = F;
    }

    static if (members.length == 0)
        alias UniqMembers = AliasSeq!();
    else
    {
        alias func = members[0];
        enum  name = __traits(identifier, func);
        alias type = FunctionTypeOf!func;
        template check(size_t i, mem...)
        {
            static if (i >= mem.length)
                enum ptrdiff_t check = -1;
            else static if
              (__traits(identifier, func) == __traits(identifier, mem[i]) &&
              !is(DerivedFunctionType!(type, FunctionTypeOf!(mem[i])) == void))
            {
                enum ptrdiff_t check = i;
            }
            else
                enum ptrdiff_t check = check!(i + 1, mem);
        }
        enum ptrdiff_t x = 1 + check!(0, members[1 .. $]);
        static if (x >= 1)
        {
            alias typex = DerivedFunctionType!(type, FunctionTypeOf!(members[x]));
            alias remain = UniqMembers!(members[1 .. x], members[x + 1 .. $]);

            static if (remain.length >= 1 && remain[0].name == name &&
                       !is(DerivedFunctionType!(typex, remain[0].type) == void))
            {
                alias F = DerivedFunctionType!(typex, remain[0].type);
                alias UniqMembers = AliasSeq!(FuncInfo!(name, F), remain[1 .. $]);
            }
            else
                alias UniqMembers = AliasSeq!(FuncInfo!(name, typex), remain);
        }
        else
        {
            alias UniqMembers = AliasSeq!(FuncInfo!(name, type), UniqMembers!(members[1 .. $]));
        }
    }
}

// find a function from Fs that has same identifier and covariant type with f
private template findCovariantFunction(alias finfo, Source, Fs...)
{
    template check(size_t i = 0)
    {
        static if (i >= Fs.length)
            enum ptrdiff_t check = -1;
        else
        {
            enum ptrdiff_t check =
                (finfo.name == __traits(identifier, Fs[i])) &&
                isCovariantWith!(FunctionTypeOf!(Fs[i]), finfo.type)
              ? i : check!(i + 1);
        }
    }
    enum x = check!();
    static if (x == -1 && is(typeof(Source.opDispatch)))
    {
        alias Params = Parameters!(finfo.type);
        enum ptrdiff_t findCovariantFunction =
            is(typeof((             Source).init.opDispatch!(finfo.name)(Params.init))) ||
            is(typeof((       const Source).init.opDispatch!(finfo.name)(Params.init))) ||
            is(typeof((   immutable Source).init.opDispatch!(finfo.name)(Params.init))) ||
            is(typeof((      shared Source).init.opDispatch!(finfo.name)(Params.init))) ||
            is(typeof((shared const Source).init.opDispatch!(finfo.name)(Params.init)))
          ? ptrdiff_t.max : -1;
    }
    else
        enum ptrdiff_t findCovariantFunction = x;
}

/**
Type constructor for final (aka head-const) variables.

Final variables cannot be directly mutated or rebound, but references
reached through the variable are typed with their original mutability.
It is equivalent to `final` variables in D1 and Java, as well as
`readonly` variables in C#.

When `T` is a `const` or `immutable` type, `Final` aliases
to `T`.
*/
template Final(T)
{
static if (is(T == const) || is(T == immutable))
    alias Final = T;
else
{
    struct Final
    {
        import std.typecons : Proxy;

        private T final_value;
        mixin Proxy!final_value;

        /**
         * Construction is forwarded to the underlying type.
         */
        this(T other)
        {
            this.final_value = other;
        }

        /// Ditto
        this(Args...)(auto ref Args args)
            if (__traits(compiles, T(args)))
        {
            static assert((!is(T == struct) && !is(T == union)) || !isNested!T,
                "Non-static nested type " ~ fullyQualifiedName!T ~ " must be " ~
                "constructed explicitly at the call-site (e.g. auto s = " ~
                "makeFinal(" ~ T.stringof ~ "(...));)");
            this.final_value = T(args);
        }

        // Attaching function attributes gives less noisy error messages
        pure nothrow @safe @nogc
        {
            /++
             + All operators, including member access, are forwarded to the
             + underlying value of type `T` except for these mutating operators,
             + which are disabled.
             +/
            void opAssign(Other)(Other other)
            {
                static assert(0, typeof(this).stringof ~
                                 " cannot be reassigned.");
            }

            /// Ditto
            void opOpAssign(string op, Other)(Other other)
            {
                static assert(0, typeof(this).stringof ~
                                 " cannot be reassigned.");
            }

            /// Ditto
            void opUnary(string op : "--")()
            {
                static assert(0, typeof(this).stringof ~
                                 " cannot be mutated.");
            }

            /// Ditto
            void opUnary(string op : "++")()
            {
                static assert(0, typeof(this).stringof ~
                                 " cannot be mutated.");
            }
        }

        /**
         *
         * `Final!T` implicitly converts to an rvalue of type `T` through
         * `AliasThis`.
         */
        inout(T) final_get() inout
        {
            return final_value;
        }

        /// Ditto
        alias final_get this;

        /// Ditto
        auto ref opUnary(string op)()
            if (__traits(compiles, mixin(op ~ "T.init")))
        {
            return mixin(op ~ "this.final_value");
        }
    }
}
}

/// Ditto
Final!T makeFinal(T)(T t)
{
    return Final!T(t);
}

/// `Final` can be used to create class references which cannot be rebound:
pure nothrow @safe unittest
{
    static class A
    {
        int i;

        this(int i) pure nothrow @nogc @safe
        {
            this.i = i;
        }
    }

    auto a = makeFinal(new A(42));
    assert(a.i == 42);

    //a = new A(24); // Reassignment is illegal,
    a.i = 24; // But fields are still mutable.

    assert(a.i == 24);
}

/// `Final` can also be used to create read-only data fields without using transitive immutability:
pure nothrow @safe unittest
{
    static class A
    {
        int i;

        this(int i) pure nothrow @nogc @safe
        {
            this.i = i;
        }
    }

    static class B
    {
        Final!A a;

        this(A a) pure nothrow @nogc @safe
        {
            this.a = a; // Construction, thus allowed.
        }
    }

    auto b = new B(new A(42));
    assert(b.a.i == 42);

    // b.a = new A(24); // Reassignment is illegal,
    b.a.i = 24; // but `a` is still mutable.

    assert(b.a.i == 24);
}

pure nothrow @safe unittest
{
    static class A { int i; }
    static assert(!is(Final!A == A));
    static assert(is(Final!(const A) == const A));
    static assert(is(Final!(immutable A) == immutable A));

    Final!A a = new A;
    static assert(!__traits(compiles, a = new A));

    assert(a.i == 0);
    a.i = 42;
    assert(a.i == 42);

    Final!int i = 42;
    static assert(!__traits(compiles, i = 24));
    static assert(!__traits(compiles, --i));
    static assert(!__traits(compiles, ++i));
    assert(i == 42);
    int iCopy = i;
    assert(iCopy == 42);
    iCopy = -i; // non-mutating unary operators must work
    assert(iCopy == -42);

    static struct S
    {
        int i;

        pure nothrow @safe @nogc:
        this(int i){}
        this(string s){}
        this(int i, string s, float f){ this.i = i; }
    }

    Final!S sint = 42;
    Final!S sstr = "foo";
    static assert(!__traits(compiles, sint = sstr));

    auto sboth = Final!S(42, "foo", 3.14);
    assert(sboth.i == 42);

    sboth.i = 24;
    assert(sboth.i == 24);

    struct NestedS
    {
        int i;
        int get() pure nothrow @safe @nogc { return sboth.i + i; }
    }

    // Nested structs must be constructed at the call-site
    static assert(!__traits(compiles, Final!NestedS(6)));
    auto s = makeFinal(NestedS(6));
    assert(s.i == 6);
    assert(s.get == 30);

    class NestedC
    {
        int i;

        pure nothrow @safe @nogc:
        this(int i) { this.i = i; }
        int get() { return sboth.i + i; }
    }

    auto c = makeFinal(new NestedC(6));
    assert(c.i == 6);
    assert(c.get == 30);
}

pure nothrow @safe unittest
{
    auto arr = makeFinal([1, 2, 3]);
    static assert(!__traits(compiles, arr = null));
    static assert(!__traits(compiles, arr ~= 4));
    assert((arr ~ 4) == [1, 2, 3, 4]);
}

// https://issues.dlang.org/show_bug.cgi?id=17270
pure nothrow @nogc @system unittest
{
    int i = 1;
    Final!(int*) fp = &i;
    assert(*fp == 1);
    static assert(!__traits(compiles,
        fp = &i // direct assignment
    ));
    static assert(is(typeof(*fp) == int));
    *fp = 2; // indirect assignment
    assert(*fp == 2);
    int* p = fp;
    assert(*p == 2);
}

pure nothrow @system unittest
{
    Final!(int[]) arr;
    // static assert(!__traits(compiles,
        // arr.length = 10; // bug!
    // ));
    static assert(!__traits(compiles,
        arr.ptr = null
    ));
    static assert(!__traits(compiles,
        arr.ptr++
    ));
}