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
26 changes: 26 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,32 @@ behind it still answers.

---

### A string parsed inside a settings scope is parsed under that scope

**Silent: a stale value is corrected.** `MathS.FromString`, and with it the implicit conversion from `string` and
`ToEntity`, cached its parse by the string object and returned it under whatever settings were in force later, on any
thread. A literal is rounded as it is parsed, by `PrecisionErrorZeroRange`, `DecimalPrecisionContext`,
`MaxAbsNumeratorOrDenominatorValue` and `DowncastingEnabled`, so the same string answered differently depending on
where it had been parsed first ([#2478](https://github.com/asc-community/AngouriMath/issues/2478)). The cache now holds
only parses made with every setting at its default, and inside a scope of any setting each call parses afresh, as
`FromString(s, useCache: false)` always did. Measured with one string object parsed first at the defaults and then in
the scope:

| Input | Scope | Was (2.7.0) | Now |
|---|---|---|---|
| `1e-20` | `PrecisionErrorZeroRange` at `1e-10` | `1E-20` (`Real`) | `0` (`Integer`) |
| `1e-20` | `DecimalPrecisionContext` at 20 digits | `1E-20` (`Real`) | `0` (`Integer`) |
| `1.00000000001` | `PrecisionErrorZeroRange` at `1e-10` | `1.00000000001` | `1` |
| `0.142857142857142857142857142857` | `DecimalPrecisionContext` at 20 digits | the decimal (`Real`) | `1/7` |
| `0.12345679` | `MaxAbsNumeratorOrDenominatorValue` at 100 | `12345679/100000000` | `0.12345679` (`Real`) |

In the other order, the scope's parse came back at the defaults: `1e-20` parsed first in the `1e-10` scope was `0`
afterwards everywhere. And `0`, `1` and `-1`, which the cache answered without parsing, were `Integer` with
`DowncastingEnabled` off, where every other whole number is `Real`; they are `Real` there now, as `FromString(s,
useCache: false)` gave on 2.7.0. Outside any scope nothing moves.

---

### An indexed union or intersection binds its index

**Silent: a bound name is no longer reported free.** `FreeVariables` of `union(A_k, k in I)` and `intersection(A_k, k in I)`
Expand Down
38 changes: 23 additions & 15 deletions Sources/AngouriMath/Convenience/MathS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4591,6 +4591,14 @@ public static (Variable, Variable, Variable, Variable, Variable) Var(string name
/// First occurance will be parsed, others will be replaced with the cached entity
/// </param>
/// <returns>The parsed expression</returns>
/// <remarks>
/// The cache holds parses made with every setting at its default, and is neither read nor
/// written while a scope of any setting is open in the calling flow: a literal is rounded
/// as it is parsed, by <see cref="Settings.PrecisionErrorZeroRange"/>,
/// <see cref="Settings.DecimalPrecisionContext"/> and the other numeric settings, so
/// <c>1e-20</c> is a number under the defaults and <c>0</c> with the zero range at
/// <c>1e-10</c>. Inside such a scope every call parses afresh.
/// </remarks>
/// <example>
/// Multiple ways to parse an expression.
/// <code>
Expand All @@ -4612,7 +4620,16 @@ public static (Variable, Variable, Variable, Variable, Variable) Var(string name
public static Entity FromString(string expr, bool useCache)
=> expr
.LetLazy(out var parsed, Parser.Parse)
.ReplaceWith(useCache)
// Only a parse made under the defaults is cached. The parse reads the settings, and
// not a fixed few of them: a literal is rounded by PrecisionErrorZeroRange,
// DecimalPrecisionContext, MaxAbsNumeratorOrDenominatorValue, FloatToRationalIterCount
// and DowncastingEnabled, ExplicitParsingOnly decides what juxtaposition means, and
// det, trace, dot, cross, an entry and resultant are computed while parsing, by
// whatever those computations read. A cache keyed by a list of them is wrong the day
// the parse reads one more, so an open scope of any setting bypasses it: the scope's
// parse is neither answered from it nor written to it.
// https://github.com/asc-community/AngouriMath/issues/2478
.ReplaceWith(useCache && !Convenience.SettingsState.AnyScopeOpen())
switch
{
false => parsed.Value,
Expand All @@ -4624,23 +4641,10 @@ public static Entity FromString(string expr, bool useCache)
"-1" => Integer.Create(-1),
"+oo" => Real.PositiveInfinity,
"-oo" => Real.NegativeInfinity,
// One cache per pair of the settings the parse reads: with the
// downcasting off a whole number parses as a decimal, so a string
// parsed under one setting is not the other's parse.
// https://github.com/asc-community/AngouriMath/issues/1513
_ => (Settings.ExplicitParsingOnly.Value, Settings.DowncastingEnabled.Value) switch
{
(false, true) => stringToEntityCache.GetValue(expr, _ => parsed.Value),
(true, true) => stringToEntityCacheExplicitOnly.GetValue(expr, _ => parsed.Value),
(false, false) => stringToEntityCacheNotDowncasting.GetValue(expr, _ => parsed.Value),
(true, false) => stringToEntityCacheExplicitOnlyNotDowncasting.GetValue(expr, _ => parsed.Value)
}
_ => stringToEntityCache.GetValue(expr, _ => parsed.Value)
}
};
private static ConditionalWeakTable<string, Entity> stringToEntityCacheExplicitOnly = new();
private static ConditionalWeakTable<string, Entity> stringToEntityCache = new();
private static ConditionalWeakTable<string, Entity> stringToEntityCacheNotDowncasting = new();
private static ConditionalWeakTable<string, Entity> stringToEntityCacheExplicitOnlyNotDowncasting = new();

/// <summary>Converts a <see cref="string"/> to an expression</summary>
/// <param name="expr"><see cref="string"/> expression, for example, <code>"2 * x + 3 + sqrt(x)"</code></param>
Expand Down Expand Up @@ -6226,6 +6230,10 @@ public static Matrix Matrix(int rows, int columns, params Entity[] values) =>
/// // here you write your code normally
/// </code>
/// </summary>
/// <remarks>
/// While any setting is scoped, <see cref="FromString(string, bool)"/> does not use its cache,
/// and parsing the same string repeatedly inside the scope costs a parse each time.
/// </remarks>
public static partial class Settings
{
/// <summary>
Expand Down
31 changes: 31 additions & 0 deletions Sources/AngouriMath/Convenience/SettingClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ internal interface ISettingState
/// <see langword="null"/> where nothing is set and the default applies.
/// </summary>
object? CurrentState { get; }

/// <summary>Whether a scope of this setting has been opened, in any flow, since the process started.</summary>
bool EverScoped { get; }
}

/// <summary>
Expand Down Expand Up @@ -65,6 +68,31 @@ internal static void Register(ISettingState setting)
}
}

[ConcurrentField] private static bool anyEverScoped;

/// <summary>Called by every <see cref="Setting{T}.Set"/>, before its frame is pushed.</summary>
internal static void NoteScoped()
{
if (!anyEverScoped)
System.Threading.Volatile.Write(ref anyEverScoped, true);
}

/// <summary>
/// Whether any setting reads, in this flow, from a scope rather than from its default.
/// Until a scope of any setting has been opened somewhere this is one read of a flag; after
/// that, one async-local read for each setting that has ever been scoped.
/// </summary>
internal static bool AnyScopeOpen()
{
if (!System.Threading.Volatile.Read(ref anyEverScoped))
return false;
var settings = System.Threading.Volatile.Read(ref registered);
for (var i = 0; i < settings.Length; i++)
if (settings[i].EverScoped && settings[i].CurrentState is not null)
return true;
return false;
}

/// <summary>What every setting reads as right now, in this flow.</summary>
internal static object?[] Snapshot()
{
Expand Down Expand Up @@ -156,6 +184,8 @@ internal Setting(T defaultValue)
/// </summary>
object? ISettingState.CurrentState => frames.Value;

bool ISettingState.EverScoped => EverScoped;

/// <summary>
/// Whether a scope of this setting has been opened, in any flow, since the process
/// started, so that a reader can skip asking for the flow's frame while none can exist.
Expand Down Expand Up @@ -185,6 +215,7 @@ public AutoBackRollableTemporarySettingUnit Set(T value)
// Before the frame, so that no flow can see the frame without the flag.
if (!everScoped)
Volatile.Write(ref everScoped, true);
SettingsState.NoteScoped();
frames.Value = new Frame(id, value, frames.Value);
return new AutoBackRollableTemporarySettingUnit(this, id);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static class UnsafeAndInternal
/// instead and set the flag useCache to false)
/// </summary>
public static void ClearFromStringCache()
=> (stringToEntityCache, stringToEntityCacheExplicitOnly) = (new(), new());
=> stringToEntityCache = new();

/// <summary>
/// Checks if two expressions are equivalent if
Expand Down
92 changes: 92 additions & 0 deletions Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,98 @@
Assert.Equal(Entity.Number.Integer.Create(0), "1e-20".ToEntity().EvalNumerical());
}

// The parse cache answered a string with whatever it had been parsed to first, under
// whichever settings were then in force, though a literal is rounded by them as it is
// parsed. https://github.com/asc-community/AngouriMath/issues/2478
private static System.IDisposable ScopeOf(string setting) => setting switch
{
"zero range 1e-10" => MathS.Settings.PrecisionErrorZeroRange.Set(EDecimal.Create(1, -10)),
"20 digits" => MathS.Settings.DecimalPrecisionContext.Set(new EContext(20, ERounding.HalfUp, -100000, 100000, false)),
"max 100" => MathS.Settings.MaxAbsNumeratorOrDenominatorValue.Set(EInteger.FromInt32(100)),
"no downcasting" => MathS.Settings.DowncastingEnabled.Set(false),
_ => throw new System.ArgumentException(setting),
};

// The type with the value: an Integer and a Real of one value are different parses.
private static (System.Type, Entity) Parse(string text, bool useCache = true)
{
var parsed = MathS.FromString(text, useCache);
return (parsed.GetType(), parsed);
}

[Theory]
[InlineData("1e-20", "zero range 1e-10")]
[InlineData("1e-20", "20 digits")]
[InlineData("0.333333333333333333333333", "zero range 1e-10")]
[InlineData("0.333333333333333333333333", "20 digits")]
[InlineData("1.00000000001", "zero range 1e-10")]
[InlineData("0.142857142857142857142857142857", "20 digits")]
[InlineData("0.12345679", "20 digits")]
[InlineData("0.12345679", "max 100")]
[InlineData("1", "no downcasting")]
[InlineData("0.1", "no downcasting")]
public void Issue2478_ACachedParseIsTheParseUnderTheSettingsInForce(string text, string setting)
{
var atDefaults = Parse(text, useCache: false);
(System.Type, Entity) inScope;
using (ScopeOf(setting))
inScope = Parse(text, useCache: false);
Assert.NotEqual(atDefaults, inScope);

// Defaults first, then the scope, on one string object.
var first = new string(text.ToCharArray());
Assert.Equal(atDefaults, Parse(first));
using (ScopeOf(setting))
Assert.Equal(inScope, Parse(first));

// The scope first, then the defaults.
var second = new string(text.ToCharArray());
using (ScopeOf(setting))
Assert.Equal(inScope, Parse(second));
Assert.Equal(atDefaults, Parse(second));

// And the interned literal, which every assembly in the process shares.
var interned = string.Intern(text);
Assert.Equal(atDefaults, Parse(interned));
using (ScopeOf(setting))
Assert.Equal(inScope, Parse(interned));
Assert.Equal(atDefaults, Parse(interned));
}

// A scope is the calling flow's, so one thread's scope must not decide what another
// thread's parse of the same string object is, in either order.
// https://github.com/asc-community/AngouriMath/issues/2478
[Fact]
public void Issue2478_AScopeOnOneThreadDoesNotReachAnothersParse()
{
var atDefaults = Parse("1e-20", useCache: false);
(System.Type, Entity) inScope;
using (ScopeOf("zero range 1e-10"))
inScope = Parse("1e-20", useCache: false);
Assert.NotEqual(atDefaults, inScope);

(System.Type, Entity) OnAThread(string text, bool scoped)
{
(System.Type, Entity) result = default;
var thread = new System.Threading.Thread(() =>
{
using var _ = scoped ? ScopeOf("zero range 1e-10") : null;
result = Parse(text);
});
thread.Start();
thread.Join();
return result;
}

var first = new string("1e-20".ToCharArray());
Assert.Equal(atDefaults, OnAThread(first, scoped: false));
Assert.Equal(inScope, OnAThread(first, scoped: true));

var second = new string("1e-20".ToCharArray());
Assert.Equal(inScope, OnAThread(second, scoped: true));
Assert.Equal(atDefaults, OnAThread(second, scoped: false));
}

// https://github.com/asc-community/AngouriMath/issues/561
// The reporter's 4x4 matrix spans 1e5 to 1e50, so entries of its inverse fall
// below 1e-16 and downcasting rounded them to zero. Fixed by the same change as
Expand All @@ -185,7 +277,7 @@
{ 20692733745923116440.0, 985012471441596398530723840.0, 53035823659846109665657533505732608.0, 3088144109088191970827418502918634458841088.0 },
{ 985012471441596398530723840.0, 53035823659846109665657533505732608.0, 3088144109088191970827418502918634458841088.0, 190454802288659943182846234171424053458511757049856.0 }
});
var product = (Entity.Matrix)(matrix * matrix.Inverse).InnerSimplified;

Check warning on line 280 in Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

Possible null reference argument for parameter 'm2' in 'Matrix Matrix.operator *(Matrix m1, Matrix m2)'.

Check warning on line 280 in Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

Possible null reference argument for parameter 'm2' in 'Matrix Matrix.operator *(Matrix m1, Matrix m2)'.
Assert.Equal(MathS.IdentityMatrix(4), product);
}

Expand Down
Loading