From 968996fb3e1ee343da8754efa4e8b3b034edabf8 Mon Sep 17 00:00:00 2001 From: Nicholas Wilson Date: Sat, 21 Dec 2024 10:39:11 +0800 Subject: [PATCH 1/2] Fix #20583 - Initialisation of `@mustuse` member variable causes spurious error --- compiler/src/dmd/mustuse.d | 24 +++++++++++++++++++++- compiler/test/compilable/must_use_assign.d | 14 +++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/compiler/src/dmd/mustuse.d b/compiler/src/dmd/mustuse.d index fc7618bfc0ed..8ad89ebbad43 100644 --- a/compiler/src/dmd/mustuse.d +++ b/compiler/src/dmd/mustuse.d @@ -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)); @@ -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. */ diff --git a/compiler/test/compilable/must_use_assign.d b/compiler/test/compilable/must_use_assign.d index bd1983a40e63..6fae4a5e4238 100644 --- a/compiler/test/compilable/must_use_assign.d +++ b/compiler/test/compilable/must_use_assign.d @@ -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; + } +} From 848fcc541bf029b8c08fc000b78e5875205f58be Mon Sep 17 00:00:00 2001 From: Nicholas Wilson Date: Sat, 21 Dec 2024 11:25:02 +0800 Subject: [PATCH 2/2] Update compiler/src/dmd/mustuse.d Co-authored-by: Paul Backus --- compiler/src/dmd/mustuse.d | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/src/dmd/mustuse.d b/compiler/src/dmd/mustuse.d index 8ad89ebbad43..2dfe2ed5b665 100644 --- a/compiler/src/dmd/mustuse.d +++ b/compiler/src/dmd/mustuse.d @@ -108,8 +108,8 @@ private bool isAssignment(Expression e) } /** - * Returns: true if `e` is - * `(this.field = typeof(this.field).init, this.field.__ctor(arg))` + * Returns: true if `e` is an assignment that's been rewritten to a + * constructor call. */ private bool isCtorAssignment(Expression e) {