-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathAotOptimizer.cs
1962 lines (1750 loc) · 103 KB
/
AotOptimizer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading;
using WinRT.SourceGenerator;
namespace Generator
{
[Generator]
public class WinRTAotSourceGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var properties = context.AnalyzerConfigOptionsProvider
.Combine(context.CompilationProvider)
.Select(static ((AnalyzerConfigOptionsProvider provider, Compilation compilation) value, CancellationToken _) =>
new CsWinRTAotOptimizerProperties(
value.provider.IsCsWinRTAotOptimizerEnabled(),
value.provider.IsCsWinRTComponent(),
value.provider.IsCsWinRTCcwLookupTableGeneratorEnabled(),
GeneratorExecutionContextHelper.IsCsWinRTAotOptimizerInAutoMode(value.provider, value.compilation))
);
var assemblyName = context.CompilationProvider.Select(static (compilation, _) => GeneratorHelper.EscapeAssemblyNameForIdentifier(compilation.AssemblyName));
var propertiesAndAssemblyName = properties.Combine(assemblyName);
var typeMapperAndProperties = context.AnalyzerConfigOptionsProvider
.Select(static (options, ct) => options.GetCsWinRTUseWindowsUIXamlProjections())
.Select(static (mode, ct) => new TypeMapper(mode))
.Combine(properties);
var vtablesToAddFromDetectedClassTypes = context.SyntaxProvider.CreateSyntaxProvider(
static (n, _) => NeedVtableAttribute(n),
static (n, _) => n)
.Combine(typeMapperAndProperties)
.Select(static ((GeneratorSyntaxContext generatorSyntaxContext, (TypeMapper typeMapper, CsWinRTAotOptimizerProperties properties) typeMapperAndProperties) value, CancellationToken _) =>
value.typeMapperAndProperties.properties.IsCsWinRTAotOptimizerInAutoMode ?
GetVtableAttributeToAdd(value.generatorSyntaxContext, value.typeMapperAndProperties.typeMapper, false, value.typeMapperAndProperties.properties.IsCsWinRTCcwLookupTableGeneratorEnabled) : default)
.Where(static vtableAttribute => vtableAttribute != default);
var autoDetectedVtableAttributesToAdd = vtablesToAddFromDetectedClassTypes.Select(static (vtable, _) => vtable.Item1);
var autoDetectedAdapterTypesToAddOnLookupTable = vtablesToAddFromDetectedClassTypes.SelectMany(static (vtable, _) => vtable.Item2);
var vtablesToAddFromOptInClassTypes = context.SyntaxProvider.ForAttributeWithMetadataName(
"WinRT.GeneratedWinRTExposedTypeAttribute",
static (n, _) => NeedVtableAttribute(n),
static (n, _) => n)
.Combine(typeMapperAndProperties)
.Select(static ((GeneratorAttributeSyntaxContext generatorSyntaxContext, (TypeMapper typeMapper, CsWinRTAotOptimizerProperties properties) typeMapperAndProperties) value, CancellationToken _) =>
value.typeMapperAndProperties.properties.IsCsWinRTAotOptimizerEnabled ?
GetVtableAttributeToAdd(value.generatorSyntaxContext, value.typeMapperAndProperties.typeMapper, false, value.typeMapperAndProperties.properties.IsCsWinRTCcwLookupTableGeneratorEnabled) : default)
.Where(static vtableAttribute => vtableAttribute != default);
var optinVtableAttributesToAdd = vtablesToAddFromOptInClassTypes.Select(static (vtable, _) => vtable.Item1);
var optinAdapterTypesToAddOnLookupTable = vtablesToAddFromOptInClassTypes.SelectMany(static (vtable, _) => vtable.Item2);
// Merge both auto detected vtables and opt-in vtables.
var vtableAttributesToAdd = autoDetectedVtableAttributesToAdd.Collect().Combine(optinVtableAttributesToAdd.Collect()).SelectMany(static (value, _) => value.Left.AddRange(value.Right).Distinct());
context.RegisterImplementationSourceOutput(vtableAttributesToAdd.Collect().Combine(propertiesAndAssemblyName), GenerateVtableAttributes);
// Get the vtables for component types. This is used for filtering out generic interfaces
// that will already be generated by the component generator.
var vtablesFromComponentTypes = context.SyntaxProvider.CreateSyntaxProvider(
static (n, _) => IsComponentType(n),
static (n, _) => n)
.Combine(typeMapperAndProperties)
// Get component types if only authoring scenario and if aot optimizer enabled.
.Select(static ((GeneratorSyntaxContext generatorSyntaxContext, (TypeMapper typeMapper, CsWinRTAotOptimizerProperties properties) typeMapperAndProperties) value, CancellationToken _) =>
value.typeMapperAndProperties.properties.IsCsWinRTAotOptimizerEnabled && value.typeMapperAndProperties.properties.IsCsWinRTComponent ?
GetVtableAttributeToAdd(value.generatorSyntaxContext, value.typeMapperAndProperties.typeMapper, true, true) : default)
.Where(static vtableAttribute => vtableAttribute != default);
var autoDetectedInstantiatedTypesToAddOnLookupTable = context.SyntaxProvider.CreateSyntaxProvider(
static (n, _) => NeedVtableOnLookupTable(n),
static (n, _) => n)
.Combine(typeMapperAndProperties)
.Select(static ((GeneratorSyntaxContext generatorSyntaxContext, (TypeMapper typeMapper, CsWinRTAotOptimizerProperties properties) typeMapperAndProperties) value,
CancellationToken _) =>
value.typeMapperAndProperties.properties.IsCsWinRTAotOptimizerInAutoMode && value.typeMapperAndProperties.properties.IsCsWinRTCcwLookupTableGeneratorEnabled ?
GetVtableAttributesToAddOnLookupTable(value.generatorSyntaxContext, value.typeMapperAndProperties.typeMapper, value.typeMapperAndProperties.properties.IsCsWinRTComponent) :
(EquatableArray<VtableAttribute>)ImmutableArray<VtableAttribute>.Empty)
.SelectMany(static (vtable, _) => vtable)
.Where(static vtableAttribute => vtableAttribute != null);
var optinInstantiatedTypesToAddOnLookupTable = context.SyntaxProvider.ForAttributeWithMetadataName(
"WinRT.GeneratedWinRTExposedExternalTypeAttribute",
static (n, _) => true,
static (n, _) => n)
.Combine(typeMapperAndProperties)
.Select(static ((GeneratorAttributeSyntaxContext generatorSyntaxContext, (TypeMapper typeMapper, CsWinRTAotOptimizerProperties properties) typeMapperAndProperties) value,
CancellationToken _) =>
value.typeMapperAndProperties.properties.IsCsWinRTAotOptimizerEnabled && value.typeMapperAndProperties.properties.IsCsWinRTCcwLookupTableGeneratorEnabled ?
GetVtableAttributesToAddOnLookupTable(value.generatorSyntaxContext, value.typeMapperAndProperties.typeMapper, value.typeMapperAndProperties.properties.IsCsWinRTComponent) :
(EquatableArray<VtableAttribute>)ImmutableArray<VtableAttribute>.Empty)
.SelectMany(static (vtable, _) => vtable)
.Where(static vtableAttribute => vtableAttribute != null);
var instantiatedTaskAdapters = context.SyntaxProvider.CreateSyntaxProvider(
static (n, _) => IsAsyncOperationMethodCall(n),
static (n, _) => n)
.Combine(typeMapperAndProperties)
.Select(static ((GeneratorSyntaxContext generatorSyntaxContext, (TypeMapper typeMapper, CsWinRTAotOptimizerProperties properties) typeMapperAndProperties) value,
CancellationToken _) =>
value.typeMapperAndProperties.properties.IsCsWinRTAotOptimizerInAutoMode && value.typeMapperAndProperties.properties.IsCsWinRTCcwLookupTableGeneratorEnabled ?
GetVtableAttributesForTaskAdapters(value.generatorSyntaxContext, value.typeMapperAndProperties.typeMapper, value.typeMapperAndProperties.properties.IsCsWinRTComponent) : default)
.Where(static vtableAttribute => vtableAttribute != default)
.Collect();
// Merge both adapter types lists and instantiated types lists.
var vtablesToAddOnLookupTable =
autoDetectedInstantiatedTypesToAddOnLookupTable.Collect().
Combine(autoDetectedAdapterTypesToAddOnLookupTable.Collect()).
Combine(optinInstantiatedTypesToAddOnLookupTable.Collect()).
Combine(optinAdapterTypesToAddOnLookupTable.Collect()).
Combine(instantiatedTaskAdapters).
SelectMany(static (value, _) =>
value.Left.Left.Left.Left
.AddRange(value.Left.Left.Left.Right)
.AddRange(value.Left.Left.Right)
.AddRange(value.Left.Right)
.AddRange(value.Right)
.Distinct()
);
var genericInterfacesFromVtableAttribute = vtableAttributesToAdd.Combine(properties).SelectMany(
static ((VtableAttribute vtableAttribute, CsWinRTAotOptimizerProperties properties) value, CancellationToken _) =>
// If this is a CsWinRT component, the public types are handled by the component source generator rather than
// the AOT source generator. So we filter those out here.
(!value.properties.IsCsWinRTComponent || (value.properties.IsCsWinRTComponent && !value.vtableAttribute.IsPublic)) ?
value.vtableAttribute.GenericInterfaces : (EquatableArray<GenericInterface>)ImmutableArray<GenericInterface>.Empty).Collect();
var genericInterfacesFromVtableLookupTable = vtablesToAddOnLookupTable.SelectMany(static (vtable, _) => vtable.GenericInterfaces).Collect();
// The component generator generates vtable attributes for public types. The generic interfaces used by those types or its adapter types
// can overlap with the ones being generated here. So get which ones are already generated to be able to filter them out.
var genericInterfacesGeneratedByComponentGenerator = vtablesFromComponentTypes.
SelectMany(static ((VtableAttribute vtableAttribute, EquatableArray<VtableAttribute> adapterTypes) classType, CancellationToken _) =>
classType.vtableAttribute.GenericInterfaces.Union(classType.adapterTypes.SelectMany(static v => v.GenericInterfaces)).Distinct()).
Collect();
context.RegisterImplementationSourceOutput(
genericInterfacesFromVtableAttribute
.Combine(genericInterfacesFromVtableLookupTable)
.Combine(genericInterfacesGeneratedByComponentGenerator)
.Combine(propertiesAndAssemblyName),
GenerateCCWForGenericInstantiation);
context.RegisterImplementationSourceOutput(vtablesToAddOnLookupTable.Collect().Combine(propertiesAndAssemblyName), GenerateVtableLookupTable);
var bindableCustomPropertyAttributes = context.SyntaxProvider.ForAttributeWithMetadataName(
"WinRT.GeneratedBindableCustomPropertyAttribute",
static (n, _) => NeedCustomPropertyImplementation(n),
static (n, _) => n)
.Combine(properties)
.Select(static ((GeneratorAttributeSyntaxContext generatorSyntaxContext, CsWinRTAotOptimizerProperties properties) value, CancellationToken _) =>
value.properties.IsCsWinRTAotOptimizerEnabled ? GetBindableCustomProperties(value.generatorSyntaxContext) : default)
.Where(static bindableCustomProperties => bindableCustomProperties != default)
.Collect()
.Combine(properties);
context.RegisterImplementationSourceOutput(bindableCustomPropertyAttributes, GenerateBindableCustomProperties);
}
// Restrict to non-projected classes which can be instantiated
// and are partial allowing to add attributes.
private static bool NeedVtableAttribute(SyntaxNode node)
{
return node is ClassDeclarationSyntax declaration &&
!declaration.Modifiers.Any(static m => m.IsKind(SyntaxKind.StaticKeyword) || m.IsKind(SyntaxKind.AbstractKeyword)) &&
GeneratorHelper.IsPartial(declaration) &&
!GeneratorHelper.IsWinRTType(declaration); // Making sure it isn't an RCW we are projecting.
}
// Filters to non WinRT types which are public and can be instantiated.
// This is used to try to determine types which a component source generator will process.
private static bool IsComponentType(SyntaxNode node)
{
return node is ClassDeclarationSyntax declaration &&
!declaration.Modifiers.Any(static m => m.IsKind(SyntaxKind.StaticKeyword) || m.IsKind(SyntaxKind.AbstractKeyword)) &&
declaration.Modifiers.Any(static m => m.IsKind(SyntaxKind.PublicKeyword)) &&
!GeneratorHelper.IsWinRTType(declaration); // Making sure it isn't an RCW we are projecting.
}
private static bool NeedCustomPropertyImplementation(SyntaxNode node)
{
if ((node is ClassDeclarationSyntax classDeclaration && !classDeclaration.Modifiers.Any(static m => m.IsKind(SyntaxKind.StaticKeyword) || m.IsKind(SyntaxKind.AbstractKeyword))) ||
(node is RecordDeclarationSyntax recordDeclaration && !recordDeclaration.Modifiers.Any(static m => m.IsKind(SyntaxKind.StaticKeyword) || m.IsKind(SyntaxKind.AbstractKeyword))) ||
(node is StructDeclarationSyntax structDeclaration && !structDeclaration.Modifiers.Any(static m => m.IsKind(SyntaxKind.StaticKeyword))))
{
TypeDeclarationSyntax typeDeclaration = (TypeDeclarationSyntax)node;
return GeneratorHelper.IsPartial(typeDeclaration);
}
return false;
}
private static (VtableAttribute, EquatableArray<VtableAttribute>) GetVtableAttributeToAdd(
GeneratorSyntaxContext context,
TypeMapper typeMapper,
bool checkForComponentTypes,
bool isCsWinRTCcwLookupTableGeneratorEnabled)
{
return GetVtableAttributeToAdd(
context.SemanticModel.GetDeclaredSymbol(context.Node as ClassDeclarationSyntax),
typeMapper,
context.SemanticModel.Compilation,
checkForComponentTypes,
isCsWinRTCcwLookupTableGeneratorEnabled);
}
private static (VtableAttribute, EquatableArray<VtableAttribute>) GetVtableAttributeToAdd(
GeneratorAttributeSyntaxContext context,
TypeMapper typeMapper,
bool checkForComponentTypes,
bool isCsWinRTCcwLookupTableGeneratorEnabled)
{
return GetVtableAttributeToAdd(
(ITypeSymbol)context.TargetSymbol,
typeMapper,
context.SemanticModel.Compilation,
checkForComponentTypes,
isCsWinRTCcwLookupTableGeneratorEnabled);
}
private static (VtableAttribute, EquatableArray<VtableAttribute>) GetVtableAttributeToAdd(
ITypeSymbol symbol,
TypeMapper typeMapper,
Compilation compilation,
bool checkForComponentTypes,
bool isCsWinRTCcwLookupTableGeneratorEnabled)
{
var isManagedOnlyType = GeneratorHelper.IsManagedOnlyType(compilation);
var isWinRTTypeFunc = GeneratorHelper.IsWinRTType(compilation, checkForComponentTypes);
var vtableAttribute = GetVtableAttributeToAdd(symbol, isManagedOnlyType, isWinRTTypeFunc, typeMapper, compilation, false);
if (vtableAttribute != default)
{
HashSet<VtableAttribute> vtableAttributesForLookupTable = [];
// Add any adapter types which may be needed if certain functions
// from some known interfaces are called.
if (isCsWinRTCcwLookupTableGeneratorEnabled)
{
AddVtableAdapterTypeForKnownInterface(symbol, compilation, isManagedOnlyType, isWinRTTypeFunc, typeMapper, vtableAttributesForLookupTable);
}
return (vtableAttribute, vtableAttributesForLookupTable.ToImmutableArray());
}
return default;
}
// There are several async operation related methods that can be called.
// But they are all under the AsyncInfo static class or is the AsAsyncOperation
// extension method.
static bool IsAsyncOperationMethodCall(SyntaxNode node)
{
if (node is InvocationExpressionSyntax methodInvoke &&
methodInvoke.Expression is MemberAccessExpressionSyntax methodAccess)
{
// Check for static class as a way of handling all the async functions from it.
if (methodAccess.Expression is IdentifierNameSyntax className &&
className.Identifier.ValueText == "AsyncInfo")
{
return true;
}
// Check for calling the fully qualified static class.
// i.e. System.Runtime.InteropServices.WindowsRuntime.AsyncInfo
if (methodAccess.Expression is MemberAccessExpressionSyntax memberAccess &&
memberAccess.Name.Identifier.ValueText == "AsyncInfo")
{
return true;
}
// Check for function call for the scenario that doesn't use the static class.
if (methodAccess.Name is IdentifierNameSyntax methodName)
{
return methodName.Identifier.ValueText == "AsAsyncOperation";
}
}
return false;
}
// Detect if AsAsyncOperation or similar function is being called and if so,
// make sure the generic adapter type we use for it is on the lookup table.
// We do this both assuming this is not an authoring component and is an authoring
// component as we don't know that at this stage and the results can vary based on that.
// We will choose the right one later when we can combine with properties.
private static VtableAttribute GetVtableAttributesForTaskAdapters(GeneratorSyntaxContext context, TypeMapper typeMapper, bool isCsWinRTComponent)
{
// Generic instantiation of task adapters make of use of unsafe.
// This will be caught by GetVtableAttributeToAdd, but catching it early here too.
if (!GeneratorHelper.AllowUnsafe(context.SemanticModel.Compilation))
{
return default;
}
if (context.SemanticModel.GetSymbolInfo(context.Node as InvocationExpressionSyntax).Symbol is IMethodSymbol symbol)
{
var adapterTypeStr = GeneratorHelper.GetTaskAdapterIfAsyncMethod(symbol);
if (!string.IsNullOrEmpty(adapterTypeStr))
{
var adpaterType = context.SemanticModel.Compilation.GetTypeByMetadataName(adapterTypeStr);
if (adpaterType is not null)
{
var constructedAdapterType = adpaterType.Construct([.. symbol.TypeArguments]);
return GetVtableAttributeToAdd(
constructedAdapterType,
GeneratorHelper.IsManagedOnlyType(context.SemanticModel.Compilation),
GeneratorHelper.IsWinRTType(context.SemanticModel.Compilation, isCsWinRTComponent),
typeMapper,
context.SemanticModel.Compilation,
false);
}
}
}
return default;
}
#nullable enable
private static BindableCustomProperties GetBindableCustomProperties(GeneratorAttributeSyntaxContext context)
{
// We expect a class with a single attribute.
var symbol = (INamedTypeSymbol)context.TargetSymbol;
var attributeData = context.Attributes.First();
List<BindableCustomProperty> bindableCustomProperties = new();
// Make all public properties in the class bindable including ones in base type.
if (attributeData.ConstructorArguments.Length == 0)
{
for (var curSymbol = symbol; curSymbol != null; curSymbol = curSymbol.BaseType)
{
foreach (var propertySymbol in curSymbol.GetMembers().
Where(static m => m.Kind == SymbolKind.Property &&
m.DeclaredAccessibility == Accessibility.Public))
{
AddProperty(propertySymbol);
}
}
}
// Make specified public properties in the class bindable including ones in base type.
else if (attributeData.ConstructorArguments is
[
{ Kind: TypedConstantKind.Array, Values: [..] propertyNames },
{ Kind: TypedConstantKind.Array, Values: [..] propertyIndexerTypes }
])
{
for (var curSymbol = symbol; curSymbol != null; curSymbol = curSymbol.BaseType)
{
foreach (var member in curSymbol.GetMembers())
{
if (member is IPropertySymbol propertySymbol &&
member.DeclaredAccessibility == Accessibility.Public)
{
if (!propertySymbol.IsIndexer &&
propertyNames.Any(p => p.Value is string value && value == propertySymbol.Name))
{
AddProperty(propertySymbol);
}
else if (propertySymbol.IsIndexer &&
// ICustomProperty only supports single indexer parameter.
propertySymbol.Parameters.Length == 1 &&
propertyIndexerTypes.Any(p => p.Value is ISymbol typeSymbol && typeSymbol.Equals(propertySymbol.Parameters[0].Type, SymbolEqualityComparer.Default)))
{
AddProperty(propertySymbol);
}
}
}
}
}
var typeName = ToFullyQualifiedString(symbol);
bool isGlobalNamespace = symbol.ContainingNamespace == null || symbol.ContainingNamespace.IsGlobalNamespace;
var @namespace = symbol.ContainingNamespace?.ToDisplayString();
if (!isGlobalNamespace)
{
typeName = typeName[(@namespace!.Length + 1)..];
}
EquatableArray<TypeInfo> classHierarchy = ImmutableArray<TypeInfo>.Empty;
// Gather the type hierarchy, only if the type is nested (as an optimization)
if (symbol.ContainingType is not null)
{
List<TypeInfo> hierarchyList = new();
for (ITypeSymbol parent = symbol; parent is not null; parent = parent.ContainingType)
{
hierarchyList.Add(new TypeInfo(
parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
parent.TypeKind,
parent.IsRecord));
}
classHierarchy = ImmutableArray.CreateRange(hierarchyList);
}
return new BindableCustomProperties(
@namespace,
isGlobalNamespace,
typeName,
symbol.TypeKind,
symbol.IsRecord,
classHierarchy,
ToFullyQualifiedString(symbol),
bindableCustomProperties.ToImmutableArray());
void AddProperty(ISymbol symbol)
{
if (symbol is IPropertySymbol propertySymbol)
{
bindableCustomProperties.Add(new BindableCustomProperty(
propertySymbol.MetadataName,
ToFullyQualifiedString(propertySymbol.Type),
// Make sure the property accessors are also public even if property itself is public.
propertySymbol.GetMethod != null && propertySymbol.GetMethod.DeclaredAccessibility == Accessibility.Public,
propertySymbol.SetMethod != null && !propertySymbol.SetMethod.IsInitOnly && propertySymbol.SetMethod.DeclaredAccessibility == Accessibility.Public,
propertySymbol.IsIndexer,
propertySymbol.IsIndexer ? ToFullyQualifiedString(propertySymbol.Parameters[0].Type) : "",
propertySymbol.IsStatic
));
}
}
}
#nullable disable
private static string ToFullyQualifiedString(ISymbol symbol)
{
// Used to ensure class names within generics are fully qualified to avoid
// having issues when put in ABI namespaces.
var symbolDisplayString = new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.ExpandNullable);
var qualifiedString = symbol.ToDisplayString(symbolDisplayString);
return qualifiedString.StartsWith("global::") ? qualifiedString[8..] : qualifiedString;
}
private static string ToVtableLookupString(ISymbol symbol)
{
List<string> genericArguments = [];
var fullName = ToVtableLookupString(symbol, genericArguments);
if (genericArguments.Count == 0)
{
return fullName;
}
return $$"""{{fullName}}[{{string.Join(",", genericArguments)}}]""";
}
private static string ToVtableLookupString(ISymbol symbol, List<string> genericArguments, bool ignoreTypeArguments = false)
{
if (symbol is INamedTypeSymbol namedTypeSymbol &&
!ignoreTypeArguments &&
namedTypeSymbol.TypeArguments.Length != 0)
{
// Ignore type arguments and get the string representation for the rest of
// the type to properly handle nested types.
var fullName = ToVtableLookupString(symbol, genericArguments, true);
// Type arguments are collected but not added to the type name until the end
// per the format of Type.ToString(). ToVtableLookupString on the symbol is
// also called first to ensure any type arguments from any nested parent types
// are added first.
foreach (var typeArgument in namedTypeSymbol.TypeArguments)
{
genericArguments.Add(ToVtableLookupString(typeArgument));
}
return fullName;
}
else
{
// If it is a generic type argument or the type is directly under a namspace, we just use the ToDisplayString API.
if (symbol is not INamedTypeSymbol || symbol.ContainingSymbol is INamespaceSymbol || symbol.ContainingSymbol is null)
{
var arity = symbol is INamedTypeSymbol namedType && namedType.Arity > 0 ? "`" + namedType.Arity : "";
var symbolDisplayString = new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.ExpandNullable);
return symbol.ToDisplayString(symbolDisplayString) + arity;
}
else
{
// Nested types use + in the fully qualified name rather than .
return ToVtableLookupString(symbol.ContainingSymbol, genericArguments) + "+" + symbol.MetadataName;
}
}
}
private static string GetRuntimeClassName(
INamedTypeSymbol type,
Func<ISymbol, TypeMapper, bool> isWinRTType,
TypeMapper mapper)
{
if (type == null)
{
return string.Empty;
}
string metadataName = string.Join(".", type.ContainingNamespace?.ToDisplayString(), type.MetadataName);
if (type.IsGenericType && !type.IsDefinition)
{
StringBuilder builder = new();
builder.Append(GetRuntimeClassName(type.OriginalDefinition, isWinRTType, mapper));
builder.Append("<");
bool first = true;
foreach (var genericArg in type.TypeArguments)
{
if (!first)
{
builder.Append(", ");
}
builder.Append(GetRuntimeClassName(genericArg as INamedTypeSymbol, isWinRTType, mapper));
first = false;
}
builder.Append(">");
return builder.ToString();
}
else if (type.SpecialType == SpecialType.System_Object)
{
return "Object";
}
else if (type.SpecialType == SpecialType.System_Byte)
{
return "UInt8";
}
else if (type.SpecialType == SpecialType.System_SByte)
{
return "Int8";
}
else if (mapper.HasMappingForType(metadataName))
{
var mapping = mapper.GetMappedType(metadataName).GetMapping();
return mapping.Item1 + "." + mapping.Item2;
}
else if (type.SpecialType != SpecialType.None)
{
return type.Name;
}
else if (isWinRTType(type, mapper))
{
return metadataName;
}
else
{
// If we end up here, this is most likely an authoring scenario where the type is being authored
// for WinRT projection in this component.
return metadataName;
}
}
internal static VtableAttribute GetVtableAttributeToAdd(
ITypeSymbol symbol,
Func<ISymbol, bool> isManagedOnlyType,
Func<ISymbol, TypeMapper, bool> isWinRTType,
TypeMapper mapper,
Compilation compilation,
bool isAuthoring,
string authoringDefaultInterface = "")
{
if (symbol is null)
{
return default;
}
if (GeneratorHelper.HasNonInstantiatedWinRTGeneric(symbol, mapper))
{
return default;
}
// Skip all types explicitly blocked for marshalling.
// We don't want them to affect the codegen at all.
if (isManagedOnlyType(symbol))
{
return default;
}
HashSet<string> interfacesToAddToVtable = new();
HashSet<GenericInterface> genericInterfacesToAddToVtable = new();
if (!string.IsNullOrEmpty(authoringDefaultInterface))
{
interfacesToAddToVtable.Add(authoringDefaultInterface);
}
// If the attribute is already placed on the type, don't generate a new one as we will
// use the specified one. Also for authoring scenarios where we call this for authored WinRT types,
// don't generate the runtimeclass name for them as we will rely on the full name for them as we do today.
var checkForRuntimeClasName = !GeneratorHelper.HasWinRTRuntimeClassNameAttribute(symbol, compilation) &&
(!isAuthoring || (isAuthoring && !isWinRTType(symbol, mapper)));
INamedTypeSymbol interfaceToUseForRuntimeClassName = null;
foreach (var iface in symbol.AllInterfaces)
{
if (isWinRTType(iface, mapper))
{
// If the interface projection was generated using an older CsWinRT version,
// it won't have the necessary properties to generate the AOT compatible code
// and we don't want to result in compiler errors.
// We exclude generic types as they are either defined in WinRT.Runtime or the
// Windows SDK projection, so we don't need to check them.
if (!iface.IsGenericType &&
GeneratorHelper.IsOldProjectionAssembly(iface.ContainingAssembly))
{
return default;
}
interfacesToAddToVtable.Add(ToFullyQualifiedString(iface));
AddGenericInterfaceInstantiation(iface);
CheckForInterfaceToUseForRuntimeClassName(iface);
}
if (iface.IsGenericType && TryGetCompatibleWindowsRuntimeTypesForVariantType(iface, mapper, null, isWinRTType, compilation.ObjectType, out var compatibleIfaces))
{
foreach (var compatibleIface in compatibleIfaces)
{
// For covariant interfaces which are exclusive interfaces that the projection implemented
// such as overrides / protected interfaces in composable types, we don't include them in
// the vtable as they are today marked internal and we can't reference them due to that.
// If this scenarios matters where native callers do indeed QI for these exclusive
// covariant interfaces, we can in the future project them as public, but for now
// leaving as is.
if (GeneratorHelper.IsInternalInterfaceFromReferences(compatibleIface, compilation.Assembly))
{
continue;
}
interfacesToAddToVtable.Add(ToFullyQualifiedString(compatibleIface));
AddGenericInterfaceInstantiation(compatibleIface);
CheckForInterfaceToUseForRuntimeClassName(compatibleIface);
}
}
}
// KeyValueType is a value type in C#, but it is projected as a reference type in WinRT.
if (symbol.TypeKind == TypeKind.Struct && symbol.MetadataName == "KeyValuePair`2" && isWinRTType(symbol, mapper))
{
interfacesToAddToVtable.Add(ToFullyQualifiedString(symbol));
AddGenericInterfaceInstantiation(symbol as INamedTypeSymbol);
// KeyValuePair is projected as an interface.
CheckForInterfaceToUseForRuntimeClassName(symbol as INamedTypeSymbol);
}
bool isDelegate = false;
if (symbol.TypeKind == TypeKind.Delegate)
{
isDelegate = true;
interfacesToAddToVtable.Add(ToFullyQualifiedString(symbol));
AddGenericInterfaceInstantiation(symbol as INamedTypeSymbol);
}
if (!interfacesToAddToVtable.Any())
{
return default;
}
// If there are generic interfaces, the generic interface instantiations make use of
// unsafe. But if it isn't enabled, we don't want to fail to compile in case it is
// not a WinRT scenario. So we instead, don't generate the code that needs the unsafe
// and there would be a diagnostic produced by the analyzer.
if (genericInterfacesToAddToVtable.Any() && !GeneratorHelper.AllowUnsafe(compilation))
{
return default;
}
var typeName = ToFullyQualifiedString(symbol);
bool isGlobalNamespace = symbol.ContainingNamespace == null || symbol.ContainingNamespace.IsGlobalNamespace;
var @namespace = symbol.ContainingNamespace?.ToDisplayString();
if (!isGlobalNamespace)
{
typeName = typeName[(@namespace.Length + 1)..];
}
EquatableArray<TypeInfo> classHierarchy = ImmutableArray<TypeInfo>.Empty;
// Gather the type hierarchy, only if the type is nested (as an optimization)
if (symbol.ContainingType is not null)
{
List<TypeInfo> hierarchyList = new();
for (ITypeSymbol parent = symbol; parent is not null; parent = parent.ContainingType)
{
hierarchyList.Add(new TypeInfo(
parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
parent.TypeKind,
parent.IsRecord));
}
classHierarchy = ImmutableArray.CreateRange(hierarchyList);
}
return new VtableAttribute(
isAuthoring ? "ABI.Impl." + @namespace : @namespace,
isGlobalNamespace,
typeName,
classHierarchy,
ToVtableLookupString(symbol),
interfacesToAddToVtable.ToImmutableArray(),
genericInterfacesToAddToVtable.ToImmutableArray(),
symbol is IArrayTypeSymbol,
isDelegate,
symbol.DeclaredAccessibility == Accessibility.Public,
GetRuntimeClassName(interfaceToUseForRuntimeClassName, isWinRTType, mapper));
void AddGenericInterfaceInstantiation(INamedTypeSymbol iface)
{
if (iface.IsGenericType)
{
List<GenericParameter> genericParameters = new();
foreach (var genericParameter in iface.TypeArguments)
{
var isNullable = genericParameter.IsValueType && genericParameter.NullableAnnotation.HasFlag(NullableAnnotation.Annotated);
// Handle initialization of nested generics as they may not be
// initialized already.
if (!isNullable &&
genericParameter is INamedTypeSymbol genericParameterIface &&
genericParameterIface.IsGenericType)
{
AddGenericInterfaceInstantiation(genericParameterIface);
}
genericParameters.Add(new GenericParameter(
ToFullyQualifiedString(genericParameter),
GeneratorHelper.GetAbiType(genericParameter, mapper),
isNullable ? TypeKind.Interface : genericParameter.TypeKind));
}
genericInterfacesToAddToVtable.Add(new GenericInterface(
ToFullyQualifiedString(iface),
$$"""{{iface.ContainingNamespace}}.{{iface.MetadataName}}""",
genericParameters.ToImmutableArray()));
}
}
bool IsExternalInternalInterface(INamedTypeSymbol iface)
{
return (iface.DeclaredAccessibility == Accessibility.Internal && !SymbolEqualityComparer.Default.Equals(iface.ContainingAssembly, compilation.Assembly)) ||
(iface.IsGenericType && iface.TypeArguments.Any(typeArgument => IsExternalInternalInterface(typeArgument as INamedTypeSymbol)));
}
// Determines the interface to use to represent the type when GetRuntimeClassName is called.
// Given these are non WinRT types implementing WinRT interfaces, we find the most derived
// interface to represent it so that it applies for most scenarios.
void CheckForInterfaceToUseForRuntimeClassName(INamedTypeSymbol iface)
{
if (!checkForRuntimeClasName)
{
return;
}
if (interfaceToUseForRuntimeClassName is null || compilation.HasImplicitConversion(iface, interfaceToUseForRuntimeClassName))
{
interfaceToUseForRuntimeClassName = iface;
}
}
}
private static bool TryGetCompatibleWindowsRuntimeTypesForVariantType(INamedTypeSymbol type, TypeMapper mapper, Stack<INamedTypeSymbol> typeStack, Func<ISymbol, TypeMapper, bool> isWinRTType, INamedTypeSymbol objectType, out IList<INamedTypeSymbol> compatibleTypes)
{
compatibleTypes = null;
// Out of all the C# interfaces which are valid WinRT interfaces and
// support covariance, they all only have one generic parameter,
// so scoping to only handle that.
if (type is not { IsGenericType: true, TypeParameters: [{ Variance: VarianceKind.Out }], TypeArguments: [{ IsValueType: false }] })
{
return false;
}
var definition = type.OriginalDefinition;
if (!isWinRTType(definition, mapper))
{
return false;
}
if (typeStack == null)
{
typeStack = new Stack<INamedTypeSymbol>();
}
else
{
if (typeStack.Contains(type))
{
return false;
}
}
typeStack.Push(type);
HashSet<ITypeSymbol> compatibleTypesForGeneric = new(SymbolEqualityComparer.Default);
if (isWinRTType(type.TypeArguments[0], mapper))
{
compatibleTypesForGeneric.Add(type.TypeArguments[0]);
}
foreach (var iface in type.TypeArguments[0].AllInterfaces)
{
if (isWinRTType(iface, mapper))
{
compatibleTypesForGeneric.Add(iface);
}
if (iface.IsGenericType
&& TryGetCompatibleWindowsRuntimeTypesForVariantType(iface, mapper, typeStack, isWinRTType, objectType, out var compatibleIfaces))
{
compatibleTypesForGeneric.UnionWith(compatibleIfaces);
}
}
// BaseType reports null for interfaces, but interfaces still can be passed as an object.
// So we handle that separately.
var typeArgument = type.TypeArguments[0];
var baseType = typeArgument.TypeKind == TypeKind.Interface ? objectType : typeArgument.BaseType;
while (baseType != null)
{
if (isWinRTType(baseType, mapper))
{
compatibleTypesForGeneric.Add(baseType);
}
baseType = baseType.BaseType;
}
typeStack.Pop();
compatibleTypes = new List<INamedTypeSymbol>(compatibleTypesForGeneric.Count);
foreach (var compatibleType in compatibleTypesForGeneric)
{
compatibleTypes.Add(definition.Construct(compatibleType));
}
return true;
}
private static void GenerateVtableAttributes(
SourceProductionContext sourceProductionContext,
(ImmutableArray<VtableAttribute> vtableAttributes, (CsWinRTAotOptimizerProperties properties, string escapedAssemblyName) context) value)
{
if (!value.context.properties.IsCsWinRTAotOptimizerEnabled)
{
return;
}
GenerateVtableAttributes(sourceProductionContext.AddSource, value.vtableAttributes, value.context.properties.IsCsWinRTComponent, value.context.escapedAssemblyName);
}
internal static string GenerateVtableEntry(VtableEntry vtableEntry, string escapedAssemblyName)
{
StringBuilder source = new();
foreach (var genericInterface in vtableEntry.GenericInterfaces)
{
source.AppendLine(GenericVtableInitializerStrings.GetInstantiationInitFunction(
genericInterface.GenericDefinition,
genericInterface.GenericParameters,
escapedAssemblyName));
}
if (vtableEntry.IsDelegate)
{
var @interface = vtableEntry.Interfaces.First();
source.AppendLine();
source.AppendLine($$"""
var delegateInterface = new global::System.Runtime.InteropServices.ComWrappers.ComInterfaceEntry
{
IID = global::ABI.{{@interface}}.IID,
Vtable = global::ABI.{{@interface}}.AbiToProjectionVftablePtr
};
return global::WinRT.DelegateTypeDetails<{{@interface}}>.GetExposedInterfaces(delegateInterface);
""");
}
else if (vtableEntry.Interfaces.Any())
{
source.AppendLine();
source.AppendLine($$"""
return new global::System.Runtime.InteropServices.ComWrappers.ComInterfaceEntry[]
{
""");
foreach (var @interface in vtableEntry.Interfaces)
{
var genericStartIdx = @interface.IndexOf('<');
var interfaceStaticsMethod = @interface[..(genericStartIdx == -1 ? @interface.Length : genericStartIdx)] + "Methods";
if (genericStartIdx != -1)
{
interfaceStaticsMethod += @interface[[email protected]];
}
source.AppendLine($$"""
new global::System.Runtime.InteropServices.ComWrappers.ComInterfaceEntry
{
IID = global::ABI.{{interfaceStaticsMethod}}.IID,
Vtable = global::ABI.{{interfaceStaticsMethod}}.AbiToProjectionVftablePtr
},
""");
}
source.AppendLine($$"""
};
""");
}
else
{
source.AppendLine($$"""
return global::System.Array.Empty<global::System.Runtime.InteropServices.ComWrappers.ComInterfaceEntry>();
""");
}
return source.ToString();
}
internal static void GenerateVtableAttributes(Action<string, string> addSource, ImmutableArray<VtableAttribute> vtableAttributes, bool isCsWinRTComponentFromAotOptimizer, string escapedAssemblyName)
{
var vtableEntryToVtableClassName = new Dictionary<VtableEntry, string>();
StringBuilder vtableClassesSource = new();
bool firstVtableClass = true;
// Using ToImmutableHashSet to avoid duplicate entries from the use of partial classes by the developer
// to split out their implementation. When they do that, we will get multiple entries here for that
// and try to generate the same attribute and file with the same data as we use the semantic model
// to get all the symbol data rather than the data at an instance of a partial class definition.
foreach (var vtableAttribute in vtableAttributes.ToImmutableHashSet())
{
// If this is a WinRT component project and this call is coming
// from the AOT optimizer, then any public types are not handled
// right now as they are handled by the WinRT component source generator
// calling this.
if (((isCsWinRTComponentFromAotOptimizer && !vtableAttribute.IsPublic) || !isCsWinRTComponentFromAotOptimizer) &&
vtableAttribute.Interfaces.Any())
{
StringBuilder source = new();
if (!vtableAttribute.IsGlobalNamespace)
{
source.AppendLine($$"""
namespace {{vtableAttribute.Namespace}}
{
""");
}
// Check if this class shares the same vtable as another class. If so, reuse the same generated class for it.
VtableEntry entry = new(vtableAttribute.Interfaces, vtableAttribute.GenericInterfaces, vtableAttribute.IsDelegate);
bool vtableEntryExists = vtableEntryToVtableClassName.TryGetValue(entry, out var ccwClassName);
if (!vtableEntryExists)
{
var @namespace = vtableAttribute.IsGlobalNamespace ? "" : $"{vtableAttribute.Namespace}.";
ccwClassName = GeneratorHelper.EscapeTypeNameForIdentifier(@namespace + vtableAttribute.ClassName);
vtableEntryToVtableClassName.Add(entry, ccwClassName);
}
var escapedClassName = GeneratorHelper.EscapeTypeNameForIdentifier(vtableAttribute.ClassName);
// Simple case when the type is not nested
if (vtableAttribute.ClassHierarchy.IsEmpty)
{
if (!string.IsNullOrEmpty(vtableAttribute.RuntimeClassName))
{
source.AppendLine($$"""[global::WinRT.WinRTRuntimeClassName("{{vtableAttribute.RuntimeClassName}}")]""");
}
source.AppendLine($$"""
[global::WinRT.WinRTExposedType(typeof(global::WinRT.{{escapedAssemblyName}}VtableClasses.{{ccwClassName}}WinRTTypeDetails))]
partial class {{vtableAttribute.ClassName}}
{
}
""");
}
else
{
ReadOnlySpan<TypeInfo> classHierarchy = vtableAttribute.ClassHierarchy.AsSpan();
// If the type is nested, correctly nest the type definition
for (int i = classHierarchy.Length - 1; i > 0; i--)
{
source.AppendLine($$"""
partial {{classHierarchy[i].GetTypeKeyword()}} {{classHierarchy[i].QualifiedName}}
{
""");
}
// Define the inner-most item with the attribute
if (!string.IsNullOrEmpty(vtableAttribute.RuntimeClassName))
{
source.AppendLine($$"""[global::WinRT.WinRTRuntimeClassName("{{vtableAttribute.RuntimeClassName}}")]""");