Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing multiple type definition issue and fixing NotifyCollectionChangedAction issue #1816

Merged
merged 4 commits into from
Oct 10, 2024
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

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@
<data name="ClassImplementsOldProjection_Text" xml:space="preserve">
<value>Class '{0}' implements WinRT interface(s) {1} generated using an older version of CsWinRT. Update to a projection generated using CsWinRT 2.1.0 or later for trimming and AOT compatibility.</value>
</data>
<data name="ClassOldProjectionMultipleInstances_Text" xml:space="preserve">
<value>Class '{0}' was generated using an older version of CsWinRT and due to the type being defined in multiple DLLs, CsWinRT can not generate compat code to make it trimming safe. Update to a projection generated using CsWinRT 2.1.0 or later for trimming and AOT compatibility.</value>
</data>
<data name="ClassNotMarkedPartial_Brief" xml:space="preserve">
<value>Class is not marked partial</value>
</data>
Expand Down
5 changes: 5 additions & 0 deletions src/Authoring/WinRT.SourceGenerator/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1122,5 +1122,10 @@ public static string GetTaskAdapterIfAsyncMethod(IMethodSymbol symbol)

return null;
}

public static string TrimGlobalFromTypeName(string typeName)
{
return typeName.StartsWith("global::") ? typeName[8..] : typeName;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
IncrementalValueProvider<bool> isGeneratorForceOptOut = context.AnalyzerConfigOptionsProvider.Select(static (options, token) =>
{
return options.GetCsWinRTRcwFactoryFallbackGeneratorForceOptOut();
});

IncrementalValueProvider<bool> csWinRTAotWarningEnabled = context.AnalyzerConfigOptionsProvider.Select(static (options, token) =>
{
return options.GetCsWinRTAotWarningLevel() >= 1;
});

// Get whether the generator should actually run or not
Expand All @@ -72,28 +77,28 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
.Where(static item => item.Right);

// Get all the names of the projected types to root
IncrementalValuesProvider<EquatableArray<string>> executableTypeNames = enabledExecutableReferences.Select(static (executableReference, token) =>
IncrementalValuesProvider<EquatableArray<RcwReflectionFallbackType>> executableTypeNames = enabledExecutableReferences.Select(static (executableReference, token) =>
{
Compilation compilation = executableReference.Value.GetCompilationUnsafe();

// We only care about resolved assembly symbols (this should always be the case anyway)
if (compilation.GetAssemblyOrModuleSymbol(executableReference.Value.Reference) is not IAssemblySymbol assemblySymbol)
{
return EquatableArray<string>.FromImmutableArray(ImmutableArray<string>.Empty);
return EquatableArray<RcwReflectionFallbackType>.FromImmutableArray(ImmutableArray<RcwReflectionFallbackType>.Empty);
}

// If the assembly is not an old projections assembly, we have nothing to do
if (!GeneratorHelper.IsOldProjectionAssembly(assemblySymbol))
{
return EquatableArray<string>.FromImmutableArray(ImmutableArray<string>.Empty);
return EquatableArray<RcwReflectionFallbackType>.FromImmutableArray(ImmutableArray<RcwReflectionFallbackType>.Empty);
}

token.ThrowIfCancellationRequested();

ITypeSymbol attributeSymbol = compilation.GetTypeByMetadataName("System.Attribute")!;
ITypeSymbol windowsRuntimeTypeAttributeSymbol = compilation.GetTypeByMetadataName("WinRT.WindowsRuntimeTypeAttribute")!;

ImmutableArray<string>.Builder executableTypeNames = ImmutableArray.CreateBuilder<string>();
ImmutableArray<RcwReflectionFallbackType>.Builder executableTypeNames = ImmutableArray.CreateBuilder<RcwReflectionFallbackType>();

// Process all type symbols in the current assembly
foreach (INamedTypeSymbol typeSymbol in VisitNamedTypeSymbolsExceptABI(assemblySymbol))
Expand Down Expand Up @@ -141,25 +146,31 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
continue;
}

executableTypeNames.Add(typeName);
// Check if we are able to resolve the type using GetTypeByMetadataName. If not,
// it indicates there are multiple definitions of this type in the references
// and us emitting a dependency on this type would cause compiler error. So emit
// a warning instead.
bool hasMultipleDefinitions = compilation.GetTypeByMetadataName(GeneratorHelper.TrimGlobalFromTypeName(typeName)) is null;
executableTypeNames.Add(new RcwReflectionFallbackType(typeName, hasMultipleDefinitions));
}

token.ThrowIfCancellationRequested();

return EquatableArray<string>.FromImmutableArray(executableTypeNames.ToImmutable());
return EquatableArray<RcwReflectionFallbackType>.FromImmutableArray(executableTypeNames.ToImmutable());
});

// Combine all names into a single sequence
IncrementalValueProvider<ImmutableArray<string>> projectedTypeNames =
IncrementalValueProvider<(ImmutableArray<RcwReflectionFallbackType>, bool)> projectedTypeNamesAndAotWarningEnabled =
executableTypeNames
.Where(static names => !names.IsEmpty)
.SelectMany(static (executableTypeNames, token) => executableTypeNames.AsImmutableArray())
.Collect();
.Collect()
.Combine(csWinRTAotWarningEnabled);

// Generate the [DynamicDependency] attributes
context.RegisterImplementationSourceOutput(projectedTypeNames, static (context, projectedTypeNames) =>
context.RegisterImplementationSourceOutput(projectedTypeNamesAndAotWarningEnabled, static (SourceProductionContext context, (ImmutableArray<RcwReflectionFallbackType> projectedTypeNames, bool csWinRTAotWarningEnabled) value) =>
{
if (projectedTypeNames.IsEmpty)
if (value.projectedTypeNames.IsEmpty)
{
return;
}
Expand Down Expand Up @@ -187,11 +198,25 @@ internal static class RcwFallbackInitializer
[ModuleInitializer]
""");

foreach (string projectedTypeName in projectedTypeNames)
bool emittedDynamicDependency = false;
foreach (RcwReflectionFallbackType projectedTypeName in value.projectedTypeNames)
{
builder.Append(" [DynamicDependency(DynamicallyAccessedMemberTypes.NonPublicConstructors, typeof(");
builder.Append(projectedTypeName);
builder.AppendLine("))]");
// If there are multiple definitions of the type, emitting a dependency would result in a compiler error.
// So instead, emit a diagnostic for it.
if (projectedTypeName.HasMultipleDefinitions)
{
var diagnosticDescriptor = value.csWinRTAotWarningEnabled ?
WinRTRules.ClassNotAotCompatibleOldProjectionMultipleInstancesWarning : WinRTRules.ClassNotAotCompatibleOldProjectionMultipleInstancesInfo;
// We have no location to emit the diagnostic as this is just a reference we detect.
context.ReportDiagnostic(Diagnostic.Create(diagnosticDescriptor, null, GeneratorHelper.TrimGlobalFromTypeName(projectedTypeName.TypeName)));
}
else
{
emittedDynamicDependency = true;
builder.Append(" [DynamicDependency(DynamicallyAccessedMemberTypes.NonPublicConstructors, typeof(");
builder.Append(projectedTypeName.TypeName);
builder.AppendLine("))]");
}
}

builder.Append("""
Expand All @@ -202,7 +227,10 @@ public static void InitializeRcwFallback()
}
""");

context.AddSource("RcwFallbackInitializer.g.cs", builder.ToString());
if (emittedDynamicDependency)
{
context.AddSource("RcwFallbackInitializer.g.cs", builder.ToString());
}
});
}

Expand Down Expand Up @@ -305,5 +333,7 @@ public bool Equals(EquatablePortableExecutableReference other)

return other.Reference.GetMetadataId() == Reference.GetMetadataId();
}
}
}

internal readonly record struct RcwReflectionFallbackType(string TypeName, bool HasMultipleDefinitions);
}
4 changes: 2 additions & 2 deletions src/Authoring/WinRT.SourceGenerator/TypeMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public TypeMapper(bool useWindowsUIXamlProjections)
{ "System.Collections.IEnumerable", new MappedType("Windows.UI.Xaml.Interop", "IBindableIterable", "Windows.UI.Xaml") },
{ "System.Collections.IList", new MappedType("Windows.UI.Xaml.Interop", "IBindableVector", "Windows.UI.Xaml") },
{ "System.Collections.Specialized.INotifyCollectionChanged", new MappedType("Windows.UI.Xaml.Interop", "INotifyCollectionChanged", "Windows.UI.Xaml") },
{ "System.Collections.Specialized.NotifyCollectionChangedAction", new MappedType("Windows.UI.Xaml.Interop", "NotifyCollectionChangedAction", "Windows.UI.Xaml") },
{ "System.Collections.Specialized.NotifyCollectionChangedAction", new MappedType("Windows.UI.Xaml.Interop", "NotifyCollectionChangedAction", "Windows.UI.Xaml", true, true) },
{ "System.Collections.Specialized.NotifyCollectionChangedEventArgs", new MappedType("Windows.UI.Xaml.Interop", "NotifyCollectionChangedEventArgs", "Windows.UI.Xaml") },
{ "System.Collections.Specialized.NotifyCollectionChangedEventHandler", new MappedType("Windows.UI.Xaml.Interop", "NotifyCollectionChangedEventHandler", "Windows.UI.Xaml") },
{ "WinRT.EventRegistrationToken", new MappedType("Windows.Foundation", "EventRegistrationToken", "Windows.Foundation.FoundationContract", true, true) },
Expand Down Expand Up @@ -92,7 +92,7 @@ public TypeMapper(bool useWindowsUIXamlProjections)
{ "System.Collections.IEnumerable", new MappedType("Microsoft.UI.Xaml.Interop", "IBindableIterable", "Microsoft.UI") },
{ "System.Collections.IList", new MappedType("Microsoft.UI.Xaml.Interop", "IBindableVector", "Microsoft.UI") },
{ "System.Collections.Specialized.INotifyCollectionChanged", new MappedType("Microsoft.UI.Xaml.Interop", "INotifyCollectionChanged", "Microsoft.UI") },
{ "System.Collections.Specialized.NotifyCollectionChangedAction", new MappedType("Microsoft.UI.Xaml.Interop", "NotifyCollectionChangedAction", "Microsoft.UI") },
{ "System.Collections.Specialized.NotifyCollectionChangedAction", new MappedType("Microsoft.UI.Xaml.Interop", "NotifyCollectionChangedAction", "Microsoft.UI", true, true) },
{ "System.Collections.Specialized.NotifyCollectionChangedEventArgs", new MappedType("Microsoft.UI.Xaml.Interop", "NotifyCollectionChangedEventArgs", "Microsoft.UI") },
{ "System.Collections.Specialized.NotifyCollectionChangedEventHandler", new MappedType("Microsoft.UI.Xaml.Interop", "NotifyCollectionChangedEventHandler", "Microsoft.UI") },
{ "WinRT.EventRegistrationToken", new MappedType("Windows.Foundation", "EventRegistrationToken", "Windows.Foundation.FoundationContract", true, true) },
Expand Down
13 changes: 13 additions & 0 deletions src/Authoring/WinRT.SourceGenerator/WinRTRules.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,5 +225,18 @@ private static DiagnosticDescriptor MakeRule(string id, string title, string mes
CsWinRTDiagnosticStrings.BindableCustomPropertyClassNotMarkedPartial_Text,
false,
true);

public static DiagnosticDescriptor ClassNotAotCompatibleOldProjectionMultipleInstancesWarning = MakeRule(
"CsWinRT1029",
CsWinRTDiagnosticStrings.ClassImplementsOldProjection_Brief,
CsWinRTDiagnosticStrings.ClassOldProjectionMultipleInstances_Text,
false,
true);

public static DiagnosticDescriptor ClassNotAotCompatibleOldProjectionMultipleInstancesInfo = MakeRule(
"CsWinRT1029",
CsWinRTDiagnosticStrings.ClassImplementsOldProjection_Brief,
CsWinRTDiagnosticStrings.ClassOldProjectionMultipleInstances_Text,
false);
}
}
4 changes: 4 additions & 0 deletions src/Tests/FunctionalTests/CCW/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Runtime.CompilerServices;
using System.Windows.Input;
using System.Runtime.InteropServices;
using System.Collections.Specialized;

var managedProperties = new ManagedProperties(42);
var instance = new Class();
Expand Down Expand Up @@ -174,6 +175,9 @@
var managedWarningClassList = new List<ManagedWarningClass>();
instance.BindableIterableProperty = managedWarningClassList;

var notifyCollectionChangedActionList = new List<NotifyCollectionChangedAction>();
instance.BindableIterableProperty = notifyCollectionChangedActionList;

var customCommand = new CustomCommand() as ICommand;
ccw = MarshalInspectable<object>.CreateMarshaler(customCommand);
ccw.TryAs<IUnknownVftbl>(ABI.System.Windows.Input.ICommandMethods.IID, out var commandCCW);
Expand Down