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
83 changes: 80 additions & 3 deletions Coder.Test/Languages/FailedGenerationStateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,91 @@ public void CppGenerator_AfterAFailureInsideAType_WritesWhatAFreshInstanceWrites
public void RustGenerator_AfterAFailureInsideAType_WritesWhatAFreshInstanceWrites() =>
AssertUnaffectedByFailure(() => new RustGenerator(), ClassWithAnUnknownOperatorDefault());

private static void AssertUnaffectedByFailure(Func<LanguageGeneratorBase> create, AstNode failing)
[TestMethod]
public void RustGenerator_AfterAFailureInsideATrait_WritesWhatAFreshInstanceWrites() =>
AssertUnaffectedByFailure(() => new RustGenerator(), TraitWithAnUnknownOperatorBody(), FreeFunctions);

[TestMethod]
public void RustGenerator_AfterAFailureInsideASpecialisation_WritesWhatAFreshInstanceWrites() =>
AssertUnaffectedByFailure(() => new RustGenerator(), SpecialisationWithAnUnknownOperatorBody(), FreeFunctions);

[TestMethod]
public void GoGenerator_AfterAFailureInsideAnInterface_WritesWhatAFreshInstanceWrites() =>
AssertUnaffectedByFailure(() => new GoGenerator(), InterfaceWithAnUnknownOperatorDefault(), FreeFunctions);

private static void AssertUnaffectedByFailure(Func<LanguageGeneratorBase> create, AstNode failing) =>
AssertUnaffectedByFailure(create, failing, FileScopeConstant);

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

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

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

/// <summary>
/// A file holding a free function that returns a value and one with no statements, which a
/// generator that thinks it is inside a trait or an interface writes as bare signatures.
/// </summary>
private static SourceFile FreeFunctions()
{
FunctionDeclaration answer = new("Answer") { ReturnType = TypeReference.Parse("int") };
answer.Body.Add(new ReturnStatement(1));
SourceFile file = new("m");
file.Members.Add(answer);
file.Members.Add(new FunctionDeclaration("Noop"));
return file;
}

/// <summary>
/// An expression no generator can spell, as YAML can produce from a number.
/// </summary>
private static BinaryExpression UnknownOperator() =>
new(Literal.Number(1), (BinaryOperator)999, Literal.Number(2));

/// <summary>
/// An interface whose method returns an expression Rust refuses while writing the trait.
/// </summary>
private static SourceFile TraitWithAnUnknownOperatorBody()
{
FunctionDeclaration area = new("Area") { ReturnType = TypeReference.Parse("int") };
area.Body.Add(new ReturnStatement(UnknownOperator()));
ClassDeclaration shape = new("Shape") { Kind = TypeDeclarationKind.Interface };
shape.Members.Add(area);
SourceFile file = new("m");
file.Members.Add(shape);
return file;
}

/// <summary>
/// A specialisation whose method returns an expression Rust refuses while writing the impl.
/// </summary>
private static SourceFile SpecialisationWithAnUnknownOperatorBody()
{
FunctionDeclaration area = new("Area") { ReturnType = TypeReference.Parse("int") };
area.Body.Add(new ReturnStatement(UnknownOperator()));
ClassDeclaration describe = new("Describe") { SpecialisationArguments = { new TypeReference("Box") } };
describe.Members.Add(area);
SourceFile file = new("m");
file.Members.Add(describe);
return file;
}

/// <summary>
/// An interface whose method has a default Go refuses while writing it into a comment.
/// </summary>
private static SourceFile InterfaceWithAnUnknownOperatorDefault()
{
FunctionDeclaration area = new("Area") { ReturnType = TypeReference.Parse("int") };
area.Parameters.Add(new Parameter("scale", "int") { IsOptional = true, DefaultValue = UnknownOperator() });
ClassDeclaration shape = new("Shape") { Kind = TypeDeclarationKind.Interface };
shape.Members.Add(area);
SourceFile file = new("m");
file.Members.Add(shape);
return file;
}

/// <summary>
Expand Down
25 changes: 16 additions & 9 deletions Coder/Languages/GoGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -916,20 +916,27 @@ .. classDecl.Interfaces.Select(SpellType),
code.WriteLine(contract);
}

// Restored in finally, so a member that throws cannot leave later output on this instance
// generated as interface members.
bool enclosingIsInterface = insideInterface;
insideInterface = true;

foreach (AstNode member in members)
try
{
if (member is FunctionDeclaration function)
foreach (AstNode member in members)
{
GenerateFunction(function, code, name);
continue;
}
if (member is FunctionDeclaration function)
{
GenerateFunction(function, code, name);
continue;
}

GenerateInternal(member, code);
GenerateInternal(member, code);
}
}
finally
{
insideInterface = enclosingIsInterface;
}

insideInterface = false;
}

/// <inheritdoc/>
Expand Down
50 changes: 33 additions & 17 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.

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.

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 @@ -617,9 +617,18 @@

using Scope body = new(code);

// Restored in finally, so a member that throws cannot leave later output on this instance
// generated as though it were still inside the impl.
bool enclosingIsTraitImplementation = insideTraitImplementation;
insideTraitImplementation = true;
WriteMembers(classDecl.Members, code);
insideTraitImplementation = false;
try
{
WriteMembers(classDecl.Members, code);
}
finally
{
insideTraitImplementation = enclosingIsTraitImplementation;
}
}

/// <summary>
Expand Down Expand Up @@ -1034,28 +1043,35 @@

using Scope body = new(code);

// Restored in finally, so a member that throws cannot leave later output on this instance
// generated as trait items.
bool enclosingIsTrait = insideTrait;
insideTrait = true;

bool first = true;
foreach (AstNode member in classDecl.Members.Where(member => member is FunctionDeclaration or FieldDeclaration))
try
{
if (!first)
bool first = true;
foreach (AstNode member in classDecl.Members.Where(member => member is FunctionDeclaration or FieldDeclaration))
{
code.NewLine();
}
if (!first)
{
code.NewLine();
}

first = false;
first = false;

if (member is FunctionDeclaration function)
{
GenerateFunction(function, code, name);
continue;
}
if (member is FunctionDeclaration function)
{
GenerateFunction(function, code, name);
continue;
}

GenerateInternal(member, code);
GenerateInternal(member, code);
}
}
finally
{
insideTrait = enclosingIsTrait;
}

insideTrait = false;
}

/// <summary>
Expand All @@ -1064,7 +1080,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 1083 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.

Check warning on line 1083 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 @@ -1116,7 +1132,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 1135 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.

Check warning on line 1135 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 @@ -2012,7 +2028,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 2031 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 @@ -2075,7 +2091,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 2094 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