Skip to content

Commit 46a5e83

Browse files
MoonlightSentineldlang-bot
authored andcommitted
Add __traits(initSymbol) to the spec
The traits was upstreamed from LDC in dlang/dmd#13298
1 parent b1c4d7e commit 46a5e83

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

spec/traits.dd

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ $(GNAME TraitsKeyword):
7777
$(RELATIVE_LINK2 isSame, $(D isSame))
7878
$(RELATIVE_LINK2 compiles, $(D compiles))
7979
$(RELATIVE_LINK2 toType, $(D toType))
80+
$(RELATIVE_LINK2 initSymbol, $(D initSymbol))
8081

8182
$(GNAME TraitsArguments):
8283
$(GLINK TraitsArgument)
@@ -1713,6 +1714,49 @@ $(H2 $(GNAME toType))
17131714

17141715
$(RATIONALE Provides the inverse operation of the $(DDSUBLINK property, mangleof, `.mangleof`) property.)
17151716

1717+
$(H2 $(GNAME initSymbol))
1718+
1719+
$(P Takes a single argument, which must evaluate to a `class`, `struct` or `union` type.
1720+
Returns a `const(void)[]` that holds the initial state of any instance of the supplied type.
1721+
The slice is constructed for any type `T` as follows:
1722+
1723+
- `ptr` points to either the initializer symbol of `T`
1724+
or `null` if `T` is a zero-initialized struct / unions.
1725+
1726+
- `length` is equal to the size of an instance, i.e. `T.sizeof` for structs / unions and
1727+
$(RELATIVE_LINK2 classInstanceSize, $(D __traits(classInstanceSize, T)`)) for classes.
1728+
)
1729+
1730+
$(P
1731+
This trait matches the behaviour of `TypeInfo.initializer()` but can also be used when
1732+
`TypeInfo` is not available.
1733+
)
1734+
1735+
$(P
1736+
This traits is not available during $(DDSUBLINK glossary, ctfe, CTFE) because the actual address
1737+
of the initializer symbol will be set by the linker and hence is not available at compile time.
1738+
)
1739+
1740+
---
1741+
class C
1742+
{
1743+
int i = 4;
1744+
}
1745+
1746+
/// Initializes a malloc'ed instance of `C`
1747+
void main()
1748+
{
1749+
const void[] initSym = __traits(initSymbol, C);
1750+
1751+
void* ptr = malloc(initSym.length);
1752+
scope (exit) free(ptr);
1753+
1754+
ptr[0..initSym.length] = initSym[];
1755+
1756+
C c = cast(C) ptr;
1757+
assert(c.i == 4);
1758+
}
1759+
---
17161760

17171761
$(SPEC_SUBNAV_PREV_NEXT version, Conditional Compilation, errors, Error Handling)
17181762

0 commit comments

Comments
 (0)