Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Docs/pages/06-parameter-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,8 @@ In verifications, use `It.IsOut<T>()` and `It.IsRef<T>()` without arguments to m
kitchen.Mock.Verify.TryParse("abc", It.IsOut<int>()).Once();
```

Unlike `ref readonly` method parameters, indexer keys declared `in` or `ref readonly` take a value or a matcher like `It.Is<T>(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]
Expand Down
21 changes: 18 additions & 3 deletions Source/Mockolate.SourceGenerators/Entities/MethodParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

/// <summary>
/// Whether the parameter is passed by reference and marked with a public <c>[UnscopedRef]</c>, which a mock
/// constructor repeats to pass the parameter on to the base constructor.
/// Whether the indexer key is declared <c>ref readonly</c>. <see cref="AsIndexerKey" /> sets up and verifies such
/// a key like an <see langword="in" /> key, while the declaration of the indexer repeats the modifier.
/// </summary>
public bool IsRefReadOnlyIndexerKey { get; private init; }

/// <summary>
/// Whether the parameter is passed by reference and marked with a public <c>[UnscopedRef]</c>, which a
/// declaration matching the original signature repeats.
/// </summary>
public bool IsUnscopedRef { get; }

/// <summary>
/// The parameter as an indexer key: the indexer setups have no slot for a by-reference matcher, so a
/// <c>ref readonly</c> key outside the ref-struct pipeline is set up and verified like an <see langword="in" /> key.
/// </summary>
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;
Expand Down
2 changes: 1 addition & 1 deletion Source/Mockolate.SourceGenerators/Entities/Property.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public Property(IPropertySymbol propertySymbol, List<Property>? alreadyDefinedPr
if (IsIndexer && propertySymbol.Parameters.Length > 0)
{
IndexerParameters = new EquatableArray<MethodParameter>(
propertySymbol.Parameters.Select(MethodParameter.From).ToArray());
propertySymbol.Parameters.Select(parameter => MethodParameter.From(parameter).AsIndexerKey()).ToArray());
}

Attributes = propertySymbol.GetAttributes().ToAttributeArray(sourceAssembly, propertySymbol.ContainingType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
}

Expand Down Expand Up @@ -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 ");
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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\"";
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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/// <inheritdoc />").AppendLine();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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\"";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
19 changes: 17 additions & 2 deletions Source/Mockolate.SourceGenerators/Sources/SourceTemplates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -433,10 +433,12 @@ private static void EmitIndexerSetupLookup(StringBuilder sb, string indent,
}

/// <summary>
/// Formats indexer parameters as comma-separated names.
/// Formats indexer parameters as comma-separated arguments, passing a <c>ref readonly</c> key with
/// <see langword="in" /> (CS9192).
/// </summary>
private static string FormatIndexerParametersAsNames(EquatableArray<MethodParameter> parameters)
=> string.Join(", ", parameters.Select(p => p.Name));
=> string.Join(", ", parameters.Select(p
=> p.IsRefReadOnlyIndexerKey || p.RefKind == RefKind.RefReadOnlyParameter ? "in " + p.Name : p.Name));

/// <summary>
/// Formats parameters with type and name (e.g., "int value, ref string name"), preserving any
Expand Down Expand Up @@ -868,6 +870,19 @@ internal string GetString(bool replaceRefReadonlyWithIn = false)
/// </summary>
internal string GetScopedModifier()
=> parameter.IsScoped ? "scoped " : "";

/// <summary>
/// The <c>[UnscopedRef]</c> attribute that a declaration matching the original signature must repeat.
/// </summary>
internal string GetUnscopedRefAttribute()
=> parameter.IsUnscopedRef ? "[global::System.Diagnostics.CodeAnalysis.UnscopedRef] " : "";

/// <summary>
/// The attribute and modifiers of an indexer key in a declaration matching the original signature.
/// </summary>
internal string GetIndexerKeyModifiers()
=> parameter.GetUnscopedRefAttribute() + parameter.GetScopedModifier() +
(parameter.IsRefReadOnlyIndexerKey ? "ref readonly " : parameter.RefKind.GetString());
}

extension(string value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Loading
Loading