Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions Coder.Test/Languages/ConstructorFieldDefaultTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,18 @@ public class ConstructorFieldDefaultTests

/// <summary>
/// The Rust driver. <c>Mixed</c> has a field with no declared value, which its constructor
/// leaves to <c>Default</c>; 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 <c>Default</c>
/// of its own (#344).
/// </summary>
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); }
}

""";
Expand All @@ -64,7 +59,7 @@ int main(void)

/// <summary>
/// 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 <c>Default</c>.
/// without initialisers of its own, and value-initialises only the undeclared rest.
/// </summary>
[TestMethod]
public void Rust_ConstructorAppliesDeclaredFieldValues()
Expand Down
61 changes: 61 additions & 0 deletions Coder.Test/Languages/RustGeneratedSourceCompilesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1299,4 +1299,65 @@ public void StringLiteralsReassignedOrPassedAsString_Compile()
Assert.AreEqual(0, exitCode, $"rustc rejected the generated source:{Environment.NewLine}{source}{Environment.NewLine}{output}");
});
}

/// <summary>
/// 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).
/// </summary>
[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<int>(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());
});
}
}
29 changes: 24 additions & 5 deletions Coder.Test/Languages/RustGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) 2023-2026 ktsu-dev contributors
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.Coder.Test.Languages;

Expand Down Expand Up @@ -334,16 +334,35 @@
}

/// <summary>
/// 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 <c>Default</c> to ask (#344).
/// </summary>
[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);

Check warning on line 349 in Coder.Test/Languages/RustGeneratorTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaG_gJk05CrBYceHTKCc&open=AaG_gJk05CrBYceHTKCc&pullRequest=480
Assert.IsFalse(code.Contains("Self::default", StringComparison.Ordinal), code);
}

/// <summary>
/// Tests that a constructor of a struct with no fields builds its empty literal.
/// </summary>
[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);

Check warning on line 364 in Coder.Test/Languages/RustGeneratorTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaG_gJk05CrBYceHTKCd&open=AaG_gJk05CrBYceHTKCd&pullRequest=480
Assert.IsFalse(code.Contains("Self::default", StringComparison.Ordinal), code);
}

/// <summary>
Expand Down Expand Up @@ -572,7 +591,7 @@
string code = Generator.Generate(new EnumDeclaration("Empty") { UnderlyingType = "int" });

Assert.IsFalse(code.Contains("#[repr", StringComparison.Ordinal));
StringAssert.StartsWith(code, "#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]", StringComparison.Ordinal);

Check warning on line 594 in Coder.Test/Languages/RustGeneratorTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.StartsWith' instead of 'StringAssert.StartsWith'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaG_gJk05CrBYceHTKCe&open=AaG_gJk05CrBYceHTKCe&pullRequest=480
Assert.Contains("pub enum Empty {", code, StringComparison.Ordinal);
}

Expand Down
62 changes: 47 additions & 15 deletions Coder/Languages/RustGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@
/// The associated constants of <c>f64</c>, which need nothing imported.
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "f64::NAN" : value > 0 ? "f64::INFINITY" : "f64::NEG_INFINITY";

Check warning on line 454 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

/// <inheritdoc/>
/// <remarks>
Expand Down Expand Up @@ -1858,10 +1858,10 @@
: [.. 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;
}
Expand All @@ -1879,29 +1879,61 @@
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<string?> named = [.. value.Arguments.OfType<MemberInitialiser>().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);
code.WriteLine();
}

/// <summary>
/// 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.
/// </summary>
/// <param name="classDecl">The struct being built.</param>
/// <param name="value">The literal building it.</param>
/// <returns>True when no field is left for struct update syntax to fill in.</returns>
private static bool NamesEveryField(ClassDeclaration classDecl, ConstructionExpression value)
/// <returns>The field holding the base, when there is one, then each instance field.</returns>
/// <remarks>
/// The marker for an unused type parameter is left out: the literal adds it itself.
/// </remarks>
private static IEnumerable<string> InstanceFieldNames(ClassDeclaration classDecl)
{
HashSet<string?> named = [.. value.Arguments.OfType<MemberInitialiser>().Select(initialiser => initialiser.Name)];
return classDecl.BaseType is null
&& classDecl.Members.OfType<FieldDeclaration>().Where(field => !IsAssociatedField(field)).All(field => named.Contains(field.Name))
&& classDecl.Members.OfType<VariableDeclaration>().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;
}
}
Comment thread
matt-edmondson marked this conversation as resolved.
Resolved
}

/// <summary>
Expand Down
Loading