From 83e200b66bc7855c4a91a0c4654fd2d3e918bf40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Breu=C3=9F=20Valentin?= Date: Fri, 4 Dec 2026 17:40:29 +0100 Subject: [PATCH] fix: support in and ref readonly indexer keys, span returns with ref struct parameters and [UnscopedRef] parameters in mocks Three member shapes made the generated mock fail to compile, and with it the whole test project. - Indexer keys declared `in` or `ref readonly` (also `scoped`) lost their modifier, so the mock did not implement or override the indexer (CS0535, CS9048). The declaration now repeats the modifiers and the wrapped or base indexer gets a `ref readonly` key with `in` (CS9192). A `ref readonly` key outside the ref struct pipeline is set up and verified like an `in` key, because the indexer setups have no slot for a by-reference matcher. - A member with a custom ref struct parameter that returns `Span` or `ReadOnlySpan` by value used the span as a type argument of its ref struct setup (CS9244). These setups now wrap the span like every other span return, for methods and for indexers keyed by a ref struct. - A member whose result may refer to an `[UnscopedRef]` parameter, such as `Span Get([UnscopedRef] ref int value)`, could not return the result of the wrapped or base member (CS9077, CS8347). The method declarations and the `Invoke` method of delegate mocks now repeat the attribute. A plain `ref int` return already compiled. --- Docs/pages/06-parameter-matching.md | 2 + .../Entities/MethodParameter.cs | 21 +++- .../Entities/Property.cs | 2 +- .../Sources/SourceTemplates.MockClass.cs | 37 +++--- .../Sources/SourceTemplates.MockDelegate.cs | 2 +- .../Sources/SourceTemplates.cs | 19 ++- .../Incrementality/MockClassEqualityTests.cs | 30 +++++ .../SpecialCases/IndexerKeyRefKindTests.cs | 111 ++++++++++++++++++ .../SpecialCases/RefStructSpanReturnTests.cs | 80 +++++++++++++ .../SpecialCases/ScopedParameterTests.cs | 6 +- .../SpecialCases/UnscopedRefParameterTests.cs | 99 ++++++++++++++++ .../GeneratorCoverage/IndexerKeyRefKinds.cs | 23 ++++ .../GeneratorCoverage/RefStructSpanReturns.cs | 22 ++++ .../UnscopedRefParameters.cs | 25 ++++ .../GeneratorShapes/IndexerKeyRefKindTests.cs | 85 ++++++++++++++ .../RefStructSpanReturnTests.cs | 64 ++++++++++ .../UnscopedRefParameterTests.cs | 80 +++++++++++++ 17 files changed, 681 insertions(+), 27 deletions(-) create mode 100644 Tests/Mockolate.SourceGenerators.Tests/SpecialCases/IndexerKeyRefKindTests.cs create mode 100644 Tests/Mockolate.SourceGenerators.Tests/SpecialCases/RefStructSpanReturnTests.cs create mode 100644 Tests/Mockolate.SourceGenerators.Tests/SpecialCases/UnscopedRefParameterTests.cs create mode 100644 Tests/Mockolate.Tests/GeneratorCoverage/IndexerKeyRefKinds.cs create mode 100644 Tests/Mockolate.Tests/GeneratorCoverage/RefStructSpanReturns.cs create mode 100644 Tests/Mockolate.Tests/GeneratorCoverage/UnscopedRefParameters.cs create mode 100644 Tests/Mockolate.Tests/GeneratorShapes/IndexerKeyRefKindTests.cs create mode 100644 Tests/Mockolate.Tests/GeneratorShapes/RefStructSpanReturnTests.cs create mode 100644 Tests/Mockolate.Tests/GeneratorShapes/UnscopedRefParameterTests.cs diff --git a/Docs/pages/06-parameter-matching.md b/Docs/pages/06-parameter-matching.md index 35863bfde..28212c346 100644 --- a/Docs/pages/06-parameter-matching.md +++ b/Docs/pages/06-parameter-matching.md @@ -366,6 +366,8 @@ In verifications, use `It.IsOut()` and `It.IsRef()` without arguments to m kitchen.Mock.Verify.TryParse("abc", It.IsOut()).Once(); ``` +Unlike `ref readonly` method parameters, indexer keys declared `in` or `ref readonly` take a value or a matcher like `It.Is(value)`, as keys passed by value do. Keys of a custom ref struct type use the [ref struct matchers](#ref-struct-parameters-net-9). + ## Span parameters (.NET 8+) :::info[.NET 8 or later] diff --git a/Source/Mockolate.SourceGenerators/Entities/MethodParameter.cs b/Source/Mockolate.SourceGenerators/Entities/MethodParameter.cs index 361b052ce..28072c020 100644 --- a/Source/Mockolate.SourceGenerators/Entities/MethodParameter.cs +++ b/Source/Mockolate.SourceGenerators/Entities/MethodParameter.cs @@ -70,14 +70,29 @@ public MethodParameter(IParameterSymbol parameterSymbol) public bool IsNullableAnnotated { get; } public Type Type { get; } public string Name { get; } - public RefKind RefKind { get; } + public RefKind RefKind { get; private init; } /// - /// Whether the parameter is passed by reference and marked with a public [UnscopedRef], which a mock - /// constructor repeats to pass the parameter on to the base constructor. + /// Whether the indexer key is declared ref readonly. sets up and verifies such + /// a key like an key, while the declaration of the indexer repeats the modifier. + /// + public bool IsRefReadOnlyIndexerKey { get; private init; } + + /// + /// Whether the parameter is passed by reference and marked with a public [UnscopedRef], which a + /// declaration matching the original signature repeats. /// public bool IsUnscopedRef { get; } + /// + /// The parameter as an indexer key: the indexer setups have no slot for a by-reference matcher, so a + /// ref readonly key outside the ref-struct pipeline is set up and verified like an key. + /// + internal MethodParameter AsIndexerKey() + => RefKind == RefKind.RefReadOnlyParameter && !Type.IsRefStruct + ? this with { RefKind = RefKind.In, IsRefReadOnlyIndexerKey = true, } + : this; + internal static MethodParameter From(IParameterSymbol symbol) { EntityCache? cache = EntityCache.Current; diff --git a/Source/Mockolate.SourceGenerators/Entities/Property.cs b/Source/Mockolate.SourceGenerators/Entities/Property.cs index 2e83bb26d..d57c7c47b 100644 --- a/Source/Mockolate.SourceGenerators/Entities/Property.cs +++ b/Source/Mockolate.SourceGenerators/Entities/Property.cs @@ -26,7 +26,7 @@ public Property(IPropertySymbol propertySymbol, List? alreadyDefinedPr if (IsIndexer && propertySymbol.Parameters.Length > 0) { IndexerParameters = new EquatableArray( - propertySymbol.Parameters.Select(MethodParameter.From).ToArray()); + propertySymbol.Parameters.Select(parameter => MethodParameter.From(parameter).AsIndexerKey()).ToArray()); } Attributes = propertySymbol.GetAttributes().ToAttributeArray(sourceAssembly, propertySymbol.ContainingType); diff --git a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.cs b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.cs index 47ce6f1d8..7ad9ffe3e 100644 --- a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.cs +++ b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.cs @@ -2380,7 +2380,7 @@ void AppendIndexerSetCall(string prefix, string suffix, string accessVarName, st sb.Append(property.IsStatic ? "\t\tstatic " : "\t\t").Append(refReturnPrefix).Append(property.Type.Fullname) .Append(' ').Append(property.ContainingType).Append('.').Append(property.IndexerParameters is not null ? property.Name.Replace("[]", - $"[{string.Join(", ", property.IndexerParameters.Value.Select(p => $"{p.GetScopedModifier()}{p.Type.Fullname} {p.Name}"))}]") + $"[{string.Join(", ", property.IndexerParameters.Value.Select(p => $"{p.GetIndexerKeyModifiers()}{p.Type.Fullname} {p.Name}"))}]") : property.Name).AppendLine(); } else @@ -2419,7 +2419,7 @@ void AppendIndexerSetCall(string prefix, string suffix, string accessVarName, st sb.Append(property.IndexerParameters is not null ? property.Name.Replace("[]", - $"[{string.Join(", ", property.IndexerParameters.Value.Select(p => $"{p.GetScopedModifier()}{p.Type.Fullname} {p.Name}"))}]") + $"[{string.Join(", ", property.IndexerParameters.Value.Select(p => $"{p.GetIndexerKeyModifiers()}{p.Type.Fullname} {p.Name}"))}]") : property.Name).AppendLine(); } @@ -3060,7 +3060,8 @@ method.ExplicitImplementation is null && sb.Append(", "); } - sb.Append(parameter.GetScopedModifier()).Append(parameter.RefKind.GetString()); + sb.Append(parameter.GetUnscopedRefAttribute()).Append(parameter.GetScopedModifier()) + .Append(parameter.RefKind.GetString()); if (parameter.IsParams) { sb.Append("params "); @@ -3688,7 +3689,7 @@ private static void AppendMockSubject_ImplementClass_AddRefStructMethodBody( string typeParams = string.Join(", ", method.Parameters.Select(p => p.Type.Fullname)); string setupType = method.ReturnType == Type.Void ? $"global::Mockolate.Setup.RefStructVoidMethodSetup<{typeParams}>" - : $"global::Mockolate.Setup.RefStructReturnMethodSetup<{method.ReturnType.Fullname}, {typeParams}>"; + : $"global::Mockolate.Setup.RefStructReturnMethodSetup<{method.ReturnType.ToTypeOrWrapper()}, {typeParams}>"; // Record the invocation — names only, no values. The ref-struct values stay on the stack. sb.Append("\t\t\t").Append(mockRegistry) @@ -3862,7 +3863,7 @@ private static void AppendRefStructIndexerGetterBody(StringBuilder sb, Property string typeParams = string.Join(", ", property.IndexerParameters!.Value.Select(p => p.Type.Fullname)); string setupType = - $"global::Mockolate.Setup.RefStructIndexerGetterSetup<{property.Type.Fullname}, {typeParams}>"; + $"global::Mockolate.Setup.RefStructIndexerGetterSetup<{property.Type.ToTypeOrWrapper()}, {typeParams}>"; string displayName = $"{property.ContainingType}.this[{string.Join(", ", property.IndexerParameters!.Value.Select(p => p.Type.DisplayName))}]"; string indexerName = $"\"{property.ContainingType}.get_Item\""; @@ -3958,7 +3959,7 @@ private static void AppendRefStructIndexerSetterBody(StringBuilder sb, Property string typeParams = string.Join(", ", property.IndexerParameters!.Value.Select(p => p.Type.Fullname)); string setupType = - $"global::Mockolate.Setup.RefStructIndexerSetterSetup<{property.Type.Fullname}, {typeParams}>"; + $"global::Mockolate.Setup.RefStructIndexerSetterSetup<{property.Type.ToTypeOrWrapper()}, {typeParams}>"; string indexerName = $"\"{property.ContainingType}.set_Item\""; // Record the invocation — names only, no ref-struct key values (stays on the stack). The @@ -5970,7 +5971,7 @@ private static void AppendRefStructMethodSetupDefinition(StringBuilder sb, Metho string typeParams = string.Join(", ", method.Parameters.Select(p => p.Type.Fullname)); string iface = method.ReturnType == Type.Void ? $"global::Mockolate.Setup.IRefStructVoidMethodSetup<{typeParams}>" - : $"global::Mockolate.Setup.IRefStructReturnMethodSetup<{method.ReturnType.Fullname}, {typeParams}>"; + : $"global::Mockolate.Setup.IRefStructReturnMethodSetup<{method.ReturnType.ToTypeOrWrapper()}, {typeParams}>"; sb.Append("#if NET9_0_OR_GREATER").AppendLine(); sb.AppendXmlSummary( @@ -6030,10 +6031,10 @@ private static void AppendRefStructMethodSetupImplementation(StringBuilder sb, M string typeParams = string.Join(", ", method.Parameters.Select(p => p.Type.Fullname)); string iface = method.ReturnType == Type.Void ? $"global::Mockolate.Setup.IRefStructVoidMethodSetup<{typeParams}>" - : $"global::Mockolate.Setup.IRefStructReturnMethodSetup<{method.ReturnType.Fullname}, {typeParams}>"; + : $"global::Mockolate.Setup.IRefStructReturnMethodSetup<{method.ReturnType.ToTypeOrWrapper()}, {typeParams}>"; string concrete = method.ReturnType == Type.Void ? $"global::Mockolate.Setup.RefStructVoidMethodSetup<{typeParams}>" - : $"global::Mockolate.Setup.RefStructReturnMethodSetup<{method.ReturnType.Fullname}, {typeParams}>"; + : $"global::Mockolate.Setup.RefStructReturnMethodSetup<{method.ReturnType.ToTypeOrWrapper()}, {typeParams}>"; sb.Append("#if NET9_0_OR_GREATER").AppendLine(); sb.Append("\t\t/// ").AppendLine(); @@ -6307,7 +6308,7 @@ private static void AppendRefStructIndexerGetterSetupDefinition(StringBuilder sb $"Setup for the ref-struct-keyed getter-only indexer {indexer.XmlDocReference}" + " — narrow setup surface (Returns / Throws / SkippingBaseClass)."); sb.Append("\t\tglobal::Mockolate.Setup.IRefStructIndexerGetterSetup<") - .Append(indexer.Type.Fullname); + .Append(indexer.Type.ToTypeOrWrapper()); foreach (MethodParameter p in indexer.IndexerParameters!.Value) { sb.Append(", ").Append(p.Type.Fullname); @@ -6343,9 +6344,9 @@ private static void AppendRefStructIndexerGetterSetupImplementation(StringBuilde string scopePrefix = scopeExpression is null ? "" : scopeExpression + ", "; string typeParams = string.Join(", ", indexer.IndexerParameters!.Value.Select(p => p.Type.Fullname)); string iface = - $"global::Mockolate.Setup.IRefStructIndexerGetterSetup<{indexer.Type.Fullname}, {typeParams}>"; + $"global::Mockolate.Setup.IRefStructIndexerGetterSetup<{indexer.Type.ToTypeOrWrapper()}, {typeParams}>"; string concrete = - $"global::Mockolate.Setup.RefStructIndexerGetterSetup<{indexer.Type.Fullname}, {typeParams}>"; + $"global::Mockolate.Setup.RefStructIndexerGetterSetup<{indexer.Type.ToTypeOrWrapper()}, {typeParams}>"; string indexerName = $"\"{indexer.ContainingType}.get_Item\""; sb.Append("#if NET9_0_OR_GREATER").AppendLine(); @@ -6400,7 +6401,7 @@ private static void AppendRefStructIndexerSetterSetupDefinition(StringBuilder sb $"Setup for the ref-struct-keyed setter-only indexer {indexer.XmlDocReference}" + " — narrow setter surface (OnSet / Throws / SkippingBaseClass)."); sb.Append("\t\tglobal::Mockolate.Setup.IRefStructIndexerSetterSetup<") - .Append(indexer.Type.Fullname); + .Append(indexer.Type.ToTypeOrWrapper()); foreach (MethodParameter p in indexer.IndexerParameters!.Value) { sb.Append(", ").Append(p.Type.Fullname); @@ -6431,9 +6432,9 @@ private static void AppendRefStructIndexerSetterSetupImplementation(StringBuilde string scopePrefix = scopeExpression is null ? "" : scopeExpression + ", "; string typeParams = string.Join(", ", indexer.IndexerParameters!.Value.Select(p => p.Type.Fullname)); string iface = - $"global::Mockolate.Setup.IRefStructIndexerSetterSetup<{indexer.Type.Fullname}, {typeParams}>"; + $"global::Mockolate.Setup.IRefStructIndexerSetterSetup<{indexer.Type.ToTypeOrWrapper()}, {typeParams}>"; string concrete = - $"global::Mockolate.Setup.RefStructIndexerSetterSetup<{indexer.Type.Fullname}, {typeParams}>"; + $"global::Mockolate.Setup.RefStructIndexerSetterSetup<{indexer.Type.ToTypeOrWrapper()}, {typeParams}>"; string indexerName = $"\"{indexer.ContainingType}.set_Item\""; sb.Append("#if NET9_0_OR_GREATER").AppendLine(); @@ -6486,7 +6487,7 @@ private static void AppendRefStructIndexerSetupDefinition(StringBuilder sb, Prop $"Setup for the ref-struct-keyed get+set indexer {indexer.XmlDocReference}" + " — combined getter/setter facade."); sb.Append("\t\tglobal::Mockolate.Setup.IRefStructIndexerSetup<") - .Append(indexer.Type.Fullname); + .Append(indexer.Type.ToTypeOrWrapper()); foreach (MethodParameter p in indexer.IndexerParameters!.Value) { sb.Append(", ").Append(p.Type.Fullname); @@ -6517,9 +6518,9 @@ private static void AppendRefStructIndexerSetupImplementation(StringBuilder sb, string scopePrefix = scopeExpression is null ? "" : scopeExpression + ", "; string typeParams = string.Join(", ", indexer.IndexerParameters!.Value.Select(p => p.Type.Fullname)); string iface = - $"global::Mockolate.Setup.IRefStructIndexerSetup<{indexer.Type.Fullname}, {typeParams}>"; + $"global::Mockolate.Setup.IRefStructIndexerSetup<{indexer.Type.ToTypeOrWrapper()}, {typeParams}>"; string concrete = - $"global::Mockolate.Setup.RefStructIndexerSetup<{indexer.Type.Fullname}, {typeParams}>"; + $"global::Mockolate.Setup.RefStructIndexerSetup<{indexer.Type.ToTypeOrWrapper()}, {typeParams}>"; string getterName = $"\"{indexer.ContainingType}.get_Item\""; string setterName = $"\"{indexer.ContainingType}.set_Item\""; diff --git a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockDelegate.cs b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockDelegate.cs index f79287452..8f0a82ea9 100644 --- a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockDelegate.cs +++ b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockDelegate.cs @@ -70,7 +70,7 @@ public static string MockDelegate(string name, MockClass @class, Method delegate }; sb.Append("\t\tprivate ").Append(returnRefPrefix) .Append(delegateMethod.ReturnType == Type.Void ? "void" : delegateMethod.ReturnType.Fullname).Append(" Invoke(") - .Append(string.Join(", ", delegateMethod.Parameters.Select(p => $"{p.GetScopedModifier()}{p.RefKind.GetString()}{p.Type.Fullname} {p.Name}"))).Append(')').AppendLine(); + .Append(string.Join(", ", delegateMethod.Parameters.Select(p => $"{p.GetUnscopedRefAttribute()}{p.GetScopedModifier()}{p.RefKind.GetString()}{p.Type.Fullname} {p.Name}"))).Append(')').AppendLine(); sb.Append("\t\t{").AppendLine(); AppendMockDelegateInvokeBody(sb, delegateMethod, mockRegistryName, memberIds, memberIdPrefix, autoMocking); sb.Append("\t\t}").AppendLine(); diff --git a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.cs b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.cs index 1c8a40f77..cef208cad 100644 --- a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.cs +++ b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.cs @@ -433,10 +433,12 @@ private static void EmitIndexerSetupLookup(StringBuilder sb, string indent, } /// - /// Formats indexer parameters as comma-separated names. + /// Formats indexer parameters as comma-separated arguments, passing a ref readonly key with + /// (CS9192). /// private static string FormatIndexerParametersAsNames(EquatableArray parameters) - => string.Join(", ", parameters.Select(p => p.Name)); + => string.Join(", ", parameters.Select(p + => p.IsRefReadOnlyIndexerKey || p.RefKind == RefKind.RefReadOnlyParameter ? "in " + p.Name : p.Name)); /// /// Formats parameters with type and name (e.g., "int value, ref string name"), preserving any @@ -868,6 +870,19 @@ internal string GetString(bool replaceRefReadonlyWithIn = false) /// internal string GetScopedModifier() => parameter.IsScoped ? "scoped " : ""; + + /// + /// The [UnscopedRef] attribute that a declaration matching the original signature must repeat. + /// + internal string GetUnscopedRefAttribute() + => parameter.IsUnscopedRef ? "[global::System.Diagnostics.CodeAnalysis.UnscopedRef] " : ""; + + /// + /// The attribute and modifiers of an indexer key in a declaration matching the original signature. + /// + internal string GetIndexerKeyModifiers() + => parameter.GetUnscopedRefAttribute() + parameter.GetScopedModifier() + + (parameter.IsRefReadOnlyIndexerKey ? "ref readonly " : parameter.RefKind.GetString()); } extension(string value) diff --git a/Tests/Mockolate.SourceGenerators.Tests/Incrementality/MockClassEqualityTests.cs b/Tests/Mockolate.SourceGenerators.Tests/Incrementality/MockClassEqualityTests.cs index 033fa9d70..d94539233 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Incrementality/MockClassEqualityTests.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Incrementality/MockClassEqualityTests.cs @@ -86,6 +86,36 @@ await That(a.Equals(b)).IsFalse() .Because("the mock repeats the scoped modifier"); } + [Test] + public async Task TwoMockClassesWithMethodsThatDifferInUnscopedRef_ShouldNotBeEqual() + { + (Compilation scopedCompilation, INamedTypeSymbol[] scoped) = ParseSymbols( + "public interface IRef { ref int Get(ref int value); }", "IRef"); + (Compilation unscopedCompilation, INamedTypeSymbol[] unscoped) = ParseSymbols( + "public interface IRef { ref int Get([System.Diagnostics.CodeAnalysis.UnscopedRef] ref int value); }", "IRef"); + + MockClass a = new([scoped[0],], scopedCompilation); + MockClass b = new([unscoped[0],], unscopedCompilation); + + await That(a.Equals(b)).IsFalse() + .Because("the mock repeats the attribute"); + } + + [Test] + public async Task TwoMockClassesWithIndexersThatDifferInTheRefKindOfTheirKey_ShouldNotBeEqual() + { + (Compilation inCompilation, INamedTypeSymbol[] inKey) = ParseSymbols( + "public interface IKeyed { int this[in int key] { get; } }", "IKeyed"); + (Compilation refReadOnlyCompilation, INamedTypeSymbol[] refReadOnlyKey) = ParseSymbols( + "public interface IKeyed { int this[ref readonly int key] { get; } }", "IKeyed"); + + MockClass a = new([inKey[0],], inCompilation); + MockClass b = new([refReadOnlyKey[0],], refReadOnlyCompilation); + + await That(a.Equals(b)).IsFalse() + .Because("both keys are set up alike, but the mock repeats the declared modifier"); + } + [Test] public async Task TwoMockClassesWithDifferentConstructorsWithoutArguments_ShouldNotBeEqual() { diff --git a/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/IndexerKeyRefKindTests.cs b/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/IndexerKeyRefKindTests.cs new file mode 100644 index 000000000..50d413011 --- /dev/null +++ b/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/IndexerKeyRefKindTests.cs @@ -0,0 +1,111 @@ +using Microsoft.CodeAnalysis; + +namespace Mockolate.SourceGenerators.Tests.SpecialCases; + +public sealed partial class IndexerKeyRefKindTests +{ + [Test] + [Arguments("int this[in int key] { get; }", "this[in int key]")] + [Arguments("int this[in int key] { get; set; }", "this[in int key]")] + [Arguments("int this[ref readonly int key] { get; }", "this[ref readonly int key]")] + [Arguments("int this[scoped in int key] { get; }", "this[scoped in int key]")] + [Arguments("int this[int index, ref readonly string key] { set; }", "this[int index, ref readonly string key]")] + [Arguments("int this[ref readonly Packet key] { get; }", "this[ref readonly global::MyCode.Packet key]")] + [Arguments("int this[scoped ref readonly Packet key] { get; set; }", + "this[scoped ref readonly global::MyCode.Packet key]")] + public async Task WithInterface_ShouldRepeatTheModifiers(string indexer, string expected) + { + GeneratorResult result = Generator.Run([$$""" + #nullable enable + using System; + using Mockolate; + + namespace MyCode; + + public class Program + { + public static void Main(string[] args) + { + _ = IFoo.CreateMock(); + } + } + + public ref struct Packet { public int Id; } + + public interface IFoo + { + {{indexer}} + } + """,], DocumentationMode.Parse, ["NET9_0_OR_GREATER",]); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources).ContainsKey("Mock.IFoo.g.cs").WhoseValue + .Contains(expected); + } + + [Test] + [Arguments("public virtual int this[in int key] => key;", "override int this[in int key]")] + [Arguments("public virtual int this[ref readonly int key] { get => key; set { } }", + "override int this[ref readonly int key]")] + [Arguments("public abstract int this[in int key, ref readonly long other] { get; }", + "override int this[in int key, ref readonly long other]")] + public async Task WithClass_ShouldRepeatTheModifiers(string indexer, string expected) + { + GeneratorResult result = Generator.Run($$""" + #nullable enable + using System; + using Mockolate; + + namespace MyCode; + + public class Program + { + public static void Main(string[] args) + { + _ = MyBase.CreateMock(); + } + } + + public abstract class MyBase + { + {{indexer}} + } + """); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources).ContainsKey("Mock.MyBase.g.cs").WhoseValue + .Contains(expected); + } + + [Test] + public async Task WithRefReadOnlyKey_ShouldSetUpAndVerifyTheKeyLikeAnInKey() + { + GeneratorResult result = Generator.Run(""" + #nullable enable + using System; + using Mockolate; + + namespace MyCode; + + public class Program + { + public static void Main(string[] args) + { + _ = IFoo.CreateMock(); + } + } + + public interface IFoo + { + int this[ref readonly int key] { get; set; } + } + """); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources).ContainsKey("Mock.IFoo.g.cs").WhoseValue + .Contains("[global::Mockolate.Parameters.IParameter? ").And + .Contains("this[int key]").And + .Contains("wraps[in key]").And + .DoesNotContain("IRefParameter"); + } +} diff --git a/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/RefStructSpanReturnTests.cs b/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/RefStructSpanReturnTests.cs new file mode 100644 index 000000000..5a4f7570f --- /dev/null +++ b/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/RefStructSpanReturnTests.cs @@ -0,0 +1,80 @@ +using Microsoft.CodeAnalysis; + +namespace Mockolate.SourceGenerators.Tests.SpecialCases; + +public sealed partial class RefStructSpanReturnTests +{ + [Test] + [Arguments("Span Get(Packet packet);", "RefStructReturnMethodSetup, global::MyCode.Packet>")] + [Arguments("ReadOnlySpan Get(Packet packet);", + "RefStructReturnMethodSetup, global::MyCode.Packet>")] + [Arguments("Span Get(scoped Packet packet);", "RefStructReturnMethodSetup, global::MyCode.Packet>")] + [Arguments("ReadOnlySpan Get(Packet packet, Span span, int count);", + "RefStructReturnMethodSetup, global::MyCode.Packet, global::System.Span, int>")] + [Arguments("Span Get(Packet p1, Packet p2, Packet p3, Packet p4, Packet p5);", + "RefStructReturnMethodSetup, global::MyCode.Packet, global::MyCode.Packet, global::MyCode.Packet, global::MyCode.Packet, global::MyCode.Packet>")] + [Arguments("Span this[Packet key] { get; }", "RefStructIndexerGetterSetup, global::MyCode.Packet>")] + [Arguments("ReadOnlySpan this[Packet key] { set; }", + "RefStructIndexerSetterSetup, global::MyCode.Packet>")] + [Arguments("Span this[Packet key] { get; set; }", "RefStructIndexerSetup, global::MyCode.Packet>")] + public async Task WithInterface_ShouldWrapTheSpan(string member, string expected) + { + GeneratorResult result = Generator.Run([$$""" + #nullable enable + using System; + using Mockolate; + + namespace MyCode; + + public class Program + { + public static void Main(string[] args) + { + _ = IFoo.CreateMock(); + } + } + + public ref struct Packet { public int Id; } + + public interface IFoo + { + {{member}} + } + """,], DocumentationMode.Parse, ["NET9_0_OR_GREATER",]); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources).ContainsKey("Mock.IFoo.g.cs").WhoseValue + .Contains(expected); + } + + [Test] + public async Task WithClass_ShouldWrapTheSpan() + { + GeneratorResult result = Generator.Run([""" + #nullable enable + using System; + using Mockolate; + + namespace MyCode; + + public class Program + { + public static void Main(string[] args) + { + _ = MyBase.CreateMock(); + } + } + + public ref struct Packet { public int Id; } + + public abstract class MyBase + { + public virtual Span Get(Packet packet) => default; + } + """,], DocumentationMode.Parse, ["NET9_0_OR_GREATER",]); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources).ContainsKey("Mock.MyBase.g.cs").WhoseValue + .Contains("RefStructReturnMethodSetup, global::MyCode.Packet>"); + } +} diff --git a/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/ScopedParameterTests.cs b/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/ScopedParameterTests.cs index 0fa672c37..292e1ac2e 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/ScopedParameterTests.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/ScopedParameterTests.cs @@ -235,8 +235,10 @@ public interface IParser [Test] [Arguments("void Produce(out Span span);", "void Produce(out global::System.Span span)")] - [Arguments("ref int Get([UnscopedRef] out int value);", "ref int Get(out int value)")] - [Arguments("ref int Get([UnscopedRef] ref int value);", "ref int Get(ref int value)")] + [Arguments("ref int Get([UnscopedRef] out int value);", + "ref int Get([global::System.Diagnostics.CodeAnalysis.UnscopedRef] out int value)")] + [Arguments("ref int Get([UnscopedRef] ref int value);", + "ref int Get([global::System.Diagnostics.CodeAnalysis.UnscopedRef] ref int value)")] public async Task WithImplicitlyScopedOrUnscopedParameter_ShouldNotAddTheScopedModifier(string method, string expected) { GeneratorResult result = Run($$""" diff --git a/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/UnscopedRefParameterTests.cs b/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/UnscopedRefParameterTests.cs new file mode 100644 index 000000000..b57285b0b --- /dev/null +++ b/Tests/Mockolate.SourceGenerators.Tests/SpecialCases/UnscopedRefParameterTests.cs @@ -0,0 +1,99 @@ +namespace Mockolate.SourceGenerators.Tests.SpecialCases; + +public sealed partial class UnscopedRefParameterTests +{ + private const string Attribute = "[global::System.Diagnostics.CodeAnalysis.UnscopedRef] "; + + [Test] + [Arguments("Span Get([UnscopedRef] ref int value);", $"Span Get({Attribute}ref int value)")] + [Arguments("ReadOnlySpan Get([UnscopedRef] in int value);", $"ReadOnlySpan Get({Attribute}in int value)")] + [Arguments("ref int Get([UnscopedRef] ref int value);", $"ref int Get({Attribute}ref int value)")] + [Arguments("ref int Get([UnscopedRef] out int value);", $"ref int Get({Attribute}out int value)")] + [Arguments("Span Get(int index, [UnscopedRef] ref int value);", + $"Span Get(int index, {Attribute}ref int value)")] + public async Task WithInterfaceMethod_ShouldRepeatTheAttribute(string method, string expected) + { + GeneratorResult result = Generator.Run($$""" + #nullable enable + using System; + using System.Diagnostics.CodeAnalysis; + using Mockolate; + + namespace MyCode; + + public class Program + { + public static void Main(string[] args) + { + _ = IFoo.CreateMock(); + } + } + + public interface IFoo + { + {{method}} + } + """); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources).ContainsKey("Mock.IFoo.g.cs").WhoseValue + .Contains(expected); + } + + [Test] + public async Task WithClassMethod_ShouldRepeatTheAttribute() + { + GeneratorResult result = Generator.Run(""" + #nullable enable + using System; + using System.Diagnostics.CodeAnalysis; + using Mockolate; + + namespace MyCode; + + public class Program + { + public static void Main(string[] args) + { + _ = MyBase.CreateMock(); + } + } + + public abstract class MyBase + { + public virtual Span Get([UnscopedRef] ref int value) => new(ref value); + } + """); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources).ContainsKey("Mock.MyBase.g.cs").WhoseValue + .Contains($"override global::System.Span Get({Attribute}ref int value)"); + } + + [Test] + public async Task WithDelegate_ShouldRepeatTheAttribute() + { + GeneratorResult result = Generator.Run(""" + #nullable enable + using System; + using System.Diagnostics.CodeAnalysis; + using Mockolate; + + namespace MyCode; + + public class Program + { + public static void Main(string[] args) + { + _ = Reader.CreateMock(); + } + } + + public delegate Span Reader([UnscopedRef] ref int value); + """); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources).ContainsKey("Mock.Reader.g.cs").WhoseValue + .Contains($"Invoke({Attribute}ref int value)"); + } +} diff --git a/Tests/Mockolate.Tests/GeneratorCoverage/IndexerKeyRefKinds.cs b/Tests/Mockolate.Tests/GeneratorCoverage/IndexerKeyRefKinds.cs new file mode 100644 index 000000000..1288d4fe1 --- /dev/null +++ b/Tests/Mockolate.Tests/GeneratorCoverage/IndexerKeyRefKinds.cs @@ -0,0 +1,23 @@ +namespace Mockolate.Tests.GeneratorCoverage; + +/// +/// Indexers with and ref readonly keys. The mock has to repeat the modifiers, or it +/// does not implement or override them (CS0535, CS0115); a ref readonly key is set up like an +/// key. +/// +public interface IIndexerKeyRefKinds +{ + int this[in int key] { get; set; } + string this[ref readonly int key, in string name] { get; } + long this[scoped in long key] { get; } +#if NET10_0_OR_GREATER + int this[ref readonly Packet key] { get; } +#endif +} + +/// +public abstract class IndexerKeyRefKindsBase +{ + public virtual int this[in int key] => key; + public abstract string this[ref readonly int key, in string name] { get; set; } +} diff --git a/Tests/Mockolate.Tests/GeneratorCoverage/RefStructSpanReturns.cs b/Tests/Mockolate.Tests/GeneratorCoverage/RefStructSpanReturns.cs new file mode 100644 index 000000000..7b0a1a360 --- /dev/null +++ b/Tests/Mockolate.Tests/GeneratorCoverage/RefStructSpanReturns.cs @@ -0,0 +1,22 @@ +#if NET10_0_OR_GREATER +using System; + +namespace Mockolate.Tests.GeneratorCoverage; + +/// +/// Members with a ref struct parameter that return a span by value. The ref-struct pipeline has to wrap the span +/// like every other span return, because a span cannot be a type argument of its setup (CS9244). +/// +public interface IRefStructSpanReturns +{ + Span Get(Packet packet); + ReadOnlySpan Peek(scoped Packet packet, int count); + Span this[Packet key] { get; set; } +} + +/// +public abstract class RefStructSpanReturnsBase +{ + public virtual Span Get(Packet packet) => new([packet.Id,]); +} +#endif diff --git a/Tests/Mockolate.Tests/GeneratorCoverage/UnscopedRefParameters.cs b/Tests/Mockolate.Tests/GeneratorCoverage/UnscopedRefParameters.cs new file mode 100644 index 000000000..c7cd643a8 --- /dev/null +++ b/Tests/Mockolate.Tests/GeneratorCoverage/UnscopedRefParameters.cs @@ -0,0 +1,25 @@ +#if NET8_0_OR_GREATER +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Mockolate.Tests.GeneratorCoverage; + +/// +/// Members with [UnscopedRef] parameters. The mock has to repeat the attribute, or the result of the wrapped +/// or base member, which may refer to the parameter, cannot leave the mock (CS9077, CS8347). +/// +public interface IUnscopedRefParameters +{ + Span Get([UnscopedRef] ref int value); + ref int Select([UnscopedRef] ref int value); +} + +/// +public abstract class UnscopedRefParametersBase +{ + public virtual Span Get([UnscopedRef] ref int value) => new(ref value); +} + +/// +public delegate Span UnscopedRefDelegate([UnscopedRef] ref int value); +#endif diff --git a/Tests/Mockolate.Tests/GeneratorShapes/IndexerKeyRefKindTests.cs b/Tests/Mockolate.Tests/GeneratorShapes/IndexerKeyRefKindTests.cs new file mode 100644 index 000000000..4ec93a8c0 --- /dev/null +++ b/Tests/Mockolate.Tests/GeneratorShapes/IndexerKeyRefKindTests.cs @@ -0,0 +1,85 @@ +using Mockolate.Tests.GeneratorCoverage; + +namespace Mockolate.Tests.GeneratorShapes; + +public sealed partial class IndexerKeyRefKindTests +{ + [Test] + public async Task WithInKey_ShouldSetUpAndVerify() + { + IIndexerKeyRefKinds sut = IIndexerKeyRefKinds.CreateMock(); + sut.Mock.Setup[2].Returns(5); + int key = 2; + + int result = sut[in key]; + sut[key] = 7; + + await That(result).IsEqualTo(5); + await That(sut.Mock.Verify[2].Got()).Once(); + await That(sut.Mock.Verify[It.IsAny()].Set(7)).Once(); + } + + [Test] + public async Task WithRefReadOnlyKey_ShouldSetUpAndVerifyLikeAnInKey() + { + IIndexerKeyRefKinds sut = IIndexerKeyRefKinds.CreateMock(); + sut.Mock.Setup[It.Is(1), "a"].Returns("one"); + int key = 1; + + string result = sut[in key, "a"]; + + await That(result).IsEqualTo("one"); + await That(sut.Mock.Verify[1, It.IsAny()].Got()).Once(); + } + + [Test] + public async Task WithScopedInKey_ShouldSetUpAndVerify() + { + IIndexerKeyRefKinds sut = IIndexerKeyRefKinds.CreateMock(); + sut.Mock.Setup[It.Satisfies(key => key > 3)].Returns(9L); + + long result = sut[4L]; + + await That(result).IsEqualTo(9L); + await That(sut.Mock.Verify[4L].Got()).Once(); + } + + [Test] + public async Task OverriddenIndexer_WithInKey_WhenNotSetUp_ShouldCallTheBaseClass() + { + IndexerKeyRefKindsBase sut = IndexerKeyRefKindsBase.CreateMock(); + int key = 3; + + int result = sut[in key]; + + await That(result).IsEqualTo(3); + } + + [Test] + public async Task AbstractIndexer_WithRefReadOnlyKey_ShouldSetUpAndVerify() + { + IndexerKeyRefKindsBase sut = IndexerKeyRefKindsBase.CreateMock(); + sut.Mock.Setup[1, It.IsAny()].Returns("mocked"); + int key = 1; + + string result = sut[in key, "b"]; + sut[in key, "c"] = "value"; + + await That(result).IsEqualTo("mocked"); + await That(sut.Mock.Verify[1, "c"].Set("value")).Once(); + } + +#if NET10_0_OR_GREATER + [Test] + public async Task WithRefReadOnlyRefStructKey_ShouldSetUp() + { + IIndexerKeyRefKinds sut = IIndexerKeyRefKinds.CreateMock(); + sut.Mock.Setup[It.IsRefStruct(packet => packet.Id == 6)].Returns(12); + Packet key = new(6); + + int result = sut[in key]; + + await That(result).IsEqualTo(12); + } +#endif +} diff --git a/Tests/Mockolate.Tests/GeneratorShapes/RefStructSpanReturnTests.cs b/Tests/Mockolate.Tests/GeneratorShapes/RefStructSpanReturnTests.cs new file mode 100644 index 000000000..e4e55d197 --- /dev/null +++ b/Tests/Mockolate.Tests/GeneratorShapes/RefStructSpanReturnTests.cs @@ -0,0 +1,64 @@ +#if NET10_0_OR_GREATER +using Mockolate.Tests.GeneratorCoverage; + +namespace Mockolate.Tests.GeneratorShapes; + +public sealed partial class RefStructSpanReturnTests +{ + [Test] + public async Task Method_ShouldReturnTheSetUpSpan() + { + IRefStructSpanReturns sut = IRefStructSpanReturns.CreateMock(); + sut.Mock.Setup.Get(It.IsRefStruct(packet => packet.Id == 1)).Returns(new Span([1, 2,])); + + int[] matching = sut.Get(new Packet(1)).ToArray(); + int[] other = sut.Get(new Packet(2)).ToArray(); + + await That(matching).IsEqualTo([1, 2,]); + await That(other).IsEmpty(); + } + + [Test] + public async Task Method_WithScopedParameter_ShouldReturnTheSetUpReadOnlySpan() + { + IRefStructSpanReturns sut = IRefStructSpanReturns.CreateMock(); + sut.Mock.Setup.Peek(It.IsAnyRefStruct(), It.Is(2)).Returns(new ReadOnlySpan(['a', 'b',])); + + string result = sut.Peek(new Packet(1), 2).ToString(); + + await That(result).IsEqualTo("ab"); + } + + [Test] + public async Task Method_WhenNotSetUp_ShouldReturnAnEmptySpan() + { + IRefStructSpanReturns sut = IRefStructSpanReturns.CreateMock(); + + int length = sut.Get(new Packet(1)).Length; + + await That(length).IsEqualTo(0); + } + + [Test] + public async Task Indexer_ShouldReturnTheSetUpSpan() + { + IRefStructSpanReturns sut = IRefStructSpanReturns.CreateMock(); + sut.Mock.Setup[It.IsAnyRefStruct()].Returns(new Span([3,])); + + int[] result = sut[new Packet(1)].ToArray(); + + await That(result).IsEqualTo([3,]); + } + + [Test] + public async Task OverriddenMethod_ShouldReturnTheSetUpSpan() + { + RefStructSpanReturnsBase sut = RefStructSpanReturnsBase.CreateMock(); + sut.Mock.Setup.Get(It.IsAnyRefStruct()).Returns(new Span([4,])); + + int[] result = sut.Get(new Packet(1)).ToArray(); + + await That(result).IsEqualTo([4,]); + } +} +#endif diff --git a/Tests/Mockolate.Tests/GeneratorShapes/UnscopedRefParameterTests.cs b/Tests/Mockolate.Tests/GeneratorShapes/UnscopedRefParameterTests.cs new file mode 100644 index 000000000..66963204f --- /dev/null +++ b/Tests/Mockolate.Tests/GeneratorShapes/UnscopedRefParameterTests.cs @@ -0,0 +1,80 @@ +#if NET8_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; +using Mockolate.Tests.GeneratorCoverage; + +namespace Mockolate.Tests.GeneratorShapes; + +public sealed partial class UnscopedRefParameterTests +{ + [Test] + public async Task Method_ShouldSetUpAndVerify() + { + IUnscopedRefParameters sut = IUnscopedRefParameters.CreateMock(); + sut.Mock.Setup.Get(It.IsRef(value => value + 1)).Returns(new Span([7,])); + int value = 1; + + int[] result = sut.Get(ref value).ToArray(); + + await That(result).IsEqualTo([7,]); + await That(value).IsEqualTo(2); + await That(sut.Mock.Verify.Get(It.IsRef())).Once(); + } + + [Test] + public async Task Method_WhenWrapping_ShouldReturnTheSpanOfTheWrappedInstance() + { + IUnscopedRefParameters sut = IUnscopedRefParameters.CreateMock().Wrapping(new UnscopedRefParameters()); + int value = 3; + + Span result = sut.Get(ref value); + result[0] = 4; + + await That(value).IsEqualTo(4).Because("the span of the wrapped instance refers to the argument"); + } + + [Test] + public async Task RefReturningMethod_ShouldSetUpAndVerify() + { + IUnscopedRefParameters sut = IUnscopedRefParameters.CreateMock(); + sut.Mock.Setup.Select(It.IsAnyRef()).Returns(5); + int value = 1; + + int result = sut.Select(ref value); + + await That(result).IsEqualTo(5); + await That(sut.Mock.Verify.Select(It.IsRef())).Once(); + } + + [Test] + public async Task OverriddenMethod_WithoutSetup_ShouldCallTheBaseClass() + { + UnscopedRefParametersBase sut = UnscopedRefParametersBase.CreateMock(); + int value = 6; + + Span result = sut.Get(ref value); + result[0] = 8; + + await That(value).IsEqualTo(8).Because("the span of the base class refers to the argument"); + } + + [Test] + public async Task Delegate_ShouldSetUpAndVerify() + { + UnscopedRefDelegate sut = UnscopedRefDelegate.CreateMock(); + sut.Mock.Setup(It.IsAnyRef()).Returns(new Span([9,])); + int value = 1; + + int[] result = sut(ref value).ToArray(); + + await That(result).IsEqualTo([9,]); + await That(sut.Mock.Verify(It.IsRef())).Once(); + } + + private sealed class UnscopedRefParameters : IUnscopedRefParameters + { + public Span Get([UnscopedRef] ref int value) => new(ref value); + + public ref int Select([UnscopedRef] ref int value) => ref value; + } +} +#endif