diff --git a/Coder.Test/Languages/ConstructorFieldDefaultTests.cs b/Coder.Test/Languages/ConstructorFieldDefaultTests.cs
index fc2e440..851a800 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 8c5b47a..b631f3d 100644
--- a/Coder.Test/Languages/RustGeneratedSourceCompilesTests.cs
+++ b/Coder.Test/Languages/RustGeneratedSourceCompilesTests.cs
@@ -1299,4 +1299,65 @@ public void StringLiteralsReassignedOrPassedAsString_Compile()
Assert.AreEqual(0, exitCode, $"rustc rejected the generated source:{Environment.NewLine}{source}{Environment.NewLine}{output}");
});
}
+
+ ///
+ /// 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 ba15ef0..1c41274 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 bf24ae2..f61afd9 100644
--- a/Coder/Languages/RustGenerator.cs
+++ b/Coder/Languages/RustGenerator.cs
@@ -1858,10 +1858,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;
}
@@ -1879,11 +1879,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);
@@ -1891,17 +1906,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;
+ }
+ }
}
///