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