Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
45 changes: 31 additions & 14 deletions src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -444,9 +444,12 @@ private static void GenerateWrapProperty(CodeWriter writer, MockMemberModel prop
? "global::System.Array.Empty<object?>()"
: "new object?[] { value }";

if (prop.IsAbstractMember)
// An init-only property cannot be assigned on the wrapped instance (CS8852 — only
// `this`/`base` are assignable from an init accessor), so it dispatches without the
// pass-through fallback the `set` path has (#6829).
if (prop.IsAbstractMember || prop.IsInitOnly)
{
writer.AppendLine($"{setterPrefix}set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs});");
writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs});");
}
else
{
Expand Down Expand Up @@ -951,7 +954,7 @@ private static void GenerateInterfaceProperty(CodeWriter writer, MockMemberModel
if (prop.HasSetter)
{
writer.AppendLineIfNotEmpty(prop.SetterObsoleteAttribute);
writer.AppendLine($"set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", new object?[] {{ value }});");
writer.AppendLine($"{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", new object?[] {{ value }});");
}
writer.CloseBrace();
return;
Expand Down Expand Up @@ -988,11 +991,11 @@ private static void GenerateInterfaceProperty(CodeWriter writer, MockMemberModel
if (prop.IsRefStructReturn)
{
// ref struct property — can't box value, use empty args
writer.AppendLine($"set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", global::System.Array.Empty<object?>());");
writer.AppendLine($"{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", global::System.Array.Empty<object?>());");
}
else
{
writer.AppendLine($"set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", new object?[] {{ value }});");
writer.AppendLine($"{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", new object?[] {{ value }});");
}
}

Expand Down Expand Up @@ -1082,12 +1085,13 @@ private static void GeneratePartialProperty(CodeWriter writer, MockMemberModel p

if (prop.IsAbstractMember)
{
writer.AppendLine($"{setterPrefix}set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs});");
writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs});");
}
else
{
// Virtual property setter: try engine, fall back to base
writer.AppendLine($"{setterPrefix}set");
// Virtual property setter: try engine, fall back to base (assigning `base` is
// allowed from an init accessor, so init-only needs no special case here)
writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)}");
writer.OpenBrace();
writer.AppendLine($"if (!_engine.TryHandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs}))");
writer.AppendLine("{");
Expand All @@ -1106,7 +1110,12 @@ private static void GenerateInterfaceIndexer(CodeWriter writer, MockMemberModel
{
var paramList = FormatIndexerParameterList(prop);
writer.AppendLineIfNotEmpty(prop.ObsoleteAttribute);
writer.AppendLine($"public {prop.ReturnType} this[{paramList}]");
// An explicit slot dispatches on the same member ids as the implicit indexer, but it has to
// be declared explicitly: the two differ only in accessor kind, so declaring both publicly
// would be a duplicate member (CS0111, #6829).
writer.AppendLine(prop.ExplicitInterfaceName is not null
? $"{prop.ReturnType} {prop.ExplicitInterfaceName}.this[{paramList}]"
: $"public {prop.ReturnType} this[{paramList}]");
writer.OpenBrace();

if (prop.HasGetter)
Expand All @@ -1120,7 +1129,7 @@ private static void GenerateInterfaceIndexer(CodeWriter writer, MockMemberModel
{
var setterArgs = GetIndexerSetterArgsArray(prop);
writer.AppendLineIfNotEmpty(prop.SetterObsoleteAttribute);
writer.AppendLine($"set => _engine.HandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs});");
writer.AppendLine($"{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs});");
}

writer.CloseBrace();
Expand Down Expand Up @@ -1167,13 +1176,15 @@ private static void GenerateOverrideIndexer(CodeWriter writer, MockMemberModel p
{
var setterArgs = GetIndexerSetterArgsArray(prop);
writer.AppendLineIfNotEmpty(prop.SetterObsoleteAttribute);
if (prop.IsAbstractMember)
// `base[...]` stays assignable from an init accessor, but the wrapped instance does not
// (CS8852), so an init-only wrap indexer dispatches without the fallback (#6829).
if (prop.IsAbstractMember || (prop.IsInitOnly && fallbackTarget != "base"))
{
writer.AppendLine($"{setterPrefix}set => _engine.HandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs});");
writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs});");
}
else
{
writer.AppendLine($"{setterPrefix}set");
writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)}");
writer.OpenBrace();
writer.AppendLine($"if (!_engine.TryHandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs}))");
writer.OpenBrace();
Expand All @@ -1192,14 +1203,20 @@ private static string FormatIndexerParameterList(MockMemberModel indexer)
private static string AccessorPrefix(string accessModifier)
=> accessModifier.Length == 0 ? "" : accessModifier + " ";

/// <summary>
/// The keyword the setter must be emitted with. An <c>init</c> slot has to be implemented by an
/// <c>init</c> accessor — a <c>set</c> accessor fails with CS8854/CS8855 (#6829).
/// </summary>
private static string SetterKeyword(MockMemberModel prop) => prop.IsInitOnly ? "init" : "set";

private static string GetIndexerGetterArgsArray(MockMemberModel indexer)
{
if (indexer.Parameters.Length == 0) return "global::System.Array.Empty<object?>()";
var args = string.Join(", ", indexer.Parameters.Select(p => p.Name));
return $"new object?[] {{ {args} }}";
}

private static string GetIndexerSetterArgsArray(MockMemberModel indexer)
internal static string GetIndexerSetterArgsArray(MockMemberModel indexer)
{
if (indexer.Parameters.Length == 0) return "new object?[] { value }";
var args = string.Join(", ", indexer.Parameters.Select(p => p.Name)) + ", value";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,13 @@ public static string Build(MockTypeModel model)
// Indexers -- expose as Item(...)/SetItem(..., value) extension methods so
// setups and verifications can target distinct index values independently.
// Each indexer overload (different parameter signature) gets its own pair.
// Explicit implementations are skipped for the same reason as explicit properties:
// they are forwarding shims sharing the implicit member's ids, so generating their
// own Item/SetItem would duplicate an existing overload (CS0111, #6829).
var indexers = model.Properties
.Where(p => p.IsIndexer
&& p.IsSignatureAccessibleFromAssembly
&& p.ExplicitInterfaceName is null
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
&& !p.IsStaticAbstract
&& !p.IsRefStructReturn
&& !p.IsReturnTypeStaticAbstractInterface)
Expand Down
56 changes: 46 additions & 10 deletions src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,16 +134,16 @@ private static void GeneratePropertyForwarding(CodeWriter writer, MockMemberMode
var interfaceName = GetForwardingInterfaceName(prop, model);
// The primary forward emits the declaring slot's OWN accessors, not the merged set, so an
// asymmetric `new`-hidden slot doesn't gain an accessor it never declared (CS0550, #6263).
EmitPropertyForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName), prop.OwnHasGetter, prop.OwnHasSetter);
EmitPropertyForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName, model), prop.OwnHasGetter, prop.OwnHasSetter, prop.IsInitOnly);

foreach (var extra in prop.AdditionalExplicitSlots)
{
writer.AppendLine();
EmitPropertyForward(writer, prop, extra.InterfaceName, CastTarget(extra.InterfaceName), extra.HasGetter, extra.HasSetter);
EmitPropertyForward(writer, prop, extra.InterfaceName, CastTarget(extra.InterfaceName), extra.HasGetter, extra.HasSetter, extra.IsInitOnly);
}
}

private static void EmitPropertyForward(CodeWriter writer, MockMemberModel prop, string interfaceName, string target, bool hasGetter, bool hasSetter)
private static void EmitPropertyForward(CodeWriter writer, MockMemberModel prop, string interfaceName, string target, bool hasGetter, bool hasSetter, bool isInitOnly)
{
var returnType = prop.ReturnType;

Expand All @@ -153,24 +153,31 @@ private static void EmitPropertyForward(CodeWriter writer, MockMemberModel prop,
var getterAttr = GetAccessorObsoletePrefix(prop.GetterObsoleteAttribute);
var setterAttr = GetAccessorObsoletePrefix(prop.SetterObsoleteAttribute);
var getter = hasGetter ? $"{getterAttr}get => {target}.{EscapeIdentifier(prop.Name)}; " : "";
var setter = hasSetter ? $"{setterAttr}set => {target}.{EscapeIdentifier(prop.Name)} = value; " : "";
var setter = hasSetter
? isInitOnly
// An init-only slot can't be forwarded by assignment (CS8852 — only `this`/`base`
// are assignable from an init accessor), so it dispatches straight to the engine,
// exactly as the mock implementation's own init accessor does (#6829).
? $"{setterAttr}init => {EngineDispatch(prop)}; "
: $"{setterAttr}set => {target}.{EscapeIdentifier(prop.Name)} = value; "
: "";

writer.AppendLine($"{returnType} {interfaceName}.{EscapeIdentifier(prop.Name)} {{ {getter}{setter}}}");
}

private static void GenerateIndexerForwarding(CodeWriter writer, MockMemberModel prop, MockTypeModel model)
{
var interfaceName = GetForwardingInterfaceName(prop, model);
EmitIndexerForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName), prop.OwnHasGetter, prop.OwnHasSetter);
EmitIndexerForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName, model), prop.OwnHasGetter, prop.OwnHasSetter, prop.IsInitOnly);

foreach (var extra in prop.AdditionalExplicitSlots)
{
writer.AppendLine();
EmitIndexerForward(writer, prop, extra.InterfaceName, CastTarget(extra.InterfaceName), extra.HasGetter, extra.HasSetter);
EmitIndexerForward(writer, prop, extra.InterfaceName, CastTarget(extra.InterfaceName), extra.HasGetter, extra.HasSetter, extra.IsInitOnly);
}
}

private static void EmitIndexerForward(CodeWriter writer, MockMemberModel prop, string interfaceName, string target, bool hasGetter, bool hasSetter)
private static void EmitIndexerForward(CodeWriter writer, MockMemberModel prop, string interfaceName, string target, bool hasGetter, bool hasSetter, bool isInitOnly)
{
var returnType = prop.ReturnType;
var paramList = MockImplBuilder.GetParameterList(prop);
Expand All @@ -181,11 +188,25 @@ private static void EmitIndexerForward(CodeWriter writer, MockMemberModel prop,
var getterAttr = GetAccessorObsoletePrefix(prop.GetterObsoleteAttribute);
var setterAttr = GetAccessorObsoletePrefix(prop.SetterObsoleteAttribute);
var getter = hasGetter ? $"{getterAttr}get => {target}[{argPassList}]; " : "";
var setter = hasSetter ? $"{setterAttr}set => {target}[{argPassList}] = value; " : "";
var setter = hasSetter
? isInitOnly
// See EmitPropertyForward: an init-only slot can't be forwarded by assignment (#6829).
? $"{setterAttr}init => {EngineDispatch(prop, "set_Item", MockImplBuilder.GetIndexerSetterArgsArray(prop))}; "
: $"{setterAttr}set => {target}[{argPassList}] = value; "
: "";

writer.AppendLine($"{returnType} {interfaceName}.this[{paramList}] {{ {getter}{setter}}}");
}

/// <summary>
/// Dispatches a setter through the wrapper's own engine, for slots the wrapper cannot forward
/// by assignment. Uses the same member id and member name the mock implementation dispatches
/// with, so setups and verifications see one call either way.
/// </summary>
private static string EngineDispatch(MockMemberModel prop, string? memberName = null, string? args = null)
=> $"global::TUnit.Mocks.MockRegistry.GetEngine(this).HandleCall({prop.SetterMemberId}, "
+ $"\"{memberName ?? "set_" + prop.Name}\", {args ?? "new object?[] { value }"})";

// Cast the underlying Object to a specific interface so an explicit forward dispatches to
// that interface's slot (necessary when distinct slots share a signature — e.g. a `new`-hidden
// base member, or wrapping a real object whose explicit impls differ per interface).
Expand All @@ -198,11 +219,26 @@ private static string GetForwardingInterfaceName(MockMemberModel member, MockTyp
// to the slot's interface when the member is an explicit interface impl on the underlying object,
// or when it also satisfies other slots — otherwise `Object.X` may be ambiguous (CS0121) or bind
// to the wrong slot (#6252).
private static string GetPrimaryTarget(MockMemberModel member, string interfaceName)
=> member.ExplicitInterfaceName is not null || member.AdditionalExplicitSlots.Length > 0
private static string GetPrimaryTarget(MockMemberModel member, string interfaceName, MockTypeModel? model = null)
=> member.ExplicitInterfaceName is not null
|| member.AdditionalExplicitSlots.Length > 0
|| (model is not null && HasExplicitSiblingSlot(member, model))
? CastTarget(interfaceName)
: "Object";

/// <summary>
/// Whether another property or indexer of the same shape is implemented explicitly for a
/// different interface — the case where two slots share a signature but cannot share one member
/// (clashing <c>set</c>/<c>init</c> accessor kinds, #6829). <c>Object.X</c> is ambiguous across
/// those two slots, so the implicit member's forward has to name the slot it targets.
/// </summary>
private static bool HasExplicitSiblingSlot(MockMemberModel member, MockTypeModel model)
=> member.ExplicitInterfaceName is null
&& model.Properties.Any(other => other.ExplicitInterfaceName is not null
&& other.IsIndexer == member.IsIndexer
&& other.Name == member.Name
&& other.ReturnType == member.ReturnType);

private static string GetAccessorObsoletePrefix(string obsoleteAttribute)
=> obsoleteAttribute.Length > 0 ? obsoleteAttribute + " " : "";

Expand Down
Loading
Loading