Skip to content
Merged
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: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Correctness is a must. The other goals are strong defaults and win in this order
- **Arity**: the library hand-writes setup and verification types for up to four parameters; the generator emits the same shapes for more. A change to one arity applies to every arity in both places.
- **Analyzers**: rule IDs are `MockolateNNNN`. Add the descriptor in `Rules.cs`, its texts in `Resources.resx`, the row in `AnalyzerReleases.Unshipped.md` and the user docs in `Docs/pages/10-analyzers.md`.
- **AOT and trimming**: the runtime library sets `IsAotCompatible` and `IsTrimmable` for `net8.0`+ with warnings as errors. Do not add reflection-based dispatch to the library or the generated code.
- **Performance**: recording, setup matching and verification are hot paths with allocation-free fast paths (`FastMockInteractions`, the `Fast*Buffer` types). Measure hot-path changes with the benchmarks before and after.
- **Performance**: recording, setup matching and verification are hot paths with allocation-free fast paths (`FastMockInteractions`, the `*Records` types). Measure hot-path changes with the benchmarks before and after.
- **Public API**: every change to the public surface of `Mockolate` shows up in the API snapshots. Document new public members with XML comments. Mark breaking changes with `!` in the PR title (`feat!:`, `refactor!:`).
- **Strong naming**: all assemblies are signed with `strongname.snk`; an `InternalsVisibleTo` needs `PublicKey="$(PublicKey)"`.
- **Style**: follow `.editorconfig`: tabs, explicit types instead of `var`, no `this.`, `System` usings first; private fields are `_camelCase`. New extension members use C# 14 `extension` blocks. Tests use TUnit with aweXpect (`await That(...)`) and are preferably named `<Subject>_Should<Outcome>`.
Expand Down
4 changes: 2 additions & 2 deletions Docs/agents/conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ The rules the code already follows. Read the parts that match the change and cop

### API shape

- **Arity:** the library contains the setup, verification and buffer types for up to four parameters (`ReturnMethodSetup<TReturn, T1..T4>`, `IndexerSetup<TValue, T1..T4>`, `FastMethod0..4Buffer`, ...), one full copy per arity. The generator emits the same types for more parameters (`MaxExplicitParameters` in `Sources.MockClass.cs`; the higher arities come from `Sources.MethodSetups.cs`, `Sources.IndexerSetups.cs` and `Sources.RefStructMethodSetups.cs`). A change to one arity applies to all of them, in the library and in the generator.
- **Arity:** the library contains the setup, verification and record types for up to four parameters (`ReturnMethodSetup<TReturn, T1..T4>`, `IndexerSetup<TValue, T1..T4>`, `MethodRecords<T1..T4>`, ...), one full copy per arity. The generator emits the same types for more parameters (`MaxExplicitParameters` in `Sources.MockClass.cs`; the higher arities come from `Sources.MethodSetups.cs`, `Sources.IndexerSetups.cs` and `Sources.RefStructMethodSetups.cs`). A change to one arity applies to all of them, in the library and in the generator.
- **Builders:** setups are chains of small interfaces (`IReturnMethodSetup` → `Do`/`Returns`/`Throws` → `InParallel`/`When` → `For`/`Only`). Concrete setups implement them explicitly and return `this`. Terminators and convenience members (`Forever`, `OnlyOnce`, `ReturnsAsync`, the count methods on `VerificationResult<T>`) are C# 14 `extension` blocks; add new extensions as `extension` blocks, not as classic `this` extension methods.
- **Naming:** reuse the existing verbs. Setups use `Returns`, `Throws`, `Do`, `TransitionTo`, `InParallel`, `When`, `For`, `Only`. Behavior toggles are `-ing` methods with a `bool` defaulting to `true` that return a copy of the immutable `MockBehavior` record (`SkippingBaseClass`, `ThrowingWhenNotSetup`). Counts are `Never`, `Once`, `Twice`, `Exactly`, `AtLeast...`, `AtMost...`, `Between`, `Times`.
- **Matchers:** `It` is a non-static `partial class`, so add-ons extend it with `extension(It _)`. Each matcher lives in its own `It.<Name>.cs`, returns an interface (`IParameterWithCallback<T>`, `It.IIsParameter<T>`) and overrides `ToString()` to reproduce its call syntax, which is what failure messages show.
Expand All @@ -24,7 +24,7 @@ The rules the code already follows. Read the parts that match the change and cop

Recording, setup matching and counting must not allocate. Measure changes with the benchmarks.

- Interactions are recorded as typed nodes in one lock-free list per mock (`FastMockInteractions`, `RecordNode`) and boxed into `IInteraction` only on demand. The `Fast*Buffer` types record a call and are views on the calls of one member (`RecordList`).
- Interactions are recorded as typed nodes in one lock-free list per mock (`FastMockInteractions`, `RecordNode`) and boxed into `IInteraction` only on demand. The `*Records` types (`MethodRecords<T1>`, `PropertyGetterRecords`, ...) record a call and are views on the calls of one member (`MemberRecords`).
- No LINQ, closures, iterators or boxing on these paths. Use index-based loops, `static` lambdas and the `TState` overloads (`Callback<T>.Invoke<TState>`). LINQ is fine on cold paths such as failure messages.
- Concurrency: the per-member setup tables are copy-on-write arrays published with `Volatile.Write` and read without a lock; lazy fields are created with `Interlocked.CompareExchange`; new locks use the `MockolateLock` alias. Do not run user code (a callback or a matcher) while holding a lock; snapshot under the lock and invoke afterwards, as `MockSetups.Methods.cs` does.
- The latest matching setup wins: lookups walk the setups backwards, and scenario setups come before the default ones.
Expand Down
2 changes: 1 addition & 1 deletion Docs/agents/project-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ The runtime library (`netstandard2.0`, `net8.0`, `net10.0`, `net11.0`).
| `Monitor/` | `MockMonitor` for interactions within a scope |
| `Web/` | `HttpClient` support: setups, verifications and `It` extensions for requests and content |
| `Exceptions/` | `MockException`, `MockNotSetupException`, `MockVerificationException`, `MockVerificationTimeoutException` |
| `Internals/` | Infrastructure that generated code calls (`MockRegistry`, the per-mock store that generated mocks delegate every member access to; `FastMockInteractions` and the `Fast*Buffer` types, the allocation-sensitive recording path; `Callbacks<T>`, `Matchers`, ...), helpers and polyfills for older frameworks |
| `Internals/` | Infrastructure that generated code calls (`MockRegistry`, the per-mock store that generated mocks delegate every member access to; `FastMockInteractions` and the `*Records` types, the allocation-sensitive recording path; `Callbacks<T>`, `Matchers`, ...), helpers and polyfills for older frameworks |

### `Source/Mockolate.SourceGenerators`

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public void Forever()
sb.Append("{").AppendLine();
foreach (int count in methodSetups.GroupBy(x => x.Item1).Select(x => x.Key))
{
AppendFastMethodBuffer(sb, count);
AppendMethodRecords(sb, count);
}

sb.Append("}").AppendLine();
Expand All @@ -155,7 +155,7 @@ public void Forever()
return sb.ToString();
}

private static void AppendFastMethodBuffer(StringBuilder sb, int count)
private static void AppendMethodRecords(StringBuilder sb, int count)
{
string typeArgs = string.Join(", ", Enumerable.Range(1, count).Select(x => $"T{x}"));
string parameters = string.Join(", ", Enumerable.Range(1, count).Select(x => $"T{x} parameter{x}"));
Expand All @@ -171,7 +171,7 @@ private static void AppendFastMethodBuffer(StringBuilder sb, int count)
#if !DEBUG
sb.Append("\t[global::System.Diagnostics.DebuggerNonUserCode]").AppendLine();
#endif
sb.Append("\tinternal static class FastMethod").Append(count).Append("Buffer<").Append(typeArgs).Append(">")
sb.Append("\tinternal static class MethodRecords<").Append(typeArgs).Append(">")
.AppendLine();
sb.Append("\t{").AppendLine();
sb.Append("\t\tpublic static void Append(global::Mockolate.Internals.FastMockInteractions owner, int memberId, string name, ")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -658,11 +658,11 @@ private static void AppendUnionMethodVerifyDefinition(StringBuilder sb, Class @c
#pragma warning disable S107 // Methods should not have too many parameters
private static void AppendUnionMethodVerifyImplementation(StringBuilder sb, Method method,
string mockRegistryName, string verifyName, MemberIdTable memberIds, string memberIdPrefix,
bool useFastBuffers, UnionSlot[] slots, string? methodNameOverride = null)
bool useTypedRecords, UnionSlot[] slots, string? methodNameOverride = null)
#pragma warning restore S107
{
MethodParameter[] parameters = method.Parameters.AsArray();
bool useFastForMethod = useFastBuffers && IsFastBufferEligibleMethod(method);
bool useFastForMethod = useTypedRecords && IsTypedRecordingEligibleMethod(method);
string methodMemberId = useFastForMethod
? memberIdPrefix + memberIds.GetMethodIdentifier(method)
: "-1";
Expand All @@ -677,7 +677,7 @@ private static void AppendUnionMethodVerifyImplementation(StringBuilder sb, Meth
AppendUnionArgumentLocals(sb, method, slots);

// Mirrors the classic verify paths: literal values go through the allocation-free VerifyMethod overload,
// matchers through the typed overload when the member has a fast buffer, everything else through the
// matchers through the typed overload when the member is recorded typed, everything else through the
// MethodInvocation predicate.
bool noFixedSlots = slots.All(s => s != UnionSlot.Fixed);
bool literalEligible = parameters.Length <= MaxExplicitParameters && noFixedSlots &&
Expand Down Expand Up @@ -974,13 +974,13 @@ private static void AppendUnionIndexerVerifyDefinition(StringBuilder sb, Propert
#pragma warning disable S107 // Methods should not have too many parameters
private static void AppendUnionIndexerVerifyImplementation(StringBuilder sb, Property indexer,
string mockRegistryName, string verifyName, MemberIdTable memberIds, string memberIdPrefix,
bool useFastBuffers, UnionSlot[] slots)
bool useTypedRecords, UnionSlot[] slots)
#pragma warning restore S107
{
MethodParameter[] parameters = indexer.IndexerParameters!.Value.AsArray();
string[] names = UnionIndexerVerifyNames(indexer);
string[] expressionNames = UnionIndexerExpressionNames(indexer, names);
bool useFastForIndexer = useFastBuffers && IsFastBufferEligibleIndexer(indexer);
bool useFastForIndexer = useTypedRecords && IsTypedRecordingEligibleIndexer(indexer);
string indexerGetMemberId = useFastForIndexer
? memberIdPrefix + memberIds.GetIndexerGetIdentifier(indexer)
: "-1";
Expand Down
Loading
Loading