diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 0b5838a6b..0e88c1c08 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -415,6 +415,23 @@ compiled to `bool`, it is `false`, as one that does not hold | `"x provided x > 1".ToEntity().Compile("x")(2)` | `UncompilableNodeException` | `(2, 0)` | | `"x provided x > 1".ToEntity().Compile("x")(Complex.ImaginaryOne)` | `UncompilableNodeException` | `(NaN, 0)` | +### A compiled statement asked for as a number is its truth value + +**Not silent: what threw is compiled.** In the LINQ compiler, a statement compiled to a number, as +`Compile` or `Compile`, threw `InvalidProtocolProvided`, there being no `NaN` of a +`bool`. It is now its truth value, `1` where it holds, `0` where it does not and `NaN` where it has none, as +FastExpression and an Iverson bracket give it. A `provided` statement and a `piecewise` one compile too, with no truth +value where no case holds. A `piecewise` mixing statements and numbers, and a statement that may have no truth value +asked for as an integer type, which has no `NaN`, are refused with `UncompilableNodeException`. A `piecewise` of +statements threw `KeyNotFoundException`, outside the library's own exceptions +([#2224](https://github.com/asc-community/AngouriMath/issues/2224)). + +| Input | Was (2.6.0) | Now | +|---|---|---| +| `"x > 1".ToEntity().Compile("x")(2)` | throws `InvalidProtocolProvided` | `1` | +| `"x > 1 provided x > 0".ToEntity().Compile("x")(-1)` | throws `InvalidProtocolProvided` | `null` | +| `"piecewise(x > 1 provided x > 0, x < -1)".ToEntity().Compile("x")(-2)` | throws `KeyNotFoundException` | `true` | + ### `Compile` compiles statements, `provided` and `piecewise` **Not silent: what was refused is compiled.** `Entity.Compile(...)`, which returns a `FastExpression`, refused a diff --git a/Sources/.editorconfig b/Sources/.editorconfig index acfbb3481..77c1f0cc8 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -896,6 +896,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [Tests/UnitTests/Convenience/LambertWTest.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n +[Tests/UnitTests/Common/StatementAsANumberCompilationTest.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + [AngouriMath/Functions/Continuous/Solvers/EquationSolver/LambertWSolver.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs index 0a23b6da8..7899e432e 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs @@ -49,6 +49,10 @@ public virtual Expression ConvertNaN(Type type) type = Nullable.GetUnderlyingType(type) ?? type; + // A statement with no truth value is null, as Kleene's logic has it: the NaN of a provided + // statement where its predicate fails. https://github.com/asc-community/AngouriMath/issues/2224 + if (type == typeof(bool)) + return Expression.Constant(null, typeof(bool?)); if (type == typeof(System.Numerics.Complex)) return Expression.Constant(new System.Numerics.Complex(double.NaN, 0)); if (type == typeof(double)) @@ -80,6 +84,15 @@ public virtual Expression ConvertType(Expression expr, Type type) return Expression.Call(ThreeValuedLogic.HoldsMethod, expr); if (expr.Type == typeof(bool) && type == typeof(bool?)) return Expression.Convert(expr, type); + // A statement as a number is its truth value: 1 where it holds, 0 where it does not and NaN where + // it has none, as FastExpression and an Iverson bracket give it. It threw InvalidProtocolProvided, + // there being no NaN of a bool. https://github.com/asc-community/AngouriMath/issues/2224 + if ((expr.Type == typeof(bool) || expr.Type == typeof(bool?)) && typeLevelInHierarchy.ContainsKey(Nullable.GetUnderlyingType(type) ?? type)) + { + if (expr.Type == typeof(bool?) && Nullable.GetUnderlyingType(type) is null && ((ConstantExpression)ConvertNaN(type)).Value is null && type != typeof(object)) + throw new UncompilableNodeException($"A statement that may have no truth value cannot be compiled as {type}, which has no NaN"); + return ConvertType(Expression.Call(ThreeValuedLogic.IversonMethod, ConvertType(expr, typeof(bool?))), type); + } // A tensor converts to nothing but itself: a matrix over one element type is not // a matrix over another, and it is not a number. if (TensorCompilation.IsTensor(expr.Type) || TensorCompilation.IsTensor(type)) @@ -293,6 +306,9 @@ Equalsf when IsUndecidable(left, right) => Expression.Equal(Undecidable(left), U Expression HandleProvidedf(Expression expr, Expression cond) { + // A provided statement has no truth value where its predicate fails. + if (expr.Type == typeof(bool)) + expr = Expression.Convert(expr, typeof(bool?)); var nan = ConvertNaN(expr.Type); (expr, nan) = EqualizeTypesIfAble(expr, nan); return Expression.Condition(Holds(cond), expr, nan); @@ -340,11 +356,25 @@ private Expression HandlePiecewise(IEnumerable en) if (children.Length == 0) return Expression.Constant(null, typeof(object)); - Type maxType = typeof(int); + // A piecewise statement is one of its cases' truth values, and none where no case holds; one that + // mixes statements and numbers has no type to compile to. + // https://github.com/asc-community/AngouriMath/issues/2224 + var statements = 0; for (int i = 0; i < children.Length; i += 2) - { - maxType = MaxType(maxType, children[i].Type); - } + if (children[i].Type == typeof(bool) || children[i].Type == typeof(bool?)) + { + children[i] = ConvertType(children[i], typeof(bool?)); + statements++; + } + if (statements > 0 && statements * 2 != children.Length) + throw new UncompilableNodeException("A piecewise whose cases are statements and numbers at once has no compiled form"); + + Type maxType = statements > 0 ? typeof(bool?) : typeof(int); + if (statements == 0) + for (int i = 0; i < children.Length; i += 2) + { + maxType = MaxType(maxType, children[i].Type); + } // last case var expression = children[^2]; diff --git a/Sources/Tests/UnitTests/Common/StatementAsANumberCompilationTest.cs b/Sources/Tests/UnitTests/Common/StatementAsANumberCompilationTest.cs new file mode 100644 index 000000000..6e218b081 --- /dev/null +++ b/Sources/Tests/UnitTests/Common/StatementAsANumberCompilationTest.cs @@ -0,0 +1,76 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System.Numerics; +using AngouriMath; +using AngouriMath.Core.Exceptions; +using AngouriMath.Extensions; +using Xunit; + +namespace AngouriMath.Tests.Common +{ + /// + /// In the LINQ compiler a statement asked for as a number is its truth value, 1, 0 or NaN, as in FastExpression, + /// and a provided or a piecewise statement has no truth value where no case holds. Each threw + /// InvalidProtocolProvided, there being no NaN of a bool. + /// #2224 + /// + [Trait("Area", "Common")] + public sealed class StatementAsANumberCompilationTest + { + private static readonly Complex[] points = + { -2, -0.5, 0, 0.5, 1, 2, 3, 6, Complex.ImaginaryOne, new Complex(1, 1), double.NaN, double.PositiveInfinity }; + + private static bool Same(Complex expected, Complex actual) + => double.IsNaN(expected.Real) || double.IsNaN(expected.Imaginary) + ? double.IsNaN(actual.Real) || double.IsNaN(actual.Imaginary) + : expected == actual; + + [Theory] + [InlineData("x > 1")] + [InlineData("x = 2")] + [InlineData("not x > 1")] + [InlineData("x > 0 and x < 2")] + [InlineData("x in [0; 1]")] + [InlineData("3 divides x")] + [InlineData("x > 1 provided x > 0")] + [InlineData("piecewise(x > 1 provided x > 0, x < -1)")] + public void AsANumberAStatementIsFastExpressionsTruthValue(string statement) + { + var fast = statement.ToEntity().Compile("x"); + var complex = statement.ToEntity().Compile("x"); + var real = statement.ToEntity().Compile("x"); + foreach (var x in points) + { + Assert.True(Same(fast.Call(x), complex(x)), $"{statement} at {x}: {fast.Call(x)} by FastExpression, {complex(x)} by LINQ"); + if (x.Imaginary == 0) + Assert.True(Same(fast.Call(x), real(x.Real)), $"{statement} at {x}: {fast.Call(x)} by FastExpression, {real(x.Real)} over double"); + } + } + + [Theory] + [InlineData("x > 1 provided x > 0", 2, true)] + [InlineData("x > 1 provided x > 0", 0.5, false)] + [InlineData("x > 1 provided x > 0", -1, null)] + [InlineData("piecewise(x > 1 provided x > 0, x < -1)", 0.5, false)] + [InlineData("piecewise(x > 1 provided x > 0, x < -1)", -2, true)] + [InlineData("piecewise(x > 1 provided x > 0, x < -1)", -0.5, false)] + [InlineData("piecewise(x > 1 provided x > 0, x < -1 provided x < 0)", 0, null)] + public void AProvidedOrPiecewiseStatementHasTheTruthValueOfItsCase(string statement, double x, bool? expected) + => Assert.Equal(expected, statement.ToEntity().Compile("x")(x)); + + [Theory] + [InlineData("piecewise(x > 1 provided x > 0, x)")] + public void APiecewiseOfStatementsAndNumbersIsRefused(string expression) + => Assert.Throws(() => expression.ToEntity().Compile("x")); + + /// A statement that may have no truth value has none as an integer type, which has no NaN. + [Fact] + public void AsAnIntegerAStatementThatMayHaveNoTruthValueIsRefused() + => Assert.Throws(() => "x > 1".ToEntity().Compile("x")); + } +}