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/FailedGenerationStateTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// 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>
/// A generator is registered as a singleton and the editor keeps using it after a preview fails, so
/// a <c>Generate</c> call that throws inside a type must not change what the next call writes.
/// </summary>
[TestClass]
public sealed class FailedGenerationStateTests
{
[TestMethod]
public void CGenerator_AfterAFailureInsideAType_WritesWhatAFreshInstanceWrites() =>
AssertUnaffectedByFailure(() => new CGenerator(), ClassHoldingAnEnumMember());

[TestMethod]
public void CppGenerator_AfterAFailureInsideAType_WritesWhatAFreshInstanceWrites() =>
AssertUnaffectedByFailure(() => new CppGenerator(), ClassHoldingAnEnumMember());

[TestMethod]
public void RustGenerator_AfterAFailureInsideAType_WritesWhatAFreshInstanceWrites() =>
AssertUnaffectedByFailure(() => new RustGenerator(), ClassWithAnUnknownOperatorDefault());

private static void AssertUnaffectedByFailure(Func<LanguageGeneratorBase> create, AstNode failing)
{
string expected = create().Generate(FileScopeConstant());

LanguageGeneratorBase generator = create();
Assert.ThrowsExactly<NotSupportedException>(() => generator.Generate(failing), "Precondition: the document fails inside the type.");

Assert.AreEqual(expected, generator.Generate(FileScopeConstant()), generator.DisplayName);
}

/// <summary>
/// A file holding only a static constant, whose spelling depends on whether the generator thinks
/// it is inside a type.
/// </summary>
private static SourceFile FileScopeConstant()
{
SourceFile file = new("m");
file.Members.Add(new FieldDeclaration("limit", TypeReference.Parse("int"))
{
IsStatic = true,
IsConstant = true,
InitialValue = Literal.Number(3),
});
return file;
}

/// <summary>
/// A class with an enum member, which C and C++ refuse once they are inside the struct.
/// </summary>
private static SourceFile ClassHoldingAnEnumMember()
{
ClassDeclaration box = new("Box");
box.Members.Add(new FieldDeclaration("w", TypeReference.Parse("int")));
box.Members.Add(new EnumMember("Red"));
SourceFile file = new("m");
file.Members.Add(box);
return file;
}

/// <summary>
/// A struct whose field starts at an operator no generator can spell, as YAML can produce from a
/// number, which Rust refuses while writing the struct's fields.
/// </summary>
private static SourceFile ClassWithAnUnknownOperatorDefault()
{
ClassDeclaration box = new("Box");
box.Members.Add(new VariableDeclaration("w", "int", new BinaryExpression(Literal.Number(1), (BinaryOperator)999, Literal.Number(2))));
SourceFile file = new("m");
file.Members.Add(box);
return file;
}
}
60 changes: 32 additions & 28 deletions Coder/Languages/CGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@
/// The <c>&lt;math.h&gt;</c> macros, which is why a file holding one includes it.
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "NAN" : value > 0 ? "INFINITY" : "-INFINITY";

Check warning on line 180 in Coder/Languages/CGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

/// <inheritdoc/>
protected override IEnumerable<string> RequiredImports(SourceFile file)
Expand Down Expand Up @@ -640,42 +640,46 @@
code.Indent();

insideType++;

WriteEmbeddedBases(classDecl, fields.Count, code);

if (fields.Count == 0 && classDecl.BaseType is null && classDecl.Interfaces.Count == 0)
try
{
WriteInexpressible(code, $"{name} holds no data: C has no empty struct, so this member stands in");
code.WriteLine($"char {UnusedMemberName};");
}
WriteEmbeddedBases(classDecl, fields.Count, code);

AstNode? previous = null;
foreach (AstNode member in fields)
{
if (previous is not null && NeedsSeparation(previous, member))
if (fields.Count == 0 && classDecl.BaseType is null && classDecl.Interfaces.Count == 0)
{
code.NewLine();
WriteInexpressible(code, $"{name} holds no data: C has no empty struct, so this member stands in");
code.WriteLine($"char {UnusedMemberName};");
}

previous = member;

switch (member)
AstNode? previous = null;
foreach (AstNode member in fields)
{
case FunctionDeclaration method:
GenerateFunctionPointer(method, code);
break;

case VariableDeclaration field:
GenerateStructMember(field.Name, field.Type, field.InitialValue, field.IsConstant, code);
break;

default:
GenerateInternal(member, code);
break;
if (previous is not null && NeedsSeparation(previous, member))
{
code.NewLine();
}

previous = member;

switch (member)
{
case FunctionDeclaration method:
GenerateFunctionPointer(method, code);
break;

case VariableDeclaration field:
GenerateStructMember(field.Name, field.Type, field.InitialValue, field.IsConstant, code);
break;

default:
GenerateInternal(member, code);
break;
}
}
}

insideType--;
finally
{
insideType--;
}

code.Outdent();
code.WriteLine($"}} {name};");
Expand Down
99 changes: 52 additions & 47 deletions Coder/Languages/CppGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "std::numeric_limits<double>::quiet_NaN()"
: value > 0 ? "std::numeric_limits<double>::infinity()"

Check warning on line 166 in Coder/Languages/CppGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.
: "-std::numeric_limits<double>::infinity()";

/// <inheritdoc/>
Expand All @@ -173,7 +173,7 @@
/// </remarks>
protected override string SpellNonFiniteSingle(float value) =>
float.IsNaN(value) ? "std::numeric_limits<float>::quiet_NaN()"
: value > 0 ? "std::numeric_limits<float>::infinity()"

Check warning on line 176 in Coder/Languages/CppGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.
: "-std::numeric_limits<float>::infinity()";

/// <inheritdoc/>
Expand Down Expand Up @@ -257,7 +257,7 @@
/// elided or duplicated, which is a stronger promise than the AST is in a position to make.
/// </para>
/// </remarks>
protected override void GenerateFunction(FunctionDeclaration funcDecl, CodeBlocker code, string? enclosingType)

Check warning on line 260 in Coder/Languages/CppGenerator.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.
{
Ensure.NotNull(funcDecl);
Ensure.NotNull(code);
Expand Down Expand Up @@ -540,56 +540,61 @@
AstNode? previous = null;

insideType++;
foreach (AstNode member in classDecl.Members)
{
Visibility access = classDecl.Kind == TypeDeclarationKind.Interface
? Visibility.Public
: AccessOf(member);

// A blank line goes between two members when either says something about itself, when
// they are different kinds of thing, or where the access changes. A documented member
// needs air above it or its first comment line butts against the member before it and
// reads as belonging to that one; the member after a documented one needs the same, or it
// is swallowed into that block. Two of the same kind that say nothing stay together,
// which is what keeps a run of aliases, or of defaulted and deleted declarations, reading
// as one group rather than as four paragraphs.
if (!first && (NeedsSeparation(previous!, member) || access != current))
{
// NewLine rather than WriteLine: a separator carrying the current indent is a line of
// trailing whitespace, which every formatter strips and every diff then shows.
code.NewLine();
}

first = false;
previous = member;

if (access != current)
{
// An access label sits at the class's own indentation rather than the members', which
// is what makes it read as dividing them rather than as one of them.
code.Outdent();
code.WriteLine($"{SpellVisibility(access)}:");
code.Indent();
current = access;
}

switch (member)
try
{
foreach (AstNode member in classDecl.Members)
{
case VariableDeclaration field:
GenerateField(field, code);
break;

case FunctionDeclaration method:
GenerateFunction(method, code, classDecl.Name);
break;

default:
GenerateInternal(member, code);
break;
Visibility access = classDecl.Kind == TypeDeclarationKind.Interface
? Visibility.Public
: AccessOf(member);

// A blank line goes between two members when either says something about itself, when
// they are different kinds of thing, or where the access changes. A documented member
// needs air above it or its first comment line butts against the member before it and
// reads as belonging to that one; the member after a documented one needs the same, or it
// is swallowed into that block. Two of the same kind that say nothing stay together,
// which is what keeps a run of aliases, or of defaulted and deleted declarations, reading
// as one group rather than as four paragraphs.
if (!first && (NeedsSeparation(previous!, member) || access != current))
{
// NewLine rather than WriteLine: a separator carrying the current indent is a line of
// trailing whitespace, which every formatter strips and every diff then shows.
code.NewLine();
}

first = false;
previous = member;

if (access != current)
{
// An access label sits at the class's own indentation rather than the members', which
// is what makes it read as dividing them rather than as one of them.
code.Outdent();
code.WriteLine($"{SpellVisibility(access)}:");
code.Indent();
current = access;
}

switch (member)
{
case VariableDeclaration field:
GenerateField(field, code);
break;

case FunctionDeclaration method:
GenerateFunction(method, code, classDecl.Name);
break;

default:
GenerateInternal(member, code);
break;
}
}
}

insideType--;
finally
{
insideType--;
}
}

/// <inheritdoc/>
Expand Down
50 changes: 27 additions & 23 deletions Coder/Languages/RustGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,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 419 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 @@ -424,7 +424,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 427 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 @@ -685,34 +685,38 @@
using Scope body = new(code);

insideType++;

if (classDecl.BaseType is TypeReference baseType)
{
WriteInexpressible(code, "the base: Rust has no inheritance, so it is held rather than derived from");
code.WriteLine($"pub {BaseMemberName}: {SpellType(baseType)},");
}

foreach (AstNode member in classDecl.Members)
try
{
switch (member)
if (classDecl.BaseType is TypeReference baseType)
{
case VariableDeclaration field:
WriteUnconstructedDefault(classDecl, field.Name, field.InitialValue, code);
WriteStructMember(field.Name, field.Type, VisibilityOf(field), code);
break;

case FieldDeclaration field when !IsAssociatedField(field):
WritePreamble(field, code, PreambleSite.Field);
WriteUnconstructedDefault(classDecl, field.Name, field.InitialValue, code);
WriteStructMember(field.Name, field.Type, field.Visibility, code);
break;
WriteInexpressible(code, "the base: Rust has no inheritance, so it is held rather than derived from");
code.WriteLine($"pub {BaseMemberName}: {SpellType(baseType)},");
}

default:
break;
foreach (AstNode member in classDecl.Members)
{
switch (member)
{
case VariableDeclaration field:
WriteUnconstructedDefault(classDecl, field.Name, field.InitialValue, code);
WriteStructMember(field.Name, field.Type, VisibilityOf(field), code);
break;

case FieldDeclaration field when !IsAssociatedField(field):
WritePreamble(field, code, PreambleSite.Field);
WriteUnconstructedDefault(classDecl, field.Name, field.InitialValue, code);
WriteStructMember(field.Name, field.Type, field.Visibility, code);
break;

default:
break;
}
}
}

insideType--;
finally
{
insideType--;
}
}

/// <summary>
Expand Down Expand Up @@ -1060,7 +1064,7 @@
/// <param name="funcDecl">The declaration to emit.</param>
/// <param name="typeName">The type it belongs to.</param>
/// <param name="code">The writer to emit into.</param>
private void GenerateTraitImplementation(FunctionDeclaration funcDecl, string typeName, CodeBlocker code)

Check warning on line 1067 in Coder/Languages/RustGenerator.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 (funcDecl.Kind == FunctionKind.ConversionOperator)
{
Expand Down Expand Up @@ -1112,7 +1116,7 @@
.. operands.Select(parameter => new KeyValuePair<string, TypeReference?>(OperandName(parameter), parameter.Type)),
]);
bool rebind = receiverName != SelfName;
string self = op.ReturnsBool ? "&self" : reassigned.Contains(receiverName) && !rebind ? $"mut {SelfName}" : SelfName;

Check warning on line 1119 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 operands)
Expand Down Expand Up @@ -2008,7 +2012,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 2015 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 @@ -2071,7 +2075,7 @@

string visibility = IsAssociatedItem ? string.Empty : SpellVisibilityKeyword(field.Visibility);
string storage = IsAssociatedItem || field.IsConstant ? "const"
: field.Name is not null && WrittenStatics().Contains(field.Name) ? "static mut"

Check warning on line 2078 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.
: "static";

code.Write($"{visibility}{storage} ");
Expand Down
Loading