Skip to content

Commit 009af72

Browse files
ntrelBolpat
authored andcommitted
Fix Bugzilla 19348 - Struct casts should be better documented
Document fallback casting from struct/static array to struct. Add example. Also add link to struct constructors for `T(args)` *PostfixExpression*.
1 parent 76d936d commit 009af72

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

spec/expression.dd

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1504,13 +1504,38 @@ $(H4 $(LNAME2 cast_floating, Floating Point))
15041504

15051505
$(H4 $(LNAME2 cast_struct, Structs))
15061506

1507-
$(P Casting an expression $(I e) to a struct $(I S), when the
1508-
expression is not a struct of the same type, is equivalent to a
1509-
$(GLINK PostfixExpression):)
1507+
$(P An expression `e` can be cast to a struct type `S`:)
15101508

1509+
* The compiler attempts a
1510+
$(RELATIVE_LINK2 type-constructor-arguments, *PostfixExpression*) `S(e)`.
1511+
If that would fail:
1512+
* When `e` is a struct or static array instance, its data is reinterpreted as
1513+
the target type `S`. The data sizes must match.
1514+
* Otherwise, it is an error.
1515+
1516+
$(SPEC_RUNNABLE_EXAMPLE_RUN
15111517
---
1512-
S(e)
1518+
struct S
1519+
{
1520+
int i;
1521+
}
1522+
struct R
1523+
{
1524+
short[2] a;
1525+
}
1526+
1527+
S s = cast(S) 5; // same as S(5)
1528+
assert(s.i == 5);
1529+
static assert(!__traits(compiles, cast(S) long.max)); // S(long.max) is invalid
1530+
1531+
R r = R([1, 2]);
1532+
s = cast(S) r; // reinterpret r
1533+
assert(s.i == 0x00020001);
1534+
1535+
byte[4] a = [1, 0, 2, 0];
1536+
assert(r == cast(R) a); // reinterpret a
15131537
---
1538+
)
15141539

15151540
$(P A struct instance can be cast to a static array type when
15161541
their `.sizeof` properties each give the same result.)
@@ -1520,7 +1545,7 @@ $(H4 $(LNAME2 cast_struct, Structs))
15201545
struct S { short a, b, c; }
15211546

15221547
S s = S(1, 2, 3);
1523-
static assert(!__traits(compiles, cast(short[2]) s));
1548+
static assert(!__traits(compiles, cast(short[2]) s)); // size mismatch
15241549

15251550
short[3] x = cast(short[3]) s;
15261551
assert(x.tupleof == s.tupleof);
@@ -1730,6 +1755,7 @@ $(H4 $(LNAME2 type-constructor-arguments, Constructing a Type with an Argument L
17301755
$(P A type can precede a list of arguments. See:)
17311756

17321757
* $(DDSUBLINK spec/struct, struct-literal, Struct Literals)
1758+
* $(DDSUBLINK spec/struct, struct-constructor, Struct Constructors)
17331759
* $(RELATIVE_LINK2 uniform_construction_syntax, Uniform construction syntax for built-in scalar types)
17341760

17351761
$(H3 $(LEGACY_LNAME2 index_operations, index_expressions, Index Operations))

0 commit comments

Comments
 (0)