diff --git a/Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs b/Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs index 3838132..51756d1 100644 --- a/Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs +++ b/Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs @@ -50,6 +50,55 @@ public class NonFiniteDoubleLiteralTests public void ANonFiniteDoubleIsSpelledInTheTargetLanguage(string language, double value, string expected) => Assert.AreEqual(expected, GeneratorFor(language).Generate(new LiteralExpression(value)).Trim()); + /// + /// 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. + /// + /// The generator's display name. + /// The value to write. + /// What the generator should write. + [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::quiet_NaN()")] + [DataRow("C++", float.PositiveInfinity, "std::numeric_limits::infinity()")] + [DataRow("C++", float.NegativeInfinity, "-std::numeric_limits::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(value)).Trim()); + + /// + /// Tests that a file whose only non-finite literal is a float still imports what its spelling + /// needs. + /// + /// The generator's display name. + /// The line the file should carry. + [TestMethod] + [DataRow("C", "#include ")] + [DataRow("C++", "#include ")] + [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); + } + /// /// Tests that a file holding a non-finite double includes or imports what its spelling needs. /// @@ -209,6 +258,75 @@ public void GeneratedRust_Compiles() CompileIn(new RustGenerator(), "limits.rs", "rustc", "--crate-type lib --edition 2021 -o limits.rlib limits.rs"); } + /// + /// Tests that a C file returning a NaN and both infinite floats compiles. + /// + [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"); + } + + /// + /// Tests that a C++ file returning a NaN and both infinite floats compiles. + /// + [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"); + } + + /// + /// Tests that a Go file returning a NaN and both infinite floats, and declaring an inferred + /// local holding one, compiles. + /// + [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")); + } + + /// + /// Tests that a Rust file returning a NaN and both infinite floats compiles. + /// + [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(), @@ -238,6 +356,39 @@ private static SourceFile FileReturning(string name, params double[] values) return file; } + /// + /// Builds a file with one function returning each of the given floats. + /// + 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(values[index]))); + file.Members.Add(function); + } + + return file; + } + + /// + /// 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. + /// + 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.PositiveInfinity)) { IsTypeInferred = true }); + inferred.Body.Add(new ReturnStatement(new VariableReference("ceiling"))); + file.Members.Add(inferred); + + return file; + } + /// /// Builds a file with a constant NaN field and a function holding a constant infinite local. /// @@ -268,11 +419,26 @@ private static void CompileIn( string compiler, string arguments, Action? 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? 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); diff --git a/Coder/Languages/CGenerator.cs b/Coder/Languages/CGenerator.cs index 6d1e77b..53a28e8 100644 --- a/Coder/Languages/CGenerator.cs +++ b/Coder/Languages/CGenerator.cs @@ -177,7 +177,7 @@ protected override string SpellNonFiniteDouble(double value) => protected override IEnumerable RequiredImports(SourceFile file) { Ensure.NotNull(file); - if (ContainsNonFiniteDouble(file)) + if (ContainsNonFiniteLiteral(file)) { yield return MathHeader; } diff --git a/Coder/Languages/CSharpGenerator.cs b/Coder/Languages/CSharpGenerator.cs index 473325d..0a750cc 100644 --- a/Coder/Languages/CSharpGenerator.cs +++ b/Coder/Languages/CSharpGenerator.cs @@ -108,7 +108,9 @@ private void GenerateExpressionOrLeaf(AstNode node, CodeBlocker code) : SpellNonFiniteDouble(doubleLit.Value)); break; case LiteralExpression 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 longLit: code.Write($"{longLit.Value.ToString(CultureInfo.InvariantCulture)}L"); @@ -306,6 +308,14 @@ private static IEnumerable InDeclarationOrder(IEnumerable double.IsNaN(value) ? "double.NaN" : value > 0 ? "double.PositiveInfinity" : "double.NegativeInfinity"; + /// + /// + /// The constants on , because C# does not narrow a double to a + /// float implicitly. + /// + protected override string SpellNonFiniteSingle(float value) => + float.IsNaN(value) ? "float.NaN" : value > 0 ? "float.PositiveInfinity" : "float.NegativeInfinity"; + /// /// Emits a namespace and its members. /// diff --git a/Coder/Languages/CppGenerator.cs b/Coder/Languages/CppGenerator.cs index a25e8a3..0c08650 100644 --- a/Coder/Languages/CppGenerator.cs +++ b/Coder/Languages/CppGenerator.cs @@ -127,11 +127,21 @@ protected override string SpellNonFiniteDouble(double value) => : value > 0 ? "std::numeric_limits::infinity()" : "-std::numeric_limits::infinity()"; + /// + /// + /// The float specialisation, so an inferred local holding one is a float rather + /// than a double. + /// + protected override string SpellNonFiniteSingle(float value) => + float.IsNaN(value) ? "std::numeric_limits::quiet_NaN()" + : value > 0 ? "std::numeric_limits::infinity()" + : "-std::numeric_limits::infinity()"; + /// protected override IEnumerable RequiredImports(SourceFile file) { Ensure.NotNull(file); - if (ContainsNonFiniteDouble(file)) + if (ContainsNonFiniteLiteral(file)) { yield return LimitsHeader; } diff --git a/Coder/Languages/GoGenerator.cs b/Coder/Languages/GoGenerator.cs index 1c200d1..011b8a7 100644 --- a/Coder/Languages/GoGenerator.cs +++ b/Coder/Languages/GoGenerator.cs @@ -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)"; + /// + /// + /// The same functions converted, because they return float64 and Go converts nothing + /// implicitly: a float32 declared with math.NaN() does not compile. + /// + protected override string SpellNonFiniteSingle(float value) => $"float32({SpellNonFiniteDouble(value)})"; + /// /// /// Nothing: a Go file's imports are written with its package clause, by @@ -411,7 +418,7 @@ private static List> 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); } diff --git a/Coder/Languages/LanguageGeneratorBase.cs b/Coder/Languages/LanguageGeneratorBase.cs index 222686f..02830fd 100644 --- a/Coder/Languages/LanguageGeneratorBase.cs +++ b/Coder/Languages/LanguageGeneratorBase.cs @@ -162,7 +162,7 @@ protected bool TryGenerateCommonNode(AstNode node, CodeBlocker code) return true; case LiteralExpression floatLit: - code.Write(FormatSingle(floatLit.Value)); + code.Write(float.IsFinite(floatLit.Value) ? FormatSingle(floatLit.Value) : SpellNonFiniteSingle(floatLit.Value)); return true; case LiteralExpression longLit: @@ -454,16 +454,21 @@ protected static IReadOnlyList WrittenElements(ConstructionExpression c } /// - /// 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. /// /// The file being emitted. - /// True if any double literal in the file is NaN or an infinity. + /// True if any double or float literal in the file is NaN or an infinity. /// /// What a generator asks before deciding whether the file needs the import its spelling of - /// depends on. + /// and depend on. /// - protected static bool ContainsNonFiniteDouble(SourceFile file) => - SelfAndDescendants(file).Any(node => node is LiteralExpression literal && !double.IsFinite(literal.Value)); + protected static bool ContainsNonFiniteLiteral(SourceFile file) => + SelfAndDescendants(file).Any(node => node switch + { + LiteralExpression literal => !double.IsFinite(literal.Value), + LiteralExpression literal => !float.IsFinite(literal.Value), + _ => false, + }); /// /// Reports whether a value is one the compiler evaluates, and so one a constant can hold. @@ -1169,6 +1174,19 @@ protected static string FormatDouble(double value) => protected virtual string SpellNonFiniteDouble(double value) => double.IsNaN(value) ? "NaN" : value > 0 ? "Infinity" : "-Infinity"; + /// + /// Spells a float that is NaN or an infinity. + /// + /// The value to spell, which is not finite. + /// The language's name for the value. + /// + /// 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 + /// NAN and INFINITY are float constants to begin with. A target whose name + /// for the double would widen the value, or fail to convert back, spells the float itself. + /// + protected virtual string SpellNonFiniteSingle(float value) => SpellNonFiniteDouble(value); + /// /// Formats a single-precision value so that every target reads it as floating-point. /// diff --git a/Coder/Languages/RustGenerator.cs b/Coder/Languages/RustGenerator.cs index 347bf9c..1d29e4f 100644 --- a/Coder/Languages/RustGenerator.cs +++ b/Coder/Languages/RustGenerator.cs @@ -343,6 +343,14 @@ private sealed record OperatorTrait(string Name, string Method, bool ReturnsBool protected override string SpellNonFiniteDouble(double value) => double.IsNaN(value) ? "f64::NAN" : value > 0 ? "f64::INFINITY" : "f64::NEG_INFINITY"; + /// + /// + /// The associated constants of f32, since Rust does not convert an f64 to an + /// f32 implicitly. + /// + protected override string SpellNonFiniteSingle(float value) => + float.IsNaN(value) ? "f32::NAN" : value > 0 ? "f32::INFINITY" : "f32::NEG_INFINITY"; + /// /// /// Rust has modules, so a namespace is one — and a dotted name is nested modules rather than one