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
40 changes: 40 additions & 0 deletions Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -402,4 +402,44 @@ public static class Driver
Assert.AreEqual(0, exitCode, $"C# rejected the generated source:{Environment.NewLine}{output}{Environment.NewLine}{source}");
});
}

/// <summary>
/// Tests that a local with no initialiser compiles whether or not it says a type, which C# can
/// only infer from an initialiser (CS0818), and that one with an initialiser is still <c>var</c> (#355).
/// </summary>
[TestMethod]
public void LocalsWithoutAnInitialiser_Compile()
{
if (ToolchainHarness.FindOnPath("--version", "dotnet") is null)
{
Assert.Inconclusive("No dotnet on the path, so nothing was compiled.");
return;
}

FunctionDeclaration locals = new("locals") { ReturnType = "int" };
locals.Body.Add(new VariableDeclaration("untyped"));
locals.Body.Add(new VariableDeclaration("typed", "int") { IsTypeInferred = true });
locals.Body.Add(new VariableDeclaration("started", "int", Literal.Number(2)) { IsTypeInferred = true });
locals.Body.Add(new AssignmentStatement(new VariableReference("untyped"), Literal.Number(1)));
locals.Body.Add(new AssignmentStatement(new VariableReference("typed"), Literal.Number(3)));
locals.Body.Add(new ReturnStatement(new BinaryExpression(new VariableReference("typed"), BinaryOperator.Add, new VariableReference("started"))));

SourceFile file = new("Generated");
file.Members.Add(locals);

ToolchainHarness.InTemporaryDirectory(directory =>
{
string source = new CSharpGenerator().Generate(file);
Assert.Contains("object untyped;", source, StringComparison.Ordinal, source);
Assert.Contains("untyped: C# infers a type only from an initialiser", source, StringComparison.Ordinal, source);
Assert.Contains("int typed;", source, StringComparison.Ordinal, source);
Assert.Contains("var started = 2;", source, StringComparison.Ordinal, source);

File.WriteAllText(Path.Combine(directory, "Generated.csproj"), Project);
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}");
});
}
}
18 changes: 12 additions & 6 deletions Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@
/// A member is emitted through the same dispatch as any other node, so a nested class, a method
/// and a field each come out through the emitter for their own shape.
/// </remarks>
private void GenerateClass(ClassDeclaration classDecl, CodeBlocker code)

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed.

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed.
{
bool aliasesWereHoisted = memberAliasesHoisted;
if (!aliasesWereHoisted)
Expand Down Expand Up @@ -619,7 +619,7 @@
/// The constants on <see cref="double"/>, which every file can name without a <c>using</c>.
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "double.NaN" : value > 0 ? "double.PositiveInfinity" : "double.NegativeInfinity";

Check warning on line 622 in Coder/Languages/CSharpGenerator.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 622 in Coder/Languages/CSharpGenerator.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 @@ -627,7 +627,7 @@
/// <c>float</c> implicitly.
/// </remarks>
protected override string SpellNonFiniteSingle(float value) =>
float.IsNaN(value) ? "float.NaN" : value > 0 ? "float.PositiveInfinity" : "float.NegativeInfinity";

Check warning on line 630 in Coder/Languages/CSharpGenerator.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 630 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

/// <summary>
/// Emits a namespace and its members.
Expand Down Expand Up @@ -698,7 +698,7 @@
/// CS0103 (#279). The import is fully qualified because it is resolved from the scope it is in.
/// </para>
/// </remarks>
private void GenerateScopeMembers(IEnumerable<AstNode> members, string holderName, CodeBlocker code)

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 18 to the 15 allowed.
{
AstNode[] declared = [.. members];
FunctionDeclaration[] lodged = LodgeScopeOperators(declared);
Expand Down Expand Up @@ -1251,7 +1251,7 @@
/// <c>= default</c> means there.
/// </para>
/// </remarks>
private void GenerateFunction(FunctionDeclaration function, CodeBlocker code, ClassDeclaration? enclosingType)

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed.
{
WritePreamble(function, code, enclosingType is null ? PreambleSite.Function : PreambleSite.Method);

Expand Down Expand Up @@ -1398,7 +1398,7 @@
/// <param name="enclosingType">The type it belongs to, when it belongs to one.</param>
/// <param name="code">The writer to emit into.</param>
/// <returns>False when the note stands in for the whole declaration, so nothing else is written.</returns>
private bool WriteMemberNotes(FunctionDeclaration function, string name, ClassDeclaration? enclosingType, CodeBlocker code)

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed.
{
// A struct cannot have a finalizer (CS0575), so the destructor is written down rather than
// declared, the way a member C# expresses by not declaring it is.
Expand Down Expand Up @@ -1799,21 +1799,21 @@
return string.Equals(name, "void", StringComparison.OrdinalIgnoreCase) ? "void" : name;
}

private void GenerateVariableDeclaration(VariableDeclaration varDecl, CodeBlocker code)

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 20 to the 15 allowed.
{
if (!varDecl.IsTypeInferred && varDecl.Type is TypeReference declaredType)
// C# infers a type only from an initialiser (CS0818), so a declaration without one says the
// type it was given, whether or not it asked for inference.
TypeReference? saidType = varDecl.IsTypeInferred && varDecl.InitialValue is not null ? null : varDecl.Type;
if (saidType is not null)
{
shiftCountTypes[varDecl.Name] = declaredType;
shiftCountTypes[varDecl.Name] = saidType;
}
else
{
shiftCountTypes.Remove(varDecl.Name);
}

// Use type or var for type inference
string type = varDecl.IsTypeInferred || varDecl.Type is null
? "var"
: MapToCSType(varDecl.Type);
string type = saidType is null ? "var" : MapToCSType(saidType);

// A local has no access modifier and a field usually does, and the AST distinguishes the two
// by whether one was set: emitting it only when present keeps both correct. A variable of a
Expand All @@ -1834,6 +1834,12 @@
type = UnknownTypeName;
}
}
else if (varDecl.InitialValue is null && string.Equals(type, "var", StringComparison.Ordinal))
{
// A local with neither a type nor an initialiser has nothing to infer from.
WriteInexpressible(code, $"{varDecl.Name}: C# infers a type only from an initialiser, and nothing here says one");
type = UnknownTypeName;
}
if ((isHeld ? SpellVisibility(varDecl.Visibility) ?? DefaultVisibility : SpellVisibility(varDecl.Visibility)) is string modifier)
{
code.Write($"{modifier} ");
Expand Down
Loading