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
137 changes: 137 additions & 0 deletions Coder.Test/Languages/TypelessDesignatedListTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.Coder.Test.Languages;

using ktsu.Coder.Ast;
using ktsu.Coder.Languages;
using Microsoft.VisualStudio.TestTools.UnitTesting;

/// <summary>
/// Tests that a typeless list naming its members, which initialises a declaration that has said its
/// type, compiles in C# and Rust (#473).
/// </summary>
[TestClass]
public class TypelessDesignatedListTests
{
private const string CSharpProject = """
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>
""";

/// <summary>
/// Builds a struct <c>Point { x, y }</c>, a struct <c>Frame</c> whose <c>origin</c> field starts
/// at a typeless list naming Point's members, and a function <c>sum</c> whose local is
/// initialised the same way (#473).
/// </summary>
/// <returns>The source file.</returns>
private static SourceFile DesignatedLists()
{
static ConstructionExpression Designated(int x, int y)
{
ConstructionExpression list = new();
list.Arguments.Add(new MemberInitialiser("x", Literal.Number(x)));
list.Arguments.Add(new MemberInitialiser("y", Literal.Number(y)));
return list;
}

ClassDeclaration point = new("Point") { Kind = TypeDeclarationKind.Struct, Visibility = Visibility.Public };
point.Members.Add(new FieldDeclaration("x", "int") { Visibility = Visibility.Public });
point.Members.Add(new FieldDeclaration("y", "int") { Visibility = Visibility.Public });

ClassDeclaration frame = new("Frame") { Kind = TypeDeclarationKind.Struct, Visibility = Visibility.Public };
frame.Members.Add(new FieldDeclaration("origin", "Point") { Visibility = Visibility.Public, InitialValue = Designated(3, 4) });
frame.Members.Add(new FunctionDeclaration("Frame") { Kind = FunctionKind.Constructor, Visibility = Visibility.Public });

FunctionDeclaration sum = new("sum") { ReturnType = "int", Visibility = Visibility.Public, IsStatic = true };
sum.Body.Add(new VariableDeclaration("p", "Point", Designated(1, 2)));
sum.Body.Add(new ReturnStatement(new BinaryExpression(new VariableReference("p.x"), BinaryOperator.Add, new VariableReference("p.y"))));
frame.Members.Add(sum);

SourceFile file = new("designated");
file.Members.Add(point);
file.Members.Add(frame);
return file;
}

/// <summary>
/// Tests that a typeless list naming its members, initialising a local and a field, compiles as
/// a target-typed <c>new() { … }</c> rather than bare braces, which C# takes only for an array
/// (CS0622), and that the values arrive (#473).
/// </summary>
[TestMethod]
public void TypelessDesignatedLists_Compile()
{
string source = new CSharpGenerator().Generate(DesignatedLists());
Assert.Contains("Point p = new() { x = 1, y = 2 };", source, StringComparison.Ordinal, source);
Assert.Contains("Point origin = new() { x = 3, y = 4 };", source, StringComparison.Ordinal, source);

if (ToolchainHarness.FindOnPath("--version", "dotnet") is null)
{
Assert.Inconclusive("No dotnet on the path, so nothing was compiled.");
return;
}

const string DesignatedDriver = """
public static class DesignatedDriver
{
public static int Use() => Frame.sum() + new Frame().origin.x + new Frame().origin.y;
}
""";

ToolchainHarness.InTemporaryDirectory(directory =>
{
File.WriteAllText(Path.Combine(directory, "Generated.csproj"), CSharpProject);
File.WriteAllText(Path.Combine(directory, "DesignatedDriver.cs"), DesignatedDriver);
File.WriteAllText(Path.Combine(directory, "Generated.cs"), source);

(int exitCode, string output) = ToolchainHarness.Run("dotnet", "build -nologo", directory);
Assert.AreEqual(0, exitCode, $"C# rejected the generated source:{Environment.NewLine}{output}{Environment.NewLine}{source}");
});
}

/// <summary>
/// Tests that a typeless list naming its members, initialising a local and a field, is written
/// as a struct literal of the receiving type rather than <c>[x: 1, y: 2]</c>, which is not Rust,
/// and that the values arrive when run (#473).
/// </summary>
[TestMethod]
public void TypelessDesignatedLists_CompileAndRun()
{
string source = new RustGenerator().Generate(DesignatedLists());
Assert.Contains("Point { x: 1, y: 2 }", source, StringComparison.Ordinal, source);
Assert.Contains("Point { x: 3, y: 4 }", source, StringComparison.Ordinal, source);

if (ToolchainHarness.FindOnPath("--version", "rustc") is null)
{
Assert.Inconclusive("No Rust compiler on the path, so nothing was compiled.");
return;
}

const string Driver = """
fn main() {
let f = Frame::new();
if Frame::sum() + f.origin.x + f.origin.y != 10 {
std::process::exit(1);
}
}
""";

ToolchainHarness.InTemporaryDirectory(directory =>
{
File.WriteAllText(
Path.Combine(directory, "designated.rs"),
$"#![allow(unused_parens, dead_code, unused_mut)]{Environment.NewLine}{source}{Environment.NewLine}{Driver}");

(int exitCode, string output) = ToolchainHarness.Run("rustc", "--edition 2021 -o designated designated.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, "designated"), string.Empty, directory);
Assert.AreEqual(0, ran, $"The program computed the wrong total:{Environment.NewLine}{printed}");
});
}
}
9 changes: 9 additions & 0 deletions Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -223,13 +223,13 @@
/// </remarks>
protected override IReadOnlySet<string> ReservedWords { get; } = new HashSet<string>(StringComparer.Ordinal)
{
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const",

Check warning on line 226 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'abstract' 4 times.
"continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit",

Check warning on line 227 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'double' 5 times.
"extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int",

Check warning on line 228 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'float' 5 times.
"interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out",

Check warning on line 229 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'object' 4 times.
"override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try",

Check warning on line 231 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'string' 5 times.
"typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while",

Check warning on line 232 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'ulong' 4 times.
"field",
};

Expand Down Expand Up @@ -1339,6 +1339,8 @@
/// because that is the one spelling C# takes for an array and a <c>List&lt;T&gt;</c> alike, and
/// in a return, an assignment or an argument as well as an initialiser. The bare braces
/// <c>{ 1, 2 }</c> are only an array's initialiser and not an expression at all (#418).
/// A list with no type that names its members is a target-typed <c>new() { Name = value }</c>,
/// for the same reason (#473).
/// Everything else is a constructor call.
/// </remarks>
private void GenerateConstruction(ConstructionExpression construction, CodeBlocker code)
Expand All @@ -1347,6 +1349,13 @@

if (construction.Type is null)
{
// A list naming its members is an object initialiser, and C# takes one only after a
// `new`. Bare braces are an array's initialiser (CS0622), so it is target-typed (#473).
if (designated)
{
code.Write("new() ");
}

WriteBracedList(construction, code, asCollection: !designated);
return;
}
Expand Down
20 changes: 20 additions & 0 deletions Coder/Languages/RustGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1558,9 +1558,29 @@ protected override void GenerateReturnStatement(ReturnStatement returnStmt, Code
/// <para>
/// A conditional answers what its branches do, so each branch is written for the same type.
/// </para>
/// <para>
/// A list with no type that names its members takes the receiving type as its own, so it is
/// written as that type's struct literal.
/// </para>
/// </remarks>
private void WriteValue(AstNode value, TypeReference? target, CodeBlocker code)
{
// A list with no type that names its members is a struct literal of the type receiving it,
// which is the only place the type can come from: `[x: 1]` is not Rust at all (#473).
if (value is ConstructionExpression { Type: null } list
&& target is { IsArray: false }
&& list.Arguments.Any(argument => argument is MemberInitialiser))
{
ConstructionExpression typed = new(target);
foreach (AstNode argument in list.Arguments)
{
typed.Arguments.Add(argument);
}

GenerateConstructionExpression(typed, code);
return;
}

if (value is ConditionalExpression conditional && IsOwnedString(target))
{
code.Write("(if ");
Expand Down
Loading