1 // Written in the D programming language.
4 This module implements a
5 $(HTTP erdani.org/publications/cuj-04-2002.html,discriminated union)
7 $(HTTP en.wikipedia.org/wiki/Tagged_union,tagged union),
8 $(HTTP en.wikipedia.org/wiki/Algebraic_data_type,algebraic type)).
10 for type-uniform binary interfaces, interfacing with scripting
11 languages, and comfortable exploratory programming.
13 A $(LREF Variant) object can hold a value of any type, with very few
14 restrictions (such as `shared` types and noncopyable types). Setting the value
15 is as immediate as assigning to the `Variant` object. To read back the value of
16 the appropriate type `T`, use the $(LREF get!T) call. To query whether a
17 `Variant` currently holds a value of type `T`, use $(LREF peek!T). To fetch the
18 exact type currently held, call $(LREF type), which returns the `TypeInfo` of
21 In addition to $(LREF Variant), this module also defines the $(LREF Algebraic)
22 type constructor. Unlike `Variant`, `Algebraic` only allows a finite set of
23 types, which are specified in the instantiation (e.g. $(D Algebraic!(int,
24 string)) may only hold an `int` or a `string`).
26 Credits: Reviewed by Brad Roberts. Daniel Keep provided a detailed code review
27 prompting the following improvements: (1) better support for arrays; (2) support
28 for associative arrays; (3) friendlier behavior towards the garbage collector.
29 Copyright: Copyright Andrei Alexandrescu 2007 - 2015.
30 License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
31 Authors: $(HTTP erdani.org, Andrei Alexandrescu)
32 Source: $(PHOBOSSRC std/_variant.d)
36 import std.meta, std.traits, std.typecons;
41 Variant a; // Must assign before use, otherwise exception ensues
42 // Initialize with an integer; make the type int
44 assert(b.type == typeid(int));
46 assert(b.peek!(int) !is null && *b.peek!(int) == 42);
47 // Automatically convert per language rules
48 auto x = b.get!(real);
50 // Assign any other type, including other variants
53 assert(a.type == typeid(double));
54 // Implicit conversions work just as with built-in types
56 // Check for convertibility
57 assert(!a.convertsTo!(int)); // double not convertible to int
58 // Strings and all other arrays are supported
59 a = "now I'm a string";
60 assert(a == "now I'm a string");
62 // can also assign arrays
64 assert(a.length == 42);
68 // Can also assign class values
72 assert(*a.peek!(Foo) == foo); // and full type information is preserved
76 Gives the $(D sizeof) the largest type given.
78 template maxSize(T...)
80 static if (T.length == 1)
82 enum size_t maxSize = T[0].sizeof;
86 import std.algorithm.comparison : max;
87 enum size_t maxSize = max(T[0].sizeof, maxSize!(T[1 .. $]));
94 static assert(maxSize!(int, long) == 8);
95 static assert(maxSize!(bool, byte) == 1);
97 struct Cat { int a, b, c; }
98 static assert(maxSize!(bool, Cat) == 12);
103 private alias This2Variant(V, T...) = AliasSeq!(ReplaceType!(This, V, T));
106 * Back-end type seldom used directly by user
107 * code. Two commonly-used types using $(D VariantN) are:
109 * $(OL $(LI $(LREF Algebraic): A closed discriminated union with a
110 * limited type universe (e.g., $(D Algebraic!(int, double,
111 * string)) only accepts these three types and rejects anything
112 * else).) $(LI $(LREF Variant): An open discriminated union allowing an
113 * unbounded set of types. If any of the types in the $(D Variant)
114 * are larger than the largest built-in type, they will automatically
115 * be boxed. This means that even large types will only be the size
116 * of a pointer within the $(D Variant), but this also implies some
117 * overhead. $(D Variant) can accommodate all primitive types and
118 * all user-defined types.))
120 * Both $(D Algebraic) and $(D Variant) share $(D
121 * VariantN)'s interface. (See their respective documentations below.)
123 * $(D VariantN) is a discriminated union type parameterized
124 * with the largest size of the types stored ($(D maxDataSize))
125 * and with the list of allowed types ($(D AllowedTypes)). If
126 * the list is empty, then any type up of size up to $(D
127 * maxDataSize) (rounded up for alignment) can be stored in a
128 * $(D VariantN) object without being boxed (types larger
129 * than this will be boxed).
132 struct VariantN(size_t maxDataSize, AllowedTypesParam...)
135 The list of allowed types. If empty, any type is allowed.
137 alias AllowedTypes = This2Variant!(VariantN, AllowedTypesParam);
140 // Compute the largest practical size from maxDataSize
144 ubyte[maxDataSize] data;
146 enum size = SizeChecker.sizeof - (int function()).sizeof;
148 /** Tells whether a type $(D T) is statically _allowed for
149 * storage inside a $(D VariantN) object by looking
150 * $(D T) up in $(D AllowedTypes).
152 public template allowed(T)
157 //T.sizeof <= size &&
158 (AllowedTypes.length == 0 || staticIndexOf!(T, AllowedTypes) >= 0);
161 // Each internal operation is encoded with an identifier. See
162 // the "handler" function below.
163 enum OpID { getTypeInfo, get, compare, equals, testConversion, toString,
164 index, indexAssign, catAssign, copyOut, length,
165 apply, postblit, destruct }
168 ptrdiff_t function(OpID selector, ubyte[size]* store, void* data) fptr
173 // conservatively mark the region as pointers
174 static if (size >= (void*).sizeof)
175 void*[size / (void*).sizeof] p;
179 // Handler for an uninitialized value
180 static ptrdiff_t handler(A : void)(OpID selector, ubyte[size]*, void* parm)
184 case OpID.getTypeInfo:
185 *cast(TypeInfo *) parm = typeid(A);
188 auto target = cast(VariantN *) parm;
189 target.fptr = &handler!(A);
190 // no need to copy the data (it's garbage)
194 auto rhs = cast(const VariantN *) parm;
196 ? 0 // all uninitialized are equal
197 : ptrdiff_t.min; // uninitialized variant is not comparable otherwise
199 string * target = cast(string*) parm;
200 *target = "<Uninitialized VariantN>";
206 case OpID.testConversion:
208 case OpID.indexAssign:
211 throw new VariantException(
212 "Attempt to use an uninitialized VariantN");
213 default: assert(false, "Invalid OpID");
218 // Handler for all of a type's operations
219 static ptrdiff_t handler(A)(OpID selector, ubyte[size]* pStore, void* parm)
221 import std.conv : to;
222 static A* getPtr(void* untyped)
226 static if (A.sizeof <= size)
227 return cast(A*) untyped;
229 return *cast(A**) untyped;
234 static ptrdiff_t compare(A* rhsPA, A* zis, OpID selector)
236 static if (is(typeof(*rhsPA == *zis)))
242 static if (is(typeof(*zis < *rhsPA)))
244 // Many types (such as any using the default Object opCmp)
245 // will throw on an invalid opCmp, so do it only
246 // if the caller requests it.
247 if (selector == OpID.compare)
248 return *zis < *rhsPA ? -1 : 1;
250 return ptrdiff_t.min;
254 // Not equal, and type does not support ordering
256 return ptrdiff_t.min;
261 // Type does not support comparisons at all.
262 return ptrdiff_t.min;
266 auto zis = getPtr(pStore);
267 // Input: TypeInfo object
268 // Output: target points to a copy of *me, if me was not null
269 // Returns: true iff the A can be converted to the type represented
270 // by the incoming TypeInfo
271 static bool tryPutting(A* src, TypeInfo targetType, void* target)
274 alias MutaTypes = AliasSeq!(UA, ImplicitConversionTargets!UA);
275 alias ConstTypes = staticMap!(ConstOf, MutaTypes);
276 alias SharedTypes = staticMap!(SharedOf, MutaTypes);
277 alias SharedConstTypes = staticMap!(SharedConstOf, MutaTypes);
278 alias ImmuTypes = staticMap!(ImmutableOf, MutaTypes);
280 static if (is(A == immutable))
281 alias AllTypes = AliasSeq!(ImmuTypes, ConstTypes, SharedConstTypes);
282 else static if (is(A == shared))
284 static if (is(A == const))
285 alias AllTypes = SharedConstTypes;
287 alias AllTypes = AliasSeq!(SharedTypes, SharedConstTypes);
291 static if (is(A == const))
292 alias AllTypes = ConstTypes;
294 alias AllTypes = AliasSeq!(MutaTypes, ConstTypes);
297 foreach (T ; AllTypes)
299 if (targetType != typeid(T))
302 static if (is(typeof(*cast(T*) target = *src)) ||
303 is(T == const(U), U) ||
304 is(T == shared(U), U) ||
305 is(T == shared const(U), U) ||
306 is(T == immutable(U), U))
308 import std.conv : emplaceRef;
310 auto zat = cast(T*) target;
313 static if (T.sizeof > 0)
314 assert(target, "target must be non-null");
316 emplaceRef(*cast(Unqual!T*) zat, *cast(UA*) src);
321 // type T is not constructible from A
323 assert(false, A.stringof);
332 case OpID.getTypeInfo:
333 *cast(TypeInfo *) parm = typeid(A);
336 auto target = cast(VariantN *) parm;
339 static if (target.size < A.sizeof)
341 if (target.type.tsize < A.sizeof)
342 *cast(A**)&target.store = new A;
344 tryPutting(zis, typeid(A), cast(void*) getPtr(&target.store))
346 target.fptr = &handler!(A);
349 auto t = * cast(Tuple!(TypeInfo, void*)*) parm;
350 return !tryPutting(zis, t[0], t[1]);
351 case OpID.testConversion:
352 return !tryPutting(null, *cast(TypeInfo*) parm, null);
355 auto rhsP = cast(VariantN *) parm;
356 auto rhsType = rhsP.type;
358 if (rhsType == typeid(A))
361 auto rhsPA = getPtr(&rhsP.store);
362 return compare(rhsPA, zis, selector);
364 else if (rhsType == typeid(void))
366 // No support for ordering comparisons with
367 // uninitialized vars
368 return ptrdiff_t.min;
371 // Do I convert to rhs?
372 if (tryPutting(zis, rhsType, &temp.store))
374 // cool, I do; temp's store contains my data in rhs's type!
375 // also fix up its fptr
376 temp.fptr = rhsP.fptr;
377 // now lhsWithRhsType is a full-blown VariantN of rhs's type
378 if (selector == OpID.compare)
379 return temp.opCmp(*rhsP);
381 return temp.opEquals(*rhsP) ? 0 : 1;
383 // Does rhs convert to zis?
384 auto t = tuple(typeid(A), &temp.store);
385 if (rhsP.fptr(OpID.get, &rhsP.store, &t) == 0)
387 // cool! Now temp has rhs in my type!
388 auto rhsPA = getPtr(&temp.store);
389 return compare(rhsPA, zis, selector);
391 return ptrdiff_t.min; // dunno
393 auto target = cast(string*) parm;
394 static if (is(typeof(to!(string)(*zis))))
396 *target = to!(string)(*zis);
399 // TODO: The following test evaluates to true for shared objects.
400 // Use __traits for now until this is sorted out.
401 // else static if (is(typeof((*zis).toString)))
402 else static if (__traits(compiles, {(*zis).toString();}))
404 *target = (*zis).toString();
409 throw new VariantException(typeid(A), typeid(string));
413 auto result = cast(Variant*) parm;
414 static if (isArray!(A) && !is(Unqual!(typeof(A.init[0])) == void))
416 // array type; input and output are the same VariantN
417 size_t index = result.convertsTo!(int)
418 ? result.get!(int) : result.get!(size_t);
419 *result = (*zis)[index];
422 else static if (isAssociativeArray!(A))
424 *result = (*zis)[result.get!(typeof(A.init.keys[0]))];
429 throw new VariantException(typeid(A), result[0].type);
432 case OpID.indexAssign:
433 // array type; result comes first, index comes second
434 auto args = cast(Variant*) parm;
435 static if (isArray!(A) && is(typeof((*zis)[0] = (*zis)[0])))
437 size_t index = args[1].convertsTo!(int)
438 ? args[1].get!(int) : args[1].get!(size_t);
439 (*zis)[index] = args[0].get!(typeof((*zis)[0]));
442 else static if (isAssociativeArray!(A))
444 (*zis)[args[1].get!(typeof(A.init.keys[0]))]
445 = args[0].get!(typeof(A.init.values[0]));
450 throw new VariantException(typeid(A), args[0].type);
454 static if (!is(Unqual!(typeof((*zis)[0])) == void) && is(typeof((*zis)[0])) && is(typeof((*zis) ~= *zis)))
456 // array type; parm is the element to append
457 auto arg = cast(Variant*) parm;
458 alias E = typeof((*zis)[0]);
459 if (arg[0].convertsTo!(E))
461 // append one element to the array
462 (*zis) ~= [ arg[0].get!(E) ];
466 // append a whole array to the array
467 (*zis) ~= arg[0].get!(A);
473 throw new VariantException(typeid(A), typeid(void[]));
477 static if (isArray!(A) || isAssociativeArray!(A))
483 throw new VariantException(typeid(A), typeid(void[]));
487 static if (!isFunctionPointer!A && !isDelegate!A)
489 import std.conv : text;
490 import std.exception : enforce;
491 enforce(0, text("Cannot apply `()' to a value of type `",
496 import std.conv : text;
497 import std.exception : enforce;
498 alias ParamTypes = Parameters!A;
499 auto p = cast(Variant*) parm;
500 auto argCount = p.get!size_t;
501 // To assign the tuple we need to use the unqualified version,
502 // otherwise we run into issues such as with const values.
503 // We still get the actual type from the Variant though
504 // to ensure that we retain const correctness.
505 Tuple!(staticMap!(Unqual, ParamTypes)) t;
506 enforce(t.length == argCount,
507 text("Argument count mismatch: ",
508 A.stringof, " expects ", t.length,
509 " argument(s), not ", argCount, "."));
510 auto variantArgs = p[1 .. argCount + 1];
511 foreach (i, T; ParamTypes)
513 t[i] = cast() variantArgs[i].get!T;
516 auto args = cast(Tuple!(ParamTypes))t;
517 static if (is(ReturnType!A == void))
520 *p = Variant.init; // void returns uninitialized Variant.
524 *p = (*zis)(args.expand);
530 static if (hasElaborateCopyConstructor!A)
532 typeid(A).postblit(zis);
537 static if (hasElaborateDestructor!A)
539 typeid(A).destroy(zis);
543 default: assert(false);
548 enum doUnittest = is(VariantN == Variant);
551 /** Constructs a $(D VariantN) value given an argument of a
552 * generic type. Statically rejects disallowed types.
557 static assert(allowed!(T), "Cannot store a " ~ T.stringof
558 ~ " in a " ~ VariantN.stringof);
562 /// Allows assignment from a subset algebraic type
563 this(T : VariantN!(tsize, Types), size_t tsize, Types...)(T value)
564 if (!is(T : VariantN) && Types.length > 0 && allSatisfy!(allowed, Types))
569 static if (!AllowedTypes.length || anySatisfy!(hasElaborateCopyConstructor, AllowedTypes))
573 fptr(OpID.postblit, &store, null);
577 static if (!AllowedTypes.length || anySatisfy!(hasElaborateDestructor, AllowedTypes))
581 fptr(OpID.destruct, &store, null);
585 /** Assigns a $(D VariantN) from a generic
586 * argument. Statically rejects disallowed types. */
588 VariantN opAssign(T)(T rhs)
590 //writeln(typeid(rhs));
591 static assert(allowed!(T), "Cannot store a " ~ T.stringof
592 ~ " in a " ~ VariantN.stringof ~ ". Valid types are "
593 ~ AllowedTypes.stringof);
595 static if (is(T : VariantN))
597 rhs.fptr(OpID.copyOut, &rhs.store, &this);
599 else static if (is(T : const(VariantN)))
602 "Assigning Variant objects from const Variant"~
603 " objects is currently not supported.");
607 static if (!AllowedTypes.length || anySatisfy!(hasElaborateDestructor, AllowedTypes))
609 // Assignment should destruct previous value
610 fptr(OpID.destruct, &store, null);
613 static if (T.sizeof <= size)
615 import core.stdc.string : memcpy;
616 // If T is a class we're only copying the reference, so it
617 // should be safe to cast away shared so the memcpy will work.
619 // TODO: If a shared class has an atomic reference then using
620 // an atomic load may be more correct. Just make sure
621 // to use the fastest approach for the load op.
622 static if (is(T == class) && is(T == shared))
623 memcpy(&store, cast(const(void*)) &rhs, rhs.sizeof);
625 memcpy(&store, &rhs, rhs.sizeof);
626 static if (hasElaborateCopyConstructor!T)
628 typeid(T).postblit(&store);
633 import core.stdc.string : memcpy;
634 static if (__traits(compiles, {new T(T.init);}))
643 memcpy(&store, &p, p.sizeof);
650 // Allow assignment from another variant which is a subset of this one
651 VariantN opAssign(T : VariantN!(tsize, Types), size_t tsize, Types...)(T rhs)
652 if (!is(T : VariantN) && Types.length > 0 && allSatisfy!(allowed, Types))
654 // discover which type rhs is actually storing
655 foreach (V; T.AllowedTypes)
656 if (rhs.type == typeid(V))
657 return this = rhs.get!V;
658 assert(0, T.AllowedTypes.stringof);
662 Variant opCall(P...)(auto ref P params)
664 Variant[P.length + 1] pack;
666 foreach (i, _; params)
668 pack[i + 1] = params[i];
670 fptr(OpID.apply, &store, &pack);
674 /** Returns true if and only if the $(D VariantN) object
675 * holds a valid value (has been initialized with, or assigned
676 * from, a valid value).
678 @property bool hasValue() const pure nothrow
680 // @@@BUG@@@ in compiler, the cast shouldn't be needed
681 return cast(typeof(&handler!(void))) fptr != &handler!(void);
685 static if (doUnittest)
692 assert(!a.hasValue); // still no value
698 * If the $(D VariantN) object holds a value of the
699 * $(I exact) type $(D T), returns a pointer to that
700 * value. Otherwise, returns $(D null). In cases
701 * where $(D T) is statically disallowed, $(D
702 * peek) will not compile.
704 @property inout(T)* peek(T)() inout
706 static if (!is(T == void))
707 static assert(allowed!(T), "Cannot store a " ~ T.stringof
708 ~ " in a " ~ VariantN.stringof);
709 if (type != typeid(T))
711 static if (T.sizeof <= size)
712 return cast(inout T*)&store;
714 return *cast(inout T**)&store;
718 static if (doUnittest)
722 auto b = a.peek!(int);
729 * Returns the $(D typeid) of the currently held value.
732 @property TypeInfo type() const nothrow @trusted
734 scope(failure) assert(0);
737 fptr(OpID.getTypeInfo, null, &result);
742 * Returns $(D true) if and only if the $(D VariantN)
743 * object holds an object implicitly convertible to type `T`.
744 * Implicit convertibility is defined as per
745 * $(REF_ALTTEXT ImplicitConversionTargets, ImplicitConversionTargets, std,traits).
748 @property bool convertsTo(T)() const
750 TypeInfo info = typeid(T);
751 return fptr(OpID.testConversion, null, &info) == 0;
755 Returns the value stored in the `VariantN` object, either by specifying the
756 needed type or the index in the list of allowed types. The latter overload
757 only applies to bounded variants (e.g. $(LREF Algebraic)).
760 T = The requested type. The currently stored value must implicitly convert
761 to the requested type, in fact `DecayStaticToDynamicArray!T`. If an
762 implicit conversion is not possible, throws a `VariantException`.
763 index = The index of the type among `AllowedTypesParam`, zero-based.
765 @property inout(T) get(T)() inout
767 inout(T) result = void;
768 static if (is(T == shared))
769 alias R = shared Unqual!T;
772 auto buf = tuple(typeid(T), cast(R*)&result);
774 if (fptr(OpID.get, cast(ubyte[size]*) &store, &buf))
776 throw new VariantException(type, typeid(T));
782 @property auto get(uint index)() inout
783 if (index < AllowedTypes.length)
785 foreach (i, T; AllowedTypes)
787 static if (index == i) return get!T;
793 * Returns the value stored in the $(D VariantN) object,
794 * explicitly converted (coerced) to the requested type $(D
795 * T). If $(D T) is a string type, the value is formatted as
796 * a string. If the $(D VariantN) object is a string, a
797 * parse of the string to type $(D T) is attempted. If a
798 * conversion is not possible, throws a $(D
802 @property T coerce(T)()
804 import std.conv : to, text;
805 static if (isNumeric!T || isBoolean!T)
809 // maybe optimize this fella; handle ints separately
810 return to!T(get!real);
812 else if (convertsTo!(const(char)[]))
814 return to!T(get!(const(char)[]));
816 // I'm not sure why this doesn't convert to const(char),
817 // but apparently it doesn't (probably a deeper bug).
819 // Until that is fixed, this quick addition keeps a common
820 // function working. "10".coerce!int ought to work.
821 else if (convertsTo!(immutable(char)[]))
823 return to!T(get!(immutable(char)[]));
827 import std.exception : enforce;
828 enforce(false, text("Type ", type, " does not convert to ",
833 else static if (is(T : Object))
835 return to!(T)(get!(Object));
837 else static if (isSomeString!(T))
839 return to!(T)(toString());
844 static assert(false, "unsupported type for coercion");
849 * Formats the stored value as a string.
855 fptr(OpID.toString, &store, &result) == 0 || assert(false);
860 * Comparison for equality used by the "==" and "!=" operators.
863 // returns 1 if the two are equal
864 bool opEquals(T)(auto ref T rhs) const
865 if (allowed!T || is(Unqual!T == VariantN))
867 static if (is(Unqual!T == VariantN))
870 auto temp = VariantN(rhs);
871 return !fptr(OpID.equals, cast(ubyte[size]*) &store,
875 // workaround for bug 10567 fix
876 int opCmp(ref const VariantN rhs) const
878 return (cast() this).opCmp!(VariantN)(cast() rhs);
882 * Ordering comparison used by the "<", "<=", ">", and ">="
883 * operators. In case comparison is not sensible between the held
884 * value and $(D rhs), an exception is thrown.
888 if (allowed!T) // includes T == VariantN
890 static if (is(T == VariantN))
893 auto temp = VariantN(rhs);
894 auto result = fptr(OpID.compare, &store, &temp);
895 if (result == ptrdiff_t.min)
897 throw new VariantException(type, temp.type);
900 assert(result >= -1 && result <= 1); // Should be true for opCmp.
901 return cast(int) result;
905 * Computes the hash of the held value.
908 size_t toHash() const nothrow @safe
910 return type.getHash(&store);
913 private VariantN opArithmetic(T, string op)(T other)
915 static if (isInstanceOf!(.VariantN, T))
917 string tryUseType(string tp)
919 import std.format : format;
921 static if (allowed!%1$s && T.allowed!%1$s)
922 if (convertsTo!%1$s && other.convertsTo!%1$s)
923 return VariantN(get!%1$s %2$s other.get!%1$s);
927 mixin(tryUseType("uint"));
928 mixin(tryUseType("int"));
929 mixin(tryUseType("ulong"));
930 mixin(tryUseType("long"));
931 mixin(tryUseType("float"));
932 mixin(tryUseType("double"));
933 mixin(tryUseType("real"));
937 static if (allowed!T)
938 if (auto pv = peek!T) return VariantN(mixin("*pv " ~ op ~ " other"));
939 static if (allowed!uint && is(typeof(T.max) : uint) && isUnsigned!T)
940 if (convertsTo!uint) return VariantN(mixin("get!(uint) " ~ op ~ " other"));
941 static if (allowed!int && is(typeof(T.max) : int) && !isUnsigned!T)
942 if (convertsTo!int) return VariantN(mixin("get!(int) " ~ op ~ " other"));
943 static if (allowed!ulong && is(typeof(T.max) : ulong) && isUnsigned!T)
944 if (convertsTo!ulong) return VariantN(mixin("get!(ulong) " ~ op ~ " other"));
945 static if (allowed!long && is(typeof(T.max) : long) && !isUnsigned!T)
946 if (convertsTo!long) return VariantN(mixin("get!(long) " ~ op ~ " other"));
947 static if (allowed!float && is(T : float))
948 if (convertsTo!float) return VariantN(mixin("get!(float) " ~ op ~ " other"));
949 static if (allowed!double && is(T : double))
950 if (convertsTo!double) return VariantN(mixin("get!(double) " ~ op ~ " other"));
951 static if (allowed!real && is (T : real))
952 if (convertsTo!real) return VariantN(mixin("get!(real) " ~ op ~ " other"));
955 throw new VariantException("No possible match found for VariantN "~op~" "~T.stringof);
958 private VariantN opLogic(T, string op)(T other)
961 static if (is(T == VariantN))
963 if (convertsTo!(uint) && other.convertsTo!(uint))
964 result = mixin("get!(uint) " ~ op ~ " other.get!(uint)");
965 else if (convertsTo!(int) && other.convertsTo!(int))
966 result = mixin("get!(int) " ~ op ~ " other.get!(int)");
967 else if (convertsTo!(ulong) && other.convertsTo!(ulong))
968 result = mixin("get!(ulong) " ~ op ~ " other.get!(ulong)");
970 result = mixin("get!(long) " ~ op ~ " other.get!(long)");
974 if (is(typeof(T.max) : uint) && T.min == 0 && convertsTo!(uint))
975 result = mixin("get!(uint) " ~ op ~ " other");
976 else if (is(typeof(T.max) : int) && T.min < 0 && convertsTo!(int))
977 result = mixin("get!(int) " ~ op ~ " other");
978 else if (is(typeof(T.max) : ulong) && T.min == 0
979 && convertsTo!(ulong))
980 result = mixin("get!(ulong) " ~ op ~ " other");
982 result = mixin("get!(long) " ~ op ~ " other");
988 * Arithmetic between $(D VariantN) objects and numeric
989 * values. All arithmetic operations return a $(D VariantN)
990 * object typed depending on the types of both values
991 * involved. The conversion rules mimic D's built-in rules for
992 * arithmetic conversions.
995 // Adapted from http://www.prowiki.org/wiki4d/wiki.cgi?DanielKeep/Variant
997 VariantN opAdd(T)(T rhs) { return opArithmetic!(T, "+")(rhs); }
999 VariantN opSub(T)(T rhs) { return opArithmetic!(T, "-")(rhs); }
1001 // Commenteed all _r versions for now because of ambiguities
1002 // arising when two Variants are used
1005 // VariantN opSub_r(T)(T lhs)
1007 // return VariantN(lhs).opArithmetic!(VariantN, "-")(this);
1010 VariantN opMul(T)(T rhs) { return opArithmetic!(T, "*")(rhs); }
1012 VariantN opDiv(T)(T rhs) { return opArithmetic!(T, "/")(rhs); }
1014 // VariantN opDiv_r(T)(T lhs)
1016 // return VariantN(lhs).opArithmetic!(VariantN, "/")(this);
1019 VariantN opMod(T)(T rhs) { return opArithmetic!(T, "%")(rhs); }
1021 // VariantN opMod_r(T)(T lhs)
1023 // return VariantN(lhs).opArithmetic!(VariantN, "%")(this);
1026 VariantN opAnd(T)(T rhs) { return opLogic!(T, "&")(rhs); }
1028 VariantN opOr(T)(T rhs) { return opLogic!(T, "|")(rhs); }
1030 VariantN opXor(T)(T rhs) { return opLogic!(T, "^")(rhs); }
1032 VariantN opShl(T)(T rhs) { return opLogic!(T, "<<")(rhs); }
1034 // VariantN opShl_r(T)(T lhs)
1036 // return VariantN(lhs).opLogic!(VariantN, "<<")(this);
1039 VariantN opShr(T)(T rhs) { return opLogic!(T, ">>")(rhs); }
1041 // VariantN opShr_r(T)(T lhs)
1043 // return VariantN(lhs).opLogic!(VariantN, ">>")(this);
1046 VariantN opUShr(T)(T rhs) { return opLogic!(T, ">>>")(rhs); }
1048 // VariantN opUShr_r(T)(T lhs)
1050 // return VariantN(lhs).opLogic!(VariantN, ">>>")(this);
1053 VariantN opCat(T)(T rhs)
1060 // VariantN opCat_r(T)(T rhs)
1062 // VariantN temp = rhs;
1068 VariantN opAddAssign(T)(T rhs) { return this = this + rhs; }
1070 VariantN opSubAssign(T)(T rhs) { return this = this - rhs; }
1072 VariantN opMulAssign(T)(T rhs) { return this = this * rhs; }
1074 VariantN opDivAssign(T)(T rhs) { return this = this / rhs; }
1076 VariantN opModAssign(T)(T rhs) { return this = this % rhs; }
1078 VariantN opAndAssign(T)(T rhs) { return this = this & rhs; }
1080 VariantN opOrAssign(T)(T rhs) { return this = this | rhs; }
1082 VariantN opXorAssign(T)(T rhs) { return this = this ^ rhs; }
1084 VariantN opShlAssign(T)(T rhs) { return this = this << rhs; }
1086 VariantN opShrAssign(T)(T rhs) { return this = this >> rhs; }
1088 VariantN opUShrAssign(T)(T rhs) { return this = this >>> rhs; }
1090 VariantN opCatAssign(T)(T rhs)
1092 auto toAppend = Variant(rhs);
1093 fptr(OpID.catAssign, &store, &toAppend) == 0 || assert(false);
1098 * Array and associative array operations. If a $(D
1099 * VariantN) contains an (associative) array, it can be indexed
1100 * into. Otherwise, an exception is thrown.
1102 inout(Variant) opIndex(K)(K i) inout
1104 auto result = Variant(i);
1105 fptr(OpID.index, cast(ubyte[size]*) &store, &result) == 0 || assert(false);
1110 static if (doUnittest)
1113 Variant a = new int[10];
1119 int[int] hash = [ 42:24 ];
1121 assert(a[42] == 24);
1123 assert(a[42] == 12);
1127 Variant opIndexAssign(T, N)(T value, N i)
1129 static if (AllowedTypes.length && !isInstanceOf!(.VariantN, T))
1131 enum canAssign(U) = __traits(compiles, (U u){ u[i] = value; });
1132 static assert(anySatisfy!(canAssign, AllowedTypes),
1133 "Cannot assign " ~ T.stringof ~ " to " ~ VariantN.stringof ~
1134 " indexed with " ~ N.stringof);
1136 Variant[2] args = [ Variant(value), Variant(i) ];
1137 fptr(OpID.indexAssign, &store, &args) == 0 || assert(false);
1142 Variant opIndexOpAssign(string op, T, N)(T value, N i)
1144 return opIndexAssign(mixin(`opIndex(i)` ~ op ~ `value`), i);
1147 /** If the $(D VariantN) contains an (associative) array,
1148 * returns the _length of that array. Otherwise, throws an
1151 @property size_t length()
1153 return cast(size_t) fptr(OpID.length, &store, null);
1157 If the $(D VariantN) contains an array, applies $(D dg) to each
1158 element of the array in turn. Otherwise, throws an exception.
1160 int opApply(Delegate)(scope Delegate dg) if (is(Delegate == delegate))
1162 alias A = Parameters!(Delegate)[0];
1163 if (type == typeid(A[]))
1165 auto arr = get!(A[]);
1166 foreach (ref e; arr)
1168 if (dg(e)) return 1;
1171 else static if (is(A == VariantN))
1173 foreach (i; 0 .. length)
1175 // @@@TODO@@@: find a better way to not confuse
1176 // clients who think they change values stored in the
1177 // Variant when in fact they are only changing tmp.
1179 debug scope(exit) assert(tmp == this[i]);
1180 if (dg(tmp)) return 1;
1185 import std.conv : text;
1186 import std.exception : enforce;
1187 enforce(false, text("Variant type ", type,
1188 " not iterable with values of type ",
1197 import std.conv : to;
1199 int foo() { return 42; }
1203 static int bar(string s) { return to!int(s); }
1205 assert(v("43") == 43);
1210 int[int] hash = [ 42:24 ];
1212 assert(v[42] == 24);
1217 // opIndex with static arrays, issue 12771
1220 int[4] elements = [0, 1, 2, 3];
1221 Variant v = elements;
1222 assert(v == elements);
1227 assert(v != elements);
1232 import std.exception : assertThrown;
1233 Algebraic!(int[]) v = [2, 2];
1235 assert(v == [2, 2]);
1238 assert(v != [2, 2]);
1240 // opIndexAssign from Variant
1244 static assert(!__traits(compiles, (v[1] = null)));
1245 assertThrown!VariantException(v[1] = Variant(null));
1260 static assert(S.sizeof >= Variant.sizeof);
1261 alias Types = AliasSeq!(string, int, S);
1262 alias MyVariant = VariantN!(maxSize!Types, Types);
1264 auto v = MyVariant(S.init);
1265 assert(v == S.init);
1271 // Primarily test that we can assign a void[] to a Variant.
1272 void[] elements = cast(void[])[1, 2, 3];
1273 Variant v = elements;
1274 void[] returned = v.get!(void[]);
1275 assert(returned == elements);
1281 alias TP = Algebraic!(long);
1284 assert(!TP.allowed!ulong);
1285 assert(a + b == 3L);
1286 assert(a + 2 == 3L);
1287 assert(1 + b == 3L);
1289 alias TP2 = Algebraic!(long, string);
1291 assert(a + c == 4L);
1297 alias A = Algebraic!(string[]);
1299 assert(a[0] == "a");
1300 assert(a[1] == "b");
1302 assert(a[1] == "c");
1304 alias AA = Algebraic!(int[string]);
1305 AA aa = ["a": 1, "b": 2];
1306 assert(aa["a"] == 1);
1307 assert(aa["b"] == 2);
1309 assert(aa["b"] == 3);
1316 assert(a.type == typeid(bool));
1322 alias Atom = Algebraic!(string, This[]);
1325 auto a = Atom(values);
1331 Algebraic!(int, double) a;
1339 alias A = Algebraic!(int, float, double);
1340 alias B = Algebraic!(int, float);
1346 assert(a.type == typeid(float));
1347 assert(a.get!float == 6f);
1356 ~this() {assert(x == 42);}
1364 const Variant v = new immutable Object;
1365 v.get!(immutable Object);
1372 T opCast(T)() {assert(false);}
1380 _Algebraic data type restricted to a closed set of possible
1381 types. It's an alias for $(LREF VariantN) with an
1382 appropriately-constructed maximum size. `Algebraic` is
1383 useful when it is desirable to restrict what a discriminated type
1384 could hold to the end of defining simpler and more efficient
1388 template Algebraic(T...)
1390 alias Algebraic = VariantN!(maxSize!T, T);
1396 auto v = Algebraic!(int, double, string)(5);
1397 assert(v.peek!(int));
1399 assert(v.peek!(double));
1400 // auto x = v.peek!(long); // won't compile, type long not allowed
1401 // v = '1'; // won't compile, type char not allowed
1405 $(H4 Self-Referential Types)
1407 A useful and popular use of algebraic data structures is for defining $(LUCKY
1408 self-referential data structures), i.e. structures that embed references to
1409 values of their own type within.
1411 This is achieved with `Algebraic` by using `This` as a placeholder whenever a
1412 reference to the type being defined is needed. The `Algebraic` instantiation
1413 will perform $(LINK2 https://en.wikipedia.org/wiki/Name_resolution_(programming_languages)#Alpha_renaming_to_make_name_resolution_trivial,
1414 alpha renaming) on its constituent types, replacing `This`
1415 with the self-referenced type. The structure of the type involving `This` may
1416 be arbitrarily complex.
1420 import std.typecons : Tuple, tuple;
1422 // A tree is either a leaf or a branch of two other trees
1423 alias Tree(Leaf) = Algebraic!(Leaf, Tuple!(This*, This*));
1424 Tree!int tree = tuple(new Tree!int(42), new Tree!int(43));
1425 Tree!int* right = tree.get!1[1];
1426 assert(*right == 43);
1428 // An object is a double, a string, or a hash of objects
1429 alias Obj = Algebraic!(double, string, This[string]);
1431 assert(obj.get!1 == "hello");
1433 assert(obj.get!0 == 42);
1434 obj = ["customer": Obj("John"), "paid": Obj(23.95)];
1435 assert(obj.get!2["customer"] == "John");
1439 Alias for $(LREF VariantN) instantiated with the largest size of `creal`,
1440 `char[]`, and `void delegate()`. This ensures that `Variant` is large enough
1441 to hold all of D's predefined types unboxed, including all numeric types,
1442 pointers, delegates, and class references. You may want to use
1443 $(D VariantN) directly with a different maximum size either for
1444 storing larger types unboxed, or for saving memory.
1446 alias Variant = VariantN!(maxSize!(creal, char[], void delegate()));
1449 * Returns an array of variants constructed from $(D args).
1451 * This is by design. During construction the $(D Variant) needs
1452 * static type information about the type being held, so as to store a
1453 * pointer to function for fast retrieval.
1455 Variant[] variantArray(T...)(T args)
1460 result ~= Variant(arg);
1468 auto a = variantArray(1, 3.14, "Hi!");
1469 assert(a[1] == 3.14);
1470 auto b = Variant(a); // variant array as variant
1471 assert(b[1] == 3.14);
1475 * Thrown in three cases:
1477 * $(OL $(LI An uninitialized `Variant` is used in any way except
1478 * assignment and $(D hasValue);) $(LI A $(D get) or
1479 * $(D coerce) is attempted with an incompatible target type;)
1480 * $(LI A comparison between $(D Variant) objects of
1481 * incompatible types is attempted.))
1485 // @@@ BUG IN COMPILER. THE 'STATIC' BELOW SHOULD NOT COMPILE
1486 static class VariantException : Exception
1488 /// The source type in the conversion or comparison
1490 /// The target type in the conversion or comparison
1496 this(TypeInfo source, TypeInfo target)
1498 super("Variant: attempting to use incompatible types "
1500 ~ " and " ~ target.toString());
1501 this.source = source;
1502 this.target = target;
1508 alias W1 = This2Variant!(char, int, This[int]);
1509 alias W2 = AliasSeq!(int, char[int]);
1510 static assert(is(W1 == W2));
1512 alias var_t = Algebraic!(void, string);
1518 alias A = Algebraic!(real, This[], This[int], This[This]);
1523 auto v = v1.peek!(A[]);
1533 import std.conv : ConvException;
1534 import std.exception : assertThrown, collectException;
1535 // try it with an oddly small size
1537 assert(test.size > 1);
1539 // variantArray tests
1540 auto heterogeneous = variantArray(1, 4.5, "hi");
1541 assert(heterogeneous.length == 3);
1542 auto variantArrayAsVariant = Variant(heterogeneous);
1543 assert(variantArrayAsVariant[0] == 1);
1544 assert(variantArrayAsVariant.length == 3);
1547 auto arr = Variant([1.2].dup);
1551 assert(arr[0] == 2);
1553 assert(arr[1] == 4.5);
1557 auto b = Variant(5);
1558 assert(!b.peek!(real) && b.peek!(int));
1562 assert(a == b, a.type.toString() ~ " " ~ b.type.toString());
1563 auto c = Variant("this is a string");
1565 // comparison via implicit conversions
1566 a = 42; b = 42.0; assert(a == b);
1568 // try failing conversions
1569 bool failed = false;
1572 auto d = c.get!(int);
1576 //writeln(stderr, e.toString);
1579 assert(failed); // :o)
1582 a = Variant(42); assert(a.toString() == "42");
1583 a = Variant(42.22); assert(a.toString() == "42.22");
1586 a = Variant(42.22); assert(a.coerce!(int) == 42);
1587 a = cast(short) 5; assert(a.coerce!(double) == 5);
1588 a = Variant("10"); assert(a.coerce!int == 10);
1591 assert(a.coerce!bool);
1593 assert(!a.coerce!bool);
1596 assert(a.coerce!bool);
1598 assert(!a.coerce!bool);
1599 a = Variant(float.init);
1600 assertThrown!ConvException(a.coerce!bool);
1602 a = Variant("true");
1603 assert(a.coerce!bool);
1604 a = Variant("false");
1605 assert(!a.coerce!bool);
1607 assertThrown!ConvException(a.coerce!bool);
1613 assert(a.coerce!(B1) !is null);
1615 assert(collectException(a.coerce!(B2) is null));
1616 a = cast(Object) new B2; // lose static type info; should still work
1617 assert(a.coerce!(B2) !is null);
1619 // struct Big { int a[45]; }
1623 assert(a.toHash() != 0);
1626 // tests adapted from
1627 // http://www.dsource.org/projects/tango/browser/trunk/tango/core/Variant.d?rev=2601
1632 assert(!v.hasValue);
1634 assert( v.peek!(int) );
1635 assert( v.convertsTo!(long) );
1636 assert( v.get!(int) == 42 );
1637 assert( v.get!(long) == 42L );
1638 assert( v.get!(ulong) == 42uL );
1640 v = "Hello, World!";
1641 assert( v.peek!(string) );
1643 assert( v.get!(string) == "Hello, World!" );
1644 assert(!is(char[] : wchar[]));
1645 assert( !v.convertsTo!(wchar[]) );
1646 assert( v.get!(string) == "Hello, World!" );
1648 // Literal arrays are dynamically-typed
1649 v = cast(int[4]) [1,2,3,4];
1650 assert( v.peek!(int[4]) );
1651 assert( v.get!(int[4]) == [1,2,3,4] );
1655 assert( v.peek!(int[]) );
1656 assert( v.get!(int[]) == [1,2,3,4,5] );
1660 assert( v.peek!(double) );
1661 assert( v.convertsTo!(real) );
1662 //@@@ BUG IN COMPILER: DOUBLE SHOULD NOT IMPLICITLY CONVERT TO FLOAT
1663 assert( !v.convertsTo!(float) );
1664 assert( *v.peek!(double) == 3.1413 );
1666 auto u = Variant(v);
1667 assert( u.peek!(double) );
1668 assert( *u.peek!(double) == 3.1413 );
1672 assert( v + 4 == 42 );
1673 assert( 4 + v == 42 );
1674 assert( v - 4 == 34 );
1675 assert( Variant(4) - v == -34 );
1676 assert( v * 2 == 76 );
1677 assert( 2 * v == 76 );
1678 assert( v / 2 == 19 );
1679 assert( Variant(2) / v == 0 );
1680 assert( v % 2 == 0 );
1681 assert( Variant(2) % v == 2 );
1682 assert( (v & 6) == 6 );
1683 assert( (6 & v) == 6 );
1684 assert( (v | 9) == 47 );
1685 assert( (9 | v) == 47 );
1686 assert( (v ^ 5) == 35 );
1687 assert( (5 ^ v) == 35 );
1688 assert( v << 1 == 76 );
1689 assert( Variant(1) << Variant(2) == 4 );
1690 assert( v >> 1 == 19 );
1691 assert( Variant(4) >> Variant(2) == 1 );
1692 assert( Variant("abc") ~ "def" == "abcdef" );
1693 assert( Variant("abc") ~ Variant("def") == "abcdef" );
1698 v = 38; v -= 4; assert( v == 34 );
1699 v = 38; v *= 2; assert( v == 76 );
1700 v = 38; v /= 2; assert( v == 19 );
1701 v = 38; v %= 2; assert( v == 0 );
1702 v = 38; v &= 6; assert( v == 6 );
1703 v = 38; v |= 9; assert( v == 47 );
1704 v = 38; v ^= 5; assert( v == 35 );
1705 v = 38; v <<= 1; assert( v == 76 );
1706 v = 38; v >>= 1; assert( v == 19 );
1707 v = 38; v += 1; assert( v < 40 );
1711 assert( v == "abcdef", *v.peek!(char[]) );
1712 assert( Variant(0) < Variant(42) );
1713 assert( Variant(42) > Variant(0) );
1714 assert( Variant(42) > Variant(0.1) );
1715 assert( Variant(42.1) > Variant(1) );
1716 assert( Variant(21) == Variant(21) );
1717 assert( Variant(0) != Variant(42) );
1718 assert( Variant("bar") == Variant("bar") );
1719 assert( Variant("foo") != Variant("bar") );
1722 auto v1 = Variant(42);
1723 auto v2 = Variant("foo");
1724 auto v3 = Variant(1+2.0i);
1731 assert( hash[v1] == 0 );
1732 assert( hash[v2] == 1 );
1733 assert( hash[v3] == 2 );
1741 Variant vhash = hash;
1743 assert( vhash.get!(int[char[]])["a"] == 1 );
1744 assert( vhash.get!(int[char[]])["b"] == 2 );
1745 assert( vhash.get!(int[char[]])["c"] == 3 );
1751 // check comparisons incompatible with AllowedTypes
1752 Algebraic!int v = 2;
1756 static assert(!__traits(compiles, {v == long.max;}));
1757 static assert(!__traits(compiles, {v == null;}));
1758 static assert(!__traits(compiles, {v < long.max;}));
1759 static assert(!__traits(compiles, {v > null;}));
1767 assert((va+vb).get!(int) == -1);
1768 assert((va-vb).get!(int) == 3);
1778 c = variantArray(1, 2, 3.0, "hello", 4);
1779 assert(c[3] == "hello");
1785 assert(!__traits(compiles, v.coerce!(bool delegate())));
1792 real a, b, c, d, e, f, g;
1798 v = huge; // Compile time error.
1799 assert(v.get!(Huge).e == 42);
1804 const x = Variant(42);
1805 auto y1 = x.get!(const int);
1807 //auto y2 = x.get!(immutable int)();
1813 auto v = Variant([ 1, 2, 3, 4 ][]);
1822 // test convertibility
1825 auto v = Variant("abc".dup);
1826 assert(v.convertsTo!(char[]));
1829 // http://d.puremagic.com/issues/show_bug.cgi?id=5424
1835 static class AC: A {
1842 Variant b = Variant(a);
1852 // Class and interface opEquals, issue 12157
1857 class DerivedFoo : Foo { }
1860 Foo f2 = new DerivedFoo();
1862 Variant v1 = f1, v2 = f2;
1864 assert(v1 != new Foo());
1870 // Const parameters with opCall, issue 11361.
1873 static string t1(string c) {
1877 static const(char)[] t2(const(char)[] p) {
1881 static char[] t3(int p) {
1882 import std.conv : text;
1890 assert(v1("abc") == "abca");
1891 assert(v1("abc").type == typeid(string));
1892 assert(v2("abc") == "abcb");
1894 assert(v2(cast(char[])("abc".dup)) == "abcb");
1895 assert(v2("abc").type == typeid(const(char)[]));
1897 assert(v3(4) == ['4']);
1898 assert(v3(4).type == typeid(char[]));
1904 static struct Structure { int data; }
1905 alias VariantTest = Algebraic!(Structure delegate() pure nothrow @nogc @safe);
1907 bool called = false;
1908 Structure example() pure nothrow @nogc @safe
1911 return Structure.init;
1913 auto m = VariantTest(&example);
1918 // Ordering comparisons of incompatible types, e.g. issue 7990.
1921 import std.exception : assertThrown;
1922 assertThrown!VariantException(Variant(3) < "a");
1923 assertThrown!VariantException("a" < Variant(3));
1924 assertThrown!VariantException(Variant(3) < Variant("a"));
1926 assertThrown!VariantException(Variant.init < Variant(3));
1927 assertThrown!VariantException(Variant(3) < Variant.init);
1930 // Handling of unordered types, e.g. issue 9043.
1933 import std.exception : assertThrown;
1934 static struct A { int a; }
1936 assert(Variant(A(3)) != A(4));
1938 assertThrown!VariantException(Variant(A(3)) < A(4));
1939 assertThrown!VariantException(A(3) < Variant(A(4)));
1940 assertThrown!VariantException(Variant(A(3)) < Variant(A(4)));
1943 // Handling of empty types and arrays, e.g. issue 10958
1946 class EmptyClass { }
1947 struct EmptyStruct { }
1948 alias EmptyArray = void[0];
1949 alias Alg = Algebraic!(EmptyClass, EmptyStruct, EmptyArray);
1951 Variant testEmpty(T)()
1955 assert(v.get!T == inst);
1956 assert(v.peek!T !is null);
1957 assert(*v.peek!T == inst);
1959 assert(alg.get!T == inst);
1963 testEmpty!EmptyClass();
1964 testEmpty!EmptyStruct();
1965 testEmpty!EmptyArray();
1967 // EmptyClass/EmptyStruct sizeof is 1, so we have this to test just size 0.
1968 EmptyArray arr = EmptyArray.init;
1969 Algebraic!(EmptyArray) a = arr;
1970 assert(a.length == 0);
1971 assert(a.get!EmptyArray == arr);
1974 // Handling of void function pointers / delegates, e.g. issue 11360
1977 static void t1() { }
1979 assert(v() == Variant.init);
1981 static int t2() { return 3; }
1986 // Using peek for large structs, issue 8580
1989 struct TestStruct(bool pad)
1993 ubyte[Variant.size] padding;
1997 void testPeekWith(T)()
2003 T* original = v.peek!T;
2004 assert(original.val1 == 3);
2005 assert(original.val2 == 4);
2008 T modified = v.get!T;
2009 assert(modified.val1 == 6);
2010 assert(modified.val2 == 8);
2013 testPeekWith!(TestStruct!false)();
2014 testPeekWith!(TestStruct!true)();
2018 * Applies a delegate or function to the given $(LREF Algebraic) depending on the held type,
2019 * ensuring that all types are handled by the visiting functions.
2021 * The delegate or function having the currently held value as parameter is called
2022 * with $(D variant)'s current value. Visiting handlers are passed
2023 * in the template parameter list.
2024 * It is statically ensured that all held types of
2025 * $(D variant) are handled across all handlers.
2026 * $(D visit) allows delegates and static functions to be passed
2029 * If a function with an untyped parameter is specified, this function is called
2030 * when the variant contains a type that does not match any other function.
2031 * This can be used to apply the same function across multiple possible types.
2032 * Exactly one generic function is allowed.
2034 * If a function without parameters is specified, this function is called
2035 * when `variant` doesn't hold a value. Exactly one parameter-less function
2038 * Duplicate overloads matching the same type in one of the visitors are disallowed.
2040 * Returns: The return type of visit is deduced from the visiting functions and must be
2041 * the same across all overloads.
2042 * Throws: $(LREF VariantException) if `variant` doesn't hold a value and no
2043 * parameter-less fallback function is specified.
2045 template visit(Handlers...)
2046 if (Handlers.length > 0)
2049 auto visit(VariantType)(VariantType variant)
2050 if (isAlgebraic!VariantType)
2052 return visitImpl!(true, VariantType, Handlers)(variant);
2059 Algebraic!(int, string) variant;
2062 assert(variant.visit!((string s) => cast(int) s.length,
2066 assert(variant.visit!((int i) => i,
2067 (string s) => cast(int) s.length)()
2070 // Error function usage
2071 Algebraic!(int, string) emptyVar;
2072 auto rslt = emptyVar.visit!((string s) => cast(int) s.length,
2077 // Generic function usage
2078 Algebraic!(int, float, real) number = 2;
2079 assert(number.visit!(x => x += 1) == 3);
2081 // Generic function for int/float with separate behavior for string
2082 Algebraic!(int, float, string) something = 2;
2083 assert(something.visit!((string s) => s.length, x => x) == 2); // generic
2085 assert(something.visit!((string s) => s.length, x => x) == 4); // string
2087 // Generic handler and empty handler
2088 Algebraic!(int, float, real) empty2;
2089 assert(empty2.visit!(x => x + 1, () => -1) == -1);
2094 Algebraic!(size_t, string) variant;
2096 // not all handled check
2097 static assert(!__traits(compiles, variant.visit!((size_t i){ })() ));
2099 variant = cast(size_t) 10;
2101 variant.visit!( (string s) => which = 1,
2102 (size_t i) => which = 0
2105 // integer overload was called
2108 // mustn't compile as generic Variant not supported
2110 static assert(!__traits(compiles, v.visit!((string s) => which = 1,
2111 (size_t i) => which = 0
2115 static size_t func(string s) {
2120 assert( 4 == variant.visit!(func,
2124 Algebraic!(int, float, string) variant2 = 5.0f;
2125 // Shouldn' t compile as float not handled by visitor.
2126 static assert(!__traits(compiles, variant2.visit!(
2130 Algebraic!(size_t, string, float) variant3;
2132 auto floatVisited = false;
2134 assert(variant3.visit!(
2135 (float f) { floatVisited = true; return cast(size_t) f; },
2137 (size_t i) { return i; }
2139 assert(floatVisited == true);
2141 Algebraic!(float, string) variant4;
2143 assert(variant4.visit!(func, (float f) => cast(size_t) f, () => size_t.max)() == size_t.max);
2145 // double error func check
2146 static assert(!__traits(compiles,
2147 visit!(() => size_t.max, func, (float f) => cast(size_t) f, () => size_t.max)(variant4))
2151 // disallow providing multiple generic handlers to visit
2152 // disallow a generic handler that does not apply to all types
2155 Algebraic!(int, float) number = 2;
2156 // ok, x + 1 valid for int and float
2157 static assert( __traits(compiles, number.visit!(x => x + 1)));
2158 // bad, two generic handlers
2159 static assert(!__traits(compiles, number.visit!(x => x + 1, x => x + 2)));
2160 // bad, x ~ "a" does not apply to int or float
2161 static assert(!__traits(compiles, number.visit!(x => x ~ "a")));
2162 // bad, x ~ "a" does not apply to int or float
2163 static assert(!__traits(compiles, number.visit!(x => x + 1, x => x ~ "a")));
2165 Algebraic!(int, string) maybenumber = 2;
2166 // ok, x ~ "a" valid for string, x + 1 valid for int, only 1 generic
2167 static assert( __traits(compiles, number.visit!((string x) => x ~ "a", x => x + 1)));
2168 // bad, x ~ "a" valid for string but not int
2169 static assert(!__traits(compiles, number.visit!(x => x ~ "a")));
2170 // bad, two generics, each only applies in one case
2171 static assert(!__traits(compiles, number.visit!(x => x + 1, x => x ~ "a")));
2175 * Behaves as $(LREF visit) but doesn't enforce that all types are handled
2176 * by the visiting functions.
2178 * If a parameter-less function is specified it is called when
2179 * either $(D variant) doesn't hold a value or holds a type
2180 * which isn't handled by the visiting functions.
2182 * Returns: The return type of tryVisit is deduced from the visiting functions and must be
2183 * the same across all overloads.
2184 * Throws: $(LREF VariantException) if `variant` doesn't hold a value or
2185 * `variant` holds a value which isn't handled by the visiting functions,
2186 * when no parameter-less fallback function is specified.
2188 template tryVisit(Handlers...)
2189 if (Handlers.length > 0)
2192 auto tryVisit(VariantType)(VariantType variant)
2193 if (isAlgebraic!VariantType)
2195 return visitImpl!(false, VariantType, Handlers)(variant);
2202 Algebraic!(int, string) variant;
2206 variant.tryVisit!((int i) { which = 0; })();
2209 // Error function usage
2211 variant.tryVisit!((int i) { which = 0; },
2212 () { which = -100; })();
2213 assert(which == -100);
2218 import std.exception : assertThrown;
2219 Algebraic!(int, string) variant;
2223 variant.tryVisit!((int i){ which = 0; })();
2229 assertThrown!VariantException(variant.tryVisit!((int i) { which = 0; })());
2236 variant.tryVisit!((int i) { which = 0; }, errorfunc)();
2238 assert(which == -1);
2241 private template isAlgebraic(Type)
2243 static if (is(Type _ == VariantN!T, T...))
2244 enum isAlgebraic = T.length >= 2; // T[0] == maxDataSize, T[1..$] == AllowedTypesParam
2246 enum isAlgebraic = false;
2251 static assert(!isAlgebraic!(Variant));
2252 static assert( isAlgebraic!(Algebraic!(string)));
2253 static assert( isAlgebraic!(Algebraic!(int, int[])));
2256 private auto visitImpl(bool Strict, VariantType, Handler...)(VariantType variant)
2257 if (isAlgebraic!VariantType && Handler.length > 0)
2259 alias AllowedTypes = VariantType.AllowedTypes;
2263 * Returns: Struct where $(D indices) is an array which
2264 * contains at the n-th position the index in Handler which takes the
2265 * n-th type of AllowedTypes. If an Handler doesn't match an
2266 * AllowedType, -1 is set. If a function in the delegates doesn't
2267 * have parameters, the field $(D exceptionFuncIdx) is set;
2268 * otherwise it's -1.
2270 auto visitGetOverloadMap()
2273 int[AllowedTypes.length] indices;
2274 int exceptionFuncIdx = -1;
2275 int generalFuncIdx = -1;
2280 foreach (tidx, T; AllowedTypes)
2283 foreach (dgidx, dg; Handler)
2285 // Handle normal function objects
2286 static if (isSomeFunction!dg)
2288 alias Params = Parameters!dg;
2289 static if (Params.length == 0)
2291 // Just check exception functions in the first
2292 // inner iteration (over delegates)
2297 if (result.exceptionFuncIdx != -1)
2298 assert(false, "duplicate parameter-less (error-)function specified");
2299 result.exceptionFuncIdx = dgidx;
2302 else static if (is(Params[0] == T) || is(Unqual!(Params[0]) == T))
2305 assert(false, "duplicate overload specified for type '" ~ T.stringof ~ "'");
2308 result.indices[tidx] = dgidx;
2311 else static if (isSomeFunction!(dg!T))
2313 assert(result.generalFuncIdx == -1 ||
2314 result.generalFuncIdx == dgidx,
2315 "Only one generic visitor function is allowed");
2316 result.generalFuncIdx = dgidx;
2318 // Handle composite visitors with opCall overloads
2321 static assert(false, dg.stringof ~ " is not a function or delegate");
2326 result.indices[tidx] = -1;
2332 enum HandlerOverloadMap = visitGetOverloadMap();
2334 if (!variant.hasValue)
2336 // Call the exception function. The HandlerOverloadMap
2337 // will have its exceptionFuncIdx field set to value != -1 if an
2338 // exception function has been specified; otherwise we just through an exception.
2339 static if (HandlerOverloadMap.exceptionFuncIdx != -1)
2340 return Handler[ HandlerOverloadMap.exceptionFuncIdx ]();
2342 throw new VariantException("variant must hold a value before being visited.");
2345 foreach (idx, T; AllowedTypes)
2347 if (auto ptr = variant.peek!T)
2349 enum dgIdx = HandlerOverloadMap.indices[idx];
2351 static if (dgIdx == -1)
2353 static if (HandlerOverloadMap.generalFuncIdx >= 0)
2354 return Handler[HandlerOverloadMap.generalFuncIdx](*ptr);
2355 else static if (Strict)
2356 static assert(false, "overload for type '" ~ T.stringof ~ "' hasn't been specified");
2357 else static if (HandlerOverloadMap.exceptionFuncIdx != -1)
2358 return Handler[HandlerOverloadMap.exceptionFuncIdx]();
2360 throw new VariantException(
2361 "variant holds value of type '"
2363 "' but no visitor has been provided"
2368 return Handler[ dgIdx ](*ptr);
2378 // validate that visit can be called with a const type
2379 struct Foo { int depth; }
2380 struct Bar { int depth; }
2381 alias FooBar = Algebraic!(Foo, Bar);
2383 int depth(in FooBar fb) {
2384 return fb.visit!((Foo foo) => foo.depth,
2385 (Bar bar) => bar.depth);
2389 assert(depth(fb) == 3);
2394 // https://issues.dlang.org/show_bug.cgi?id=16383
2395 class Foo {this() immutable {}}
2396 alias V = Algebraic!(immutable Foo);
2398 auto x = V(new immutable Foo).visit!(
2399 (immutable(Foo) _) => 3
2406 // http://d.puremagic.com/issues/show_bug.cgi?id=5310
2416 const Variant a = [2];
2422 // http://d.puremagic.com/issues/show_bug.cgi?id=10017
2425 ubyte[Variant.size + 1] s;
2429 v1 = S(); // the payload is allocated on the heap
2430 v2 = v1; // AssertError: target must be non-null
2435 import std.exception : assertThrown;
2436 // http://d.puremagic.com/issues/show_bug.cgi?id=7069
2441 foreach (qual; AliasSeq!(MutableOf, ConstOf))
2443 assert(v.get!(qual!int) == 10);
2444 assert(v.get!(qual!float) == 10.0f);
2446 foreach (qual; AliasSeq!(ImmutableOf, SharedOf, SharedConstOf))
2448 assertThrown!VariantException(v.get!(qual!int));
2453 foreach (qual; AliasSeq!(ConstOf))
2455 assert(v.get!(qual!int) == 20);
2456 assert(v.get!(qual!float) == 20.0f);
2458 foreach (qual; AliasSeq!(MutableOf, ImmutableOf, SharedOf, SharedConstOf))
2460 assertThrown!VariantException(v.get!(qual!int));
2461 assertThrown!VariantException(v.get!(qual!float));
2464 immutable(int) ii = ci;
2466 foreach (qual; AliasSeq!(ImmutableOf, ConstOf, SharedConstOf))
2468 assert(v.get!(qual!int) == 20);
2469 assert(v.get!(qual!float) == 20.0f);
2471 foreach (qual; AliasSeq!(MutableOf, SharedOf))
2473 assertThrown!VariantException(v.get!(qual!int));
2474 assertThrown!VariantException(v.get!(qual!float));
2479 foreach (qual; AliasSeq!(MutableOf, ConstOf))
2481 assert(v.get!(qual!(int[])) == [1,2,3]);
2482 assert(v.get!(qual!(int)[]) == [1,2,3]);
2484 foreach (qual; AliasSeq!(ImmutableOf, SharedOf, SharedConstOf))
2486 assertThrown!VariantException(v.get!(qual!(int[])));
2487 assertThrown!VariantException(v.get!(qual!(int)[]));
2490 const(int[]) cai = [4,5,6];
2492 foreach (qual; AliasSeq!(ConstOf))
2494 assert(v.get!(qual!(int[])) == [4,5,6]);
2495 assert(v.get!(qual!(int)[]) == [4,5,6]);
2497 foreach (qual; AliasSeq!(MutableOf, ImmutableOf, SharedOf, SharedConstOf))
2499 assertThrown!VariantException(v.get!(qual!(int[])));
2500 assertThrown!VariantException(v.get!(qual!(int)[]));
2503 immutable(int[]) iai = [7,8,9];
2505 //assert(v.get!(immutable(int[])) == [7,8,9]); // Bug ??? runtime error
2506 assert(v.get!(immutable(int)[]) == [7,8,9]);
2507 assert(v.get!(const(int[])) == [7,8,9]);
2508 assert(v.get!(const(int)[]) == [7,8,9]);
2509 //assert(v.get!(shared(const(int[]))) == cast(shared const)[7,8,9]); // Bug ??? runtime error
2510 //assert(v.get!(shared(const(int))[]) == cast(shared const)[7,8,9]); // Bug ??? runtime error
2511 foreach (qual; AliasSeq!(MutableOf))
2513 assertThrown!VariantException(v.get!(qual!(int[])));
2514 assertThrown!VariantException(v.get!(qual!(int)[]));
2521 foreach (qual; AliasSeq!(MutableOf, ConstOf))
2523 assert(v.get!(qual!B) is b);
2524 assert(v.get!(qual!A) is b);
2525 assert(v.get!(qual!Object) is b);
2527 foreach (qual; AliasSeq!(ImmutableOf, SharedOf, SharedConstOf))
2529 assertThrown!VariantException(v.get!(qual!B));
2530 assertThrown!VariantException(v.get!(qual!A));
2531 assertThrown!VariantException(v.get!(qual!Object));
2534 const(B) cb = new B();
2536 foreach (qual; AliasSeq!(ConstOf))
2538 assert(v.get!(qual!B) is cb);
2539 assert(v.get!(qual!A) is cb);
2540 assert(v.get!(qual!Object) is cb);
2542 foreach (qual; AliasSeq!(MutableOf, ImmutableOf, SharedOf, SharedConstOf))
2544 assertThrown!VariantException(v.get!(qual!B));
2545 assertThrown!VariantException(v.get!(qual!A));
2546 assertThrown!VariantException(v.get!(qual!Object));
2549 immutable(B) ib = new immutable(B)();
2551 foreach (qual; AliasSeq!(ImmutableOf, ConstOf, SharedConstOf))
2553 assert(v.get!(qual!B) is ib);
2554 assert(v.get!(qual!A) is ib);
2555 assert(v.get!(qual!Object) is ib);
2557 foreach (qual; AliasSeq!(MutableOf, SharedOf))
2559 assertThrown!VariantException(v.get!(qual!B));
2560 assertThrown!VariantException(v.get!(qual!A));
2561 assertThrown!VariantException(v.get!(qual!Object));
2564 shared(B) sb = new shared B();
2566 foreach (qual; AliasSeq!(SharedOf, SharedConstOf))
2568 assert(v.get!(qual!B) is sb);
2569 assert(v.get!(qual!A) is sb);
2570 assert(v.get!(qual!Object) is sb);
2572 foreach (qual; AliasSeq!(MutableOf, ImmutableOf, ConstOf))
2574 assertThrown!VariantException(v.get!(qual!B));
2575 assertThrown!VariantException(v.get!(qual!A));
2576 assertThrown!VariantException(v.get!(qual!Object));
2579 shared(const(B)) scb = new shared const B();
2581 foreach (qual; AliasSeq!(SharedConstOf))
2583 assert(v.get!(qual!B) is scb);
2584 assert(v.get!(qual!A) is scb);
2585 assert(v.get!(qual!Object) is scb);
2587 foreach (qual; AliasSeq!(MutableOf, ConstOf, ImmutableOf, SharedOf))
2589 assertThrown!VariantException(v.get!(qual!B));
2590 assertThrown!VariantException(v.get!(qual!A));
2591 assertThrown!VariantException(v.get!(qual!Object));
2597 static struct DummyScope
2599 // https://d.puremagic.com/issues/show_bug.cgi?id=12540
2600 alias Alias12540 = Algebraic!Class12540;
2602 static class Class12540
2611 // https://issues.dlang.org/show_bug.cgi?id=10194
2612 // Also test for elaborate copying
2626 @disable S opAssign();
2644 // assigning a new value should destroy the existing one
2648 // destroying the variant should destroy it's current value
2664 static assert( hasElaborateCopyConstructor!(Variant));
2665 static assert(!hasElaborateCopyConstructor!(Algebraic!bool));
2666 static assert( hasElaborateCopyConstructor!(Algebraic!S));
2667 static assert( hasElaborateCopyConstructor!(Algebraic!(bool, S)));
2669 static assert( hasElaborateDestructor!(Variant));
2670 static assert(!hasElaborateDestructor!(Algebraic!bool));
2671 static assert( hasElaborateDestructor!(Algebraic!S));
2672 static assert( hasElaborateDestructor!(Algebraic!(bool, S)));
2675 alias Value = Algebraic!bool;
2682 auto a = appender!(T[]);
2688 alias A = Algebraic!(int, typeof(null));
2689 static struct B { A value; }
2690 alias C = std.variant.Algebraic!B;
2698 import std.exception : assertThrown, assertNotThrown;
2699 // Make sure Variant can handle types with opDispatch but no length field.
2700 struct SWithNoLength
2702 void opDispatch(string s)() { }
2707 @property int opDispatch(string s)()
2709 // Assume that s == "length"
2710 return 5; // Any value is OK for test.
2714 SWithNoLength sWithNoLength;
2715 Variant v = sWithNoLength;
2716 assertThrown!VariantException(v.length);
2718 SWithLength sWithLength;
2720 assertNotThrown!VariantException(v.get!SWithLength.length);
2721 assertThrown!VariantException(v.length);
2727 static assert(!__traits(compiles, () @safe {
2728 auto foo() @system { return 3; }
2729 auto v = Variant(&foo);
2730 v(); // foo is called in safe code!?
2737 import std.typecons;
2740 alias IntTypedef = Typedef!int;
2741 alias Obj = Algebraic!(int, IntTypedef, This[]);
2756 struct NS1 { int foo() { return n + 10; } }
2757 struct NS2 { int foo() { return n * 10; } }
2761 assert(v.get!NS1.foo() == 13);
2763 assert(v.get!NS2.foo() == 30);
2769 static struct Foo15827 { Variant v; this(Foo15827 v) {} }
2770 Variant v = Foo15827.init;