diff --git a/Coder.Test/Languages/TypelessDesignatedListTests.cs b/Coder.Test/Languages/TypelessDesignatedListTests.cs new file mode 100644 index 0000000..dc619d8 --- /dev/null +++ b/Coder.Test/Languages/TypelessDesignatedListTests.cs @@ -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; + +/// +/// Tests that a typeless list naming its members, which initialises a declaration that has said its +/// type, compiles in C# and Rust (#473). +/// +[TestClass] +public class TypelessDesignatedListTests +{ + private const string CSharpProject = """ + + + net10.0 + disable + disable + + + """; + + /// + /// Builds a struct Point { x, y }, a struct Frame whose origin field starts + /// at a typeless list naming Point's members, and a function sum whose local is + /// initialised the same way (#473). + /// + /// The source file. + 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; + } + + /// + /// Tests that a typeless list naming its members, initialising a local and a field, compiles as + /// a target-typed new() { … } rather than bare braces, which C# takes only for an array + /// (CS0622), and that the values arrive (#473). + /// + [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}"); + }); + } + + /// + /// 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 [x: 1, y: 2], which is not Rust, + /// and that the values arrive when run (#473). + /// + [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}"); + }); + } +} diff --git a/Coder/Languages/CSharpGenerator.cs b/Coder/Languages/CSharpGenerator.cs index 98164f0..56dfd13 100644 --- a/Coder/Languages/CSharpGenerator.cs +++ b/Coder/Languages/CSharpGenerator.cs @@ -1339,6 +1339,8 @@ private void GenerateUsingAlias(UsingAlias usingAlias, CodeBlocker code) /// because that is the one spelling C# takes for an array and a List<T> alike, and /// in a return, an assignment or an argument as well as an initialiser. The bare braces /// { 1, 2 } 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 new() { Name = value }, + /// for the same reason (#473). /// Everything else is a constructor call. /// private void GenerateConstruction(ConstructionExpression construction, CodeBlocker code) @@ -1347,6 +1349,13 @@ private void GenerateConstruction(ConstructionExpression construction, CodeBlock 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; } diff --git a/Coder/Languages/RustGenerator.cs b/Coder/Languages/RustGenerator.cs index bf24ae2..0bb3e55 100644 --- a/Coder/Languages/RustGenerator.cs +++ b/Coder/Languages/RustGenerator.cs @@ -1558,9 +1558,29 @@ protected override void GenerateReturnStatement(ReturnStatement returnStmt, Code /// /// A conditional answers what its branches do, so each branch is written for the same type. /// + /// + /// 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. + /// /// 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 ");