diff --git a/Coder.Test/Languages/FailedGenerationStateTests.cs b/Coder.Test/Languages/FailedGenerationStateTests.cs
new file mode 100644
index 0000000..a8ce532
--- /dev/null
+++ b/Coder.Test/Languages/FailedGenerationStateTests.cs
@@ -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;
+
+///
+/// A generator is registered as a singleton and the editor keeps using it after a preview fails, so
+/// a Generate call that throws inside a type must not change what the next call writes.
+///
+[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 create, AstNode failing)
+ {
+ string expected = create().Generate(FileScopeConstant());
+
+ LanguageGeneratorBase generator = create();
+ Assert.ThrowsExactly(() => generator.Generate(failing), "Precondition: the document fails inside the type.");
+
+ Assert.AreEqual(expected, generator.Generate(FileScopeConstant()), generator.DisplayName);
+ }
+
+ ///
+ /// A file holding only a static constant, whose spelling depends on whether the generator thinks
+ /// it is inside a type.
+ ///
+ 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;
+ }
+
+ ///
+ /// A class with an enum member, which C and C++ refuse once they are inside the struct.
+ ///
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+}
diff --git a/Coder/Languages/CGenerator.cs b/Coder/Languages/CGenerator.cs
index eb4c2e4..4a81947 100644
--- a/Coder/Languages/CGenerator.cs
+++ b/Coder/Languages/CGenerator.cs
@@ -640,42 +640,46 @@ .. classDecl.Members.Where(member =>
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};");
diff --git a/Coder/Languages/CppGenerator.cs b/Coder/Languages/CppGenerator.cs
index b2320e3..edbafd9 100644
--- a/Coder/Languages/CppGenerator.cs
+++ b/Coder/Languages/CppGenerator.cs
@@ -540,56 +540,61 @@ .. classDecl.Interfaces.Select(contract => $"public {MapToCppType(contract)}"),
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--;
+ }
}
///
diff --git a/Coder/Languages/RustGenerator.cs b/Coder/Languages/RustGenerator.cs
index cc4e563..c56b020 100644
--- a/Coder/Languages/RustGenerator.cs
+++ b/Coder/Languages/RustGenerator.cs
@@ -685,34 +685,38 @@ private void GenerateStruct(ClassDeclaration classDecl, string name, CodeBlocker
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--;
+ }
}
///