From 0914af8f9ceea01c99d1d71f832ea15f50e37e06 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:35:57 +0000 Subject: [PATCH] Name each field a Rust constructor leaves unset as Default::default() [patch] A constructor that set no fields wrote Self::default(), and one that set only some wrote ..Self::default(), but a plain struct derives no Default, so both failed rustc with E0599. Each field nobody sets is now named with its type's Default::default(), which asks nothing of the struct, and a struct with no fields is built by its empty literal. Fixes #344 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017vfJW5DpgpWQJFgB8kvHME --- .../Languages/ConstructorFieldDefaultTests.cs | 13 ++-- .../RustGeneratedSourceCompilesTests.cs | 61 ++++++++++++++++++ Coder.Test/Languages/RustGeneratorTests.cs | 29 +++++++-- Coder/Languages/RustGenerator.cs | 62 ++++++++++++++----- 4 files changed, 136 insertions(+), 29 deletions(-) diff --git a/Coder.Test/Languages/ConstructorFieldDefaultTests.cs b/Coder.Test/Languages/ConstructorFieldDefaultTests.cs index fc2e4403..851a800a 100644 --- a/Coder.Test/Languages/ConstructorFieldDefaultTests.cs +++ b/Coder.Test/Languages/ConstructorFieldDefaultTests.cs @@ -22,23 +22,18 @@ public class ConstructorFieldDefaultTests /// /// The Rust driver. Mixed has a field with no declared value, which its constructor - /// leaves to Default; the driver supplies that, as a user of the type would. + /// value-initialises by name, as the C constructor does, so the struct needs no Default + /// of its own (#344). /// private const string RustDriver = """ - impl Default for Mixed { - fn default() -> Self { - Mixed { count: 0, step: 7 } - } - } - fn main() { let counter = Counter::new(3); if counter.count != 5 || counter.step != 3 { std::process::exit(1); } let settings = Settings::new(); if settings.count != 5 || settings.step != 1 { std::process::exit(2); } let mixed = Mixed::new(); - if mixed.count != 5 || mixed.step != 7 { std::process::exit(3); } + if mixed.count != 5 || mixed.step != 0 { std::process::exit(3); } } """; @@ -64,7 +59,7 @@ int main(void) /// /// Tests that a Rust constructor builds a field it does not set from its declared value, with or - /// without initialisers of its own, and leaves only the undeclared rest to Default. + /// without initialisers of its own, and value-initialises only the undeclared rest. /// [TestMethod] public void Rust_ConstructorAppliesDeclaredFieldValues() diff --git a/Coder.Test/Languages/RustGeneratedSourceCompilesTests.cs b/Coder.Test/Languages/RustGeneratedSourceCompilesTests.cs index 595311cf..41a0b88d 100644 --- a/Coder.Test/Languages/RustGeneratedSourceCompilesTests.cs +++ b/Coder.Test/Languages/RustGeneratedSourceCompilesTests.cs @@ -1242,4 +1242,65 @@ public void AbstractMembers_CompileInStructsAndTraits() Assert.AreEqual(0, exitCode, $"rustc rejected the generated source:{Environment.NewLine}{output}{Environment.NewLine}{source}"); }); } + + /// + /// Tests that a constructor leaving fields unset compiles, for a struct whose fields declare no + /// value and for a class with one that does, and that the unset fields start at their zero value + /// and the declared one at its value (#344). + /// + [TestMethod] + public void ConstructorsLeavingFieldsUnset_CompileAndRun() + { + if (ToolchainHarness.FindOnPath("--version", "rustc") is null) + { + Assert.Inconclusive("No Rust compiler on the path, so nothing was compiled."); + return; + } + + ClassDeclaration point = new("Point") { Kind = TypeDeclarationKind.Struct }; + point.Members.Add(new FieldDeclaration("x", new TypeReference("int"))); + point.Members.Add(new FunctionDeclaration("Point") { Kind = FunctionKind.Constructor }); + + ClassDeclaration counter = new("Counter") { Kind = TypeDeclarationKind.Class }; + counter.Members.Add(new FieldDeclaration("count", new TypeReference("int"))); + counter.Members.Add(new FieldDeclaration("step", new TypeReference("int")) { InitialValue = new LiteralExpression(1) }); + counter.Members.Add(new FunctionDeclaration("Counter") { Kind = FunctionKind.Constructor }); + + ClassDeclaration empty = new("Empty") { Kind = TypeDeclarationKind.Struct }; + empty.Members.Add(new FunctionDeclaration("Empty") { Kind = FunctionKind.Constructor }); + + SourceFile file = new("unset"); + file.Members.Add(point); + file.Members.Add(counter); + file.Members.Add(empty); + + string source = new RustGenerator().Generate(file); + + const string Driver = """ + fn main() { + let point = Point::new(); + let counter = Counter::new(); + let _empty = Empty::new(); + println!("{} {} {}", point.x, counter.count, counter.step); + } + + """; + + ToolchainHarness.InTemporaryDirectory(directory => + { + File.WriteAllText( + Path.Combine(directory, "unset.rs"), + $"#![allow(dead_code)]{Environment.NewLine}{source}{Environment.NewLine}{Driver}"); + + (int exitCode, string output) = ToolchainHarness.Run( + "rustc", + "--edition 2021 -o unset unset.rs", + directory); + Assert.AreEqual(0, exitCode, $"rustc rejected the generated source:{Environment.NewLine}{source}{Environment.NewLine}{output}"); + + (int ran, string printed) = ToolchainHarness.Run(Path.Combine(directory, "unset"), string.Empty, directory); + Assert.AreEqual(0, ran, printed); + Assert.AreEqual("0 0 1", printed.Trim()); + }); + } } diff --git a/Coder.Test/Languages/RustGeneratorTests.cs b/Coder.Test/Languages/RustGeneratorTests.cs index ba15ef06..1c41274d 100644 --- a/Coder.Test/Languages/RustGeneratorTests.cs +++ b/Coder.Test/Languages/RustGeneratorTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023-2026 ktsu-dev contributors +// Copyright (c) 2023-2026 ktsu-dev contributors namespace ktsu.Coder.Test.Languages; @@ -334,16 +334,35 @@ public void Constructor_BuildsSelfWithTheFieldInitShorthand() } /// - /// Tests that a constructor with nothing to build from asks the type for its default, since Rust - /// has no zero value to fall back on. + /// Tests that a constructor with nothing to build from value-initialises each field by name, + /// since the struct derives no Default to ask (#344). /// [TestMethod] - public void Constructor_WithNoInitialisers_AsksForTheDefault() + public void Constructor_WithNoInitialisers_DefaultsEachFieldByName() { ClassDeclaration point = new("Point") { Kind = TypeDeclarationKind.Struct }; + point.Members.Add(new FieldDeclaration("x", new TypeReference("int"))); point.Members.Add(new FunctionDeclaration("Point") { Kind = FunctionKind.Constructor }); - StringAssert.Contains(Generator.Generate(point), "Self::default()", StringComparison.Ordinal); + string code = Generator.Generate(point); + + StringAssert.Contains(code, "Self { x: Default::default() }", StringComparison.Ordinal, code); + Assert.IsFalse(code.Contains("Self::default", StringComparison.Ordinal), code); + } + + /// + /// Tests that a constructor of a struct with no fields builds its empty literal. + /// + [TestMethod] + public void Constructor_OfAStructWithNoFields_BuildsTheEmptyLiteral() + { + ClassDeclaration empty = new("Empty") { Kind = TypeDeclarationKind.Struct }; + empty.Members.Add(new FunctionDeclaration("Empty") { Kind = FunctionKind.Constructor }); + + string code = Generator.Generate(empty); + + StringAssert.Contains(code, "Self {}", StringComparison.Ordinal, code); + Assert.IsFalse(code.Contains("Self::default", StringComparison.Ordinal), code); } /// diff --git a/Coder/Languages/RustGenerator.cs b/Coder/Languages/RustGenerator.cs index 18a5fdd1..1c64ad29 100644 --- a/Coder/Languages/RustGenerator.cs +++ b/Coder/Languages/RustGenerator.cs @@ -1795,10 +1795,10 @@ private void WriteConstructorBody(FunctionDeclaration funcDecl, CodeBlocker code : [.. InstanceDefaults(constructedType) .Where(field => !funcDecl.Initialisers.Any(initialiser => initialiser.Name == field.Name))]; - if (funcDecl.Initialisers.Count == 0 && defaulted.Count == 0) + if (constructedType is null) { - // There is nothing to build from, and Rust has no zero value to fall back on. Default is - // the one thing a type can ask for without naming its fields. + // A constructor outside any type has no fields to name, so Default is the one thing it + // can ask for. code.WriteLine("Self::default()"); return; } @@ -1816,11 +1816,26 @@ private void WriteConstructorBody(FunctionDeclaration funcDecl, CodeBlocker code value.Arguments.Add(new MemberInitialiser(field.Name ?? string.Empty, (Expression)field.Value!.DeepClone())); } - // With no initialisers, the fields nobody gave a value still come from Default, as they - // did before any had a declared one: struct update syntax fills in the rest. - if (funcDecl.Initialisers.Count == 0 && !NamesEveryField(constructedType!, value)) + // A field nobody gave a value is value-initialised by name. Self::default(), or struct + // update syntax's ..Self::default(), would ask the struct for a Default it never derives + // (#344), where naming the field asks only its type, as an empty initialiser already does. + HashSet named = [.. value.Arguments.OfType().Select(initialiser => initialiser.Name)]; + foreach (string field in InstanceFieldNames(constructedType).Where(field => !named.Contains(field))) { - value.Arguments.Add(new CallExpression("..Self::default")); + value.Arguments.Add(new MemberInitialiser(field, new CallExpression("Default::default"))); + } + + if (value.Arguments.Count == 0) + { + // A struct with no fields is built by its empty literal, unless it holds a marker for an + // unused type parameter, which the literal names like any other field. + if (PhantomType(constructedType) is null) + { + code.WriteLine("Self {}"); + return; + } + + value.Arguments.Add(new MemberInitialiser(PhantomFieldName, new VariableReference(PhantomValue))); } GenerateConstructionExpression(value, code); @@ -1828,17 +1843,34 @@ private void WriteConstructorBody(FunctionDeclaration funcDecl, CodeBlocker code } /// - /// Reports whether a struct literal names every field of the struct it builds. + /// The names of the fields every instance of a struct holds, as its literal has to name them. /// /// The struct being built. - /// The literal building it. - /// True when no field is left for struct update syntax to fill in. - private static bool NamesEveryField(ClassDeclaration classDecl, ConstructionExpression value) + /// The field holding the base, when there is one, then each instance field. + /// + /// The marker for an unused type parameter is left out: the literal adds it itself. + /// + private static IEnumerable InstanceFieldNames(ClassDeclaration classDecl) { - HashSet named = [.. value.Arguments.OfType().Select(initialiser => initialiser.Name)]; - return classDecl.BaseType is null - && classDecl.Members.OfType().Where(field => !IsAssociatedField(field)).All(field => named.Contains(field.Name)) - && classDecl.Members.OfType().All(field => named.Contains(field.Name)); + if (classDecl.BaseType is not null) + { + yield return BaseMemberName; + } + + foreach (AstNode member in classDecl.Members) + { + string? name = member switch + { + VariableDeclaration field => field.Name, + FieldDeclaration field when !IsAssociatedField(field) => field.Name, + _ => null, + }; + + if (name is not null) + { + yield return name; + } + } } ///