1 /**
2  * Metaprogramming
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <ae@cy.md>
12  */
13 
14 module ae.utils.meta;
15 
16 public import ae.utils.meta.reference;
17 public import ae.utils.meta.x;
18 public import ae.utils.meta.proxy;
19 public import ae.utils.meta.binding_v1;
20 public import ae.utils.meta.binding;
21 
22 import ae.utils.meta.caps;
23 
24 // ************************************************************************
25 
26 import std.traits;
27 
28 /**
29  * Same as TypeTuple, but meant to be used with values.
30  *
31  * Example:
32  *   foreach (char channel; ValueTuple!('r', 'g', 'b'))
33  *   {
34  *     // the loop is unrolled at compile-time
35  *     // "channel" is a compile-time value, and can be used in string mixins
36  *   }
37  */
38 template ValueTuple(T...)
39 {
40 	alias T ValueTuple;
41 }
42 
43 template _RangeTupleImpl(size_t N, R...)
44 {
45 	static if (N==R.length)
46 		alias R _RangeTupleImpl;
47 	else
48 		alias _RangeTupleImpl!(N, ValueTuple!(R, R.length)) _RangeTupleImpl;
49 }
50 
51 /// Generate a tuple containing integers from 0 to N-1.
52 /// Useful for static loop unrolling. (staticIota)
53 template RangeTuple(size_t N)
54 {
55 	alias _RangeTupleImpl!(N, ValueTuple!()) RangeTuple;
56 }
57 
58 /// Expand an array to a tuple.
59 /// The array value must be known during compilation.
60 template ArrayToTuple(alias arr, Elements...)
61 {
62 	///
63 	static if (arr.length)
64 		alias ArrayToTuple = ArrayToTuple!(arr[1..$], ValueTuple!(Elements, arr[0]));
65 	else
66 		alias ArrayToTuple = Elements;
67 }
68 
69 unittest
70 {
71 	alias X = ArrayToTuple!"abc";
72 	static assert(X[0] == 'a' && X[2] == 'c');
73 	static assert([X] == "abc");
74 }
75 
76 /// Expand a static array to a tuple.
77 /// Unlike `ArrayToTuple`, the array may be a runtime variable.
78 template expand(alias arr, size_t offset = 0)
79 	if (isStaticArray!(typeof(arr)))
80 {
81 	import std.typetuple : AliasSeq;
82 
83 	///
84 	static if (arr.length == offset)
85 		alias expand = AliasSeq!();
86 	else
87 	{
88 		@property ref getValue() { return arr[offset]; }
89 		alias expand = AliasSeq!(getValue, expand!(arr, offset+1));
90 	}
91 }
92 
93 unittest
94 {
95 	int[3] arr = [1, 2, 3];
96 	void test(int a, int b, int c) {}
97 	test(expand!arr);
98 }
99 
100 /// Return something to foreach over optimally.
101 /// If A is known at compile-time, return a tuple,
102 /// so the foreach is unrolled at compile-time.
103 /// Otherwise, return A for a regular runtime foreach.
104 template CTIterate(alias A)
105 {
106 	///
107 	static if (is(typeof(ArrayToTuple!A)))
108 		enum CTIterate = ArrayToTuple!A;
109 	else
110 		alias CTIterate = A;
111 }
112 
113 unittest
114 {
115 	foreach (c; CTIterate!"abc") {}
116 	string s;
117 	foreach (c; CTIterate!s) {}
118 }
119 
120 /// Like std.typecons.Tuple, but a template mixin.
121 /// Unlike std.typecons.Tuple, names may not be omitted - but repeating types may be.
122 /// Example: FieldList!(ubyte, "r", "g", "b", ushort, "a");
123 mixin template FieldList(Fields...)
124 {
125 	mixin(_GenFieldList!(void, Fields));
126 }
127 
128 template _GenFieldList(T, Fields...)
129 {
130 	///
131 	static if (Fields.length == 0)
132 		enum _GenFieldList = "";
133 	else
134 	{
135 		static if (is(typeof(Fields[0]) == string))
136 			enum _GenFieldList = T.stringof ~ " " ~ Fields[0] ~ ";\n" ~ _GenFieldList!(T, Fields[1..$]);
137 		else
138 			enum _GenFieldList = _GenFieldList!(Fields[0], Fields[1..$]);
139 	}
140 }
141 
142 unittest
143 {
144 	struct S
145 	{
146 		mixin FieldList!(ubyte, "r", "g", "b", ushort, "a");
147 	}
148 	S s;
149 	static assert(is(typeof(s.r) == ubyte));
150 	static assert(is(typeof(s.g) == ubyte));
151 	static assert(is(typeof(s.b) == ubyte));
152 	static assert(is(typeof(s.a) == ushort));
153 }
154 
155 /// Return true if all of T's fields are the same type.
156 @property bool isHomogeneous(T)()
157 {
158 	foreach (i, f; T.init.tupleof)
159 		if (!is(typeof(T.init.tupleof[i]) == typeof(T.init.tupleof[0])))
160 			return false;
161 	return true;
162 }
163 deprecated alias isHomogenous = isHomogeneous;
164 
165 /// Resolves to `true` if tuple `T` contains a value whose type is `X`.
166 template isValueOfTypeInTuple(X, T...)
167 {
168 	///
169 	static if (T.length==0)
170 		enum bool isValueOfTypeInTuple = false;
171 	else
172 	static if (T.length==1)
173 		enum bool isValueOfTypeInTuple = is(typeof(T[0]) : X);
174 	else
175 		enum bool isValueOfTypeInTuple = isValueOfTypeInTuple!(X, T[0..$/2]) || isValueOfTypeInTuple!(X, T[$/2..$]);
176 }
177 
178 unittest
179 {
180 	static assert( isValueOfTypeInTuple!(int, ValueTuple!("a", 42)));
181 	static assert(!isValueOfTypeInTuple!(int, ValueTuple!("a", 42.42)));
182 	static assert(!isValueOfTypeInTuple!(int, ValueTuple!()));
183 
184 	static assert(!isValueOfTypeInTuple!(int, "a", int, Object));
185 	static assert( isValueOfTypeInTuple!(int, "a", int, Object, 42));
186 }
187 
188 /// Returns the first value in `T` of type `X`.
189 template findValueOfTypeInTuple(X, T...)
190 {
191 	///
192 	static if (T.length==0)
193 		static assert(false, "Can't find value of type " ~ X.stringof ~ " in specified tuple");
194 	else
195 	static if (is(typeof(T[0]) : X))
196 		enum findValueOfTypeInTuple = T[0];
197 	else
198 		enum findValueOfTypeInTuple = findValueOfTypeInTuple!(X, T[1..$]);
199 }
200 
201 unittest
202 {
203 	static assert(findValueOfTypeInTuple!(int, ValueTuple!("a", 42))==42);
204 	static assert(findValueOfTypeInTuple!(int, "a", int, Object, 42)==42);
205 }
206 
207 /// Combines the getMember and allMembers traits, to return the
208 /// parameter's members as aliases.
209 template AllMembers(X...)
210 if (X.length == 1)
211 {
212 	alias GetMember(string name) = I!(__traits(getMember, X, name));
213 	alias AllMembers = staticMap!(GetMember, __traits(allMembers, X));
214 }
215 
216 unittest
217 {
218 	import std.typetuple : AliasSeq;
219 
220 	struct A { struct B {} struct C {} }
221 	static assert(is(AllMembers!A == AliasSeq!(A.B, A.C)));
222 }
223 
224 /// One past the biggest element of the enum T.
225 /// Example: string[enumLength!E] arr;
226 template enumLength(T)
227 	if (is(T==enum))
228 {
229 	enum enumLength = cast(T)(cast(size_t)T.max + 1);
230 }
231 
232 deprecated alias EnumLength = enumLength;
233 
234 /// A range that iterates over all members of an enum.
235 @property auto enumIota(T)()
236 {
237 	import std.range : iota;
238 	return iota(T.init, enumLength!T);
239 }
240 
241 unittest
242 {
243 	import std.algorithm.comparison : equal;
244 	enum E { a, b, c }
245 	static assert(equal(enumIota!E, [E.a, E.b, E.c]));
246 }
247 
248 // ************************************************************************
249 
250 /// What to use instead of void for boxVoid/unboxVoid.
251 /// Use void[0] instead of an empty struct as this one has a .sizeof
252 /// of 0, unlike the struct.
253 alias BoxedVoid = void[0];
254 
255 /// Resolves to `BoxedVoid` if `T` is `void`, or to `T` otherwise.
256 template BoxVoid(T)
257 {
258 	///
259 	static if (is(T == void))
260 		alias BoxVoid = BoxedVoid;
261 	else
262 		alias BoxVoid = T;
263 }
264 
265 /// D does not allow void variables or parameters.
266 /// As such, there is no "common type" for functions that return void
267 /// and non-void.
268 /// To allow generic metaprogramming in such cases, this function will
269 /// "box" a void expression to a different type.
270 BoxVoid!T boxVoid(T)(lazy T expr)
271 {
272 	static if (is(T == void))
273 	{
274 		expr;
275 		return BoxedVoid.init;
276 	}
277 	else
278 		return expr;
279 }
280 
281 /// Inverse of boxVoid.
282 /// Can be used in a return statement, i.e.:
283 /// return unboxVoid(someBoxedVoid);
284 auto unboxVoid(T)(T value)
285 {
286 	static if (is(T == BoxedVoid))
287 		return;
288 	else
289 		return value;
290 }
291 
292 unittest
293 {
294 	struct S { void* p; }
295 
296 	auto process(T)(T delegate() dg)
297 	{
298 		auto result = dg().boxVoid;
299 		return result.unboxVoid;
300 	}
301 
302 	S fun() { return S(); }
303 	assert(process(&fun) == S.init);
304 
305 	void gun() { }
306 	static assert(is(typeof(process(&gun)) == void));
307 }
308 
309 // ************************************************************************
310 
311 /// Apply `.stringof` over `Args` and
312 /// return the result as a `string[]`.
313 static // https://issues.dlang.org/show_bug.cgi?id=7805
314 template stringofArray(Args...)
315 {
316 	static string[] stringofArray()
317 	{
318 		string[] args;
319 		foreach (i, _ ; typeof(Args))
320 			args ~= Args[i].stringof;
321 		return args;
322 	}
323 }
324 
325 /// Returns the index of fun's parameter with the name
326 /// matching "names", or asserts if the parameter is not found.
327 /// "names" can contain multiple names separated by slashes.
328 static size_t findParameter(alias fun, string names)()
329 {
330 	import std.array : split;
331 
332 	foreach (name; names.split("/"))
333 		foreach (i, param; ParameterIdentifierTuple!fun)
334 			if (param == name)
335 				return i;
336 	assert(false, "Function " ~ __traits(identifier, fun) ~ " doesn't have a parameter called " ~ names);
337 }
338 
339 /// ditto
340 // Workaround for no "static alias" template parameters
341 static size_t findParameter()(string[] searchedNames, string soughtNames, string funName)
342 {
343 	import std.array : split;
344 
345 	foreach (soughtName; soughtNames.split("/"))
346 	{
347 		import std.algorithm.searching : countUntil;
348 
349 		auto targetIndex = searchedNames.countUntil(soughtName);
350 		if (targetIndex >= 0)
351 			return targetIndex;
352 	}
353 
354 	{
355 		import std.format : format;
356 
357 		assert(false, "No argument %s in %s's parameters (%s)"
358 			.format(soughtNames, funName, searchedNames).idup);
359 	}
360 }
361 
362 unittest
363 {
364 	static void fun(int a, int b, int c) {}
365 
366 	static assert(findParameter!(fun, "x/c") == 2);
367 	assert(findParameter(["a", "b", "c"], "x/c", "fun") == 2);
368 }
369 
370 // ************************************************************************
371 
372 /// Generates a function which passes its arguments to a struct, which is
373 /// returned. Preserves field names (as parameter names) and default values.
374 template structFun(S)
375 {
376 	mixin((){
377 		import std.algorithm.iteration : map;
378 		import std.array : join;
379 		import std.format : format;
380 		import std.meta : staticMap;
381 		import std.range : iota;
382 
383 		enum identifierAt(int n) = __traits(identifier, S.tupleof[n]);
384 		enum names = [staticMap!(identifierAt, RangeTuple!(S.tupleof.length))];
385 
386 		return
387 			"S structFun(\n" ~
388 			S.tupleof.length.iota.map!(n =>
389 			"	typeof(S.init.tupleof[%d]) %s = S.init.tupleof[%d],\n".format(n, names[n], n)
390 			).join() ~
391 			`) { return S(` ~ names.join(", ") ~ "); }";
392 	}());
393 }
394 
395 unittest
396 {
397 	static struct Test
398 	{
399 		string a;
400 		int b = 42;
401 	}
402 
403 	Test test = structFun!Test("banana");
404 	assert(test.a is "banana");
405 	assert(test.b == 42);
406 }
407 
408 /// Generates a struct containing fields with names, types, and default values
409 /// corresponding to a function's parameter list.
410 struct StructFromParams(args...)
411 if (args.length == 1 || args.length == 2)
412 {
413 	mixin((){
414 		alias fun = args[0];
415 		static if (args.length == 1)
416 			enum bool voidInitializeRequired = false;
417 		else
418 			enum bool voidInitializeRequired = args[1];
419 		import ae.utils.text.ascii : toDec;
420 
421 		string code;
422 		foreach (i; RangeTuple!(ParameterTypeTuple!fun.length))
423 		{
424 			enum n = toDec(i);
425 
426 			code ~= `ParameterTypeTuple!(args[0])[` ~ n ~ `] `;
427 
428 			static if (ParameterIdentifierTuple!fun[i].length)
429 				code ~= ParameterIdentifierTuple!fun[i];
430 			else
431 				code ~= "_param_" ~ toDec(i);
432 
433 			static if (is(ParameterDefaultValueTuple!fun[i] == void))
434 				static if (voidInitializeRequired)
435 					code ~= ` = void;`;
436 				else
437 					code ~= `;`;
438 			else
439 				code ~= ` = ParameterDefaultValueTuple!(args[0])[` ~ n ~ `];`;
440 		}
441 		return code;
442 	}());
443 }
444 
445 unittest
446 {
447 	static void fun(string a, int b = 42) {}
448 	alias S = StructFromParams!fun;
449 	static assert(is(typeof(S.a) == string));
450 	static assert(S.init.b == 42);
451 }
452 
453 unittest
454 {
455 	static void fun(string, int = 42) {}
456 	alias Fun = typeof(&fun);
457 	alias S = StructFromParams!Fun;
458 	static assert(is(typeof(S.tupleof[0]) == string));
459 }
460 
461 // ************************************************************************
462 
463 // By Paul Backus: https://forum.dlang.org/post/mkiyylyjznwgkzpnbryk@forum.dlang.org
464 /// Pass struct / tuple members as arguments to a function.
465 alias tupleAs(alias fun) = args => fun(args.tupleof);
466 
467 /// Call a predicate with the given value. Return the value.
468 /// Intended to be used in UFCS chains using functions which mutate their argument,
469 /// such as skipOver and each.
470 template apply(alias dg)
471 {
472 	auto ref T apply(T)(auto ref T v)
473 	{
474 		dg(v);
475 		return v;
476 	}
477 }
478 
479 ///
480 unittest
481 {
482 	int i = 7;
483 	int j = i.apply!((ref v) => v++);
484 	assert(j == 8);
485 }
486 
487 /// Evaluate all arguments and return the last argument.
488 /// Can be used instead of the comma operator.
489 /// Inspired by http://clhs.lisp.se/Body/s_progn.htm
490 Args[$-1] progn(Args...)(lazy Args args)
491 {
492 	foreach (n; RangeTuple!(Args[1..$].length))
493 		cast(void)args[n];
494 	return args[$-1];
495 }
496 
497 unittest
498 {
499 	// Test that expressions are correctly evaluated exactly once.
500 	int a, b, c, d;
501 	d = progn(a++, b++, c++);
502 	assert(a==1 && b==1 && c == 1 && d == 0);
503 	d = progn(a++, b++, ++c);
504 	assert(a==2 && b==2 && c == 2 && d == 2);
505 }
506 
507 unittest
508 {
509 	// Test void expressions.
510 	int a, b;
511 	void incA() { a++; }
512 	void incB() { b++; }
513 	progn(incA(), incB());
514 	assert(a == 1 && b == 1);
515 }
516 
517 /// Like progn, but return the first argument instead.
518 Args[0] prog1(Args...)(lazy Args args)
519 {
520 	auto result = args[0];
521 	foreach (n; RangeTuple!(Args.length-1))
522 		cast(void)args[1+n];
523 	return result;
524 }
525 
526 unittest
527 {
528 	int a = 10, b = 20, c = 30;
529 	int d = prog1(a++, b++, c++);
530 	assert(a==11 && b==21 && c == 31 && d == 10);
531 }
532 
533 /// Resolves to `true` if there exists a non-`void`
534 /// common type for all elements of `T`.
535 enum bool haveCommonType(T...) = is(CommonType!T) && !is(CommonType!T == void);
536 
537 /// Lazily evaluate and return first true-ish result; otherwise return last result.
538 CommonType!Args or(Args...)(lazy Args args)
539 if (haveCommonType!Args)
540 {
541 	foreach (n; RangeTuple!(Args.length-1))
542 	{
543 		auto r = args[n];
544 		if (r)
545 			return r;
546 	}
547 	return args[$-1];
548 }
549 
550 unittest
551 {
552 	assert(or(0, 7, 5) == 7);
553 	assert(or(0, 0, 0) == 0);
554 	int fun() { assert(false); }
555 	assert(or(0, 7, fun) == 7);
556 }
557 
558 /// Lazily evaluate and return first false-ish result; otherwise return last result.
559 CommonType!Args and(Args...)(lazy Args args)
560 if (haveCommonType!Args)
561 {
562 	foreach (n; RangeTuple!(Args.length-1))
563 	{
564 		auto r = args[n];
565 		if (!r)
566 			return r;
567 	}
568 	return args[$-1];
569 }
570 
571 unittest
572 {
573 	assert(and(7, 5, 0) == 0);
574 	assert(and(7, 5, 3) == 3);
575 	int fun() { assert(false); }
576 	assert(and(7, 0, fun) == 0);
577 }
578 
579 // ************************************************************************
580 
581 // Using a compiler with UDA support?
582 deprecated alias HAVE_UDA = haveUDA;
583 
584 static if (haveUDA)
585 {
586 	/*
587 	template hasAttribute(T, alias D)
588 	{
589 		enum bool hasAttribute = isValueOfTypeInTuple!(T, __traits(getAttributes, D));
590 	}
591 	*/
592 
593 	/// Detects types and values of the given type.
594 	template hasAttribute(Args...)
595 		if (Args.length == 2)
596 	{
597 	//	alias attribute = Args[0];
598 	//	alias symbol = Args[1];
599 
600 		import std.typetuple : staticIndexOf;
601 		import std.traits : staticMap;
602 
603 		///
604 		static if (is(Args[0]))
605 		{
606 			template _isTypeOrValueInTuple(T, Args...)
607 			{
608 				static if (!Args.length)
609 					enum _isTypeOrValueInTuple = false;
610 				else
611 				static if (is(Args[0] == T))
612 					enum _isTypeOrValueInTuple = true;
613 				else
614 				static if (is(typeof(Args[0]) == T))
615 					enum _isTypeOrValueInTuple = true;
616 				else
617 					enum _isTypeOrValueInTuple = _isTypeOrValueInTuple!(T, Args[1..$]);
618 			}
619 
620 			enum bool hasAttribute = _isTypeOrValueInTuple!(Args[0], __traits(getAttributes, Args[1]));
621 		}
622 		else
623 			enum bool hasAttribute = staticIndexOf!(Args[0], __traits(getAttributes, Args[1])) != -1;
624 	}
625 
626 	/// Retrieves the attribute (type or value of the given type).
627 	template getAttribute(T, alias D)
628 	{
629 		enum T getAttribute = findValueOfTypeInTuple!(T, __traits(getAttributes, D));
630 	}
631 
632 	unittest
633 	{
634 		struct Attr { int i; }
635 
636 		struct S
637 		{
638 			@Attr int a;
639 			@Attr(5) int b;
640 			@("test") int c;
641 		}
642 
643 		static assert(hasAttribute!(Attr, S.a));
644 		static assert(hasAttribute!(Attr, S.b));
645 		static assert(hasAttribute!(string, S.c));
646 		static assert(hasAttribute!("test", S.c));
647 	}
648 }
649 else
650 {
651 	/// Stub (unsupported)>
652 	template hasAttribute(T, alias D)
653 	{
654 		enum bool hasAttribute = false;
655 	}
656 
657 	/// ditto
658 	template getAttribute(T, alias D)
659 	{
660 		static assert(false, "This D compiler has no UDA support.");
661 	}
662 }
663 
664 // ************************************************************************
665 
666 /// Generate constructors that simply call the parent class constructors.
667 /// Based on http://forum.dlang.org/post/i3hpj0$2vc6$1@digitalmars.com
668 mixin template GenerateConstructorProxies()
669 {
670 	mixin(() {
671 		import std.conv : text;
672 		import std.string : join;
673 		import std.traits : ParameterTypeTuple, fullyQualifiedName;
674 
675 		alias T = typeof(super);
676 
677 		string s;
678 		static if (__traits(hasMember, T, "__ctor"))
679 			foreach (ctor; __traits(getOverloads, T, "__ctor"))
680 			{
681 				string[] declarationList, usageList;
682 				foreach (i, param; ParameterTypeTuple!(typeof(&ctor)))
683 				{
684 					auto varName = "v" ~ text(i);
685 					declarationList ~= fullyQualifiedName!param ~ " " ~ varName;
686 					usageList ~= varName;
687 				}
688 				s ~= "this(" ~ declarationList.join(", ") ~ ") { super(" ~ usageList.join(", ") ~ "); }\n";
689 			}
690 		return s;
691 	} ());
692 }
693 
694 deprecated alias GenerateContructorProxies = GenerateConstructorProxies;
695 
696 unittest
697 {
698 	class A
699 	{
700 		int i, j;
701 		this() { }
702 		this(int i) { this.i = i; }
703 		this(int i, int j ) { this.i = i; this.j = j; }
704 	}
705 
706 	class B : A
707 	{
708 		mixin GenerateConstructorProxies;
709 	}
710 
711 	A a;
712 
713 	a = new B();
714 	assert(a.i == 0);
715 	a = new B(17);
716 	assert(a.i == 17);
717 	a = new B(17, 42);
718 	assert(a.j == 42);
719 }
720 
721 // ************************************************************************
722 
723 /// Generate a @property function which creates/returns
724 /// a thread-local singleton of a class with the given arguments.
725 
726 @property T singleton(T, args...)()
727 	if (is(typeof(new T(args))))
728 {
729 	static T instance;
730 	if (!instance)
731 		instance = new T(args);
732 	return instance;
733 }
734 
735 unittest
736 {
737 	static class C
738 	{
739 		static int n = 0;
740 
741 		this()      { n++; }
742 		this(int x) { n += x; }
743 
744 		void fun() {}
745 	}
746 
747 	alias singleton!C c0;
748 	c0.fun();
749 	c0.fun();
750 	assert(C.n == 1);
751 
752 	alias singleton!(C, 5) c1;
753 	c1.fun();
754 	c1.fun();
755 	assert(C.n == 6);
756 }
757 
758 /// As above, but using arbitrary types and a factory function.
759 @property singleton(alias fun, args...)()
760 	if (is(typeof(fun(args))))
761 {
762 	alias T = typeof(fun(args));
763 	static T instance;
764 	static bool initialized;
765 	if (!initialized)
766 	{
767 		instance = fun(args);
768 		initialized = true;
769 	}
770 	return instance;
771 }
772 
773 unittest
774 {
775 	int n;
776 	int gen(int _ = 0)
777 	{
778 		return ++n;
779 	}
780 
781 	alias singleton!gen c0;
782 	assert(c0 == 1);
783 	assert(c0 == 1);
784 
785 	alias singleton!(gen, 1) c1;
786 	assert(c1 == 2);
787 	assert(c1 == 2);
788 }
789 
790 // ************************************************************************
791 
792 /// Were we built with -debug?
793 debug
794 	enum isDebug = true;
795 else
796 	enum isDebug = false;
797 
798 deprecated alias IsDebug = isDebug;
799 
800 /// Is a specific version on?
801 template isVersion(string versionName)
802 {
803 	mixin(`version (` ~ versionName ~ `) enum isVersion = true; else enum isVersion = false;`);
804 }
805 
806 // ************************************************************************
807 
808 /// Identity function.
809 auto ref T identity(T)(auto ref T value) { return value; }
810 
811 /// Shorter synonym for std.traits.Identity.
812 /// Can be used to UFCS-chain static methods and nested functions.
813 alias I(alias A) = A;
814 
815 // ************************************************************************
816 
817 /// Get f's ancestor which represents its "this" pointer.
818 /// Skips template and mixin ancestors until it finds a struct or class.
819 template thisOf(alias f)
820 {
821 	alias _p = I!(__traits(parent, f));
822 	///
823 	static if (is(_p == class) || is(_p == struct) || is(_p == union))
824 		alias thisOf = _p;
825 	else
826 		alias thisOf = thisOf!_p;
827 }
828 
829 // ************************************************************************
830 
831 /// Return the number of bits used to store the value part, i.e.
832 /// T.sizeof*8 for integer parts and the mantissa size for
833 /// floating-point types.
834 template valueBits(T)
835 {
836 	///
837 	static if (is(T : ulong))
838 		enum valueBits = T.sizeof * 8;
839 	else
840 	static if (is(T : real))
841 		enum valueBits = T.mant_dig;
842 	else
843 		static assert(false, "Don't know how many value bits there are in " ~ T.stringof);
844 }
845 
846 static assert(valueBits!uint == 32);
847 static assert(valueBits!double == 53);
848 
849 /// Expand to a built-in numeric type of the same kind
850 /// (signed integer / unsigned integer / floating-point)
851 /// with at least the indicated number of bits of precision.
852 template ResizeNumericType(T, uint bits)
853 {
854 	///
855 	static if (is(T : ulong))
856 		static if (isSigned!T)
857 			alias ResizeNumericType = SignedBitsType!bits;
858 		else
859 			alias ResizeNumericType = UnsignedBitsType!bits;
860 	else
861 	static if (is(T : real))
862 	{
863 		static if (bits <= float.mant_dig)
864 			alias ResizeNumericType = float;
865 		else
866 		static if (bits <= double.mant_dig)
867 			alias ResizeNumericType = double;
868 		else
869 		static if (bits <= real.mant_dig)
870 			alias ResizeNumericType = real;
871 		else
872 			static assert(0, "No floating-point type big enough to fit " ~ bits.stringof ~ " bits");
873 	}
874 	else
875 		static assert(false, "Don't know how to resize type: " ~ T.stringof);
876 }
877 
878 static assert(is(ResizeNumericType!(float, double.mant_dig) == double));
879 
880 /// Expand to a built-in numeric type of the same kind
881 /// (signed integer / unsigned integer / floating-point)
882 /// with at least additionalBits more bits of precision.
883 alias ExpandNumericType(T, uint additionalBits) =
884 	ResizeNumericType!(T, valueBits!T + additionalBits);
885 
886 /// Like ExpandNumericType, but do not error if the resulting type is
887 /// too large to fit any native D type - just expand to the largest
888 /// type of the same kind instead.
889 template TryExpandNumericType(T, uint additionalBits)
890 {
891 	///
892 	static if (is(typeof(ExpandNumericType!(T, additionalBits))))
893 		alias TryExpandNumericType = ExpandNumericType!(T, additionalBits);
894 	else
895 		static if (is(T : ulong))
896 			static if (isSigned!T)
897 				alias TryExpandNumericType = long;
898 			else
899 				alias TryExpandNumericType = ulong;
900 		else
901 		static if (is(T : real))
902 			alias TryExpandNumericType = real;
903 		else
904 			static assert(false, "Don't know how to expand type: " ~ T.stringof);
905 }
906 
907 /// Integer type big enough to fit N bits of precision.
908 template UnsignedBitsType(uint bits)
909 {
910 	///
911 	static if (bits <= 8)
912 		alias ubyte UnsignedBitsType;
913 	else
914 	static if (bits <= 16)
915 		alias ushort UnsignedBitsType;
916 	else
917 	static if (bits <= 32)
918 		alias uint UnsignedBitsType;
919 	else
920 	static if (bits <= 64)
921 		alias ulong UnsignedBitsType;
922 	else
923 		static assert(0, "No integer type big enough to fit " ~ bits.stringof ~ " bits");
924 }
925 
926 /// ditto
927 template SignedBitsType(uint bits)
928 {
929 	alias Signed!(UnsignedBitsType!bits) SignedBitsType;
930 }
931 
932 /// Evaluates to array of strings with name for each field.
933 @property string[] structFields(T)()
934 	if (is(T == struct) || is(T == class))
935 {
936 	import std.string : split;
937 
938 	string[] fields;
939 	foreach (i, f; T.init.tupleof)
940 	{
941 		string field = T.tupleof[i].stringof;
942 		field = field.split(".")[$-1];
943 		fields ~= field;
944 	}
945 	return fields;
946 }
947 
948 /// Returns the class's initializer instance.
949 /// Returns null if all class fields are zero.
950 /// Can be used to get the value of class fields' initial values.
951 immutable(T) classInit(T)()
952 if (is(T == class))
953 {
954 	return cast(immutable(T))typeid(T).initializer.ptr;
955 }
956 
957 ///
958 unittest
959 {
960 	class C { int n = 42; }
961 	assert(classInit!C.n == 42);
962 }
963 
964 /// Create a functor value type (bound struct) from an alias.
965 template functor(alias fun)
966 {
967 	struct Functor
968 	{
969 		//alias opCall = fun;
970 		auto opCall(T...)(auto ref T args) { return fun(args); }
971 	}
972 
973 	Functor functor()
974 	{
975 		Functor f;
976 		return f;
977 	}
978 }
979 
980 static if (haveAliasStructBinding)
981 unittest
982 {
983 	static void caller(F)(F fun)
984 	{
985 		fun(42);
986 	}
987 
988 	int result;
989 	caller(functor!((int i) => result = i));
990 	assert(result == 42);
991 }