## 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
200 lines
6.3 KiB
C#
200 lines
6.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Server;
|
|
using Server.Commands.Generic;
|
|
using Server.Items;
|
|
using Xunit;
|
|
|
|
namespace UOContent.Tests.Commands;
|
|
|
|
// `where` compiles conditions to IL. Two shapes were broken there: a property type with value
|
|
// equality but no IComparable fell through to a raw Ceq (reference equality, so never true), and
|
|
// a chained binding dereferenced every link with no null guard (so the first object with a null
|
|
// intermediate took the whole sweep down with an NRE).
|
|
[Collection("Sequential UOContent Tests")]
|
|
public class ObjectConditionalTests : IDisposable
|
|
{
|
|
private readonly List<Item> _items = [];
|
|
private readonly Mobile _from = new() { AccessLevel = AccessLevel.Developer };
|
|
|
|
public void Dispose()
|
|
{
|
|
for (var i = 0; i < _items.Count; i++)
|
|
{
|
|
_items[i].Delete();
|
|
}
|
|
|
|
_items.Clear();
|
|
_from.Delete();
|
|
}
|
|
|
|
private SkillTeleporter Teleporter(TextDefinition message)
|
|
{
|
|
var tp = new SkillTeleporter { Message = message };
|
|
_items.Add(tp);
|
|
return tp;
|
|
}
|
|
|
|
private bool Check(object target, params string[] condition)
|
|
{
|
|
var args = new string[condition.Length + 1];
|
|
args[0] = nameof(SkillTeleporter);
|
|
Array.Copy(condition, 0, args, 1, condition.Length);
|
|
|
|
return ObjectConditional.ParseDirect(_from, args, 0, args.Length).CheckCondition(target);
|
|
}
|
|
|
|
[Fact]
|
|
public void EqualityUsesValueSemanticsNotReferenceIdentity()
|
|
{
|
|
var tp = Teleporter(TextDefinition.Of(1060847));
|
|
|
|
Assert.True(Check(tp, "Message", "=", "1060847"));
|
|
}
|
|
|
|
[Fact]
|
|
public void InequalityUsesValueSemanticsNotReferenceIdentity()
|
|
{
|
|
var tp = Teleporter(TextDefinition.Of(1060847));
|
|
|
|
Assert.False(Check(tp, "Message", "!=", "1060847"));
|
|
Assert.True(Check(tp, "Message", "!=", "1234567"));
|
|
}
|
|
|
|
[Fact]
|
|
public void StringValuedDefinitionsCompareByValue()
|
|
{
|
|
var tp = Teleporter(TextDefinition.Of("Hail, traveller."));
|
|
|
|
Assert.True(Check(tp, "Message", "=", "Hail, traveller."));
|
|
Assert.False(Check(tp, "Message", "=", "Farewell."));
|
|
}
|
|
|
|
[Fact]
|
|
public void NullComparisonStillWorks()
|
|
{
|
|
Assert.True(Check(Teleporter(null), "Message", "=", "null"));
|
|
Assert.False(Check(Teleporter(TextDefinition.Of(1060847)), "Message", "=", "null"));
|
|
}
|
|
|
|
// The sweep case: [global where SkillTeleporter Message.Number = X hits teleporters whose
|
|
// Message was never set long before it hits one that matches.
|
|
[Fact]
|
|
public void ChainedBindingOnANullIntermediateIsFalseNotAnException()
|
|
{
|
|
var blank = Teleporter(null);
|
|
|
|
Assert.False(Check(blank, "Message.Number", "=", "1060847"));
|
|
}
|
|
|
|
[Fact]
|
|
public void ChainedBindingStillMatchesWhenIntermediateIsPresent()
|
|
{
|
|
var tp = Teleporter(TextDefinition.Of(1060847));
|
|
|
|
Assert.True(Check(tp, "Message.Number", "=", "1060847"));
|
|
Assert.False(Check(tp, "Message.Number", "=", "1234567"));
|
|
}
|
|
|
|
[Fact]
|
|
public void ChainedBindingOnANullIntermediateIsFalseUnderNegationToo()
|
|
{
|
|
var blank = Teleporter(null);
|
|
|
|
Assert.False(Check(blank, "not", "Message.Number", "=", "1060847"));
|
|
}
|
|
|
|
// The string operators (contains / starts / ends / =~) compile through StringCondition, which
|
|
// chains the same way ComparisonCondition does and so had the same null-intermediate crash.
|
|
[Theory]
|
|
[InlineData("contains")]
|
|
[InlineData("contains~")]
|
|
[InlineData("starts")]
|
|
[InlineData("ends")]
|
|
[InlineData("=~")]
|
|
[InlineData("!=~")]
|
|
public void StringOperatorsOnANullIntermediateAreFalseNotAnException(string oper)
|
|
{
|
|
var blank = Teleporter(null);
|
|
|
|
Assert.False(Check(blank, "Message.String", oper, "gate"));
|
|
}
|
|
|
|
[Fact]
|
|
public void StringOperatorsOnANullIntermediateAreFalseUnderNegationToo()
|
|
{
|
|
var blank = Teleporter(null);
|
|
|
|
Assert.False(Check(blank, "not", "Message.String", "contains", "gate"));
|
|
}
|
|
|
|
[Fact]
|
|
public void StringOperatorsStillMatchThroughAChain()
|
|
{
|
|
var tp = Teleporter(TextDefinition.Of("Moongate"));
|
|
|
|
Assert.True(Check(tp, "Message.String", "contains", "gate"));
|
|
Assert.True(Check(tp, "Message.String", "starts", "Moon"));
|
|
Assert.True(Check(tp, "Message.String", "ends", "gate"));
|
|
Assert.True(Check(tp, "Message.String", "=~", "moongate"));
|
|
Assert.False(Check(tp, "Message.String", "contains", "portal"));
|
|
}
|
|
|
|
// The chain resolves here -- Message is set -- but its String is null because the definition
|
|
// holds a cliloc. That is the final value, which StringCondition already guarded.
|
|
[Fact]
|
|
public void StringOperatorsHandleANullFinalValue()
|
|
{
|
|
var tp = Teleporter(TextDefinition.Of(1060847));
|
|
|
|
Assert.False(Check(tp, "Message.String", "contains", "gate"));
|
|
Assert.False(Check(tp, "Message.String", "=~", "gate"));
|
|
}
|
|
|
|
[Fact]
|
|
public void UnchainedStringOperatorsStillWork()
|
|
{
|
|
var tp = Teleporter(null);
|
|
tp.Name = "Moongate";
|
|
|
|
Assert.True(Check(tp, "Name", "contains", "gate"));
|
|
Assert.True(Check(tp, "Name", "=~", "moongate"));
|
|
Assert.False(Check(tp, "Name", "contains", "portal"));
|
|
}
|
|
|
|
// Guards for the comparison paths the equality change must not disturb. Ints, strings and
|
|
// enums are IComparable, so they route through CompareTo and never reach CompareEquality --
|
|
// these prove that routing is intact.
|
|
[Fact]
|
|
public void NumericComparisonsStillWork()
|
|
{
|
|
var tp = Teleporter(null);
|
|
tp.Hue = 42;
|
|
|
|
Assert.True(Check(tp, "Hue", "=", "42"));
|
|
Assert.False(Check(tp, "Hue", "=", "43"));
|
|
Assert.True(Check(tp, "Hue", ">", "41"));
|
|
Assert.True(Check(tp, "Hue", "<", "43"));
|
|
Assert.True(Check(tp, "Hue", "!=", "43"));
|
|
}
|
|
|
|
[Fact]
|
|
public void StringComparisonsStillWork()
|
|
{
|
|
var tp = Teleporter(null);
|
|
tp.Name = "gate";
|
|
|
|
Assert.True(Check(tp, "Name", "=", "gate"));
|
|
Assert.False(Check(tp, "Name", "=", "portal"));
|
|
}
|
|
|
|
[Fact]
|
|
public void EnumComparisonsStillWork()
|
|
{
|
|
var tp = Teleporter(null);
|
|
tp.Skill = SkillName.Magery;
|
|
|
|
Assert.True(Check(tp, "Skill", "=", "Magery"));
|
|
Assert.False(Check(tp, "Skill", "=", "Anatomy"));
|
|
}
|
|
}
|