2 * Forms the symbols available to all D programs. Includes Object, which is
3 * the root of the class object hierarchy. This module is implicitly
6 * Copyright: Copyright Digital Mars 2000 - 2011.
7 * License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
8 * Authors: Walter Bright, Sean Kelly
15 extern (C) Object _d_newclass(const TypeInfo_Class ci);
16 extern (C) void rt_finalize(void *data, bool det=true);
19 // NOTE: For some reason, this declaration method doesn't work
20 // in this particular file (and this file only). It must
22 //alias typeof(int.sizeof) size_t;
23 //alias typeof(cast(void*)0 - cast(void*)0) ptrdiff_t;
28 alias ptrdiff_t = long;
33 alias ptrdiff_t = int;
36 alias sizediff_t = ptrdiff_t; //For backwards compatibility only.
38 alias hash_t = size_t; //For backwards compatibility only.
39 alias equals_t = bool; //For backwards compatibility only.
41 alias string = immutable(char)[];
42 alias wstring = immutable(wchar)[];
43 alias dstring = immutable(dchar)[];
45 version (D_ObjectiveC) public import core.attribute : selector;
48 * All D class objects inherit from Object.
53 * Convert Object to a human readable string.
57 return typeid(this).name;
61 * Compute hash function for Object.
63 size_t toHash() @trusted nothrow
65 // BUG: this prevents a compacting GC from working, needs to be fixed
66 size_t addr = cast(size_t) cast(void*) this;
67 // The bottom log2((void*).alignof) bits of the address will always
68 // be 0. Moreover it is likely that each Object is allocated with a
69 // separate call to malloc. The alignment of malloc differs from
70 // platform to platform, but rather than having special cases for
71 // each platform it is safe to use a shift of 4. To minimize
72 // collisions in the low bits it is more important for the shift to
73 // not be too small than for the shift to not be too big.
74 return addr ^ (addr >>> 4);
78 * Compare with another Object obj.
81 * $(TR $(TD this < obj) $(TD < 0))
82 * $(TR $(TD this == obj) $(TD 0))
83 * $(TR $(TD this > obj) $(TD > 0))
88 // BUG: this prevents a compacting GC from working, needs to be fixed
89 //return cast(int)cast(void*)this - cast(int)cast(void*)o;
91 throw new Exception("need opCmp for class " ~ typeid(this).name);
96 * Test whether $(D this) is equal to $(D o).
97 * The default implementation only compares by identity (using the $(D is) operator).
98 * Generally, overrides for $(D opEquals) should attempt to compare objects by their contents.
100 bool opEquals(Object o)
112 * Create instance of class specified by the fully qualified name
114 * The class must either have no constructors or have
115 * a default constructor.
130 * auto c = cast(C)Object.factory("foo.bar.C");
131 * assert(c !is null && c.x == 10);
135 static Object factory(string classname)
137 auto ci = TypeInfo_Class.find(classname);
146 auto opEquals(Object lhs, Object rhs)
148 // If aliased to the same object or both null => equal
149 if (lhs is rhs) return true;
151 // If either is null => non-equal
152 if (lhs is null || rhs is null) return false;
154 // If same exact type => one call to method opEquals
155 if (typeid(lhs) is typeid(rhs) ||
156 !__ctfe && typeid(lhs).opEquals(typeid(rhs)))
157 /* CTFE doesn't like typeid much. 'is' works, but opEquals doesn't
158 (issue 7147). But CTFE also guarantees that equal TypeInfos are
159 always identical. So, no opEquals needed during CTFE. */
161 return lhs.opEquals(rhs);
164 // General case => symmetric calls to method opEquals
165 return lhs.opEquals(rhs) && rhs.opEquals(lhs);
168 /************************
169 * Returns true if lhs and rhs are equal.
171 auto opEquals(const Object lhs, const Object rhs)
173 // A hack for the moment.
174 return opEquals(cast()lhs, cast()rhs);
177 private extern(C) void _d_setSameMutex(shared Object ownee, shared Object owner) nothrow;
179 void setSameMutex(shared Object ownee, shared Object owner)
181 _d_setSameMutex(ownee, owner);
185 * Information about an interface.
186 * When an object is accessed via an interface, an Interface* appears as the
187 * first entry in its vtbl.
191 TypeInfo_Class classinfo; /// .classinfo for this interface (not for containing class)
193 size_t offset; /// offset to Interface 'this' from Object 'this'
197 * Array of pairs giving the offset and type information for each
198 * member in an aggregate.
200 struct OffsetTypeInfo
202 size_t offset; /// Offset of member from start of object
203 TypeInfo ti; /// TypeInfo for this member
207 * Runtime type information about a type.
208 * Can be retrieved for any type using a
209 * $(GLINK2 expression,TypeidExpression, TypeidExpression).
213 override string toString() const pure @safe nothrow
215 return typeid(this).name;
218 override size_t toHash() @trusted const nothrow
220 return hashOf(this.toString());
223 override int opCmp(Object o)
225 import core.internal.traits : externDFunc;
226 alias dstrcmp = externDFunc!("core.internal.string.dstrcmp",
227 int function(scope const char[] s1, scope const char[] s2) @trusted pure nothrow @nogc);
231 TypeInfo ti = cast(TypeInfo)o;
234 return dstrcmp(this.toString(), ti.toString());
237 override bool opEquals(Object o)
239 /* TypeInfo instances are singletons, but duplicates can exist
240 * across DLL's. Therefore, comparing for a name match is
245 auto ti = cast(const TypeInfo)o;
246 return ti && this.toString() == ti.toString();
250 * Computes a hash of the instance of a type.
252 * p = pointer to start of instance of the type
256 * fix https://issues.dlang.org/show_bug.cgi?id=12516 e.g. by changing this to a truly safe interface.
258 size_t getHash(scope const void* p) @trusted nothrow const
263 /// Compares two instances for equality.
264 bool equals(in void* p1, in void* p2) const { return p1 == p2; }
266 /// Compares two instances for <, ==, or >.
267 int compare(in void* p1, in void* p2) const { return _xopCmp(p1, p2); }
269 /// Returns size of the type.
270 @property size_t tsize() nothrow pure const @safe @nogc { return 0; }
272 /// Swaps two instances of the type.
273 void swap(void* p1, void* p2) const
275 immutable size_t n = tsize;
276 for (size_t i = 0; i < n; i++)
278 byte t = (cast(byte *)p1)[i];
279 (cast(byte*)p1)[i] = (cast(byte*)p2)[i];
280 (cast(byte*)p2)[i] = t;
284 /** Get TypeInfo for 'next' type, as defined by what kind of type this is,
286 @property inout(TypeInfo) next() nothrow pure inout @nogc { return null; }
289 * Return default initializer. If the type should be initialized to all
290 * zeros, an array with a null ptr and a length equal to the type size will
291 * be returned. For static arrays, this returns the default initializer for
292 * a single element of the array, use `tsize` to get the correct size.
294 abstract const(void)[] initializer() nothrow pure const @safe @nogc;
296 /** Get flags for type: 1 means GC should scan for pointers,
297 2 means arg of this type is passed in XMM register */
298 @property uint flags() nothrow pure const @safe @nogc { return 0; }
300 /// Get type information on the contents of the type; null if not available
301 const(OffsetTypeInfo)[] offTi() const { return null; }
302 /// Run the destructor on the object and all its sub-objects
303 void destroy(void* p) const {}
304 /// Run the postblit on the object and all its sub-objects
305 void postblit(void* p) const {}
308 /// Return alignment of type
309 @property size_t talign() nothrow pure const @safe @nogc { return tsize; }
311 /** Return internal info on arguments fitting into 8byte.
312 * See X86-64 ABI 3.2.3
314 version (X86_64) int argTypes(out TypeInfo arg1, out TypeInfo arg2) @safe nothrow
320 /** Return info used by the garbage collector to do precise collection.
322 @property immutable(void)* rtInfo() nothrow pure const @safe @nogc { return null; }
325 class TypeInfo_Enum : TypeInfo
327 override string toString() const { return name; }
329 override bool opEquals(Object o)
333 auto c = cast(const TypeInfo_Enum)o;
334 return c && this.name == c.name &&
338 override size_t getHash(scope const void* p) const { return base.getHash(p); }
339 override bool equals(in void* p1, in void* p2) const { return base.equals(p1, p2); }
340 override int compare(in void* p1, in void* p2) const { return base.compare(p1, p2); }
341 override @property size_t tsize() nothrow pure const { return base.tsize; }
342 override void swap(void* p1, void* p2) const { return base.swap(p1, p2); }
344 override @property inout(TypeInfo) next() nothrow pure inout { return base.next; }
345 override @property uint flags() nothrow pure const { return base.flags; }
347 override const(void)[] initializer() const
349 return m_init.length ? m_init : base.initializer();
352 override @property size_t talign() nothrow pure const { return base.talign; }
354 version (X86_64) override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
356 return base.argTypes(arg1, arg2);
359 override @property immutable(void)* rtInfo() const { return base.rtInfo; }
366 unittest // issue 12233
368 static assert(is(typeof(TypeInfo.init) == TypeInfo));
369 assert(TypeInfo.init is null);
373 // Please make sure to keep this in sync with TypeInfo_P (src/rt/typeinfo/ti_ptr.d)
374 class TypeInfo_Pointer : TypeInfo
376 override string toString() const { return m_next.toString() ~ "*"; }
378 override bool opEquals(Object o)
382 auto c = cast(const TypeInfo_Pointer)o;
383 return c && this.m_next == c.m_next;
386 override size_t getHash(scope const void* p) @trusted const
388 size_t addr = cast(size_t) *cast(const void**)p;
389 return addr ^ (addr >> 4);
392 override bool equals(in void* p1, in void* p2) const
394 return *cast(void**)p1 == *cast(void**)p2;
397 override int compare(in void* p1, in void* p2) const
399 if (*cast(void**)p1 < *cast(void**)p2)
401 else if (*cast(void**)p1 > *cast(void**)p2)
407 override @property size_t tsize() nothrow pure const
409 return (void*).sizeof;
412 override const(void)[] initializer() const @trusted
414 return (cast(void *)null)[0 .. (void*).sizeof];
417 override void swap(void* p1, void* p2) const
419 void* tmp = *cast(void**)p1;
420 *cast(void**)p1 = *cast(void**)p2;
421 *cast(void**)p2 = tmp;
424 override @property inout(TypeInfo) next() nothrow pure inout { return m_next; }
425 override @property uint flags() nothrow pure const { return 1; }
430 class TypeInfo_Array : TypeInfo
432 override string toString() const { return value.toString() ~ "[]"; }
434 override bool opEquals(Object o)
438 auto c = cast(const TypeInfo_Array)o;
439 return c && this.value == c.value;
442 override size_t getHash(scope const void* p) @trusted const
444 void[] a = *cast(void[]*)p;
445 return getArrayHash(value, a.ptr, a.length);
448 override bool equals(in void* p1, in void* p2) const
450 void[] a1 = *cast(void[]*)p1;
451 void[] a2 = *cast(void[]*)p2;
452 if (a1.length != a2.length)
454 size_t sz = value.tsize;
455 for (size_t i = 0; i < a1.length; i++)
457 if (!value.equals(a1.ptr + i * sz, a2.ptr + i * sz))
463 override int compare(in void* p1, in void* p2) const
465 void[] a1 = *cast(void[]*)p1;
466 void[] a2 = *cast(void[]*)p2;
467 size_t sz = value.tsize;
468 size_t len = a1.length;
472 for (size_t u = 0; u < len; u++)
474 immutable int result = value.compare(a1.ptr + u * sz, a2.ptr + u * sz);
478 return cast(int)a1.length - cast(int)a2.length;
481 override @property size_t tsize() nothrow pure const
483 return (void[]).sizeof;
486 override const(void)[] initializer() const @trusted
488 return (cast(void *)null)[0 .. (void[]).sizeof];
491 override void swap(void* p1, void* p2) const
493 void[] tmp = *cast(void[]*)p1;
494 *cast(void[]*)p1 = *cast(void[]*)p2;
495 *cast(void[]*)p2 = tmp;
500 override @property inout(TypeInfo) next() nothrow pure inout
505 override @property uint flags() nothrow pure const { return 1; }
507 override @property size_t talign() nothrow pure const
509 return (void[]).alignof;
512 version (X86_64) override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
514 arg1 = typeid(size_t);
515 arg2 = typeid(void*);
520 class TypeInfo_StaticArray : TypeInfo
522 override string toString() const
524 import core.internal.traits : externDFunc;
525 alias sizeToTempString = externDFunc!("core.internal.string.unsignedToTempString",
526 char[] function(ulong, return char[], uint) @safe pure nothrow @nogc);
528 char[20] tmpBuff = void;
529 return value.toString() ~ "[" ~ sizeToTempString(len, tmpBuff, 10) ~ "]";
532 override bool opEquals(Object o)
536 auto c = cast(const TypeInfo_StaticArray)o;
537 return c && this.len == c.len &&
538 this.value == c.value;
541 override size_t getHash(scope const void* p) @trusted const
543 return getArrayHash(value, p, len);
546 override bool equals(in void* p1, in void* p2) const
548 size_t sz = value.tsize;
550 for (size_t u = 0; u < len; u++)
552 if (!value.equals(p1 + u * sz, p2 + u * sz))
558 override int compare(in void* p1, in void* p2) const
560 size_t sz = value.tsize;
562 for (size_t u = 0; u < len; u++)
564 immutable int result = value.compare(p1 + u * sz, p2 + u * sz);
571 override @property size_t tsize() nothrow pure const
573 return len * value.tsize;
576 override void swap(void* p1, void* p2) const
579 import core.stdc.string : memcpy;
582 size_t sz = value.tsize;
586 if (sz < buffer.sizeof)
589 tmp = pbuffer = (new void[sz]).ptr;
591 for (size_t u = 0; u < len; u += sz)
594 memcpy(tmp, p1 + o, sz);
595 memcpy(p1 + o, p2 + o, sz);
596 memcpy(p2 + o, tmp, sz);
602 override const(void)[] initializer() nothrow pure const
604 return value.initializer();
607 override @property inout(TypeInfo) next() nothrow pure inout { return value; }
608 override @property uint flags() nothrow pure const { return value.flags; }
610 override void destroy(void* p) const
612 immutable sz = value.tsize;
614 foreach (i; 0 .. len)
621 override void postblit(void* p) const
623 immutable sz = value.tsize;
624 foreach (i; 0 .. len)
634 override @property size_t talign() nothrow pure const
639 version (X86_64) override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
641 arg1 = typeid(void*);
646 class TypeInfo_AssociativeArray : TypeInfo
648 override string toString() const
650 return value.toString() ~ "[" ~ key.toString() ~ "]";
653 override bool opEquals(Object o)
657 auto c = cast(const TypeInfo_AssociativeArray)o;
658 return c && this.key == c.key &&
659 this.value == c.value;
662 override bool equals(in void* p1, in void* p2) @trusted const
664 return !!_aaEqual(this, *cast(const AA*) p1, *cast(const AA*) p2);
667 override hash_t getHash(scope const void* p) nothrow @trusted const
669 return _aaGetHash(cast(AA*)p, this);
672 // BUG: need to add the rest of the functions
674 override @property size_t tsize() nothrow pure const
676 return (char[int]).sizeof;
679 override const(void)[] initializer() const @trusted
681 return (cast(void *)null)[0 .. (char[int]).sizeof];
684 override @property inout(TypeInfo) next() nothrow pure inout { return value; }
685 override @property uint flags() nothrow pure const { return 1; }
690 override @property size_t talign() nothrow pure const
692 return (char[int]).alignof;
695 version (X86_64) override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
697 arg1 = typeid(void*);
702 class TypeInfo_Vector : TypeInfo
704 override string toString() const { return "__vector(" ~ base.toString() ~ ")"; }
706 override bool opEquals(Object o)
710 auto c = cast(const TypeInfo_Vector)o;
711 return c && this.base == c.base;
714 override size_t getHash(scope const void* p) const { return base.getHash(p); }
715 override bool equals(in void* p1, in void* p2) const { return base.equals(p1, p2); }
716 override int compare(in void* p1, in void* p2) const { return base.compare(p1, p2); }
717 override @property size_t tsize() nothrow pure const { return base.tsize; }
718 override void swap(void* p1, void* p2) const { return base.swap(p1, p2); }
720 override @property inout(TypeInfo) next() nothrow pure inout { return base.next; }
721 override @property uint flags() nothrow pure const { return base.flags; }
723 override const(void)[] initializer() nothrow pure const
725 return base.initializer();
728 override @property size_t talign() nothrow pure const { return 16; }
730 version (X86_64) override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
732 return base.argTypes(arg1, arg2);
738 class TypeInfo_Function : TypeInfo
740 override string toString() const
742 import core.demangle : demangleType;
744 alias SafeDemangleFunctionType = char[] function (const(char)[] buf, char[] dst = null) @safe nothrow pure;
745 SafeDemangleFunctionType demangle = ( () @trusted => cast(SafeDemangleFunctionType)(&demangleType) ) ();
747 return (() @trusted => cast(string)(demangle(deco))) ();
750 override bool opEquals(Object o)
754 auto c = cast(const TypeInfo_Function)o;
755 return c && this.deco == c.deco;
758 // BUG: need to add the rest of the functions
760 override @property size_t tsize() nothrow pure const
762 return 0; // no size for functions
765 override const(void)[] initializer() const @safe
773 * Mangled function type string
784 int func(int a, int b);
787 alias functionTypes = typeof(__traits(getVirtualFunctions, C, "func"));
788 assert(typeid(functionTypes[0]).toString() == "void function()");
789 assert(typeid(functionTypes[1]).toString() == "void function(int)");
790 assert(typeid(functionTypes[2]).toString() == "int function(int, int)");
793 class TypeInfo_Delegate : TypeInfo
795 override string toString() const
797 return cast(string)(next.toString() ~ " delegate()");
800 override bool opEquals(Object o)
804 auto c = cast(const TypeInfo_Delegate)o;
805 return c && this.deco == c.deco;
808 override size_t getHash(scope const void* p) @trusted const
810 return hashOf(*cast(void delegate()*)p);
813 override bool equals(in void* p1, in void* p2) const
815 auto dg1 = *cast(void delegate()*)p1;
816 auto dg2 = *cast(void delegate()*)p2;
820 override int compare(in void* p1, in void* p2) const
822 auto dg1 = *cast(void delegate()*)p1;
823 auto dg2 = *cast(void delegate()*)p2;
833 override @property size_t tsize() nothrow pure const
835 alias dg = int delegate();
839 override const(void)[] initializer() const @trusted
841 return (cast(void *)null)[0 .. (int delegate()).sizeof];
844 override @property uint flags() nothrow pure const { return 1; }
849 override @property size_t talign() nothrow pure const
851 alias dg = int delegate();
855 version (X86_64) override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
857 arg1 = typeid(void*);
858 arg2 = typeid(void*);
864 * Runtime type information about a class.
865 * Can be retrieved from an object instance by using the
866 * $(DDSUBLINK spec/property,classinfo, .classinfo) property.
868 class TypeInfo_Class : TypeInfo
870 override string toString() const { return info.name; }
872 override bool opEquals(Object o)
876 auto c = cast(const TypeInfo_Class)o;
877 return c && this.info.name == c.info.name;
880 override size_t getHash(scope const void* p) @trusted const
882 auto o = *cast(Object*)p;
883 return o ? o.toHash() : 0;
886 override bool equals(in void* p1, in void* p2) const
888 Object o1 = *cast(Object*)p1;
889 Object o2 = *cast(Object*)p2;
891 return (o1 is o2) || (o1 && o1.opEquals(o2));
894 override int compare(in void* p1, in void* p2) const
896 Object o1 = *cast(Object*)p1;
897 Object o2 = *cast(Object*)p2;
900 // Regard null references as always being "less than"
916 override @property size_t tsize() nothrow pure const
918 return Object.sizeof;
921 override const(void)[] initializer() nothrow pure const @safe
926 override @property uint flags() nothrow pure const { return 1; }
928 override @property const(OffsetTypeInfo)[] offTi() nothrow pure const
933 @property auto info() @safe nothrow pure const { return this; }
934 @property auto typeinfo() @safe nothrow pure const { return this; }
936 byte[] m_init; /** class static initializer
937 * (init.length gives size in bytes of class)
939 string name; /// class name
940 void*[] vtbl; /// virtual function pointer table
941 Interface[] interfaces; /// interfaces this class implements
942 TypeInfo_Class base; /// base class
944 void function(Object) classInvariant;
945 enum ClassFlags : uint
951 hasGetMembers = 0x10,
959 OffsetTypeInfo[] m_offTi;
960 void function(Object) defaultConstructor; // default Constructor
962 immutable(void)* m_RTInfo; // data for precise GC
963 override @property immutable(void)* rtInfo() const { return m_RTInfo; }
966 * Search all modules for TypeInfo_Class corresponding to classname.
967 * Returns: null if not found
969 static const(TypeInfo_Class) find(in char[] classname)
971 foreach (m; ModuleInfo)
975 //writefln("module %s, %d", m.name, m.localClasses.length);
976 foreach (c; m.localClasses)
980 //writefln("\tclass %s", c.name);
981 if (c.name == classname)
990 * Create instance of Object represented by 'this'.
992 Object create() const
994 if (m_flags & 8 && !defaultConstructor)
996 if (m_flags & 64) // abstract
998 Object o = _d_newclass(this);
999 if (m_flags & 8 && defaultConstructor)
1001 defaultConstructor(o);
1007 alias ClassInfo = TypeInfo_Class;
1017 assert(typeid(X).initializer is typeid(X).m_init);
1018 assert(typeid(X).initializer.length == typeid(const(X)).initializer.length);
1019 assert(typeid(X).initializer.length == typeid(shared(X)).initializer.length);
1020 assert(typeid(X).initializer.length == typeid(immutable(X)).initializer.length);
1023 class TypeInfo_Interface : TypeInfo
1025 override string toString() const { return info.name; }
1027 override bool opEquals(Object o)
1031 auto c = cast(const TypeInfo_Interface)o;
1032 return c && this.info.name == typeid(c).name;
1035 override size_t getHash(scope const void* p) @trusted const
1037 if (!*cast(void**)p)
1041 Interface* pi = **cast(Interface ***)*cast(void**)p;
1042 Object o = cast(Object)(*cast(void**)p - pi.offset);
1047 override bool equals(in void* p1, in void* p2) const
1049 Interface* pi = **cast(Interface ***)*cast(void**)p1;
1050 Object o1 = cast(Object)(*cast(void**)p1 - pi.offset);
1051 pi = **cast(Interface ***)*cast(void**)p2;
1052 Object o2 = cast(Object)(*cast(void**)p2 - pi.offset);
1054 return o1 == o2 || (o1 && o1.opCmp(o2) == 0);
1057 override int compare(in void* p1, in void* p2) const
1059 Interface* pi = **cast(Interface ***)*cast(void**)p1;
1060 Object o1 = cast(Object)(*cast(void**)p1 - pi.offset);
1061 pi = **cast(Interface ***)*cast(void**)p2;
1062 Object o2 = cast(Object)(*cast(void**)p2 - pi.offset);
1065 // Regard null references as always being "less than"
1081 override @property size_t tsize() nothrow pure const
1083 return Object.sizeof;
1086 override const(void)[] initializer() const @trusted
1088 return (cast(void *)null)[0 .. Object.sizeof];
1091 override @property uint flags() nothrow pure const { return 1; }
1093 TypeInfo_Class info;
1096 class TypeInfo_Struct : TypeInfo
1098 override string toString() const { return name; }
1100 override bool opEquals(Object o)
1104 auto s = cast(const TypeInfo_Struct)o;
1105 return s && this.name == s.name &&
1106 this.initializer().length == s.initializer().length;
1109 override size_t getHash(scope const void* p) @trusted pure nothrow const
1114 return (*xtoHash)(p);
1118 return hashOf(p[0 .. initializer().length]);
1122 override bool equals(in void* p1, in void* p2) @trusted pure nothrow const
1124 import core.stdc.string : memcmp;
1131 { // BUG: GDC and DMD use different calling conventions
1132 return (*xopEquals)(p2, p1);
1135 return (*xopEquals)(p1, p2);
1140 // BUG: relies on the GC not moving objects
1141 return memcmp(p1, p2, initializer().length) == 0;
1144 override int compare(in void* p1, in void* p2) @trusted pure nothrow const
1146 import core.stdc.string : memcmp;
1148 // Regard null references as always being "less than"
1158 { // BUG: GDC and DMD use different calling conventions
1159 return (*xopCmp)(p1, p2);
1162 return (*xopCmp)(p2, p1);
1165 // BUG: relies on the GC not moving objects
1166 return memcmp(p1, p2, initializer().length);
1174 override @property size_t tsize() nothrow pure const
1176 return initializer().length;
1179 override const(void)[] initializer() nothrow pure const @safe
1184 override @property uint flags() nothrow pure const { return m_flags; }
1186 override @property size_t talign() nothrow pure const { return m_align; }
1188 final override void destroy(void* p) const
1192 if (m_flags & StructFlags.isDynamicType)
1193 (*xdtorti)(p, this);
1199 override void postblit(void* p) const
1206 void[] m_init; // initializer; m_init.ptr == null if 0 initialize
1210 size_t function(in void*) xtoHash;
1211 bool function(in void*, in void*) xopEquals;
1212 int function(in void*, in void*) xopCmp;
1213 string function(in void*) xtoString;
1215 enum StructFlags : uint
1218 isDynamicType = 0x2, // built at runtime, needs type info in xdtor
1220 StructFlags m_flags;
1224 void function(void*) xdtor;
1225 void function(void*, const TypeInfo_Struct ti) xdtorti;
1227 void function(void*) xpostblit;
1231 override @property immutable(void)* rtInfo() const { return m_RTInfo; }
1235 override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
1244 immutable(void)* m_RTInfo; // data for precise GC
1251 bool opEquals(ref const S rhs) const
1257 assert(!typeid(S).equals(&s, &s));
1260 class TypeInfo_Tuple : TypeInfo
1262 TypeInfo[] elements;
1264 override string toString() const
1267 foreach (i, element; elements)
1271 s ~= element.toString();
1277 override bool opEquals(Object o)
1282 auto t = cast(const TypeInfo_Tuple)o;
1283 if (t && elements.length == t.elements.length)
1285 for (size_t i = 0; i < elements.length; i++)
1287 if (elements[i] != t.elements[i])
1295 override size_t getHash(scope const void* p) const
1300 override bool equals(in void* p1, in void* p2) const
1305 override int compare(in void* p1, in void* p2) const
1310 override @property size_t tsize() nothrow pure const
1315 override const(void)[] initializer() const @trusted
1320 override void swap(void* p1, void* p2) const
1325 override void destroy(void* p) const
1330 override void postblit(void* p) const
1335 override @property size_t talign() nothrow pure const
1340 version (X86_64) override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
1346 class TypeInfo_Const : TypeInfo
1348 override string toString() const
1350 return cast(string) ("const(" ~ base.toString() ~ ")");
1353 //override bool opEquals(Object o) { return base.opEquals(o); }
1354 override bool opEquals(Object o)
1359 if (typeid(this) != typeid(o))
1362 auto t = cast(TypeInfo_Const)o;
1363 return base.opEquals(t.base);
1366 override size_t getHash(scope const void *p) const { return base.getHash(p); }
1367 override bool equals(in void *p1, in void *p2) const { return base.equals(p1, p2); }
1368 override int compare(in void *p1, in void *p2) const { return base.compare(p1, p2); }
1369 override @property size_t tsize() nothrow pure const { return base.tsize; }
1370 override void swap(void *p1, void *p2) const { return base.swap(p1, p2); }
1372 override @property inout(TypeInfo) next() nothrow pure inout { return base.next; }
1373 override @property uint flags() nothrow pure const { return base.flags; }
1375 override const(void)[] initializer() nothrow pure const
1377 return base.initializer();
1380 override @property size_t talign() nothrow pure const { return base.talign; }
1382 version (X86_64) override int argTypes(out TypeInfo arg1, out TypeInfo arg2)
1384 return base.argTypes(arg1, arg2);
1390 class TypeInfo_Invariant : TypeInfo_Const
1392 override string toString() const
1394 return cast(string) ("immutable(" ~ base.toString() ~ ")");
1398 class TypeInfo_Shared : TypeInfo_Const
1400 override string toString() const
1402 return cast(string) ("shared(" ~ base.toString() ~ ")");
1406 class TypeInfo_Inout : TypeInfo_Const
1408 override string toString() const
1410 return cast(string) ("inout(" ~ base.toString() ~ ")");
1415 ///////////////////////////////////////////////////////////////////////////////
1417 ///////////////////////////////////////////////////////////////////////////////
1422 MIctorstart = 0x1, // we've started constructing it
1423 MIctordone = 0x2, // finished construction
1424 MIstandalone = 0x4, // module ctor does not depend on other module
1425 // ctors being done first
1430 MIxgetMembers = 0x80,
1433 MIimportedModules = 0x400,
1434 MIlocalClasses = 0x800,
1442 uint _index; // index into _moduleinfo_array[]
1446 deprecated("ModuleInfo cannot be copy-assigned because it is a variable-sized struct.")
1447 void opAssign(in ModuleInfo m) { _flags = m._flags; _index = m._index; }
1452 @disable this(this) const;
1456 private void* addrOf(int flag) nothrow pure @nogc
1459 assert(flag >= MItlsctor && flag <= MIname);
1460 assert(!(flag & (flag - 1)) && !(flag & ~(flag - 1) << 1));
1464 import core.stdc.string : strlen;
1466 void* p = cast(void*)&this + ModuleInfo.sizeof;
1468 if (flags & MItlsctor)
1470 if (flag == MItlsctor) return p;
1471 p += typeof(tlsctor).sizeof;
1473 if (flags & MItlsdtor)
1475 if (flag == MItlsdtor) return p;
1476 p += typeof(tlsdtor).sizeof;
1480 if (flag == MIctor) return p;
1481 p += typeof(ctor).sizeof;
1485 if (flag == MIdtor) return p;
1486 p += typeof(dtor).sizeof;
1488 if (flags & MIxgetMembers)
1490 if (flag == MIxgetMembers) return p;
1491 p += typeof(xgetMembers).sizeof;
1493 if (flags & MIictor)
1495 if (flag == MIictor) return p;
1496 p += typeof(ictor).sizeof;
1498 if (flags & MIunitTest)
1500 if (flag == MIunitTest) return p;
1501 p += typeof(unitTest).sizeof;
1503 if (flags & MIimportedModules)
1505 if (flag == MIimportedModules) return p;
1506 p += size_t.sizeof + *cast(size_t*)p * typeof(importedModules[0]).sizeof;
1508 if (flags & MIlocalClasses)
1510 if (flag == MIlocalClasses) return p;
1511 p += size_t.sizeof + *cast(size_t*)p * typeof(localClasses[0]).sizeof;
1513 if (true || flags & MIname) // always available for now
1515 if (flag == MIname) return p;
1516 p += strlen(cast(immutable char*)p);
1521 @property uint index() nothrow pure @nogc { return _index; }
1523 @property uint flags() nothrow pure @nogc { return _flags; }
1525 @property void function() tlsctor() nothrow pure @nogc
1527 return flags & MItlsctor ? *cast(typeof(return)*)addrOf(MItlsctor) : null;
1530 @property void function() tlsdtor() nothrow pure @nogc
1532 return flags & MItlsdtor ? *cast(typeof(return)*)addrOf(MItlsdtor) : null;
1535 @property void* xgetMembers() nothrow pure @nogc
1537 return flags & MIxgetMembers ? *cast(typeof(return)*)addrOf(MIxgetMembers) : null;
1540 @property void function() ctor() nothrow pure @nogc
1542 return flags & MIctor ? *cast(typeof(return)*)addrOf(MIctor) : null;
1545 @property void function() dtor() nothrow pure @nogc
1547 return flags & MIdtor ? *cast(typeof(return)*)addrOf(MIdtor) : null;
1550 @property void function() ictor() nothrow pure @nogc
1552 return flags & MIictor ? *cast(typeof(return)*)addrOf(MIictor) : null;
1555 @property void function() unitTest() nothrow pure @nogc
1557 return flags & MIunitTest ? *cast(typeof(return)*)addrOf(MIunitTest) : null;
1560 @property immutable(ModuleInfo*)[] importedModules() nothrow pure @nogc
1562 if (flags & MIimportedModules)
1564 auto p = cast(size_t*)addrOf(MIimportedModules);
1565 return (cast(immutable(ModuleInfo*)*)(p + 1))[0 .. *p];
1570 @property TypeInfo_Class[] localClasses() nothrow pure @nogc
1572 if (flags & MIlocalClasses)
1574 auto p = cast(size_t*)addrOf(MIlocalClasses);
1575 return (cast(TypeInfo_Class*)(p + 1))[0 .. *p];
1580 @property string name() nothrow pure @nogc
1582 if (true || flags & MIname) // always available for now
1584 import core.stdc.string : strlen;
1586 auto p = cast(immutable char*)addrOf(MIname);
1587 return p[0 .. strlen(p)];
1592 static int opApply(scope int delegate(ModuleInfo*) dg)
1594 import core.internal.traits : externDFunc;
1595 alias moduleinfos_apply = externDFunc!("rt.minfo.moduleinfos_apply",
1596 int function(scope int delegate(immutable(ModuleInfo*))));
1597 // Bugzilla 13084 - enforcing immutable ModuleInfo would break client code
1598 return moduleinfos_apply(
1599 (immutable(ModuleInfo*)m) => dg(cast(ModuleInfo*)m));
1606 foreach (m; ModuleInfo)
1612 ///////////////////////////////////////////////////////////////////////////////
1614 ///////////////////////////////////////////////////////////////////////////////
1618 * The base class of all thrown objects.
1620 * All thrown objects must inherit from Throwable. Class $(D Exception), which
1621 * derives from this class, represents the category of thrown objects that are
1622 * safe to catch and handle. In principle, one should not catch Throwable
1623 * objects that are not derived from $(D Exception), as they represent
1624 * unrecoverable runtime errors. Certain runtime guarantees may fail to hold
1625 * when these errors are thrown, making it unsafe to continue execution after
1628 class Throwable : Object
1632 int opApply(scope int delegate(ref const(char[]))) const;
1633 int opApply(scope int delegate(ref size_t, ref const(char[]))) const;
1634 string toString() const;
1637 string msg; /// A message describing the error.
1640 * The _file name of the D source code corresponding with
1641 * where the error was thrown from.
1645 * The _line number of the D source code corresponding with
1646 * where the error was thrown from.
1651 * The stack trace of where the error happened. This is an opaque object
1652 * that can either be converted to $(D string), or iterated over with $(D
1653 * foreach) to extract the items in the stack trace (as strings).
1658 * A reference to the _next error in the list. This is used when a new
1659 * $(D Throwable) is thrown from inside a $(D catch) block. The originally
1660 * caught $(D Exception) will be chained to the new $(D Throwable) via this
1665 @nogc @safe pure nothrow this(string msg, Throwable next = null)
1669 //this.info = _d_traceContext();
1672 @nogc @safe pure nothrow this(string msg, string file, size_t line, Throwable next = null)
1677 //this.info = _d_traceContext();
1681 * Overrides $(D Object.toString) and returns the error message.
1682 * Internally this forwards to the $(D toString) overload that
1683 * takes a $(D_PARAM sink) delegate.
1685 override string toString()
1688 toString((buf) { s ~= buf; });
1693 * The Throwable hierarchy uses a toString overload that takes a
1694 * $(D_PARAM _sink) delegate to avoid GC allocations, which cannot be
1695 * performed in certain error situations. Override this $(D
1696 * toString) method to customize the error message.
1698 void toString(scope void delegate(in char[]) sink) const
1700 import core.internal.traits : externDFunc;
1701 alias sizeToTempString = externDFunc!("core.internal.string.unsignedToTempString",
1702 char[] function(ulong, return char[], uint) @safe pure nothrow @nogc);
1704 char[20] tmpBuff = void;
1706 sink(typeid(this).name);
1707 sink("@"); sink(file);
1708 sink("("); sink(sizeToTempString(line, tmpBuff, 10)); sink(")");
1712 sink(": "); sink(msg);
1718 sink("\n----------------");
1721 sink("\n"); sink(t);
1726 // ignore more errors
1734 * The base class of all errors that are safe to catch and handle.
1736 * In principle, only thrown objects derived from this class are safe to catch
1737 * inside a $(D catch) block. Thrown objects not derived from Exception
1738 * represent runtime errors that should not be caught, as certain runtime
1739 * guarantees may not hold, making it unsafe to continue program execution.
1741 class Exception : Throwable
1745 * Creates a new instance of Exception. The next parameter is used
1746 * internally and should always be $(D null) when passed by user code.
1747 * This constructor does not automatically throw the newly-created
1748 * Exception; the $(D throw) statement should be used for that purpose.
1750 @nogc @safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
1752 super(msg, file, line, next);
1755 @nogc @safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
1757 super(msg, file, line, next);
1764 auto e = new Exception("msg");
1765 assert(e.file == __FILE__);
1766 assert(e.line == __LINE__ - 2);
1767 assert(e.next is null);
1768 assert(e.msg == "msg");
1772 auto e = new Exception("msg", new Exception("It's an Exception!"), "hello", 42);
1773 assert(e.file == "hello");
1774 assert(e.line == 42);
1775 assert(e.next !is null);
1776 assert(e.msg == "msg");
1780 auto e = new Exception("msg", "hello", 42, new Exception("It's an Exception!"));
1781 assert(e.file == "hello");
1782 assert(e.line == 42);
1783 assert(e.next !is null);
1784 assert(e.msg == "msg");
1790 * The base class of all unrecoverable runtime errors.
1792 * This represents the category of $(D Throwable) objects that are $(B not)
1793 * safe to catch and handle. In principle, one should not catch Error
1794 * objects, as they represent unrecoverable runtime errors.
1795 * Certain runtime guarantees may fail to hold when these errors are
1796 * thrown, making it unsafe to continue execution after catching them.
1798 class Error : Throwable
1801 * Creates a new instance of Error. The next parameter is used
1802 * internally and should always be $(D null) when passed by user code.
1803 * This constructor does not automatically throw the newly-created
1804 * Error; the $(D throw) statement should be used for that purpose.
1806 @nogc @safe pure nothrow this(string msg, Throwable next = null)
1809 bypassedException = null;
1812 @nogc @safe pure nothrow this(string msg, string file, size_t line, Throwable next = null)
1814 super(msg, file, line, next);
1815 bypassedException = null;
1818 /** The first $(D Exception) which was bypassed when this Error was thrown,
1819 or $(D null) if no $(D Exception)s were pending. */
1820 Throwable bypassedException;
1826 auto e = new Error("msg");
1827 assert(e.file is null);
1828 assert(e.line == 0);
1829 assert(e.next is null);
1830 assert(e.msg == "msg");
1831 assert(e.bypassedException is null);
1835 auto e = new Error("msg", new Exception("It's an Exception!"));
1836 assert(e.file is null);
1837 assert(e.line == 0);
1838 assert(e.next !is null);
1839 assert(e.msg == "msg");
1840 assert(e.bypassedException is null);
1844 auto e = new Error("msg", "hello", 42, new Exception("It's an Exception!"));
1845 assert(e.file == "hello");
1846 assert(e.line == 42);
1847 assert(e.next !is null);
1848 assert(e.msg == "msg");
1849 assert(e.bypassedException is null);
1853 /* Used in Exception Handling LSDA tables to 'wrap' C++ type info
1854 * so it can be distinguished from D TypeInfo
1856 class __cpp_type_info_ptr
1858 void* ptr; // opaque pointer to C++ RTTI type info
1863 // from druntime/src/rt/aaA.d
1865 private struct AA { void* impl; }
1866 // size_t _aaLen(in AA aa) pure nothrow @nogc;
1867 private void* _aaGetY(AA* paa, const TypeInfo_AssociativeArray ti, in size_t valsz, in void* pkey) pure nothrow;
1868 private void* _aaGetX(AA* paa, const TypeInfo_AssociativeArray ti, in size_t valsz, in void* pkey, out bool found) pure nothrow;
1869 // inout(void)* _aaGetRvalueX(inout AA aa, in TypeInfo keyti, in size_t valsz, in void* pkey);
1870 inout(void[]) _aaValues(inout AA aa, in size_t keysz, in size_t valsz, const TypeInfo tiValueArray) pure nothrow;
1871 inout(void[]) _aaKeys(inout AA aa, in size_t keysz, const TypeInfo tiKeyArray) pure nothrow;
1872 void* _aaRehash(AA* paa, in TypeInfo keyti) pure nothrow;
1873 void _aaClear(AA aa) pure nothrow;
1875 // alias _dg_t = extern(D) int delegate(void*);
1876 // int _aaApply(AA aa, size_t keysize, _dg_t dg);
1878 // alias _dg2_t = extern(D) int delegate(void*, void*);
1879 // int _aaApply2(AA aa, size_t keysize, _dg2_t dg);
1881 private struct AARange { AA impl; size_t idx; }
1882 AARange _aaRange(AA aa) pure nothrow @nogc @safe;
1883 bool _aaRangeEmpty(AARange r) pure nothrow @nogc @safe;
1884 void* _aaRangeFrontKey(AARange r) pure nothrow @nogc @safe;
1885 void* _aaRangeFrontValue(AARange r) pure nothrow @nogc @safe;
1886 void _aaRangePopFront(ref AARange r) pure nothrow @nogc @safe;
1888 int _aaEqual(in TypeInfo tiRaw, in AA aa1, in AA aa2);
1889 hash_t _aaGetHash(in AA* aa, in TypeInfo tiRaw) nothrow;
1892 _d_assocarrayliteralTX marked as pure, because aaLiteral can be called from pure code.
1893 This is a typesystem hole, however this is existing hole.
1894 Early compiler didn't check purity of toHash or postblit functions, if key is a UDT thus
1895 copiler allowed to create AA literal with keys, which have impure unsafe toHash methods.
1897 void* _d_assocarrayliteralTX(const TypeInfo_AssociativeArray ti, void[] keys, void[] values) pure;
1900 void* aaLiteral(Key, Value)(Key[] keys, Value[] values) @trusted pure
1902 return _d_assocarrayliteralTX(typeid(Value[Key]), *cast(void[]*)&keys, *cast(void[]*)&values);
1905 alias AssociativeArray(Key, Value) = Value[Key];
1907 /***********************************
1908 * Removes all remaining keys and values from an associative array.
1910 * aa = The associative array.
1912 void clear(T : Value[Key], Value, Key)(T aa)
1914 _aaClear(*cast(AA *) &aa);
1918 void clear(T : Value[Key], Value, Key)(T* aa)
1920 _aaClear(*cast(AA *) aa);
1923 /***********************************
1924 * Reorganizes the associative array in place so that lookups are more
1927 * aa = The associative array.
1929 * The rehashed associative array.
1931 T rehash(T : Value[Key], Value, Key)(T aa)
1933 _aaRehash(cast(AA*)&aa, typeid(Value[Key]));
1938 T rehash(T : Value[Key], Value, Key)(T* aa)
1940 _aaRehash(cast(AA*)aa, typeid(Value[Key]));
1945 T rehash(T : shared Value[Key], Value, Key)(T aa)
1947 _aaRehash(cast(AA*)&aa, typeid(Value[Key]));
1952 T rehash(T : shared Value[Key], Value, Key)(T* aa)
1954 _aaRehash(cast(AA*)aa, typeid(Value[Key]));
1958 /***********************************
1959 * Create a new associative array of the same size and copy the contents of the
1960 * associative array into it.
1962 * aa = The associative array.
1964 V[K] dup(T : V[K], K, V)(T aa)
1966 //pragma(msg, "K = ", K, ", V = ", V);
1968 // Bug10720 - check whether V is copyable
1969 static assert(is(typeof({ V v = aa[K.init]; })),
1970 "cannot call " ~ T.stringof ~ ".dup because " ~ V.stringof ~ " is not copyable");
1974 //foreach (k, ref v; aa)
1975 // result[k] = v; // Bug13701 - won't work if V is not mutable
1977 ref V duplicateElem(ref K k, ref const V v) @trusted pure nothrow
1979 import core.stdc.string : memcpy;
1981 void* pv = _aaGetY(cast(AA*)&result, typeid(V[K]), V.sizeof, &k);
1982 memcpy(pv, &v, V.sizeof);
1986 if (auto postblit = _getPostblit!V())
1988 foreach (k, ref v; aa)
1989 postblit(duplicateElem(k, v));
1993 foreach (k, ref v; aa)
1994 duplicateElem(k, v);
2001 V[K] dup(T : V[K], K, V)(T* aa)
2006 // this should never be made public.
2007 private AARange _aaToRange(T: V[K], K, V)(ref T aa) pure nothrow @nogc @safe
2009 // ensure we are dealing with a genuine AA.
2010 static if (is(const(V[K]) == const(T)))
2013 const(V[K]) realAA = aa;
2014 return _aaRange(() @trusted { return *cast(AA*)&realAA; } ());
2017 /***********************************
2018 * Returns a forward range over the keys of the associative array.
2020 * aa = The associative array.
2024 auto byKey(T : V[K], K, V)(T aa) pure nothrow @nogc @safe
2026 import core.internal.traits : substInout;
2028 static struct Result
2033 @property bool empty() @safe { return _aaRangeEmpty(r); }
2034 @property ref front()
2036 auto p = (() @trusted => cast(substInout!K*) _aaRangeFrontKey(r)) ();
2039 void popFront() @safe { _aaRangePopFront(r); }
2040 @property Result save() { return this; }
2043 return Result(_aaToRange(aa));
2047 auto byKey(T : V[K], K, V)(T* aa) pure nothrow @nogc
2049 return (*aa).byKey();
2052 /***********************************
2053 * Returns a forward range over the values of the associative array.
2055 * aa = The associative array.
2059 auto byValue(T : V[K], K, V)(T aa) pure nothrow @nogc @safe
2061 import core.internal.traits : substInout;
2063 static struct Result
2068 @property bool empty() @safe { return _aaRangeEmpty(r); }
2069 @property ref front()
2071 auto p = (() @trusted => cast(substInout!V*) _aaRangeFrontValue(r)) ();
2074 void popFront() @safe { _aaRangePopFront(r); }
2075 @property Result save() { return this; }
2078 return Result(_aaToRange(aa));
2082 auto byValue(T : V[K], K, V)(T* aa) pure nothrow @nogc
2084 return (*aa).byValue();
2087 /***********************************
2088 * Returns a forward range over the key value pairs of the associative array.
2090 * aa = The associative array.
2094 auto byKeyValue(T : V[K], K, V)(T aa) pure nothrow @nogc @safe
2096 import core.internal.traits : substInout;
2098 static struct Result
2103 @property bool empty() @safe { return _aaRangeEmpty(r); }
2104 @property auto front()
2108 // We save the pointers here so that the Pair we return
2109 // won't mutate when Result.popFront is called afterwards.
2113 @property ref key() inout
2115 auto p = (() @trusted => cast(substInout!K*) keyp) ();
2118 @property ref value() inout
2120 auto p = (() @trusted => cast(substInout!V*) valp) ();
2124 return Pair(_aaRangeFrontKey(r),
2125 _aaRangeFrontValue(r));
2127 void popFront() @safe { return _aaRangePopFront(r); }
2128 @property Result save() { return this; }
2131 return Result(_aaToRange(aa));
2135 auto byKeyValue(T : V[K], K, V)(T* aa) pure nothrow @nogc
2137 return (*aa).byKeyValue();
2140 /***********************************
2141 * Returns a dynamic array, the elements of which are the keys in the
2142 * associative array.
2144 * aa = The associative array.
2148 Key[] keys(T : Value[Key], Value, Key)(T aa) @property
2150 // ensure we are dealing with a genuine AA.
2151 static if (is(const(Value[Key]) == const(T)))
2154 const(Value[Key]) realAA = aa;
2155 auto a = cast(void[])_aaKeys(*cast(inout(AA)*)&realAA, Key.sizeof, typeid(Key[]));
2156 auto res = *cast(Key[]*)&a;
2162 Key[] keys(T : Value[Key], Value, Key)(T *aa) @property
2172 void[][string] dict;
2177 assert(s.keys.length == 0);
2180 /***********************************
2181 * Returns a dynamic array, the elements of which are the values in the
2182 * associative array.
2184 * aa = The associative array.
2188 Value[] values(T : Value[Key], Value, Key)(T aa) @property
2190 // ensure we are dealing with a genuine AA.
2191 static if (is(const(Value[Key]) == const(T)))
2194 const(Value[Key]) realAA = aa;
2195 auto a = cast(void[])_aaValues(*cast(inout(AA)*)&realAA, Key.sizeof, Value.sizeof, typeid(Value[]));
2196 auto res = *cast(Value[]*)&a;
2202 Value[] values(T : Value[Key], Value, Key)(T *aa) @property
2204 return (*aa).values;
2212 void[][string] dict;
2217 assert(s.values.length == 0);
2220 /***********************************
2221 * Looks up key; if it exists returns corresponding value else evaluates and
2222 * returns defaultValue.
2224 * aa = The associative array.
2226 * defaultValue = The default value.
2230 inout(V) get(K, V)(inout(V[K]) aa, K key, lazy inout(V) defaultValue)
2233 return p ? *p : defaultValue;
2237 inout(V) get(K, V)(inout(V[K])* aa, K key, lazy inout(V) defaultValue)
2239 return (*aa).get(key, defaultValue);
2242 /***********************************
2243 * Looks up key; if it exists returns corresponding value else evaluates
2244 * value, adds it to the associative array and returns it.
2246 * aa = The associative array.
2248 * value = The required value.
2252 ref V require(K, V)(ref V[K] aa, K key, lazy V value = V.init)
2255 // if key is @safe-ly copyable, `require` can infer @safe
2256 static if (isSafeCopyable!K)
2258 auto p = () @trusted
2260 return cast(V*) _aaGetX(cast(AA*) &aa, typeid(V[K]), V.sizeof, &key, found);
2265 auto p = cast(V*) _aaGetX(cast(AA*) &aa, typeid(V[K]), V.sizeof, &key, found);
2267 return found ? *p : (*p = value);
2270 // Constraints for aa update. Delegates, Functions or Functors (classes that
2271 // provide opCall) are allowed. See unittest for an example.
2274 template isCreateOperation(C, V)
2276 static if (is(C : V delegate()) || is(C : V function()))
2277 enum bool isCreateOperation = true;
2278 else static if (isCreateOperation!(typeof(&C.opCall), V))
2279 enum bool isCreateOperation = true;
2281 enum bool isCreateOperation = false;
2284 template isUpdateOperation(U, V)
2286 static if (is(U : V delegate(ref V)) || is(U : V function(ref V)))
2287 enum bool isUpdateOperation = true;
2288 else static if (isUpdateOperation!(typeof(&U.opCall), V))
2289 enum bool isUpdateOperation = true;
2291 enum bool isUpdateOperation = false;
2295 // Tests whether T can be @safe-ly copied. Use a union to exclude destructor from the test.
2296 private enum bool isSafeCopyable(T) = is(typeof(() @safe { union U { T x; } T *x; auto u = U(*x); }));
2298 /***********************************
2299 * Looks up key; if it exists applies the update delegate else evaluates the
2300 * create delegate and adds it to the associative array
2302 * aa = The associative array.
2304 * create = The delegate to apply on create.
2305 * update = The delegate to apply on update.
2307 void update(K, V, C, U)(ref V[K] aa, K key, scope C create, scope U update)
2308 if (isCreateOperation!(C, V) && isUpdateOperation!(U, V))
2311 // if key is @safe-ly copyable, `update` may infer @safe
2312 static if (isSafeCopyable!K)
2314 auto p = () @trusted
2316 return cast(V*) _aaGetX(cast(AA*) &aa, typeid(V[K]), V.sizeof, &key, found);
2321 auto p = cast(V*) _aaGetX(cast(AA*) &aa, typeid(V[K]), V.sizeof, &key, found);
2335 this(this) @system {}
2339 bool opEquals(S rhs) { assert(0); }
2340 size_t toHash() { assert(0); }
2344 static assert(is(typeof(() @safe { aai.require("a", 1234); })));
2345 static assert(is(typeof(() @safe { aai.update("a", { return 1234; }, (ref int x) { x++; return x; }); })));
2348 static assert(is(typeof(() { aas.require("a", S(1234)); })));
2349 static assert(is(typeof(() { aas.update("a", { return S(1234); }, (ref S s) { s.x++; return s; }); })));
2350 static assert(!is(typeof(() @safe { aas.update("a", { return S(1234); }, (ref S s) { s.x++; return s; }); })));
2353 static assert(is(typeof(() { aais.require(S(1234), 1234); })));
2354 static assert(is(typeof(() { aais.update(S(1234), { return 1234; }, (ref int x) { x++; return x; }); })));
2355 static assert(!is(typeof(() @safe { aais.require(S(1234), 1234); })));
2356 static assert(!is(typeof(() @safe { aais.update(S(1234), { return 1234; }, (ref int x) { x++; return x; }); })));
2359 private void _destructRecurse(S)(ref S s)
2360 if (is(S == struct))
2362 static if (__traits(hasMember, S, "__xdtor") &&
2363 // Bugzilla 14746: Check that it's the exact member of S.
2364 __traits(isSame, S, __traits(parent, s.__xdtor)))
2368 private void _destructRecurse(E, size_t n)(ref E[n] arr)
2370 import core.internal.traits : hasElaborateDestructor;
2372 static if (hasElaborateDestructor!E)
2374 foreach_reverse (ref elem; arr)
2375 _destructRecurse(elem);
2379 // Public and explicitly undocumented
2380 void _postblitRecurse(S)(ref S s)
2381 if (is(S == struct))
2383 static if (__traits(hasMember, S, "__xpostblit") &&
2384 // Bugzilla 14746: Check that it's the exact member of S.
2385 __traits(isSame, S, __traits(parent, s.__xpostblit)))
2390 void _postblitRecurse(E, size_t n)(ref E[n] arr)
2392 import core.internal.traits : hasElaborateCopyConstructor;
2394 static if (hasElaborateCopyConstructor!E)
2401 _destructRecurse(arr[i - 1]); // What to do if this throws?
2405 for (i = 0; i < arr.length; ++i)
2406 _postblitRecurse(arr[i]);
2410 // Test destruction/postblit order
2411 @safe nothrow pure unittest
2417 ~this() @safe nothrow pure
2419 order ~= "destroy inner top";
2422 this(this) @safe nothrow pure
2424 order ~= "copy inner top";
2428 struct InnerMiddle {}
2430 version (none) // https://issues.dlang.org/show_bug.cgi?id=14242
2433 static char counter = '1';
2435 ~this() @safe nothrow pure
2437 order ~= "destroy inner element #" ~ counter++;
2440 this(this) @safe nothrow pure
2442 order ~= "copy inner element #" ~ counter++;
2448 ~this() @safe nothrow pure
2450 order ~= "destroy inner bottom";
2453 this(this) @safe nothrow pure
2455 order ~= "copy inner bottom";
2464 version (none) InnerElement[3] array; // https://issues.dlang.org/show_bug.cgi?id=14242
2467 ~this() @safe nothrow pure { order ~= "destroy outer"; }
2468 this(this) @safe nothrow pure { order ~= "copy outer"; }
2471 string[] destructRecurseOrder;
2474 _destructRecurse(s);
2475 destructRecurseOrder = order;
2479 assert(order.length);
2480 assert(destructRecurseOrder == order);
2484 _postblitRecurse(s);
2485 assert(order.length);
2486 auto postblitRecurseOrder = order;
2489 assert(order.length);
2490 assert(postblitRecurseOrder == order);
2493 // Test static struct
2494 nothrow @safe @nogc unittest
2497 static struct S { ~this() nothrow @safe @nogc { i = 42; } }
2499 _destructRecurse(s);
2506 static struct HasDtor
2508 ~this() { assert(0); }
2517 assert(o.ptr is null);
2518 destroy(o); // must not reach in HasDtor.__dtor()
2524 static struct HasPostblit
2526 this(this) { assert(0); }
2535 assert(o.ptr is null);
2536 _postblitRecurse(o); // must not reach in HasPostblit.__postblit()
2539 // Test handling of fixed-length arrays
2540 // Separate from first test because of https://issues.dlang.org/show_bug.cgi?id=14242
2551 order ~= "copy #" ~ id;
2556 order ~= "destroy #" ~ id;
2560 string[] destructRecurseOrder;
2562 S[3] arr = [S('1'), S('2'), S('3')];
2563 _destructRecurse(arr);
2564 destructRecurseOrder = order;
2567 assert(order.length);
2568 assert(destructRecurseOrder == order);
2571 S[3] arr = [S('1'), S('2'), S('3')];
2572 _postblitRecurse(arr);
2573 assert(order.length);
2574 auto postblitRecurseOrder = order;
2578 assert(order.length);
2579 assert(postblitRecurseOrder == order);
2582 // Test handling of failed postblit
2583 // Not nothrow or @safe because of https://issues.dlang.org/show_bug.cgi?id=14242
2584 /+ nothrow @safe +/ unittest
2586 static class FailedPostblitException : Exception { this() nothrow @safe { super(null); } }
2587 static string[] order;
2595 order ~= "copy inner #" ~ id;
2597 throw new FailedPostblitException();
2602 order ~= "destroy inner #" ~ id;
2608 Inner inner1, inner2, inner3;
2611 this(char first, char second, char third)
2613 inner1 = Inner(first);
2614 inner2 = Inner(second);
2615 inner3 = Inner(third);
2620 order ~= "copy outer";
2625 order ~= "destroy outer";
2629 auto outer = Outer('1', '2', '3');
2631 try _postblitRecurse(outer);
2632 catch (FailedPostblitException) {}
2633 catch (Exception) assert(false);
2635 auto postblitRecurseOrder = order;
2638 try auto copy = outer;
2639 catch (FailedPostblitException) {}
2640 catch (Exception) assert(false);
2642 assert(postblitRecurseOrder == order);
2645 Outer[3] arr = [Outer('1', '1', '1'), Outer('1', '2', '3'), Outer('3', '3', '3')];
2647 try _postblitRecurse(arr);
2648 catch (FailedPostblitException) {}
2649 catch (Exception) assert(false);
2651 postblitRecurseOrder = order;
2654 try auto arrCopy = arr;
2655 catch (FailedPostblitException) {}
2656 catch (Exception) assert(false);
2658 assert(postblitRecurseOrder == order);
2662 Destroys the given object and puts it in an invalid state. It's used to
2663 _destroy an object so that any cleanup which its destructor or finalizer
2664 does is done and so that it no longer references any other objects. It does
2665 $(I not) initiate a GC cycle or free any GC memory.
2667 void destroy(T)(T obj) if (is(T == class))
2669 rt_finalize(cast(void*)obj);
2673 void destroy(T)(T obj) if (is(T == interface))
2675 destroy(cast(Object)obj);
2678 version (unittest) unittest
2682 class A: I { string s = "A"; this() {} }
2683 auto a = new A, b = new A;
2693 static bool destroyed = false;
2703 auto a = new B, b = new B;
2715 // this test is invalid now that the default ctor is not run after clearing
2734 void destroy(T)(ref T obj) if (is(T == struct))
2736 _destructRecurse(obj);
2738 auto buf = (cast(ubyte*) &obj)[0 .. T.sizeof];
2739 auto init = cast(ubyte[])typeid(T).initializer();
2740 if (init.ptr is null) // null ptr means initialize to 0s
2747 version (unittest) nothrow @safe @nogc unittest
2750 struct A { string s = "A"; }
2757 static int destroyed = 0;
2761 ~this() nothrow @safe @nogc
2771 ~this() nothrow @safe @nogc
2780 assert(destroyed == 2);
2782 assert(a.c.s == "C" );
2787 void destroy(T : U[n], U, size_t n)(ref T obj) if (!is(T == struct))
2789 foreach_reverse (ref e; obj[])
2793 version (unittest) unittest
2799 assert(a == [ 0, 0 ]);
2804 static struct vec2f {
2820 this(int x) { op ~= "C" ~ cast(char)('0'+x); this.x = x; }
2821 this(this) { op ~= "P" ~ cast(char)('0'+x); }
2822 ~this() { op ~= "D" ~ cast(char)('0'+x); }
2826 S[2] a1 = [S(1), S(2)];
2829 assert(op == "D2D1"); // built-in scope destruction
2831 S[2] a1 = [S(1), S(2)];
2834 assert(op == "D2D1"); // consistent with built-in behavior
2838 S[2][2] a2 = [[S(1), S(2)], [S(3), S(4)]];
2841 assert(op == "D4D3D2D1");
2843 S[2][2] a2 = [[S(1), S(2)], [S(3), S(4)]];
2846 assert(op == "D4D3D2D1", op);
2851 void destroy(T)(ref T obj)
2852 if (!is(T == struct) && !is(T == interface) && !is(T == class) && !_isStaticArray!T)
2857 template _isStaticArray(T : U[N], U, size_t N)
2859 enum bool _isStaticArray = true;
2862 template _isStaticArray(T)
2864 enum bool _isStaticArray = false;
2867 version (unittest) unittest
2883 private bool isnan(float x)
2891 extern (C) void _d_arrayshrinkfit(const TypeInfo ti, void[] arr) nothrow;
2892 extern (C) size_t _d_arraysetcapacity(const TypeInfo ti, size_t newcapacity, void *arrptr) pure nothrow;
2896 * (Property) Gets the current _capacity of a slice. The _capacity is the size
2897 * that the slice can grow to before the underlying array must be
2898 * reallocated or extended.
2900 * If an append must reallocate a slice with no possibility of extension, then
2901 * `0` is returned. This happens when the slice references a static array, or
2902 * if another slice references elements past the end of the current slice.
2904 * Note: The _capacity of a slice may be impacted by operations on other slices.
2906 @property size_t capacity(T)(T[] arr) pure nothrow @trusted
2908 return _d_arraysetcapacity(typeid(T[]), 0, cast(void *)&arr);
2913 //Static array slice: no capacity
2914 int[4] sarray = [1, 2, 3, 4];
2915 int[] slice = sarray[];
2916 assert(sarray.capacity == 0);
2917 //Appending to slice will reallocate to a new array
2919 assert(slice.capacity >= 5);
2921 //Dynamic array slices
2922 int[] a = [1, 2, 3, 4];
2923 int[] b = a[1 .. $];
2924 int[] c = a[1 .. $ - 1];
2925 debug(SENTINEL) {} else // non-zero capacity very much depends on the array and GC implementation
2927 assert(a.capacity != 0);
2928 assert(a.capacity == b.capacity + 1); //both a and b share the same tail
2930 assert(c.capacity == 0); //an append to c must relocate c.
2934 * Reserves capacity for a slice. The capacity is the size
2935 * that the slice can grow to before the underlying array must be
2936 * reallocated or extended.
2938 * Returns: The new capacity of the array (which may be larger than
2939 * the requested capacity).
2941 size_t reserve(T)(ref T[] arr, size_t newcapacity) pure nothrow @trusted
2943 return _d_arraysetcapacity(typeid(T[]), newcapacity, cast(void *)&arr);
2948 //Static array slice: no capacity. Reserve relocates.
2949 int[4] sarray = [1, 2, 3, 4];
2950 int[] slice = sarray[];
2951 auto u = slice.reserve(8);
2953 assert(sarray.ptr !is slice.ptr);
2954 assert(slice.capacity == u);
2956 //Dynamic array slices
2957 int[] a = [1, 2, 3, 4];
2958 a.reserve(8); //prepare a for appending 4 more items
2962 assert(p == a.ptr); //a should not have been reallocated
2963 assert(u == a.capacity); //a should not have been extended
2966 // Issue 6646: should be possible to use array.reserve from SafeD.
2974 * Assume that it is safe to append to this array. Appends made to this array
2975 * after calling this function may append in place, even if the array was a
2976 * slice of a larger array to begin with.
2978 * Use this only when it is certain there are no elements in use beyond the
2979 * array in the memory block. If there are, those elements will be
2980 * overwritten by appending to this array.
2982 * Warning: Calling this function, and then using references to data located after the
2983 * given array results in undefined behavior.
2986 * The input is returned.
2988 auto ref inout(T[]) assumeSafeAppend(T)(auto ref inout(T[]) arr) nothrow
2990 _d_arrayshrinkfit(typeid(T[]), *(cast(void[]*)&arr));
2996 int[] a = [1, 2, 3, 4];
2998 // Without assumeSafeAppend. Appending relocates.
2999 int[] b = a [0 .. 3];
3001 assert(a.ptr != b.ptr);
3003 debug(SENTINEL) {} else
3005 // With assumeSafeAppend. Appending overwrites.
3006 int[] c = a [0 .. 3];
3007 c.assumeSafeAppend() ~= 5;
3008 assert(a.ptr == c.ptr);
3015 auto newcap = arr.reserve(2000);
3016 assert(newcap >= 2000);
3017 assert(newcap == arr.capacity);
3019 foreach (i; 0..2000)
3021 assert(ptr == arr.ptr);
3023 arr.assumeSafeAppend();
3025 assert(ptr == arr.ptr);
3030 int[] arr = [1, 2, 3];
3031 void foo(ref int[] i)
3036 foo(assumeSafeAppend(arr)); //pass by ref
3037 assert(arr[]==[1, 2, 5]);
3038 arr = arr[0 .. 1].assumeSafeAppend(); //pass by value
3041 // https://issues.dlang.org/show_bug.cgi?id=10574
3046 auto a2 = &assumeSafeAppend(a);
3047 auto b2 = &assumeSafeAppend(b);
3048 auto a3 = assumeSafeAppend(a[]);
3049 auto b3 = assumeSafeAppend(b[]);
3050 assert(is(typeof(*a2) == int[]));
3051 assert(is(typeof(*b2) == immutable(int[])));
3052 assert(is(typeof(a3) == int[]));
3053 assert(is(typeof(b3) == immutable(int[])));
3058 // enforce() copied from Phobos std.contracts for destroy(), left out until
3059 // we decide whether to use it.
3062 T _enforce(T, string file = __FILE__, int line = __LINE__)
3063 (T value, lazy const(char)[] msg = null)
3065 if (!value) bailOut(file, line, msg);
3069 T _enforce(T, string file = __FILE__, int line = __LINE__)
3070 (T value, scope void delegate() dg)
3076 T _enforce(T)(T value, lazy Exception ex)
3078 if (!value) throw ex();
3082 private void _bailOut(string file, int line, in char[] msg)
3085 throw new Exception(cast(string)(file ~ "(" ~ ulongToString(buf[], line) ~ "): " ~ (msg ? msg : "Enforcement failed")));
3090 /***************************************
3091 * Helper function used to see if two containers of different
3092 * types have the same contents in the same sequence.
3095 bool _ArrayEq(T1, T2)(T1[] a1, T2[] a2)
3097 if (a1.length != a2.length)
3100 // This is function is used as a compiler intrinsic and explicitly written
3101 // in a lowered flavor to use as few CTFE instructions as possible.
3103 immutable length = a1.length;
3105 for (;idx < length;++idx)
3107 if (a1[idx] != a2[idx])
3115 // This lets DDoc produce better documentation.
3118 Calculates the hash value of `arg` with an optional `seed` initial value.
3119 The result might not be equal to `typeid(T).getHash(&arg)`.
3122 arg = argument to calculate the hash value of
3123 seed = optional `seed` value (may be used for hash chaining)
3125 Return: calculated hash value of `arg`
3127 size_t hashOf(T)(auto ref T arg, size_t seed)
3129 static import core.internal.hash;
3130 return core.internal.hash.hashOf(arg, seed);
3133 size_t hashOf(T)(auto ref T arg)
3135 static import core.internal.hash;
3136 return core.internal.hash.hashOf(arg);
3141 public import core.internal.hash : hashOf;
3146 // Issue # 16654 / 16764
3149 assert(hashOf(a) == hashOf(b));
3152 bool _xopEquals(in void*, in void*)
3154 throw new Error("TypeInfo.equals is not implemented");
3157 bool _xopCmp(in void*, in void*)
3159 throw new Error("TypeInfo.compare is not implemented");
3162 void __ctfeWrite(const string s) @nogc @safe pure nothrow {}
3164 /******************************************
3165 * Create RTInfo for type T
3173 // lhs == rhs lowers to __equals(lhs, rhs) for dynamic arrays
3174 bool __equals(T1, T2)(T1[] lhs, T2[] rhs)
3176 import core.internal.traits : Unqual;
3177 alias U1 = Unqual!T1;
3178 alias U2 = Unqual!T2;
3180 static @trusted ref R at(R)(R[] r, size_t i) { return r.ptr[i]; }
3181 static @trusted R trustedCast(R, S)(S[] r) { return cast(R) r; }
3183 if (lhs.length != rhs.length)
3186 if (lhs.length == 0 && rhs.length == 0)
3189 static if (is(U1 == void) && is(U2 == void))
3191 return __equals(trustedCast!(ubyte[])(lhs), trustedCast!(ubyte[])(rhs));
3193 else static if (is(U1 == void))
3195 return __equals(trustedCast!(ubyte[])(lhs), rhs);
3197 else static if (is(U2 == void))
3199 return __equals(lhs, trustedCast!(ubyte[])(rhs));
3201 else static if (!is(U1 == U2))
3203 // This should replace src/object.d _ArrayEq which
3204 // compares arrays of different types such as long & int,
3206 // Compiler lowers to __ArrayEq in dmd/src/opover.d
3207 foreach (const u; 0 .. lhs.length)
3209 if (at(lhs, u) != at(rhs, u))
3214 else static if (__traits(isIntegral, U1))
3219 import core.stdc.string : memcmp;
3220 return () @trusted { return memcmp(cast(void*)lhs.ptr, cast(void*)rhs.ptr, lhs.length * U1.sizeof) == 0; }();
3224 foreach (const u; 0 .. lhs.length)
3226 if (at(lhs, u) != at(rhs, u))
3234 foreach (const u; 0 .. lhs.length)
3236 static if (__traits(compiles, __equals(at(lhs, u), at(rhs, u))))
3238 if (!__equals(at(lhs, u), at(rhs, u)))
3241 else static if (__traits(isFloating, U1))
3243 if (at(lhs, u) != at(rhs, u))
3246 else static if (is(U1 : Object) && is(U2 : Object))
3248 if (!(cast(Object)at(lhs, u) is cast(Object)at(rhs, u)
3249 || at(lhs, u) && (cast(Object)at(lhs, u)).opEquals(cast(Object)at(rhs, u))))
3252 else static if (__traits(hasMember, U1, "opEquals"))
3254 if (!at(lhs, u).opEquals(at(rhs, u)))
3257 else static if (is(U1 == delegate))
3259 if (at(lhs, u) != at(rhs, u))
3262 else static if (is(U1 == U11*, U11))
3264 if (at(lhs, u) != at(rhs, u))
3269 if (at(lhs, u).tupleof != at(rhs, u).tupleof)
3279 assert(__equals([], []));
3280 assert(!__equals([1, 2], [1, 2, 3]));
3290 auto arr1 = [A(0), A(2)];
3291 auto arr2 = [A(0), A(1)];
3292 auto arr3 = [A(0), A(1)];
3294 assert(arr1 != arr2);
3295 assert(arr2 == arr3);
3305 bool opEquals(const A other)
3307 return this.a == other.b && this.b == other.a;
3311 auto arr1 = [A(1, 0), A(0, 1)];
3312 auto arr2 = [A(1, 0), A(0, 1)];
3313 auto arr3 = [A(0, 1), A(1, 0)];
3315 assert(arr1 != arr2);
3316 assert(arr2 == arr3);
3319 // Compare class and interface objects for ordering.
3320 private int __cmp(Obj)(Obj lhs, Obj rhs)
3321 if (is(Obj : Object))
3325 // Regard null references as always being "less than"
3330 return lhs.opCmp(rhs);
3333 int __cmp(T)(const T[] lhs, const T[] rhs) @trusted
3334 if (__traits(isScalar, T))
3336 // Compute U as the implementation type for T
3337 static if (is(T == ubyte) || is(T == void) || is(T == bool))
3339 else static if (is(T == wchar))
3341 else static if (is(T == dchar))
3343 else static if (is(T == ifloat))
3345 else static if (is(T == idouble))
3347 else static if (is(T == ireal))
3352 static if (is(U == char))
3354 import core.internal.string : dstrcmp;
3355 return dstrcmp(cast(char[]) lhs, cast(char[]) rhs);
3357 else static if (!is(U == T))
3359 // Reuse another implementation
3360 return __cmp(cast(U[]) lhs, cast(U[]) rhs);
3364 immutable len = lhs.length <= rhs.length ? lhs.length : rhs.length;
3365 foreach (const u; 0 .. len)
3367 static if (__traits(isFloating, T))
3369 immutable a = lhs.ptr[u], b = rhs.ptr[u];
3370 static if (is(T == cfloat) || is(T == cdouble)
3373 // Use rt.cmath2._Ccmp instead ?
3374 auto r = (a.re > b.re) - (a.re < b.re);
3375 if (!r) r = (a.im > b.im) - (a.im < b.im);
3379 const r = (a > b) - (a < b);
3383 else if (lhs.ptr[u] != rhs.ptr[u])
3384 return lhs.ptr[u] < rhs.ptr[u] ? -1 : 1;
3386 return lhs.length < rhs.length ? -1 : (lhs.length > rhs.length);
3390 // This function is called by the compiler when dealing with array
3391 // comparisons in the semantic analysis phase of CmpExp. The ordering
3392 // comparison is lowered to a call to this template.
3393 int __cmp(T1, T2)(T1[] s1, T2[] s2)
3394 if (!__traits(isScalar, T1) && !__traits(isScalar, T2))
3396 import core.internal.traits : Unqual;
3397 alias U1 = Unqual!T1;
3398 alias U2 = Unqual!T2;
3400 static if (is(U1 == void) && is(U2 == void))
3401 static @trusted ref inout(ubyte) at(inout(void)[] r, size_t i) { return (cast(inout(ubyte)*) r.ptr)[i]; }
3403 static @trusted ref R at(R)(R[] r, size_t i) { return r.ptr[i]; }
3405 // All unsigned byte-wide types = > dstrcmp
3406 immutable len = s1.length <= s2.length ? s1.length : s2.length;
3408 foreach (const u; 0 .. len)
3410 static if (__traits(compiles, __cmp(at(s1, u), at(s2, u))))
3412 auto c = __cmp(at(s1, u), at(s2, u));
3416 else static if (__traits(compiles, at(s1, u).opCmp(at(s2, u))))
3418 auto c = at(s1, u).opCmp(at(s2, u));
3422 else static if (__traits(compiles, at(s1, u) < at(s2, u)))
3424 if (at(s1, u) != at(s2, u))
3425 return at(s1, u) < at(s2, u) ? -1 : 1;
3429 // TODO: fix this legacy bad behavior, see
3430 // https://issues.dlang.org/show_bug.cgi?id=17244
3431 static assert(is(U1 == U2), "Internal error.");
3432 import core.stdc.string : memcmp;
3433 auto c = (() @trusted => memcmp(&at(s1, u), &at(s2, u), U1.sizeof))();
3438 return s1.length < s2.length ? -1 : (s1.length > s2.length);
3444 void compareMinMax(T)()
3446 T[2] a = [T.max, T.max];
3447 T[2] b = [T.min, T.min];
3449 assert(__cmp(a, b) > 0);
3450 assert(__cmp(b, a) < 0);
3456 compareMinMax!ulong;
3457 compareMinMax!short;
3458 compareMinMax!ushort;
3460 compareMinMax!dchar;
3461 compareMinMax!wchar;
3464 // char types (dstrcmp)
3467 void compareMinMax(T)()
3469 T[2] a = [T.max, T.max];
3470 T[2] b = [T.min, T.min];
3472 assert(__cmp(a, b) > 0);
3473 assert(__cmp(b, a) < 0);
3476 compareMinMax!ubyte;
3479 compareMinMax!(const char);
3483 assert(__cmp(s2, s1) > 0);
3484 assert(__cmp(s1, s2) < 0);
3490 void compareMinMax(T)()
3492 T[2] a = [T.max, T.max];
3493 T[2] b = [T.min_normal, T.min_normal];
3494 T[2] c = [T.max, T.min_normal];
3497 assert(__cmp(a, b) > 0);
3498 assert(__cmp(b, a) < 0);
3499 assert(__cmp(a, c) > 0);
3500 assert(__cmp(a, d) > 0);
3501 assert(__cmp(d, c) < 0);
3502 assert(__cmp(c, c) == 0);
3506 compareMinMax!float;
3507 compareMinMax!double;
3508 compareMinMax!ireal;
3509 compareMinMax!ifloat;
3510 compareMinMax!idouble;
3511 compareMinMax!creal;
3512 //compareMinMax!cfloat;
3513 compareMinMax!cdouble;
3516 compareMinMax!(const real);
3517 compareMinMax!(immutable real);
3528 a = cast(void[]) "bb";
3529 b = cast(const(void)[]) "aa";
3532 assert(__cmp(a, b) > 0);
3533 assert(__cmp(b, a) < 0);
3536 // arrays of arrays with mixed modifiers
3539 // https://issues.dlang.org/show_bug.cgi?id=17876
3540 bool less1(immutable size_t[][] a, size_t[][] b) { return a < b; }
3541 bool less2(const void[][] a, void[][] b) { return a < b; }
3542 bool less3(inout size_t[][] a, size_t[][] b) { return a < b; }
3544 immutable size_t[][] a = [[1, 2], [3, 4]];
3545 size_t[][] b = [[1, 2], [3, 5]];
3546 assert(less1(a, b));
3547 assert(less3(a, b));
3549 auto va = [cast(immutable void[])a[0], a[1]];
3550 auto vb = [cast(void[])b[0], b[1]];
3551 assert(less2(va, vb));
3560 this(int i) { this.i = i; }
3562 override int opCmp(Object c) const @safe
3564 return i - (cast(C)c).i;
3570 assert(__cmp(c1, null) > 0);
3571 assert(__cmp(null, c1) < 0);
3572 assert(__cmp(c1, c1) == 0);
3573 assert(__cmp(c1, c2) < 0);
3574 assert(__cmp(c2, c1) > 0);
3576 assert(__cmp([c1, c1][], [c2, c2][]) < 0);
3577 assert(__cmp([c2, c2], [c1, c1]) > 0);
3586 this(ubyte i) { this.i = i; }
3592 assert(__cmp([c1, c1][], [c2, c2][]) < 0);
3593 assert(__cmp([c2, c2], [c1, c1]) > 0);
3594 assert(__cmp([c2, c2], [c2, c1]) > 0);
3597 // Compiler hook into the runtime implementation of array (vector) operations.
3598 template _arrayOp(Args...)
3600 import core.internal.arrayop;
3601 alias _arrayOp = arrayOp!Args;
3606 private inout(TypeInfo) getElement(inout TypeInfo value) @trusted pure nothrow
3608 TypeInfo element = cast() value;
3611 if (auto qualified = cast(TypeInfo_Const) element)
3612 element = qualified.base;
3613 else if (auto redefined = cast(TypeInfo_Enum) element)
3614 element = redefined.base;
3615 else if (auto staticArray = cast(TypeInfo_StaticArray) element)
3616 element = staticArray.value;
3617 else if (auto vector = cast(TypeInfo_Vector) element)
3618 element = vector.base;
3622 return cast(inout) element;
3625 private size_t getArrayHash(in TypeInfo element, in void* ptr, in size_t count) @trusted nothrow
3630 const size_t elementSize = element.tsize;
3634 static bool hasCustomToHash(in TypeInfo value) @trusted pure nothrow
3636 const element = getElement(value);
3638 if (const struct_ = cast(const TypeInfo_Struct) element)
3639 return !!struct_.xtoHash;
3641 return cast(const TypeInfo_Array) element
3642 || cast(const TypeInfo_AssociativeArray) element
3643 || cast(const ClassInfo) element
3644 || cast(const TypeInfo_Interface) element;
3647 import core.internal.traits : externDFunc;
3648 if (!hasCustomToHash(element))
3649 return hashOf(ptr[0 .. elementSize * count]);
3652 foreach (size_t i; 0 .. count)
3653 hash = hashOf(element.getHash(ptr + i * elementSize), hash);
3657 /// Provide the .dup array property.
3658 @property auto dup(T)(T[] a)
3659 if (!is(const(T) : T))
3661 import core.internal.traits : Unconst;
3662 static assert(is(T : Unconst!T), "Cannot implicitly convert type "~T.stringof~
3663 " to "~Unconst!T.stringof~" in dup.");
3665 // wrap unsafe _dup in @trusted to preserve @safe postblit
3666 static if (__traits(compiles, (T b) @safe { T a = b; }))
3667 return _trustedDup!(T, Unconst!T)(a);
3669 return _dup!(T, Unconst!T)(a);
3673 // const overload to support implicit conversion to immutable (unique result, see DIP29)
3674 @property T[] dup(T)(const(T)[] a)
3675 if (is(const(T) : T))
3677 // wrap unsafe _dup in @trusted to preserve @safe postblit
3678 static if (__traits(compiles, (T b) @safe { T a = b; }))
3679 return _trustedDup!(const(T), T)(a);
3681 return _dup!(const(T), T)(a);
3685 /// Provide the .idup array property.
3686 @property immutable(T)[] idup(T)(T[] a)
3688 static assert(is(T : immutable(T)), "Cannot implicitly convert type "~T.stringof~
3689 " to immutable in idup.");
3691 // wrap unsafe _dup in @trusted to preserve @safe postblit
3692 static if (__traits(compiles, (T b) @safe { T a = b; }))
3693 return _trustedDup!(T, immutable(T))(a);
3695 return _dup!(T, immutable(T))(a);
3699 @property immutable(T)[] idup(T:void)(const(T)[] a)
3704 private U[] _trustedDup(T, U)(T[] a) @trusted
3706 return _dup!(T, U)(a);
3709 private U[] _dup(T, U)(T[] a) // pure nothrow depends on postblit
3713 static if (is(T : void))
3714 assert(0, "Cannot dup a void[] array at compile time.");
3724 import core.stdc.string : memcpy;
3726 void[] arr = _d_newarrayU(typeid(T[]), a.length);
3727 memcpy(arr.ptr, cast(const(void)*)a.ptr, T.sizeof * a.length);
3728 auto res = *cast(U[]*)&arr;
3730 static if (!is(T : void))
3735 private extern (C) void[] _d_newarrayU(const TypeInfo ti, size_t length) pure nothrow;
3739 * Get the postblit for type T.
3741 * null if no postblit is necessary
3742 * function pointer for struct postblits
3743 * delegate for class postblits
3745 private auto _getPostblit(T)() @trusted pure nothrow @nogc
3747 // infer static postblit type, run postblit if any
3748 static if (is(T == struct))
3750 import core.internal.traits : Unqual;
3751 // use typeid(Unqual!T) here to skip TypeInfo_Const/Shared/...
3752 alias _PostBlitType = typeof(function (ref T t){ T a = t; });
3753 return cast(_PostBlitType)typeid(Unqual!T).xpostblit;
3755 else if ((&typeid(T).postblit).funcptr !is &TypeInfo.postblit)
3757 alias _PostBlitType = typeof(delegate (ref T t){ T a = t; });
3758 return cast(_PostBlitType)&typeid(T).postblit;
3764 private void _doPostblit(T)(T[] arr)
3766 // infer static postblit type, run postblit if any
3767 if (auto postblit = _getPostblit!T())
3769 foreach (ref elem; arr)
3776 static struct S1 { int* p; }
3777 static struct S2 { @disable this(); }
3778 static struct S3 { @disable this(this); }
3780 int dg1() pure nothrow @safe
3795 static assert(!is(typeof(m.idup)));
3796 static assert(!is(typeof(i.dup)));
3801 static assert(!is(typeof(m.dup)));
3802 static assert(!is(typeof(i.idup)));
3807 static assert(!is(typeof(m.idup)));
3810 int[] a = (inout(int)) { inout(const(int))[] a; return a.dup; }(0);
3815 int dg2() pure nothrow @safe
3818 S2[] m = [S2.init, S2.init];
3819 immutable(S2)[] i = [S2.init, S2.init];
3836 static struct Sunpure { this(this) @safe nothrow {} }
3837 static struct Sthrow { this(this) @safe pure {} }
3838 static struct Sunsafe { this(this) @system pure nothrow {} }
3840 static assert( __traits(compiles, () { [].dup!Sunpure; }));
3841 static assert(!__traits(compiles, () pure { [].dup!Sunpure; }));
3842 static assert( __traits(compiles, () { [].dup!Sthrow; }));
3843 static assert(!__traits(compiles, () nothrow { [].dup!Sthrow; }));
3844 static assert( __traits(compiles, () { [].dup!Sunsafe; }));
3845 static assert(!__traits(compiles, () @safe { [].dup!Sunsafe; }));
3847 static assert( __traits(compiles, () { [].idup!Sunpure; }));
3848 static assert(!__traits(compiles, () pure { [].idup!Sunpure; }));
3849 static assert( __traits(compiles, () { [].idup!Sthrow; }));
3850 static assert(!__traits(compiles, () nothrow { [].idup!Sthrow; }));
3851 static assert( __traits(compiles, () { [].idup!Sunsafe; }));
3852 static assert(!__traits(compiles, () @safe { [].idup!Sunsafe; }));
3857 static int*[] pureFoo() pure { return null; }
3858 { char[] s; immutable x = s.dup; }
3859 { immutable x = (cast(int*[])null).dup; }
3860 { immutable x = pureFoo(); }
3861 { immutable x = pureFoo().dup; }
3868 debug(SENTINEL) {} else
3869 assert(b.capacity >= 3);
3876 shared(void)[] s = [cast(shared)1];
3877 immutable(void)[] i = [cast(immutable)2];
3880 static assert(is(typeof(s.dup) == shared(void)[]));
3888 static assert(!__traits(compiles, m = s.dup));
3911 // postblit and hence .dup could escape
3912 this(this) { gp = p; }
3916 scope arr = [S(&p)];
3917 auto a = arr.dup; // dup does escape
3920 // compiler frontend lowers dynamic array comparison to this
3921 bool __ArrayEq(T1, T2)(T1[] a, T2[] b)
3923 if (a.length != b.length)
3925 foreach (size_t i; 0 .. a.length)
3933 // compiler frontend lowers struct array postblitting to this
3934 void __ArrayPostblit(T)(T[] a)
3936 foreach (ref T e; a)
3940 // compiler frontend lowers dynamic array deconstruction to this
3941 void __ArrayDtor(T)(T[] a)
3943 foreach_reverse (ref T e; a)