fix: Harden Advanced Search: crash-safety, autosave, correct results & worker fixes (#2543)

## Summary

Hardens the **Advanced Search** engine (`Projects/UOContent/Engines/Advanced Search/`) — the GM entity finder that fans searches across background worker threads. A code review surfaced 14 defects (A–N), including a shard-crasher reachable from a single admin typo and a path that silently disables autosave for the rest of the shard's uptime. Each behavioral fix ships with a test.

Full `UOContent.Tests` suite: **530/530 green** (21 new AdvancedSearch tests).

## Fixes

### Crash / data-loss
- **A — Shard crash on a malformed Property Test.** `AdvancedSearchThreadWorker.Execute` had no `try/catch` and the worker `Thread` is foreground, so a parse throw (`Hits>abc`, `Layer=onehanded` — `Enum.Parse` was case-sensitive, `Hits>1@` — empty sub-expression indexing) terminated the process. Now: `ParseValue`/`CompareValues` use `TryParse`/`Enum.TryParse(ignoreCase)` and return no-match instead of throwing; the per-entity filter is wrapped in `try/catch` (logs + skips); empty expressions are guarded.
- **C — Overlapping searches corrupt state + brick autosave.** `_threadWorkers`/`_threadId` were `static` but `DoSearch` is an instance method; a second search (double-click / two admins) stomped shared worker state and could leave a drain waiting forever on the shared `AutoResetEvent`, so `AutoSave.SavesEnabled` was never restored. Now: an `Interlocked` re-entrancy guard rejects concurrent searches.
- **G — Autosave restore not guaranteed.** The restore lived only in the success callback. Now it's in a `finally` (plus an outer `catch` covering the synchronous setup and a `catch` on the drain body), so autosave + the guard are always released.

### Wrong results
- **D — `@`/`|` operator precedence.** `a@b|c` evaluated as `a && (b || c)` instead of `(a && b) || c`. OR now binds looser than AND (`AdvancedSearchUtilities.EvaluateBoolean`, unit-tested).
- **E — Descending sort, partial last page rendered blank** (the index decreased in descending mode and the `break` early-out killed the loop). Now a bounded `VisibleCount`-driven loop renders the last page in both directions.
- **F — Deleted entities** were not skipped (ghost rows). Now `DoEntitySearch` skips `entity.Deleted`.
- **N — Reference-type comparisons** threw (`Comparer<T>.Default.Compare` on non-`IComparable`) and compared references to a string. Now equality is by value and ordering is guarded to `IComparable` (no throw).

### Worker perf / hardening
- **H** busy-spin → `Thread.Yield()` in the drain; **I** `GetProperties()` cached per `Type`; **J** `HandleValidInternal` moved behind the cheap map/range/region filters; **K** worker threads are `IsBackground` + `Exit()` tolerates an already-terminated worker; **L** `_filter == null` guard; **M** consistent `Volatile` access on `_pause`/`_exit`.

### Documented
- **B** — the residual worker/event-loop read race is documented on `AdvancedSearchThreadWorker`: workers read live entity state concurrently with the loop, so value-type reads may be stale-but-safe and getter exceptions are swallowed; fully eliminating it would require snapshotting entity fields on the main thread (deferred).

## Notes
- New test-only seams (`TryBeginSearch`/`EndSearch`/`IsSearchInProgress`/`VisibleCount`/`TryParseValue`/`EvaluateBoolean`) are `internal` via the existing `InternalsVisibleTo("UOContent.Tests")`.
- Dead `public ParseValue<T>` removed.
- `ConcurrentDictionary` for the reflection cache is intentional — these workers are genuinely parallel.
This commit is contained in:
Kamron Batman 2026-07-21 07:51:06 -07:00 • committed by GitHub
parent 858c1d18bc
commit 1e97ed50f6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 842 additions and 209 deletions

View file

@ -8,6 +8,7 @@ using Server.Commands;
using Server.Commands.Generic;
using Server.Engines.Spawners;
using Server.Gumps;
using Server.Logging;
using Server.Network;
using Server.Saves;
@ -28,11 +29,19 @@ public enum AdvancedSearchGumpOptions : long
public class AdvancedSearchGump : Gump
{
private static readonly ILogger _logger = LogFactory.GetLogger(typeof(AdvancedSearchGump));
private const int MaxEntries = 18;
private static int _threadId;
private static AdvancedSearchThreadWorker[] _threadWorkers;
private static int _searchInProgress;
internal static bool IsSearchInProgress => Volatile.Read(ref _searchInProgress) == 1;
internal static bool TryBeginSearch() => Interlocked.CompareExchange(ref _searchInProgress, 1, 0) == 0;
internal static void EndSearch() => Volatile.Write(ref _searchInProgress, 0);
private static void Configure()
{
EventSink.Shutdown += Shutdown;
@ -124,6 +133,10 @@ public class AdvancedSearchGump : Gump
public AdvancedSearchGump() : base(50, 50) => Build();
// Entries on the current page — bounds the paging loop so a partial last page can't read past the end.
internal static int VisibleCount(int total, int displayFrom, int maxEntries) =>
Math.Clamp(total - displayFrom, 0, maxEntries);
private void Build()
{
const int height = 500;
@ -319,15 +332,13 @@ public class AdvancedSearchGump : Gump
var allDisplayedSelected = true;
for (var i = 0; i < MaxEntries; i++)
{
var offset = SortDescending ? MaxEntries - 1 - i : i;
var index = offset + DisplayFrom;
// Bound to this page's real entries so a partial last page still renders in descending mode.
var visibleCount = VisibleCount(SearchResults.Length, DisplayFrom, MaxEntries);
if (index >= SearchResults.Length)
{
break;
}
for (var i = 0; i < visibleCount; i++)
{
var offset = SortDescending ? visibleCount - 1 - i : i;
var index = offset + DisplayFrom;
var entry = SearchResults[index];
@ -739,78 +750,103 @@ public class AdvancedSearchGump : Gump
return;
}
if (!TryBeginSearch())
{
from.SendMessage("A search is already running. Please wait for it to finish.");
return;
}
_threadId = 0;
var autoSave = AutoSave.SavesEnabled;
if (autoSave)
AutoSave.SavesEnabled = false;
try
{
AutoSave.SavesEnabled = false;
}
_threadWorkers ??= new AdvancedSearchThreadWorker[Math.Max(Environment.ProcessorCount - 1, 1)];
_threadWorkers ??= new AdvancedSearchThreadWorker[Math.Max(Environment.ProcessorCount - 1, 1)];
var ignoreQueue = new ConcurrentQueue<IEntity>();
var results = new ConcurrentQueue<AdvancedSearchResult>();
var worldLocation = new WorldLocation(from.Location, from.Map);
var ignoreQueue = new ConcurrentQueue<IEntity>();
var results = new ConcurrentQueue<AdvancedSearchResult>();
var worldLocation = new WorldLocation(from.Location, from.Map);
for (var i = 0; i < _threadWorkers.Length; i++)
{
(_threadWorkers[i] ??= new AdvancedSearchThreadWorker()).Wake(worldLocation, Filter, results, ignoreQueue);
}
var type = Filter.FilterType ? Filter.Type : null;
// Push the entities
foreach (var item in World.Items.Values)
{
if (type == null || type.IsInstanceOfType(item))
{
PushToWorkers(item);
}
}
foreach (var m in World.Mobiles.Values)
{
if (type == null || type.IsInstanceOfType(m))
{
PushToWorkers(m);
}
}
ThreadPool.QueueUserWorkItem(state =>
{
// Block until everything is processed
for (var i = 0; i < _threadWorkers.Length; i++)
{
_threadWorkers[i].Sleep();
(_threadWorkers[i] ??= new AdvancedSearchThreadWorker()).Wake(worldLocation, Filter, results, ignoreQueue);
}
var ignoredEntities = new HashSet<IEntity>(ignoreQueue);
var type = Filter.FilterType ? Filter.Type : null;
// Force the GC to collect the ignored entities
ignoreQueue.Clear();
var resultsList = new List<AdvancedSearchResult>(results.Count);
foreach (var result in results)
// Push the entities. Workers read entity state concurrently with the main loop —
// see AdvancedSearchThreadWorker for the accepted, bounded race.
foreach (var item in World.Items.Values)
{
if (!ignoredEntities.Contains(result.Entity))
if (type == null || type.IsInstanceOfType(item))
{
resultsList.Add(result);
PushToWorkers(item);
}
}
SearchResults = resultsList.ToArray();
// Force the GC to collect the results
resultsList.Clear();
resultsList.TrimExcess();
// Send the gump on the main thread
Core.LoopContext.Post(
autoSaveState =>
foreach (var m in World.Mobiles.Values)
{
if (type == null || type.IsInstanceOfType(m))
{
AutoSave.SavesEnabled = (bool)autoSaveState!;
Resend(from);
}, state);
}, autoSave);
PushToWorkers(m);
}
}
ThreadPool.QueueUserWorkItem(state =>
{
try
{
// Block until everything is processed
for (var i = 0; i < _threadWorkers.Length; i++)
{
_threadWorkers[i].Sleep();
}
var ignoredEntities = new HashSet<IEntity>(ignoreQueue);
// Force the GC to collect the ignored entities
ignoreQueue.Clear();
var resultsList = new List<AdvancedSearchResult>(results.Count);
foreach (var result in results)
{
if (!ignoredEntities.Contains(result.Entity))
{
resultsList.Add(result);
}
}
SearchResults = resultsList.ToArray();
// Force the GC to collect the results
resultsList.Clear();
resultsList.TrimExcess();
// Send the gump on the main thread
Core.LoopContext.Post(() => Resend(from));
}
catch (Exception ex)
{
// A drain-phase throw here would terminate the process; the finally still
// restores autosave and releases the guard.
_logger.Warning(ex, "AdvancedSearch: search drain failed");
}
finally
{
AutoSave.SavesEnabled = (bool)state!;
EndSearch();
}
}, autoSave);
}
catch
{
// Setup failed before the work item took ownership of the release.
AutoSave.SavesEnabled = autoSave;
EndSearch();
throw;
}
}
private void SetSortSwitches(int radioSwitch)

View file

@ -3,13 +3,26 @@ using System.Collections.Concurrent;
using System.Reflection;
using System.Threading;
using Server.Items;
using Server.Logging;
using Server.Mobiles;
using Server.Multis;
namespace Server.Engines.AdvancedSearch;
/// <summary>
/// Filters entities on a background thread while the main loop keeps mutating them — an
/// intentional, bounded race. Reads of live <see cref="Item"/>/<see cref="Mobile"/> state are
/// unsynchronized, so a torn <see cref="Point3D"/> read may report stale coordinates, and any
/// getter that throws mid-read is caught per-entity in <see cref="DoEntitySearch"/> and skipped.
/// Results are best-effort and may omit a concurrently modified entity, but never fault or corrupt
/// server state. Eliminating the race would require snapshotting each read field onto the main
/// thread before handing entities off; that is deferred.
/// </summary>
public class AdvancedSearchThreadWorker
{
private static readonly ILogger _logger = LogFactory.GetLogger(typeof(AdvancedSearchThreadWorker));
private static readonly ConcurrentDictionary<Type, PropertyInfo[]> _propCache = new();
private readonly Thread _thread;
private readonly AutoResetEvent _startEvent; // Main thread tells the thread to start working
private readonly AutoResetEvent _stopEvent; // Main thread waits for the worker finish draining
@ -26,7 +39,10 @@ public class AdvancedSearchThreadWorker
_startEvent = new AutoResetEvent(false);
_stopEvent = new AutoResetEvent(false);
_entities = new ConcurrentQueue<IEntity>();
_thread = new Thread(Execute);
_thread = new Thread(Execute)
{
IsBackground = true
};
_thread.Start(this);
}
@ -52,10 +68,16 @@ public class AdvancedSearchThreadWorker
public void Exit()
{
_exit = true;
Volatile.Write(ref _exit, true);
Wake(WorldLocation.Zero, null, null, null);
Sleep();
// Tolerate a worker that has already terminated (e.g. Core.Closing raced us) so
// shutdown can't deadlock waiting on a stopEvent that will never be set.
if (_thread.IsAlive)
{
Sleep();
}
}
public void Push(IEntity entity)
@ -88,12 +110,17 @@ public class AdvancedSearchThreadWorker
worker._filter = null;
break;
}
else
{
// Transiently empty but not yet paused: yield rather than busy-spin.
Thread.Yield();
}
}
worker._stopEvent.Set(); // Allow the main thread to continue now that we are finished
worker._pause = false;
Volatile.Write(ref worker._pause, false);
if (Core.Closing || worker._exit)
if (Core.Closing || Volatile.Read(ref worker._exit))
{
return;
}
@ -102,9 +129,28 @@ public class AdvancedSearchThreadWorker
private AdvancedSearchResult DoEntitySearch(IEntity entity)
{
if (_filter.HideValidInternalMap)
if (entity == null || entity.Deleted)
{
HandleValidInternal(entity);
return null;
}
try
{
return DoEntitySearchCore(entity);
}
catch (Exception ex)
{
_logger.Warning(ex, "AdvancedSearch: filter threw for {Entity}; skipping", entity);
return null;
}
}
private AdvancedSearchResult DoEntitySearchCore(IEntity entity)
{
if (_filter == null)
{
// Exit() clears the filter; a straggler entity dequeued after teardown bails here.
return null;
}
// Check for valid map
@ -138,6 +184,12 @@ public class AdvancedSearchThreadWorker
return null;
}
// After the cheap filters, so non-qualifying entities skip the house/keyring enumeration.
if (_filter.HideValidInternalMap)
{
HandleValidInternal(entity);
}
if (entity is Mobile mobile)
{
return DoMobileSearch(mobile);
@ -296,27 +348,17 @@ public class AdvancedSearchThreadWorker
}
}
private static bool EvaluateRecursive(IEntity entity, ReadOnlySpan<char> span)
{
var atIndex = span.IndexOf('@');
var orIndex = span.IndexOf('|');
if (atIndex == -1 && orIndex == -1)
{
return EvaluateSingleExpression(entity, span);
}
var result = atIndex != -1;
var splitIndex = result ? atIndex : orIndex;
var left = EvaluateRecursive(entity, span.Slice(0, splitIndex));
var right = EvaluateRecursive(entity, span.Slice(splitIndex + 1));
return result ? left && right : left || right;
}
private static bool EvaluateRecursive(IEntity entity, ReadOnlySpan<char> span) =>
AdvancedSearchUtilities.EvaluateBoolean(span, entity, static (e, leaf) => EvaluateSingleExpression(e, leaf));
private static bool EvaluateSingleExpression(IEntity entity, ReadOnlySpan<char> expression)
{
expression = expression.Trim();
if (expression.Length == 0)
{
return false;
}
var negate = false;
if (expression[0] == '~')
{
@ -338,7 +380,7 @@ public class AdvancedSearchThreadWorker
return false;
}
var properties = entity.GetType().GetProperties();
var properties = _propCache.GetOrAdd(entity.GetType(), static t => t.GetProperties());
PropertyInfo property = null;
for (var i = 0; i < properties.Length; ++i)
{

View file

@ -43,77 +43,80 @@ public static class AdvancedSearchUtilities
if (propertyType == typeof(long))
{
var parsedValue = ParseValue<long>(valuePart);
return CompareNumeric((long)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<long>(valuePart, out var parsedValue) &&
CompareNumeric((long)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(ulong))
{
var parsedValue = ParseValue<ulong>(valuePart);
return CompareNumeric((ulong)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<ulong>(valuePart, out var parsedValue) &&
CompareNumeric((ulong)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(int))
{
var parsedValue = ParseValue<int>(valuePart);
return CompareNumeric((int)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<int>(valuePart, out var parsedValue) &&
CompareNumeric((int)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(uint))
{
var parsedValue = ParseValue<uint>(valuePart);
return CompareNumeric((uint)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<uint>(valuePart, out var parsedValue) &&
CompareNumeric((uint)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(short))
{
var parsedValue = ParseValue<short>(valuePart);
return CompareNumeric((short)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<short>(valuePart, out var parsedValue) &&
CompareNumeric((short)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(ushort))
{
var parsedValue = ParseValue<ushort>(valuePart);
return CompareNumeric((ushort)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<ushort>(valuePart, out var parsedValue) &&
CompareNumeric((ushort)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(sbyte))
{
var parsedValue = ParseValue<sbyte>(valuePart);
return CompareNumeric((sbyte)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<sbyte>(valuePart, out var parsedValue) &&
CompareNumeric((sbyte)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(byte))
{
var parsedValue = ParseValue<byte>(valuePart);
return CompareNumeric((byte)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<byte>(valuePart, out var parsedValue) &&
CompareNumeric((byte)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(float))
{
var parsedValue = ParseValue<float>(valuePart);
return Compare((float)propertyValue!, parsedValue, valuePart, operatorSpan);
return TryParseValue<float>(valuePart, out var parsedValue) &&
Compare((float)propertyValue!, parsedValue, valuePart, operatorSpan);
}
if (propertyType == typeof(double))
{
var parsedValue = ParseValue<double>(valuePart);
return Compare((double)propertyValue!, parsedValue, valuePart, operatorSpan);
return TryParseValue<double>(valuePart, out var parsedValue) &&
Compare((double)propertyValue!, parsedValue, valuePart, operatorSpan);
}
if (propertyType == typeof(string))
{
var parsedValue = ParseValue<string>(valuePart);
return Compare((string)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<string>(valuePart, out var parsedValue) &&
Compare((string)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(TimeSpan))
{
var parsedValue = ParseValue<TimeSpan>(valuePart);
return Compare((TimeSpan)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<TimeSpan>(valuePart, out var parsedValue) &&
Compare((TimeSpan)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(DateTime))
{
var parsedValue = ParseValue<DateTime>(valuePart);
return Compare((DateTime)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<DateTime>(valuePart, out var parsedValue) &&
Compare((DateTime)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(bool))
{
var parsedValue = ParseValue<bool>(valuePart);
return Compare((bool)propertyValue!, parsedValue, operatorSpan);
return TryParseValue<bool>(valuePart, out var parsedValue) &&
Compare((bool)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType.IsEnum)
{
var valueEnum = Enum.Parse(propertyType, valuePart, false);
if (!Enum.TryParse(propertyType, valuePart.ToString(), true, out var valueEnum) || valueEnum == null)
{
return false;
}
return GetEnumSize(propertyType) switch
{
@ -121,15 +124,17 @@ public static class AdvancedSearchUtilities
2 => CompareNumeric((short)propertyValue!, (short)valueEnum, operatorSpan),
4 => CompareNumeric((int)propertyValue!, (int)valueEnum, operatorSpan),
8 => CompareNumeric((long)propertyValue!, (long)valueEnum, operatorSpan),
_ => false
};
}
if (!propertyType.IsValueType)
{
var parsedValue = ParseValue<object>(valuePart);
return CompareReference(propertyValue!, parsedValue, operatorSpan);
}
return false;
// Anything the hot typed paths above didn't handle — reference types (Poison, Map, entity
// properties resolved by serial), IParsable value types (Guid, decimal, ...), and legacy
// RunUO types with a static Parse(string) (Faction, Town, ...). Delegate to the shared,
// thread-safe Types converter so the target is parsed into the property's real type, then
// compare by value. A string is allocated here, but this is the uncommon path; the common
// types never reach it. Types returns a non-null message when it can't parse -> no match.
return Types.TryParse(propertyType, valuePart.ToString(), out var parsed) == null &&
CompareReference(propertyValue!, parsed, operatorSpan);
}
public static bool CompareNumeric<T>(T propertyValue, T parsedValue, ReadOnlySpan<char> operatorSpan) where T : INumber<T> =>
@ -236,19 +241,40 @@ public static class AdvancedSearchUtilities
_ => false
};
public static bool CompareReference<T>(T propertyValue, T parsedValue, ReadOnlySpan<char> operatorSpan) =>
operatorSpan switch
public static bool CompareReference<T>(T propertyValue, T parsedValue, ReadOnlySpan<char> operatorSpan)
{
switch (operatorSpan)
{
"=" or "==" => propertyValue.Equals(parsedValue),
"!" or "!=" => !propertyValue.Equals(parsedValue),
">" => Comparer<T>.Default.Compare(propertyValue, parsedValue) > 0,
"<" => Comparer<T>.Default.Compare(propertyValue, parsedValue) < 0,
">=" => Comparer<T>.Default.Compare(propertyValue, parsedValue) >= 0,
"<=" => Comparer<T>.Default.Compare(propertyValue, parsedValue) <= 0,
_ => false
};
case "=":
case "==": return Equals(propertyValue, parsedValue);
case "!":
case "!=": return !Equals(propertyValue, parsedValue);
}
public static T ParseValue<T>(ReadOnlySpan<char> valuePart)
if (propertyValue is IComparable cmp && parsedValue != null)
{
try
{
var c = cmp.CompareTo(parsedValue);
return operatorSpan switch
{
">" => c > 0,
"<" => c < 0,
">=" => c >= 0,
"<=" => c <= 0,
_ => false
};
}
catch
{
return false;
}
}
return false;
}
internal static bool TryParseValue<T>(ReadOnlySpan<char> valuePart, out T value)
{
// Special handling for boolean and hexadecimal values
if (typeof(T) == typeof(bool))
@ -256,74 +282,149 @@ public static class AdvancedSearchUtilities
var val = valuePart.ToString().ToLower();
if (val is "true" or "1" or "enabled" or "on")
{
return (T)(object)true;
value = (T)(object)true;
return true;
}
if (val is "false" or "0" or "disabled" or "off")
{
return (T)(object)false;
value = (T)(object)false;
return true;
}
value = default;
return false;
}
if (typeof(T) == typeof(long))
{
return ParseNumericValue<long, T>(valuePart);
return TryParseNumericValue<long, T>(valuePart, out value);
}
if (typeof(T) == typeof(ulong))
{
return ParseNumericValue<ulong, T>(valuePart);
return TryParseNumericValue<ulong, T>(valuePart, out value);
}
if (typeof(T) == typeof(int))
{
return ParseNumericValue<int, T>(valuePart);
return TryParseNumericValue<int, T>(valuePart, out value);
}
if (typeof(T) == typeof(uint))
{
return ParseNumericValue<uint, T>(valuePart);
return TryParseNumericValue<uint, T>(valuePart, out value);
}
if (typeof(T) == typeof(short))
{
return ParseNumericValue<short, T>(valuePart);
return TryParseNumericValue<short, T>(valuePart, out value);
}
if (typeof(T) == typeof(ushort))
{
return ParseNumericValue<ushort, T>(valuePart);
return TryParseNumericValue<ushort, T>(valuePart, out value);
}
if (typeof(T) == typeof(sbyte))
{
return ParseNumericValue<sbyte, T>(valuePart);
return TryParseNumericValue<sbyte, T>(valuePart, out value);
}
if (typeof(T) == typeof(byte))
{
return ParseNumericValue<byte, T>(valuePart);
return TryParseNumericValue<byte, T>(valuePart, out value);
}
if (typeof(T) == typeof(float))
{
return ParseNumericValue<float, T>(valuePart);
return TryParseNumericValue<float, T>(valuePart, out value);
}
if (typeof(T) == typeof(double))
{
return ParseNumericValue<double, T>(valuePart);
return TryParseNumericValue<double, T>(valuePart, out value);
}
// Default parsing for other types
return (T)Convert.ChangeType(valuePart.ToString(), typeof(T));
// string needs no parsing — the span itself is the value.
if (typeof(T) == typeof(string))
{
value = (T)(object)valuePart.ToString();
return true;
}
// Remaining supported types (TimeSpan, DateTime) parse straight from the span via
// ISpanParsable<T> — no allocation, no reflection, and unlike Convert.ChangeType it handles
// TimeSpan, which is not IConvertible and previously failed silently.
if (typeof(T) == typeof(TimeSpan))
{
return TryParseSpanParsable<TimeSpan, T>(valuePart, out value);
}
if (typeof(T) == typeof(DateTime))
{
return TryParseSpanParsable<DateTime, T>(valuePart, out value);
}
value = default;
return false;
}
// Parses U (a value type exposing ISpanParsable<U>) from the span and reinterprets it as T. The
// two type params mirror TryParseNumericValue: the caller dispatches on typeof(T), so U == T at
// every call site and the (T)(object) cast is always valid.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryParseSpanParsable<U, T>(ReadOnlySpan<char> valuePart, out T value) where U : ISpanParsable<U>
{
if (U.TryParse(valuePart, null, out var parsed))
{
value = (T)(object)parsed;
return true;
}
value = default;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static R ParseNumericValue<T, R>(ReadOnlySpan<char> valuePart) where T : INumber<T> =>
valuePart.StartsWith("0x")
? (R)(object)T.Parse(valuePart[2..], NumberStyles.HexNumber, null)
: (R)(object)T.Parse(valuePart, null);
private static bool TryParseNumericValue<T, R>(ReadOnlySpan<char> valuePart, out R value) where T : INumber<T>
{
var ok = valuePart.StartsWith("0x")
? T.TryParse(valuePart[2..], NumberStyles.HexNumber, null, out var parsed)
: T.TryParse(valuePart, null, out parsed);
if (ok)
{
value = (R)(object)parsed;
return true;
}
value = default;
return false;
}
// Evaluates one trimmed leaf atom against caller-supplied state. A custom delegate is required
// because ReadOnlySpan<char> cannot be a Func<> type argument; passing state avoids a per-call
// capturing closure, so the recursion allocates neither a string nor a closure.
internal delegate bool LeafEvaluator<in TState>(TState state, ReadOnlySpan<char> leaf);
// OR ('|') binds looser than AND ('@'); split on the outermost OR first, then AND.
internal static bool EvaluateBoolean<TState>(ReadOnlySpan<char> expr, TState state, LeafEvaluator<TState> evalLeaf)
{
var orIndex = expr.IndexOf('|');
if (orIndex != -1)
{
return EvaluateBoolean(expr[..orIndex], state, evalLeaf) || EvaluateBoolean(expr[(orIndex + 1)..], state, evalLeaf);
}
var andIndex = expr.IndexOf('@');
if (andIndex != -1)
{
return EvaluateBoolean(expr[..andIndex], state, evalLeaf) && EvaluateBoolean(expr[(andIndex + 1)..], state, evalLeaf);
}
return evalLeaf(state, expr.Trim());
}
private static int GetEnumSize(Type enumType) =>
Type.GetTypeCode(Enum.GetUnderlyingType(enumType)) switch