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
79 changes: 79 additions & 0 deletions Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,85 @@ public void ScopeMembers_Compile()
});
}

/// <summary>
/// The consumer of the generated lists, which reads each one back.
/// </summary>
private const string ListDriver = """
public static class ListDriver
{
public static int Use()
{
Bag bag = new Bag();
bag.reset();
return bag.items.Count + bag.make().Count + bag.table.Length + bag.grid[1][0] + Bag.empty().Count;
}
}
""";

/// <summary>
/// Tests that a typeless list compiles wherever C# can meet one — initialising a
/// <c>List&lt;T&gt;</c> field or local, an array and a table of arrays, and as a return value and
/// an assigned value — rather than only as an array's initialiser (#418).
/// </summary>
[TestMethod]
public void TypelessLists_Compile()
{
if (ToolchainHarness.FindOnPath("--version", "dotnet") is null)
{
Assert.Inconclusive("No dotnet on the path, so nothing was compiled.");
return;
}

static ConstructionExpression List(params Expression[] elements)
{
ConstructionExpression list = new();
foreach (Expression element in elements)
{
list.Arguments.Add(element);
}

return list;
}

ClassDeclaration bag = new("Bag");
bag.Members.Add(new FieldDeclaration("items", TypeReference.Parse("list<int>")) { Visibility = Visibility.Public, InitialValue = List(Literal.Number(1), Literal.Number(2)) });
bag.Members.Add(new FieldDeclaration("table", new TypeReference("int") { IsArray = true }) { Visibility = Visibility.Public, InitialValue = List(Literal.Number(3), Literal.Number(4)) });
bag.Members.Add(new FieldDeclaration("grid", new TypeReference("int[]") { IsArray = true })
{
Visibility = Visibility.Public,
InitialValue = List(List(Literal.Number(1), Literal.Number(2)), List(Literal.Number(3), Literal.Number(4))),
});

FunctionDeclaration make = new("make") { ReturnType = "list<int>", Visibility = Visibility.Public };
make.Body.Add(new VariableDeclaration("xs", "list<int>", List(Literal.Number(1), Literal.Number(2))));
make.Body.Add(new ReturnStatement(List(Literal.Number(5), Literal.Number(6))));
bag.Members.Add(make);

FunctionDeclaration reset = new("reset") { ReturnType = "void", Visibility = Visibility.Public };
reset.Body.Add(new AssignmentStatement(new VariableReference("items"), List(Literal.Number(7))));
bag.Members.Add(reset);

FunctionDeclaration empty = new("empty") { ReturnType = "list<int>", Visibility = Visibility.Public, IsStatic = true };
empty.Body.Add(new ReturnStatement(List()));
bag.Members.Add(empty);

// The using is the file's to declare; that a list<T> parameter does not bring one is #334.
SourceFile file = new("Generated");
file.Imports.Add("System.Collections.Generic");
file.Members.Add(bag);

ToolchainHarness.InTemporaryDirectory(directory =>
{
string source = new CSharpGenerator().Generate(file);
File.WriteAllText(Path.Combine(directory, "Generated.csproj"), Project);
File.WriteAllText(Path.Combine(directory, "ListDriver.cs"), ListDriver);
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>
/// The consumer of the generated operators, which uses each the way C# code would.
/// </summary>
Expand Down
27 changes: 17 additions & 10 deletions Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,12 @@
/// </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 222 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 223 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 224 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 225 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 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 'string' 5 times.
"typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while",
};

Expand Down Expand Up @@ -1185,16 +1185,19 @@
/// the member they are for become an object initialiser — <c>new T { Name = value }</c> — which
/// is what C# has in place of a designated initialiser, and it is written in the order given
/// because C# does not care about declaration order the way C++ does. A construction with no
/// type at all is the braced list on its own, which C# accepts where the declaration has
/// already named an array type. Everything else is a constructor call.
/// type at all is the list on its own, written as a collection expression — <c>[1, 2]</c> —
/// 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).
/// Everything else is a constructor call.
/// </remarks>
private void GenerateConstruction(ConstructionExpression construction, CodeBlocker code)
{
bool designated = construction.Arguments.Any(argument => argument is MemberInitialiser);

if (construction.Type is null)
{
WriteBracedList(construction, code);
WriteBracedList(construction, code, asCollection: !designated);
return;
}

Expand All @@ -1203,7 +1206,7 @@
if (designated)
{
code.Write(" ");
WriteBracedList(construction, code);
WriteBracedList(construction, code, asCollection: false);
return;
}

Expand All @@ -1227,18 +1230,22 @@
/// </summary>
/// <param name="construction">The expression whose arguments to write.</param>
/// <param name="code">The writer to emit into.</param>
/// <param name="asCollection">True to write a collection expression in square brackets; false for an initialiser in braces.</param>
/// <remarks>
/// A list whose elements are themselves lists is a table, and a table on one line is a diff
/// nobody can read, so it goes one element per line with a trailing comma. A list of plain
/// values is a value and stays where it is.
/// </remarks>
private void WriteBracedList(ConstructionExpression construction, CodeBlocker code)
private void WriteBracedList(ConstructionExpression construction, CodeBlocker code, bool asCollection)
{
IReadOnlyList<AstNode> elements = WrittenElements(construction);
string open = asCollection ? "[" : "{";
string close = asCollection ? "]" : "}";
string padding = asCollection ? string.Empty : " ";

if (elements.Count == 0)
{
code.Write("{ }");
code.Write($"{open}{padding}{close}");
return;
}

Expand All @@ -1247,7 +1254,7 @@

if (stacked)
{
code.WriteLine("{");
code.WriteLine(open);
code.Indent();

foreach (AstNode argument in elements)
Expand All @@ -1257,11 +1264,11 @@
}

code.Outdent();
code.Write("}");
code.Write(close);
return;
}

code.Write("{ ");
code.Write($"{open}{padding}");

for (int index = 0; index < elements.Count; index++)
{
Expand All @@ -1273,7 +1280,7 @@
WriteListElement(elements[index], code);
}

code.Write(" }");
code.Write($"{padding}{close}");
}

/// <summary>
Expand Down
Loading