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
168 changes: 167 additions & 1 deletion Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,55 @@ public class NonFiniteDoubleLiteralTests
public void ANonFiniteDoubleIsSpelledInTheTargetLanguage(string language, double value, string expected) =>
Assert.AreEqual(expected, GeneratorFor(language).Generate(new LiteralExpression<double>(value)).Trim());

/// <summary>
/// Tests that each generator spells a NaN or infinite float in its own language, at single
/// precision where the language has a name for it.
/// </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#", float.NaN, "float.NaN")]
[DataRow("C#", float.PositiveInfinity, "float.PositiveInfinity")]
[DataRow("C#", float.NegativeInfinity, "float.NegativeInfinity")]
[DataRow("C++", float.NaN, "std::numeric_limits<float>::quiet_NaN()")]
[DataRow("C++", float.PositiveInfinity, "std::numeric_limits<float>::infinity()")]
[DataRow("C++", float.NegativeInfinity, "-std::numeric_limits<float>::infinity()")]
[DataRow("C", float.NaN, "NAN")]
[DataRow("C", float.PositiveInfinity, "INFINITY")]
[DataRow("C", float.NegativeInfinity, "-INFINITY")]
[DataRow("Go", float.NaN, "float32(math.NaN())")]
[DataRow("Go", float.PositiveInfinity, "float32(math.Inf(1))")]
[DataRow("Go", float.NegativeInfinity, "float32(math.Inf(-1))")]
[DataRow("Rust", float.NaN, "f32::NAN")]
[DataRow("Rust", float.PositiveInfinity, "f32::INFINITY")]
[DataRow("Rust", float.NegativeInfinity, "f32::NEG_INFINITY")]
[DataRow("Python", float.NaN, "float(\"nan\")")]
[DataRow("Python", float.PositiveInfinity, "float(\"inf\")")]
[DataRow("Python", float.NegativeInfinity, "float(\"-inf\")")]
[DataRow("JavaScript", float.NaN, "NaN")]
[DataRow("JavaScript", float.PositiveInfinity, "Infinity")]
[DataRow("JavaScript", float.NegativeInfinity, "-Infinity")]
public void ANonFiniteFloatIsSpelledInTheTargetLanguage(string language, float value, string expected) =>
Assert.AreEqual(expected, GeneratorFor(language).Generate(new LiteralExpression<float>(value)).Trim());

/// <summary>
/// Tests that a file whose only non-finite literal is a float still 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 AFileHoldingANonFiniteFloatImportsItsSpelling(string language, string import)
{
string code = GeneratorFor(language).Generate(FileReturningFloats("limits", float.NaN));

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

/// <summary>
/// Tests that a file holding a non-finite double includes or imports what its spelling needs.
/// </summary>
Expand Down Expand Up @@ -209,6 +258,75 @@ public void GeneratedRust_Compiles()
CompileIn(new RustGenerator(), "limits.rs", "rustc", "--crate-type lib --edition 2021 -o limits.rlib limits.rs");
}

/// <summary>
/// Tests that a C file returning a NaN and both infinite floats compiles.
/// </summary>
[TestMethod]
public void GeneratedCFloats_Compile()
{
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(), FloatFile(), "limits.c", compiler, "-std=c11 -Wall -Wextra -pedantic -Werror -c limits.c -o limits.o");
}

/// <summary>
/// Tests that a C++ file returning a NaN and both infinite floats compiles.
/// </summary>
[TestMethod]
public void GeneratedCppFloats_Compile()
{
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(), FloatFile(), "limits.cpp", compiler, "-std=c++20 -Wall -Wextra -pedantic -Werror -c limits.cpp -o limits.o");
}

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

CompileIn(
new GoGenerator(),
FloatFile(),
"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 a NaN and both infinite floats compiles.
/// </summary>
[TestMethod]
public void GeneratedRustFloats_Compile()
{
if (ToolchainHarness.FindOnPath("--version", "rustc") is null)
{
Assert.Inconclusive("No Rust compiler on the path, so nothing was compiled.");
return;
}

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

private static ILanguageGenerator GeneratorFor(string language) => language switch
{
"C#" => new CSharpGenerator(),
Expand Down Expand Up @@ -238,6 +356,39 @@ private static SourceFile FileReturning(string name, params double[] values)
return file;
}

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

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

return file;
}

/// <summary>
/// Builds a file returning a NaN and both infinite floats, and a function that holds one in an
/// inferred local, whose type is the one the spelling gives it.
/// </summary>
private static SourceFile FloatFile()
{
SourceFile file = FileReturningFloats("limits", float.NaN, float.PositiveInfinity, float.NegativeInfinity);

FunctionDeclaration inferred = new("inferred") { ReturnType = new TypeReference("float") };
inferred.Body.Add(new VariableDeclaration("ceiling", "float", new LiteralExpression<float>(float.PositiveInfinity)) { IsTypeInferred = true });
inferred.Body.Add(new ReturnStatement(new VariableReference("ceiling")));
file.Members.Add(inferred);

return file;
}

/// <summary>
/// Builds a file with a constant NaN field and a function holding a constant infinite local.
/// </summary>
Expand Down Expand Up @@ -268,11 +419,26 @@ private static void CompileIn(
string compiler,
string arguments,
Action<string>? prepare = null) =>
CompileIn(
generator,
FileReturning("limits", double.NaN, double.PositiveInfinity, double.NegativeInfinity),
fileName,
compiler,
arguments,
prepare);

private static void CompileIn(
ILanguageGenerator generator,
SourceFile file,
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));
string code = generator.Generate(file);
File.WriteAllText(Path.Combine(directory, fileName), code);

(int exitCode, string output) = ToolchainHarness.Run(compiler, arguments, directory);
Expand Down
2 changes: 1 addition & 1 deletion Coder/Languages/CGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,13 @@
/// 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 174 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.

Check warning on line 174 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)
{
Ensure.NotNull(file);
if (ContainsNonFiniteDouble(file))
if (ContainsNonFiniteLiteral(file))
{
yield return MathHeader;
}
Expand Down
12 changes: 11 additions & 1 deletion Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,9 @@
: SpellNonFiniteDouble(doubleLit.Value));
break;
case LiteralExpression<float> floatLit:
code.Write($"{floatLit.Value.ToString(CultureInfo.InvariantCulture)}f");
code.Write(float.IsFinite(floatLit.Value)
? $"{floatLit.Value.ToString(CultureInfo.InvariantCulture)}f"
: SpellNonFiniteSingle(floatLit.Value));
break;
case LiteralExpression<long> longLit:
code.Write($"{longLit.Value.ToString(CultureInfo.InvariantCulture)}L");
Expand Down Expand Up @@ -306,6 +308,14 @@
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "double.NaN" : value > 0 ? "double.PositiveInfinity" : "double.NegativeInfinity";

/// <inheritdoc/>
/// <remarks>
/// The constants on <see cref="float"/>, because C# does not narrow a <c>double</c> to a
/// <c>float</c> implicitly.
/// </remarks>
protected override string SpellNonFiniteSingle(float value) =>
float.IsNaN(value) ? "float.NaN" : value > 0 ? "float.PositiveInfinity" : "float.NegativeInfinity";

Check warning on line 317 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=AaExBOItTDDmFxd8Z3ul&open=AaExBOItTDDmFxd8Z3ul&pullRequest=205

/// <summary>
/// Emits a namespace and its members.
/// </summary>
Expand Down
12 changes: 11 additions & 1 deletion Coder/Languages/CppGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,24 @@
/// </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 127 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.

Check warning on line 127 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/>
/// <remarks>
/// The <c>float</c> specialisation, so an inferred local holding one is a <c>float</c> rather
/// than a <c>double</c>.
/// </remarks>
protected override string SpellNonFiniteSingle(float value) =>
float.IsNaN(value) ? "std::numeric_limits<float>::quiet_NaN()"
: value > 0 ? "std::numeric_limits<float>::infinity()"
: "-std::numeric_limits<float>::infinity()";

Check warning on line 138 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=AaExBORBTDDmFxd8Z3um&open=AaExBORBTDDmFxd8Z3um&pullRequest=205

/// <inheritdoc/>
protected override IEnumerable<string> RequiredImports(SourceFile file)
{
Ensure.NotNull(file);
if (ContainsNonFiniteDouble(file))
if (ContainsNonFiniteLiteral(file))
{
yield return LimitsHeader;
}
Expand Down
9 changes: 8 additions & 1 deletion Coder/Languages/GoGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,13 @@ protected override string GetUnaryOperatorSpelling(UnaryOperator op) =>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "math.NaN()" : value > 0 ? "math.Inf(1)" : "math.Inf(-1)";

/// <inheritdoc/>
/// <remarks>
/// The same functions converted, because they return <c>float64</c> and Go converts nothing
/// implicitly: a <c>float32</c> declared with <c>math.NaN()</c> does not compile.
/// </remarks>
protected override string SpellNonFiniteSingle(float value) => $"float32({SpellNonFiniteDouble(value)})";

/// <inheritdoc/>
/// <remarks>
/// Nothing: a Go file's imports are written with its package clause, by
Expand Down Expand Up @@ -411,7 +418,7 @@ private static List<List<string>> ImportGroups(SourceFile file)
groups[0].Add(RuntimePackage);
}

if (ContainsNonFiniteDouble(file) && !groups.Any(group => group.Contains(MathPackage)))
if (ContainsNonFiniteLiteral(file) && !groups.Any(group => group.Contains(MathPackage)))
{
groups[0].Add(MathPackage);
}
Expand Down
30 changes: 24 additions & 6 deletions Coder/Languages/LanguageGeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ protected bool TryGenerateCommonNode(AstNode node, CodeBlocker code)
return true;

case LiteralExpression<float> floatLit:
code.Write(FormatSingle(floatLit.Value));
code.Write(float.IsFinite(floatLit.Value) ? FormatSingle(floatLit.Value) : SpellNonFiniteSingle(floatLit.Value));
return true;

case LiteralExpression<long> longLit:
Expand Down Expand Up @@ -454,16 +454,21 @@ protected static IReadOnlyList<AstNode> WrittenElements(ConstructionExpression c
}

/// <summary>
/// Reports whether a file holds a double literal that is not a finite number.
/// Reports whether a file holds a double or float literal that is not a finite number.
/// </summary>
/// <param name="file">The file being emitted.</param>
/// <returns>True if any double literal in the file is NaN or an infinity.</returns>
/// <returns>True if any double or float literal in the file is NaN or an infinity.</returns>
/// <remarks>
/// What a generator asks before deciding whether the file needs the import its spelling of
/// <see cref="SpellNonFiniteDouble"/> depends on.
/// <see cref="SpellNonFiniteDouble"/> and <see cref="SpellNonFiniteSingle"/> depend on.
/// </remarks>
protected static bool ContainsNonFiniteDouble(SourceFile file) =>
SelfAndDescendants(file).Any(node => node is LiteralExpression<double> literal && !double.IsFinite(literal.Value));
protected static bool ContainsNonFiniteLiteral(SourceFile file) =>
SelfAndDescendants(file).Any(node => node switch
{
LiteralExpression<double> literal => !double.IsFinite(literal.Value),
LiteralExpression<float> literal => !float.IsFinite(literal.Value),
_ => false,
});

/// <summary>
/// Reports whether a value is one the compiler evaluates, and so one a constant can hold.
Expand Down Expand Up @@ -1169,6 +1174,19 @@ protected static string FormatDouble(double value) =>
protected virtual string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "NaN" : value > 0 ? "Infinity" : "-Infinity";

/// <summary>
/// Spells a float that is NaN or an infinity.
/// </summary>
/// <param name="value">The value to spell, which is not finite.</param>
/// <returns>The language's name for the value.</returns>
/// <remarks>
/// The double's spelling, for the targets where that name already reads as a float or where
/// there is only one width: JavaScript and Python have a single floating-point type, and C's
/// <c>NAN</c> and <c>INFINITY</c> are <c>float</c> constants to begin with. A target whose name
/// for the double would widen the value, or fail to convert back, spells the float itself.
/// </remarks>
protected virtual string SpellNonFiniteSingle(float value) => SpellNonFiniteDouble(value);

/// <summary>
/// Formats a single-precision value so that every target reads it as floating-point.
/// </summary>
Expand Down
8 changes: 8 additions & 0 deletions Coder/Languages/RustGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,16 @@
/// 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 344 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 344 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>
/// The associated constants of <c>f32</c>, since Rust does not convert an <c>f64</c> to an
/// <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 352 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 352 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 352 in Coder/Languages/RustGenerator.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=AaExBOSOTDDmFxd8Z3un&open=AaExBOSOTDDmFxd8Z3un&pullRequest=205

/// <inheritdoc/>
/// <remarks>
/// Rust has modules, so a namespace is one — and a dotted name is nested modules rather than one
Expand Down Expand Up @@ -782,7 +790,7 @@
HashSet<string> reassigned = op.ReturnsBool
? []
: ReassignedNames(funcDecl.Body, [SelfName, .. funcDecl.Parameters.Select(OperandName)]);
string self = op.ReturnsBool ? "&self" : reassigned.Contains(SelfName) ? $"mut {SelfName}" : SelfName;

Check warning on line 793 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 793 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 funcDecl.Parameters)
Expand Down
Loading