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
2 changes: 1 addition & 1 deletion Coder.Editor/CoderEditorApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ public bool CopyGeneratedCode()
? documentPath[..^DocumentStore.Extension.Length]
: documentPath;

DocumentResult result = documents.Export(GeneratedCode, $"{stem}.{generator.FileExtension}");
DocumentResult result = documents.Export(GeneratedCode, $"{stem}.{generator.FileExtensionFor(Editor.Graph.Root)}");
if (!result.Success)
{
Status = result.Error ?? "Could not write the generated code.";
Expand Down
33 changes: 33 additions & 0 deletions Coder.Test/Editor/CoderEditorAppTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,39 @@ public void Export_UsesTheExtensionOfThePreviewedLanguage()
Assert.AreEqual(Path.Combine(root, "greeting.cpp"), app.Export(document));
}

/// <summary>
/// Tests that a document marked as a header is exported under a header's extension in C and C++,
/// and that one that is not keeps the implementation file's (issue #367).
/// </summary>
/// <remarks>
/// The export named every C++ file <c>.cpp</c> and every C file <c>.c</c>, so a header came out as
/// an implementation file starting with <c>#pragma once</c>, which an <c>#include</c> of the
/// header's name cannot find.
/// </remarks>
/// <param name="languageId">The language the pane previews.</param>
/// <param name="isHeader">Whether the document's root is marked as a header.</param>
/// <param name="extension">The extension the export should write.</param>
[TestMethod]
[DataRow("cpp", true, "hpp")]
[DataRow("cpp", false, "cpp")]
[DataRow("c", true, "h")]
[DataRow("c", false, "c")]
public void Export_NamesAHeaderDocumentAsAHeader(string languageId, bool isHeader, string extension)
{
DocumentStore store = NewStore();
CoderEditorApp app = NewApp(store, new EditorSettings { PreviewLanguageId = languageId });
SourceFile file = new("Physics") { IsHeader = isHeader };
file.Members.Add(new FieldDeclaration("limit", new TypeReference("int")) { IsConstant = true, InitialValue = Literal.Number(4) });
string document = WriteDocument(store, file, PathIn("physics"));
Assert.IsTrue(app.Open(document), app.Status);

string? written = app.Export(document);

Assert.IsNotNull(written, app.Status);
Assert.AreEqual(Path.Combine(root, $"physics.{extension}"), written);
Assert.AreEqual(isHeader, File.ReadAllText(written).Contains("#pragma once", StringComparison.Ordinal));
}

/// <summary>
/// Tests that an incomplete document is not written out, since what it would generate is not
/// source anybody wants on disk.
Expand Down
66 changes: 66 additions & 0 deletions Coder.Test/Languages/GeneratorFileExtensionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// 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>
/// Tests for the file extension each generator gives the source generated from a node (issue #367).
/// </summary>
[TestClass]
public sealed class GeneratorFileExtensionTests
{
private static ILanguageGenerator[] AllGenerators() =>
[new CSharpGenerator(), new PythonGenerator(), new CppGenerator(), new CGenerator(), new RustGenerator(), new GoGenerator(), new JavaScriptGenerator()];

/// <summary>
/// Tests that C and C++ name a header source file as a header.
/// </summary>
[TestMethod]
public void CFamily_NamesAHeaderSourceFileAsAHeader()
{
SourceFile header = new("Physics") { IsHeader = true };

Assert.AreEqual("hpp", new CppGenerator().FileExtensionFor(header));
Assert.AreEqual("h", new CGenerator().FileExtensionFor(header));
}

/// <summary>
/// Tests that a source file that is not a header, and a node that is not a source file at all,
/// keep each generator's ordinary extension.
/// </summary>
[TestMethod]
public void EveryGenerator_KeepsItsExtensionForANonHeader()
{
AstNode[] nodes = [new SourceFile("Physics"), new ClassDeclaration("Body")];

foreach (ILanguageGenerator generator in AllGenerators())
{
foreach (AstNode node in nodes)
{
Assert.AreEqual(generator.FileExtension, generator.FileExtensionFor(node), $"{generator.LanguageId} on {node.GetType().Name}");
}
}
}

/// <summary>
/// Tests that a header flag means nothing to the languages that do not split a file in two.
/// </summary>
[TestMethod]
public void NonCFamily_IgnoresTheHeaderFlag()
{
SourceFile header = new("Physics") { IsHeader = true };

foreach (ILanguageGenerator generator in AllGenerators())
{
if (generator is CFamilyGenerator)
{
continue;
}

Assert.AreEqual(generator.FileExtension, generator.FileExtensionFor(header), generator.LanguageId);
}
}
}
17 changes: 17 additions & 0 deletions Coder/Languages/CFamilyGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,23 @@ protected sealed override void GenerateFunctionDeclaration(FunctionDeclaration f
/// </remarks>
protected abstract string SpellType(TypeReference type);

/// <summary>
/// Gets the file extension (without the dot) used for a header in this language.
/// </summary>
public virtual string HeaderFileExtension => "h";

/// <inheritdoc/>
/// <remarks>
/// A <see cref="SourceFile"/> marked as a header is written with <c>#pragma once</c>, and a file
/// named as an implementation file holding one cannot be found by an <c>#include</c> of the
/// header's name and is compiled as its own translation unit by a build that globs sources.
/// </remarks>
public override string FileExtensionFor(AstNode astNode)
{
Ensure.NotNull(astNode);
return astNode is SourceFile { IsHeader: true } ? HeaderFileExtension : FileExtension;
}

/// <inheritdoc/>
/// <remarks>
/// <c>#pragma once</c> rather than an include guard, for the reason a guard cannot answer: the
Expand Down
6 changes: 6 additions & 0 deletions Coder/Languages/CppGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@
/// </summary>
public override string FileExtension => "cpp";

/// <inheritdoc/>
/// <remarks>
/// <c>.hpp</c> rather than <c>.h</c>, so a C++ header is not mistaken for one a C compiler can read.
/// </remarks>
public override string HeaderFileExtension => "hpp";

/// <summary>
/// Writes the template head a declaration written over types needs.
/// </summary>
Expand Down Expand Up @@ -163,7 +169,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 172 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 +179,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 182 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 +263,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 266 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 @@ -471,7 +477,7 @@
/// describing a scope.
/// </para>
/// </remarks>
protected override void GenerateClassDeclaration(ClassDeclaration classDecl, CodeBlocker code)

Check warning on line 480 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(classDecl);
Ensure.NotNull(code);
Expand Down
11 changes: 11 additions & 0 deletions Coder/Languages/ILanguageGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@ public interface ILanguageGenerator
/// </summary>
public string FileExtension { get; }

/// <summary>
/// Gets the file extension (without the dot) for the source generated from a particular node.
/// </summary>
/// <param name="astNode">The AST node the source is generated from.</param>
/// <returns>The extension a file holding that source should have.</returns>
/// <remarks>
/// Usually <see cref="FileExtension"/>. A language that splits a program into headers and
/// implementation files names the two differently, and only the node says which one it is.
/// </remarks>
public string FileExtensionFor(AstNode astNode) => FileExtension;

/// <summary>
/// Generates code in the target language from an AST node.
/// </summary>
Expand Down
7 changes: 7 additions & 0 deletions Coder/Languages/LanguageGeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@
/// </summary>
public abstract string FileExtension { get; }

/// <inheritdoc/>
public virtual string FileExtensionFor(AstNode astNode)
{
Ensure.NotNull(astNode);
return FileExtension;
}

/// <summary>
/// Generates code in the target language from an AST node.
/// </summary>
Expand Down Expand Up @@ -399,7 +406,7 @@
}
}

foreach (object item in expected)

Check warning on line 409 in Coder/Languages/LanguageGeneratorBase.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Loops should be simplified using the "Where" LINQ method

Check warning on line 409 in Coder/Languages/LanguageGeneratorBase.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Loops should be simplified using the "Where" LINQ method
{
if (!emittedPreambleItems!.Contains(item))
{
Expand All @@ -417,7 +424,7 @@
/// Read off the nodes' public properties rather than a list of node types, so a node added to the
/// AST is walked without anybody remembering to add it here.
/// </remarks>
protected static IEnumerable<AstNode> SelfAndDescendants(AstNode root)

Check warning on line 427 in Coder/Languages/LanguageGeneratorBase.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

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

Check warning on line 427 in Coder/Languages/LanguageGeneratorBase.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 26 to the 15 allowed.
{
HashSet<AstNode> visited = new(ReferenceEqualityComparer.Instance);
Stack<AstNode> pending = new();
Expand Down Expand Up @@ -1334,7 +1341,7 @@
/// the generator adds through <see cref="RequiredImports"/>.
/// </remarks>
protected virtual string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "NaN" : value > 0 ? "Infinity" : "-Infinity";

Check warning on line 1344 in Coder/Languages/LanguageGeneratorBase.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

/// <summary>
/// Spells a float that is NaN or an infinity.
Expand Down Expand Up @@ -1445,7 +1452,7 @@
string? origin = null;
long offset = 0;

foreach (EnumMember member in enumDecl.Members)

Check warning on line 1455 in Coder/Languages/LanguageGeneratorBase.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Loop should be simplified by calling Select(member => member.Value)
{
if (member.Value is not null)
{
Expand Down
Loading