From 03c811d3b10857c40358d0143a5e43b2a7b42245 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 13 Nov 2026 22:12:06 +0000 Subject: [PATCH 1/3] Add the polytype-middleware agent skill Copy the Nerdbank.MessagePack skill for authors of PolyType middleware libraries and regenerate the skills index. Co-authored-by: Andrew Arnott --- docs/README.skills.md | 1 + skills/polytype-middleware/SKILL.md | 275 ++++++++++++++++++++++++++++ 2 files changed, 276 insertions(+) create mode 100644 skills/polytype-middleware/SKILL.md diff --git a/docs/README.skills.md b/docs/README.skills.md index a8c7e16126..b00a33dfed 100644 --- a/docs/README.skills.md +++ b/docs/README.skills.md @@ -342,6 +342,7 @@ See [CONTRIBUTING.md](../CONTRIBUTING.md#adding-skills) for guidelines on how to | [playwright-explore-website](../skills/playwright-explore-website/SKILL.md)
`gh skills install github/awesome-copilot playwright-explore-website` | Website exploration for testing using Playwright MCP | None | | [playwright-generate-test](../skills/playwright-generate-test/SKILL.md)
`gh skills install github/awesome-copilot playwright-generate-test` | Generate a Playwright test based on a scenario using Playwright MCP | None | | [poka-yoke](../skills/poka-yoke/SKILL.md)
`gh skills install github/awesome-copilot poka-yoke` | Mistake-proof code so misuse cannot be expressed, rather than warning against it. Use when designing an interface, schema, or state machine and the user wants it hard to get wrong ("make invalid states unrepresentable", "so callers cannot screw it up", "type-safe API", "pit of success"); when auditing existing code for footguns ("what could bite us here", "what is easy to misuse", "poka-yoke this repo", "review this diff for ways to get it wrong"); or when a bug has recurred and the fix must close the class rather than the case ("make sure this never happens again", "this is the third time"). Especially for money, auth, permissions, deletion, migrations, and pipelines where failure is silent. Classifies every finding by what happens when the mistake occurs and how the device notices, which is what keeps it from collapsing into generic code review. | `references/hazard-catalog.md`
`references/lang-python.md`
`references/lang-rust-go.md`
`references/lang-typescript.md`
`scripts/detect_hazards.py` | +| [polytype-middleware](../skills/polytype-middleware/SKILL.md)
`gh skills install github/awesome-copilot polytype-middleware` | Design or review public APIs for a PolyType middleware library (serializer, comparer, schema exporter, or similar) that must stay complete on net472 and netstandard2.0 while modern .NET callers use where T : IShapeable with no witness. Use when adding generic methods, witness/TProvider overloads, extension members, or a #if NET / #if !NET split. Reference implementation: Nerdbank.MessagePack. | None | | [ponder](../skills/ponder/SKILL.md)
`gh skills install github/awesome-copilot ponder` | Convergent deliberation loop - repeated grading passes over one subject until the answer stops changing, with coverage enforced so no unit is silently skipped. Use when the user says "ponder " ("ponder the UI", "ponder our error handling"), "think this over properly", "keep thinking until it converges", "keep looping until it converges", "loop on this until it stops changing", "go through all the screens and grade them", "audit/rate/grade every X", or asks for any broad sweep-and-grade across many units where a single pass would miss things. Also use to resume or recover a ponder already in flight - "where were we", "carry on pondering", a lost thread mid-loop, or a .ponder/ directory in the project - where the move is to run ponder status rather than start over. | `references/harness-notes.md`
`references/perspectives.md`
`references/protocol.md` | | [postgresql-code-review](../skills/postgresql-code-review/SKILL.md)
`gh skills install github/awesome-copilot postgresql-code-review` | PostgreSQL-specific code review assistant focusing on PostgreSQL best practices, anti-patterns, and unique quality standards. Covers JSONB operations, array usage, custom types, schema design, function optimization, and PostgreSQL-exclusive security features like Row Level Security (RLS). | None | | [postgresql-optimization](../skills/postgresql-optimization/SKILL.md)
`gh skills install github/awesome-copilot postgresql-optimization` | PostgreSQL-specific development assistant focusing on unique PostgreSQL features, advanced data types, and PostgreSQL-exclusive capabilities. Covers JSONB operations, array types, custom types, range/geometric types, full-text search, window functions, and PostgreSQL extensions ecosystem. | None | diff --git a/skills/polytype-middleware/SKILL.md b/skills/polytype-middleware/SKILL.md new file mode 100644 index 0000000000..335c30ae40 --- /dev/null +++ b/skills/polytype-middleware/SKILL.md @@ -0,0 +1,275 @@ +--- +name: polytype-middleware +description: "Design or review public APIs for a PolyType middleware library (serializer, comparer, schema exporter, or similar) that must stay complete on net472 and netstandard2.0 while modern .NET callers use where T : IShapeable with no witness. Use when adding generic methods, witness/TProvider overloads, extension members, or a #if NET / #if !NET split. Reference implementation: Nerdbank.MessagePack." +--- + +# PolyType middleware APIs + +A PolyType middleware library sits on `PolyType.IShapeable` and ships one package to every target framework its consumers use. Modern .NET callers get a constrained, witness-free API. Downlevel callers (net472, netstandard2.0, Unity on .NET Standard) still get a complete API, usually with a witness type parameter. + +Nerdbank.MessagePack is the reference. Copy the shape below. Do not invent a second public surface. + +Repository: https://github.com/AArnott/Nerdbank.MessagePack + +The library targets `net10.0`, `net472`, and `netstandard2.0` (`src/Nerdbank.MessagePack/Nerdbank.MessagePack.csproj`). `IShapeable` constraints are part of the `net10.0` assembly only. `net472` and `netstandard2.0` each ship the downlevel surface. Applications that still run on .NET 8 or .NET 9 use those .NET Standard APIs (`docfx/docs/getting-started.md`). + +## What the caller should be able to write + +Self-describing type (`[GenerateShape]` on `T`, so `T : IShapeable`): + +```csharp +serializer.Serialize(value); +byte[] bytes = serializer.Serialize(value); +Person? person = serializer.Deserialize(bytes); +``` + +Type the consumer does not own, or a top-level array (`[GenerateShapeFor]` on a witness): + +```csharp +serializer.Serialize(value); +ExternalType? value = serializer.Deserialize(bytes); +``` + +Explicit shape, every target framework, no source generator required: + +```csharp +serializer.Serialize(ref writer, value, shape, cancellationToken); +``` + +The first two call shapes compile on every TFM. On modern .NET they bind to members declared on the type. On downlevel they bind to extension members, so the file needs `using Nerdbank.MessagePack;` (`docfx/docs/unity.md`). + +## Why the members are split + +`IShapeable.GetTypeShape()` is a static abstract interface member. `where T : IShapeable` compiles only in the modern assembly. That constraint is the witness-free API: the caller names `T`, and `T` supplies its own shape. + +A generic constraint is not part of the method signature. Two methods in the same declaration space cannot differ only by `where T : IShapeable`. + +The library therefore keeps two declarations with the same parameters: + +1. An instance member (or a static member declared on the type) compiled only under `#if NET`, with the constraint, forwarding to `T.GetTypeShape()` or `TProvider.GetTypeShape()`. +2. An extension member compiled for every TFM, with no `IShapeable` constraint, forwarding to `TypeShapeResolver.ResolveDynamicOrThrow()` or `ResolveDynamicOrThrow()`. + +Overload resolution prefers an applicable instance member over an extension. When `T : IShapeable`, the constrained member wins. When the constraint is not met, the extension is still a candidate. Serialize and deserialize leave that candidate callable. `GetJsonSchema`, `GetConverter`, and structural equality mark it `Obsolete(error: true)` under `#if NET`, so a modern call that misses the constraint fails at compile time. + +The extension stays in the modern assembly. The modern public surface is the downlevel surface plus the constrained members. Wrapping the extension in `#if !NET` would delete that surface from the modern build. + +The constrained path is the fast, AOT-friendly one: the shape is a static call. The extension looks the shape up dynamically and throws `NotSupportedException` at runtime when the source generator did not emit it. See the remarks on `MessagePackSerializer` and `MessagePackSerializerExtensions`. + +## Preprocessor convention + +Use `#if NET` for members and attributes that exist only on modern .NET. Use `#if !NET` for implementations that exist only on downlevel TFMs (polyfills, missing runtime APIs). + +The SDK defines `NET` for .NET 5+ target frameworks. In this library that is the `net10.0` output. `net472` and `netstandard2.0` are `!NET`. + +Do not select this split with `NET8_0_OR_GREATER`, `NET8_0`, or any other leftover .NET 8 symbol. This library has no .NET 8 target. + +`#if !NET` is for downlevel-only code, such as the ref-field fallback in `src/Nerdbank.MessagePack/MessagePackAsyncWriter.cs`. It is not a way to hide the public extension API from modern .NET. + +## The three layers + +Keep all three. Friendly overloads only obtain a shape and forward. + +### 1. Shape-taking implementation, every TFM + +The real work takes `ITypeShape` or `ITypeShapeProvider`. No `#if`. + +```csharp +public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShape shape, CancellationToken cancellationToken = default) +``` + +`src/Nerdbank.MessagePack/MessagePackSerializer.cs` (`Serialize`, `Deserialize`, and the async and path overloads). Schema and converter equivalents take the same inputs in `MessagePackSerializer.GetSchema.cs`, `SerializationContext.cs`, and `ConverterContext.cs`. + +### 2. Constrained members on the type, `#if NET` only + +Two generic shapes, both on the type, both one line of forwarding: + +- `where T : IShapeable` calls `T.GetTypeShape()`. This is the no-witness API for `[GenerateShape]`. +- `where TProvider : IShapeable` calls `TProvider.GetTypeShape()`. This is the witness API for `[GenerateShapeFor]`. `T` itself is not constrained. + +Abbreviated from `src/Nerdbank.MessagePack/MessagePackSerializer.AutomatedFriendlyOverloads.cs` (the whole partial is inside `#if NET`): + +```csharp +public void Serialize(ref MessagePackWriter writer, in T? value, CancellationToken cancellationToken = default) + where T : IShapeable + => this.Serialize(ref writer, value, T.GetTypeShape(), cancellationToken); + +public void Serialize(ref MessagePackWriter writer, in T? value, CancellationToken cancellationToken = default) + where TProvider : IShapeable + => this.Serialize(ref writer, value, TProvider.GetTypeShape(), cancellationToken); +``` + +The same pair is hand-written for: + +- `GetJsonSchema` and `GetJsonSchema` in `src/Nerdbank.MessagePack/MessagePackSerializer.GetSchema.cs` +- `SerializationContext.GetConverter` and `GetConverter` in `src/Nerdbank.MessagePack/SerializationContext.cs` +- `ConverterContext.GetConverter` and `GetConverter` in `src/Nerdbank.MessagePack/ConverterContext.cs` +- `StructuralEqualityComparer.GetDefault` and `GetDefault` (and the hash-collision-resistant pair) in `src/Nerdbank.MessagePack/StructuralEqualityComparer.cs` +- `DerivedShapeMapping.Add` and `Add` in `src/Nerdbank.MessagePack/DerivedShapeMapping`1.cs` + +`Add` also keeps the base-type constraint the shape-taking method already had: `where TDerived : TBase, IShapeable`. + +### 3. Unconstrained extension, every TFM including NET + +Same parameters. No `IShapeable` constraint. Dynamic resolve. Null-check the receiver. + +Abbreviated from the extension half of `MessagePackSerializer.AutomatedFriendlyOverloads.cs`: + +```csharp +#if NET +[PreferDotNetAlternativeApi(MessagePackSerializer.PreferTypeConstrainedInstanceOverloads)] +[EditorBrowsable(EditorBrowsableState.Never)] +#endif +public static void Serialize(this MessagePackSerializer self, ref MessagePackWriter writer, in T? value, CancellationToken cancellationToken = default) + => Requires.NotNull(self).Serialize(ref writer, value, ResolveTypeShapeOrThrow(self.ConverterCache), cancellationToken); + +#if NET +[PreferDotNetAlternativeApi(MessagePackSerializer.PreferTypeConstrainedInstanceOverloads)] +[EditorBrowsable(EditorBrowsableState.Never)] +#endif +public static void Serialize(this MessagePackSerializer self, ref MessagePackWriter writer, in T? value, CancellationToken cancellationToken = default) + => Requires.NotNull(self).Serialize(ref writer, value, ResolveTypeShapeOrThrow(self.ConverterCache), cancellationToken); +``` + +`ResolveTypeShapeOrThrow` and `ResolveTypeShapeOrThrow` live in `src/Nerdbank.MessagePack/MessagePackSerializerExtensions.cs`. They call `TypeShapeResolver.ResolveDynamicOrThrow` (or the serializer cache's equivalent) and add array-specific witness guidance to the `NotSupportedException`. + +The witness extension takes `TProvider` as a type argument only. It does not say `where TProvider : IShapeable`. That constraint is the modern member's job. + +Both halves of the serializer overloads are emitted by one T4 template, `src/Nerdbank.MessagePack/MessagePackSerializer.AutomatedFriendlyOverloads.tt`. `WriteClass(targetNET: true)` writes the constrained instance members. `WriteClass(targetNET: false)` writes the extensions. The template chooses the constraint, the shape expression, and the `#if NET` attributes from that flag. Edit the template when adding a transport, then regenerate the `.cs`. Do not hand-edit one half. + +Document on the main type that downlevel callers must import the namespace. `MessagePackSerializer` says so in its remarks. + +## Attributes, and where they go + +Apply these attributes only inside `#if NET`, on the downlevel member. The downlevel compilation of that same method stays an ordinary public API: visible, not obsolete, not hidden. + +| Attribute | Role | +| --- | --- | +| `[EditorBrowsable(EditorBrowsableState.Never)]` | Hides the dynamic member from modern completion. Does not remove it from metadata or from overload resolution. | +| `[PreferDotNetAlternativeApi(message)]` | Internal marker. Analyzer NBMsgPack051 (`src/Nerdbank.MessagePack.Analyzers/DotNetApiUsageAnalyzer.cs`) warns when the marked member is actually invoked. The attribute type is `src/Nerdbank.MessagePack/PreferDotNetAlternativeApiAttribute.cs`. The serializer message is `MessagePackSerializer.PreferTypeConstrainedInstanceOverloads`: "Use a non-extension method that constrains the generic T : IShapeable." | +| `[Obsolete("...", error: true)]` | Turns a modern binding to the dynamic member into a compile error. | + +Which combination this library uses: + +| Dynamic member | Attributes under `#if NET` | +| --- | --- | +| Serialize and deserialize extensions in `MessagePackSerializer.AutomatedFriendlyOverloads.cs` | `EditorBrowsable.Never`, `PreferDotNetAlternativeApi` | +| `DerivedShapeMapping.AddSourceGenerated` | `EditorBrowsable.Never`, `PreferDotNetAlternativeApi` | +| `GetJsonSchema` and `GetConverter` extensions in `MessagePackSerializerExtensions.cs` | `EditorBrowsable.Never`, `PreferDotNetAlternativeApi`, `Obsolete(..., error: true)` | +| `StructuralEqualityComparer` extension members | `EditorBrowsable.Never`, `Obsolete(..., error: true)` | + +Leave `Obsolete` off serialize and deserialize. An unconstrained `T` must still compile against the modern assembly and fail at runtime if no shape was generated. The analyzer warns (NBMsgPack051) so multi-targeting projects can suppress it instead of sprinkling `#if`. See `docfx/analyzers/NBMsgPack051.md`. + +Put `Obsolete(..., error: true)` on members where a modern call that misses the constraint should not compile (`GetJsonSchema`, `GetConverter`, structural equality). The extension remains in the assembly. Call sites that satisfy `where T : IShapeable` bind to the member on the type and never see the obsolete extension. + +`EditorBrowsable.Never` on the modern build is what makes completion offer `Serialize` and `Serialize` on the type. It must not be applied when compiling `net472` or `netstandard2.0`, or downlevel completion loses the only API those TFMs have. + +## When both overloads are instance methods + +Use a different name for the dynamic member when it cannot be an extension. `DerivedShapeMapping.Add` is already an instance method on every TFM (the overloads that take `ITypeShape` or `ITypeShapeProvider`). A second `Add(alias)` that differs only by `where TDerived : IShapeable` is illegal. + +The library's split, from `DerivedShapeMapping`1.cs`: + +```csharp +#if NET +public void Add(DerivedTypeIdentifier alias) + where TDerived : TBase, IShapeable + => this.Add(alias, TDerived.GetTypeShape()); + +public void Add(DerivedTypeIdentifier alias) + where TDerived : TBase + where TProvider : IShapeable + => this.Add(alias, TProvider.GetTypeShape()); +#endif + +#if NET +[PreferDotNetAlternativeApi(UseDotNetAlternativeMessage)] +[EditorBrowsable(EditorBrowsableState.Never)] +#endif +public void AddSourceGenerated(DerivedTypeIdentifier alias) + where TDerived : TBase + => this.Add(alias, TypeShapeResolver.ResolveDynamicOrThrow()); +``` + +`AddSourceGenerated` is the witness twin and is also compiled for every TFM. + +A multi-targeting caller then branches on the name, as in `samples/cs/AnalyzerDocs/NBMsgPack051.cs`: + +```csharp +#if NET +mapping.Add(1); +#else +mapping.AddSourceGenerated(1); +#endif +``` + +Prefer suppressing NBMsgPack051 over repeating that `#if` at every call. The serialize and deserialize extensions do not need a call-site `#if`: the names match, so one call binds to the instance member or the extension depending on the TFM. + +## Static APIs and C# 14 extension members + +Classic extension methods only add instance methods. A static call such as `StructuralEqualityComparer.GetDefault()` needs a C# 14 extension block on downlevel, and a real static method on the type under `#if NET`. + +Constrained static method, from `StructuralEqualityComparer.cs`: + +```csharp +#if NET +public static IEqualityComparer GetDefault() + where T : IShapeable + => (IEqualityComparer)DefaultEqualityComparerCache.GetOrAdd(T.GetTypeShape())!; + +public static IEqualityComparer GetDefault() + where TProvider : IShapeable + => (IEqualityComparer)DefaultEqualityComparerCache.GetOrAdd(TProvider.GetTypeShape())!; +#endif +``` + +Downlevel shape, from `StructuralEqualityComparerExtensions.cs`. The file is wrapped in `#if !DOCFX` because DocFX does not parse extension blocks. Use that guard only when the doc tool has the same limitation. + +```csharp +extension(StructuralEqualityComparer) +{ +#if NET + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Use the StructuralEqualityComparer.GetDefault() method instead. Check that T actually has a [GenerateShape] attribute or otherwise implements IShapeable to avoid a runtime failure.", error: true)] +#endif + public static IEqualityComparer GetDefault() + => (IEqualityComparer)StructuralEqualityComparer.DefaultEqualityComparerCache.GetOrAdd(TypeShapeResolver.ResolveDynamicOrThrow())!; +} +``` + +Consumers need C# 14 (`LangVersion` 14) to call extension members, including when the project targets .NET Framework or .NET Standard. The runtime does not need to be modern. `docfx/docs/getting-started.md` states that. + +## Do + +- Put the implementation on `ITypeShape` and `ITypeShapeProvider` methods that exist on every TFM. Friendly overloads only fetch a shape and forward. +- Under `#if NET`, add `where T : IShapeable` and `where TProvider : IShapeable` as members of the type. Call `T.GetTypeShape()` or `TProvider.GetTypeShape()`. +- Keep an unconstrained extension (or a differently named instance method) on every TFM, including the modern one. Resolve with `TypeShapeResolver.ResolveDynamicOrThrow()` or `ResolveDynamicOrThrow()`. +- Keep the parameter list of the dynamic member identical to the constrained member. The declaration site and the constraint are what differ. +- Put `EditorBrowsable.Never`, `PreferDotNetAlternativeApi`, and `Obsolete` only inside `#if NET`. +- Offer both generic shapes whenever the operation can run on a type the caller owns and on a type they do not own. Top-level arrays need a witness even when the element type has `[GenerateShape]` (`docfx/docs/type-shapes.md`). +- State in the type remarks that downlevel projects need the namespace import to see the extensions. +- Generate repeated overload pairs from one template so the constrained half and the extension half cannot drift. +- If a warning is preferable to a hard error, ship an analyzer that reads an attribute on the dynamic member, and document a suppression for multi-targeting projects. This repo's diagnostic is NBMsgPack051. + +## Do not + +- Do not remove the dynamic member from the modern assembly, and do not wrap it in `#if !NET`. Constrained overloads are additive. +- Do not declare the constrained overload as a second extension with the same parameters. That is a duplicate signature. The member on the type is what overload resolution prefers. +- Do not put `where T : IShapeable` or `where TProvider : IShapeable` on the downlevel member. Those constraints do not compile for net472 or netstandard2.0, and they remove the dynamic fallback. +- Do not make the common case pass `ITypeShape` or a witness. Witness-free `where T : IShapeable` is the modern API for `[GenerateShape]` types. +- Do not drop the witness overload. External types and top-level arrays still need `TProvider`. +- Do not change the dynamic member's parameters, name, or visibility when adding the constrained member, except for the `Add` / `AddSourceGenerated` case where a second instance method needs a distinct name. +- Do not apply `EditorBrowsable.Never` or `Obsolete` to the downlevel compilation. That is the API those callers have. +- Do not mark serialize or deserialize extensions `Obsolete(error: true)`. That removes the unconstrained fallback the modern assembly still publishes. +- Do not choose the modern API with `NET8_0_OR_GREATER`, `NET8_0`, or any other .NET 8-specific symbol. Use `#if NET` and `#if !NET`. + +## Review checklist + +1. Every friendly operation has an `ITypeShape` (or `ITypeShapeProvider`) implementation on every TFM. +2. `#if NET` adds `where T : IShapeable` on the type, calling `T.GetTypeShape()`, with no witness parameter. +3. `#if NET` adds `where TProvider : IShapeable` on the type, calling `TProvider.GetTypeShape()`. +4. The unconstrained extension, or the distinctly named instance method, is compiled into the modern assembly as well as net472 and netstandard2.0. +5. `EditorBrowsable`, `Obsolete`, and `PreferDotNetAlternativeApi` sit inside `#if NET` on that dynamic member. +6. The preprocessor symbols are `NET` and `!NET`. +7. A netstandard2.0 caller can finish the operation with a witness type argument and a namespace import. +8. A net10.0 caller whose type has `[GenerateShape]` can call the operation with a single type argument. +9. New serializer transports were added in the T4 template, and both generated halves match. From ff824dd660f751791365770887fde4e362842243 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 13 Nov 2026 23:03:37 +0000 Subject: [PATCH 2/3] Generalize the polytype-middleware skill Teach the additive PolyType middleware API once, on ShapeMiddleware.Process, and mention Nerdbank.MessagePack only as further examples. Co-authored-by: Andrew Arnott --- docs/README.skills.md | 2 +- skills/polytype-middleware/SKILL.md | 283 ++++++++-------------------- 2 files changed, 81 insertions(+), 204 deletions(-) diff --git a/docs/README.skills.md b/docs/README.skills.md index b00a33dfed..a2c01346b5 100644 --- a/docs/README.skills.md +++ b/docs/README.skills.md @@ -342,7 +342,7 @@ See [CONTRIBUTING.md](../CONTRIBUTING.md#adding-skills) for guidelines on how to | [playwright-explore-website](../skills/playwright-explore-website/SKILL.md)
`gh skills install github/awesome-copilot playwright-explore-website` | Website exploration for testing using Playwright MCP | None | | [playwright-generate-test](../skills/playwright-generate-test/SKILL.md)
`gh skills install github/awesome-copilot playwright-generate-test` | Generate a Playwright test based on a scenario using Playwright MCP | None | | [poka-yoke](../skills/poka-yoke/SKILL.md)
`gh skills install github/awesome-copilot poka-yoke` | Mistake-proof code so misuse cannot be expressed, rather than warning against it. Use when designing an interface, schema, or state machine and the user wants it hard to get wrong ("make invalid states unrepresentable", "so callers cannot screw it up", "type-safe API", "pit of success"); when auditing existing code for footguns ("what could bite us here", "what is easy to misuse", "poka-yoke this repo", "review this diff for ways to get it wrong"); or when a bug has recurred and the fix must close the class rather than the case ("make sure this never happens again", "this is the third time"). Especially for money, auth, permissions, deletion, migrations, and pipelines where failure is silent. Classifies every finding by what happens when the mistake occurs and how the device notices, which is what keeps it from collapsing into generic code review. | `references/hazard-catalog.md`
`references/lang-python.md`
`references/lang-rust-go.md`
`references/lang-typescript.md`
`scripts/detect_hazards.py` | -| [polytype-middleware](../skills/polytype-middleware/SKILL.md)
`gh skills install github/awesome-copilot polytype-middleware` | Design or review public APIs for a PolyType middleware library (serializer, comparer, schema exporter, or similar) that must stay complete on net472 and netstandard2.0 while modern .NET callers use where T : IShapeable with no witness. Use when adding generic methods, witness/TProvider overloads, extension members, or a #if NET / #if !NET split. Reference implementation: Nerdbank.MessagePack. | None | +| [polytype-middleware](../skills/polytype-middleware/SKILL.md)
`gh skills install github/awesome-copilot polytype-middleware` | Design or review the public API of a PolyType middleware library so it stays complete on net472 and netstandard2.0 while modern .NET callers use where T : IShapeable with no witness. Use when adding generic methods, witness or TProvider overloads, extension members, or a #if NET / #if !NET split. | None | | [ponder](../skills/ponder/SKILL.md)
`gh skills install github/awesome-copilot ponder` | Convergent deliberation loop - repeated grading passes over one subject until the answer stops changing, with coverage enforced so no unit is silently skipped. Use when the user says "ponder " ("ponder the UI", "ponder our error handling"), "think this over properly", "keep thinking until it converges", "keep looping until it converges", "loop on this until it stops changing", "go through all the screens and grade them", "audit/rate/grade every X", or asks for any broad sweep-and-grade across many units where a single pass would miss things. Also use to resume or recover a ponder already in flight - "where were we", "carry on pondering", a lost thread mid-loop, or a .ponder/ directory in the project - where the move is to run ponder status rather than start over. | `references/harness-notes.md`
`references/perspectives.md`
`references/protocol.md` | | [postgresql-code-review](../skills/postgresql-code-review/SKILL.md)
`gh skills install github/awesome-copilot postgresql-code-review` | PostgreSQL-specific code review assistant focusing on PostgreSQL best practices, anti-patterns, and unique quality standards. Covers JSONB operations, array usage, custom types, schema design, function optimization, and PostgreSQL-exclusive security features like Row Level Security (RLS). | None | | [postgresql-optimization](../skills/postgresql-optimization/SKILL.md)
`gh skills install github/awesome-copilot postgresql-optimization` | PostgreSQL-specific development assistant focusing on unique PostgreSQL features, advanced data types, and PostgreSQL-exclusive capabilities. Covers JSONB operations, array types, custom types, range/geometric types, full-text search, window functions, and PostgreSQL extensions ecosystem. | None | diff --git a/skills/polytype-middleware/SKILL.md b/skills/polytype-middleware/SKILL.md index 335c30ae40..bc1cfc9164 100644 --- a/skills/polytype-middleware/SKILL.md +++ b/skills/polytype-middleware/SKILL.md @@ -1,42 +1,13 @@ --- name: polytype-middleware -description: "Design or review public APIs for a PolyType middleware library (serializer, comparer, schema exporter, or similar) that must stay complete on net472 and netstandard2.0 while modern .NET callers use where T : IShapeable with no witness. Use when adding generic methods, witness/TProvider overloads, extension members, or a #if NET / #if !NET split. Reference implementation: Nerdbank.MessagePack." +description: 'Design or review the public API of a PolyType middleware library so it stays complete on net472 and netstandard2.0 while modern .NET callers use where T : IShapeable with no witness. Use when adding generic methods, witness or TProvider overloads, extension members, or a #if NET / #if !NET split.' --- # PolyType middleware APIs -A PolyType middleware library sits on `PolyType.IShapeable` and ships one package to every target framework its consumers use. Modern .NET callers get a constrained, witness-free API. Downlevel callers (net472, netstandard2.0, Unity on .NET Standard) still get a complete API, usually with a witness type parameter. +A PolyType middleware library sits on `PolyType.IShapeable` and ships one package to every target framework its consumers use. Modern .NET callers get a constrained, witness-free API. Downlevel callers (`net472`, `netstandard2.0`) still get a complete API, usually with a witness type parameter. Callers that still run on .NET 8 or .NET 9 use that downlevel surface. -Nerdbank.MessagePack is the reference. Copy the shape below. Do not invent a second public surface. - -Repository: https://github.com/AArnott/Nerdbank.MessagePack - -The library targets `net10.0`, `net472`, and `netstandard2.0` (`src/Nerdbank.MessagePack/Nerdbank.MessagePack.csproj`). `IShapeable` constraints are part of the `net10.0` assembly only. `net472` and `netstandard2.0` each ship the downlevel surface. Applications that still run on .NET 8 or .NET 9 use those .NET Standard APIs (`docfx/docs/getting-started.md`). - -## What the caller should be able to write - -Self-describing type (`[GenerateShape]` on `T`, so `T : IShapeable`): - -```csharp -serializer.Serialize(value); -byte[] bytes = serializer.Serialize(value); -Person? person = serializer.Deserialize(bytes); -``` - -Type the consumer does not own, or a top-level array (`[GenerateShapeFor]` on a witness): - -```csharp -serializer.Serialize(value); -ExternalType? value = serializer.Deserialize(bytes); -``` - -Explicit shape, every target framework, no source generator required: - -```csharp -serializer.Serialize(ref writer, value, shape, cancellationToken); -``` - -The first two call shapes compile on every TFM. On modern .NET they bind to members declared on the type. On downlevel they bind to extension members, so the file needs `using Nerdbank.MessagePack;` (`docfx/docs/unity.md`). +Use the same shape for every friendly operation. The modern assembly is the downlevel surface plus the constrained members. ## Why the members are split @@ -44,232 +15,138 @@ The first two call shapes compile on every TFM. On modern .NET they bind to memb A generic constraint is not part of the method signature. Two methods in the same declaration space cannot differ only by `where T : IShapeable`. -The library therefore keeps two declarations with the same parameters: +Keep two declarations with the same parameters: -1. An instance member (or a static member declared on the type) compiled only under `#if NET`, with the constraint, forwarding to `T.GetTypeShape()` or `TProvider.GetTypeShape()`. +1. A member declared on the type, compiled only under `#if NET`, with the constraint, forwarding to `T.GetTypeShape()` or `TProvider.GetTypeShape()`. 2. An extension member compiled for every TFM, with no `IShapeable` constraint, forwarding to `TypeShapeResolver.ResolveDynamicOrThrow()` or `ResolveDynamicOrThrow()`. -Overload resolution prefers an applicable instance member over an extension. When `T : IShapeable`, the constrained member wins. When the constraint is not met, the extension is still a candidate. Serialize and deserialize leave that candidate callable. `GetJsonSchema`, `GetConverter`, and structural equality mark it `Obsolete(error: true)` under `#if NET`, so a modern call that misses the constraint fails at compile time. - -The extension stays in the modern assembly. The modern public surface is the downlevel surface plus the constrained members. Wrapping the extension in `#if !NET` would delete that surface from the modern build. - -The constrained path is the fast, AOT-friendly one: the shape is a static call. The extension looks the shape up dynamically and throws `NotSupportedException` at runtime when the source generator did not emit it. See the remarks on `MessagePackSerializer` and `MessagePackSerializerExtensions`. - -## Preprocessor convention - -Use `#if NET` for members and attributes that exist only on modern .NET. Use `#if !NET` for implementations that exist only on downlevel TFMs (polyfills, missing runtime APIs). - -The SDK defines `NET` for .NET 5+ target frameworks. In this library that is the `net10.0` output. `net472` and `netstandard2.0` are `!NET`. +Overload resolution prefers an applicable instance member over an extension. When `T : IShapeable`, the constrained member wins. When the constraint is not met, the extension is still a candidate. -Do not select this split with `NET8_0_OR_GREATER`, `NET8_0`, or any other leftover .NET 8 symbol. This library has no .NET 8 target. +The extension stays in the modern assembly. Wrapping it in `#if !NET` removes that surface from the modern build. Constrained overloads are additive. -`#if !NET` is for downlevel-only code, such as the ref-field fallback in `src/Nerdbank.MessagePack/MessagePackAsyncWriter.cs`. It is not a way to hide the public extension API from modern .NET. +The constrained path is the fast, AOT-friendly one: the shape is a static call. The extension looks the shape up dynamically and throws `NotSupportedException` at runtime when the source generator did not emit it. -## The three layers +## Preprocessor -Keep all three. Friendly overloads only obtain a shape and forward. +Use `#if NET` for members and attributes that exist only on modern .NET. Use `#if !NET` for implementations that exist only on downlevel TFMs, such as polyfills and missing runtime APIs. -### 1. Shape-taking implementation, every TFM +The SDK defines `NET` for .NET 5 and later. `net472` and `netstandard2.0` are `!NET`. Select this split with `NET` and `!NET`. Leave `NET8_0_OR_GREATER`, `NET8_0`, and other version-specific symbols unused. -The real work takes `ITypeShape` or `ITypeShapeProvider`. No `#if`. +`#if !NET` is for downlevel-only implementation. It is not a way to hide the public extension from modern .NET. -```csharp -public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShape shape, CancellationToken cancellationToken = default) -``` - -`src/Nerdbank.MessagePack/MessagePackSerializer.cs` (`Serialize`, `Deserialize`, and the async and path overloads). Schema and converter equivalents take the same inputs in `MessagePackSerializer.GetSchema.cs`, `SerializationContext.cs`, and `ConverterContext.cs`. +## The pattern -### 2. Constrained members on the type, `#if NET` only +Friendly overloads only obtain a shape and forward. Real work takes `ITypeShape` or `ITypeShapeProvider` and exists on every TFM, with no `#if`. -Two generic shapes, both on the type, both one line of forwarding: - -- `where T : IShapeable` calls `T.GetTypeShape()`. This is the no-witness API for `[GenerateShape]`. -- `where TProvider : IShapeable` calls `TProvider.GetTypeShape()`. This is the witness API for `[GenerateShapeFor]`. `T` itself is not constrained. - -Abbreviated from `src/Nerdbank.MessagePack/MessagePackSerializer.AutomatedFriendlyOverloads.cs` (the whole partial is inside `#if NET`): +The sample is one method, `ShapeMiddleware.Process`. Copy this split for each operation. `IShapeable`, `ITypeShape`, and `TypeShapeResolver` come from PolyType. `PreferDotNetAlternativeApi` is an attribute the library defines so an analyzer can see the dynamic member. ```csharp -public void Serialize(ref MessagePackWriter writer, in T? value, CancellationToken cancellationToken = default) - where T : IShapeable - => this.Serialize(ref writer, value, T.GetTypeShape(), cancellationToken); - -public void Serialize(ref MessagePackWriter writer, in T? value, CancellationToken cancellationToken = default) - where TProvider : IShapeable - => this.Serialize(ref writer, value, TProvider.GetTypeShape(), cancellationToken); -``` - -The same pair is hand-written for: - -- `GetJsonSchema` and `GetJsonSchema` in `src/Nerdbank.MessagePack/MessagePackSerializer.GetSchema.cs` -- `SerializationContext.GetConverter` and `GetConverter` in `src/Nerdbank.MessagePack/SerializationContext.cs` -- `ConverterContext.GetConverter` and `GetConverter` in `src/Nerdbank.MessagePack/ConverterContext.cs` -- `StructuralEqualityComparer.GetDefault` and `GetDefault` (and the hash-collision-resistant pair) in `src/Nerdbank.MessagePack/StructuralEqualityComparer.cs` -- `DerivedShapeMapping.Add` and `Add` in `src/Nerdbank.MessagePack/DerivedShapeMapping`1.cs` - -`Add` also keeps the base-type constraint the shape-taking method already had: `where TDerived : TBase, IShapeable`. - -### 3. Unconstrained extension, every TFM including NET - -Same parameters. No `IShapeable` constraint. Dynamic resolve. Null-check the receiver. - -Abbreviated from the extension half of `MessagePackSerializer.AutomatedFriendlyOverloads.cs`: +public sealed class ShapeMiddleware +{ + // Real work. Every TFM. + public void Process(T? value, ITypeShape shape) + { + ArgumentNullException.ThrowIfNull(shape); + // use shape + } -```csharp #if NET -[PreferDotNetAlternativeApi(MessagePackSerializer.PreferTypeConstrainedInstanceOverloads)] -[EditorBrowsable(EditorBrowsableState.Never)] -#endif -public static void Serialize(this MessagePackSerializer self, ref MessagePackWriter writer, in T? value, CancellationToken cancellationToken = default) - => Requires.NotNull(self).Serialize(ref writer, value, ResolveTypeShapeOrThrow(self.ConverterCache), cancellationToken); + public void Process(T? value) + where T : IShapeable + => this.Process(value, T.GetTypeShape()); -#if NET -[PreferDotNetAlternativeApi(MessagePackSerializer.PreferTypeConstrainedInstanceOverloads)] -[EditorBrowsable(EditorBrowsableState.Never)] + public void Process(T? value) + where TProvider : IShapeable + => this.Process(value, TProvider.GetTypeShape()); #endif -public static void Serialize(this MessagePackSerializer self, ref MessagePackWriter writer, in T? value, CancellationToken cancellationToken = default) - => Requires.NotNull(self).Serialize(ref writer, value, ResolveTypeShapeOrThrow(self.ConverterCache), cancellationToken); -``` - -`ResolveTypeShapeOrThrow` and `ResolveTypeShapeOrThrow` live in `src/Nerdbank.MessagePack/MessagePackSerializerExtensions.cs`. They call `TypeShapeResolver.ResolveDynamicOrThrow` (or the serializer cache's equivalent) and add array-specific witness guidance to the `NotSupportedException`. - -The witness extension takes `TProvider` as a type argument only. It does not say `where TProvider : IShapeable`. That constraint is the modern member's job. - -Both halves of the serializer overloads are emitted by one T4 template, `src/Nerdbank.MessagePack/MessagePackSerializer.AutomatedFriendlyOverloads.tt`. `WriteClass(targetNET: true)` writes the constrained instance members. `WriteClass(targetNET: false)` writes the extensions. The template chooses the constraint, the shape expression, and the `#if NET` attributes from that flag. Edit the template when adding a transport, then regenerate the `.cs`. Do not hand-edit one half. - -Document on the main type that downlevel callers must import the namespace. `MessagePackSerializer` says so in its remarks. - -## Attributes, and where they go - -Apply these attributes only inside `#if NET`, on the downlevel member. The downlevel compilation of that same method stays an ordinary public API: visible, not obsolete, not hidden. - -| Attribute | Role | -| --- | --- | -| `[EditorBrowsable(EditorBrowsableState.Never)]` | Hides the dynamic member from modern completion. Does not remove it from metadata or from overload resolution. | -| `[PreferDotNetAlternativeApi(message)]` | Internal marker. Analyzer NBMsgPack051 (`src/Nerdbank.MessagePack.Analyzers/DotNetApiUsageAnalyzer.cs`) warns when the marked member is actually invoked. The attribute type is `src/Nerdbank.MessagePack/PreferDotNetAlternativeApiAttribute.cs`. The serializer message is `MessagePackSerializer.PreferTypeConstrainedInstanceOverloads`: "Use a non-extension method that constrains the generic T : IShapeable." | -| `[Obsolete("...", error: true)]` | Turns a modern binding to the dynamic member into a compile error. | - -Which combination this library uses: - -| Dynamic member | Attributes under `#if NET` | -| --- | --- | -| Serialize and deserialize extensions in `MessagePackSerializer.AutomatedFriendlyOverloads.cs` | `EditorBrowsable.Never`, `PreferDotNetAlternativeApi` | -| `DerivedShapeMapping.AddSourceGenerated` | `EditorBrowsable.Never`, `PreferDotNetAlternativeApi` | -| `GetJsonSchema` and `GetConverter` extensions in `MessagePackSerializerExtensions.cs` | `EditorBrowsable.Never`, `PreferDotNetAlternativeApi`, `Obsolete(..., error: true)` | -| `StructuralEqualityComparer` extension members | `EditorBrowsable.Never`, `Obsolete(..., error: true)` | - -Leave `Obsolete` off serialize and deserialize. An unconstrained `T` must still compile against the modern assembly and fail at runtime if no shape was generated. The analyzer warns (NBMsgPack051) so multi-targeting projects can suppress it instead of sprinkling `#if`. See `docfx/analyzers/NBMsgPack051.md`. - -Put `Obsolete(..., error: true)` on members where a modern call that misses the constraint should not compile (`GetJsonSchema`, `GetConverter`, structural equality). The extension remains in the assembly. Call sites that satisfy `where T : IShapeable` bind to the member on the type and never see the obsolete extension. - -`EditorBrowsable.Never` on the modern build is what makes completion offer `Serialize` and `Serialize` on the type. It must not be applied when compiling `net472` or `netstandard2.0`, or downlevel completion loses the only API those TFMs have. - -## When both overloads are instance methods - -Use a different name for the dynamic member when it cannot be an extension. `DerivedShapeMapping.Add` is already an instance method on every TFM (the overloads that take `ITypeShape` or `ITypeShapeProvider`). A second `Add(alias)` that differs only by `where TDerived : IShapeable` is illegal. - -The library's split, from `DerivedShapeMapping`1.cs`: +} -```csharp +extension(ShapeMiddleware self) +{ #if NET -public void Add(DerivedTypeIdentifier alias) - where TDerived : TBase, IShapeable - => this.Add(alias, TDerived.GetTypeShape()); - -public void Add(DerivedTypeIdentifier alias) - where TDerived : TBase - where TProvider : IShapeable - => this.Add(alias, TProvider.GetTypeShape()); + [PreferDotNetAlternativeApi("Use the method that constrains T : IShapeable.")] + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("T must implement IShapeable, or pass a witness type.", error: true)] // omit Obsolete when this fallback must still compile #endif + public void Process(T? value) + { + ArgumentNullException.ThrowIfNull(self); + self.Process(value, TypeShapeResolver.ResolveDynamicOrThrow()); + } #if NET -[PreferDotNetAlternativeApi(UseDotNetAlternativeMessage)] -[EditorBrowsable(EditorBrowsableState.Never)] + [PreferDotNetAlternativeApi("Use the method that constrains T : IShapeable.")] + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("T must implement IShapeable, or pass a witness type.", error: true)] // omit Obsolete when this fallback must still compile #endif -public void AddSourceGenerated(DerivedTypeIdentifier alias) - where TDerived : TBase - => this.Add(alias, TypeShapeResolver.ResolveDynamicOrThrow()); + public void Process(T? value) + { + ArgumentNullException.ThrowIfNull(self); + self.Process(value, TypeShapeResolver.ResolveDynamicOrThrow()); + } +} ``` -`AddSourceGenerated` is the witness twin and is also compiled for every TFM. +`where T : IShapeable` calls `T.GetTypeShape()`. That is the witness-free API for `[GenerateShape]` on `T`. `where TProvider : IShapeable` calls `TProvider.GetTypeShape()`. That is the witness API for `[GenerateShapeFor]`. `T` itself is not constrained on the witness member. The witness extension takes `TProvider` as a type argument only. It does not repeat `where TProvider : IShapeable`. -A multi-targeting caller then branches on the name, as in `samples/cs/AnalyzerDocs/NBMsgPack051.cs`: +A caller whose type has `[GenerateShape]` writes `middleware.Process(value)` on modern .NET. A type the caller does not own, including a top-level array, needs a witness: `middleware.Process(value)`. Passing an `ITypeShape` or `ITypeShapeProvider` explicitly works on every TFM with no source generator: `middleware.Process(value, shape)`. -```csharp -#if NET -mapping.Add(1); -#else -mapping.AddSourceGenerated(1); -#endif -``` +The first two calls compile on every TFM. On modern .NET they bind to the members declared on the type. On downlevel they bind to the extension, so the file needs the namespace import. State that in the remarks on the type. -Prefer suppressing NBMsgPack051 over repeating that `#if` at every call. The serialize and deserialize extensions do not need a call-site `#if`: the names match, so one call binds to the instance member or the extension depending on the TFM. +A static operation uses the same split. Declare the constrained method on the type under `#if NET`. Put the unconstrained member in the extension block, on every TFM. Consumers need C# 14 (`LangVersion` 14) to call extension members, including when the project targets .NET Framework or .NET Standard. The runtime does not need to be modern. Guard the extension block from a documentation tool only when that tool cannot parse it. -## Static APIs and C# 14 extension members +When the dynamic member cannot be an extension because the type already has an instance method with those parameters, give the dynamic member a different name. A second instance method that differs only by the constraint is illegal. Keep the constrained member's name under `#if NET`, and compile the distinctly named dynamic member for every TFM with the same parameters and the same `#if NET` attributes. -Classic extension methods only add instance methods. A static call such as `StructuralEqualityComparer.GetDefault()` needs a C# 14 extension block on downlevel, and a real static method on the type under `#if NET`. +## Attributes -Constrained static method, from `StructuralEqualityComparer.cs`: +Apply `EditorBrowsable`, `PreferDotNetAlternativeApi`, and `Obsolete` only inside `#if NET`, on the dynamic member. The downlevel compilation of that same method stays an ordinary public API: visible, not obsolete, and not hidden. -```csharp -#if NET -public static IEqualityComparer GetDefault() - where T : IShapeable - => (IEqualityComparer)DefaultEqualityComparerCache.GetOrAdd(T.GetTypeShape())!; - -public static IEqualityComparer GetDefault() - where TProvider : IShapeable - => (IEqualityComparer)DefaultEqualityComparerCache.GetOrAdd(TProvider.GetTypeShape())!; -#endif -``` +| Attribute | Role | +| --- | --- | +| `[EditorBrowsable(EditorBrowsableState.Never)]` | Hides the dynamic member from modern completion. It stays in metadata and in overload resolution. | +| `[PreferDotNetAlternativeApi(message)]` | Marker the library defines. An analyzer can warn when a caller actually invokes the marked member, so a multi-targeting project can suppress that warning. | +| `[Obsolete("...", error: true)]` | Turns a modern binding to the dynamic member into a compile error. | -Downlevel shape, from `StructuralEqualityComparerExtensions.cs`. The file is wrapped in `#if !DOCFX` because DocFX does not parse extension blocks. Use that guard only when the doc tool has the same limitation. +Include `Obsolete(..., error: true)` when a modern call that misses the constraint should not compile. Leave it off when an unconstrained `T` must still compile against the modern assembly and fail at runtime if no shape was generated. The extension remains in the assembly either way. A call site that satisfies `where T : IShapeable` binds to the member on the type and never sees the obsolete extension. -```csharp -extension(StructuralEqualityComparer) -{ -#if NET - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Use the StructuralEqualityComparer.GetDefault() method instead. Check that T actually has a [GenerateShape] attribute or otherwise implements IShapeable to avoid a runtime failure.", error: true)] -#endif - public static IEqualityComparer GetDefault() - => (IEqualityComparer)StructuralEqualityComparer.DefaultEqualityComparerCache.GetOrAdd(TypeShapeResolver.ResolveDynamicOrThrow())!; -} -``` +`EditorBrowsable.Never` on the modern build is what makes completion offer the constrained overloads on the type. Applying it while compiling `net472` or `netstandard2.0` hides the only API those TFMs have. -Consumers need C# 14 (`LangVersion` 14) to call extension members, including when the project targets .NET Framework or .NET Standard. The runtime does not need to be modern. `docfx/docs/getting-started.md` states that. +The library may ship an analyzer that reads the marker attribute and steers .NET callers toward the constrained overload. Document the suppression for multi-targeting projects. ## Do -- Put the implementation on `ITypeShape` and `ITypeShapeProvider` methods that exist on every TFM. Friendly overloads only fetch a shape and forward. +- Put the implementation on an `ITypeShape` or `ITypeShapeProvider` method that exists on every TFM. Friendly overloads only fetch a shape and forward. - Under `#if NET`, add `where T : IShapeable` and `where TProvider : IShapeable` as members of the type. Call `T.GetTypeShape()` or `TProvider.GetTypeShape()`. -- Keep an unconstrained extension (or a differently named instance method) on every TFM, including the modern one. Resolve with `TypeShapeResolver.ResolveDynamicOrThrow()` or `ResolveDynamicOrThrow()`. +- Keep an unconstrained extension, or a differently named instance method, on every TFM, including the modern one. Resolve with `TypeShapeResolver.ResolveDynamicOrThrow()` or `ResolveDynamicOrThrow()`. - Keep the parameter list of the dynamic member identical to the constrained member. The declaration site and the constraint are what differ. - Put `EditorBrowsable.Never`, `PreferDotNetAlternativeApi`, and `Obsolete` only inside `#if NET`. -- Offer both generic shapes whenever the operation can run on a type the caller owns and on a type they do not own. Top-level arrays need a witness even when the element type has `[GenerateShape]` (`docfx/docs/type-shapes.md`). +- Offer both generic shapes when the operation can run on a type the caller owns and on a type they do not own. Top-level arrays need a witness even when the element type has `[GenerateShape]`. - State in the type remarks that downlevel projects need the namespace import to see the extensions. -- Generate repeated overload pairs from one template so the constrained half and the extension half cannot drift. -- If a warning is preferable to a hard error, ship an analyzer that reads an attribute on the dynamic member, and document a suppression for multi-targeting projects. This repo's diagnostic is NBMsgPack051. +- Generate repeated overload pairs from one template so the constrained half and the extension half stay aligned. +- When a warning is preferable to a hard error, ship an analyzer that reads an attribute on the dynamic member, and document a suppression for multi-targeting projects. ## Do not - Do not remove the dynamic member from the modern assembly, and do not wrap it in `#if !NET`. Constrained overloads are additive. - Do not declare the constrained overload as a second extension with the same parameters. That is a duplicate signature. The member on the type is what overload resolution prefers. -- Do not put `where T : IShapeable` or `where TProvider : IShapeable` on the downlevel member. Those constraints do not compile for net472 or netstandard2.0, and they remove the dynamic fallback. +- Do not put `where T : IShapeable` or `where TProvider : IShapeable` on the downlevel member. Those constraints do not compile for `net472` or `netstandard2.0`, and they remove the dynamic fallback. - Do not make the common case pass `ITypeShape` or a witness. Witness-free `where T : IShapeable` is the modern API for `[GenerateShape]` types. - Do not drop the witness overload. External types and top-level arrays still need `TProvider`. -- Do not change the dynamic member's parameters, name, or visibility when adding the constrained member, except for the `Add` / `AddSourceGenerated` case where a second instance method needs a distinct name. +- Do not change the dynamic member's parameters, name, or visibility when adding the constrained member, except when a second instance method needs a distinct name. - Do not apply `EditorBrowsable.Never` or `Obsolete` to the downlevel compilation. That is the API those callers have. -- Do not mark serialize or deserialize extensions `Obsolete(error: true)`. That removes the unconstrained fallback the modern assembly still publishes. -- Do not choose the modern API with `NET8_0_OR_GREATER`, `NET8_0`, or any other .NET 8-specific symbol. Use `#if NET` and `#if !NET`. +- Do not mark the dynamic member `Obsolete(error: true)` when an unconstrained `T` must still compile against the modern assembly. +- Do not choose the modern API with `NET8_0_OR_GREATER`, `NET8_0`, or any other version-specific symbol. Use `#if NET` and `#if !NET`. ## Review checklist -1. Every friendly operation has an `ITypeShape` (or `ITypeShapeProvider`) implementation on every TFM. +1. Every friendly operation has an `ITypeShape` or `ITypeShapeProvider` implementation on every TFM. 2. `#if NET` adds `where T : IShapeable` on the type, calling `T.GetTypeShape()`, with no witness parameter. 3. `#if NET` adds `where TProvider : IShapeable` on the type, calling `TProvider.GetTypeShape()`. -4. The unconstrained extension, or the distinctly named instance method, is compiled into the modern assembly as well as net472 and netstandard2.0. +4. The unconstrained extension, or the distinctly named instance method, is compiled into the modern assembly as well as `net472` and `netstandard2.0`. 5. `EditorBrowsable`, `Obsolete`, and `PreferDotNetAlternativeApi` sit inside `#if NET` on that dynamic member. 6. The preprocessor symbols are `NET` and `!NET`. -7. A netstandard2.0 caller can finish the operation with a witness type argument and a namespace import. -8. A net10.0 caller whose type has `[GenerateShape]` can call the operation with a single type argument. -9. New serializer transports were added in the T4 template, and both generated halves match. +7. A `netstandard2.0` caller can finish the operation with a witness type argument and a namespace import. +8. A modern caller whose type has `[GenerateShape]` can call the operation with a single type argument. +9. Generated overload pairs come from one template, and both halves match. + +For more examples, see [Nerdbank.MessagePack](https://github.com/AArnott/Nerdbank.MessagePack). From fdb099d6efd2266866fecc700139d663c99ff406 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 14 Nov 2026 20:11:05 +0000 Subject: [PATCH 3/3] Make the polytype-middleware sample compile on every TFM Use a downlevel null check, place the extension block in a top-level static class, and give the witness overload its own message. Co-authored-by: Andrew Arnott --- skills/polytype-middleware/SKILL.md | 55 ++++++++++++++++++----------- 1 file changed, 35 insertions(+), 20 deletions(-) diff --git a/skills/polytype-middleware/SKILL.md b/skills/polytype-middleware/SKILL.md index bc1cfc9164..f1cf7ede84 100644 --- a/skills/polytype-middleware/SKILL.md +++ b/skills/polytype-middleware/SKILL.md @@ -38,7 +38,7 @@ The SDK defines `NET` for .NET 5 and later. `net472` and `netstandard2.0` are `! Friendly overloads only obtain a shape and forward. Real work takes `ITypeShape` or `ITypeShapeProvider` and exists on every TFM, with no `#if`. -The sample is one method, `ShapeMiddleware.Process`. Copy this split for each operation. `IShapeable`, `ITypeShape`, and `TypeShapeResolver` come from PolyType. `PreferDotNetAlternativeApi` is an attribute the library defines so an analyzer can see the dynamic member. +The sample is one method, `ShapeMiddleware.Process`. Copy this split for each operation. `IShapeable`, `ITypeShape`, and `TypeShapeResolver` come from PolyType. `PreferDotNetAlternativeApi` is an attribute the library defines so an analyzer can see the dynamic member. Null checks throw `ArgumentNullException` directly. `ArgumentNullException.ThrowIfNull` is not in the `net472` or `netstandard2.0` reference assemblies. The `extension` block sits in a top-level static class. C# rejects that block at namespace scope. ```csharp public sealed class ShapeMiddleware @@ -46,7 +46,11 @@ public sealed class ShapeMiddleware // Real work. Every TFM. public void Process(T? value, ITypeShape shape) { - ArgumentNullException.ThrowIfNull(shape); + if (shape is null) + { + throw new ArgumentNullException(nameof(shape)); + } + // use shape } @@ -61,39 +65,50 @@ public sealed class ShapeMiddleware #endif } -extension(ShapeMiddleware self) +public static class ShapeMiddlewareExtensions { + extension(ShapeMiddleware self) + { #if NET - [PreferDotNetAlternativeApi("Use the method that constrains T : IShapeable.")] - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("T must implement IShapeable, or pass a witness type.", error: true)] // omit Obsolete when this fallback must still compile + [PreferDotNetAlternativeApi("Use the method that constrains T : IShapeable.")] + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("T must implement IShapeable, or pass a witness type.", error: true)] // omit Obsolete when this fallback must still compile #endif - public void Process(T? value) - { - ArgumentNullException.ThrowIfNull(self); - self.Process(value, TypeShapeResolver.ResolveDynamicOrThrow()); - } + public void Process(T? value) + { + if (self is null) + { + throw new ArgumentNullException(nameof(self)); + } + + self.Process(value, TypeShapeResolver.ResolveDynamicOrThrow()); + } #if NET - [PreferDotNetAlternativeApi("Use the method that constrains T : IShapeable.")] - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("T must implement IShapeable, or pass a witness type.", error: true)] // omit Obsolete when this fallback must still compile + [PreferDotNetAlternativeApi("Use the method that constrains TProvider : IShapeable.")] + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("TProvider must implement IShapeable.", error: true)] // omit Obsolete when this fallback must still compile #endif - public void Process(T? value) - { - ArgumentNullException.ThrowIfNull(self); - self.Process(value, TypeShapeResolver.ResolveDynamicOrThrow()); + public void Process(T? value) + { + if (self is null) + { + throw new ArgumentNullException(nameof(self)); + } + + self.Process(value, TypeShapeResolver.ResolveDynamicOrThrow()); + } } } ``` -`where T : IShapeable` calls `T.GetTypeShape()`. That is the witness-free API for `[GenerateShape]` on `T`. `where TProvider : IShapeable` calls `TProvider.GetTypeShape()`. That is the witness API for `[GenerateShapeFor]`. `T` itself is not constrained on the witness member. The witness extension takes `TProvider` as a type argument only. It does not repeat `where TProvider : IShapeable`. +`where T : IShapeable` calls `T.GetTypeShape()`. That is the witness-free API for `[GenerateShape]` on `T`. `where TProvider : IShapeable` calls `TProvider.GetTypeShape()`. That is the witness API for `[GenerateShapeFor]`. `T` itself is not constrained on the witness member. The witness extension takes `TProvider` as a type argument only. It does not repeat `where TProvider : IShapeable`. Its `PreferDotNetAlternativeApi` and `Obsolete` text names `TProvider`, the type that must provide the shape. A caller whose type has `[GenerateShape]` writes `middleware.Process(value)` on modern .NET. A type the caller does not own, including a top-level array, needs a witness: `middleware.Process(value)`. Passing an `ITypeShape` or `ITypeShapeProvider` explicitly works on every TFM with no source generator: `middleware.Process(value, shape)`. The first two calls compile on every TFM. On modern .NET they bind to the members declared on the type. On downlevel they bind to the extension, so the file needs the namespace import. State that in the remarks on the type. -A static operation uses the same split. Declare the constrained method on the type under `#if NET`. Put the unconstrained member in the extension block, on every TFM. Consumers need C# 14 (`LangVersion` 14) to call extension members, including when the project targets .NET Framework or .NET Standard. The runtime does not need to be modern. Guard the extension block from a documentation tool only when that tool cannot parse it. +A static operation uses the same split. Declare the constrained method on the type under `#if NET`. Put the unconstrained member in an `extension` block inside a top-level static class, on every TFM. Consumers need C# 14 (`LangVersion` 14) to call extension members, including when the project targets .NET Framework or .NET Standard. The runtime does not need to be modern. Guard the extension block from a documentation tool only when that tool cannot parse it. When the dynamic member cannot be an extension because the type already has an instance method with those parameters, give the dynamic member a different name. A second instance method that differs only by the constraint is illegal. Keep the constrained member's name under `#if NET`, and compile the distinctly named dynamic member for every TFM with the same parameters and the same `#if NET` attributes.