ModernUO/Projects/UOContent.Tests/Tests/Engines/AdvancedSearch/AdvancedSearchConditionsTests.cs
Kamron Batman 535a098996
refactor: compile where/sort/distinct and Advanced Search through expression trees (#2625)
## Summary

`where`, `sort by`, `distinct` and the Advanced Search property test now compile through expression trees instead of the hand-rolled IL in `Emitter.cs`. The emitter and its three `Reflection.Emit` compilers were RunUO-era code from before expression trees existed; they were the only way to avoid per-object reflection at the time, and they are not any more.

Net: ~1,900 lines of IL bookkeeping deleted, one comparison engine instead of two, faster per object, cheaper to compile, collectible, and `Nullable<T>` properties work.

## Why

- **Bugs hid in the IL.** Equality on a type with value semantics but no `IComparable` (`TextDefinition`) was a raw `ceq`, so `where Message = 1060847` never matched. A chained binding (`Message.Number`) dereferenced every link unguarded, so the first swept object with a null intermediate killed the sweep with an NRE. A constant narrower or unsigned than `int` threw before compiling. A struct with no `CompareTo` reached `ceq` on two unboxed values, which is invalid IL. Every dynamic assembly was `Run`, so each `[global where` grew the process for good.
- **Advanced Search had its own engine.** Per entity and per leaf it re-split the expression, scanned the runtime type's properties by name, read the value by reflection, re-parsed the right-hand side and dispatched on type through ~300 lines of `CompareValues`. Same job, second implementation, second set of bugs.

## What changed

- `ICondition.Compile(MethodEmitter)` becomes `ICondition.Build(ParameterExpression)` returning an `Expression`. `ConditionalCompiler` assembles a `Func<object, bool>`, `SortCompiler` a `Comparison<T>`, `DistinctCompiler` both comparer interfaces over one lambda. The parsed constant is an `Expression.Constant`, so the generated type, its constructor and the per-condition field for non-primitive constants disappear with `PropertyValue`.
- `PropertyExpressions` holds the shared pieces: the chain walk with its null-intermediate guard, `CompareTo` resolution with the old null ordering, the integral/enum operator path, and constant parsing.
- `BaseExtension.Optimize` loses its `ref AssemblyEmitter` parameter. An out-of-tree extension that overrides `Optimize` needs to drop it.
- Advanced Search keeps its grammar (`~` negates, `@` is AND, `|` is OR and binds looser, string `>` is "starts with") and translates each leaf into the same conditions, compiled once per declaring type per search and memoized across the workers. Float and double keep their typed-precision tolerance through a small `EpsilonCondition` in the Advanced Search folder.

## Semantics preserved

- Equality on a non-comparable reference type is `object.Equals`, never reference identity. A non-comparable struct boxes into the same call.
- A null intermediate in a chained binding is no match, and stays no match under negation. Sort and distinct read it as `default(T)`.
- Unsigned relational compares stay unsigned; integral primitives and enums use the operator directly, nothing widens to a signed type. `float`, `double`, `decimal`, `string` and structs still go through the type's own `CompareTo`, so `string` equality stays culture-sensitive exactly as before.
- Only `==` and `!=` are valid for non-comparable types; a relational operator still throws at build time.
- `TypeCondition` is still first and still null-checks the cast target.

## Behavior changes

- **`Nullable<T>` works**, with C# lifted semantics in `where`: two nulls are equal, a null and a value are unequal, a null satisfies no relation. Sort keeps a total order with unset values at one end. A null *reference* keeps the ordering it had.
- **Advanced Search**: a leaf that cannot be parsed or resolved is no match even under `~` (it used to negate the failure and match every entity); `null` is the null value for equality on strings, nullables and reference types, as in `where`; dotted names walk into a property; static properties are no longer searchable.

## Measurements

`where`, from the handoff (Debug test host, single condition, ratios not absolutes):

| Approach | ns/object | Compile | Collectible | LOC |
|---|---:|---:|---|---:|
| `AssemblyBuilder` + IL (before) | 20.5 | 0.311 ms | no (`Run`) | ~1,916 |
| Expression trees (after) | ~12 | 0.187 ms warm | yes | ~600 |

Advanced Search, Release, one `SkillTeleporter`, 2M evaluations per leaf:

| Leaf | Before | After |
|---|---:|---:|
| `Hue=5` | 137 ns | 20 ns |
| `Name~~gate` | 121 ns | 39 ns |
| `Skill=Magery` | 116 ns | 21 ns |
| `Weight>0.5` | 122 ns | 28 ns |

Plus 0.5 to 2 ms to compile each declaring type a search meets (12 ms for the first compile in the process). All of it runs on the search workers; nothing new touches the loop.

## Also fixed: Advanced Search map filters

Found while testing the property test in game. The map boxes are independent checkboxes, but the worker applied each ticked map as "must be on this map", so ticking two or more (all maps and Internal, say) rejected every entity before any other filter ran. Present since #1649; the default of Felucca alone never showed it. An entity now passes when its map is any of the ticked ones, with none ticked meaning no map constraint. Pinned by a worker test.

## Test plan

- [x] `UOContent.Tests`: 862 passed, 0 failed
- [x] `Server.Tests`: 869 passed, 0 failed
- [x] Every commit builds and its tests pass on its own (bisectable)
- [ ] In game: `[global where`, `[area where`, `[condition`, `sort by`, `distinct`, Advanced Search property test
2026-09-10 19:01:59 -07:00

232 lines
7.8 KiB
C#

using System;
using Server;
using Server.Engines.AdvancedSearch;
using Xunit;
namespace UOContent.Tests;
// The Advanced Search property test compiles through the same conditions a `where` clause does.
// The grammar is the gump's own; these pin its operators and precedence, and that a leaf which
// cannot be resolved or parsed is "no match" rather than an exception on the search worker.
public class AdvancedSearchConditionsTests
{
public sealed class Inner
{
public int Value { get; set; } = 7;
}
public sealed class LegacyParseType
{
public string Value { get; private init; }
public static LegacyParseType Parse(string s) => new() { Value = s };
public override bool Equals(object obj) => obj is LegacyParseType o && o.Value == Value;
public override int GetHashCode() => Value?.GetHashCode() ?? 0;
}
public class Subject
{
public int Hue { get; set; } = 5;
public string Name { get; set; } = "Moongate";
public bool Movable { get; set; } = true;
public bool Visible { get; set; }
public double Weight { get; set; } = 0.1 + 0.2;
public float Ratio { get; set; } = 0.1f;
public TimeSpan Delay { get; set; } = TimeSpan.FromMinutes(5);
public Guid Id { get; set; } = Guid.Parse("00000000-0000-0000-0000-000000000001");
public Layer Layer { get; set; } = Layer.OneHanded;
public object Reference { get; set; } = new();
public LegacyParseType Legacy { get; set; } = LegacyParseType.Parse("alpha");
public Inner Child { get; set; } = new();
public int? Maybe { get; set; }
}
public sealed class Derived : Subject
{
}
private static bool Check(string test, Subject subject = null) =>
AdvancedSearchConditions.Compile(typeof(Subject), test)(subject ?? new Subject());
[Theory]
[InlineData("Hue=abc")] // not a number
[InlineData("Hue=99999999999")] // overflows int
[InlineData("Hue=0xZZ")] // bad hex
[InlineData("Layer=Bogus")] // not an enum member
[InlineData("Delay=notaspan")]
[InlineData("Bogus=1")] // no such property
[InlineData("Hue=")] // no value
[InlineData("Hue")] // no operator
public void UnusableLeafIsNoMatchAndDoesNotThrow(string test)
{
var ex = Record.Exception(() => Assert.False(Check(test)));
Assert.Null(ex);
}
// The old evaluator negated a failed comparison, so `~Hue=abc` matched every entity.
[Fact]
public void UnusableLeafStaysNoMatchUnderNegation()
{
Assert.False(Check("~Hue=abc"));
Assert.False(Check("~Bogus=1"));
}
[Fact]
public void NumericOperators()
{
Assert.True(Check("Hue=5"));
Assert.True(Check("Hue==5"));
Assert.True(Check("Hue=0x5"));
Assert.False(Check("Hue!=5"));
Assert.True(Check("Hue!4"));
Assert.True(Check("Hue>4"));
Assert.True(Check("Hue<6"));
Assert.True(Check("Hue>=5"));
Assert.True(Check("Hue<=5"));
Assert.False(Check("Hue~5"));
}
[Fact]
public void NegationPrefix()
{
Assert.False(Check("~Hue=5"));
Assert.True(Check("~Hue=4"));
}
// '|' binds looser than '@'.
[Theory]
[InlineData("Movable=1", true)]
[InlineData("Visible=1", false)]
[InlineData("Visible=1@Visible=1|Movable=1", true)] // (F&&F)||T
[InlineData("Movable=1|Visible=1@Visible=1", true)] // T||(F&&F)
[InlineData("Movable=1@Visible=1", false)]
[InlineData("Movable=1@Movable=1", true)]
[InlineData("Visible=1|Visible=1", false)]
public void Precedence(string test, bool expected)
{
Assert.Equal(expected, Check(test));
}
[Theory]
[InlineData("Name=Moongate", true)]
[InlineData("Name=moongate", false)]
[InlineData("Name!Moongate", false)]
[InlineData("Name>Moon", true)]
[InlineData("Name<gate", true)]
[InlineData("Name~ong", true)]
[InlineData("Name~>moon", true)]
[InlineData("Name~<GATE", true)]
[InlineData("Name~~ONG", true)]
[InlineData("Name~=MOONGATE", true)]
[InlineData("Name~!MOONGATE", false)]
[InlineData("Name>=Moon", false)] // no such string operator
public void StringOperators(string test, bool expected)
{
Assert.Equal(expected, Check(test));
}
[Fact]
public void StringNullIsTheNullStringForEqualityAndTextOtherwise()
{
var unnamed = new Subject { Name = null };
Assert.True(Check("Name=null", unnamed));
Assert.False(Check("Name=null"));
Assert.False(Check("Name~null", unnamed));
Assert.True(Check("Name~null", new Subject { Name = "nullable" }));
}
[Fact]
public void BooleanAcceptsSwitchWordsAndOnlyEquality()
{
Assert.True(Check("Movable=true"));
Assert.True(Check("Movable=1"));
Assert.True(Check("Movable=on"));
Assert.True(Check("Movable=Enabled"));
Assert.True(Check("Visible=off"));
Assert.False(Check("Movable=maybe"));
Assert.False(Check("Movable>0"));
}
[Fact]
public void EnumIgnoresCaseAndOrdersByValue()
{
Assert.True(Check("Layer=onehanded"));
Assert.True(Check("Layer>Invalid"));
Assert.False(Check("Layer=TwoHanded"));
}
// Floating point compares to a tolerance derived from the typed value.
[Fact]
public void FloatingPointUsesEpsilon()
{
Assert.True(Check("Weight=0.3"));
Assert.False(Check("Weight=0.31"));
Assert.True(Check("Weight>0.2"));
Assert.True(Check("Weight<=0.3"));
Assert.True(Check("Ratio=0.1"));
Assert.False(Check("Ratio=0.2"));
}
[Fact]
public void TimeSpanParsesAndCompares()
{
Assert.True(Check("Delay=00:05:00"));
Assert.False(Check("Delay=00:10:00"));
Assert.True(Check("Delay>00:01:00"));
}
[Fact]
public void ValueTypeWithoutHotPathParsesThroughTypes()
{
Assert.True(Check("Id=00000000-0000-0000-0000-000000000001"));
Assert.False(Check("Id=00000000-0000-0000-0000-000000000002"));
}
// A pre-IParsable type with only a static Parse(string) is still searchable, compared against
// a real parsed instance rather than the raw text.
[Fact]
public void LegacyParseStringParsesThroughTypes()
{
Assert.True(Check("Legacy=alpha"));
Assert.False(Check("Legacy=beta"));
}
// A reference type with no CompareTo answers equality only; ordering is no match, not a throw.
[Fact]
public void ReferenceTypeOrderingIsNoMatchAndDoesNotThrow()
{
var ex = Record.Exception(() => Assert.False(Check("Reference>whatever")));
Assert.Null(ex);
}
[Fact]
public void DottedNameWalksIntoTheProperty()
{
Assert.True(Check("Child.Value=7"));
Assert.False(Check("Child.Value=8"));
Assert.False(Check("Child.Value=7", new Subject { Child = null }));
Assert.False(Check("~Child.Value=7", new Subject { Child = null }));
}
[Fact]
public void NullableCompares()
{
Assert.True(Check("Maybe=null"));
Assert.False(Check("Maybe=5"));
Assert.True(Check("Maybe=5", new Subject { Maybe = 5 }));
Assert.True(Check("Maybe>4", new Subject { Maybe = 5 }));
}
// Two runtime types resolving the same declared property share one compiled predicate.
[Fact]
public void SubclassesShareThePredicateCompiledForTheDeclaringType()
{
var cache = new AdvancedSearchConditions.Cache();
var forBase = AdvancedSearchConditions.GetPredicate(cache, typeof(Subject), "Hue=5");
var forDerived = AdvancedSearchConditions.GetPredicate(cache, typeof(Derived), "Hue=5");
Assert.Same(forBase, forDerived);
Assert.True(forDerived(new Derived()));
}
}