Repository navigation
Description
Background and motivation
While we were working with trimming, we found that we often want to express "code only needed if a type is preserved", but currently we do not have such thing in C#.
For example, in XAML frameworks, we use URLs to locate resources. With source generator, the code of the resource locator which is generated by a source generator may consist with a method with plenty of if statements, for example:
// auto-generated by a source generator
object? LoadResource(string path)
{
if (path == "ms-appx://MyAssembly/My/Fancy/XamlControl1Style") return XamlLoader.Load<XamlControl1Style>();
if (path == "ms-appx://MyAssembly/Another/XamlControl2Style") return XamlLoader.Load<XamlControl2Style>();
return null;
}With this source generator approach, we can achieve trimming compatibility. However, this would result in all types referenced in LoadResource being preserved even they are not being actually used. In this case, we only want XamlControl1Style to be preserved if XamlControl1 is referenced in other pieces of code.
API Proposal
namespace System.Diagnostics.CodeAnalysis;
public class ControlFlow
{
public static bool MakeWeakTypeReference<T>() => true;
}API Usage
object? LoadResource(string path)
{
if (ControlFlow.MakeWeakTypeReference<XamlControl1>())
if (path == "ms-appx://MyAssembly/My/Fancy/XamlControl1Style")
return XamlLoader.Load<XamlControl1Style>();
if (ControlFlow.MakeWeakTypeReference<XamlControl2>())
if (path == "ms-appx://MyAssembly/Another/XamlControl2Style")
return XamlLoader.Load<XamlControl2Style>();
return null;
}It behaves as a no-op which always returns true, but if there are no other type references to XamlControl1, the whole block of the if statement can be safely trimmed, which produces code after trimming like below:
object? LoadResource(string path)
{
if (path == "ms-appx://MyAssembly/Another/XamlControl2Style")
return XamlLoader.Load<XamlControl2Style>();
return null;
}Therefore, all types related to XamlControl1 and XamlControl1Type can also be trimmed away.
This should also support and and or so that we can express multiple types as a single prerequisite:
if (ControlFlow.MakeWeakTypeReference<Foo>() && ControlFlow.MakeWeakTypeReference<Bar>())
{
// only preserved if both Foo and Bar are referenced
}
if (ControlFlow.MakeWeakTypeReference<Foo>() || ControlFlow.MakeWeakTypeReference<Bar>())
{
// only preserved if either Foo or Bar is referenced
}
// Bogus
if (!ControlFlow.MakeWeakTypeReference<Foo>())
{
// no-op, can never reach because `!ControlFlow.MakeWeakTypeReference<Foo>()` is always false, maybe a warning should be emitted by the compiler or illink?
}Alternative Designs
No response
Risks
No response
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNo status
Activity
teo-tsirpanis commentedon Aug 21, 2022
Interesting idea; the name does not sound right to me though.
hez2010 commentedon Aug 21, 2022
Yes. I did think about the name for a while but didn't conclude a fancy name :)
MichalPetryka commentedon Aug 21, 2022
Maybe
IsTypePresent<T>?teo-tsirpanis commentedon Aug 21, 2022
That's better, and with that name it fits more on
Type.eerhardt commentedon Aug 22, 2022
See the following code, which we use in System.Text.Json to do this exact scenario:
runtime/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverterFactoryHelpers.cs
Lines 120 to 125 in e71a958
jkoritzinsky commentedon Aug 22, 2022
@eerhardt that's really clever and I think a good example for where an API like this could be useful. I think being able to have a well-known API that would enable this to work while using generics or strongly-typed
System.Typeobjects instead of having to round-trip through type name parsing would be quite useful and likely more maintainable than the existing mechanism you shared.MichalPetryka commentedon Aug 22, 2022
Additionally, it'd be more AOT safe.
teo-tsirpanis commentedon Aug 22, 2022
5 remaining items
kekekeks commentedon Aug 24, 2022
The problem with XAML styles is that they are completely separate from the control itself. Control does not and should not know anything about its styles, they are essentially user-defined and can be switched to a separate set of styles at runtime during the theme switch.
Just like in WPF, in Avalonia styles are defined in a separate assembly (in case of Avalonia they come in separate nuget packages) and can be replaced for the entire app or a particular control subtree with another set of styles that come from a 3rd party package.
kekekeks commentedon Aug 26, 2022
Another use case:
My COM interop bindings generate COM interfaces as normal .NET interfaces.
e. g.
becomes
Interop is handled by separate generated classes
__MicroComIFooProxy(implements the managed interface and forwards calls to native function pointers) and__MicroComIFooVTable(builds a CCW vtable).Both are registered by the module initializer. I'd like to be able to trim unneeded interop types when the interface isn't used.
jkotas commentedon Aug 26, 2022
CsWinRT solved this problem by linking the interop helper types via custom attributes: microsoft/CsWinRT#1224
kekekeks commentedon Aug 26, 2022
I believe such custom attributes require reflection access. MicroCom aims to work with IlcDisableReflection=True
teo-tsirpanis commentedon Aug 26, 2022
No, the attributes would be accessed at the time of the source generation, not at runtime.
kekekeks commentedon Aug 26, 2022
type.GetCustomAttributelooks like run-time reflection to me: https://github.com/microsoft/CsWinRT/pull/1224/files#diff-2c2d5b5c93b2d4df6db3e983e3ba3126c9de5efa3648d9987c499904a3ea99b2R26-R54This code doesn't seem like it would run with IlcDisableReflection too
jkotas commentedon Aug 27, 2022
Yes, custom attributes are accessed via reflection. The key advantage is that the helper type associations via custom attribute can be statically analyzed for correctness and the solution does not have concerns shared by @vitek-karas and @MichalStrehovsky above.
This is temporary fallback path that should go away eventually.
MichalStrehovsky commentedon Aug 29, 2022
Working with IlcDisableReflection is a noble goal but I don't think the base class libraries will ever be in a position where they work with IlcDisableReflection=true. They likely won't even work in the more usable future version of it: #67193 (comment). Trimmable reflection is not a problem and would be a good solution for this.
IlcDisableReflection is a tech demo that was introduced before we had things like IlcTrimMetadata=true (which is now the default). With metadata trimming, I don't believe you'll see meaningful size differences with/without reflection for apps that are bigger than a console hello world. IlcDisableReflection produces meaningful savings for hello-world-sized apps because it allows removing the whole reflection stack, but that's a fixed ~1MB cost that is not worth it for most. We'll likely do work that will indirectly make this cost smaller over time. The reflection stack in NativeAOT is a bit overengineered.
If you still see a meaningful difference for Avalonia-sized apps, please add
<ItemGroup><IlcArg Include="--make-repro-path:c:\some\path\where\a\zip\can\be\created" /></ItemGroup>to the project and share the resulting ZIP with me (in a new issue) - it's likely a bug - IlcDisableReflection has been useful in finding those in the past.vitek-karas commentedon Aug 31, 2022
I view this as two separate things:
That said, it would be nice to have some agreed upon way especially for libraries to verify that they can be successfully trimmed to a certain degree - and to enable detection or regressions and such. But that's sort of outside the scope of this issue.
dotnet-policy-service commentedon Apr 15, 2026
Tagging subscribers to this area: @agocke, @elinor-fung
See info in area-owners.md if you want to be subscribed.