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
52 changes: 52 additions & 0 deletions Coder.Test/Languages/RustGeneratedSourceCompilesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,58 @@ public void EntryPointArguments_LeaveOutTheProgramPath()
});
}

/// <summary>
/// Tests that an enumeration's values can be compared, held in a record and read out of
/// <c>&amp;self</c>, which each need a trait the enumeration has to derive (#255).
/// </summary>
[TestMethod]
public void EnumValuesCompareCopyAndSitInARecord_Compile()
{
if (ToolchainHarness.FindOnPath("--version", "rustc") is null)
{
Assert.Inconclusive("No Rust compiler on the path, so nothing was compiled.");
return;
}

// same(a, b) -> bool { return a == b; }
FunctionDeclaration same = new("same") { ReturnType = "bool" };
same.Parameters.Add(new Parameter("a", "Colour"));
same.Parameters.Add(new Parameter("b", "Colour"));
same.Body.Add(new ReturnStatement(
new BinaryExpression(new VariableReference("a"), BinaryOperator.Equal, new VariableReference("b"))));

// A record's derive needs every field to implement what it derives.
ClassDeclaration paint = new("Paint") { Kind = TypeDeclarationKind.Struct, IsRecord = true };
paint.Members.Add(new VariableDeclaration("colour", "Colour"));

// colour(&self) -> Colour { return self.colour; }
FunctionDeclaration colour = new("colour") { ReturnType = "Colour", IsReadOnly = true };
colour.Body.Add(new ReturnStatement(new VariableReference("self.colour")));
paint.Members.Add(colour);

SourceFile file = new("enums");
file.Members.Add(CompiledExemplar.Colour());
file.Members.Add(same);
file.Members.Add(paint);

ToolchainHarness.InTemporaryDirectory(directory =>
{
string source = new RustGenerator().Generate(file);
string allowed = "#![allow(unused_parens, dead_code)]";

File.WriteAllText(
Path.Combine(directory, "enums.rs"),
$"{allowed}{Environment.NewLine}{source}");

(int exitCode, string output) = ToolchainHarness.Run(
"rustc",
"--crate-type lib --edition 2021 -o enums.rlib enums.rs",
directory);

Assert.AreEqual(0, exitCode, $"rustc rejected the generated source:{Environment.NewLine}{source}{Environment.NewLine}{output}");
});
}

/// <summary>
/// Builds a file holding one of everything the generator has a spelling for.
/// </summary>
Expand Down
5 changes: 3 additions & 2 deletions Coder.Test/Languages/RustGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ public void Enum_IsScopedAndCanFixItsRepresentation()
string code = Generator.Generate(colour);

Assert.AreEqual(
$"#[repr(i32)]{NewLine}pub enum Colour {{{NewLine} Red = 1,{NewLine} Green,{NewLine}}}{NewLine}",
$"#[repr(i32)]{NewLine}#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]{NewLine}pub enum Colour {{{NewLine} Red = 1,{NewLine} Green,{NewLine}}}{NewLine}",
code);
}

Expand All @@ -572,7 +572,8 @@ public void Enum_WithNoVariants_HasNoRepr()
string code = Generator.Generate(new EnumDeclaration("Empty") { UnderlyingType = "int" });

Assert.IsFalse(code.Contains("#[repr", StringComparison.Ordinal));
StringAssert.StartsWith(code, "pub enum Empty {", StringComparison.Ordinal);
StringAssert.StartsWith(code, "#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]", StringComparison.Ordinal);
Assert.Contains("pub enum Empty {", code, StringComparison.Ordinal);
}

/// <summary>
Expand Down
7 changes: 7 additions & 0 deletions Coder/Languages/RustGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,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 344 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.

Check warning on line 344 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.

Check warning on line 344 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 All @@ -349,7 +349,7 @@
/// <c>f32</c> implicitly.
/// </remarks>
protected override string SpellNonFiniteSingle(float value) =>
float.IsNaN(value) ? "f32::NAN" : value > 0 ? "f32::INFINITY" : "f32::NEG_INFINITY";

Check warning on line 352 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.

Check warning on line 352 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.

Check warning on line 352 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 @@ -844,7 +844,7 @@
new(SelfName, new TypeReference(typeName)),
.. funcDecl.Parameters.Select(parameter => new KeyValuePair<string, TypeReference?>(OperandName(parameter), parameter.Type)),
]);
string self = op.ReturnsBool ? "&self" : reassigned.Contains(SelfName) ? $"mut {SelfName}" : SelfName;

Check warning on line 847 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.

Check warning on line 847 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.
code.Write($"fn {op.Method}({self}");

foreach (Parameter parameter in funcDecl.Parameters)
Expand Down Expand Up @@ -1567,7 +1567,7 @@

bool inferred = varDecl.IsTypeInferred || varDecl.Type is null;
TypeReference? annotation = !inferred ? varDecl.Type
: varDecl.InitialValue is null ? new TypeReference(UnknownTypeName)

Check warning on line 1570 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.

Check warning on line 1570 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.
: InferredLiteralWidth(varDecl.InitialValue);

if (annotation is not null)
Expand Down Expand Up @@ -1673,6 +1673,12 @@
/// do. A fixed underlying type is <c>#[repr]</c>, which is the guarantee rather than a comment
/// about one. An enumeration with no variants has no representation to fix, and rustc rejects
/// <c>#[repr]</c> on one (E0084), so it is left off.
/// <para>
/// Every enumeration derives the traits a value of it needs to be compared, copied and printed.
/// The reason a plain struct derives nothing, that one of its fields might not implement them,
/// cannot apply to a fieldless enumeration, and without them <c>a == b</c> is E0369, a record
/// holding one is E0277, and reading one out of <c>&amp;self</c> is E0507.
/// </para>
/// </remarks>
protected override void GenerateEnumDeclaration(EnumDeclaration enumDecl, CodeBlocker code)
{
Expand All @@ -1687,6 +1693,7 @@
}

string name = enumDecl.Name ?? "UnnamedEnum";
code.WriteLine("#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]");
code.Write($"{SpellVisibilityOf(enumDecl)}enum {name} ");

// A variant is not a value in a discriminant, so one naming another is cast to the
Expand Down
Loading