From 7652717f3f45d0b383060ce5b886571a7d871bb8 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 25 Nov 2026 11:32:03 +0000 Subject: [PATCH 1/3] chore: sync installed skill hashes --- skills-lock.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/skills-lock.json b/skills-lock.json index d8f4457..c7f16bd 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -17,13 +17,13 @@ "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-adoption/SKILL.md", - "computedHash": "ed38157d532c45582bc3f768ca6605c4cbc1339fbbb6a45e34a8badee06af06f" + "computedHash": "5380ee60e34197a8af5ba8ec32e13ef84e541d014fe143ca0d815fff30a1b758" }, "purview-buildsdk-configuration": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-configuration/SKILL.md", - "computedHash": "7f33e4fee919a7e67033763f76f8e99e585ef128c937c6df58ebdae823949934" + "computedHash": "6eb2359d0c6acba80c5ea548c28e0e4df52ea5157435ba4372fde7e42981a577" }, "purview-buildsdk-docs-sync": { "source": "purview-dev/build-sdk", @@ -47,7 +47,7 @@ "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-project-detection/SKILL.md", - "computedHash": "8b39fdeba80cad1cfd19d394209affc95d2dbc3e6a2e0358d14dc54ba6892ed7" + "computedHash": "219f323ebd77536fa3424957798b88b89ae119cecef6d801d3101ab7981d6828" }, "purview-buildsdk-project-layout": { "source": "purview-dev/build-sdk", @@ -59,7 +59,7 @@ "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-repository-review/SKILL.md", - "computedHash": "08a5b7a34511959b72702ae8107c15ece77a27a7ef58c0b6b08e25a206f76c25" + "computedHash": "e09488299f61af4292be2a64c90622a826fd9a7df2640a73ddcc953216c07836" }, "purview-buildsdk-settings-docs-sync": { "source": "purview-dev/build-sdk", @@ -71,7 +71,7 @@ "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-skill-installation/SKILL.md", - "computedHash": "5a8cffd36dc696ec86276ddd089e9f859d4571b7606b46c0b82a5c52d5935e16" + "computedHash": "e00f5a1b4c1ab728338c9ccbfaf59dd0c2d228be4a30149d16699b2dce86fe8e" }, "purview-buildsdk-skill-tests": { "source": "purview-dev/build-sdk", From 6f086c4f74ad82e27b1f7f5378c2e592cf2370af Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 25 Nov 2026 11:32:11 +0000 Subject: [PATCH 2/3] fix: compare complex value object collections by contents Generated equality, hashing and comparison now compare array and IEnumerable members by contents through the new runtime ValueObjectEquality helper. Sets and dictionaries compare without regard to order, nested collections recurse, dictionary collection values recurse, null never equals empty, and CompareTo has a defined total order instead of throwing. A record now receives the generated Equals(TSelf): the compiler- synthesized record equality compared collection members by reference. A derived record delegates to base.Equals and includes base.GetHashCode(), and its inherited public record members are included in Create, Hydrate, hooks, the constructor and JSON serialization, so it round-trips with its base state. Also fixes CS0121 for a complex value object with a single value-type member by typing the generated parameterless constructor argument, and adds C# 15 support: concrete cases of closed hierarchies can be value objects, unions work as member types, and VO1032/VO1033 reject closed/abstract types and union declarations. Bumps the package to 2.0.1. --- AGENTS.md | 2 +- CHANGELOG.md | 36 ++ README.md | 1 + docs/Diagnostics.md | 2 + docs/Getting-Started.md | 14 + docs/Trimming-AOT-and-Blazor.md | 4 + docs/Value-Object-Design.md | 37 ++ package.json | 2 +- .../SKILL.md | 2 + skills/purview-value-objects/SKILL.md | 12 + .../AnalyzerReleases.Unshipped.md | 2 + .../ValueObjectDiagnosticAnalyzer.cs | 2 + .../Common/DiagnosticLibrary.cs | 20 + .../Common/TypeLibrary.Constants.cs | 6 + .../ComplexValueObjectEmitter.Equality.cs | 81 ++- ...ComplexValueObjectEmitter.Serialization.cs | 2 +- .../ValueObject/ComplexValueObjectEmitter.cs | 24 +- .../ComplexValueObjectModelBuilder.cs | 194 ++++++- .../Models/ComplexValueObjectModel.cs | 47 +- .../ValueObject/ValueObjectSymbolInspector.cs | 151 +++++- src/src/ValueObjects/Sdk/README.md | 2 + src/src/ValueObjects/ValueObjectEquality.cs | 480 ++++++++++++++++++ .../ValueObjectDiagnosticAnalyzerTests.cs | 45 ++ .../ValueObjectSourceGeneratorTests.cs | 456 +++++++++++++++++ ...ueObjectSourceGeneratorIncrementalTests.cs | 25 + .../Equality/CollectionEqualityModels.cs | 117 +++++ .../Equality/CollectionEqualityTests.cs | 238 +++++++++ .../Equality/ValueObjectEqualityTests.cs | 192 +++++++ 28 files changed, 2142 insertions(+), 54 deletions(-) create mode 100644 src/src/ValueObjects/ValueObjectEquality.cs create mode 100644 src/tests/ValueObjects.IntegrationTests/Equality/CollectionEqualityModels.cs create mode 100644 src/tests/ValueObjects.IntegrationTests/Equality/CollectionEqualityTests.cs create mode 100644 src/tests/ValueObjects.UnitTests/Equality/ValueObjectEqualityTests.cs diff --git a/AGENTS.md b/AGENTS.md index 738a579..c5b1000 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ a diagnostic analyzer, a code fix, tests, samples, and documentation for scalar | Path | Purpose | | --- | --- | | `src/ValueObjects.slnx` | Canonical solution for restore, build, test, and pack | -| `src/src/ValueObjects` | Runtime contracts (`[Scalar]`, `[ValueObject]`, `IValueObject`, `ScalarJsonConverterFactory`) | +| `src/src/ValueObjects` | Runtime contracts (`[Scalar]`, `[ValueObject]`, `IValueObject`, `ScalarJsonConverterFactory`, `ValueObjectEquality`) | | `src/src/SourceGenerator` | Roslyn incremental generator and analyzer metadata | | `src/src/SourceGenerator.Refactorings` | Code fixes (add `partial` modifier) | | `src/tests` | Unit and source-generator tests, plus the multi-framework Entity Framework Core compatibility project | diff --git a/CHANGELOG.md b/CHANGELOG.md index a592594..7263a11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,42 @@ Released versions correspond to `v` GitHub releases. `package.json` is newest heading below is the version in development. Earlier releases are listed under [releases](https://github.com/purview-dev/value-objects/releases). +## 2.0.1 + +### Fixed + +- **A complex value object compares a collection member by its contents, not by its reference.** The generated + `Equals`, `==`, `!=`, `GetHashCode` and `CompareTo` now route an array or `IEnumerable` member through + `ValueObjectEquality` instead of `EqualityComparer.Default` and `Comparer.Default`. Two instances built + from equal contents are now equal and hash equally, so `HashSet`, `Dictionary`, `Assert` and + record-style comparison behave as a value object should. Ordered sequences compare order-sensitively; an + `ISet`/`IReadOnlySet` compares without regard to order, as does an + `IDictionary`/`IReadOnlyDictionary`. A `null` collection equals `null` but not an + empty one, a collection of collections recurses, and a dictionary whose value is a collection compares that value + structurally. +- **A `record` complex value object now gets the generated `Equals(TSelf)`.** The C# compiler's synthesized record + `Equals` compared collection members by reference and could not be fixed from outside; the generated member + suppresses it (and is `virtual` for a non-sealed record class). A record and a non-record now agree. +- **A derived record's base members are part of its identity and its serialized shape.** The generated equality + calls `base.Equals` and the hash includes `base.GetHashCode()`, instead of silently dropping the base record's + state. The generated `Create`, `Hydrate`, hooks, constructor and JSON converter now include the inherited public + record members (base first), so a derived record round-trips through JSON and reconstructs its base state. +- **`CompareTo` no longer throws `ArgumentException` for a collection member.** Collections have a defined total + order: `null` first, then `Count`, then the elements (ordered sequences) or an order-insensitive content hash + (sets and dictionaries). +- **A complex value object with a single value-type member no longer fails to compile.** The generated + parameterless constructor emitted a bare `default` argument, which was ambiguous between the record's copy + constructor and the member constructor (`CS0121`); it now spells the type. + +This is a behaviour change: instances that compared unequal now compare equal, and their hash codes change. + +### Added + +- **C# 15 constructs are supported where they make sense.** A concrete case of a `closed` hierarchy can be a + `[ValueObject]` (its equality delegates to the base), and a `union` can be a value-object member and keeps its + own generated equality. Marking a `closed`/abstract type (`VO1032`) or a union declaration (`VO1033`) as a value + object is now a clear error rather than a compiler error in generated code. + ## 2.0.0 A major release for the .NET 11 GA. It drops the two out-of-support target frameworks and modernises the build; diff --git a/README.md b/README.md index 885c43b..4895882 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ incremental source generator produces: - `Create` / `Hydrate` / `TryCreate` factories with `OnNormalize` normalization and `OnValidate` validation - `Empty` instances, `HasValue` for null-capable scalars, equality, comparison, `CompareTo`, `ToString` (including the underlying value's `IFormattable` and format overloads), implicit conversions (with explicit extraction for nullable scalars) +- Value semantics for collection members: arrays and sequences compare in order, sets and dictionaries compare without regard to order, and a collection of collections recurses - The underlying value's standard interfaces — `IEquatable`, `ISpanFormattable`, `IUtf8SpanFormattable`, `IParsable`, `ISpanParsable`, and `IUtf8SpanParsable` — mirrored per type - JSON converters (scalar value objects serialize as their underlying value) - Contextual creation via `IContextualValueObject<,>` + `ValueObjectContext` diff --git a/docs/Diagnostics.md b/docs/Diagnostics.md index f25d815..e4cdde6 100644 --- a/docs/Diagnostics.md +++ b/docs/Diagnostics.md @@ -25,6 +25,8 @@ These govern the declaration shape a value object must have for the generator to | `VO1028` | Error | `[Scalar(Nullable = true)]` is combined with a declared `Value` property, so nullability has two sources. | Remove the declared `Value`; convert to the manual `[Scalar]` form; or remove `Nullable = true`. The code fix offers all three. | | `VO1029` | Error | Explicit `Nullable = false` contradicts a declared nullable `Value` property. | Remove the declared `Value`, or use the manual `[Scalar]` form and own the property. | | `VO1030` | Error | The automatic form's declared `Value` has a type that does not match the scalar's underlying type. | Remove the declaration, or use the manual `[Scalar]` form with a matching type. | +| `VO1032` | Error | A `closed` or `abstract` type is marked `[Scalar]`/`[ValueObject]`. A closed type is implicitly abstract, so the generated `Create`/`Hydrate` cannot instantiate it. | Mark a concrete derived type as the value object instead. | +| `VO1033` | Error | A C# 15 `union` declaration is marked `[Scalar]`/`[ValueObject]`. A union already provides its own `value`/`HasValue`/`TryGetValue` and equality members and cannot carry a partial value-object declaration. | Use the union as a member type; mark a record or class as the value object instead. | ## ZodSharp validation rules diff --git a/docs/Getting-Started.md b/docs/Getting-Started.md index 5337c88..0f5a223 100644 --- a/docs/Getting-Started.md +++ b/docs/Getting-Started.md @@ -267,6 +267,20 @@ public readonly partial record struct Money } ``` +A collection member participates in equality and hashing by its **contents**. An array or `IEnumerable` +member compares element by element in order; an `ISet`/`IReadOnlySet` compares without regard to +order, and so does an `IDictionary`/`IReadOnlyDictionary` (including a +collection value). `null` equals `null` but not an empty collection, and a collection of collections +compares recursively. Elements use `EqualityComparer.Default`, so a nested value object keeps its own +generated equality. `CompareTo` orders a collection member by its count and then its contents rather than +throwing. + +A derived record's inherited public members are part of its identity **and** its generated `Create`, +`Hydrate`, hooks, constructor and JSON shape (base members first), so a derived record round-trips with its +base state. A concrete case of a C# 15 `closed` hierarchy can be a `[ValueObject]`; a closed or abstract type +itself cannot (`VO1032`), because it cannot be instantiated. A C# 15 `union` can be a member and keeps its own +generated equality, but a union declaration cannot itself be a value object (`VO1033`). + ## 4. Contextual value objects When validity depends on the owning instance, implement `IContextualValueObject`: diff --git a/docs/Trimming-AOT-and-Blazor.md b/docs/Trimming-AOT-and-Blazor.md index 46ebc42..6ca5b94 100644 --- a/docs/Trimming-AOT-and-Blazor.md +++ b/docs/Trimming-AOT-and-Blazor.md @@ -72,6 +72,10 @@ Inside a generated converter: - anything else - an enum, or a custom underlying type - needs metadata, so add `[JsonSerializable(typeof(T))]` to the context. The `NotSupportedException` thrown otherwise names the type. +Generated collection equality is reflection-free too: `Equals`, `GetHashCode` and `CompareTo` call the generic +`ValueObjectEquality` helpers, which use only `EqualityComparer.Default`, interfaces and enumerators, so an array +or collection member stays trimming- and Native AOT-safe. + ## ZodSharp packages A Native AOT minimal API with `[Scalar]` + `[ZodSchema]` value objects in `Strict` mode, built against ZodSharp diff --git a/docs/Value-Object-Design.md b/docs/Value-Object-Design.md index 6814bfc..4d9837e 100644 --- a/docs/Value-Object-Design.md +++ b/docs/Value-Object-Design.md @@ -121,6 +121,43 @@ The value object always implements `IComparable` and `IComparable` (and a `CompareTo(TValue)`) because the value-object contract requires it. Numeric and arithmetic interfaces, `IConvertible`, and collection interfaces are intentionally not mirrored. +## Equality and hashing + +A complex value object's identity includes its collection members by **contents**. The generated `Equals`, +`==`, `!=` and `GetHashCode` route an array or `IEnumerable` member through `ValueObjectEquality` rather +than `EqualityComparer.Default`, whose collection implementation is reference identity: + +| Member shape | Equality | Hash | +| --- | --- | --- | +| array or other `IEnumerable` | ordered sequence, element by element | order-sensitive | +| `ISet` / `IReadOnlySet` | set contents, order-insensitive | order-insensitive | +| `IDictionary` / `IReadOnlyDictionary` | same keys mapped to equal values, order-insensitive | order-insensitive | + +Elements compare through `EqualityComparer.Default`, so a nested value object keeps its own generated +equality, a collection of collections recurses, and a dictionary whose value is a collection compares that +value structurally. `null` equals `null` but not an empty collection; a nullable collection member never +throws. A custom `ISet`/`IDictionary` comparer is not observed, because using it for +equality while hashing with `EqualityComparer.Default` would let equal values produce different hashes; +a dictionary key that is itself a collection is likewise not recursed. + +This applies to records and non-records alike: the generator declares `Equals(TSelf)` on a record (the +compiler-synthesized record member compares fields by reference), marking it `virtual` on a non-sealed +record class. A derived record's base members are included through `base.Equals` and `base.GetHashCode()`, +and its inherited public record members are included (base first) in the generated `Create`, `Hydrate`, +hooks, constructor and JSON converter — so the serialized shape and the factories agree with identity. +`CompareTo` gives a collection member a defined total order — `null` first, then `Count`, then the elements +(ordered sequences) or an order-insensitive content hash (sets and dictionaries) — so it no longer throws +`ArgumentException` ("At least one object must implement IComparable"). + +### C# 15 constructs + +A concrete case of a `closed` hierarchy can be a `[ValueObject]` (for example a positional record deriving +from a `closed` base); equality delegates to the base as above. A `closed` type is implicitly abstract, so +marking the closed type itself is `VO1032`; mark a concrete derived type instead. A `union` can be a value +object member and takes part in equality through its own generated equality, but a union declaration cannot +itself be a `[ValueObject]` (`VO1033`) — it already provides its own value, equality and `TryGetValue` +members and cannot carry a partial value-object declaration. + ## Contextual value objects `IContextualValueObject` lets a value object validate against the owning instance: diff --git a/package.json b/package.json index 68c2616..cf1da5a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "value-objects", - "version": "2.0.0", + "version": "2.0.1", "license": "MIT", "author": { "name": "Kieron Lanning", diff --git a/skills/purview-value-objects-diagnostics/SKILL.md b/skills/purview-value-objects-diagnostics/SKILL.md index 7f6b150..ea9a121 100644 --- a/skills/purview-value-objects-diagnostics/SKILL.md +++ b/skills/purview-value-objects-diagnostics/SKILL.md @@ -35,6 +35,8 @@ failure to the missing member. | `VO1028` | Error | `[Scalar(Nullable = true)]` is combined with a declared `Value`, so nullability has two sources. | Remove the declared property; convert to the manual `[Scalar]` form; or remove `Nullable = true`. The code fix offers all three. | | `VO1029` | Error | Explicit `Nullable = false` contradicts a declared nullable `Value`. | Remove the declared `Value`, or use the manual `[Scalar]` form. | | `VO1030` | Error | The automatic form's declared `Value` type does not match the underlying type. | Remove the declaration, or use the manual `[Scalar]` form with a matching type. | +| `VO1032` | Error | A `closed` or `abstract` type is marked `[Scalar]`/`[ValueObject]`. A closed type is implicitly abstract, so the generated `Create`/`Hydrate` cannot instantiate it. | Mark a concrete derived type as the value object instead. | +| `VO1033` | Error | A C# 15 `union` declaration is marked `[Scalar]`/`[ValueObject]`. A union already provides its own value/equality members and cannot be a partial value object. | Use the union as a member type and mark a record or class as the value object instead. | ## String normalization rules diff --git a/skills/purview-value-objects/SKILL.md b/skills/purview-value-objects/SKILL.md index a42b1fa..f8390cf 100644 --- a/skills/purview-value-objects/SKILL.md +++ b/skills/purview-value-objects/SKILL.md @@ -140,6 +140,18 @@ Keep members `readonly`/`init`-only — a mutable member is `VO1016` and makes e `struct`, declare `OnValidate` as `readonly` when it does not mutate; the generator mirrors the modifier. +A collection member takes part in identity by its contents: arrays and other sequences compare in order, +`ISet`/`IReadOnlySet` and `IDictionary`/`IReadOnlyDictionary` compare +without regard to order, and a collection of collections or a collection-valued dictionary entry recurses. +`null` equals `null` but not an empty collection, and `CompareTo` orders by count then contents instead of +throwing. Records and non-records behave the same; a derived record includes its base members through +`base.Equals`/`base.GetHashCode()`, and the inherited public record members are part of `Create`/`Hydrate`, +the hooks, the constructor and the JSON shape (base first). + +A concrete case of a C# 15 `closed` hierarchy can be `[ValueObject]`, but the closed type itself is +implicitly abstract (`VO1032`). A `union` can be a member, but a union declaration cannot be a value object +(`VO1033`). + ## Contextual value objects When validity depends on the owning instance's current state — a state machine, a cross-field rule diff --git a/src/src/SourceGenerator/AnalyzerReleases.Unshipped.md b/src/src/SourceGenerator/AnalyzerReleases.Unshipped.md index f21fc2d..2f6c553 100644 --- a/src/src/SourceGenerator/AnalyzerReleases.Unshipped.md +++ b/src/src/SourceGenerator/AnalyzerReleases.Unshipped.md @@ -8,4 +8,6 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- +VO1032 | ValueObjects | Error | A closed or abstract type cannot be a value object; mark a concrete derived type instead. +VO1033 | ValueObjects | Error | A union declaration cannot be a value object; use the union as a member type instead. diff --git a/src/src/SourceGenerator/Analyzers/ValueObjectDiagnosticAnalyzer.cs b/src/src/SourceGenerator/Analyzers/ValueObjectDiagnosticAnalyzer.cs index f2136e4..08fc773 100644 --- a/src/src/SourceGenerator/Analyzers/ValueObjectDiagnosticAnalyzer.cs +++ b/src/src/SourceGenerator/Analyzers/ValueObjectDiagnosticAnalyzer.cs @@ -34,6 +34,8 @@ public sealed class ValueObjectDiagnosticAnalyzer : DiagnosticAnalyzer DiagnosticLibrary.ScalarNullabilityContradictsProperty, DiagnosticLibrary.ScalarPropertyTypeMismatch, DiagnosticLibrary.NullableScalarPropertyShouldBeNullable, + DiagnosticLibrary.ValueObjectMustBeInstantiable, + DiagnosticLibrary.UnionValueObjectsAreNotSupported, ]; public override void Initialize(AnalysisContext context) diff --git a/src/src/SourceGenerator/Common/DiagnosticLibrary.cs b/src/src/SourceGenerator/Common/DiagnosticLibrary.cs index c808b44..5010095 100644 --- a/src/src/SourceGenerator/Common/DiagnosticLibrary.cs +++ b/src/src/SourceGenerator/Common/DiagnosticLibrary.cs @@ -283,4 +283,24 @@ public static class DiagnosticLibrary isEnabledByDefault: true, customTags: [WellKnownDiagnosticTags.CompilationEnd] ); + + /// VO1032: A closed or abstract type cannot be a value object + public static readonly DiagnosticDescriptor ValueObjectMustBeInstantiable = new( + id: "VO1032", + title: "Value object must be instantiable", + messageFormat: "Value object '{0}' cannot be used with [{1}] because it is {2}; mark a concrete type as the value object instead", + category: ValueObjectCategory, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true + ); + + /// VO1033: A union cannot be a value object + public static readonly DiagnosticDescriptor UnionValueObjectsAreNotSupported = new( + id: "VO1033", + title: "Unions cannot be value objects", + messageFormat: "Value object '{0}' is a union and cannot be used with [{1}]; a union already provides its own value, equality and TryGetValue members, so use the union as a member type instead", + category: ValueObjectCategory, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true + ); } diff --git a/src/src/SourceGenerator/Common/TypeLibrary.Constants.cs b/src/src/SourceGenerator/Common/TypeLibrary.Constants.cs index 084c3cb..3457439 100644 --- a/src/src/SourceGenerator/Common/TypeLibrary.Constants.cs +++ b/src/src/SourceGenerator/Common/TypeLibrary.Constants.cs @@ -46,6 +46,12 @@ public static partial class TypeLibrary /// public const string ValueObjectJsonGlobalName = "global::" + SerializationNamespace + ".ValueObjectJson"; + /// + /// The runtime's collection equality, hashing and ordering helpers, which generated complex equality and + /// comparison members call for a collection member instead of EqualityComparer<T>.Default. + /// + public const string ValueObjectEqualityGlobalName = "global::" + ValueObjectsNamespace + ".ValueObjectEquality"; + // ZodSharp's runtime and generator-emitted types. The ZodSharp attribute and schema types are produced // by the ZodSharp source generator, so these names are matched and emitted as qualified text rather than // resolved as symbols (the value object generator must keep working when ZodSharp is not referenced). diff --git a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Equality.cs b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Equality.cs index d0b0d57..20f08db 100644 --- a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Equality.cs +++ b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Equality.cs @@ -9,6 +9,9 @@ static void EmitEquality(CodeWriter writer, ComplexValueObjectModel model) writer.Method( new("Equals", PurviewTypeLibrary.System.Boolean, TypeDeclarationAccessibility.Public) { + // A non-sealed record class requires Equals(TSelf) to allow overriding (CS8872); a sealed + // record class, a record struct and a non-record type declare it non-virtual. + IsVirtual = model.IsRecord && model.IsReferenceType && !model.IsSealed, // IEquatable.Equals takes a nullable parameter for a reference type, so a class // value object must accept null to satisfy the interface. Parameters = @@ -24,12 +27,23 @@ static void EmitEquality(CodeWriter writer, ComplexValueObjectModel model) if (model.IsReferenceType) body.IfBlock("other is null", ifBody => ifBody.Return("false")); + // A derived record's base members are part of its identity. The base record's own + // equality decides whether they match; the contract check keeps a derived record from + // comparing equal to a differently derived one, as the compiler-synthesized record + // equality does. + if (model.RecordBaseTypeName is { } recordBaseType) + body.IfBlock($"!base.Equals(({recordBaseType})other)", ifBody => ifBody.Return("false")); + + if ( + model.IsRecord + && model.IsReferenceType + && (model.RecordBaseTypeName is not null || !model.IsSealed) + ) + body.IfBlock("EqualityContract != other.EqualityContract", ifBody => ifBody.Return("false")); + foreach (var property in model.Properties) { - body.IfBlock( - $"!global::System.Collections.Generic.EqualityComparer<{property.TypeName}>.Default.Equals({property.Name}, other.{property.Name})", - ifBody => ifBody.Return("false") - ); + body.IfBlock($"!{EqualityExpression(property)}", ifBody => ifBody.Return("false")); } body.Return("true"); @@ -59,8 +73,13 @@ static void EmitEquality(CodeWriter writer, ComplexValueObjectModel model) body => { body.Assignment("var", "hash", "new global::System.HashCode()"); + // Equal derived records compare their base members through base.Equals above, so the + // hash must include the base hash to keep the equal-implies-equal hash contract. + if (model.RecordBaseTypeName is not null) + body.MethodCallOn("hash", "Add", "base.GetHashCode()"); + foreach (var property in model.Properties) - body.MethodCallOn("hash", "Add", property.Name); + body.MethodCallOn("hash", "Add", HashExpression(property)); body.Return("hash.ToHashCode()"); } @@ -115,13 +134,9 @@ static void EmitComparison(CodeWriter writer, ComplexValueObjectModel model) if (model.IsReferenceType) body.IfBlock("other is null", ifBody => ifBody.Return("1")); - foreach (var property in model.Properties) + foreach (var property in model.AllProperties) { - body.Assignment( - "var", - $"compare{property.Name}", - $"global::System.Collections.Generic.Comparer<{property.TypeName}>.Default.Compare({property.Name}, other.{property.Name})" - ); + body.Assignment("var", $"compare{property.Name}", ComparisonExpression(property)); body.IfBlock($"compare{property.Name} != 0", ifBody => ifBody.Return($"compare{property.Name}") ); @@ -163,4 +178,48 @@ static void EmitComparison(CodeWriter writer, ComplexValueObjectModel model) ); } } + + static string EqualityExpression(ComplexPropertyModel property) => + property.CollectionKind switch + { + ComplexMemberCollectionKind.Sequence => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.SequenceEquals<{property.CollectionElementTypeName}>({property.Name}, other.{property.Name}{ComparerArgument(property)})", + ComplexMemberCollectionKind.Set => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.SetEquals<{property.CollectionElementTypeName}>({property.Name}, other.{property.Name}{ComparerArgument(property)})", + ComplexMemberCollectionKind.Dictionary => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.DictionaryEquals({property.Name}, other.{property.Name}{ValueComparerArgument(property)})", + _ => + $"global::System.Collections.Generic.EqualityComparer<{property.TypeName}>.Default.Equals({property.Name}, other.{property.Name})", + }; + + static string HashExpression(ComplexPropertyModel property) => + property.CollectionKind switch + { + ComplexMemberCollectionKind.Sequence => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.SequenceHash<{property.CollectionElementTypeName}>({property.Name}{ComparerArgument(property)})", + ComplexMemberCollectionKind.Set => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.SetHash<{property.CollectionElementTypeName}>({property.Name}{ComparerArgument(property)})", + ComplexMemberCollectionKind.Dictionary => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.DictionaryHash({property.Name}{ValueComparerArgument(property)})", + _ => property.Name, + }; + + static string ComparisonExpression(ComplexPropertyModel property) => + property.CollectionKind switch + { + ComplexMemberCollectionKind.Sequence => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.SequenceCompare<{property.CollectionElementTypeName}>({property.Name}, other.{property.Name}{ComparerArgument(property)})", + ComplexMemberCollectionKind.Set => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.SetCompare<{property.CollectionElementTypeName}>({property.Name}, other.{property.Name}{ComparerArgument(property)})", + ComplexMemberCollectionKind.Dictionary => + $"{TypeLibrary.ValueObjectEqualityGlobalName}.DictionaryCompare({property.Name}, other.{property.Name}{ValueComparerArgument(property)})", + _ => + $"global::System.Collections.Generic.Comparer<{property.TypeName}>.Default.Compare({property.Name}, other.{property.Name})", + }; + + static string ComparerArgument(ComplexPropertyModel property) => + property.CollectionElementComparerExpression is { } comparer ? $", {comparer}" : string.Empty; + + static string ValueComparerArgument(ComplexPropertyModel property) => + property.CollectionValueComparerExpression is { } comparer ? $", {comparer}" : string.Empty; } diff --git a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Serialization.cs b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Serialization.cs index 1b8ce61..f4761c3 100644 --- a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Serialization.cs +++ b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.Serialization.cs @@ -20,7 +20,7 @@ static void EmitJsonConverter(CodeWriter writer, ComplexValueObjectModel model) return; var helper = TypeLibrary.ValueObjectJsonGlobalName; - var properties = model.Properties.ToArray(); + var properties = model.AllProperties.ToArray(); var hydrateArgs = string.Join(", ", properties.Select(static (_, index) => MemberLocal(index))); var valueObjectType = ValueObjectType(model); var unableToDeserialize = $"\"Unable to deserialize {model.TypeModel.Name}.\""; diff --git a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.cs b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.cs index c298451..7ee6b90 100644 --- a/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.cs +++ b/src/src/SourceGenerator/ValueObject/ComplexValueObjectEmitter.cs @@ -103,7 +103,7 @@ static void EmitOnNormalizeDeclaration(CodeWriter writer, ComplexValueObjectMode IsStatic = true, Parameters = [ - .. model.Properties.Select(static property => new ParameterDeclarationOptions( + .. model.AllProperties.Select(static property => new ParameterDeclarationOptions( ValueObjectSymbolInspector.ToCamelCase(property.Name), property.Type, ParameterModifier.Ref @@ -119,7 +119,7 @@ static void EmitCreateFactory(CodeWriter writer, ComplexValueObjectModel model) return; var normalizeArgs = model - .Properties.Select(property => $"ref {ValueObjectSymbolInspector.ToCamelCase(property.Name)}") + .AllProperties.Select(property => $"ref {ValueObjectSymbolInspector.ToCamelCase(property.Name)}") .ToArray(); writer.Method( @@ -128,7 +128,7 @@ static void EmitCreateFactory(CodeWriter writer, ComplexValueObjectModel model) IsStatic = true, Parameters = [ - .. model.Properties.Select(static property => new ParameterDeclarationOptions( + .. model.AllProperties.Select(static property => new ParameterDeclarationOptions( ValueObjectSymbolInspector.ToCamelCase(property.Name), property.Type )), @@ -136,7 +136,7 @@ static void EmitCreateFactory(CodeWriter writer, ComplexValueObjectModel model) }, body => { - foreach (var property in model.Properties) + foreach (var property in model.AllProperties) { var parameterName = ValueObjectSymbolInspector.ToCamelCase(property.Name); if ( @@ -157,7 +157,7 @@ static void EmitCreateFactory(CodeWriter writer, ComplexValueObjectModel model) new ObjectCreationOptions( ValueObjectType(model), [ - .. model.Properties.Select(static property => new MethodCallArgumentOptions( + .. model.AllProperties.Select(static property => new MethodCallArgumentOptions( ValueObjectSymbolInspector.ToCamelCase(property.Name) )), ] @@ -177,7 +177,7 @@ static void EmitCreateFactory(CodeWriter writer, ComplexValueObjectModel model) body.MethodCall( "instance.OnValidate", [ - .. model.Properties.Select(static property => + .. model.AllProperties.Select(static property => ValueObjectSymbolInspector.ToCamelCase(property.Name) ), ] @@ -212,7 +212,7 @@ static void EmitOnValidateDeclaration(CodeWriter writer, ComplexValueObjectModel ], Parameters = [ - .. model.Properties.Select(static property => new ParameterDeclarationOptions( + .. model.AllProperties.Select(static property => new ParameterDeclarationOptions( ValueObjectSymbolInspector.ToCamelCase(property.Name), property.Type )), @@ -228,7 +228,7 @@ static void EmitHydrateFactory(CodeWriter writer, ComplexValueObjectModel model) var hydrateArgs = string.Join( ", ", - model.Properties.Select(static property => ValueObjectSymbolInspector.ToCamelCase(property.Name)) + model.AllProperties.Select(static property => ValueObjectSymbolInspector.ToCamelCase(property.Name)) ); writer.Method( @@ -237,7 +237,7 @@ static void EmitHydrateFactory(CodeWriter writer, ComplexValueObjectModel model) IsStatic = true, Parameters = [ - .. model.Properties.Select(static property => new ParameterDeclarationOptions( + .. model.AllProperties.Select(static property => new ParameterDeclarationOptions( ValueObjectSymbolInspector.ToCamelCase(property.Name), property.Type )), @@ -263,7 +263,7 @@ static void EmitEmpty(CodeWriter writer, ComplexValueObjectModel model) static void EmitConstructor(CodeWriter writer, ComplexValueObjectModel model) { - if (model.CtorExists || model.Properties.IsEmpty) + if (model.CtorExists || model.AllProperties.IsEmpty) return; writer.Constructor( @@ -271,7 +271,7 @@ static void EmitConstructor(CodeWriter writer, ComplexValueObjectModel model) { Parameters = [ - .. model.Properties.Select(static property => new ParameterDeclarationOptions( + .. model.AllProperties.Select(static property => new ParameterDeclarationOptions( ValueObjectSymbolInspector.ToCamelCase(property.Name), property.Type )), @@ -279,7 +279,7 @@ static void EmitConstructor(CodeWriter writer, ComplexValueObjectModel model) }, body => { - foreach (var property in model.Properties) + foreach (var property in model.AllProperties) body.Assignment(property.Name, ValueObjectSymbolInspector.ToCamelCase(property.Name)); } ); diff --git a/src/src/SourceGenerator/ValueObject/ComplexValueObjectModelBuilder.cs b/src/src/SourceGenerator/ValueObject/ComplexValueObjectModelBuilder.cs index fbc7871..bfa6927 100644 --- a/src/src/SourceGenerator/ValueObject/ComplexValueObjectModelBuilder.cs +++ b/src/src/SourceGenerator/ValueObject/ComplexValueObjectModelBuilder.cs @@ -58,42 +58,75 @@ .. ValueObjectSymbolInspector.ValidateValueObjectType(typeSymbol, "ValueObject", .Where(property => ValueObjectSymbolInspector.IsValueObjectMember(typeSymbol, property)) .OrderBy(property => property.Locations.FirstOrDefault()?.SourceSpan.Start ?? int.MaxValue) .ToArray(); + var inheritedProperties = CollectInheritedRecordProperties(typeSymbol, properties); + var allProperties = ImmutableArray.CreateBuilder( + inheritedProperties.Length + properties.Length + ); + allProperties.AddRange(inheritedProperties); + allProperties.AddRange(properties); + var factoryProperties = allProperties.ToImmutable(); CollectStringNormalizePlacementDiagnostics(typeSymbol, properties, diagnosticsList, cancellationToken); var ctorExists = typeSymbol .Constructors.Where(static ctor => !ctor.IsStatic) - .Any(ctor => ValueObjectSymbolInspector.ConstructorMatches(ctor, properties)); + .Any(ctor => ValueObjectSymbolInspector.ConstructorMatches(ctor, [.. factoryProperties])); var createExists = ValueObjectSymbolInspector.HasStaticFactory( typeSymbol, "Create", - [.. properties.Select(property => property.Type)] + [.. factoryProperties.Select(property => property.Type)] + ); + // Only an author-declared Create suppresses normalization. The analyzer runs over the + // post-generation compilation, where the generated Create is present but is not an author declaration. + var declaredCreateExists = ValueObjectSymbolInspector.HasDeclaredStaticFactory( + typeSymbol, + "Create", + [.. factoryProperties.Select(property => property.Type)] ); var propertyModels = BuildPropertyModels( typeSymbol, properties, - ValueObjectSymbolInspector.HasDeclaredStaticFactory( - typeSymbol, - "Create", - [.. properties.Select(property => property.Type)] - ), + declaredCreateExists, assemblyDefaults, location, diagnosticsList ); + // The base record's own generation already reports diagnostics for its members, so the inherited + // models reuse the resolution but discard the duplicate diagnostics. + var inheritedPropertyModels = BuildPropertyModels( + typeSymbol, + inheritedProperties, + declaredCreateExists, + assemblyDefaults, + location, + [] + ); + var allPropertyModels = ImmutableArray.CreateBuilder( + inheritedPropertyModels.Length + propertyModels.Length + ); + allPropertyModels.AddRange(inheritedPropertyModels); + allPropertyModels.AddRange(propertyModels); var hydrateExists = ValueObjectSymbolInspector.HasStaticFactory( typeSymbol, "Hydrate", - [.. properties.Select(property => property.Type)] + [.. factoryProperties.Select(property => property.Type)] ); var compareToSelfExists = ValueObjectSymbolInspector.HasInstanceMethod(typeSymbol, "CompareTo", [typeSymbol]); var compareToObjectExists = ValueObjectSymbolInspector.HasCompareToObject(typeSymbol); var isReferenceType = typeSymbol.TypeKind == TypeKind.Class; - var equalsSelfExists = - typeSymbol.IsRecord || ValueObjectSymbolInspector.HasInstanceMethod(typeSymbol, "Equals", [typeSymbol]); + // A derived record's base members are part of its identity. Create/Hydrate/JSON include the + // inherited public members, and equality also delegates to the base record so base state that is + // not exposed as a property still takes part. + var recordBaseTypeName = + isReferenceType && typeSymbol.BaseType is { IsRecord: true } recordBase + ? ValueObjectSymbolInspector.ToTypeName(recordBase) + : null; + // A record's compiler-synthesized Equals(TSelf) is implicitly declared, so it must not count as an + // author declaration: the emitter replaces it to give a collection member contents equality. + var equalsSelfExists = ValueObjectSymbolInspector.HasDeclaredInstanceMethod(typeSymbol, "Equals", [typeSymbol]); // IEquatable is added for every shape that does not already implement it (records synthesize // it). When the author declared Equals(TSelf), the interface is only added if their parameter is // nullability-compatible; a non-nullable reference parameter would report CS8767. @@ -116,17 +149,17 @@ [.. properties.Select(property => property.Type)] var declareOnNormalize = ValueObjectSymbolInspector.ShouldEmitComplexHookDeclaration( typeSymbol, "OnNormalize", - properties.Length, + factoryProperties.Length, includeRef: true ); var declareOnValidate = ValueObjectSymbolInspector.ShouldEmitComplexHookDeclaration( typeSymbol, "OnValidate", - properties.Length + factoryProperties.Length ); var validateHookIsReadOnly = typeSymbol.TypeKind == TypeKind.Struct - && ValueObjectSymbolInspector.IsComplexHookReadOnly(typeSymbol, "OnValidate", properties.Length); + && ValueObjectSymbolInspector.IsComplexHookReadOnly(typeSymbol, "OnValidate", factoryProperties.Length); var parameterlessCtorExists = typeSymbol .Constructors.Where(static ctor => !ctor.IsStatic) @@ -137,7 +170,7 @@ [.. properties.Select(property => property.Type)] var efConstructorArguments = ValueObjectSymbolInspector.TryGetEFConstructorArguments( typeSymbol, - properties, + [.. factoryProperties], out var efCtorArgs ) ? efCtorArgs @@ -153,7 +186,7 @@ out var efCtorArgs onValidateImplemented: ValueObjectSymbolInspector.HasHookImplementation( typeSymbol, "OnValidate", - properties.Length + factoryProperties.Length ), diagnosticsList ); @@ -194,13 +227,14 @@ out var efCtorArgs ); } - var emptyArguments = ImmutableArray.CreateBuilder(properties.Length); - foreach (var property in properties) + var emptyArguments = ImmutableArray.CreateBuilder(factoryProperties.Length); + foreach (var property in factoryProperties) emptyArguments.Add(ValueObjectSymbolInspector.GetEmptyValueExpression(property.Type)); ComplexValueObjectModel model = new( typeModel.Value, propertyModels, + allPropertyModels.ToImmutable(), valueObjectOptions, ctorExists, hintName, @@ -209,6 +243,8 @@ out var efCtorArgs typeSymbol.TypeKind == TypeKind.Struct, typeSymbol.IsRecord, typeSymbol.IsReadOnly, + typeSymbol.IsSealed, + recordBaseTypeName, typeSymbol.DeclaredAccessibility.ToTypeDeclarationAccessibility(), implementsSelfEquatable, mirrorIEquatableSelf, @@ -414,6 +450,12 @@ List diagnostics assemblyDefaults, diagnostics ); + var ( + collectionKind, + collectionElementTypeName, + collectionElementComparerExpression, + collectionValueComparerExpression + ) = ClassifyCollectionMember(property.Type); propertyModels.Add( new ComplexPropertyModel( property.Name, @@ -422,7 +464,11 @@ List diagnostics normalizeTrim, normalizeCasing, normalizeExplicit, - ResolveMemberJsonConverter(property.Type, typeSymbol.ContainingAssembly, assemblyDefaults) + ResolveMemberJsonConverter(property.Type, typeSymbol.ContainingAssembly, assemblyDefaults), + collectionKind, + collectionElementTypeName, + collectionElementComparerExpression, + collectionValueComparerExpression ) ); } @@ -469,6 +515,118 @@ List diagnostics return propertyModels.ToImmutable(); } + /// + /// The public record members declared by the base record chain, oldest base first, so the generated + /// factories, hooks, constructor and JSON converter include the state a derived record's identity already + /// includes through base.Equals. A base member hidden by the same name in a more derived type is + /// skipped so a generated constructor cannot declare the same parameter twice. + /// + static IPropertySymbol[] CollectInheritedRecordProperties( + INamedTypeSymbol typeSymbol, + IPropertySymbol[] ownProperties + ) + { + if (!typeSymbol.IsRecord || typeSymbol.TypeKind != TypeKind.Class) + return []; + + HashSet names = new(ownProperties.Select(static property => property.Name), StringComparer.Ordinal); + List baseTypes = []; + for (var baseType = typeSymbol.BaseType; baseType is { IsRecord: true }; baseType = baseType.BaseType) + baseTypes.Add(baseType); + baseTypes.Reverse(); + + List inherited = []; + foreach (var baseType in baseTypes) + { + foreach (var property in baseType.GetMembers().OfType()) + { + if ( + property.IsStatic + || property.IsIndexer + || property.GetMethod is null + || property.DeclaredAccessibility != Accessibility.Public + || !names.Add(property.Name) + ) + continue; + + inherited.Add(property); + } + } + + return [.. inherited]; + } + + /// + /// Classifies a member's collection so the emitter never re-derives it: a dictionary or set is unordered and + /// compares without regard to order, and every other collection is an ordered sequence. A collection whose + /// element is itself a collection also carries the structural comparer the generated helper needs, so a nested + /// collection compares by contents rather than by reference. + /// + static ( + ComplexMemberCollectionKind Kind, + string? ElementTypeName, + string? ElementComparerExpression, + string? ValueComparerExpression + ) ClassifyCollectionMember(ITypeSymbol memberType) + { + if (!ValueObjectSymbolInspector.IsCollectionMember(memberType)) + return (ComplexMemberCollectionKind.None, null, null, null); + + if (ValueObjectSymbolInspector.TryGetDictionaryTypeArguments(memberType, out _, out var valueType)) + { + return (ComplexMemberCollectionKind.Dictionary, null, null, BuildElementComparerExpression(valueType)); + } + + var isSet = ValueObjectSymbolInspector.IsSetCollection(memberType); + // A set is also an IEnumerable, so the element type is resolved the same way for both shapes. + var elementType = ValueObjectSymbolInspector.GetCollectionElementType(memberType); + if (elementType is null) + return (ComplexMemberCollectionKind.None, null, null, null); + + return ( + isSet ? ComplexMemberCollectionKind.Set : ComplexMemberCollectionKind.Sequence, + ValueObjectSymbolInspector.ToTypeName(elementType), + BuildElementComparerExpression(elementType), + null + ); + } + + /// + /// The expression that constructs the structural comparer for a collection element that is itself a + /// collection, or when the element is a scalar. The comparer is recursive: a + /// collection of collections of collections keeps comparing by contents at every level. + /// + static string? BuildElementComparerExpression(ITypeSymbol elementType) + { + if (!ValueObjectSymbolInspector.IsCollectionMember(elementType)) + return null; + + var comparerNamespace = "global::" + TypeLibrary.ValueObjectsNamespace; + + if (ValueObjectSymbolInspector.TryGetDictionaryTypeArguments(elementType, out var keyType, out var valueType)) + { + var valueComparer = BuildElementComparerExpression(valueType); + var valueComparerArgument = valueComparer is null ? string.Empty : valueComparer; + return $"new {comparerNamespace}.ValueObjectDictionaryComparer<{ValueObjectSymbolInspector.ToTypeName(keyType)}, {ValueObjectSymbolInspector.ToTypeName(valueType)}>({valueComparerArgument})"; + } + + var nestedElementType = ValueObjectSymbolInspector.GetCollectionElementType(elementType); + if (nestedElementType is null) + return null; + + var isSet = ValueObjectSymbolInspector.IsSetCollection(elementType); + var nestedComparer = BuildElementComparerExpression(nestedElementType); + var comparerType = isSet ? "ValueObjectSetComparer" : "ValueObjectSequenceComparer"; + // A sequence's comparer takes both an equality and an order comparer for its element; a set is + // unordered, so its comparer only needs equality. + var comparerArguments = + nestedComparer is null ? string.Empty + : isSet ? nestedComparer + : $"{nestedComparer}, {nestedComparer}"; + + return $"new {comparerNamespace}.{comparerType}<{ValueObjectSymbolInspector.ToTypeName(nestedElementType)}>({comparerArguments})"; + } + /// /// Resolves the built-in string normalization for one complex member: an explicit /// [StringNormalize] overrides the assembly default, and the option is only meaningful for a diff --git a/src/src/SourceGenerator/ValueObject/Models/ComplexValueObjectModel.cs b/src/src/SourceGenerator/ValueObject/Models/ComplexValueObjectModel.cs index 17fac32..2864888 100644 --- a/src/src/SourceGenerator/ValueObject/Models/ComplexValueObjectModel.cs +++ b/src/src/SourceGenerator/ValueObject/Models/ComplexValueObjectModel.cs @@ -2,7 +2,12 @@ namespace Purview.ValueObjects.SourceGenerator.ValueObject.Models; sealed record class ComplexValueObjectModel( GeneratedTypeModel TypeModel, + // The type's own value members: the members its equality and comparison operate on. A derived record's + // base members are handled by the base record's equality, not repeated here. EquatableArray Properties, + // The members the generated factories, constructor, hooks and JSON converter operate on: the inherited + // record members first (base to derived), then the type's own members. + EquatableArray AllProperties, ValueObjectAttributeData Options, bool CtorExists, string HintName, @@ -11,6 +16,12 @@ sealed record class ComplexValueObjectModel( bool IsStruct, bool IsRecord, bool IsReadOnly, + // A non-sealed record class requires a generated Equals(TSelf) to be virtual (CS8872), so the emitter + // needs the declared sealed modifier even though its own partial declaration is never sealed. + bool IsSealed, + // The record base type when the value object derives from a record, or null. Generated equality and + // hashing delegate to it so a derived record keeps the base members in its identity. + string? RecordBaseTypeName, TypeDeclarationAccessibility? Accessibility, bool ImplementsSelfEquatable, bool MirrorIEquatableSelf, @@ -54,6 +65,20 @@ sealed record class ComplexValueObjectModel( /// . The generated converter passes it to ValueObjectJson, so a member that is itself /// a value object still round-trips when a source-generated JsonSerializerContext never listed its type. /// +/// How the member's collection type compares, or . +/// +/// The member's element type, used as the explicit type argument of the generated helper call for a sequence or set; +/// for a dictionary and a non-collection member. +/// +/// +/// The expression that constructs the structural comparer for a collection whose element is itself a collection, +/// or . The comparer is passed to the generated helper so a nested collection compares by +/// contents rather than by reference. +/// +/// +/// The expression that constructs the structural comparer for a dictionary whose value is itself a collection, +/// or for every other member. +/// readonly record struct ComplexPropertyModel( string Name, string TypeName, @@ -61,5 +86,25 @@ readonly record struct ComplexPropertyModel( bool NormalizeTrim, string NormalizeCasing, bool NormalizeExplicit, - string? JsonConverterExpression + string? JsonConverterExpression, + ComplexMemberCollectionKind CollectionKind, + string? CollectionElementTypeName, + string? CollectionElementComparerExpression, + string? CollectionValueComparerExpression ); + +/// How a complex value object's collection member compares and hashes. +enum ComplexMemberCollectionKind +{ + /// The member is not a collection, or is a . + None, + + /// An ordered sequence: elements compare in order. + Sequence, + + /// A set: elements compare without regard to order. + Set, + + /// A dictionary: key/value pairs compare without regard to order. + Dictionary, +} diff --git a/src/src/SourceGenerator/ValueObject/ValueObjectSymbolInspector.cs b/src/src/SourceGenerator/ValueObject/ValueObjectSymbolInspector.cs index 1e6ed8e..8c00d8f 100644 --- a/src/src/SourceGenerator/ValueObject/ValueObjectSymbolInspector.cs +++ b/src/src/SourceGenerator/ValueObject/ValueObjectSymbolInspector.cs @@ -64,6 +64,40 @@ Location location ); } + // C# 15 union declarations already provide value/HasValue/TryGetValue and equality members, and + // cannot carry a partial value-object declaration (CS0261). C# 15 closed types are implicitly + // abstract, so the generated Create/Hydrate cannot instantiate them (CS0144); a plain abstract type + // has the same problem. Report one clear diagnostic instead of a compiler error in generated code. + // IsUnion/IsClosed are Roslyn 5.9 evaluation APIs; the generator targets that pinned version and the + // build fails if they disappear. +#pragma warning disable RSEXPERIMENTAL006 // C# 15 union/closed symbols are experimental in Roslyn 5.9. + if (typeSymbol.IsUnion) + { + diagnostics.Add( + ReportableDiagnostic.Create( + DiagnosticLibrary.UnionValueObjectsAreNotSupported, + isBlocking: true, + location, + typeSymbol.Name, + attributeName + ) + ); + } + else if (typeSymbol.IsClosed || typeSymbol.IsAbstract) + { + diagnostics.Add( + ReportableDiagnostic.Create( + DiagnosticLibrary.ValueObjectMustBeInstantiable, + isBlocking: true, + location, + typeSymbol.Name, + attributeName, + typeSymbol.IsClosed ? "closed (a closed type is implicitly abstract)" : "abstract" + ) + ); + } +#pragma warning restore RSEXPERIMENTAL006 + return diagnostics; } @@ -153,6 +187,28 @@ IReadOnlyList parameterTypes ); } + /// + /// True when the author declared the instance method in source. Compiler-synthesized record members are + /// implicitly declared, so a record's synthesized Equals(TSelf) does not count as an author + /// declaration: the generator must replace it to give a collection member contents equality. + /// + public static bool HasDeclaredInstanceMethod( + INamedTypeSymbol typeSymbol, + string name, + IReadOnlyList parameterTypes + ) + { + return typeSymbol + .GetMembers(name) + .OfType() + .Any(method => + !method.IsStatic + && !method.IsImplicitlyDeclared + && method.Parameters.Length == parameterTypes.Count + && ParametersMatch(method.Parameters, parameterTypes) + ); + } + /// /// True when declares an instance Equals overload for /// whose nullability satisfies IEquatable<T>.Equals(T?). @@ -397,6 +453,86 @@ public static bool IsCollectionMember(ITypeSymbol memberType) ); } + /// + /// True when the collection is a set: it implements ISet<T> or IReadOnlySet<T>, so its + /// elements have no meaningful order and compare as a set. + /// + public static bool IsSetCollection(ITypeSymbol collectionType) => + ImplementsGenericInterfaceByName(collectionType, "ISet") + || ImplementsGenericInterfaceByName(collectionType, "IReadOnlySet"); + + /// + /// The key and value types of a dictionary member, when it implements IDictionary<K,V> or + /// IReadOnlyDictionary<K,V>. + /// + public static bool TryGetDictionaryTypeArguments( + ITypeSymbol collectionType, + out ITypeSymbol keyType, + out ITypeSymbol valueType + ) + { + foreach (var candidate in EnumerateSelfAndInterfaces(collectionType)) + { + if ( + candidate is INamedTypeSymbol { Arity: 2 } named + && named.ContainingNamespace.ToDisplayString() == "System.Collections.Generic" + && named.OriginalDefinition.Name is "IDictionary" or "IReadOnlyDictionary" + ) + { + keyType = named.TypeArguments[0]; + valueType = named.TypeArguments[1]; + return true; + } + } + + keyType = null!; + valueType = null!; + return false; + } + + /// + /// The element type of an array or of a type implementing IEnumerable<T>, or + /// when the type is not a collection. + /// + public static ITypeSymbol? GetCollectionElementType(ITypeSymbol collectionType) + { + if (collectionType is IArrayTypeSymbol array) + return array.ElementType; + + foreach (var candidate in EnumerateSelfAndInterfaces(collectionType)) + { + if ( + candidate is INamedTypeSymbol { Arity: 1 } named + && named.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T + ) + return named.TypeArguments[0]; + } + + return null; + } + + static bool ImplementsGenericInterfaceByName(ITypeSymbol type, string interfaceName) + { + foreach (var candidate in EnumerateSelfAndInterfaces(type)) + { + if ( + candidate is INamedTypeSymbol { Arity: 1 } named + && named.ContainingNamespace.ToDisplayString() == "System.Collections.Generic" + && named.OriginalDefinition.Name == interfaceName + ) + return true; + } + + return false; + } + + static IEnumerable EnumerateSelfAndInterfaces(ITypeSymbol type) + { + yield return type; + foreach (var @interface in type.AllInterfaces) + yield return @interface; + } + public static bool HasContextualCreateOverload(INamedTypeSymbol typeSymbol, ITypeSymbol primitiveType) { return typeSymbol @@ -866,16 +1002,13 @@ public static string GetConstructorArgumentExpression(ITypeSymbol typeSymbol) if (typeSymbol.IsReferenceType) return $"({ToTypeName(typeSymbol)})null!"; - if ( - typeSymbol is INamedTypeSymbol namedTypeSymbol - && namedTypeSymbol.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T - ) - { - return "null"; - } + // A bare 'default' is target-typed, and a record with one value-type member has two single-parameter + // constructors (the copy constructor and the generated member constructor), so 'this(default)' is + // ambiguous (CS0121). Spell the type so exactly one constructor is a candidate. + if (TypeLibrary.System.Guid.Equals(typeSymbol)) + return $"{TypeLibrary.System.Guid}.Empty"; - // For value types, we can use the default literal, but for Guid, we want to use Guid.Empty - return TypeLibrary.System.Guid.Equals(typeSymbol) ? $"{TypeLibrary.System.Guid}.Empty" : "default"; + return $"default({ToTypeName(typeSymbol)})"; } public static IFieldSymbol[] GetEnumFields(ITypeSymbol enumTypeSymbol) => diff --git a/src/src/ValueObjects/Sdk/README.md b/src/src/ValueObjects/Sdk/README.md index 3d5de2f..c694c16 100644 --- a/src/src/ValueObjects/Sdk/README.md +++ b/src/src/ValueObjects/Sdk/README.md @@ -9,6 +9,8 @@ incremental source generator produces: and `OnValidate` validation - `Empty` instances, equality, comparison, `CompareTo`, `ToString` (including the underlying value's `IFormattable` and format overloads), and implicit conversions (with explicit extraction for nullable scalars) +- Value semantics for collection members: arrays and sequences compare in order, sets and dictionaries compare + without regard to order, and a collection of collections recurses - The underlying value's standard interfaces — `IEquatable`, `ISpanFormattable`, `IUtf8SpanFormattable`, `IParsable`, `ISpanParsable`, and `IUtf8SpanParsable` — mirrored per type - JSON converters (scalar value objects serialize as their underlying value), with no reflection: generated code is diff --git a/src/src/ValueObjects/ValueObjectEquality.cs b/src/src/ValueObjects/ValueObjectEquality.cs new file mode 100644 index 0000000..40d1b33 --- /dev/null +++ b/src/src/ValueObjects/ValueObjectEquality.cs @@ -0,0 +1,480 @@ +using System.ComponentModel; + +namespace Purview.ValueObjects; + +/// +/// Comparison helpers for the equality, hashing and ordering the value object generator emits for a +/// complex value object's collection members. Generated members call these instead of inlining loop +/// semantics, so contents comparison is implemented and tested once. +/// +/// +/// +/// An ordered sequence compares element by element, so a different order is a different value. A set +/// ( or ) and a dictionary +/// ( or ) are +/// unordered, so their contents compare without regard to order and their hashes combine +/// order-insensitively. +/// +/// +/// Two collections are equal; a collection and an empty +/// one are not. Element comparison and hashing use , so a +/// nested value object keeps its own generated equality. Generated code supplies a structural comparer +/// for a dictionary value that is itself a collection, so that value compares by contents too. A set's or +/// dictionary's own comparer is not observed: using it for equality but +/// for hashing would let equal values produce different hashes. +/// +/// +/// These members exist for generated code. They are public so a consumer's generated members can call +/// them, and hidden from IntelliSense because application code has no reason to. +/// +/// +[EditorBrowsable(EditorBrowsableState.Never)] +public static class ValueObjectEquality +{ + /// + /// Compares two ordered sequences element by element. Two sequences are + /// equal; a sequence and an empty one are not. + /// + /// The element type. + /// The first sequence. + /// The second sequence. + /// The element comparer, or for . + /// when both sequences contain equal elements in the same order. + public static bool SequenceEquals( + IEnumerable? left, + IEnumerable? right, + IEqualityComparer? comparer = null + ) + { + if (ReferenceEquals(left, right)) + return true; + + if (left is null || right is null) + return false; + + comparer ??= EqualityComparer.Default; + + if (left is IReadOnlyList leftList && right is IReadOnlyList rightList) + { + if (leftList.Count != rightList.Count) + return false; + + for (var index = 0; index < leftList.Count; index++) + { + if (!comparer.Equals(leftList[index], rightList[index])) + return false; + } + + return true; + } + + if ( + left is IReadOnlyCollection leftCollection + && right is IReadOnlyCollection rightCollection + && leftCollection.Count != rightCollection.Count + ) + return false; + + using var leftEnumerator = left.GetEnumerator(); + using var rightEnumerator = right.GetEnumerator(); + + while (leftEnumerator.MoveNext()) + { + if (!rightEnumerator.MoveNext()) + return false; + + if (!comparer.Equals(leftEnumerator.Current, rightEnumerator.Current)) + return false; + } + + return !rightEnumerator.MoveNext(); + } + + /// + /// Returns a hash that agrees with : equal sequences produce the same + /// hash. A sequence hashes to zero. + /// + /// The element type. + /// The sequence to hash. + /// The element comparer, or for . + /// The sequence's hash. + public static int SequenceHash(IEnumerable? values, IEqualityComparer? comparer = null) + { + if (values is null) + return 0; + + comparer ??= EqualityComparer.Default; + + HashCode hash = new(); + if (values is IReadOnlyCollection collection) + hash.Add(collection.Count); + + foreach (var value in values) + hash.Add(comparer.GetHashCode(value!)); + + return hash.ToHashCode(); + } + + /// + /// Orders two ordered sequences: a sequence sorts first, then the shorter + /// sequence, then the elements through . + /// + /// The element type. + /// The first sequence. + /// The second sequence. + /// The element comparer, or for . + /// A negative value, zero, or a positive value. + public static int SequenceCompare(IEnumerable? left, IEnumerable? right, IComparer? comparer = null) + { + if (ReferenceEquals(left, right)) + return 0; + + if (left is null) + return -1; + + if (right is null) + return 1; + + comparer ??= Comparer.Default; + + if (left is IReadOnlyList leftList && right is IReadOnlyList rightList) + { + var sharedLength = Math.Min(leftList.Count, rightList.Count); + for (var index = 0; index < sharedLength; index++) + { + var comparison = comparer.Compare(leftList[index], rightList[index]); + if (comparison != 0) + return comparison; + } + + return leftList.Count.CompareTo(rightList.Count); + } + + using var leftEnumerator = left.GetEnumerator(); + using var rightEnumerator = right.GetEnumerator(); + + while (true) + { + var hasLeft = leftEnumerator.MoveNext(); + var hasRight = rightEnumerator.MoveNext(); + + if (!hasLeft) + return hasRight ? -1 : 0; + + if (!hasRight) + return 1; + + var comparison = comparer.Compare(leftEnumerator.Current, rightEnumerator.Current); + if (comparison != 0) + return comparison; + } + } + + /// + /// Compares two sets without regard to order. Two sets are equal; a + /// set and an empty one are not. + /// + /// The element type. + /// The first set. + /// The second set. + /// The element comparer, or for . + /// when both sets contain the same elements. + public static bool SetEquals(IEnumerable? left, IEnumerable? right, IEqualityComparer? comparer = null) + { + if (ReferenceEquals(left, right)) + return true; + + if (left is null || right is null) + return false; + + comparer ??= EqualityComparer.Default; + + HashSet contents = new(left, comparer); + if (contents.Count != Count(right)) + return false; + + foreach (var value in right) + { + if (!contents.Contains(value)) + return false; + } + + return true; + } + + /// + /// Returns an order-insensitive hash that agrees with : sets containing + /// the same elements produce the same hash. A set hashes to zero. + /// + /// The element type. + /// The set to hash. + /// The element comparer, or for . + /// The set's hash. + public static int SetHash(IEnumerable? values, IEqualityComparer? comparer = null) + { + if (values is null) + return 0; + + comparer ??= EqualityComparer.Default; + + var combined = 0; + var count = 0; + foreach (var value in values) + { + combined ^= comparer.GetHashCode(value!); + count++; + } + + return HashCode.Combine(0x5E7, count, combined); + } + + /// + /// Orders two sets: a set sorts first, then the shorter set, then an + /// order-insensitive content hash. Equal sets always compare as zero. + /// + /// The element type. + /// The first set. + /// The second set. + /// The element comparer, or for . + /// A negative value, zero, or a positive value. + public static int SetCompare(IEnumerable? left, IEnumerable? right, IEqualityComparer? comparer = null) + { + if (ReferenceEquals(left, right)) + return 0; + + if (left is null) + return -1; + + if (right is null) + return 1; + + var countComparison = Count(left).CompareTo(Count(right)); + if (countComparison != 0) + return countComparison; + + if (SetEquals(left, right, comparer)) + return 0; + + return SetHash(left, comparer).CompareTo(SetHash(right, comparer)); + } + + /// + /// Compares two dictionaries without regard to order. Two dictionaries are + /// equal; a dictionary and an empty one are not. + /// + /// The key type. + /// The value type. + /// The first dictionary. + /// The second dictionary. + /// + /// The comparer for a value that is itself a collection, or for + /// . + /// + /// when both dictionaries contain the same keys mapped to equal values. + public static bool DictionaryEquals( + IEnumerable>? left, + IEnumerable>? right, + IEqualityComparer? valueComparer = null + ) + where TKey : notnull + { + if (ReferenceEquals(left, right)) + return true; + + if (left is null || right is null) + return false; + + valueComparer ??= EqualityComparer.Default; + + if ( + left is IReadOnlyCollection> leftCollection + && right is IReadOnlyCollection> rightCollection + && leftCollection.Count != rightCollection.Count + ) + return false; + + Dictionary contents = new(); + foreach (var pair in left) + contents[pair.Key] = pair.Value; + + var count = 0; + foreach (var pair in right) + { + count++; + if (!contents.TryGetValue(pair.Key, out var value)) + return false; + + if (!valueComparer.Equals(value, pair.Value)) + return false; + } + + return contents.Count == count; + } + + /// + /// Returns an order-insensitive hash that agrees with : + /// dictionaries containing the same pairs produce the same hash. A + /// dictionary hashes to zero. + /// + /// The key type. + /// The value type. + /// The dictionary to hash. + /// + /// The comparer for a value that is itself a collection, or for + /// . + /// + /// The dictionary's hash. + public static int DictionaryHash( + IEnumerable>? values, + IEqualityComparer? valueComparer = null + ) + where TKey : notnull + { + if (values is null) + return 0; + + valueComparer ??= EqualityComparer.Default; + + var combined = 0; + var count = 0; + foreach (var pair in values) + { + combined ^= HashCode.Combine( + EqualityComparer.Default.GetHashCode(pair.Key!), + valueComparer.GetHashCode(pair.Value!) + ); + count++; + } + + return HashCode.Combine(0x0D1C, count, combined); + } + + /// + /// Orders two dictionaries: a dictionary sorts first, then the shorter + /// dictionary, then an order-insensitive content hash. Equal dictionaries always compare as zero. + /// + /// The key type. + /// The value type. + /// The first dictionary. + /// The second dictionary. + /// + /// The comparer for a value that is itself a collection, or for + /// . + /// + /// A negative value, zero, or a positive value. + public static int DictionaryCompare( + IEnumerable>? left, + IEnumerable>? right, + IEqualityComparer? valueComparer = null + ) + where TKey : notnull + { + if (ReferenceEquals(left, right)) + return 0; + + if (left is null) + return -1; + + if (right is null) + return 1; + + var countComparison = Count(left).CompareTo(Count(right)); + if (countComparison != 0) + return countComparison; + + if (DictionaryEquals(left, right, valueComparer)) + return 0; + + return DictionaryHash(left, valueComparer).CompareTo(DictionaryHash(right, valueComparer)); + } + + static int Count(IEnumerable values) + { + if (values is IReadOnlyCollection collection) + return collection.Count; + + var count = 0; + foreach (var _ in values) + count++; + + return count; + } +} + +/// +/// An equality and ordering comparer for an ordered sequence, used when a collection member's element is +/// itself a collection. A generated member passes it to , +/// or . +/// +/// The element type. +/// The comparer for a nested element's equality, or . +/// The comparer for a nested element's order, or . +[EditorBrowsable(EditorBrowsableState.Never)] +public sealed class ValueObjectSequenceComparer( + IEqualityComparer? elementEqualityComparer = null, + IComparer? elementComparer = null +) : IEqualityComparer>, IComparer> +{ + /// + public bool Equals(IEnumerable? x, IEnumerable? y) => + ValueObjectEquality.SequenceEquals(x, y, elementEqualityComparer); + + /// + public int GetHashCode(IEnumerable obj) => ValueObjectEquality.SequenceHash(obj, elementEqualityComparer); + + /// + public int Compare(IEnumerable? x, IEnumerable? y) => + ValueObjectEquality.SequenceCompare(x, y, elementComparer); +} + +/// +/// An equality and ordering comparer for a set, used when a collection member's element is itself a set. +/// A generated member passes it to , +/// or . +/// +/// The element type. +/// The comparer for a nested element's equality, or . +[EditorBrowsable(EditorBrowsableState.Never)] +public sealed class ValueObjectSetComparer(IEqualityComparer? elementEqualityComparer = null) + : IEqualityComparer>, + IComparer> +{ + /// + public bool Equals(IEnumerable? x, IEnumerable? y) => + ValueObjectEquality.SetEquals(x, y, elementEqualityComparer); + + /// + public int GetHashCode(IEnumerable obj) => ValueObjectEquality.SetHash(obj, elementEqualityComparer); + + /// + public int Compare(IEnumerable? x, IEnumerable? y) => + ValueObjectEquality.SetCompare(x, y, elementEqualityComparer); +} + +/// +/// An equality and ordering comparer for a dictionary, used when a collection member's element is itself a +/// dictionary. A generated member passes it to , +/// or +/// . +/// +/// The key type. +/// The value type. +/// The comparer for a value that is itself a collection, or . +[EditorBrowsable(EditorBrowsableState.Never)] +public sealed class ValueObjectDictionaryComparer(IEqualityComparer? valueComparer = null) + : IEqualityComparer>>, + IComparer>> + where TKey : notnull +{ + /// + public bool Equals(IEnumerable>? x, IEnumerable>? y) => + ValueObjectEquality.DictionaryEquals(x, y, valueComparer); + + /// + public int GetHashCode(IEnumerable> obj) => + ValueObjectEquality.DictionaryHash(obj, valueComparer); + + /// + public int Compare(IEnumerable>? x, IEnumerable>? y) => + ValueObjectEquality.DictionaryCompare(x, y, valueComparer); +} diff --git a/src/tests/SourceGenerator.UnitTests/Analyzers/ValueObjectDiagnosticAnalyzerTests.cs b/src/tests/SourceGenerator.UnitTests/Analyzers/ValueObjectDiagnosticAnalyzerTests.cs index ef92f12..c6f0c8c 100644 --- a/src/tests/SourceGenerator.UnitTests/Analyzers/ValueObjectDiagnosticAnalyzerTests.cs +++ b/src/tests/SourceGenerator.UnitTests/Analyzers/ValueObjectDiagnosticAnalyzerTests.cs @@ -858,6 +858,51 @@ await Assert .IsEqualTo(Microsoft.CodeAnalysis.DiagnosticSeverity.Error); } +#if NET11_0_OR_GREATER + [Test] + public async Task CSharp15_ClosedType_ReportsValueObjectMustBeInstantiable(CancellationToken cancellationToken) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public closed partial record ClosedProbe + { + public string Head { get; } + } + } + """; + + var result = await AnalyzeAsync( + source, + new AnalyzerTestOptions { LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.Preview }, + cancellationToken + ); + + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ValueObjectMustBeInstantiable); + } + + [Test] + public async Task CSharp15_UnionType_ReportsUnionValueObjectsAreNotSupported(CancellationToken cancellationToken) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public partial union UnionProbe(int, string); + } + """; + + var result = await AnalyzeAsync( + source, + new AnalyzerTestOptions { LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.Preview }, + cancellationToken + ); + + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.UnionValueObjectsAreNotSupported); + } +#endif + protected override AnalyzerTestOptions OnBeforeRun( IEnumerable sources, AnalyzerTestOptions options, diff --git a/src/tests/SourceGenerator.UnitTests/Generators/ValueObjectSourceGeneratorTests.cs b/src/tests/SourceGenerator.UnitTests/Generators/ValueObjectSourceGeneratorTests.cs index 8dda34d..5d350b2 100644 --- a/src/tests/SourceGenerator.UnitTests/Generators/ValueObjectSourceGeneratorTests.cs +++ b/src/tests/SourceGenerator.UnitTests/Generators/ValueObjectSourceGeneratorTests.cs @@ -1536,4 +1536,460 @@ await Assert .IsEqualTo(ValueObjectsGeneratorTestOptions.ValueObjectExpectedFileCount); await Assert.That(result.Generated().HasRecord("EmailAddress", "Testing")).IsFalse(); } + + [Test] + public async Task ComplexValueObjectGeneration_CollectionMember_ComparesByContents( + CancellationToken cancellationToken + ) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record Probe + { + public string Head { get; } + + public System.Collections.Generic.IReadOnlyList Items { get; } + } + + public static class CollectionHarness + { + public static bool AreEqual() => + Probe.Create("Document", new System.Collections.Generic.List { 1, 2, 3 }) + .Equals(Probe.Create("Document", new System.Collections.Generic.List { 1, 2, 3 })); + + public static bool HashesAreEqual() + { + var first = Probe.Create("Document", new System.Collections.Generic.List { 1, 2, 3 }); + var second = Probe.Create("Document", new System.Collections.Generic.List { 1, 2, 3 }); + return first.GetHashCode() == second.GetHashCode(); + } + + public static bool OperatorsAreEqual() => + Probe.Create("Document", new System.Collections.Generic.List { 1, 2, 3 }) + == Probe.Create("Document", new System.Collections.Generic.List { 1, 2, 3 }); + } + } + """; + + using var result = await GenerateAsync( + source, + ValueObjectsGeneratorTestOptions.Default.Compile(), + cancellationToken + ); + + var generated = result.Generated().GetRecord("Probe", "Testing").Node.ToString(); + + await Assert.That(generated).Contains("ValueObjectEquality.SequenceEquals"); + await Assert.That(generated).Contains("ValueObjectEquality.SequenceHash"); + await Assert + .That( + generated.Contains( + "EqualityComparer>", + StringComparison.Ordinal + ) + ) + .IsFalse(); + + var assembly = await Assert.That(result.CompilationResult.Assembly).IsNotNull(); + var harness = assembly.GetType("Testing.CollectionHarness")!; + + await Assert.That((bool)harness.GetMethod("AreEqual")!.Invoke(null, null)!).IsTrue(); + await Assert.That((bool)harness.GetMethod("HashesAreEqual")!.Invoke(null, null)!).IsTrue(); + await Assert.That((bool)harness.GetMethod("OperatorsAreEqual")!.Invoke(null, null)!).IsTrue(); + } + + [Test] + public async Task ComplexValueObjectGeneration_RecordShapes_DeclareEqualsWithTheRightVirtualModifier( + CancellationToken cancellationToken + ) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record SealedRecordProbe + { + public string Head { get; } + public System.Collections.Generic.IReadOnlyList Items { get; } + } + + [Purview.ValueObjects.Serialization.ValueObject] + public partial record OpenRecordProbe + { + public string Head { get; } + public System.Collections.Generic.IReadOnlyList Items { get; } + } + + [Purview.ValueObjects.Serialization.ValueObject] + public readonly partial record struct RecordStructProbe + { + public string Head { get; } + public System.Collections.Generic.IReadOnlyList Items { get; } + } + + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial class ClassProbe + { + public string Head { get; } + public System.Collections.Generic.IReadOnlyList Items { get; } + } + } + """; + + using var result = await GenerateAsync( + source, + ValueObjectsGeneratorTestOptions.Default.Compile(), + cancellationToken + ); + + var query = result.Generated(); + + var sealedEquals = query + .GetRecord("SealedRecordProbe", "Testing") + .GetMethod("Equals", TypeRefs.Named("SealedRecordProbe", "Testing")); + var openEquals = query + .GetRecord("OpenRecordProbe", "Testing") + .GetMethod("Equals", TypeRefs.Named("OpenRecordProbe", "Testing")); + var structEquals = query + .GetRecord("RecordStructProbe", "Testing") + .GetMethod("Equals", TypeRefs.Named("RecordStructProbe", "Testing")); + var classEquals = query + .GetClass("ClassProbe", "Testing") + .GetMethod("Equals", TypeRefs.Named("ClassProbe", "Testing")); + + await Assert.That(openEquals.Node.Modifiers.ToString()).Contains("virtual"); + await Assert + .That(sealedEquals.Node.Modifiers.ToString().Contains("virtual", StringComparison.Ordinal)) + .IsFalse(); + await Assert + .That(structEquals.Node.Modifiers.ToString().Contains("virtual", StringComparison.Ordinal)) + .IsFalse(); + await Assert + .That(classEquals.Node.Modifiers.ToString().Contains("virtual", StringComparison.Ordinal)) + .IsFalse(); + } + + [Test] + public async Task ComplexValueObjectGeneration_CollectionShapes_UseTheRightStructuralHelper( + CancellationToken cancellationToken + ) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record SetProbe + { + public string Head { get; } + public System.Collections.Generic.HashSet Items { get; } + } + + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record DictionaryProbe + { + public string Head { get; } + public System.Collections.Generic.Dictionary Items { get; } + } + + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record NestedProbe + { + public string Head { get; } + public System.Collections.Generic.IReadOnlyList> Items { get; } + } + } + """; + + using var result = await GenerateAsync( + source, + ValueObjectsGeneratorTestOptions.Default.Compile(), + cancellationToken + ); + + var query = result.Generated(); + + var set = query.GetRecord("SetProbe", "Testing").Node.ToString(); + var dictionary = query.GetRecord("DictionaryProbe", "Testing").Node.ToString(); + var nested = query.GetRecord("NestedProbe", "Testing").Node.ToString(); + + await Assert.That(set).Contains("ValueObjectEquality.SetEquals"); + await Assert.That(set).Contains("ValueObjectEquality.SetHash"); + await Assert.That(dictionary).Contains("ValueObjectEquality.DictionaryEquals("); + await Assert.That(dictionary).Contains("ValueObjectEquality.DictionaryHash("); + await Assert.That(nested).Contains("ValueObjectSequenceComparer"); + await Assert.That(nested).Contains("SequenceEquals>"); + } + + [Test] + public async Task ComplexValueObjectGeneration_HostDeclaredEquals_IsNotDuplicated( + CancellationToken cancellationToken + ) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record Probe + { + public string Head { get; } + public System.Collections.Generic.IReadOnlyList Items { get; } + + public bool Equals(Probe? other) => other is not null && Head == other.Head; + } + } + """; + + using var result = await GenerateAsync( + source, + ValueObjectsGeneratorTestOptions.Default.Compile(), + cancellationToken + ); + + var generated = result.Generated().GetRecord("Probe", "Testing").Node.ToString(); + + await Assert.That(generated.Contains("ValueObjectEquality.SequenceEquals", StringComparison.Ordinal)).IsFalse(); + await Assert.That(result.CompilationResult.Assembly).IsNotNull(); + } + + [Test] + public async Task ComplexValueObjectGeneration_SingleValueTypeMember_UsesTypedConstructorArgument( + CancellationToken cancellationToken + ) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record SingleIntProbe + { + public int Count { get; } + } + + [Purview.ValueObjects.Serialization.ValueObject] + public readonly partial record struct SingleNullableProbe + { + public int? Count { get; } + } + } + """; + + using var result = await GenerateAsync( + source, + ValueObjectsGeneratorTestOptions.Default.Compile(), + cancellationToken + ); + + var record = result.Generated().GetRecord("SingleIntProbe", "Testing").Node.ToString(); + var recordStruct = result.Generated().GetRecord("SingleNullableProbe", "Testing").Node.ToString(); + + // A bare 'default' would be ambiguous between the record's copy constructor and the generated + // single-member constructor (CS0121). + await Assert.That(record).Contains("this(default(int))"); + await Assert.That(recordStruct).Contains("this(default(int?))"); + await Assert.That(result.CompilationResult.Assembly).IsNotNull(); + } + + [Test] + public async Task ComplexValueObjectGeneration_DerivedRecord_ComparesBaseMembers( + CancellationToken cancellationToken + ) + { + const string source = """ + namespace Testing + { + public partial record StatefulBase + { + public string Head { get; init; } + } + + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record StatefulCase : StatefulBase + { + public int Count { get; } + } + + public static class DerivedHarness + { + public static bool BaseStateIsCompared() + { + var first = StatefulCase.Create("A", 1); + var second = StatefulCase.Create("A", 1); + var different = StatefulCase.Create("B", 1); + return first.Equals(second) && !first.Equals(different); + } + + public static bool BaseStateHashesAgree() + { + var first = StatefulCase.Create("A", 1); + var second = StatefulCase.Create("A", 1); + return first.GetHashCode() == second.GetHashCode(); + } + + public static bool BaseStateRoundTripsThroughJson() + { + var value = StatefulCase.Create("A", 1); + var json = System.Text.Json.JsonSerializer.Serialize(value); + var roundTripped = System.Text.Json.JsonSerializer.Deserialize(json); + return roundTripped is not null && roundTripped.Equals(value); + } + } + } + """; + + using var result = await GenerateAsync( + source, + ValueObjectsGeneratorTestOptions.Default.Compile(), + cancellationToken + ); + + var generated = result.Generated().GetRecord("StatefulCase", "Testing").Node.ToString(); + await Assert.That(generated).Contains("base.Equals((global::Testing.StatefulBase)other)"); + await Assert.That(generated).Contains("hash.Add(base.GetHashCode())"); + await Assert.That(generated).Contains("value.Head"); + await Assert.That(generated).Contains("value.Count"); + + var assembly = await Assert.That(result.CompilationResult.Assembly).IsNotNull(); + var harness = assembly.GetType("Testing.DerivedHarness")!; + + await Assert.That((bool)harness.GetMethod("BaseStateIsCompared")!.Invoke(null, null)!).IsTrue(); + await Assert.That((bool)harness.GetMethod("BaseStateHashesAgree")!.Invoke(null, null)!).IsTrue(); + await Assert.That((bool)harness.GetMethod("BaseStateRoundTripsThroughJson")!.Invoke(null, null)!).IsTrue(); + } + +#if NET11_0_OR_GREATER + // C# 15 union/closed declarations need the .NET 11 runtime attributes (UnionAttribute, + // IsClosedTypeAttribute), so these tests only run on the net11.0 leg. + [Test] + public async Task CSharp15_ClosedHierarchyCase_GeneratesValueObject(CancellationToken cancellationToken) + { + const string source = """ + namespace Testing + { + public closed partial record PaymentBase; + + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record CardPayment(string Reference) : PaymentBase; + + public static class ClosedHarness + { + public static bool AreEqual() => + CardPayment.Create("ABC").Equals(CardPayment.Create("ABC")); + + public static bool HashesAreEqual() + { + var first = CardPayment.Create("ABC"); + var second = CardPayment.Create("ABC"); + return first.GetHashCode() == second.GetHashCode(); + } + } + } + """; + + var options = ValueObjectsGeneratorTestOptions.Default with + { + LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.Preview, + }; + + using var result = await GenerateAsync(source, options.Compile(), cancellationToken); + + var generated = result.Generated().GetRecord("CardPayment", "Testing").Node.ToString(); + await Assert.That(generated).Contains("base.Equals((global::Testing.PaymentBase)other)"); + await Assert.That(generated).Contains("hash.Add(base.GetHashCode())"); + + var assembly = await Assert.That(result.CompilationResult.Assembly).IsNotNull(); + var harness = assembly.GetType("Testing.ClosedHarness")!; + + await Assert.That((bool)harness.GetMethod("AreEqual")!.Invoke(null, null)!).IsTrue(); + await Assert.That((bool)harness.GetMethod("HashesAreEqual")!.Invoke(null, null)!).IsTrue(); + } + + [Test] + public async Task CSharp15_UnionMember_ComparesAsAValue(CancellationToken cancellationToken) + { + const string source = """ + namespace Testing + { + public union IntOrString(int, string); + + [Purview.ValueObjects.Serialization.ValueObject] + public sealed partial record UnionMemberProbe + { + public string Head { get; } + public IntOrString Value { get; } + } + + public static class UnionHarness + { + public static bool AreEqual() => + UnionMemberProbe.Create("Document", 42).Equals(UnionMemberProbe.Create("Document", 42)); + + public static bool DifferentCaseIsNotEqual() => + !UnionMemberProbe.Create("Document", 42).Equals(UnionMemberProbe.Create("Document", "42")); + } + } + """; + + var options = ValueObjectsGeneratorTestOptions.Default with + { + LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.Preview, + }; + + using var result = await GenerateAsync(source, options.Compile(), cancellationToken); + + var assembly = await Assert.That(result.CompilationResult.Assembly).IsNotNull(); + var harness = assembly.GetType("Testing.UnionHarness")!; + + await Assert.That((bool)harness.GetMethod("AreEqual")!.Invoke(null, null)!).IsTrue(); + await Assert.That((bool)harness.GetMethod("DifferentCaseIsNotEqual")!.Invoke(null, null)!).IsTrue(); + } + + [Test] + public async Task CSharp15_ClosedType_ReportsDiagnostic(CancellationToken cancellationToken) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public closed partial record ClosedProbe + { + public string Head { get; } + } + } + """; + + var options = ValueObjectsGeneratorTestOptions.Default with + { + LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.Preview, + }; + + using var result = await GenerateAsync(source, options.Compile(), cancellationToken); + + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ValueObjectMustBeInstantiable); + await Assert.That(result.Generated().HasRecord("ClosedProbe", "Testing")).IsFalse(); + } + + [Test] + public async Task CSharp15_UnionType_ReportsDiagnostic(CancellationToken cancellationToken) + { + const string source = """ + namespace Testing + { + [Purview.ValueObjects.Serialization.ValueObject] + public partial union UnionProbe(int, string); + } + """; + + var options = ValueObjectsGeneratorTestOptions.Default with + { + LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.Preview, + }; + + using var result = await GenerateAsync(source, options.Compile(), cancellationToken); + + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.UnionValueObjectsAreNotSupported); + await Assert.That(result.Generated().HasRecord("UnionProbe", "Testing")).IsFalse(); + } +#endif } diff --git a/src/tests/SourceGenerator.UnitTests/Incremental/ValueObjectSourceGeneratorIncrementalTests.cs b/src/tests/SourceGenerator.UnitTests/Incremental/ValueObjectSourceGeneratorIncrementalTests.cs index 744c8a2..ca35875 100644 --- a/src/tests/SourceGenerator.UnitTests/Incremental/ValueObjectSourceGeneratorIncrementalTests.cs +++ b/src/tests/SourceGenerator.UnitTests/Incremental/ValueObjectSourceGeneratorIncrementalTests.cs @@ -49,6 +49,31 @@ public readonly partial record struct Money } """; + const string ComplexCollectionSource = """ + using Purview.ValueObjects.Serialization; + + namespace Testing + { + [ValueObject] + public sealed partial record DocumentProbe + { + public string Head { get; } + + public System.Collections.Generic.IReadOnlyList Items { get; } + } + } + """; + + [Test] + public async Task Generate_ComplexTargetWithCollectionMember_RerunStaysCached(CancellationToken cancellationToken) + { + var result = await GenerateIncrementalAsync([ComplexCollectionSource], cancellationToken: cancellationToken); + + var reasons = StepReasons(result.Runs[1], "GetComplexValueObjectTargets"); + await Assert.That(reasons.Length).IsEqualTo(1); + await Assert.That(reasons.All(static reason => reason is StepReason.Cached or StepReason.Unchanged)).IsTrue(); + } + [Test] public async Task Generate_FirstRun_AllScalarTargetsNew(CancellationToken cancellationToken) { diff --git a/src/tests/ValueObjects.IntegrationTests/Equality/CollectionEqualityModels.cs b/src/tests/ValueObjects.IntegrationTests/Equality/CollectionEqualityModels.cs new file mode 100644 index 0000000..c236d77 --- /dev/null +++ b/src/tests/ValueObjects.IntegrationTests/Equality/CollectionEqualityModels.cs @@ -0,0 +1,117 @@ +using System.Collections.Immutable; +using Purview.ValueObjects.Serialization; + +namespace Purview.ValueObjects.Equality; + +// Each fixture opts out of Entity Framework complex-type mapping: the test project references Entity +// Framework Core, and a collection member cannot be mapped as a complex type (VO1018). The equality +// behaviour under test is independent of persistence. +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityRecordProbe +{ + public string Head { get; } + + public IReadOnlyList Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial class EqualityClassProbe +{ + public string Head { get; } + + public IReadOnlyList Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public readonly partial record struct EqualityRecordStructProbe +{ + public string Head { get; } + + public IReadOnlyList Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityArrayProbe +{ + public string Head { get; } + + public int[] Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityStringListProbe +{ + public string Text { get; } + + public List Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualitySetProbe +{ + public string Head { get; } + + public HashSet Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityDictionaryProbe +{ + public string Head { get; } + + public Dictionary Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityDictionaryOfListsProbe +{ + public string Head { get; } + + public Dictionary> Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityNullableProbe +{ + public string Head { get; } + + public IReadOnlyList? Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityElementProbe +{ + public string Head { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityElementListProbe +{ + public string Head { get; } + + public IReadOnlyList Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityNestedListProbe +{ + public string Head { get; } + + public IReadOnlyList> Items { get; } +} + +[ValueObject(EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityImmutableArrayProbe +{ + public string Head { get; } + + public ImmutableArray Items { get; } +} + +[ValueObject(GenerateComparable = true, EFMapping = EntityFrameworkMapping.None, GenerateEFComparer = false)] +public sealed partial record EqualityComparableProbe +{ + public string Head { get; } + + public IReadOnlyList Items { get; } +} diff --git a/src/tests/ValueObjects.IntegrationTests/Equality/CollectionEqualityTests.cs b/src/tests/ValueObjects.IntegrationTests/Equality/CollectionEqualityTests.cs new file mode 100644 index 0000000..e2698c9 --- /dev/null +++ b/src/tests/ValueObjects.IntegrationTests/Equality/CollectionEqualityTests.cs @@ -0,0 +1,238 @@ +using System.Collections.Immutable; + +namespace Purview.ValueObjects.Equality; + +/// +/// End-to-end equality for a complex value object with a collection member: the generated +/// Equals, ==, GetHashCode and CompareTo must compare a collection by its +/// contents rather than by reference, for records and non-records alike. +/// +public sealed class CollectionEqualityTests +{ + [Test] + public async Task Record_EqualContents_AreEqualAndHashEqual() + { + var first = EqualityRecordProbe.Create("Document", new List { 1, 2, 3 }); + var second = EqualityRecordProbe.Create("Document", new List { 1, 2, 3 }); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first == second).IsTrue(); + await Assert.That(first != second).IsFalse(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task Class_EqualContents_AreEqualAndHashEqual() + { + var first = EqualityClassProbe.Create("Document", new List { 1, 2, 3 }); + var second = EqualityClassProbe.Create("Document", new List { 1, 2, 3 }); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first == second).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task RecordStruct_EqualContents_AreEqualAndHashEqual() + { + var first = EqualityRecordStructProbe.Create("Document", new List { 1, 2, 3 }); + var second = EqualityRecordStructProbe.Create("Document", new List { 1, 2, 3 }); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first == second).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task Array_EqualContents_AreEqualAndHashEqual() + { + var first = EqualityArrayProbe.Create("Document", [1, 2, 3]); + var second = EqualityArrayProbe.Create("Document", [1, 2, 3]); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task Sequence_DifferentOrderOrLength_IsNotEqual() + { + var first = EqualityRecordProbe.Create("Document", new List { 1, 2, 3 }); + var reordered = EqualityRecordProbe.Create("Document", new List { 3, 2, 1 }); + var shorter = EqualityRecordProbe.Create("Document", new List { 1, 2 }); + + await Assert.That(first.Equals(reordered)).IsFalse(); + await Assert.That(first.Equals(shorter)).IsFalse(); + } + + [Test] + public async Task Sequence_DifferentRuntimeCollectionTypes_AreEqual() + { + var list = EqualityRecordProbe.Create("Document", new List { 1, 2, 3 }); + IReadOnlyList array = [1, 2, 3]; + var other = EqualityRecordProbe.Create("Document", array); + + await Assert.That(list.Equals(other)).IsTrue(); + await Assert.That(list.GetHashCode()).IsEqualTo(other.GetHashCode()); + } + + [Test] + public async Task Nullable_NullEqualsNullAndNullDiffersFromEmpty() + { + var first = EqualityNullableProbe.Create("Document", null); + var second = EqualityNullableProbe.Create("Document", null); + var empty = EqualityNullableProbe.Create("Document", Array.Empty()); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + await Assert.That(first.Equals(empty)).IsFalse(); + await Assert.That(first.GetHashCode() == empty.GetHashCode()).IsFalse(); + } + + [Test] + public async Task Nullable_NullMember_DoesNotThrow() + { + var value = EqualityNullableProbe.Create("Document", null); + var other = EqualityNullableProbe.Create("Document", null); + + await Assert.That(value.Equals(other)).IsTrue(); + await Assert.That(value.GetHashCode()).IsEqualTo(other.GetHashCode()); + } + + [Test] + public async Task StringList_EqualContents_AreEqual() + { + var first = EqualityStringListProbe.Create("Document", new List { "a", "b" }); + var second = EqualityStringListProbe.Create("Document", new List { "a", "b" }); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task Set_InsertionOrder_DoesNotAffectEqualityOrHash() + { + var ascending = EqualitySetProbe.Create("Document", new HashSet { 1, 2, 3 }); + var descending = EqualitySetProbe.Create("Document", new HashSet { 3, 2, 1 }); + var different = EqualitySetProbe.Create("Document", new HashSet { 1, 2, 4 }); + + await Assert.That(ascending.Equals(descending)).IsTrue(); + await Assert.That(ascending.GetHashCode()).IsEqualTo(descending.GetHashCode()); + await Assert.That(ascending.Equals(different)).IsFalse(); + } + + [Test] + public async Task Dictionary_InsertionOrder_DoesNotAffectEqualityOrHash() + { + var forward = EqualityDictionaryProbe.Create("Document", new Dictionary { ["a"] = 1, ["b"] = 2 }); + var reverse = EqualityDictionaryProbe.Create("Document", new Dictionary { ["b"] = 2, ["a"] = 1 }); + var different = EqualityDictionaryProbe.Create( + "Document", + new Dictionary { ["a"] = 1, ["b"] = 3 } + ); + + await Assert.That(forward.Equals(reverse)).IsTrue(); + await Assert.That(forward.GetHashCode()).IsEqualTo(reverse.GetHashCode()); + await Assert.That(forward.Equals(different)).IsFalse(); + } + + [Test] + public async Task Dictionary_CollectionValues_CompareByContents() + { + var forward = EqualityDictionaryOfListsProbe.Create( + "Document", + new Dictionary> + { + ["a"] = new List { 1, 2 }, + } + ); + IReadOnlyList arrayContents = [1, 2]; + var reverse = EqualityDictionaryOfListsProbe.Create( + "Document", + new Dictionary> { ["a"] = arrayContents } + ); + var different = EqualityDictionaryOfListsProbe.Create( + "Document", + new Dictionary> + { + ["a"] = new List { 1, 3 }, + } + ); + + await Assert.That(forward.Equals(reverse)).IsTrue(); + await Assert.That(forward.GetHashCode()).IsEqualTo(reverse.GetHashCode()); + await Assert.That(forward.CompareTo(reverse)).IsEqualTo(0); + await Assert.That(forward.Equals(different)).IsFalse(); + } + + [Test] + public async Task NestedValueObject_EqualContents_UseTheElementEquality() + { + var first = EqualityElementListProbe.Create("Document", [EqualityElementProbe.Create("Element")]); + var second = EqualityElementListProbe.Create("Document", [EqualityElementProbe.Create("Element")]); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task NestedCollections_CompareByContentsAtEveryLevel() + { + IReadOnlyList[] firstItems = + [ + [1, 2], + [3], + ]; + IReadOnlyList[] secondItems = [new List { 1, 2 }, new List { 3 }]; + IReadOnlyList[] differentItems = + [ + [1, 2], + [3, 4], + ]; + + var first = EqualityNestedListProbe.Create("Document", firstItems); + var second = EqualityNestedListProbe.Create("Document", secondItems); + var different = EqualityNestedListProbe.Create("Document", differentItems); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + await Assert.That(first.CompareTo(second)).IsEqualTo(0); + await Assert.That(first.Equals(different)).IsFalse(); + } + + [Test] + public async Task ImmutableArray_EqualContents_AreEqualAndHashEqual() + { + var first = EqualityImmutableArrayProbe.Create("Document", ImmutableArray.Create(1, 2, 3)); + var second = EqualityImmutableArrayProbe.Create("Document", ImmutableArray.Create(1, 2, 3)); + + await Assert.That(first.Equals(second)).IsTrue(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + + [Test] + public async Task SetAndDictionary_UseTheGeneratedHashCode() + { + var first = EqualityRecordProbe.Create("Document", new List { 1, 2, 3 }); + var second = EqualityRecordProbe.Create("Document", new List { 1, 2, 3 }); + + HashSet set = [first, second]; + Dictionary dictionary = new() { [first] = 1, [second] = 2 }; + + await Assert.That(set.Count).IsEqualTo(1); + await Assert.That(dictionary.Count).IsEqualTo(1); + } + + [Test] + public async Task Comparable_CollectionMember_HasDefinedOrder() + { + var value = EqualityComparableProbe.Create("Document", new List { 1, 2 }); + var equal = EqualityComparableProbe.Create("Document", new List { 1, 2 }); + var later = EqualityComparableProbe.Create("Document", new List { 1, 3 }); + var longer = EqualityComparableProbe.Create("Document", new List { 1, 2, 3 }); + + await Assert.That(value.CompareTo(equal)).IsEqualTo(0); + await Assert.That(value.CompareTo(later) < 0).IsTrue(); + await Assert.That(value.CompareTo(longer) < 0).IsTrue(); + await Assert.That(value.CompareTo(null) > 0).IsTrue(); + } +} diff --git a/src/tests/ValueObjects.UnitTests/Equality/ValueObjectEqualityTests.cs b/src/tests/ValueObjects.UnitTests/Equality/ValueObjectEqualityTests.cs new file mode 100644 index 0000000..dcb7eb3 --- /dev/null +++ b/src/tests/ValueObjects.UnitTests/Equality/ValueObjectEqualityTests.cs @@ -0,0 +1,192 @@ +namespace Purview.ValueObjects.Equality; + +/// +/// The contract of the runtime helpers the generated collection equality calls: ordered sequences, +/// unordered sets and dictionaries, null handling, and a paired hash. +/// +public sealed class ValueObjectEqualityTests +{ + [Test] + public async Task SequenceEquals_EqualContents_AreEqualAcrossRuntimeTypes() + { + IReadOnlyList list = new List { 1, 2, 3 }; + int[] array = [1, 2, 3]; + + await Assert.That(ValueObjectEquality.SequenceEquals(list, array)).IsTrue(); + } + + [Test] + public async Task SequenceEquals_DifferentOrderOrLength_IsNotEqual() + { + await Assert.That(ValueObjectEquality.SequenceEquals([1, 2, 3], [3, 2, 1])).IsFalse(); + await Assert.That(ValueObjectEquality.SequenceEquals([1, 2, 3], [1, 2])).IsFalse(); + } + + [Test] + public async Task SequenceEquals_NullAndEmpty_AreNotEqual() + { + await Assert.That(ValueObjectEquality.SequenceEquals(null, null)).IsTrue(); + await Assert.That(ValueObjectEquality.SequenceEquals(null, [])).IsFalse(); + await Assert.That(ValueObjectEquality.SequenceEquals([], null)).IsFalse(); + } + + [Test] + public async Task SequenceHash_AgreesWithSequenceEquals() + { + IReadOnlyList list = new List { 1, 2, 3 }; + int[] array = [1, 2, 3]; + + await Assert + .That(ValueObjectEquality.SequenceHash(list)) + .IsEqualTo(ValueObjectEquality.SequenceHash(array)); + await Assert.That(ValueObjectEquality.SequenceHash(null)).IsEqualTo(0); + } + + [Test] + public async Task SequenceCompare_OrdersByCountThenElements() + { + await Assert.That(ValueObjectEquality.SequenceCompare([1, 2], [1, 2])).IsEqualTo(0); + await Assert.That(ValueObjectEquality.SequenceCompare([1, 2], [1, 3]) < 0).IsTrue(); + await Assert.That(ValueObjectEquality.SequenceCompare([1, 2], [1, 2, 3]) < 0).IsTrue(); + await Assert.That(ValueObjectEquality.SequenceCompare(null, []) < 0).IsTrue(); + await Assert.That(ValueObjectEquality.SequenceCompare(null, null)).IsEqualTo(0); + } + + [Test] + public async Task SetEquals_InsertionOrder_IsIgnored() + { + HashSet ascending = [1, 2, 3]; + HashSet descending = [3, 2, 1]; + + await Assert.That(ValueObjectEquality.SetEquals(ascending, descending)).IsTrue(); + await Assert.That(ValueObjectEquality.SetEquals(ascending, new HashSet { 1, 2, 4 })).IsFalse(); + } + + [Test] + public async Task SetHash_InsertionOrder_IsIgnored() + { + HashSet ascending = [1, 2, 3]; + HashSet descending = [3, 2, 1]; + + await Assert + .That(ValueObjectEquality.SetHash(ascending)) + .IsEqualTo(ValueObjectEquality.SetHash(descending)); + } + + [Test] + public async Task SetCompare_EqualSets_AreZero() + { + HashSet ascending = [1, 2, 3]; + HashSet descending = [3, 2, 1]; + + await Assert.That(ValueObjectEquality.SetCompare(ascending, descending)).IsEqualTo(0); + await Assert.That(ValueObjectEquality.SetCompare(ascending, new HashSet { 1, 2, 4 }) != 0).IsTrue(); + } + + [Test] + public async Task DictionaryEquals_InsertionOrder_IsIgnored() + { + Dictionary forward = new() { ["a"] = 1, ["b"] = 2 }; + Dictionary reverse = new() { ["b"] = 2, ["a"] = 1 }; + + await Assert.That(ValueObjectEquality.DictionaryEquals(forward, reverse)).IsTrue(); + await Assert + .That(ValueObjectEquality.DictionaryEquals(forward, new Dictionary { ["a"] = 1 })) + .IsFalse(); + } + + [Test] + public async Task DictionaryHash_InsertionOrder_IsIgnored() + { + Dictionary forward = new() { ["a"] = 1, ["b"] = 2 }; + Dictionary reverse = new() { ["b"] = 2, ["a"] = 1 }; + + await Assert + .That(ValueObjectEquality.DictionaryHash(forward)) + .IsEqualTo(ValueObjectEquality.DictionaryHash(reverse)); + } + + [Test] + public async Task Dictionary_CollectionValues_UseTheValueComparer() + { + Dictionary> forward = new() + { + ["a"] = new List { 1, 2 }, + }; + Dictionary> reverse = new() + { + ["a"] = new List { 1, 2 }, + }; + + // The default value comparer is reference equality for a list. + await Assert.That(ValueObjectEquality.DictionaryEquals(forward, reverse)).IsFalse(); + + ValueObjectSequenceComparer valueComparer = new(); + await Assert.That(ValueObjectEquality.DictionaryEquals(forward, reverse, valueComparer)).IsTrue(); + await Assert + .That(ValueObjectEquality.DictionaryHash(forward, valueComparer)) + .IsEqualTo(ValueObjectEquality.DictionaryHash(reverse, valueComparer)); + await Assert.That(ValueObjectEquality.DictionaryCompare(forward, reverse, valueComparer)).IsEqualTo(0); + } + + [Test] + public async Task DictionaryCompare_EqualDictionaries_AreZero() + { + Dictionary forward = new() { ["a"] = 1, ["b"] = 2 }; + Dictionary reverse = new() { ["b"] = 2, ["a"] = 1 }; + + await Assert.That(ValueObjectEquality.DictionaryCompare(forward, reverse)).IsEqualTo(0); + } + + [Test] + public async Task SequenceEquals_NestedCollections_UseTheStructuralComparer() + { + IReadOnlyList> first = + [ + [1, 2], + [3], + ]; + IReadOnlyList> second = [new List { 1, 2 }, new List { 3 }]; + + await Assert + .That( + ValueObjectEquality.SequenceEquals>( + first, + second, + new ValueObjectSequenceComparer() + ) + ) + .IsTrue(); + } + + [Test] + public async Task SetEquals_NestedCollections_UseTheStructuralComparer() + { + HashSet> first = new( + new[] + { + new List { 1, 2 }, + }, + new RefComparer() + ); + HashSet> second = new( + new[] + { + new List { 1, 2 }, + }, + new RefComparer() + ); + + await Assert + .That(ValueObjectEquality.SetEquals>(first, second, new ValueObjectSetComparer())) + .IsTrue(); + } + + sealed class RefComparer : IEqualityComparer> + { + public bool Equals(IReadOnlyList? x, IReadOnlyList? y) => ReferenceEquals(x, y); + + public int GetHashCode(IReadOnlyList obj) => + System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); + } +} From 9ae4e7191e9451096ffb8c6879ee1bddda1a5792 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 25 Nov 2026 12:06:37 +0000 Subject: [PATCH 3/3] qol: updated structure --- .config/dotnet-tools.json | 2 +- .config/lefthook.yml | 7 +-- .gitattributes | 14 +++++- bun.lock | 96 +++++++++++++++++++++++++++++++++++++++ bunfig.toml | 25 ++++++++++ commitlint.config.mts | 14 ++++-- package.json | 4 ++ src/Directory.Build.props | 13 ------ 8 files changed, 150 insertions(+), 25 deletions(-) create mode 100644 bun.lock create mode 100644 bunfig.toml diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index ec846e1..f614930 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "csharpier": { - "version": "1.4.0", + "version": "1.4.1", "commands": [ "csharpier" ], diff --git a/.config/lefthook.yml b/.config/lefthook.yml index 97949c3..1a4201c 100644 --- a/.config/lefthook.yml +++ b/.config/lefthook.yml @@ -1,9 +1,4 @@ -pre-commit: - jobs: - - name: lint staged - run: just lint-check - commit-msg: jobs: - name: conventional commits - run: bun x commitlint --edit {1} + run: bun x --bun commitlint --edit {1} diff --git a/.gitattributes b/.gitattributes index ee62874..e2f6fb7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -49,6 +49,10 @@ *.jsx text *.ts text *.tsx text +*.mjs text +*.mts text +*.cjs text +*.cts text *.html text diff=html *.css text *.scss text @@ -68,8 +72,16 @@ Dockerfile text eol=lf *.dockerfile text eol=lf justfile text eol=lf +Justfile text eol=lf +*.just text eol=lf Makefile text eol=lf +# Lockfiles -- text (bun.lock is JSONC) but generated, so collapse them in diffs/PRs. +bun.lock text eol=lf -diff linguist-generated +package-lock.json text eol=lf -diff linguist-generated +pnpm-lock.yaml text eol=lf -diff linguist-generated +yarn.lock text eol=lf -diff linguist-generated + # Patches carry their own endings -- never touch them. *.patch -text @@ -105,4 +117,4 @@ Makefile text eol=lf # --------------------------------------------------------------------------- .gitattributes export-ignore .gitignore export-ignore -.github/ export-ignore \ No newline at end of file +.github/ export-ignore diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..16fc145 --- /dev/null +++ b/bun.lock @@ -0,0 +1,96 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "value-objects", + "devDependencies": { + "oxfmt": "^0.79.0", + "oxlint": "^1.94.0", + }, + }, + }, + "packages": { + "@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.79.0", "", { "os": "android", "cpu": "arm" }, "sha512-xOCQ/rvokUXs8SxOQY5Wy2ukPaZJZ0PmdJovN0ryB1c8DVEtbcvliLdYtINUYh8QOTpmBOctIisSJk9tvh+J6w=="], + + "@oxfmt/binding-android-arm64": ["@oxfmt/binding-android-arm64@0.79.0", "", { "os": "android", "cpu": "arm64" }, "sha512-WMLDvCjjchUYtI6zXKOdzTDGm72BaYZiz1/VhB1rrxdakUZRlJh1aMr3CT6ui51uHcWVBycULIXSZHpw6u2pTQ=="], + + "@oxfmt/binding-darwin-arm64": ["@oxfmt/binding-darwin-arm64@0.79.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+LzSN7w7tULz96ntS1Uqe5oI00XZ0o/m/t3+eSfiQp3aTPnj2eGUafqEWryMLk84j7x9NiF+GEP2YT4/BfClgA=="], + + "@oxfmt/binding-darwin-x64": ["@oxfmt/binding-darwin-x64@0.79.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-KFiMRhKeiiooaS1dKc4r8AZgOrfOhwVe1yf/aRef+8BajJwtVjMtlsQl/BNRxtkFbq13GjEo/4Q+9YhFGU4o6g=="], + + "@oxfmt/binding-freebsd-x64": ["@oxfmt/binding-freebsd-x64@0.79.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-lHVIp0g8ZOFKiqVscvttp+3HJkkRH6XkGgfAA0lVexIlE1mMFVp4V7RBdxz/P9p7T8pSNsYdapFWvdT21Mib9w=="], + + "@oxfmt/binding-linux-arm-gnueabihf": ["@oxfmt/binding-linux-arm-gnueabihf@0.79.0", "", { "os": "linux", "cpu": "arm" }, "sha512-Pt35GoxiMUfnr+23cuzk07XQVvISDFxxPcp/aFVB87+RQvJoQaBo/XN7Re9XxgElvbELdyxTLnV9XM2aTfJeUA=="], + + "@oxfmt/binding-linux-arm-musleabihf": ["@oxfmt/binding-linux-arm-musleabihf@0.79.0", "", { "os": "linux", "cpu": "arm" }, "sha512-zPi9Dni58VKp3r1QUcFvnbJNfBr49qyecq0vlM4SaX/MSjmguq77VngirghDua5tyhIDfqdUMTCK2KRlnZFp/g=="], + + "@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/binding-linux-arm64-gnu@0.79.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-XhRehATEWjwX7VVEgDUD+7pfHYncQIJaEU0qsHvEKtu9XX0QYzcKvXhU9+URfiGX9WRh3wy2Ow+YCc3EeHtImg=="], + + "@oxfmt/binding-linux-arm64-musl": ["@oxfmt/binding-linux-arm64-musl@0.79.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-gbVjFZYug0MEyqvuTAzXGNxFJmBqBO32o1Fud1lG8bGs6oVz48ZtNQyEcAzqrOwaaG+Sxtv4gVzcsfht9aqmkg=="], + + "@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/binding-linux-ppc64-gnu@0.79.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-0N0sD3vnllyuiNh1r6zKvNXWE/CakcPKJAespg7XE2+sfvxpz5Q1iFah8sF5aedsOmVvbZaOPZcSHVmMosT1fA=="], + + "@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/binding-linux-riscv64-gnu@0.79.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-YtjqUHolcX6cv0ZMZuKQCM4H0ae/okcowy0wGcPHJk4O+8zjy3TvNhzDQ1/KGCkMJO8Fwulm1JcPJsraVJ3p+w=="], + + "@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/binding-linux-riscv64-musl@0.79.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-H2gb9bEBr5tcdP5FU8JYTfgOavXDorWcAAlwci/zEKF2jzgh/oEr/SAw6aHB9n3FLEvnKvOh0A1fjku+vgYoUA=="], + + "@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/binding-linux-s390x-gnu@0.79.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-aZUbyWW5dSOxT/u6suWc4S9GVDt7YPPNMKQon+z79M8dpXmosadcFHAb7jBhpU7Hdsd2GN6/y3nd0JFTsGddZw=="], + + "@oxfmt/binding-linux-x64-gnu": ["@oxfmt/binding-linux-x64-gnu@0.79.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-5pW/ZHYfjjQ71gQR+EKzDz8ZzWIDHlTUtWtxVFNgZbKxVZnRxiSXVrllbjpJtx1q8VtSPZ+Lyg9BLny3yw+PTA=="], + + "@oxfmt/binding-linux-x64-musl": ["@oxfmt/binding-linux-x64-musl@0.79.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-3IVUerTDB7Dvd90c1EurAzlVnlE9Azl7Wn8e33qX3wL/IqnslF+P7HvwkD+VeMbHxRtuw0EEBGSArZFXpUAZrQ=="], + + "@oxfmt/binding-openharmony-arm64": ["@oxfmt/binding-openharmony-arm64@0.79.0", "", { "os": "none", "cpu": "arm64" }, "sha512-C5QDgJBtu9+/2BQScoP7ynv54PLOqfoSqhRWwI0D0RPOwYD4tYj0TUdJbXMO1fNegL/5zJiSOxkq6II2xvttWg=="], + + "@oxfmt/binding-win32-arm64-msvc": ["@oxfmt/binding-win32-arm64-msvc@0.79.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-zlW1m8M49vNGgqQF/ze80KW8pZMicnW2XDZGBHuYtXTRYn4ewvgpqN9wwoqb6uLZZfb1R1zaQWKEB8cs7KYjwA=="], + + "@oxfmt/binding-win32-ia32-msvc": ["@oxfmt/binding-win32-ia32-msvc@0.79.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-wbb7hFv2wK3SCTfu8dl1ydNsXM5dmH+PJMU3sojCkfKcG29VDpITL5/AtouCzXjkOc90QRkcAZcg36gP0KqoHA=="], + + "@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.79.0", "", { "os": "win32", "cpu": "x64" }, "sha512-JLaeaQ+4LkQiVXY06JIV1dBFEDJzssvDieK/3Poi6CsY+c4UxghZVrrsfcKGJ5R/0F2Sw3C5Lf5Hu0sM5qJfPw=="], + + "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.94.0", "", { "os": "android", "cpu": "arm" }, "sha512-730FKSBsKg/NawYnpI3gXRroXptOVqY32iYBPLUZaSx0vgYzOeiNtwojZL4gJdzo9wDvHUlstShmGRHrWcbRYg=="], + + "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.94.0", "", { "os": "android", "cpu": "arm64" }, "sha512-8v8TICIiZpXLot1HSq5+vsG9NEKQ5czQBYlUqJR75OVfFDr3cGOmRU/CtHDWnS4tm8nW+Z4Y357qGToSfYqFvA=="], + + "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.94.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-NePcRMO/ltt1Pnytohl6pl0bd/QyRX8HbpptuDz9LK7FTsFD4lKxDMBt7di9k6IFLO0J05jO2nm7wGqIh6dRHA=="], + + "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.94.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-QV+m+OaEgLmYyillvP1wKXhMm6tDZEWx3vG7Wjmx9ybg15+6YMfqzvp6e+uPukC6zNywuule0vMn0fZgihZzZA=="], + + "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.94.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-KVZjca581nrV6P71kZ9M1otBib9LH0IMn9rr4mrnbRp18V0HiZhBHbU26gji/Ieq2G34qMacnMc3zrmKmvWqWA=="], + + "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.94.0", "", { "os": "linux", "cpu": "arm" }, "sha512-AMQtgQJk8DgdIV+qaQ5sFoHAko4iKa8zo+gYqELy2grtU8hXWB08DAGB3u90aQL1YSxbd3zqHjgcODBHDFyzBQ=="], + + "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.94.0", "", { "os": "linux", "cpu": "arm" }, "sha512-ZLzoGVGAmQkp9leeB5rNxAXLcvlmkmd/GY71LKd5uikk+28NEApY3S2FB3pq6MkfOCFFnFg6QgD9lJIjd07D0Q=="], + + "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.94.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-N1dW6o7cY90hLVkDsvz8nWIFOwbO+n272pvW7uLYB7u47HagJVnLChfK6QA9dWFdiPudud9zfksVUOciHc5PNA=="], + + "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.94.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-7tCF4OV/bGDQ2xxgb+sDI97SpmmDrUII4JxTG553voJVA9cnkbXSGSXzo78Ax73BuhEOPoQc2Qi6VrfT0cDG2A=="], + + "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.94.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-B5vUHE4wNisVEuaYxwFUn6tY+vw7A+9APxxqGKI+UmP3yKLpkhnt0qsaCrzjpX55F8rCRHBaTvIDdYo32NE36g=="], + + "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.94.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-/U0b15+c4hTodo8YhEqDlQ6OjnGKvc8igjM/mh23ukqqCUBKiBCaxqUV8bcaofK9uZ+f8wCygkyXLS6LN25YSA=="], + + "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.94.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-ba94Vwl0qOnwXIXNDR33AEbLXuX++ckM74t+9Te7CiPSPAHivhOYyeEkUAicrvOEei1pxXkWggLbFeBFFBTuHA=="], + + "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.94.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-GVwwwms3O8pdgbCiPavwq2vltyB4661GkDz6kJduZ0E5nsSJUDJ0svaP+ePYpuDVYi4+K1qhCKnWa/Ec8I4LUA=="], + + "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.94.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-iUfCFJN8ZIresSnpTfiIkhF3s8X+XA4I9KJ249QwR2QYTMwh0+pla1pj1xaFi+HtR9McjM4Jaemf70HzX7ilOQ=="], + + "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.94.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-RqWVeWpDACS4Oh0m21OBmy+CQ50CbbhuHFmNNPVS2P/4R3d188MjEuEuV7So82/tAM8UAT+UuMDtRDESd9NJ7g=="], + + "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.94.0", "", { "os": "none", "cpu": "arm64" }, "sha512-K/2DHOUoypwYVqzxJMRPdMuBKjAetZEAsGPP7rHimd+2+5J1TxM+17pG8kw+ayH4+rqBXiPd+H9wgPcU+fF77A=="], + + "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.94.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-hYOCaOJiB4ZCGswBWKl3JQrhqu6mnC5DCUw/1UMNzRXgsHIJ0V226J43LAVICVIDGlhFUZTYShFW+wHWpt6qCQ=="], + + "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.94.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-1l1FDlzbPmAeDoZ8UGspOE2dOmz1ZL6SlDsvOmRCmWSQjCdTy5LzUepS8mO/SGpAoz4D6WAt/yNZAUyHqbkmkQ=="], + + "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.94.0", "", { "os": "win32", "cpu": "x64" }, "sha512-I3eZdd4bemIJQDNv9XDV/FEofDxIoN32tzCv98wIgLdW05EqxZb5hF4AwPrRzHD/dQhl0n7KgPy5AQPfM0HWrA=="], + + "oxfmt": ["oxfmt@0.79.0", "", { "dependencies": { "tinypool": "2.2.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.79.0", "@oxfmt/binding-android-arm64": "0.79.0", "@oxfmt/binding-darwin-arm64": "0.79.0", "@oxfmt/binding-darwin-x64": "0.79.0", "@oxfmt/binding-freebsd-x64": "0.79.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.79.0", "@oxfmt/binding-linux-arm-musleabihf": "0.79.0", "@oxfmt/binding-linux-arm64-gnu": "0.79.0", "@oxfmt/binding-linux-arm64-musl": "0.79.0", "@oxfmt/binding-linux-ppc64-gnu": "0.79.0", "@oxfmt/binding-linux-riscv64-gnu": "0.79.0", "@oxfmt/binding-linux-riscv64-musl": "0.79.0", "@oxfmt/binding-linux-s390x-gnu": "0.79.0", "@oxfmt/binding-linux-x64-gnu": "0.79.0", "@oxfmt/binding-linux-x64-musl": "0.79.0", "@oxfmt/binding-openharmony-arm64": "0.79.0", "@oxfmt/binding-win32-arm64-msvc": "0.79.0", "@oxfmt/binding-win32-ia32-msvc": "0.79.0", "@oxfmt/binding-win32-x64-msvc": "0.79.0" }, "peerDependencies": { "@astrojs/compiler-rs": "^0.5.0", "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["@astrojs/compiler-rs", "svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-92iLHGxAgtYk6jLp/1ZBnEeABveNduHZgMDQj7tyqO9iafuJG3q+YHJq0R5Aa4YT+E6xswMQXdmPZYMwynS8ig=="], + + "oxlint": ["oxlint@1.94.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.94.0", "@oxlint/binding-android-arm64": "1.94.0", "@oxlint/binding-darwin-arm64": "1.94.0", "@oxlint/binding-darwin-x64": "1.94.0", "@oxlint/binding-freebsd-x64": "1.94.0", "@oxlint/binding-linux-arm-gnueabihf": "1.94.0", "@oxlint/binding-linux-arm-musleabihf": "1.94.0", "@oxlint/binding-linux-arm64-gnu": "1.94.0", "@oxlint/binding-linux-arm64-musl": "1.94.0", "@oxlint/binding-linux-ppc64-gnu": "1.94.0", "@oxlint/binding-linux-riscv64-gnu": "1.94.0", "@oxlint/binding-linux-riscv64-musl": "1.94.0", "@oxlint/binding-linux-s390x-gnu": "1.94.0", "@oxlint/binding-linux-x64-gnu": "1.94.0", "@oxlint/binding-linux-x64-musl": "1.94.0", "@oxlint/binding-openharmony-arm64": "1.94.0", "@oxlint/binding-win32-arm64-msvc": "1.94.0", "@oxlint/binding-win32-ia32-msvc": "1.94.0", "@oxlint/binding-win32-x64-msvc": "1.94.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2007", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-Fnt+3wSKRhtLmvgRfxgRX0excSPCoyiXRol4eWKZLtXxWMQtwQ3KjKQUYXOw5loyinfnZfGzh4RCYf7opfL0vw=="], + + "tinypool": ["tinypool@2.2.0", "", {}, "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ=="], + } +} diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000..cfbd095 --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,25 @@ +# Project-level Bun configuration. +# Mirrors the user-level .bunfig.toml installed by the profile; keys set here win. + +# Disable anonymous crash reporting and analytics. +telemetry = false + +[run] +# Prefer Bun over Node.js when launching scripts and shebang binaries. +bun = true + +# Cross-platform shell execution. +shell = "bun" + +# Don't echo each script command before executing it. +silent = true + +# Terminate descendant processes when the parent exits. +noOrphans = true + +[install] +# Prefer cached package metadata to network staleness checks. +prefer = "offline" + +# Still reach the registry when a package isn't cached. +offline = false diff --git a/commitlint.config.mts b/commitlint.config.mts index 00420ab..29384ce 100644 --- a/commitlint.config.mts +++ b/commitlint.config.mts @@ -1,9 +1,15 @@ +// Conventional Commits, plus `qol` (quality of life) for developer-experience changes: +// tooling, scripts, editor config, DX tweaks that are neither a feature nor a fix. +// Keep the type-enum array inline and comment-free so Show-CommitTypes can parse it. export default { + helpUrl: 'https://www.conventionalcommits.org/en/v1.0.0/', rules: { 'body-leading-blank': [1, 'always'], - 'body-max-line-length': [2, 'always', 100], + // Warn rather than fail: URLs, stack traces and pasted output legitimately run long. + 'body-max-line-length': [1, 'always', 100], 'footer-leading-blank': [1, 'always'], - 'footer-max-line-length': [2, 'always', 100], + // Warn rather than fail: Co-authored-by and issue-link trailers are often long. + 'footer-max-line-length': [1, 'always', 100], 'header-max-length': [2, 'always', 100], 'header-trim': [2, 'always'], 'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pascal-case', 'upper-case']], @@ -14,7 +20,7 @@ export default { 'type-enum': [ 2, 'always', - ['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test', 'qol'], + ['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'qol', 'refactor', 'revert', 'style', 'test'], ], }, -}; \ No newline at end of file +}; diff --git a/package.json b/package.json index cf1da5a..87a35f4 100644 --- a/package.json +++ b/package.json @@ -13,5 +13,9 @@ "repository": { "type": "git", "url": "git+https://github.com/purview-dev/value-objects.git" + }, + "devDependencies": { + "oxfmt": "^0.79.0", + "oxlint": "^1.94.0" } } \ No newline at end of file diff --git a/src/Directory.Build.props b/src/Directory.Build.props index b8c8a45..7b2117e 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -9,19 +9,6 @@ were dropped alongside the .NET 11 GA. Roslyn components are excluded by the SDK, which targets them at netstandard2.0. --> Supported - - true - 0