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
221 changes: 221 additions & 0 deletions Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
// 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 that a double literal that is NaN or an infinity is written as a name the target language
/// knows, and that a file holding one imports what that name needs.
/// </summary>
/// <remarks>
/// Round-trip formatting gives <c>NaN</c>, <c>Infinity</c> and <c>-Infinity</c>, which is JavaScript
/// and nothing else: every other target read them as undefined names, and C# as the tokens
/// <c>NaNd</c> and <c>Infinityd</c>.
/// </remarks>
[TestClass]
public class NonFiniteDoubleLiteralTests
{
/// <summary>
/// Tests that each generator spells NaN, positive infinity and negative infinity in its own
/// language.
/// </summary>
/// <param name="language">The generator's display name.</param>
/// <param name="value">The value to write.</param>
/// <param name="expected">What the generator should write.</param>
[TestMethod]
[DataRow("C#", double.NaN, "double.NaN")]
[DataRow("C#", double.PositiveInfinity, "double.PositiveInfinity")]
[DataRow("C#", double.NegativeInfinity, "double.NegativeInfinity")]
[DataRow("C++", double.NaN, "std::numeric_limits<double>::quiet_NaN()")]
[DataRow("C++", double.PositiveInfinity, "std::numeric_limits<double>::infinity()")]
[DataRow("C++", double.NegativeInfinity, "-std::numeric_limits<double>::infinity()")]
[DataRow("C", double.NaN, "NAN")]
[DataRow("C", double.PositiveInfinity, "INFINITY")]
[DataRow("C", double.NegativeInfinity, "-INFINITY")]
[DataRow("Go", double.NaN, "math.NaN()")]
[DataRow("Go", double.PositiveInfinity, "math.Inf(1)")]
[DataRow("Go", double.NegativeInfinity, "math.Inf(-1)")]
[DataRow("Rust", double.NaN, "f64::NAN")]
[DataRow("Rust", double.PositiveInfinity, "f64::INFINITY")]
[DataRow("Rust", double.NegativeInfinity, "f64::NEG_INFINITY")]
[DataRow("Python", double.NaN, "float(\"nan\")")]
[DataRow("Python", double.PositiveInfinity, "float(\"inf\")")]
[DataRow("Python", double.NegativeInfinity, "float(\"-inf\")")]
[DataRow("JavaScript", double.NaN, "NaN")]
[DataRow("JavaScript", double.PositiveInfinity, "Infinity")]
[DataRow("JavaScript", double.NegativeInfinity, "-Infinity")]
public void ANonFiniteDoubleIsSpelledInTheTargetLanguage(string language, double value, string expected) =>
Assert.AreEqual(expected, GeneratorFor(language).Generate(new LiteralExpression<double>(value)).Trim());

/// <summary>
/// Tests that a file holding a non-finite double includes or imports what its spelling needs.
/// </summary>
/// <param name="language">The generator's display name.</param>
/// <param name="import">The line the file should carry.</param>
[TestMethod]
[DataRow("C", "#include <math.h>")]
[DataRow("C++", "#include <limits>")]
[DataRow("Go", "import \"math\"")]
public void AFileHoldingANonFiniteDoubleImportsItsSpelling(string language, string import)
{
string code = GeneratorFor(language).Generate(FileReturning("limits", double.PositiveInfinity));

Assert.AreEqual(1, Occurrences(code, import), code);
}

/// <summary>
/// Tests that a file already importing what the spelling needs does not import it twice.
/// </summary>
/// <param name="language">The generator's display name.</param>
/// <param name="fileImport">The import as the file carries it.</param>
/// <param name="import">The line the file should carry once.</param>
[TestMethod]
[DataRow("C", "<math.h>", "#include <math.h>")]
[DataRow("C++", "<limits>", "#include <limits>")]
[DataRow("Go", "math", "import \"math\"")]
public void AnImportTheFileAlreadyHasIsWrittenOnce(string language, string fileImport, string import)
{
SourceFile file = FileReturning("limits", double.NaN);
file.Imports.Add(fileImport);

string code = GeneratorFor(language).Generate(file);

Assert.AreEqual(1, Occurrences(code, import), code);
}

/// <summary>
/// Tests that a file holding only finite doubles gets no import it did not ask for.
/// </summary>
/// <param name="language">The generator's display name.</param>
/// <param name="header">Text that would appear only if the import were added.</param>
[TestMethod]
[DataRow("C", "math.h")]
[DataRow("C++", "<limits>")]
[DataRow("Go", "\"math\"")]
public void AFileOfFiniteDoublesImportsNothing(string language, string header)
{
string code = GeneratorFor(language).Generate(FileReturning("limits", 0.5));

Assert.DoesNotContain(header, code, StringComparison.Ordinal, code);
}

/// <summary>
/// Tests that a C file returning NaN and both infinities compiles.
/// </summary>
[TestMethod]
public void GeneratedC_Compiles()
{
string? compiler = ToolchainHarness.FindOnPath("--version", "cc", "gcc", "clang");
if (compiler is null)
{
Assert.Inconclusive("No C compiler on the path, so nothing was compiled.");
return;
}

CompileIn(new CGenerator(), "limits.c", compiler, "-std=c11 -Wall -Wextra -pedantic -c limits.c -o limits.o");
}

/// <summary>
/// Tests that a C++ file returning NaN and both infinities compiles.
/// </summary>
[TestMethod]
public void GeneratedCpp_Compiles()
{
string? compiler = ToolchainHarness.FindOnPath("--version", "c++", "g++", "clang++");
if (compiler is null)
{
Assert.Inconclusive("No C++ compiler on the path, so nothing was compiled.");
return;
}

CompileIn(new CppGenerator(), "limits.cpp", compiler, "-std=c++20 -Wall -Wextra -pedantic -c limits.cpp -o limits.o");
}

/// <summary>
/// Tests that a Go file returning NaN and both infinities compiles.
/// </summary>
[TestMethod]
public void GeneratedGo_Compiles()
{
if (ToolchainHarness.FindOnPath("version", "go") is null)
{
Assert.Inconclusive("No Go toolchain on the path, so nothing was compiled.");
return;
}

CompileIn(
new GoGenerator(),
"limits.go",
"go",
"build ./...",
directory => File.WriteAllText(Path.Combine(directory, "go.mod"), "module limits\n\ngo 1.21\n"));
}

/// <summary>
/// Tests that a Rust file returning NaN and both infinities compiles.
/// </summary>
[TestMethod]
public void GeneratedRust_Compiles()
{
if (ToolchainHarness.FindOnPath("--version", "rustc") is null)
{
Assert.Inconclusive("No Rust compiler on the path, so nothing was compiled.");
return;
}

CompileIn(new RustGenerator(), "limits.rs", "rustc", "--crate-type lib --edition 2021 -o limits.rlib limits.rs");
}

private static ILanguageGenerator GeneratorFor(string language) => language switch
{
"C#" => new CSharpGenerator(),
"C++" => new CppGenerator(),
"C" => new CGenerator(),
"Go" => new GoGenerator(),
"Rust" => new RustGenerator(),
"Python" => new PythonGenerator(),
"JavaScript" => new JavaScriptGenerator(),
_ => throw new ArgumentOutOfRangeException(nameof(language), language, null),
};

/// <summary>
/// Builds a file with one function returning each of the given values.
/// </summary>
private static SourceFile FileReturning(string name, params double[] values)
{
SourceFile file = new(name);

for (int index = 0; index < values.Length; index++)
{
FunctionDeclaration function = new($"value{index}") { ReturnType = new TypeReference("double") };
function.Body.Add(new ReturnStatement(new LiteralExpression<double>(values[index])));
file.Members.Add(function);
}

return file;
}

private static int Occurrences(string text, string value) =>
text.Split(value, StringSplitOptions.None).Length - 1;

private static void CompileIn(
ILanguageGenerator generator,
string fileName,
string compiler,
string arguments,
Action<string>? prepare = null) =>
ToolchainHarness.InTemporaryDirectory(directory =>
{
prepare?.Invoke(directory);

string code = generator.Generate(FileReturning("limits", double.NaN, double.PositiveInfinity, double.NegativeInfinity));
File.WriteAllText(Path.Combine(directory, fileName), code);

(int exitCode, string output) = ToolchainHarness.Run(compiler, arguments, directory);

Assert.AreEqual(0, exitCode, $"{compiler} rejected the generated source:{Environment.NewLine}{code}{Environment.NewLine}{output}");
});
}
22 changes: 22 additions & 0 deletions Coder/Languages/CGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,28 @@
/// </remarks>
protected override NamingStyle MemberNaming => NamingStyle.Snake;

/// <inheritdoc/>
/// <remarks>
/// 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 169 in Coder/Languages/CGenerator.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaELuszzxT0DP8xqggBO&open=AaELuszzxT0DP8xqggBO&pullRequest=147

/// <inheritdoc/>
protected override IEnumerable<string> RequiredImports(SourceFile file)
{
Ensure.NotNull(file);
if (ContainsNonFiniteDouble(file))
{
yield return MathHeader;
}
}

/// <summary>
/// The header that declares <c>NAN</c> and <c>INFINITY</c>.
/// </summary>
private const string MathHeader = "<math.h>";

/// <inheritdoc/>
/// <remarks>
/// C has no member functions, so a member becomes a free function named for the type it belongs
Expand Down
11 changes: 10 additions & 1 deletion Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@
code.Write(boolLit.Value ? "true" : "false");
break;
case LiteralExpression<double> doubleLit:
code.Write($"{doubleLit.Value.ToString(CultureInfo.InvariantCulture)}d");
code.Write(double.IsFinite(doubleLit.Value)
? $"{doubleLit.Value.ToString(CultureInfo.InvariantCulture)}d"
: SpellNonFiniteDouble(doubleLit.Value));
break;
case LiteralExpression<float> floatLit:
code.Write($"{floatLit.Value.ToString(CultureInfo.InvariantCulture)}f");
Expand Down Expand Up @@ -297,6 +299,13 @@
/// <inheritdoc/>
protected override string? SpellImport(string import) => $"using {import};";

/// <inheritdoc/>
/// <remarks>
/// 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 307 in Coder/Languages/CSharpGenerator.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaELusp9xT0DP8xqggBL&open=AaELusp9xT0DP8xqggBL&pullRequest=147

/// <summary>
/// Emits a namespace and its members.
/// </summary>
Expand Down
25 changes: 25 additions & 0 deletions Coder/Languages/CppGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,31 @@
/// makes writing a caller's attribute through safe here.
/// </remarks>
protected override string? SpellAnnotation(Annotation annotation, PreambleSite site) => $"[[{annotation}]]";
/// <inheritdoc/>
/// <remarks>
/// <c>std::numeric_limits</c> rather than C's macros, because they are constant expressions of type
/// <c>double</c> rather than <c>float</c>, and need only <c>&lt;limits&gt;</c>.
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "std::numeric_limits<double>::quiet_NaN()"
: value > 0 ? "std::numeric_limits<double>::infinity()"
: "-std::numeric_limits<double>::infinity()";

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaELus22xT0DP8xqggBR&open=AaELus22xT0DP8xqggBR&pullRequest=147

/// <inheritdoc/>
protected override IEnumerable<string> RequiredImports(SourceFile file)
{
Ensure.NotNull(file);
if (ContainsNonFiniteDouble(file))
{
yield return LimitsHeader;
}
}

/// <summary>
/// The header that declares <c>std::numeric_limits</c>.
/// </summary>
private const string LimitsHeader = "<limits>";

/// <inheritdoc/>
/// <remarks>
/// A constructor and a destructor are named after the type rather than after themselves, so the
Expand Down
18 changes: 18 additions & 0 deletions Coder/Languages/GoGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
/// </summary>
private const string RuntimePackage = "\"os\"";

/// <summary>
/// The package that spells NaN and the infinities, quoted as an import line.
/// </summary>
private const string MathPackage = "\"math\"";

/// <summary>
/// How Go spells a string.
/// </summary>
Expand Down Expand Up @@ -258,6 +263,14 @@
protected override string GetUnaryOperatorSpelling(UnaryOperator op) =>
op == UnaryOperator.BitwiseNot ? "^" : GetUnaryOperator(op);

/// <inheritdoc/>
/// <remarks>
/// The <c>math</c> package's functions, which <see cref="ImportGroups"/> imports for a file that
/// holds one.
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "math.NaN()" : value > 0 ? "math.Inf(1)" : "math.Inf(-1)";

Check warning on line 272 in Coder/Languages/GoGenerator.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaELus0vxT0DP8xqggBQ&open=AaELus0vxT0DP8xqggBQ&pullRequest=147

/// <inheritdoc/>
/// <remarks>
/// Nothing: a Go file's imports are written with its package clause, by
Expand Down Expand Up @@ -398,6 +411,11 @@
groups[0].Add(RuntimePackage);
}

if (ContainsNonFiniteDouble(file) && !groups.Any(group => group.Contains(MathPackage)))
{
groups[0].Add(MathPackage);
}

foreach (List<string> group in groups)
{
group.Sort((left, right) => string.CompareOrdinal(ImportPath(left), ImportPath(right)));
Expand Down
Loading
Loading