forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraits.d
8662 lines (7567 loc) · 260 KB
/
traits.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
* Templates which extract information about types and symbols at compile time.
*
* $(SCRIPT inhibitQuickIndex = 1;)
*
* $(DIVC quickindex,
* $(BOOKTABLE ,
* $(TR $(TH Category) $(TH Templates))
* $(TR $(TD Symbol Name traits) $(TD
* $(LREF fullyQualifiedName)
* $(LREF moduleName)
* $(LREF packageName)
* ))
* $(TR $(TD Function traits) $(TD
* $(LREF isFunction)
* $(LREF arity)
* $(LREF functionAttributes)
* $(LREF hasFunctionAttributes)
* $(LREF functionLinkage)
* $(LREF FunctionTypeOf)
* $(LREF isSafe)
* $(LREF isUnsafe)
* $(LREF isFinal)
* $(LREF ParameterDefaults)
* $(LREF ParameterIdentifierTuple)
* $(LREF ParameterStorageClassTuple)
* $(LREF Parameters)
* $(LREF ReturnType)
* $(LREF SetFunctionAttributes)
* $(LREF variadicFunctionStyle)
* ))
* $(TR $(TD Aggregate Type traits) $(TD
* $(LREF BaseClassesTuple)
* $(LREF BaseTypeTuple)
* $(LREF classInstanceAlignment)
* $(LREF EnumMembers)
* $(LREF FieldNameTuple)
* $(LREF Fields)
* $(LREF hasAliasing)
* $(LREF hasElaborateAssign)
* $(LREF hasElaborateCopyConstructor)
* $(LREF hasElaborateDestructor)
* $(LREF hasIndirections)
* $(LREF hasMember)
* $(LREF hasStaticMember)
* $(LREF hasNested)
* $(LREF hasUnsharedAliasing)
* $(LREF InterfacesTuple)
* $(LREF isInnerClass)
* $(LREF isNested)
* $(LREF MemberFunctionsTuple)
* $(LREF RepresentationTypeTuple)
* $(LREF TemplateArgsOf)
* $(LREF TemplateOf)
* $(LREF TransitiveBaseTypeTuple)
* ))
* $(TR $(TD Type Conversion) $(TD
* $(LREF CommonType)
* $(LREF ImplicitConversionTargets)
* $(LREF CopyTypeQualifiers)
* $(LREF CopyConstness)
* $(LREF isAssignable)
* $(LREF isCovariantWith)
* $(LREF isImplicitlyConvertible)
* ))
* $(TR $(TD SomethingTypeOf) $(TD
* $(LREF rvalueOf)
* $(LREF lvalueOf)
* $(LREF InoutOf)
* $(LREF ConstOf)
* $(LREF SharedOf)
* $(LREF SharedInoutOf)
* $(LREF SharedConstOf)
* $(LREF ImmutableOf)
* $(LREF QualifierOf)
* ))
* $(TR $(TD Categories of types) $(TD
* $(LREF allSameType)
* $(LREF ifTestable)
* $(LREF isType)
* $(LREF isAggregateType)
* $(LREF isArray)
* $(LREF isAssociativeArray)
* $(LREF isAutodecodableString)
* $(LREF isBasicType)
* $(LREF isBoolean)
* $(LREF isBuiltinType)
* $(LREF isCopyable)
* $(LREF isDynamicArray)
* $(LREF isEqualityComparable)
* $(LREF isFloatingPoint)
* $(LREF isIntegral)
* $(LREF isNarrowString)
* $(LREF isConvertibleToString)
* $(LREF isNumeric)
* $(LREF isOrderingComparable)
* $(LREF isPointer)
* $(LREF isScalarType)
* $(LREF isSigned)
* $(LREF isSIMDVector)
* $(LREF isSomeChar)
* $(LREF isSomeString)
* $(LREF isStaticArray)
* $(LREF isUnsigned)
* ))
* $(TR $(TD Type behaviours) $(TD
* $(LREF isAbstractClass)
* $(LREF isAbstractFunction)
* $(LREF isCallable)
* $(LREF isDelegate)
* $(LREF isExpressions)
* $(LREF isFinalClass)
* $(LREF isFinalFunction)
* $(LREF isFunctionPointer)
* $(LREF isInstanceOf)
* $(LREF isIterable)
* $(LREF isMutable)
* $(LREF isSomeFunction)
* $(LREF isTypeTuple)
* ))
* $(TR $(TD General Types) $(TD
* $(LREF ForeachType)
* $(LREF KeyType)
* $(LREF Largest)
* $(LREF mostNegative)
* $(LREF OriginalType)
* $(LREF PointerTarget)
* $(LREF Signed)
* $(LREF Unqual)
* $(LREF Unsigned)
* $(LREF ValueType)
* $(LREF Promoted)
* ))
* $(TR $(TD Misc) $(TD
* $(LREF mangledName)
* $(LREF Select)
* $(LREF select)
* ))
* $(TR $(TD User-Defined Attributes) $(TD
* $(LREF hasUDA)
* $(LREF getUDAs)
* $(LREF getSymbolsByUDA)
* ))
* )
* )
*
* Copyright: Copyright The D Language Foundation 2005 - 2009.
* License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: $(HTTP digitalmars.com, Walter Bright),
* Tomasz Stachowiak (`isExpressions`),
* $(HTTP erdani.org, Andrei Alexandrescu),
* Shin Fujishiro,
* $(HTTP octarineparrot.com, Robert Clipsham),
* $(HTTP klickverbot.at, David Nadlinger),
* Kenji Hara,
* Shoichi Kato
* Source: $(PHOBOSSRC std/traits.d)
*/
/* Copyright The D Language Foundation 2005 - 2009.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
module std.traits;
import std.meta : AliasSeq, allSatisfy, anySatisfy;
import std.functional : unaryFun;
// Legacy inheritance from std.typetuple
// See also: https://github.com/dlang/phobos/pull/5484#discussion_r122602797
import std.meta : staticMapMeta = staticMap;
// TODO: find a way to trigger deprecation warnings
//deprecated("staticMap is part of std.meta: Please import std.meta")
alias staticMap = staticMapMeta;
///////////////////////////////////////////////////////////////////////////////
// Functions
///////////////////////////////////////////////////////////////////////////////
// Petit demangler
// (this or similar thing will eventually go to std.demangle if necessary
// ctfe stuffs are available)
private
{
struct Demangle(T)
{
T value; // extracted information
string rest;
}
/* Demangles mstr as the storage class part of Argument. */
Demangle!uint demangleParameterStorageClass(string mstr)
{
uint pstc = 0; // parameter storage class
// Argument --> Argument2 | M Argument2
if (mstr.length > 0 && mstr[0] == 'M')
{
pstc |= ParameterStorageClass.scope_;
mstr = mstr[1 .. $];
}
// Argument2 --> Type | J Type | K Type | L Type
ParameterStorageClass stc2;
switch (mstr.length ? mstr[0] : char.init)
{
case 'J': stc2 = ParameterStorageClass.out_; break;
case 'K': stc2 = ParameterStorageClass.ref_; break;
case 'L': stc2 = ParameterStorageClass.lazy_; break;
case 'N': if (mstr.length >= 2 && mstr[1] == 'k')
stc2 = ParameterStorageClass.return_;
break;
default : break;
}
if (stc2 != ParameterStorageClass.init)
{
pstc |= stc2;
mstr = mstr[1 .. $];
if (stc2 & ParameterStorageClass.return_)
mstr = mstr[1 .. $];
}
return Demangle!uint(pstc, mstr);
}
/* Demangles mstr as FuncAttrs. */
Demangle!uint demangleFunctionAttributes(string mstr)
{
immutable LOOKUP_ATTRIBUTE =
[
'a': FunctionAttribute.pure_,
'b': FunctionAttribute.nothrow_,
'c': FunctionAttribute.ref_,
'd': FunctionAttribute.property,
'e': FunctionAttribute.trusted,
'f': FunctionAttribute.safe,
'i': FunctionAttribute.nogc,
'j': FunctionAttribute.return_,
'l': FunctionAttribute.scope_
];
uint atts = 0;
// FuncAttrs --> FuncAttr | FuncAttr FuncAttrs
// FuncAttr --> empty | Na | Nb | Nc | Nd | Ne | Nf | Ni | Nj
// except 'Ng' == inout, because it is a qualifier of function type
while (mstr.length >= 2 && mstr[0] == 'N' && mstr[1] != 'g' && mstr[1] != 'k')
{
if (FunctionAttribute att = LOOKUP_ATTRIBUTE[ mstr[1] ])
{
atts |= att;
mstr = mstr[2 .. $];
}
else assert(0);
}
return Demangle!uint(atts, mstr);
}
static if (is(ucent))
{
alias CentTypeList = AliasSeq!(cent, ucent);
alias SignedCentTypeList = AliasSeq!(cent);
alias UnsignedCentTypeList = AliasSeq!(ucent);
}
else
{
alias CentTypeList = AliasSeq!();
alias SignedCentTypeList = AliasSeq!();
alias UnsignedCentTypeList = AliasSeq!();
}
alias IntegralTypeList = AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong, CentTypeList);
alias SignedIntTypeList = AliasSeq!(byte, short, int, long, SignedCentTypeList);
alias UnsignedIntTypeList = AliasSeq!(ubyte, ushort, uint, ulong, UnsignedCentTypeList);
alias FloatingPointTypeList = AliasSeq!(float, double, real);
alias ImaginaryTypeList = AliasSeq!(ifloat, idouble, ireal);
alias ComplexTypeList = AliasSeq!(cfloat, cdouble, creal);
alias NumericTypeList = AliasSeq!(IntegralTypeList, FloatingPointTypeList);
alias CharTypeList = AliasSeq!(char, wchar, dchar);
}
package
{
// Add the mutable qualifier to the given type T.
template MutableOf(T) { alias MutableOf = T ; }
}
/**
* Params:
* T = The type to qualify
* Returns:
* `T` with the `inout` qualifier added.
*/
template InoutOf(T)
{
alias InoutOf = inout(T);
}
///
@safe unittest
{
static assert(is(InoutOf!(int) == inout int));
static assert(is(InoutOf!(inout int) == inout int));
static assert(is(InoutOf!(const int) == inout const int));
static assert(is(InoutOf!(shared int) == inout shared int));
}
/**
* Params:
* T = The type to qualify
* Returns:
* `T` with the `const` qualifier added.
*/
template ConstOf(T)
{
alias ConstOf = const(T);
}
///
@safe unittest
{
static assert(is(ConstOf!(int) == const int));
static assert(is(ConstOf!(const int) == const int));
static assert(is(ConstOf!(inout int) == const inout int));
static assert(is(ConstOf!(shared int) == const shared int));
}
/**
* Params:
* T = The type to qualify
* Returns:
* `T` with the `shared` qualifier added.
*/
template SharedOf(T)
{
alias SharedOf = shared(T);
}
///
@safe unittest
{
static assert(is(SharedOf!(int) == shared int));
static assert(is(SharedOf!(shared int) == shared int));
static assert(is(SharedOf!(inout int) == shared inout int));
static assert(is(SharedOf!(immutable int) == shared immutable int));
}
/**
* Params:
* T = The type to qualify
* Returns:
* `T` with the `inout` and `shared` qualifiers added.
*/
template SharedInoutOf(T)
{
alias SharedInoutOf = shared(inout(T));
}
///
@safe unittest
{
static assert(is(SharedInoutOf!(int) == shared inout int));
static assert(is(SharedInoutOf!(int) == inout shared int));
static assert(is(SharedInoutOf!(const int) == shared inout const int));
static assert(is(SharedInoutOf!(immutable int) == shared inout immutable int));
}
/**
* Params:
* T = The type to qualify
* Returns:
* `T` with the `const` and `shared` qualifiers added.
*/
template SharedConstOf(T)
{
alias SharedConstOf = shared(const(T));
}
///
@safe unittest
{
static assert(is(SharedConstOf!(int) == shared const int));
static assert(is(SharedConstOf!(int) == const shared int));
static assert(is(SharedConstOf!(inout int) == shared inout const int));
// immutable variables are implicitly shared and const
static assert(is(SharedConstOf!(immutable int) == immutable int));
}
/**
* Params:
* T = The type to qualify
* Returns:
* `T` with the `immutable` qualifier added.
*/
template ImmutableOf(T)
{
alias ImmutableOf = immutable(T);
}
///
@safe unittest
{
static assert(is(ImmutableOf!(int) == immutable int));
static assert(is(ImmutableOf!(const int) == immutable int));
static assert(is(ImmutableOf!(inout int) == immutable int));
static assert(is(ImmutableOf!(shared int) == immutable int));
}
@safe unittest
{
static assert(is( MutableOf!int == int));
static assert(is( InoutOf!int == inout int));
static assert(is( ConstOf!int == const int));
static assert(is( SharedOf!int == shared int));
static assert(is(SharedInoutOf!int == shared inout int));
static assert(is(SharedConstOf!int == shared const int));
static assert(is( ImmutableOf!int == immutable int));
}
/**
* Gives a template that can be used to apply the same
* attributes that are on the given type `T`. E.g. passing
* `inout shared int` will return `SharedInoutOf`.
*
* Params:
* T = the type to check qualifiers from
* Returns:
* The qualifier template from the given type `T`
*/
template QualifierOf(T)
{
static if (is(T == shared(const U), U))
alias QualifierOf = SharedConstOf;
else static if (is(T == const U, U))
alias QualifierOf = ConstOf;
else static if (is(T == shared(inout U), U))
alias QualifierOf = SharedInoutOf;
else static if (is(T == inout U, U))
alias QualifierOf = InoutOf;
else static if (is(T == immutable U, U))
alias QualifierOf = ImmutableOf;
else static if (is(T == shared U, U))
alias QualifierOf = SharedOf;
else
alias QualifierOf = MutableOf;
}
///
@safe unittest
{
static assert(__traits(isSame, QualifierOf!(immutable int), ImmutableOf));
static assert(__traits(isSame, QualifierOf!(shared int), SharedOf));
static assert(__traits(isSame, QualifierOf!(shared inout int), SharedInoutOf));
}
@safe unittest
{
alias Qual1 = QualifierOf!( int); static assert(is(Qual1!long == long));
alias Qual2 = QualifierOf!( inout int); static assert(is(Qual2!long == inout long));
alias Qual3 = QualifierOf!( const int); static assert(is(Qual3!long == const long));
alias Qual4 = QualifierOf!(shared int); static assert(is(Qual4!long == shared long));
alias Qual5 = QualifierOf!(shared inout int); static assert(is(Qual5!long == shared inout long));
alias Qual6 = QualifierOf!(shared const int); static assert(is(Qual6!long == shared const long));
alias Qual7 = QualifierOf!( immutable int); static assert(is(Qual7!long == immutable long));
}
version (unittest)
{
alias TypeQualifierList = AliasSeq!(MutableOf, ConstOf, SharedOf, SharedConstOf, ImmutableOf);
struct SubTypeOf(T)
{
T val;
alias val this;
}
}
private alias parentOf(alias sym) = Identity!(__traits(parent, sym));
private alias parentOf(alias sym : T!Args, alias T, Args...) = Identity!(__traits(parent, T));
/**
* Get the full package name for the given symbol.
*/
template packageName(alias T)
{
import std.algorithm.searching : startsWith;
enum bool isNotFunc = !isSomeFunction!(T);
static if (__traits(compiles, parentOf!T))
enum parent = packageName!(parentOf!T);
else
enum string parent = null;
static if (isNotFunc && T.stringof.startsWith("package "))
enum packageName = (parent.length ? parent ~ '.' : "") ~ T.stringof[8 .. $];
else static if (parent)
enum packageName = parent;
else
static assert(false, T.stringof ~ " has no parent");
}
///
@safe unittest
{
static assert(packageName!packageName == "std");
}
@safe unittest
{
import std.array;
static assert(packageName!std == "std");
static assert(packageName!(std.traits) == "std"); // this module
static assert(packageName!packageName == "std"); // symbol in this module
static assert(packageName!(std.array) == "std"); // other module from same package
import core.sync.barrier; // local import
static assert(packageName!core == "core");
static assert(packageName!(core.sync) == "core.sync");
static assert(packageName!Barrier == "core.sync");
struct X12287(T) { T i; }
static assert(packageName!(X12287!int.i) == "std");
}
version (none) @safe unittest //Please uncomment me when changing packageName to test global imports
{
import core.sync.barrier; // global import
static assert(packageName!core == "core");
static assert(packageName!(core.sync) == "core.sync");
static assert(packageName!Barrier == "core.sync");
}
///
@safe unittest
{
static assert(packageName!moduleName == "std");
}
@safe unittest // issue 13741
{
import std.ascii : isWhite;
static assert(packageName!(isWhite) == "std");
struct Foo{void opCall(int){}}
static assert(packageName!(Foo.opCall) == "std");
@property void function(int) vf;
static assert(packageName!(vf) == "std");
}
/**
* Get the module name (including package) for the given symbol.
*/
template moduleName(alias T)
{
import std.algorithm.searching : startsWith;
enum bool isNotFunc = !isSomeFunction!(T);
static if (isNotFunc)
static assert(!T.stringof.startsWith("package "),
"cannot get the module name for a package");
static if (isNotFunc && T.stringof.startsWith("module "))
{
static if (__traits(compiles, packageName!T))
enum packagePrefix = packageName!T ~ '.';
else
enum packagePrefix = "";
enum moduleName = packagePrefix ~ T.stringof[7..$];
}
else
alias moduleName = moduleName!(parentOf!T); // If you use enum, it will cause compiler ICE
}
///
@safe unittest
{
static assert(moduleName!moduleName == "std.traits");
}
@safe unittest
{
import std.array;
static assert(!__traits(compiles, moduleName!std));
static assert(moduleName!(std.traits) == "std.traits"); // this module
static assert(moduleName!moduleName == "std.traits"); // symbol in this module
static assert(moduleName!(std.array) == "std.array"); // other module
static assert(moduleName!(std.array.array) == "std.array"); // symbol in other module
import core.sync.barrier; // local import
static assert(!__traits(compiles, moduleName!(core.sync)));
static assert(moduleName!(core.sync.barrier) == "core.sync.barrier");
static assert(moduleName!Barrier == "core.sync.barrier");
struct X12287(T) { T i; }
static assert(moduleName!(X12287!int.i) == "std.traits");
}
@safe unittest // issue 13741
{
import std.ascii : isWhite;
static assert(moduleName!(isWhite) == "std.ascii");
struct Foo{void opCall(int){}}
static assert(moduleName!(Foo.opCall) == "std.traits");
@property void function(int) vf;
static assert(moduleName!(vf) == "std.traits");
}
version (none) @safe unittest //Please uncomment me when changing moduleName to test global imports
{
import core.sync.barrier; // global import
static assert(!__traits(compiles, moduleName!(core.sync)));
static assert(moduleName!(core.sync.barrier) == "core.sync.barrier");
static assert(moduleName!Barrier == "core.sync.barrier");
}
/***
* Get the fully qualified name of a type or a symbol. Can act as an intelligent type/symbol to string converter.
Example:
-----------------
module myModule;
struct MyStruct {}
static assert(fullyQualifiedName!(const MyStruct[]) == "const(myModule.MyStruct[])");
-----------------
*/
template fullyQualifiedName(T...)
if (T.length == 1)
{
static if (is(T))
enum fullyQualifiedName = fqnType!(T[0], false, false, false, false);
else
enum fullyQualifiedName = fqnSym!(T[0]);
}
///
@safe unittest
{
static assert(fullyQualifiedName!fullyQualifiedName == "std.traits.fullyQualifiedName");
}
version (unittest)
{
// Used for both fqnType and fqnSym unittests
private struct QualifiedNameTests
{
struct Inner
{
bool value;
}
ref const(Inner[string]) func( ref Inner var1, lazy scope string var2 );
ref const(Inner[string]) retfunc( return ref Inner var1 );
Inner inoutFunc(inout Inner) inout;
shared(const(Inner[string])[]) data;
const Inner delegate(double, string) @safe nothrow deleg;
inout(int) delegate(inout int) inout inoutDeleg;
Inner function(out double, string) funcPtr;
extern(C) Inner function(double, string) cFuncPtr;
extern(C) void cVarArg(int, ...);
void dVarArg(...);
void dVarArg2(int, ...);
void typesafeVarArg(int[] ...);
Inner[] array;
Inner[16] sarray;
Inner[Inner] aarray;
const(Inner[const(Inner)]) qualAarray;
shared(immutable(Inner) delegate(ref double, scope string) const shared @trusted nothrow) attrDeleg;
struct Data(T) { int x; }
void tfunc(T...)(T args) {}
template Inst(alias A) { int x; }
class Test12309(T, int x, string s) {}
}
private enum QualifiedEnum
{
a = 42
}
}
private template fqnSym(alias T : X!A, alias X, A...)
{
template fqnTuple(T...)
{
static if (T.length == 0)
enum fqnTuple = "";
else static if (T.length == 1)
{
static if (isExpressionTuple!T)
enum fqnTuple = T[0].stringof;
else
enum fqnTuple = fullyQualifiedName!(T[0]);
}
else
enum fqnTuple = fqnTuple!(T[0]) ~ ", " ~ fqnTuple!(T[1 .. $]);
}
enum fqnSym =
fqnSym!(__traits(parent, X)) ~
'.' ~ __traits(identifier, X) ~ "!(" ~ fqnTuple!A ~ ")";
}
private template fqnSym(alias T)
{
static if (__traits(compiles, __traits(parent, T)) && !__traits(isSame, T, __traits(parent, T)))
enum parentPrefix = fqnSym!(__traits(parent, T)) ~ ".";
else
enum parentPrefix = null;
static string adjustIdent(string s)
{
import std.algorithm.searching : findSplit, skipOver;
if (s.skipOver("package ") || s.skipOver("module "))
return s;
return s.findSplit("(")[0];
}
enum fqnSym = parentPrefix ~ adjustIdent(__traits(identifier, T));
}
@safe unittest
{
alias fqn = fullyQualifiedName;
// Make sure those 2 are the same
static assert(fqnSym!fqn == fqn!fqn);
static assert(fqn!fqn == "std.traits.fullyQualifiedName");
alias qnTests = QualifiedNameTests;
enum prefix = "std.traits.QualifiedNameTests.";
static assert(fqn!(qnTests.Inner) == prefix ~ "Inner");
static assert(fqn!(qnTests.func) == prefix ~ "func");
static assert(fqn!(qnTests.Data!int) == prefix ~ "Data!(int)");
static assert(fqn!(qnTests.Data!int.x) == prefix ~ "Data!(int).x");
static assert(fqn!(qnTests.tfunc!(int[])) == prefix ~ "tfunc!(int[])");
static assert(fqn!(qnTests.Inst!(Object)) == prefix ~ "Inst!(object.Object)");
static assert(fqn!(qnTests.Inst!(Object).x) == prefix ~ "Inst!(object.Object).x");
static assert(fqn!(qnTests.Test12309!(int, 10, "str"))
== prefix ~ "Test12309!(int, 10, \"str\")");
import core.sync.barrier;
static assert(fqn!Barrier == "core.sync.barrier.Barrier");
}
@safe unittest
{
struct TemplatedStruct()
{
enum foo = 0;
}
alias TemplatedStructAlias = TemplatedStruct;
assert("TemplatedStruct.foo" == fullyQualifiedName!(TemplatedStructAlias!().foo));
}
private template fqnType(T,
bool alreadyConst, bool alreadyImmutable, bool alreadyShared, bool alreadyInout)
{
import std.format : format;
// Convenience tags
enum {
_const = 0,
_immutable = 1,
_shared = 2,
_inout = 3
}
alias qualifiers = AliasSeq!(is(T == const), is(T == immutable), is(T == shared), is(T == inout));
alias noQualifiers = AliasSeq!(false, false, false, false);
string storageClassesString(uint psc)() @property
{
alias PSC = ParameterStorageClass;
return format("%s%s%s%s%s",
psc & PSC.scope_ ? "scope " : "",
psc & PSC.return_ ? "return " : "",
psc & PSC.out_ ? "out " : "",
psc & PSC.ref_ ? "ref " : "",
psc & PSC.lazy_ ? "lazy " : ""
);
}
string parametersTypeString(T)() @property
{
alias parameters = Parameters!(T);
alias parameterStC = ParameterStorageClassTuple!(T);
enum variadic = variadicFunctionStyle!T;
static if (variadic == Variadic.no)
enum variadicStr = "";
else static if (variadic == Variadic.c)
enum variadicStr = ", ...";
else static if (variadic == Variadic.d)
enum variadicStr = parameters.length ? ", ..." : "...";
else static if (variadic == Variadic.typesafe)
enum variadicStr = " ...";
else
static assert(0, "New variadic style has been added, please update fullyQualifiedName implementation");
static if (parameters.length)
{
import std.algorithm.iteration : map;
import std.array : join;
import std.meta : staticMap;
import std.range : zip;
string result = join(
map!(a => format("%s%s", a[0], a[1]))(
zip([staticMap!(storageClassesString, parameterStC)],
[staticMap!(fullyQualifiedName, parameters)])
),
", "
);
return result ~= variadicStr;
}
else
return variadicStr;
}
string linkageString(T)() @property
{
enum linkage = functionLinkage!T;
if (linkage != "D")
return format("extern(%s) ", linkage);
else
return "";
}
string functionAttributeString(T)() @property
{
alias FA = FunctionAttribute;
enum attrs = functionAttributes!T;
static if (attrs == FA.none)
return "";
else
return format("%s%s%s%s%s%s%s%s",
attrs & FA.pure_ ? " pure" : "",
attrs & FA.nothrow_ ? " nothrow" : "",
attrs & FA.ref_ ? " ref" : "",
attrs & FA.property ? " @property" : "",
attrs & FA.trusted ? " @trusted" : "",
attrs & FA.safe ? " @safe" : "",
attrs & FA.nogc ? " @nogc" : "",
attrs & FA.return_ ? " return" : ""
);
}
string addQualifiers(string typeString,
bool addConst, bool addImmutable, bool addShared, bool addInout)
{
auto result = typeString;
if (addShared)
{
result = format("shared(%s)", result);
}
if (addConst || addImmutable || addInout)
{
result = format("%s(%s)",
addConst ? "const" :
addImmutable ? "immutable" : "inout",
result
);
}
return result;
}
// Convenience template to avoid copy-paste
template chain(string current)
{
enum chain = addQualifiers(current,
qualifiers[_const] && !alreadyConst,
qualifiers[_immutable] && !alreadyImmutable,
qualifiers[_shared] && !alreadyShared,
qualifiers[_inout] && !alreadyInout);
}
static if (is(T == string))
{
enum fqnType = "string";
}
else static if (is(T == wstring))
{
enum fqnType = "wstring";
}
else static if (is(T == dstring))
{
enum fqnType = "dstring";
}
else static if (isBasicType!T && !is(T == enum))
{
enum fqnType = chain!((Unqual!T).stringof);
}
else static if (isAggregateType!T || is(T == enum))
{
enum fqnType = chain!(fqnSym!T);
}
else static if (isStaticArray!T)
{
enum fqnType = chain!(
format("%s[%s]", fqnType!(typeof(T.init[0]), qualifiers), T.length)
);
}
else static if (isArray!T)
{
enum fqnType = chain!(
format("%s[]", fqnType!(typeof(T.init[0]), qualifiers))
);
}
else static if (isAssociativeArray!T)
{
enum fqnType = chain!(
format("%s[%s]", fqnType!(ValueType!T, qualifiers), fqnType!(KeyType!T, noQualifiers))
);
}
else static if (isSomeFunction!T)
{
static if (is(T F == delegate))
{
enum qualifierString = format("%s%s",
is(F == shared) ? " shared" : "",
is(F == inout) ? " inout" :
is(F == immutable) ? " immutable" :
is(F == const) ? " const" : ""
);
enum formatStr = "%s%s delegate(%s)%s%s";
enum fqnType = chain!(
format(formatStr, linkageString!T, fqnType!(ReturnType!T, noQualifiers),
parametersTypeString!(T), functionAttributeString!T, qualifierString)
);
}
else
{
static if (isFunctionPointer!T)
enum formatStr = "%s%s function(%s)%s";
else
enum formatStr = "%s%s(%s)%s";
enum fqnType = chain!(
format(formatStr, linkageString!T, fqnType!(ReturnType!T, noQualifiers),
parametersTypeString!(T), functionAttributeString!T)
);
}
}
else static if (isPointer!T)
{
enum fqnType = chain!(
format("%s*", fqnType!(PointerTarget!T, qualifiers))
);
}
else static if (is(T : __vector(V[N]), V, size_t N))
{
enum fqnType = chain!(
format("__vector(%s[%s])", fqnType!(V, qualifiers), N)
);
}
else
// In case something is forgotten
static assert(0, "Unrecognized type " ~ T.stringof ~ ", can't convert to fully qualified string");
}
@safe unittest
{
import std.format : format;
alias fqn = fullyQualifiedName;
// Verify those 2 are the same for simple case
alias Ambiguous = const(QualifiedNameTests.Inner);
static assert(fqn!Ambiguous == fqnType!(Ambiguous, false, false, false, false));
// Main tests
enum inner_name = "std.traits.QualifiedNameTests.Inner";
with (QualifiedNameTests)
{
// Special cases
static assert(fqn!(string) == "string");
static assert(fqn!(wstring) == "wstring");