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 // http://d.puremagic.com/issues/show_bug.cgi?id=7805 225 static template stringofArray(Args...) 226 { 227 static string[] stringofArray() 228 { 229 string[] args; 230 foreach (i, _ ; typeof(Args)) 231 args ~= Args[i].stringof; 232 return args; 233 } 234 } 235 236 /// Returns the index of fun's parameter with the name 237 /// matching "names", or asserts if the parameter is not found. 238 /// "names" can contain multiple names separated by slashes. 239 static size_t findParameter(alias fun, string names)() 240 { 241 import std.array : split; 242 243 foreach (name; names.split("/")) 244 foreach (i, param; ParameterIdentifierTuple!fun) 245 if (param == name) 246 return i; 247 assert(false, "Function " ~ __traits(identifier, fun) ~ " doesn't have a parameter called " ~ names); 248 } 249 250 /// ditto 251 // Workaround for no "static alias" template parameters 252 static size_t findParameter()(string[] searchedNames, string soughtNames, string funName) 253 { 254 import std.array : split; 255 256 foreach (soughtName; soughtNames.split("/")) 257 { 258 import std.algorithm.searching : countUntil; 259 260 auto targetIndex = searchedNames.countUntil(soughtName); 261 if (targetIndex >= 0) 262 return targetIndex; 263 } 264 265 { 266 import std.format : format; 267 268 assert(false, "No argument %s in %s's parameters (%s)" 269 .format(soughtNames, funName, searchedNames).idup); 270 } 271 } 272 273 unittest 274 { 275 static void fun(int a, int b, int c) {} 276 277 static assert(findParameter!(fun, "x/c") == 2); 278 assert(findParameter(["a", "b", "c"], "x/c", "fun") == 2); 279 } 280 281 /// Generates a function which passes its arguments to a struct, which is 282 /// returned. Preserves field names (as parameter names) and default values. 283 template structFun(S) 284 { 285 string gen() 286 { 287 import std.algorithm.iteration : map; 288 import std.array : join; 289 import std.format : format; 290 import std.meta : staticMap; 291 import std.range : iota; 292 293 enum identifierAt(int n) = __traits(identifier, S.tupleof[n]); 294 enum names = [staticMap!(identifierAt, RangeTuple!(S.tupleof.length))]; 295 296 return 297 "S structFun(\n" ~ 298 S.tupleof.length.iota.map!(n => 299 " typeof(S.init.tupleof[%d]) %s = S.init.tupleof[%d],\n".format(n, names[n], n) 300 ).join() ~ 301 `) { return S(` ~ names.join(", ") ~ "); }"; 302 } 303 304 mixin(gen()); 305 } 306 307 unittest 308 { 309 static struct Test 310 { 311 string a; 312 int b = 42; 313 } 314 315 Test test = structFun!Test("banana"); 316 assert(test.a is "banana"); 317 assert(test.b == 42); 318 } 319 320 // ************************************************************************ 321 322 /// Call a predicate with the given value. Return the value. 323 /// Intended to be used in UFCS chains using functions which mutate their argument, 324 /// such as skipOver and each. 325 template apply(alias dg) 326 { 327 auto ref T apply(T)(auto ref T v) 328 { 329 dg(v); 330 return v; 331 } 332 } 333 334 /// 335 unittest 336 { 337 int i = 7; 338 int j = i.apply!((ref v) => v++); 339 assert(j == 8); 340 } 341 342 /// Evaluate all arguments and return the last argument. 343 /// Can be used instead of the comma operator. 344 /// Inspired by http://clhs.lisp.se/Body/s_progn.htm 345 Args[$-1] progn(Args...)(lazy Args args) 346 { 347 foreach (n; RangeTuple!(Args[1..$].length)) 348 cast(void)args[n]; 349 return args[$-1]; 350 } 351 352 unittest 353 { 354 // Test that expressions are correctly evaluated exactly once. 355 int a, b, c, d; 356 d = progn(a++, b++, c++); 357 assert(a==1 && b==1 && c == 1 && d == 0); 358 d = progn(a++, b++, ++c); 359 assert(a==2 && b==2 && c == 2 && d == 2); 360 } 361 362 unittest 363 { 364 // Test void expressions. 365 int a, b; 366 void incA() { a++; } 367 void incB() { b++; } 368 progn(incA(), incB()); 369 assert(a == 1 && b == 1); 370 } 371 372 /// Like progn, but return the first argument instead. 373 Args[0] prog1(Args...)(lazy Args args) 374 { 375 auto result = args[0]; 376 foreach (n; RangeTuple!(Args.length-1)) 377 cast(void)args[1+n]; 378 return result; 379 } 380 381 unittest 382 { 383 int a = 10, b = 20, c = 30; 384 int d = prog1(a++, b++, c++); 385 assert(a==11 && b==21 && c == 31 && d == 10); 386 } 387 388 // ************************************************************************ 389 390 // Using a compiler with UDA support? 391 enum HAVE_UDA = __traits(compiles, __traits(getAttributes, Object)); 392 393 static if (HAVE_UDA) 394 { 395 /* 396 template hasAttribute(T, alias D) 397 { 398 enum bool hasAttribute = isValueOfTypeInTuple!(T, __traits(getAttributes, D)); 399 } 400 */ 401 402 /// Detects types and values of the given type 403 template hasAttribute(Args...) 404 if (Args.length == 2) 405 { 406 // alias attribute = Args[0]; 407 // alias symbol = Args[1]; 408 409 import std.typetuple : staticIndexOf; 410 import std.traits : staticMap; 411 412 static if (is(Args[0])) 413 { 414 template isTypeOrValueInTuple(T, Args...) 415 { 416 static if (!Args.length) 417 enum isTypeOrValueInTuple = false; 418 else 419 static if (is(Args[0] == T)) 420 enum isTypeOrValueInTuple = true; 421 else 422 static if (is(typeof(Args[0]) == T)) 423 enum isTypeOrValueInTuple = true; 424 else 425 enum isTypeOrValueInTuple = isTypeOrValueInTuple!(T, Args[1..$]); 426 } 427 428 enum bool hasAttribute = isTypeOrValueInTuple!(Args[0], __traits(getAttributes, Args[1])); 429 } 430 else 431 enum bool hasAttribute = staticIndexOf!(Args[0], __traits(getAttributes, Args[1])) != -1; 432 } 433 434 template getAttribute(T, alias D) 435 { 436 enum T getAttribute = findValueOfTypeInTuple!(T, __traits(getAttributes, D)); 437 } 438 439 unittest 440 { 441 struct Attr { int i; } 442 443 struct S 444 { 445 @Attr int a; 446 @Attr(5) int b; 447 @("test") int c; 448 } 449 450 static assert(hasAttribute!(Attr, S.a)); 451 static assert(hasAttribute!(Attr, S.b)); 452 static assert(hasAttribute!(string, S.c)); 453 static assert(hasAttribute!("test", S.c)); 454 } 455 } 456 else 457 { 458 template hasAttribute(T, alias D) 459 { 460 enum bool hasAttribute = false; 461 } 462 463 template getAttribute(T, alias D) 464 { 465 static assert(false, "This D compiler has no UDA support."); 466 } 467 } 468 469 // ************************************************************************ 470 471 /// Generate constructors that simply call the parent class constructors. 472 /// Based on http://forum.dlang.org/post/i3hpj0$2vc6$1@digitalmars.com 473 mixin template GenerateConstructorProxies() 474 { 475 mixin(() { 476 import std.conv : text; 477 import std.string : join; 478 import std.traits : ParameterTypeTuple, fullyQualifiedName; 479 480 alias T = typeof(super); 481 482 string s; 483 static if (__traits(hasMember, T, "__ctor")) 484 foreach (ctor; __traits(getOverloads, T, "__ctor")) 485 { 486 string[] declarationList, usageList; 487 foreach (i, param; ParameterTypeTuple!(typeof(&ctor))) 488 { 489 auto varName = "v" ~ text(i); 490 declarationList ~= fullyQualifiedName!param ~ " " ~ varName; 491 usageList ~= varName; 492 } 493 s ~= "this(" ~ declarationList.join(", ") ~ ") { super(" ~ usageList.join(", ") ~ "); }\n"; 494 } 495 return s; 496 } ()); 497 } 498 499 deprecated alias GenerateContructorProxies = GenerateConstructorProxies; 500 501 unittest 502 { 503 class A 504 { 505 int i, j; 506 this() { } 507 this(int i) { this.i = i; } 508 this(int i, int j ) { this.i = i; this.j = j; } 509 } 510 511 class B : A 512 { 513 mixin GenerateConstructorProxies; 514 } 515 516 A a; 517 518 a = new B(); 519 assert(a.i == 0); 520 a = new B(17); 521 assert(a.i == 17); 522 a = new B(17, 42); 523 assert(a.j == 42); 524 } 525 526 // ************************************************************************ 527 528 /// Generate a @property function which creates/returns 529 /// a thread-local singleton of a class with the given arguments. 530 531 @property T singleton(T, args...)() 532 if (is(typeof(new T(args)))) 533 { 534 static T instance; 535 if (!instance) 536 instance = new T(args); 537 return instance; 538 } 539 540 unittest 541 { 542 static class C 543 { 544 static int n = 0; 545 546 this() { n++; } 547 this(int x) { n += x; } 548 549 void fun() {} 550 } 551 552 alias singleton!C c0; 553 c0.fun(); 554 c0.fun(); 555 assert(C.n == 1); 556 557 alias singleton!(C, 5) c1; 558 c1.fun(); 559 c1.fun(); 560 assert(C.n == 6); 561 } 562 563 // ************************************************************************ 564 565 /// Were we built with -debug? 566 debug 567 enum isDebug = true; 568 else 569 enum isDebug = false; 570 571 deprecated alias IsDebug = isDebug; 572 573 /// Is a specific version on? 574 template isVersion(string versionName) 575 { 576 mixin(`version (` ~ versionName ~ `) enum isVersion = true; else enum isVersion = false;`); 577 } 578 579 // ************************************************************************ 580 581 /// Identity function. 582 auto ref T identity(T)(auto ref T value) { return value; } 583 584 /// Shorter synonym for std.traits.Identity. 585 /// Can be used to UFCS-chain static methods and nested functions. 586 alias I(alias A) = A; 587 588 // ************************************************************************ 589 590 /// Get f's ancestor which represents its "this" pointer. 591 /// Skips template and mixin ancestors until it finds a struct or class. 592 template thisOf(alias f) 593 { 594 alias p = Identity!(__traits(parent, f)); 595 static if (is(p == class) || is(p == struct) || is(p == union)) 596 alias thisOf = p; 597 else 598 alias thisOf = thisOf!p; 599 } 600 601 // ************************************************************************ 602 603 /// Return the number of bits used to store the value part, i.e. 604 /// T.sizeof*8 for integer parts and the mantissa size for 605 /// floating-point types. 606 template valueBits(T) 607 { 608 static if (is(T : ulong)) 609 enum valueBits = T.sizeof * 8; 610 else 611 static if (is(T : real)) 612 enum valueBits = T.mant_dig; 613 else 614 static assert(false, "Don't know how many value bits there are in " ~ T.stringof); 615 } 616 617 static assert(valueBits!uint == 32); 618 static assert(valueBits!double == 53); 619 620 /// Expand to a built-in numeric type of the same kind 621 /// (signed integer / unsigned integer / floating-point) 622 /// with at least the indicated number of bits of precision. 623 template ResizeNumericType(T, uint bits) 624 { 625 static if (is(T : ulong)) 626 static if (isSigned!T) 627 alias ResizeNumericType = SignedBitsType!bits; 628 else 629 alias ResizeNumericType = UnsignedBitsType!bits; 630 else 631 static if (is(T : real)) 632 { 633 static if (bits <= float.mant_dig) 634 alias ResizeNumericType = float; 635 else 636 static if (bits <= double.mant_dig) 637 alias ResizeNumericType = double; 638 else 639 static if (bits <= real.mant_dig) 640 alias ResizeNumericType = real; 641 else 642 static assert(0, "No floating-point type big enough to fit " ~ bits.stringof ~ " bits"); 643 } 644 else 645 static assert(false, "Don't know how to resize type: " ~ T.stringof); 646 } 647 648 static assert(is(ResizeNumericType!(float, double.mant_dig) == double)); 649 650 /// Expand to a built-in numeric type of the same kind 651 /// (signed integer / unsigned integer / floating-point) 652 /// with at least additionalBits more bits of precision. 653 alias ExpandNumericType(T, uint additionalBits) = 654 ResizeNumericType!(T, valueBits!T + additionalBits); 655 656 /// Like ExpandNumericType, but do not error if the resulting type is 657 /// too large to fit any native D type - just expand to the largest 658 /// type of the same kind instead. 659 template TryExpandNumericType(T, uint additionalBits) 660 { 661 static if (is(typeof(ExpandNumericType!(T, additionalBits)))) 662 alias TryExpandNumericType = ExpandNumericType!(T, additionalBits); 663 else 664 static if (is(T : ulong)) 665 static if (isSigned!T) 666 alias TryExpandNumericType = long; 667 else 668 alias TryExpandNumericType = ulong; 669 else 670 static if (is(T : real)) 671 alias TryExpandNumericType = real; 672 else 673 static assert(false, "Don't know how to expand type: " ~ T.stringof); 674 } 675 676 /// Unsigned integer type big enough to fit N bits of precision. 677 template UnsignedBitsType(uint bits) 678 { 679 static if (bits <= 8) 680 alias ubyte UnsignedBitsType; 681 else 682 static if (bits <= 16) 683 alias ushort UnsignedBitsType; 684 else 685 static if (bits <= 32) 686 alias uint UnsignedBitsType; 687 else 688 static if (bits <= 64) 689 alias ulong UnsignedBitsType; 690 else 691 static assert(0, "No integer type big enough to fit " ~ bits.stringof ~ " bits"); 692 } 693 694 template SignedBitsType(uint bits) 695 { 696 alias Signed!(UnsignedBitsType!bits) SignedBitsType; 697 } 698 699 /// Evaluates to array of strings with name for each field. 700 @property string[] structFields(T)() 701 if (is(T == struct) || is(T == class)) 702 { 703 import std.string : split; 704 705 string[] fields; 706 foreach (i, f; T.init.tupleof) 707 { 708 string field = T.tupleof[i].stringof; 709 field = field.split(".")[$-1]; 710 fields ~= field; 711 } 712 return fields; 713 } 714 715 /// Returns the class's initializer instance. 716 /// Returns null if all class fields are zero. 717 /// Can be used to get the value of class fields' initial values. 718 immutable(T) classInit(T)() 719 if (is(T == class)) 720 { 721 return cast(immutable(T))typeid(T).initializer.ptr; 722 } 723 724 /// 725 unittest 726 { 727 class C { int n = 42; } 728 assert(classInit!C.n == 42); 729 } 730 731 /// Create a functor value type (bound struct) from an alias. 732 template functor(alias fun) 733 { 734 struct Functor 735 { 736 //alias opCall = fun; 737 auto opCall(T...)(auto ref T args) { return fun(args); } 738 } 739 740 Functor functor() 741 { 742 Functor f; 743 return f; 744 } 745 } 746 747 static if (haveAliasStructBinding) 748 unittest 749 { 750 static void caller(F)(F fun) 751 { 752 fun(42); 753 } 754 755 int result; 756 caller(functor!((int i) => result = i)); 757 assert(result == 42); 758 }