Repository navigation
[API Proposal] Typed factory attributes for type-map activation - #137006
pavelsavara wants to merge 1 commit into
Conversation
Provide a generic contract attribute and a new()-constrained implementation adapter without changing type-map discovery or entry semantics. Adopt the factory in generated JSExport providers and replace opaque-Type activation, its warning suppression and manual constructor roots. Validate general contracts and trimmed activation on CoreCLR and Mono. Select the built Mono runtime and SDK in the JSExport test fixtures so the prototype is exercised instead of the SDK-default daily runtime. Co-authored-by: Copilot <[email protected]>
|
Azure Pipelines: Successfully started running 4 pipeline(s). 11 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
|
Tagging subscribers to this area: @dotnet/interop-contrib |
|
cc @jkoritzinsky , I'm not sure it's worth it ... |
|
Alternatively, can we put I'd like to set this up to be trim-safe without suppressions, but I'm fine with whatever approach gives us that. DynamicDependency is meant for "we cannot represent this in a trim-safe way without breaking API compat". We shouldn't be designing a new API that isn't trim-safe by design. |
That would not work, the parent class |
1. Current PR: explicit preservation +
|
|
I don't like the generalized factory option as the type map explicitly doesn't guarantee any particular trimming preservation. I think a JS-specific factory (that would allow you the flexibility to change the requirements in the future) would be better than a generalized one. I would also like option 5, but yeah there's still a warning you'd need to suppress as the trimmer's analysis can't see that the constructor will be preserved. So either option 2 or option 5 would be my preference (I think option 2 is worth bringing to API review to see what they think as that's the pattern we've specifically guided people to use when doing type-map work). |
|
Ok I looked more into option 5 and it seems that it doesn't quite work the way I thought it did (EventSource, the main user, has other special-casing around it). So option 2 is my preference. |
|
We ran into this in the Npgsql prototype as well. We currently use a zero-sized struct implementing an interface and allocate it with RuntimeHelpers.Box, since structs are always allocatable, precisely for this API. A derived attribute impl referenced on a stub class would be the most conventional way to do it, but that requires two new types per entry. With that in mind, option 5 doesn't really solve the problem for us, or for future users who run into the same issue. |
Purpose and staging
API prototype for discussion; not merge-ready. Explore a generalized, typed factory attribute for activating instances discovered through type maps, rather than adding a JSExport-specific activation attribute.
This draft is stacked on #136924, targeting its
jsexport-typemap-assembly-lazybranch so the diff contains only the factory mechanism and its adoption. The intended landing is a separate staged follow-up after the JSExport work, only if the generalized design passes discussion and API review. The factory APIs below are not included in the existing JSExport API approval.Problem
An external type map returns a
Type, but does not convey a constructor requirement or prescribe activation. JSExport currently usesActivator.CreateInstance(Type), a constructorDynamicDependency, and an IL2067 suppression. This is a general activation gap: discovery and trim-safe construction are separate responsibilities.An optional factory attribute lets the consumer retrieve a factory using its known contract, while the implementation type and
new()constraint are encoded where the implementation is declared.Proposed API
New public types in
System.Runtime.InteropServices, extracted from the built implementation with GenAPI:The concrete factory calls
new TImplementation()for everyCreateInstance()invocation. It does not cache instances. The abstract base enables typed attribute lookup without knowing the implementation type.Prototype: 42f17e4.
General usage
The mapped descriptor need not be the implementation itself. The API does not:
TypeMapAttribute, or alter type-map traversal.new()on existing maps.JSExport adoption as evidence
The generator adds this annotation to its existing provider:
The host retrieves
TypeMapFactoryAttribute<JSExportProvider>from the mapped provider type and invokesCreateInstance(). This removes the opaqueActivator.CreateInstance(Type)call, its IL2067 suppression, and the generated provider-constructorDynamicDependency. Missing factory metadata is an explicit error, not a silent fallback.Lookup to provider instance
The host's activation path is shown below (surrounding partial class omitted).
s_exportProviderscachesTypeMapping.GetOrCreateExternalTypeMapping<JSExportProvider>(); its values are mapped provider types, not provider instances:For the annotated
__GeneratedJSExportProvider, the returned attribute object has concrete typeTypeMapFactoryAttribute<JSExportProvider, __GeneratedJSExportProvider>. It is accessed through the single-argument base type, so the host does not need to name the generated implementation.The concrete attribute supplies this override:
Thus
factory.CreateInstance()constructs a fresh__GeneratedJSExportProviderand returns it asJSExportProvider. Thenew()constraint carries the public-constructor requirement to the trimmer. Discovery can then callGetExportNames()and retain the instance'sBinddelegate; method binding still waits for the first JS invocation.The independent IL2026 suppression on the concrete type-map lookup is also removed: that call is a recognized intrinsic. The new attribute is not presented as a general solution to
RequiresUnreferencedCode.The approved
JSExportProviderpublic API, raw catalog transport, lazy per-method binding, aliases, legacy binary fallback, and runtime lifetime behavior remain unchanged.Discussion / alternatives
No size, startup, or throughput improvement is claimed. Attribute lookup still uses reflection; the benefit under discussion is explicit, analyzable constructor rooting and a reusable activation contract.
The JSExport adoption changes its generated-provider activation handshake: handwritten providers must also carry factory metadata. Existing .NET 10/.NET 11 generated assemblies retain their legacy path. New attribute-using binaries require the new API; this is one reason the change is staged separately.
Adoption scope
DynamicDependency.Other in-tree type-map usages found are map-behavior/trimming tests, not additional production activation consumers. Proxy maps and COM-specific static details/lifetime contracts are intentionally not converted.
Validation also required a narrow test-setup correction: the Mono no-workload fixture previously selected the SDK-default daily runtime despite pinning the targeting pack. These two JSExport tests now opt into the existing current-runtime/current-WebAssembly-SDK override mechanism. This is necessary to test factory APIs that do not exist in the downloaded runtime; it does not change other test lanes.
Validation
Windows browser-wasm, Debug runtimes:
DynamicDependency.git diff --checkpassed.Successful Mono provider tests were checked to resolve 12.0.0-dev, not the SDK-default daily runtime. Temporary diagnostics were removed before final validation. These two fixture scenarios use a bounded 60s startup allowance after intermittent failures at the harness's default 10s under shared-machine load; all behavioral assertions and exit-code checks remain in place.
NativeAOT, mobile, multithreaded configurations and non-Windows execution were not validated. No performance measurements are claimed.
Validation commands and results
Clean CoreCLR baseline and final CoreCLR staging — passed, zero warnings/errors:
Mono build and final clean managed/runtime staging — passed, zero warnings/errors:
Generator — 46 passed:
General factory tests — 5 passed per VM:
Provider and legacy cases — CoreCLR 7 passed; Mono 6 passed. A final Mono provider-only run after the startup allowance change passed both configurations:
Full JS interop — CoreCLR 516 passed / 2 existing skips; Mono 511 passed / 3 existing skips, zero failures:
GenAPI — passed, using a session-local
GenAPITargetPath:Tests inherited
EnableHotReloadInRuntimeConfigDevFile=falsefor an unrelated SDK tooling issue and used a cached matching Chrome/ChromeDriver pair. Repository-managed test SDKs and targeting packs were provisioned; repository SDK pins and the shared SDK installation were not patched.Note
This prototype and description were prepared with GitHub Copilot.