diff --git a/Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs b/Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs new file mode 100644 index 0000000..83957ef --- /dev/null +++ b/Coder.Test/Languages/NonFiniteDoubleLiteralTests.cs @@ -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; + +/// +/// 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. +/// +/// +/// Round-trip formatting gives NaN, Infinity and -Infinity, which is JavaScript +/// and nothing else: every other target read them as undefined names, and C# as the tokens +/// NaNd and Infinityd. +/// +[TestClass] +public class NonFiniteDoubleLiteralTests +{ + /// + /// Tests that each generator spells NaN, positive infinity and negative infinity in its own + /// language. + /// + /// The generator's display name. + /// The value to write. + /// What the generator should write. + [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::quiet_NaN()")] + [DataRow("C++", double.PositiveInfinity, "std::numeric_limits::infinity()")] + [DataRow("C++", double.NegativeInfinity, "-std::numeric_limits::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(value)).Trim()); + + /// + /// Tests that a file holding a non-finite double includes or 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 AFileHoldingANonFiniteDoubleImportsItsSpelling(string language, string import) + { + string code = GeneratorFor(language).Generate(FileReturning("limits", double.PositiveInfinity)); + + Assert.AreEqual(1, Occurrences(code, import), code); + } + + /// + /// Tests that a file already importing what the spelling needs does not import it twice. + /// + /// The generator's display name. + /// The import as the file carries it. + /// The line the file should carry once. + [TestMethod] + [DataRow("C", "", "#include ")] + [DataRow("C++", "", "#include ")] + [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); + } + + /// + /// Tests that a file holding only finite doubles gets no import it did not ask for. + /// + /// The generator's display name. + /// Text that would appear only if the import were added. + [TestMethod] + [DataRow("C", "math.h")] + [DataRow("C++", "")] + [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); + } + + /// + /// Tests that a C file returning NaN and both infinities compiles. + /// + [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"); + } + + /// + /// Tests that a C++ file returning NaN and both infinities compiles. + /// + [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"); + } + + /// + /// Tests that a Go file returning NaN and both infinities compiles. + /// + [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")); + } + + /// + /// Tests that a Rust file returning NaN and both infinities compiles. + /// + [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), + }; + + /// + /// Builds a file with one function returning each of the given values. + /// + 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(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? 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}"); + }); +} diff --git a/Coder/Languages/CGenerator.cs b/Coder/Languages/CGenerator.cs index 0d02350..a0f6dcc 100644 --- a/Coder/Languages/CGenerator.cs +++ b/Coder/Languages/CGenerator.cs @@ -161,6 +161,28 @@ private static string SnakeCase(string name) => /// protected override NamingStyle MemberNaming => NamingStyle.Snake; + /// + /// + /// The <math.h> macros, which is why a file holding one includes it. + /// + protected override string SpellNonFiniteDouble(double value) => + double.IsNaN(value) ? "NAN" : value > 0 ? "INFINITY" : "-INFINITY"; + + /// + protected override IEnumerable RequiredImports(SourceFile file) + { + Ensure.NotNull(file); + if (ContainsNonFiniteDouble(file)) + { + yield return MathHeader; + } + } + + /// + /// The header that declares NAN and INFINITY. + /// + private const string MathHeader = ""; + /// /// /// C has no member functions, so a member becomes a free function named for the type it belongs diff --git a/Coder/Languages/CSharpGenerator.cs b/Coder/Languages/CSharpGenerator.cs index d4325a4..772f358 100644 --- a/Coder/Languages/CSharpGenerator.cs +++ b/Coder/Languages/CSharpGenerator.cs @@ -103,7 +103,9 @@ private void GenerateExpressionOrLeaf(AstNode node, CodeBlocker code) code.Write(boolLit.Value ? "true" : "false"); break; case LiteralExpression 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 floatLit: code.Write($"{floatLit.Value.ToString(CultureInfo.InvariantCulture)}f"); @@ -297,6 +299,13 @@ private static IEnumerable InDeclarationOrder(IEnumerable protected override string? SpellImport(string import) => $"using {import};"; + /// + /// + /// The constants on , which every file can name without a using. + /// + protected override string SpellNonFiniteDouble(double value) => + double.IsNaN(value) ? "double.NaN" : value > 0 ? "double.PositiveInfinity" : "double.NegativeInfinity"; + /// /// Emits a namespace and its members. /// diff --git a/Coder/Languages/CppGenerator.cs b/Coder/Languages/CppGenerator.cs index d0c36cf..a25e8a3 100644 --- a/Coder/Languages/CppGenerator.cs +++ b/Coder/Languages/CppGenerator.cs @@ -117,6 +117,31 @@ private static void WriteTemplateHead(IEnumerable parameters, Cod /// makes writing a caller's attribute through safe here. /// protected override string? SpellAnnotation(Annotation annotation, PreambleSite site) => $"[[{annotation}]]"; + /// + /// + /// std::numeric_limits rather than C's macros, because they are constant expressions of type + /// double rather than float, and need only <limits>. + /// + protected override string SpellNonFiniteDouble(double value) => + double.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)) + { + yield return LimitsHeader; + } + } + + /// + /// The header that declares std::numeric_limits. + /// + private const string LimitsHeader = ""; + /// /// /// A constructor and a destructor are named after the type rather than after themselves, so the diff --git a/Coder/Languages/GoGenerator.cs b/Coder/Languages/GoGenerator.cs index 333baac..18c6a95 100644 --- a/Coder/Languages/GoGenerator.cs +++ b/Coder/Languages/GoGenerator.cs @@ -117,6 +117,11 @@ public class GoGenerator : StandardLanguageGenerator /// private const string RuntimePackage = "\"os\""; + /// + /// The package that spells NaN and the infinities, quoted as an import line. + /// + private const string MathPackage = "\"math\""; + /// /// How Go spells a string. /// @@ -258,6 +263,14 @@ protected override void EndStatement(CodeBlocker code) protected override string GetUnaryOperatorSpelling(UnaryOperator op) => op == UnaryOperator.BitwiseNot ? "^" : GetUnaryOperator(op); + /// + /// + /// The math package's functions, which imports for a file that + /// holds one. + /// + protected override string SpellNonFiniteDouble(double value) => + double.IsNaN(value) ? "math.NaN()" : value > 0 ? "math.Inf(1)" : "math.Inf(-1)"; + /// /// /// Nothing: a Go file's imports are written with its package clause, by @@ -398,6 +411,11 @@ private static List> ImportGroups(SourceFile file) groups[0].Add(RuntimePackage); } + if (ContainsNonFiniteDouble(file) && !groups.Any(group => group.Contains(MathPackage))) + { + groups[0].Add(MathPackage); + } + foreach (List group in groups) { group.Sort((left, right) => string.CompareOrdinal(ImportPath(left), ImportPath(right))); diff --git a/Coder/Languages/LanguageGeneratorBase.cs b/Coder/Languages/LanguageGeneratorBase.cs index eb5e349..e2cd014 100644 --- a/Coder/Languages/LanguageGeneratorBase.cs +++ b/Coder/Languages/LanguageGeneratorBase.cs @@ -158,7 +158,7 @@ protected bool TryGenerateCommonNode(AstNode node, CodeBlocker code) return true; case LiteralExpression doubleLit: - code.Write(FormatDouble(doubleLit.Value)); + code.Write(double.IsFinite(doubleLit.Value) ? FormatDouble(doubleLit.Value) : SpellNonFiniteDouble(doubleLit.Value)); return true; case LiteralExpression floatLit: @@ -352,17 +352,9 @@ protected void RememberAnnotationClone(Annotation clone, Annotation original) private void EnsureConserved(AstNode root) { HashSet expected = new(ReferenceEqualityComparer.Instance); - HashSet visited = new(ReferenceEqualityComparer.Instance); - Stack pending = new(); - pending.Push(root); - while (pending.TryPop(out AstNode? node)) + foreach (AstNode node in SelfAndDescendants(root)) { - if (!visited.Add(node)) - { - continue; - } - if (node is IHasDocumentation documented) { foreach (string line in documented.Documentation) @@ -375,6 +367,40 @@ private void EnsureConserved(AstNode root) { expected.Add(annotation); } + } + + foreach (object item in expected) + { + if (!emittedPreambleItems!.Contains(item)) + { + throw new InvalidOperationException($"{item} was dropped by {DisplayName}."); + } + } + } + + /// + /// Lists a node and every node beneath it, each once. + /// + /// The node to start from. + /// The root, then the nodes under it, in no particular order. + /// + /// 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. + /// + protected static IEnumerable SelfAndDescendants(AstNode root) + { + HashSet visited = new(ReferenceEqualityComparer.Instance); + Stack pending = new(); + pending.Push(root); + + while (pending.TryPop(out AstNode? node)) + { + if (!visited.Add(node)) + { + continue; + } + + yield return node; if (node is AstCompositeNode composite) { @@ -408,16 +434,20 @@ private void EnsureConserved(AstNode root) } } } - - foreach (object item in expected) - { - if (!emittedPreambleItems!.Contains(item)) - { - throw new InvalidOperationException($"{item} was dropped by {DisplayName}."); - } - } } + /// + /// Reports whether a file holds a double literal that is not a finite number. + /// + /// The file being emitted. + /// True if any double 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. + /// + protected static bool ContainsNonFiniteDouble(SourceFile file) => + SelfAndDescendants(file).Any(node => node is LiteralExpression literal && !double.IsFinite(literal.Value)); + /// /// Writes down the types a declaration is written over, for a target that has no generics. /// @@ -910,7 +940,7 @@ protected void GenerateUnaryExpression(UnaryExpression unaryExpr, CodeBlocker co private static char? LeadingSign(AstNode? node) => node switch { LiteralExpression { Value: < 0 } => '-', - LiteralExpression doubleLit when double.IsNegative(doubleLit.Value) => '-', + LiteralExpression doubleLit when double.IsNegative(doubleLit.Value) && !double.IsNaN(doubleLit.Value) => '-', LiteralExpression floatLit when float.IsNegative(floatLit.Value) => '-', LiteralExpression { Value: < 0 } => '-', AstLeafNode { Value: < 0 } => '-', @@ -1080,11 +1110,26 @@ private static bool NeedsNumericEscape(char c) => /// Round-trip formatting drops the fraction of a whole number, and 2 is an integer in every /// target: 1.0 / 2.0 would become integer division in C, C++ and Go, fail to compile in Rust, /// and type an inferred local as an integer. A value with a point or an exponent already reads as a - /// float, and one that is not finite is left as it is — there is no number to add a point to. + /// float, and one that is not finite is left as it is — there is no number to add a point to. A + /// literal that is not finite is spelled by instead. /// protected static string FormatDouble(double value) => WithFraction(value.ToString("R", CultureInfo.InvariantCulture), double.IsFinite(value)); + /// + /// Spells a double that is NaN or an infinity. + /// + /// The value to spell, which is not finite. + /// The language's name for the value. + /// + /// JavaScript's NaN, Infinity and -Infinity, which is the one target where the + /// text round-trip formatting gives is already a name the language knows. Every other language + /// spells these as a constant of its own, and the C, C++ and Go spellings need an import that + /// the generator adds through . + /// + protected virtual string SpellNonFiniteDouble(double value) => + double.IsNaN(value) ? "NaN" : value > 0 ? "Infinity" : "-Infinity"; + /// /// Formats a single-precision value so that every target reads it as floating-point. /// diff --git a/Coder/Languages/PythonGenerator.cs b/Coder/Languages/PythonGenerator.cs index d801fe3..8c47963 100644 --- a/Coder/Languages/PythonGenerator.cs +++ b/Coder/Languages/PythonGenerator.cs @@ -176,6 +176,14 @@ private void WriteAccessorBody(Collection body, CodeBlocker code) : $"import {import}"; } + /// + /// + /// Python has no literal for these, and math.nan would need an import that + /// float("nan") does not. + /// + protected override string SpellNonFiniteDouble(double value) => + double.IsNaN(value) ? "float(\"nan\")" : value > 0 ? "float(\"inf\")" : "float(\"-inf\")"; + /// protected override IEnumerable RequiredImports(SourceFile file) { diff --git a/Coder/Languages/RustGenerator.cs b/Coder/Languages/RustGenerator.cs index 2635ef4..869c6aa 100644 --- a/Coder/Languages/RustGenerator.cs +++ b/Coder/Languages/RustGenerator.cs @@ -331,6 +331,13 @@ private sealed record OperatorTrait(string Name, string Method, bool ReturnsBool return import.EndsWith(';') ? import : $"use {import};"; } + /// + /// + /// The associated constants of f64, which need nothing imported. + /// + protected override string SpellNonFiniteDouble(double value) => + double.IsNaN(value) ? "f64::NAN" : value > 0 ? "f64::INFINITY" : "f64::NEG_INFINITY"; + /// /// /// Rust has modules, so a namespace is one — and a dotted name is nested modules rather than one