1 /**
2  * Generic tagged union and algebraic data type implementations.
3  *
4  * Copyright: Copyright 2015-2019, Sönke Ludwig.
5  * License:   $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
6  * Authors:   Sönke Ludwig
7 */
8 module funkwerk.stdx.data.json.taggedalgebraic.taggedunion;
9 
10 // scheduled for deprecation
11 static import funkwerk.stdx.data.json.taggedalgebraic.visit;
12 alias visit = funkwerk.stdx.data.json.taggedalgebraic.visit.visit;
13 
14 import std.algorithm.mutation : move, swap;
15 import std.meta;
16 import std.range : isOutputRange;
17 import std.traits : EnumMembers, FieldNameTuple, Unqual, hasUDA, isInstanceOf;
18 
19 
20 /** Implements a generic tagged union type.
21 
22 	This struct takes a `union` or `struct` declaration as an input and builds
23 	an algebraic data type from its fields, using an automatically generated
24 	`Kind` enumeration to identify which field of the union is currently used.
25 	Multiple fields with the same value are supported.
26 
27 	For each field defined by `U` a number of convenience members are generated.
28 	For a given field "foo", these fields are:
29 
30 	$(UL
31 		$(LI `static foo(value)` - returns a new tagged union with the specified value)
32 		$(LI `isFoo` - equivalent to `kind == Kind.foo`)
33 		$(LI `setFoo(value)` - equivalent to `set!(Kind.foo)(value)`)
34 		$(LI `getFoo` - equivalent to `get!(Kind.foo)`)
35 	)
36 */
37 template TaggedUnion(U) if (is(U == union) || is(U == struct) || is(U == enum)) {
38 align(commonAlignment!(UnionKindTypes!(UnionFieldEnum!U))) struct TaggedUnion
39 {
40 	import std.traits : FieldTypeTuple, FieldNameTuple, Largest,
41 		hasElaborateCopyConstructor, hasElaborateDestructor, isCopyable;
42 	import std.meta : templateOr;
43 	import std.ascii : toUpper;
44 
45 	alias FieldDefinitionType = U;
46 
47 	/// A type enum that identifies the type of value currently stored.
48 	alias Kind = UnionFieldEnum!U;
49 
50 	alias FieldTypes = UnionKindTypes!Kind;
51 	alias fieldNames = UnionKindNames!Kind;
52 
53 	static assert(FieldTypes.length > 0, "The TaggedUnions's union type must have at least one field.");
54 	static assert(FieldTypes.length == fieldNames.length);
55 
56 	package alias FieldTypeByName(string name) = FieldTypes[__traits(getMember, Kind, name)];
57 
58 	private {
59 		static if (isUnitType!(FieldTypes[0]) || __VERSION__ < 2072) {
60 			void[Largest!FieldTypes.sizeof] m_data;
61 		} else {
62 			union Dummy {
63 				FieldTypes[0] initField;
64 				void[Largest!FieldTypes.sizeof] data;
65 				alias data this;
66 			}
67 			Dummy m_data = { initField: FieldTypes[0].init };
68 		}
69 		Kind m_kind;
70 	}
71 
72 	this(TaggedUnion other)
73 	{
74 		rawSwap(this, other);
75 	}
76 
77 	void opAssign(TaggedUnion other)
78 	{
79 		rawSwap(this, other);
80 	}
81 
82 	static foreach (ti; UniqueTypes!FieldTypes)
83 		static if(!is(FieldTypes[ti] == void))
84 		{
85 			this(FieldTypes[ti] value)
86 			{
87 				static if (isUnitType!(FieldTypes[ti]))
88 					set!(cast(Kind)ti)();
89 				else
90 					set!(cast(Kind)ti)(.move(value));
91 			}
92 
93 			void opAssign(FieldTypes[ti] value)
94 			{
95 				static if (isUnitType!(FieldTypes[ti]))
96 					set!(cast(Kind)ti)();
97 				else
98 					set!(cast(Kind)ti)(.move(value));
99 			}
100 		}
101 
102 	// disable default construction if first type is not a null/Void type
103 	static if (!isUnitType!(FieldTypes[0]) && __VERSION__ < 2072) {
104 		@disable this();
105 	}
106 
107 	// postblit constructor
108 	static if (!allSatisfy!(templateOr!(isCopyable, isUnitType), FieldTypes)) {
109 		@disable this(this);
110 	} else static if (anySatisfy!(hasElaborateCopyConstructor, FieldTypes)) {
111 		this(this)
112 		{
113 			switch (m_kind) {
114 				default: break;
115 				foreach (i, tname; fieldNames) {
116 					alias T = FieldTypes[i];
117 					static if (hasElaborateCopyConstructor!T)
118 					{
119 						case __traits(getMember, Kind, tname):
120 							static if (hasUDA!(U, typeof(forceNothrowPostblit()))) {
121 								try typeid(T).postblit(cast(void*)&trustedGet!T());
122 								catch (Exception e) assert(false, e.msg);
123 							} else {
124 								typeid(T).postblit(cast(void*)&trustedGet!T());
125 							}
126 							return;
127 					}
128 				}
129 			}
130 		}
131 	}
132 
133 	// destructor
134 	static if (anySatisfy!(hasElaborateDestructor, FieldTypes)) {
135 		~this()
136 		{
137 			final switch (m_kind) {
138 				foreach (i, tname; fieldNames) {
139 					alias T = FieldTypes[i];
140 					case __traits(getMember, Kind, tname):
141 						static if (hasElaborateDestructor!T) {
142 							.destroy(trustedGet!T);
143 						}
144 						return;
145 				}
146 			}
147 		}
148 	}
149 
150 	/// Enables conversion or extraction of the stored value.
151 	T opCast(T)()
152 	{
153 		import std.conv : to;
154 
155 		final switch (m_kind) {
156 			foreach (i, FT; FieldTypes) {
157 				case __traits(getMember, Kind, fieldNames[i]):
158 					static if (is(typeof(trustedGet!FT) : T))
159 						return trustedGet!FT;
160 					else static if (is(typeof(to!T(trustedGet!FT)))) {
161 						return to!T(trustedGet!FT);
162 					} else {
163 						assert(false, "Cannot cast a " ~ fieldNames[i]
164 								~ " value of type " ~ FT.stringof ~ " to " ~ T.stringof);
165 					}
166 			}
167 		}
168 		assert(false); // never reached
169 	}
170 	/// ditto
171 	T opCast(T)() const
172 	{
173 		// this method needs to be duplicated because inout doesn't work with to!()
174 		import std.conv : to;
175 
176 		final switch (m_kind) {
177 			foreach (i, FT; FieldTypes) {
178 				case __traits(getMember, Kind, fieldNames[i]):
179 					static if (is(typeof(trustedGet!FT) : T))
180 						return trustedGet!FT;
181 					else static if (is(typeof(to!T(trustedGet!FT)))) {
182 						return to!T(trustedGet!FT);
183 					} else {
184 						assert(false, "Cannot cast a " ~ fieldNames[i]
185 								~ " value of type" ~ FT.stringof ~ " to " ~ T.stringof);
186 					}
187 			}
188 		}
189 		assert(false); // never reached
190 	}
191 
192 	/// Enables equality comparison with the stored value.
193 	bool opEquals(inout TaggedUnion other) @safe inout
194 	{
195 		if (this.kind != other.kind) return false;
196 
197 		final switch (this.kind) {
198 			foreach (i, fname; TaggedUnion!U.fieldNames)
199 				case __traits(getMember, Kind, fname):
200 					return trustedGet!(FieldTypes[i]) == other.trustedGet!(FieldTypes[i]);
201 		}
202 		assert(false); // never reached
203 	}
204 
205 	static if (allSatisfy!(isHashable, FieldTypes))
206 	{
207 		/// Enables using a tagged union value as an associative array key.
208 		size_t toHash()
209 		const @safe nothrow {
210 			size_t ret;
211 			final switch (m_kind) {
212 				foreach (i, tname; fieldNames) {
213 					alias T = FieldTypes[i];
214 					case __traits(getMember, Kind, tname):
215 						static if (!isUnitType!T) {
216 							ret = hashOf(trustedGet!T);
217 						}
218 						break;
219 				}
220 			}
221 			return ret ^ (m_kind * 0xBA7A57E3);
222 		}
223 	}
224 
225 	/// The type ID of the currently stored value.
226 	@property Kind kind() const { return m_kind; }
227 
228 	static foreach (i, name; fieldNames) {
229 		// NOTE: using getX/setX here because using just x would be prone to
230 		//       misuse (attempting to "get" a value for modification when
231 		//       a different kind is set instead of assigning a new value)
232 		mixin("alias set"~pascalCase(name)~" = set!(Kind."~name~");");
233 		mixin("@property bool is"~pascalCase(name)~"() const { return m_kind == Kind."~name~"; }");
234 
235 		static if (name[$-1] == '_') {
236 			mixin("alias set"~pascalCase(name[0 .. $-1])~" = set!(Kind."~name~");");
237 			mixin("@property bool is"~pascalCase(name[0 .. $-1])~"() const { return m_kind == Kind."~name~"; }");
238 		}
239 
240 		static if (!isUnitType!(FieldTypes[i])) {
241 			mixin("alias "~name~"Value = value!(Kind."~name~");");
242 
243 			// remove trailing underscore from names like "int_"
244 			static if (name[$-1] == '_')
245 				mixin("alias "~name[0 .. $-1]~"Value = value!(Kind."~name~");");
246 
247 			mixin("static TaggedUnion "~name~"(FieldTypes["~i.stringof~"] value)"
248 				~ "{ TaggedUnion tu; tu.set!(Kind."~name~")(.move(value)); return tu; }");
249 
250 			// TODO: define assignment operator for unique types
251 		} else {
252 			mixin("static @property TaggedUnion "~name~"() { TaggedUnion tu; tu.set!(Kind."~name~"); return tu; }");
253 		}
254 	}
255 
256 	/** Checks whether the currently stored value has a given type.
257 	*/
258 	@property bool hasType(T)()
259 	const {
260 		static assert(staticIndexOf!(T, FieldTypes) >= 0, "Type "~T.stringof~ " not part of "~FieldTypes.stringof);
261 
262 		final switch (this.kind) {
263 			static foreach (i, n; fieldNames) {
264 				case __traits(getMember, Kind, n):
265 					return is(FieldTypes[i] == T);
266 			}
267 		}
268 	}
269 
270 	/** Accesses the contained value by reference.
271 
272 		The specified `kind` must equal the current value of the `this.kind`
273 		property. Setting a different type must be done with `set` or `opAssign`
274 		instead.
275 
276 		See_Also: `set`, `opAssign`
277 	*/
278 	@property ref inout(FieldTypes[kind]) value(Kind kind)()
279 	inout {
280 		if (this.kind != kind) {
281 			enum msg(.string k_is) = "Attempt to get kind "~kind.stringof~" from tagged union with kind "~k_is;
282 			final switch (this.kind) {
283 				static foreach (i, n; fieldNames)
284 					case __traits(getMember, Kind, n):
285 						assert(false, msg!n);
286 			}
287 		}
288 		//return trustedGet!(FieldTypes[kind]);
289 		return *() @trusted { return cast(const(FieldTypes[kind])*)m_data.ptr; } ();
290 	}
291 
292 
293 	/** Accesses the contained value by reference.
294 
295 		The specified type `T` must equal the type of the currently set value.
296 		Setting a different type must be done with `set` or `opAssign` instead.
297 
298 		See_Also: `set`, `opAssign`
299 	*/
300 	@property ref inout(T) value(T)() inout
301 	{
302 		static assert(staticIndexOf!(T, FieldTypes) >= 0, "Type "~T.stringof~ " not part of "~FieldTypes.stringof);
303 
304 		final switch (this.kind) {
305 			static foreach (i, n; fieldNames) {
306 				case __traits(getMember, Kind, n):
307 					static if (is(FieldTypes[i] == T))
308 						return trustedGet!T;
309 					else assert(false, "Attempting to get type "~T.stringof
310 						~ " from a TaggedUnion with type "
311 						~ FieldTypes[__traits(getMember, Kind, n)].stringof);
312 			}
313 		}
314 	}
315 
316 	/** Sets a new value of the specified `kind`.
317 	*/
318 	ref FieldTypes[kind] set(Kind kind)(FieldTypes[kind] value)
319 		if (!isUnitType!(FieldTypes[kind]))
320 	{
321 		if (m_kind != kind) {
322 			destroy(this);
323 			m_data.rawEmplace(value);
324 		} else {
325 			rawSwap(trustedGet!(FieldTypes[kind]), value);
326 		}
327 		m_kind = kind;
328 
329 		return trustedGet!(FieldTypes[kind]);
330 	}
331 
332 	/** Sets a `void` value of the specified kind.
333 	*/
334 	void set(Kind kind)()
335 		if (isUnitType!(FieldTypes[kind]))
336 	{
337 		if (m_kind != kind) {
338 			destroy(this);
339 		}
340 		m_kind = kind;
341 	}
342 
343 	/** Converts the contained value to a string.
344 
345 		The format output by this method is "(kind: value)", where "kind" is
346 		the enum name of the currently stored type and "value" is the string
347 		representation of the stored value.
348 	*/
349 	void toString(W)(ref W w) const
350 		if (isOutputRange!(W, char))
351 	{
352 		import std.range.primitives : put;
353 		import std.conv : text;
354 		import std.format : FormatSpec, formatValue;
355 
356 		final switch (m_kind) {
357 			foreach (i, v; EnumMembers!Kind) {
358 				case v:
359 					enum vstr = text(v);
360 					static if (isUnitType!(FieldTypes[i])) put(w, vstr);
361 					else {
362 						// NOTE: using formatValue instead of formattedWrite
363 						//       because formattedWrite does not work for
364 						//       non-copyable types
365 						enum prefix = "(" ~ vstr ~ ": ";
366 						enum suffix = ")";
367 						put(w, prefix);
368 						FormatSpec!char spec;
369 						formatValue(w, value!v, spec);
370 						put(w, suffix);
371 					}
372 					break;
373 			}
374 		}
375 	}
376 
377 	package @trusted @property ref inout(T) trustedGet(T)() inout { return *cast(inout(T)*)m_data.ptr; }
378 }
379 }
380 
381 ///
382 @safe unittest {
383 	union Kinds {
384 		int count;
385 		string text;
386 	}
387 	alias TU = TaggedUnion!Kinds;
388 
389 	// default initialized to the first field defined
390 	TU tu;
391 	assert(tu.kind == TU.Kind.count);
392 	assert(tu.isCount); // qequivalent to the line above
393 	assert(!tu.isText);
394 	assert(tu.value!(TU.Kind.count) == int.init);
395 
396 	// set to a specific count
397 	tu.setCount(42);
398 	assert(tu.isCount);
399 	assert(tu.countValue == 42);
400 	assert(tu.value!(TU.Kind.count) == 42);
401 	assert(tu.value!int == 42); // can also get by type
402 	assert(tu.countValue == 42);
403 
404 	// assign a new tagged algebraic value
405 	tu = TU.count(43);
406 
407 	// test equivalence with other tagged unions
408 	assert(tu == TU.count(43));
409 	assert(tu != TU.count(42));
410 	assert(tu != TU.text("hello"));
411 
412 	// modify by reference
413 	tu.countValue++;
414 	assert(tu.countValue == 44);
415 
416 	// set the second field
417 	tu.setText("hello");
418 	assert(!tu.isCount);
419 	assert(tu.isText);
420 	assert(tu.kind == TU.Kind.text);
421 	assert(tu.textValue == "hello");
422 
423 	// unique types can also be directly constructed
424 	tu = TU(12);
425 	assert(tu.countValue == 12);
426 	tu = TU("foo");
427 	assert(tu.textValue == "foo");
428 }
429 
430 unittest { // test for name clashes
431 	union U { .string string; }
432 	alias TU = TaggedUnion!U;
433 	TU tu;
434 	tu = TU..string("foo");
435 	assert(tu.isString);
436 	assert(tu.stringValue == "foo");
437 }
438 
439 unittest { // test woraround for Phobos issue 19696
440 	struct T {
441 		struct F { int num; }
442 		alias Payload = TaggedUnion!F;
443 		Payload payload;
444 		alias payload this;
445 	}
446 
447 	struct U {
448 		T t;
449 	}
450 
451 	alias TU = TaggedUnion!U;
452 	static assert(is(TU.FieldTypes[0] == T));
453 }
454 
455 unittest { // non-copyable types
456 	import std.traits : isCopyable;
457 
458 	struct S { @disable this(this); }
459 	struct U {
460 		int i;
461 		S s;
462 	}
463 	alias TU = TaggedUnion!U;
464 	static assert(!isCopyable!TU);
465 
466 	auto tu = TU(42);
467 	tu.setS(S.init);
468 }
469 
470 unittest { // alignment
471 	union S1 { int v; }
472 	union S2 { ulong v; }
473 	union S3 { void* v; }
474 
475 	// sanity check for the actual checks - this may differ on non-x86 architectures
476 	static assert(S1.alignof == 4);
477 	static assert(S2.alignof == 8);
478 	version (D_LP64) static assert(S3.alignof == 8);
479 	else static assert(S3.alignof == 4);
480 
481 	// test external struct alignment
482 	static assert(TaggedUnion!S1.alignof == 4);
483 	static assert(TaggedUnion!S2.alignof == 8);
484 	version (D_LP64) static assert(TaggedUnion!S3.alignof == 8);
485 	else static assert(TaggedUnion!S3.alignof == 4);
486 
487 	// test internal struct alignment
488 	TaggedUnion!S1 s1;
489 	assert((cast(ubyte*)&s1.vValue() - cast(ubyte*)&s1) % 4 == 0);
490 	TaggedUnion!S1 s2;
491 	assert((cast(ubyte*)&s2.vValue() - cast(ubyte*)&s2) % 8 == 0);
492 	TaggedUnion!S1 s3;
493 	version (D_LP64) assert((cast(ubyte*)&s3.vValue() - cast(ubyte*)&s3) % 8 == 0);
494 	else assert((cast(ubyte*)&s3.vValue() - cast(ubyte*)&s3) % 4 == 0);
495 }
496 
497 unittest { // toString
498 	import std.conv : to;
499 
500 	static struct NoCopy {
501 		@disable this(this);
502 		string toString() const { return "foo"; }
503 	}
504 
505 	union U { Void empty; int i; NoCopy noCopy; }
506 	TaggedUnion!U val;
507 	assert(val.to!string == "empty");
508 	val.setI(42);
509 	assert(val.to!string == "(i: 42)");
510 	val.setNoCopy(NoCopy.init);
511 	assert(val.to!string == "(noCopy: foo)");
512 }
513 
514 unittest { // null members should be assignable
515 	union U { int i; typeof(null) Null; }
516 	TaggedUnion!U val;
517 	val = null;
518 	assert(val.kind == val.Kind.Null);
519 	val = TaggedUnion!U(null);
520 	assert(val.kind == val.Kind.Null);
521 }
522 
523 unittest { // make sure field names don't conflict with function names
524 	union U { int to; int move; int swap; }
525 	TaggedUnion!U val;
526 	val.setMove(1);
527 }
528 
529 unittest { // support trailing underscores properly
530 	union U {
531 		int int_;
532 	}
533 	TaggedUnion!U val;
534 
535 	val = TaggedUnion!U.int_(10);
536 	assert(val.int_Value == 10);
537 	assert(val.intValue == 10);
538 	assert(val.isInt_);
539 	assert(val.isInt);
540 	val.setInt_(20);
541 	val.setInt(20);
542 	assert(val.intValue == 20);
543 }
544 
545 @safe nothrow unittest {
546 	static struct S { int i; string s; }
547 	alias TU = TaggedUnion!S;
548 
549 	static assert(is(typeof(TU.init.toHash()) == size_t));
550 
551 	int[TU] aa;
552 	aa[TU(1)] = 1;
553 	aa[TU("foo")] = 2;
554 
555 	assert(aa[TU(1)] == 1);
556 	assert(aa[TU("foo")] == 2);
557 }
558 
559 
560 @property auto forceNothrowPostblit()
561 {
562 	if (!__ctfe) assert(false, "@forceNothrowPostblit must only be used as a UDA.");
563 	static struct R {}
564 	return R.init;
565 }
566 
567 nothrow unittest {
568 	static struct S {
569 		this(this) nothrow {}
570 	}
571 
572 	@forceNothrowPostblit
573 	struct U {
574 		S s;
575 	}
576 
577 	alias TU = TaggedUnion!U;
578 
579 	TU tu, tv;
580 	tu = S.init;
581 	tv = tu;
582 }
583 
584 
585 enum isUnitType(T) = is(T == Void) || is(T == void) || is(T == typeof(null));
586 
587 
588 private string pascalCase(string camel_case)
589 {
590 	if (!__ctfe) assert(false);
591 	import std.ascii : toUpper;
592 	return camel_case[0].toUpper ~ camel_case[1 .. $];
593 }
594 
595 /** Maps a kind enumeration value to the corresponding field type.
596 
597 	`kind` must be a value of the `TaggedAlgebraic!T.Kind` enumeration.
598 */
599 template TypeOf(alias kind)
600 	if (is(typeof(kind) == enum))
601 {
602 	import std.traits : FieldTypeTuple, TemplateArgsOf;
603 	import std.typecons : ReplaceType;
604 
605 	static if (isInstanceOf!(UnionFieldEnum, typeof(kind))) {
606 		alias U = TemplateArgsOf!(typeof(kind));
607 		alias FT = FieldTypeTuple!U[kind];
608 	} else {
609 		alias U = typeof(kind);
610 		alias Types = UnionKindTypes!(typeof(kind));
611 		alias uda = AliasSeq!(__traits(getAttributes, kind));
612 		static if (uda.length == 0) alias FT = void;
613 		else alias FT = uda[0];
614 	}
615 
616 	// NOTE: ReplaceType has issues with certain types, such as a class
617 	//       declaration like this: class C : D!C {}
618 	//       For this reason, we test first if it compiles and only then use it.
619 	//       It also replaces a type with the contained "alias this" type under
620 	//       certain conditions, so we make a second check to see heuristically
621 	//       if This is actually present in FT
622 	//
623 	//       Phobos issues: 19696, 19697
624 	static if (is(ReplaceType!(This, U, FT)) && !is(ReplaceType!(This, void, FT)))
625 		alias TypeOf = ReplaceType!(This, U, FT);
626 	else alias TypeOf = FT;
627 }
628 
629 ///
630 unittest {
631 	static struct S {
632 		int a;
633 		string b;
634 		string c;
635 	}
636 	alias TU = TaggedUnion!S;
637 
638 	static assert(is(TypeOf!(TU.Kind.a) == int));
639 	static assert(is(TypeOf!(TU.Kind.b) == string));
640 	static assert(is(TypeOf!(TU.Kind.c) == string));
641 }
642 
643 unittest {
644 	struct S {
645 		TaggedUnion!This[] test;
646 	}
647 	alias TU = TaggedUnion!S;
648 
649 	TypeOf!(TU.Kind.test) a;
650 
651 	static assert(is(TypeOf!(TU.Kind.test) == TaggedUnion!S[]));
652 }
653 
654 
655 /// Convenience type that can be used for union fields that have no value (`void` is not allowed).
656 struct Void {}
657 
658 /** Special type used as a placeholder for `U` within the definition of `U` to
659 	enable self-referential types.
660 
661 	Note that this is recognized only if used as the first argument to a
662 	template type.
663 */
664 struct This { Void nothing; }
665 
666 ///
667 unittest {
668 	union U {
669 		TaggedUnion!This[] list;
670 		int number;
671 		string text;
672 	}
673 	alias Node = TaggedUnion!U;
674 
675 	auto n = Node([Node(12), Node("foo")]);
676 	assert(n.isList);
677 	assert(n.listValue == [Node(12), Node("foo")]);
678 }
679 
680 package template UnionFieldEnum(U)
681 {
682 	static if (is(U == enum)) alias UnionFieldEnum = U;
683 	else {
684 		import std.array : join;
685 		import std.traits : FieldNameTuple;
686 		mixin("enum UnionFieldEnum { " ~ [FieldNameTuple!U].join(", ") ~ " }");
687 	}
688 }
689 
690 deprecated alias TypeEnum(U) = UnionFieldEnum!U;
691 
692 package alias UnionKindTypes(FieldEnum) = staticMap!(TypeOf, EnumMembers!FieldEnum);
693 package alias UnionKindNames(FieldEnum) = AliasSeq!(__traits(allMembers, FieldEnum));
694 
695 package template UniqueTypes(Types...) {
696 	template impl(size_t i) {
697 		static if (i < Types.length) {
698 			alias T = Types[i];
699 			static if (staticIndexOf!(T, Types) == i && staticIndexOf!(T, Types[i+1 .. $]) < 0)
700 				alias impl = AliasSeq!(i, impl!(i+1));
701 			else alias impl = AliasSeq!(impl!(i+1));
702 		} else alias impl = AliasSeq!();
703 	}
704 	alias UniqueTypes = impl!0;
705 }
706 
707 package template AmbiguousTypes(Types...) {
708 	template impl(size_t i) {
709 		static if (i < Types.length) {
710 			alias T = Types[i];
711 			static if (staticIndexOf!(T, Types) == i && staticIndexOf!(T, Types[i+1 .. $]) >= 0)
712 				alias impl = AliasSeq!(i, impl!(i+1));
713 			else alias impl = impl!(i+1);
714 		} else alias impl = AliasSeq!();
715 	}
716 	alias AmbiguousTypes = impl!0;
717 }
718 
719 /// Computes the minimum alignment necessary to align all types correctly
720 private size_t commonAlignment(TYPES...)()
721 {
722 	import std.numeric : gcd;
723 
724 	size_t ret = 1;
725 	foreach (T; TYPES)
726 		ret = (T.alignof * ret) / gcd(T.alignof, ret);
727 	return ret;
728 }
729 
730 unittest {
731 	align(2) struct S1 { ubyte x; }
732 	align(4) struct S2 { ubyte x; }
733 	align(8) struct S3 { ubyte x; }
734 
735 	static if (__VERSION__ > 2076) { // DMD 2.076 ignores the alignment
736 		assert(commonAlignment!S1 == 2);
737 		assert(commonAlignment!S2 == 4);
738 		assert(commonAlignment!S3 == 8);
739 		assert(commonAlignment!(S1, S3) == 8);
740 		assert(commonAlignment!(S1, S2, S3) == 8);
741 		assert(commonAlignment!(S2, S2, S1) == 4);
742 	}
743 }
744 
745 private template isHashable(T)
746 {
747 	static if (isUnitType!T) enum isHashable = true;
748 	else static if (__traits(compiles, (ref const(T) val) @safe nothrow => hashOf(val)))
749 		enum isHashable = true;
750 	else enum isHashable = false;
751 }
752 
753 package void rawEmplace(T)(void[] dst, ref T src)
754 {
755 	T[] tdst = () @trusted { return cast(T[])dst[0 .. T.sizeof]; } ();
756 	static if (is(T == class)) {
757 		tdst[0] = src;
758 	} else {
759 		import std.conv : emplace;
760 		emplace!T(&tdst[0]);
761 		rawSwap(tdst[0], src);
762 	}
763 }
764 
765 // std.algorithm.mutation.swap sometimes fails to compile due to
766 // internal errors in hasElaborateAssign!T/isAssignable!T. This is probably
767 // caused by cyclic dependencies. However, there is no reason to do these
768 // checks in this context, so we just directly move the raw memory.
769 package void rawSwap(T)(ref T a, ref T b)
770 @trusted {
771 	void[T.sizeof] tmp = void;
772 	void[] ab = (cast(void*)&a)[0 .. T.sizeof];
773 	void[] bb = (cast(void*)&b)[0 .. T.sizeof];
774 	tmp[] = ab[];
775 	ab[] = bb[];
776 	bb[] = tmp[];
777 }