-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathalgebraic.d
4194 lines (3661 loc) · 128 KB
/
algebraic.d
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
/++
$(H2 Variant and Nullable types)
This module implements a
$(HTTP erdani.org/publications/cuj-04-2002.php.html,discriminated union)
type (a.k.a.
$(HTTP en.wikipedia.org/wiki/Tagged_union,tagged union),
$(HTTP en.wikipedia.org/wiki/Algebraic_data_type,algebraic type)).
Such types are useful
for type-uniform binary interfaces, interfacing with scripting
languages, and comfortable exploratory programming.
The module defines generic $(LREF Algebraic) type that contains a payload.
The allowed types of the paylad are defined by the unordered $(LREF TypeSet).
$(LREF Algebraic) template accepts two arguments: self type set id and a list of type sets.
$(BOOKTABLE $(H3 $(LREF Algebraic) Aliases),
$(TR $(TH Name) $(TH Description))
$(T2 Variant, an algebraic type)
$(T2 TaggedVariant, a tagged algebraic type)
$(T2 Nullable, an algebraic type with at least `typeof(null)`)
)
$(BOOKTABLE $(H3 Visitor Handlers),
$(TR $(TH Name) $(TH Ensures can match) $(TH Throws if no match) $(TH Returns $(LREF Nullable)) $(TH Multiple dispatch) $(TH Argumments count) $(TH Fuses Algebraic types on return))
$(LEADINGROWN 8, Classic handlers)
$(T8 visit, Yes, N/A, No, No, 1+, No)
$(T8 optionalVisit, No, No, Yes, No, 1+, No)
$(T8 autoVisit, No, No, auto, No, 1+, No)
$(T8 tryVisit, No, Yes, No, No, 1+, No)
$(LEADINGROWN 8, Multiple dispatch and algebraic fusion on return)
$(T8 match, Yes, N/A, No, Yes, 0+, Yes)
$(T8 optionalMatch, No, No, Yes, Yes, 0+, Yes)
$(T8 autoMatch, No, No, auto, Yes, 0+, Yes)
$(T8 tryMatch, No, Yes, No, Yes, 0+, Yes)
$(LEADINGROWN 8, Inner handlers. Multiple dispatch and algebraic fusion on return.)
$(T8 suit, N/A(Yes), N/A, No, Yes, ?, Yes)
$(T8 some, N/A(Yes), N/A, No, Yes, 0+, Yes)
$(T8 none, N/A(Yes), N/A, No, Yes, 1+, Yes)
$(T8 assumeOk, Yes(No), No(Yes), No(Yes), Yes(No), 0+, Yes(No))
$(LEADINGROWN 8, Member access)
$(T8 getMember, Yes, N/A, No, No, 1+, No)
$(T8 optionalGetMember, No, No, Yes, No, 1+, No)
$(T8 autoGetMember, No, No, auto, No, 1+, No)
$(T8 tryGetMember, No, Yes, No, No, 1+, No)
$(LEADINGROWN 8, Member access with algebraic fusion on return)
$(T8 matchMember, Yes, N/A, No, No, 1+, Yes)
$(T8 optionalMatchMember, No, No, Yes, No, 1+, Yes)
$(T8 autoMatchMember, No, No, auto, No, 1+, Yes)
$(T8 tryMatchMember, No, Yes, No, No, 1+, Yes)
)
$(BOOKTABLE $(H3 Special Types),
$(TR $(TH Name) $(TH Description))
$(T2plain `void`, It is usefull to indicate a possible return type of the visitor. Can't be accesed by reference. )
$(T2plain `typeof(null)`, It is usefull for nullable types. Also, it is used to indicate that a visitor can't match the current value of the algebraic. Can't be accesed by reference. )
$(T2 This, Dummy structure that is used to construct self-referencing algebraic types. Example: `Variant!(int, double, string, This*[2])`)
$(T2plain $(LREF SetAlias)`!setId`, Dummy structure that is used to construct cyclic-referencing lists of algebraic types. )
$(T2 Err, Wrapper to denote an error value type. )
$(T2 reflectErr, Attribute that denotes that the type is an error value type. )
)
$(BOOKTABLE $(H3 $(LREF Algebraic) Traits),
$(TR $(TH Name) $(TH Description))
$(T2 isVariant, Checks if the type is instance of $(LREF Algebraic).)
$(T2 isNullable, Checks if the type is instance of $(LREF Algebraic) with a self $(LREF TypeSet) that contains `typeof(null)`. )
$(T2 isTypeSet, Checks if the types are the same as $(LREF TypeSet) of them. )
$(T2 ValueTypeOfNullable, Gets type of $(LI $(LREF .Algebraic.get.2)) method. )
$(T2 SomeVariant, Gets subtype of algebraic without types for which $(LREF isErr) is true.)
$(T2 NoneVariant, Gets subtype of algebraic with types for which $(LREF isErr) is true.)
$(T2 isErr, Checks if T is a instance of $(LREF Err) or if it is annotated with $(LREF reflectErr).)
$(T2 isResultVariant, Checks if T is a Variant with at least one allowed type that satisfy $(LREF isErr) traits.)
)
$(H3 Type Set)
$(UL
$(LI Type set is unordered. Example:`TypeSet!(int, double)` and `TypeSet!(double, int)` are the same. )
$(LI Duplicats are ignored. Example: `TypeSet!(float, int, float)` and `TypeSet!(int, float)` are the same. )
$(LI Types are automatically unqualified if this operation can be performed implicitly. Example: `TypeSet!(const int) and `TypeSet!int` are the same. )
$(LI Non trivial `TypeSet!(A, B, ..., etc)` is allowed.)
$(LI Trivial `TypeSet!T` is allowed.)
$(LI Empty `TypeSet!()` is allowed.)
)
$(H3 Visitors)
$(UL
$(LI Visitors are allowed to return values of different types If there are more then one return type then the an $(LREF Algebraic) type is returned. )
$(LI Visitors are allowed to accept additional arguments. The arguments can be passed to the visitor handler. )
$(LI Multiple visitors can be passes to the visitor handler. )
$(LI Visitors are matched according to the common $(HTTPS dlang.org/spec/function.html#function-overloading, Dlang Function Overloading) rules. )
$(LI Visitors are allowed accept algebraic value by reference except the value of `typeof(null)`. )
$(LI Visitors are called without algebraic value if its algebraic type is `void`. )
$(LI If the visitors arguments has known types, then such visitors should be passed to a visitor handler before others to make the compiler happy. This includes visitors with no arguments, which is used to match `void` type. )
)
$(H3 Implementation Features)
$(UL
$(LI BetterC support. Runtime `TypeInfo` is not used.)
$(LI Copy-constructors and postblit constructors are supported. )
$(LI `toHash`, `opCmp`. `opEquals`, and `toString` support. )
$(LI No string or template mixins are used. )
$(LI Optimised for fast execution. )
$(LI $(LREF some) / $(LREF none) idiom. )
)
See_also: $(HTTPS en.wikipedia.org/wiki/Algebra_of_sets, Algebra of sets).
License: $(HTTP www.apache.org/licenses/LICENSE-2.0, Apache-2.0)
Authors: Ilia Ki
Macros:
T2plain=$(TR $(TDNW $1) $(TD $+))
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
T4=$(TR $(TDNW $(LREF $1)) $(TD $2) $(TD $3) $(TD $4))
T8=$(TR $(TDNW $(LREF $1)) $(TD $2) $(TD $3) $(TD $4) $(TD $5) $(TD $6) $(TD $7) $(TD $8))
+/
module mir.algebraic;
import mir.internal.meta;
import mir.functional: naryFun;
/++
The attribute is used to define a permanent member field in an anlgebraic type.
Should applied to a field of the union passed to $(LREF TaggedVariant).
+/
enum algMeta;
/++
The attribute is used in pair with $(LREF algMeta) to exclude the field
from compression in `toHash`, `opEquals`, and `opCmp` methods.
+/
enum algTransp;
/++
The attribute is used in pair with $(LREF algMeta) to use the field
as an error infomration. Usually it is a position marker in a file.
The type should have `scope const` `toString` method.
+/
enum algVerbose;
private static immutable variantExceptionMsg = "mir.algebraic: the algebraic stores other type then requested.";
private static immutable variantNullExceptionMsg = "mir.algebraic: the algebraic is empty and doesn't store any value.";
private static immutable variantMemberExceptionMsg = "mir.algebraic: the algebraic stores a type that isn't compatible with the user provided visitor and arguments.";
version (D_Exceptions)
{
private static immutable variantException = new Exception(variantExceptionMsg);
private static immutable variantNullException = new Exception(variantNullExceptionMsg);
private static immutable variantMemberException = new Exception(variantMemberExceptionMsg);
}
private static struct _Null()
{
@safe pure nothrow @nogc const:
int opCmp(_Null) { return 0; }
this(typeof(null)) inout {}
string toString() { return "null"; }
}
private static struct _Void()
{
@safe pure nothrow @nogc const:
int opCmp(_Void) { return 0; }
string toString() { return "void"; }
}
/++
Checks if the type is instance of $(LREF Algebraic).
+/
enum bool isVariant(T) = is(immutable T == immutable Algebraic!Types, Types...);
///
@safe pure version(mir_core_test) unittest
{
static assert(isVariant!(Variant!(int, string)));
static assert(isVariant!(const Variant!(int[], string)));
static assert(isVariant!(Nullable!(int, string)));
static assert(!isVariant!int);
}
/++
Same as $(LREF isVariant), but matches for `alias this` variant types (requires
DMD FE 2.100.0 or later)
+/
enum bool isLikeVariant(T) = !is(immutable T == immutable noreturn)
&& is(immutable T : immutable Algebraic!Types, Types...);
static if (__VERSION__ >= 2_100)
{
///
@safe pure version(mir_core_test) unittest
{
static struct CustomVariant
{
Variant!(int, string) data;
alias data this;
this(T)(T v) { data = v; }
ref typeof(this) opAssign(T)(T v)
{
data = v;
return this;
}
}
static assert(isLikeVariant!(Variant!(int, string)));
static assert(isLikeVariant!(const Variant!(int[], string)));
static assert(isLikeVariant!(Nullable!(int, string)));
static assert(!isLikeVariant!int);
static assert(!isVariant!CustomVariant);
static assert(isLikeVariant!CustomVariant);
CustomVariant customVariant = 5;
assert(customVariant.match!(
(string s) => false,
(int n) => true
));
}
}
/++
Checks if the type is instance of tagged $(LREF Algebraic).
Tagged algebraics can be defined with $(LREF TaggedVariant).
+/
enum bool isTaggedVariant(T) = is(immutable T == immutable Algebraic!U, U) && is(U == union);
///
@safe pure version(mir_core_test) unittest
{
static union MyUnion
{
int integer;
immutable(char)[] string;
}
alias MyAlgebraic = Algebraic!MyUnion;
static assert(isTaggedVariant!MyAlgebraic);
static assert(!isTaggedVariant!int);
static assert(!isTaggedVariant!(Variant!(int, string)));
}
/++
Same as $(LREF isTaggedVariant), but with support for custom `alias this`
variants.
Only works since DMD FE 2.100, see $(LREF isLikeVariant).
+/
enum bool isLikeTaggedVariant(T) = isLikeVariant!T && is(T.Kind == enum);
/++
Checks if the type is instance of $(LREF Algebraic) with a self $(LREF TypeSet) that contains `typeof(null)`.
+/
enum bool isNullable(T) = is(immutable T == immutable Algebraic!(typeof(null), Types), Types...);
///
@safe pure version(mir_core_test) unittest
{
static assert(isNullable!(const Nullable!(int, string)));
static assert(isNullable!(Nullable!()));
static assert(!isNullable!(Variant!()));
static assert(!isNullable!(Variant!string));
static assert(!isNullable!int);
static assert(!isNullable!string);
}
/++
Same as $(LREF isNullable), but with support for custom `alias this` variants.
Only works since DMD FE 2.100, see $(LREF isLikeVariant).
+/
enum bool isLikeNullable(T) = !is(immutable T == immutable noreturn)
&& is(immutable T : immutable Algebraic!(typeof(null), Types), Types...);
/++
Gets type of $(LI $(LREF .Algebraic.get.2)) method.
+/
template ValueTypeOfNullable(T : Algebraic!(typeof(null), Types), Types...)
{
static if (Types.length == 1)
alias ValueTypeOfNullable = Types[0];
else
alias ValueTypeOfNullable = Algebraic!Types;
}
///
@safe pure version(mir_core_test) unittest
{
static assert(is(ValueTypeOfNullable!(const Nullable!(int, string)) == Algebraic!(int, string)));
static assert(is(ValueTypeOfNullable!(Nullable!()) == Algebraic!()));
static assert(is(typeof(Nullable!().get()) == Algebraic!()));
}
/++
Dummy type for $(LREF Variant) and $(LREF Nullable) self-referencing.
+/
struct This
{
@safe pure nothrow @nogc scope const:
int opCmp(typeof(this)) { return 0; }
string toString() { return typeof(this).stringof; }
}
private template TagInfo(T, string name, udas...)
if (udas.length <= 3)
{
import std.meta: staticIndexOf;
alias Type = T;
enum tag = name;
enum meta = staticIndexOf!(algMeta, udas) >= 0;
enum transparent = staticIndexOf!(algTransp, udas) >= 0;
enum verbose = staticIndexOf!(algVerbose, udas) >= 0;
}
// example from std.variant
/++
$(H4 Self-Referential Types)
A useful and popular use of algebraic data structures is for defining
$(LUCKY self-referential data structures), i.e. structures that embed references to
values of their own type within.
This is achieved with $(LREF Variant) by using $(LREF This) as a placeholder whenever a
reference to the type being defined is needed. The $(LREF Variant) instantiation
will perform
$(LINK2 https://en.wikipedia.org/wiki/Name_resolution_(programming_languages)#Alpha_renaming_to_make_name_resolution_trivial,
alpha renaming) on its constituent types, replacing $(LREF This)
with the self-referenced type. The structure of the type involving $(LREF This) may
be arbitrarily complex.
+/
@safe pure version(mir_core_test) unittest
{
import mir.functional: Tuple;
// A tree is either a leaf or a branch of two others
alias Tree(Leaf) = Variant!(Leaf, Tuple!(This*, This*));
alias Leafs = Tuple!(Tree!int*, Tree!int*);
Tree!int tree = Leafs(new Tree!int(41), new Tree!int(43));
Tree!int* right = tree.get!Leafs[1];
assert(*right == 43);
}
///
@safe pure version(mir_core_test) unittest
{
// An object is a double, a string, or a hash of objects
alias Obj = Variant!(double, string, This[string], This[]);
alias Map = Obj[string];
Obj obj = "hello";
assert(obj._is!string);
assert(obj.trustedGet!string == "hello");
obj = 42.0;
assert(obj.get!double == 42);
obj = ["customer": Obj("John"), "paid": Obj(23.95)];
assert(obj.get!Map["customer"] == "John");
}
/++
Type set resolution template used to construct $(LREF Algebraic) .
+/
template TypeSet(T...)
{
import std.meta: staticSort, staticMap, allSatisfy, anySatisfy;
// sort types by sizeof and them mangleof
// but typeof(null) goes first
static if (is(staticMap!(TryRemoveConst, T) == T))
{
static if (is(NoDuplicates!T == T))
{
static if (staticIsSorted!(TypeCmp, T))
{
alias TypeSet = T;
}
else
{
alias TypeSet = TypeSet!(staticSort!(TypeCmp, T));
}
}
else
{
alias TypeSet = TypeSet!(NoDuplicates!T);
}
}
else
{
alias TypeSet = TypeSet!(staticMap!(TryRemoveConst, T));
}
}
// IonNull goes first as well
private template isIonNull(T)
{
static if (is(T == TagInfo!(U, name), U, string name))
enum isIonNull = .isIonNull!U;
else
enum isIonNull = T.stringof == "IonNull";
}
private template TypeCmp(A, B)
{
enum bool TypeCmp = is(A == B) ? false:
is(A == typeof(null)) ? true:
is(B == typeof(null)) ? false:
isIonNull!A ? true:
isIonNull!B ? false:
is(A == void) || is(A == TagInfo!(void, vaname), string vaname) ? true:
is(B == void) || is(A == TagInfo!(void, vbname), string vbname) ? false:
A.sizeof < B.sizeof ? true:
A.sizeof > B.sizeof ? false:
A.mangleof < B.mangleof;
}
///
version(mir_core_test) unittest
{
static struct S {}
alias C = S;
alias Int = int;
static assert(is(TypeSet!(S, int) == TypeSet!(Int, C)));
static assert(is(TypeSet!(S, int, int) == TypeSet!(Int, C)));
static assert(!is(TypeSet!(uint, S) == TypeSet!(int, S)));
}
private template applyTags(string[] tagNames, T...)
if (tagNames.length == T.length)
{
import std.meta: AliasSeq;
static if (tagNames.length == 0)
alias applyTags = AliasSeq!();
else
alias applyTags = AliasSeq!(TagInfo!(T[0], tagNames[0]), .applyTags!(tagNames[1 .. $], T[1 .. $]));
}
/++
Checks if the type list is $(LREF TypeSet).
+/
enum bool isTypeSet(T...) = is(T == TypeSet!T);
///
@safe pure version(mir_core_test) unittest
{
static assert(isTypeSet!(TypeSet!()));
static assert(isTypeSet!(TypeSet!void));
static assert(isTypeSet!(TypeSet!(void, int, typeof(null))));
}
/++
Variant Type (aka Algebraic Type).
The impllementation is defined as
----
alias Variant(T...) = Algebraic!(TypeSet!T);
----
Compatible with BetterC mode.
+/
alias Variant(T...) = Algebraic!(TypeSet!T);
///
@safe pure @nogc
version(mir_core_test) unittest
{
Variant!(int, double, string) v = 5;
assert(v.get!int == 5);
v = 3.14;
assert(v == 3.14);
// auto x = v.get!long; // won't compile, type long not allowed
// v = '1'; // won't compile, type char not allowed
}
/// Single argument Variant
// and Type with copy constructor
@safe pure nothrow @nogc
version(mir_core_test) unittest
{
static struct S
{
int n;
this(ref return scope inout S rhs) inout
{
this.n = rhs.n + 1;
}
}
Variant!S a = S();
auto b = a;
import mir.conv;
assert(a.get!S.n == 0);
assert(b.n == 1); //direct access of a member in case of all algebraic types has this member
}
/// Empty type set
@safe pure nothrow @nogc version(mir_core_test) unittest
{
Variant!() a;
auto b = a;
assert(a.toHash == 0);
assert(a == b);
assert(a <= b && b >= a);
static assert(typeof(a).sizeof == 1);
}
/// Small types
@safe pure nothrow @nogc version(mir_core_test) unittest
{
static struct S { ubyte d; }
static assert(Nullable!(byte, char, S).sizeof == 2);
}
@safe pure nothrow @nogc version(mir_core_test) unittest
{
static struct S { ubyte[3] d; }
static assert(Nullable!(ushort, wchar, S).sizeof == 6);
}
// /// opPostMove support
// @safe pure @nogc nothrow
// version(mir_core_test) unittest
// {
// import std.algorithm.mutation: move;
// static struct S
// {
// uint s;
// void opPostMove(const ref S old) nothrow
// {
// this.s = old.s + 1;
// }
// }
// Variant!S a;
// auto b = a.move;
// assert(b.s == 1);
// }
/++
Tagged Variant Type (aka Tagged Algebraic Type).
Compatible with BetterC mode.
Template has two declarations:
----
// and
template TaggedVariant(T)
if (is(T == union))
{
...
}
----
See_also: $(LREF Variant), $(LREF isTaggedVariant).
+/
deprecated ("Use Algebraic!Union instead")
template TaggedVariant(T)
if (is(T == union))
{
alias TaggedVariant = Algebraic!T;
}
/// Json Value with styles
@safe pure
version(mir_core_test) unittest
{
enum Style { block, flow }
static struct SomeMetadata {
int a;
@safe pure nothrow @nogc scope
int opCmp(scope const SomeMetadata rhs) const { return a - rhs.a; }
}
static struct ParsePosition
{
string file, line, column;
void toString()(scope ref W w) scope const
{
w.put(file);
if (line) {
w.put("("); w.put(line);
if (column) { w.put(","); w.put(column); }
w.put(")");
}
}
}
static union Json_
{
typeof(null) null_;
bool boolean;
long integer;
double floating;
// Not, that `string` is't builtin type but an alias in `object.d`
// So we can use `string` as a name of the string field
immutable(char)[] string;
This[] array;
// commented out to test `opCmp` primitive
// This[immutable(char)[]] object;
@algMeta:
bool active;
SomeMetadata metadata;
@algTransp:
Style style;
@algVerbose ParsePosition position;
}
alias JsonAlgebraic = Algebraic!Json_;
// typeof(null) has priority
static assert(JsonAlgebraic.Kind.init == JsonAlgebraic.Kind.null_);
static assert(JsonAlgebraic.Kind.null_ == 0);
// Kind and AllowedTypes has the same order
static assert (is(JsonAlgebraic.AllowedTypes[JsonAlgebraic.Kind.array] == JsonAlgebraic[]));
static assert (is(JsonAlgebraic.AllowedTypes[JsonAlgebraic.Kind.boolean] == bool));
static assert (is(JsonAlgebraic.AllowedTypes[JsonAlgebraic.Kind.floating] == double));
static assert (is(JsonAlgebraic.AllowedTypes[JsonAlgebraic.Kind.integer] == long));
static assert (is(JsonAlgebraic.AllowedTypes[JsonAlgebraic.Kind.null_] == typeof(null)));
// static assert (is(JsonAlgebraic.AllowedTypes[JsonAlgebraic.Kind.object] == JsonAlgebraic[string]));
JsonAlgebraic v;
assert(v.kind == JsonAlgebraic.Kind.null_);
v = 1;
assert(v.kind == JsonAlgebraic.Kind.integer);
assert(v == 1);
v = JsonAlgebraic(1);
assert(v == 1);
v = v.get!(long, double);
v = "Tagged!";
// member-based access. Simple!
assert(v.string == "Tagged!");
// type-based access
assert(v.get!string == "Tagged!");
assert(v.trustedGet!string == "Tagged!");
assert(v.kind == JsonAlgebraic.Kind.string);
assert(v.get!"string" == "Tagged!"); // string-based get
assert(v.trustedGet!"string" == "Tagged!"); // string-based trustedGet
assert(v.get!(JsonAlgebraic.Kind.string) == "Tagged!"); // Kind-based get
assert(v.trustedGet!(JsonAlgebraic.Kind.string) == "Tagged!"); // Kind-based trustedGet
// checks
assert(v._is!string); // type based
assert(v._is!"string"); // string based
assert(v._is!(JsonAlgebraic.Kind.string)); //
v = null;
assert(v.kind == JsonAlgebraic.Kind.null_);
v = [JsonAlgebraic("str"), JsonAlgebraic(4.3)];
assert(v.kind == JsonAlgebraic.Kind.array);
assert(v.trustedGet!(JsonAlgebraic[])[1].kind == JsonAlgebraic.Kind.floating);
JsonAlgebraic w = v;
w.style = Style.flow;
assert(v.style != w.style);
assert(v == w);
assert(v <= w);
assert(v >= w);
assert(v.toHash == w.toHash);
w.active = true;
assert(v != w);
assert(v.toHash != w.toHash);
assert(v.get!"array" == w.get!"array");
assert(v < w);
// test equality with self-referencing allowed type
auto arr = [JsonAlgebraic("str"), JsonAlgebraic(120)];
v = arr;
assert(v == arr);
assert(v == [JsonAlgebraic("str"), JsonAlgebraic(120)]);
}
/// Wrapped algebraic with propogated primitives
@safe pure
version(mir_core_test) unittest
{
static struct Response
{
private union Response_
{
double float_;
immutable(char)[] string;
Response[] array;
Response[immutable(char)[]] table;
}
alias ResponseAlgebraic = Algebraic!Response_;
ResponseAlgebraic data;
alias Tag = ResponseAlgebraic.Kind;
// propogates opEquals, opAssign, and other primitives
alias data this;
static foreach (T; ResponseAlgebraic.AllowedTypes)
this(T v) @safe pure nothrow @nogc { data = v; }
}
Response v = 3.0;
assert(v.kind == Response.Tag.float_);
v = "str";
assert(v == "str");
}
/++
Nullable $(LREF Variant) Type (aka Algebraic Type).
The impllementation is defined as
----
alias Nullable(T...) = Variant!(typeof(null), T);
----
In additional to common algebraic API the following members can be accesssed:
$(UL
$(LI $(LREF .Algebraic.isNull))
$(LI $(LREF .Algebraic.nullify))
$(LI $(LREF .Algebraic.get.2))
)
Compatible with BetterC mode.
+/
alias Nullable(T...) = Variant!(typeof(null), T);
/// ditto
Nullable!T nullable(T)(T t)
{
import core.lifetime: forward;
return Nullable!T(forward!t);
}
/++
Single type `Nullable`
+/
@safe pure @nogc
version(mir_core_test) unittest
{
static assert(is(Nullable!int == Variant!(typeof(null), int)));
Nullable!int a = 5;
assert(a.get!int == 5);
a.nullify;
assert(a.isNull);
a = 4;
assert(!a.isNull);
assert(a.get == 4);
assert(a == 4);
a = 4;
a = null;
assert(a == null);
}
/// Empty nullable type set support
@safe pure nothrow @nogc version(mir_core_test) unittest
{
Nullable!() a;
auto b = a;
assert(a.toHash == 0);
assert(a == b);
assert(a <= b && b >= a);
static assert(typeof(a).sizeof == 1);
}
private bool contains(scope const char[][] names, scope const char[] member)
@safe pure nothrow @nogc
{
foreach (name; names)
if (name == member)
return true;
return false;
}
/++
Algebraic implementation.
For more portable code, it is higly recommeded to don't use this template directly.
Instead, please use of $(LREF Variant) and $(LREF Nullable), which sort types.
+/
struct Algebraic(T__...)
{
import mir.internal.meta: getUDAs;
import core.lifetime: moveEmplace;
import mir.conv: emplaceRef;
import mir.reflection: isPublic, hasField, isProperty;
import std.meta: Filter, AliasSeq, ApplyRight, anySatisfy, allSatisfy, staticMap, templateOr, templateNot, templateAnd;
import std.traits:
hasElaborateAssign,
hasElaborateCopyConstructor,
hasElaborateDestructor,
hasMember,
hasUDA,
isAggregateType,
isAssociativeArray,
isDynamicArray,
isEqualityComparable,
isOrderingComparable,
Largest,
Unqual
;
static if (T__.length == 1 && is(T__[0] == union))
{
private alias UMTypeInfoOf__(immutable(char)[] member) = TagInfo!(
typeof(__traits(getMember, T__[0], member)),
member,
getUDAs!(T__[0], member, algMeta),
getUDAs!(T__[0], member, algTransp),
getUDAs!(T__[0], member, algVerbose),
);
private alias UMGetType__(alias TI) = TI.Type;
private enum bool UMGetMeta(alias TI) = TI.meta;
private alias AllInfo__ = staticMap!(UMTypeInfoOf__, __traits(allMembers, T__[0]));
private alias TypesInfo__ = Filter!(templateNot!UMGetMeta, AllInfo__);
private alias MetaInfo__ = Filter!(UMGetMeta, AllInfo__);
alias Types__ = staticMap!(UMGetType__, TypesInfo__);
/++
+/
static immutable char[][] metaFieldNames__ = () {
immutable(char)[][] ret;
foreach (T; MetaInfo__)
ret ~= T.tag;
return ret;
} ();
/++
+/
static immutable char[][] typeFieldNames__ = () {
immutable(char)[][] ret;
foreach (T; TypesInfo__)
ret ~= T.tag;
return ret;
} ();
}
else
{
alias Types__ = T__;
private alias MetaInfo__ = T__[0 .. 0];
enum immutable(char[][]) metaFieldNames__ = null;
enum immutable(char[][]) typeFieldNames__ = null;
}
private enum bool variant_test__ = is(Types__ == AliasSeq!(typeof(null), double));
/++
Allowed types list
See_also: $(LREF TypeSet)
+/
alias AllowedTypes = AliasSeq!(ReplaceTypeUnless!(.isVariant, .This, Algebraic!T__, Types__));
version(mir_core_test)
static if (variant_test__)
///
unittest
{
import std.meta: AliasSeq;
alias V = Nullable!
(
This*,
string,
double,
bool,
);
static assert(is(V.AllowedTypes == TypeSet!(
typeof(null),
bool,
string,
double,
V*)));
}
static foreach (i, T; MetaInfo__)
mixin ("MetaInfo__[" ~ i.stringof ~ "].Type " ~ T.tag ~";");
private alias _Payload = Replace!(void, _Void!(), Replace!(typeof(null), _Null!(), AllowedTypes));
private static union Storage__
{
_Payload payload;
static foreach (int i, P; _Payload)
mixin(`alias _member_` ~ i.stringof ~ ` = payload[` ~ i.stringof ~ `];`);
static if (AllowedTypes.length == 0 || is(AllowedTypes == AliasSeq!(typeof(null))) || is(AllowedTypes == AliasSeq!void))
ubyte[0] bytes;
else
ubyte[Largest!_Payload.sizeof] bytes;
}
private Storage__ storage__;
static if (AllowedTypes.length > 1)
{
static if ((Storage__.alignof & 1) && _Payload.length <= ubyte.max)
private alias ID__ = ubyte;
else
static if ((Storage__.alignof & 2) && _Payload.length <= ushort.max)
private alias ID__ = ushort;
else
// static if (Storage__.alignof & 3)
private alias ID__ = uint;
// else
// private alias ID__ = ulong;
ID__ identifier__;
}
else
{
private alias ID__ = uint;
enum ID__ identifier__ = 0;
}
version (D_Ddoc)
{
/++
Algebraic Kind.
Defined as enum for tagged algebraics and as unsigned for common algebraics.
The Kind enum contains the members defined using tag names.
If the algebraic type is $(LREF Nullable) then the default Kind enum member has zero value and corresponds to `typeof(null)`.
See_also: $(LREF TaggedVariant).
+/
enum Kind { _not_me_but_tags_name_list_ }
}
static if (typeFieldNames__.length)
{
version (D_Ddoc){}
else
{
mixin(enumKindText(typeFieldNames__));
}
}
else
{
version (D_Ddoc){}
else
{
alias Kind = ID__;
}
}
/++
Returns: $(LREF .Algebraic.Kind).
Defined as enum for tagged algebraics and as unsigned for common algebraics.
See_also: $(LREF TaggedVariant).
+/
Kind kind() const @safe pure nothrow @nogc @property
{
assert(identifier__ <= Kind.max);
return cast(Kind) identifier__;
}
static if (anySatisfy!(hasElaborateDestructor, _Payload))
~this() @trusted
{
S: switch (identifier__)
{
static foreach (i, T; AllowedTypes)
static if (hasElaborateDestructor!T)
{
case i:
(*cast(Unqual!(_Payload[i])*)&storage__.payload[i]).__xdtor;
break S;
}
default:
}
version(mir_secure_memory)
storage__.bytes = 0xCC;
}
// static if (anySatisfy!(hasOpPostMove, _Payload))
// void opPostMove(const ref typeof(this) old)
// {
// S: switch (identifier__)