Skip to content

Commit

Permalink
Fix #20583 - Initialisation of @mustuse member variable causes spur…
Browse files Browse the repository at this point in the history
…ious error
  • Loading branch information
thewilsonator committed Dec 21, 2024
1 parent 32a6dfe commit 968996f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
24 changes: 23 additions & 1 deletion compiler/src/dmd/mustuse.d
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ bool checkMustUse(Expression e, Scope* sc)
{
auto sd = sym.isStructDeclaration();
// isStructDeclaration returns non-null for both structs and unions
if (sd && hasMustUseAttribute(sd, sc) && !isAssignment(e) && !isIncrementOrDecrement(e))
if (sd && hasMustUseAttribute(sd, sc)
&& !isAssignment(e)
&& !isCtorAssignment(e)
&& !isIncrementOrDecrement(e))
{
error(e.loc, "ignored value of `@%s` type `%s`; prepend a `cast(void)` if intentional",
Id.udaMustUse.toChars(), e.type.toPrettyChars(true));
Expand Down Expand Up @@ -104,6 +107,25 @@ private bool isAssignment(Expression e)
return false;
}

/**
* Returns: true if `e` is
* `(this.field = typeof(this.field).init, this.field.__ctor(arg))`
*/
private bool isCtorAssignment(Expression e)
{
import dmd.id : Id;

auto comma = e.isCommaExp();
if (!comma)
return false;
if (!isAssignment(comma.e1))
return false;
auto call = comma.e2.isCallExp();
if (!call)
return false;
return call.f.ident == Id.ctor;
}

/**
* Returns: true if id is the identifier of an assignment operator overload.
*/
Expand Down
14 changes: 14 additions & 0 deletions compiler/test/compilable/must_use_assign.d
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,17 @@ void test()
S a, b;
a = b;
}

@mustuse struct Inner
{
this(int n) {}
}

struct Outer
{
Inner inner;
this(int n)
{
this.inner = n;
}
}

0 comments on commit 968996f

Please sign in to comment.