forked from xamarin/GoogleApisForiOSComponents
-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathBindingSurfaceCoverage.cs
More file actions
1233 lines (1090 loc) · 50.5 KB
/
Copy pathBindingSurfaceCoverage.cs
File metadata and controls
1233 lines (1090 loc) · 50.5 KB
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
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace FirebaseBindingAudit;
internal static class FirebasePackageVersions
{
public const string DefaultFirebasePackageVersion = "12.10.0";
}
internal sealed class BindingSurfaceCoverageManifest
{
public List<BindingSurfaceCoverageTargetManifest> Targets { get; set; } = [];
public List<BindingSurfaceWaiver> Waivers { get; set; } = [];
}
internal sealed class BindingSurfaceCoverageTargetManifest
{
public string Id { get; set; } = string.Empty;
public string PackageId { get; set; } = string.Empty;
public string CoverageCaseMethod { get; set; } = string.Empty;
public string[] SourceFiles { get; set; } = [];
public List<BindingSurfacePackageReference> RequiredExtraPackages { get; set; } = [];
}
internal sealed class BindingSurfacePackageReference
{
public string Id { get; set; } = string.Empty;
public string Version { get; set; } = FirebasePackageVersions.DefaultFirebasePackageVersion;
}
internal sealed class BindingSurfaceWaiver
{
public string Target { get; set; } = string.Empty;
public string SurfaceId { get; set; } = string.Empty;
public string Kind { get; set; } = string.Empty;
public string Reason { get; set; } = string.Empty;
public string Evidence { get; set; } = string.Empty;
}
internal sealed record BindingSurfaceCoverageDocument(
IReadOnlyList<BindingSurfaceCoverageTargetDocument> Targets,
IReadOnlyList<BindingSurfaceWaiver> Waivers);
internal sealed record BindingSurfaceCoverageTargetDocument(
string Id,
string PackageId,
string CoverageCaseMethod,
IReadOnlyList<string> SourceFiles,
IReadOnlyList<BindingSurfacePackageReference> RequiredPackages,
IReadOnlyList<BindingSurfaceDescriptor> Surfaces);
internal sealed record BindingSurfaceDescriptor(
string Target,
string SurfaceId,
string Kind,
string TypeName,
string RuntimeTypeName,
string AssemblyName,
string? ObjectiveCName,
string? ContainerKind,
bool IsProtocol,
bool IsStatic,
string? MemberName,
string? BindingAttribute,
string? BindingValue,
bool HasGetter,
bool HasSetter,
int ParameterCount,
IReadOnlyList<string> ParameterTypes,
string? ReturnType,
string? UnderlyingType,
IReadOnlyList<BindingSurfaceNativeSelector> NativeSelectors,
string SourceFile,
string Signature);
internal sealed record BindingSurfaceNativeSelector(
string Selector,
bool IsStatic,
bool IsProtocol);
internal sealed record BindingSurfaceExerciseRecord(
string Target,
string SurfaceId);
internal sealed record BindingSurfaceCoverageValidationResult(
IReadOnlyList<string> UnclaimedSurfaceIds,
IReadOnlyList<string> StaleWaiverSurfaceIds,
IReadOnlyList<string> StaleExerciseSurfaceIds)
{
public bool IsValid => UnclaimedSurfaceIds.Count == 0 &&
StaleWaiverSurfaceIds.Count == 0 &&
StaleExerciseSurfaceIds.Count == 0;
}
internal static class BindingSurfaceCoverageManifestLoader
{
public static BindingSurfaceCoverageManifest Load(string manifestPath)
{
if (!File.Exists(manifestPath))
{
throw new FileNotFoundException("Binding surface coverage manifest not found.", manifestPath);
}
var manifest = JsonSerializer.Deserialize<BindingSurfaceCoverageManifest>(
File.ReadAllText(manifestPath),
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (manifest is null)
{
throw new InvalidOperationException($"Unable to deserialize binding surface coverage manifest at '{manifestPath}'.");
}
return manifest;
}
}
internal sealed class BindingSurfaceCoverageBuilder
{
private static readonly BindingSurfaceNativeSelector[] EmptySelectors = [];
private readonly AuditConfiguration auditConfiguration;
private readonly BindingSyntaxParser parser;
public BindingSurfaceCoverageBuilder(AuditConfiguration auditConfiguration)
{
this.auditConfiguration = auditConfiguration;
parser = new BindingSyntaxParser(auditConfiguration.ManualAttributes, auditConfiguration.BindingAttributes);
}
public BindingSurfaceCoverageDocument Build(
string repoRoot,
BindingSurfaceCoverageManifest manifest,
string selectedTarget)
{
var manifestTargetsById = manifest.Targets.ToDictionary(static target => target.Id, StringComparer.OrdinalIgnoreCase);
var selectedTargets = SelectTargets(manifest.Targets, selectedTarget);
var targetDocuments = new List<BindingSurfaceCoverageTargetDocument>();
foreach (var targetManifest in selectedTargets)
{
var auditTarget = auditConfiguration.Targets.FirstOrDefault(target =>
string.Equals(target.Id, targetManifest.Id, StringComparison.OrdinalIgnoreCase));
if (auditTarget is null)
{
throw new InvalidOperationException($"Coverage target '{targetManifest.Id}' is not present in scripts/firebase-binding-audit.json.");
}
var sourceFiles = targetManifest.SourceFiles
.Select(sourceFile => Path.Combine(repoRoot, sourceFile))
.ToList();
var sourceFileSet = targetManifest.SourceFiles.ToHashSet(StringComparer.Ordinal);
var expectedSourceFiles = auditTarget.BaselineFiles
.Concat(auditTarget.HelperFiles)
.Select(file => Path.Combine(auditTarget.BaselineDirectory, file))
.ToHashSet(StringComparer.Ordinal);
if (!sourceFileSet.SetEquals(expectedSourceFiles))
{
throw new InvalidOperationException(
$"Coverage source files for '{targetManifest.Id}' must exactly match the audit config source files.");
}
foreach (var sourceFile in sourceFiles)
{
if (!File.Exists(sourceFile))
{
throw new FileNotFoundException($"Coverage source file for '{targetManifest.Id}' was not found.", sourceFile);
}
}
var comparableFiles = auditTarget.BaselineFiles
.Select(file => Path.Combine(auditTarget.BaselineDirectoryPath(repoRoot), file))
.ToList();
var helperFiles = auditTarget.HelperFiles
.Select(file => Path.Combine(auditTarget.BaselineDirectoryPath(repoRoot), file))
.ToList();
var helperFileSet = helperFiles.ToHashSet(StringComparer.Ordinal);
var snapshot = parser.Parse(comparableFiles, helperFiles);
var surfaces = BuildSurfaces(targetManifest.Id, snapshot, helperFileSet)
.Concat(BuildPublicHelperSurfaces(targetManifest.Id, helperFiles))
.OrderBy(static surface => surface.SurfaceId, StringComparer.Ordinal)
.ToList();
var duplicateSurfaceIds = surfaces
.GroupBy(static surface => surface.SurfaceId, StringComparer.Ordinal)
.Where(static group => group.Count() > 1)
.Select(static group => group.Key)
.ToList();
if (duplicateSurfaceIds.Count > 0)
{
throw new InvalidOperationException(
$"Coverage target '{targetManifest.Id}' generated duplicate surface ids: {string.Join(", ", duplicateSurfaceIds.Take(20))}");
}
var requiredPackages = new Dictionary<string, BindingSurfacePackageReference>(StringComparer.Ordinal);
AddPackage(requiredPackages, targetManifest.PackageId, FirebasePackageVersions.DefaultFirebasePackageVersion);
foreach (var package in targetManifest.RequiredExtraPackages)
{
AddPackage(requiredPackages, package.Id, package.Version);
}
targetDocuments.Add(new BindingSurfaceCoverageTargetDocument(
targetManifest.Id,
targetManifest.PackageId,
targetManifest.CoverageCaseMethod,
targetManifest.SourceFiles,
requiredPackages.Values.OrderBy(static package => package.Id, StringComparer.Ordinal).ToList(),
surfaces));
}
var selectedTargetIds = selectedTargets.Select(static target => target.Id).ToHashSet(StringComparer.OrdinalIgnoreCase);
var selectedWaivers = manifest.Waivers
.Where(waiver => selectedTargetIds.Contains(waiver.Target))
.OrderBy(static waiver => waiver.Target, StringComparer.Ordinal)
.ThenBy(static waiver => waiver.SurfaceId, StringComparer.Ordinal)
.ToList();
foreach (var waiver in selectedWaivers)
{
if (!manifestTargetsById.ContainsKey(waiver.Target))
{
throw new InvalidOperationException($"Coverage waiver '{waiver.SurfaceId}' references unknown target '{waiver.Target}'.");
}
}
return new BindingSurfaceCoverageDocument(targetDocuments, selectedWaivers);
}
public static async Task WriteAsync(
BindingSurfaceCoverageDocument document,
string coverageOutputPath,
string propsOutputPath,
string selectedTarget,
CancellationToken cancellationToken = default)
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(coverageOutputPath))!);
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(propsOutputPath))!);
var json = JsonSerializer.Serialize(
document,
new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
});
await File.WriteAllTextAsync(coverageOutputPath, json + Environment.NewLine, cancellationToken);
var props = BuildProps(document, coverageOutputPath, selectedTarget);
await File.WriteAllTextAsync(propsOutputPath, props.ToString(SaveOptions.DisableFormatting) + Environment.NewLine, cancellationToken);
}
private static XDocument BuildProps(
BindingSurfaceCoverageDocument document,
string coverageOutputPath,
string selectedTarget)
{
var defaultPackageIds = new HashSet<string>(StringComparer.Ordinal)
{
"AdamE.Firebase.iOS.Analytics",
"AdamE.Firebase.iOS.Core",
"AdamE.Firebase.iOS.Installations",
"AdamE.Google.iOS.GoogleAppMeasurement",
"AdamE.Google.iOS.GoogleDataTransport",
"AdamE.Google.iOS.GoogleUtilities",
"AdamE.Google.iOS.Nanopb",
"AdamE.Google.iOS.PromisesObjC"
};
var packages = document.Targets
.SelectMany(static target => target.RequiredPackages)
.Where(package => !defaultPackageIds.Contains(package.Id))
.GroupBy(static package => package.Id, StringComparer.Ordinal)
.Select(static group => group.OrderByDescending(package => package.Version, StringComparer.Ordinal).First())
.OrderBy(static package => package.Id, StringComparer.Ordinal)
.ToList();
var assemblyNames = document.Targets
.SelectMany(static target => target.Surfaces)
.Select(static surface => surface.AssemblyName)
.Where(static assemblyName => !string.IsNullOrWhiteSpace(assemblyName))
.Distinct(StringComparer.Ordinal)
.OrderBy(static assemblyName => assemblyName, StringComparer.Ordinal)
.ToList();
var defineConstants = string.Join(
";",
new[] { "$(DefineConstants)", "ENABLE_BINDING_SURFACE_COVERAGE" }
.Concat(document.Targets.Select(static target => CreateTargetCompileConstant(target.Id))));
var project = new XElement("Project",
new XElement("PropertyGroup",
new XElement("BindingSurfaceCoverageTarget", selectedTarget),
new XElement("DefineConstants", defineConstants)),
new XElement("ItemGroup",
new XElement("BundleResource",
new XAttribute("Include", Path.GetFullPath(coverageOutputPath)),
new XAttribute("Link", "binding-surface-coverage.generated.json"))),
new XElement("ItemGroup",
packages.Select(package =>
new XElement("PackageReference",
new XAttribute("Include", package.Id),
new XAttribute("Version", package.Version)))),
new XElement("ItemGroup",
assemblyNames.Select(assemblyName =>
new XElement("TrimmerRootAssembly",
new XAttribute("Include", assemblyName)))));
return new XDocument(project);
}
private static string CreateTargetCompileConstant(string targetId)
{
var builder = new StringBuilder("ENABLE_BINDING_SURFACE_COVERAGE_");
foreach (var character in targetId)
{
builder.Append(char.IsLetterOrDigit(character)
? char.ToUpperInvariant(character)
: '_');
}
return builder.ToString();
}
private static IReadOnlyList<BindingSurfaceCoverageTargetManifest> SelectTargets(
IReadOnlyList<BindingSurfaceCoverageTargetManifest> targets,
string selectedTarget)
{
if (string.Equals(selectedTarget, "all", StringComparison.OrdinalIgnoreCase))
{
return targets.OrderBy(static target => target.Id, StringComparer.Ordinal).ToList();
}
var target = targets.FirstOrDefault(target =>
string.Equals(target.Id, selectedTarget, StringComparison.OrdinalIgnoreCase));
if (target is null)
{
var available = string.Join(", ", targets.Select(static target => target.Id).OrderBy(static id => id, StringComparer.Ordinal));
throw new InvalidOperationException($"Unknown binding surface target '{selectedTarget}'. Available targets: all, {available}");
}
return [target];
}
private static IEnumerable<BindingSurfaceDescriptor> BuildSurfaces(
string target,
BindingSnapshot snapshot,
IReadOnlySet<string> helperFiles)
{
foreach (var boundType in snapshot.BoundTypes.Values)
{
yield return new BindingSurfaceDescriptor(
Target: target,
SurfaceId: $"{target}:type:{boundType.ComparisonKey}",
Kind: boundType.IsProtocol ? "protocol" : "bound-type",
TypeName: boundType.DisplayName,
RuntimeTypeName: boundType.DisplayName,
AssemblyName: ResolveAssemblyName(boundType.Namespace),
ObjectiveCName: boundType.ObjectiveCName,
ContainerKind: boundType.ContainerKind,
IsProtocol: boundType.IsProtocol,
IsStatic: boundType.IsStatic,
MemberName: null,
BindingAttribute: null,
BindingValue: null,
HasGetter: false,
HasSetter: false,
ParameterCount: 0,
ParameterTypes: [],
ReturnType: null,
UnderlyingType: null,
NativeSelectors: EmptySelectors,
SourceFile: boundType.SourceFile,
Signature: $"{boundType.ContainerKind} {boundType.Name}");
foreach (var member in boundType.Members.Values)
{
var bindingAttribute = member.BindingAttribute;
var bindingValue = member.BindingValue;
yield return new BindingSurfaceDescriptor(
Target: target,
SurfaceId: $"{target}:member:{boundType.ComparisonKey}:{member.Key}",
Kind: member.Kind,
TypeName: boundType.DisplayName,
RuntimeTypeName: boundType.DisplayName,
AssemblyName: ResolveAssemblyName(boundType.Namespace),
ObjectiveCName: boundType.ObjectiveCName,
ContainerKind: boundType.ContainerKind,
IsProtocol: boundType.IsProtocol,
IsStatic: member.IsStatic,
MemberName: member.Name,
BindingAttribute: bindingAttribute,
BindingValue: bindingValue,
HasGetter: member.HasGetter,
HasSetter: member.HasSetter,
ParameterCount: member.Parameters.Count,
ParameterTypes: member.Parameters.Select(static parameter => parameter.Type).ToList(),
ReturnType: member.ReturnType,
UnderlyingType: null,
NativeSelectors: BuildNativeSelectors(boundType, member).ToList(),
SourceFile: member.SourceFile,
Signature: member.Signature);
}
}
var usedDelegateNames = FindUsedDelegateNames(snapshot);
foreach (var delegateSurface in snapshot.Delegates.Values)
{
if (!IsDelegateUsedByBoundSurface(delegateSurface, usedDelegateNames))
{
continue;
}
yield return new BindingSurfaceDescriptor(
Target: target,
SurfaceId: $"{target}:delegate:{delegateSurface.ComparisonKey}",
Kind: "delegate",
TypeName: delegateSurface.DisplayName,
RuntimeTypeName: delegateSurface.DisplayName,
AssemblyName: ResolveAssemblyName(delegateSurface.Namespace),
ObjectiveCName: null,
ContainerKind: "delegate",
IsProtocol: false,
IsStatic: false,
MemberName: null,
BindingAttribute: null,
BindingValue: null,
HasGetter: false,
HasSetter: false,
ParameterCount: delegateSurface.Parameters.Count,
ParameterTypes: delegateSurface.Parameters.Select(static parameter => parameter.Type).ToList(),
ReturnType: delegateSurface.ReturnType,
UnderlyingType: null,
NativeSelectors: EmptySelectors,
SourceFile: delegateSurface.SourceFile,
Signature: delegateSurface.Signature);
}
foreach (var enumSurface in snapshot.Enums.Values)
{
yield return new BindingSurfaceDescriptor(
Target: target,
SurfaceId: $"{target}:enum:{enumSurface.ComparisonKey}",
Kind: "enum",
TypeName: enumSurface.DisplayName,
RuntimeTypeName: enumSurface.DisplayName,
AssemblyName: ResolveAssemblyName(enumSurface.Namespace),
ObjectiveCName: null,
ContainerKind: "enum",
IsProtocol: false,
IsStatic: false,
MemberName: null,
BindingAttribute: null,
BindingValue: null,
HasGetter: false,
HasSetter: false,
ParameterCount: 0,
ParameterTypes: [],
ReturnType: null,
UnderlyingType: enumSurface.UnderlyingType,
NativeSelectors: EmptySelectors,
SourceFile: enumSurface.SourceFile,
Signature: $"enum {enumSurface.Name}");
foreach (var enumMember in enumSurface.Members.Values)
{
yield return new BindingSurfaceDescriptor(
Target: target,
SurfaceId: $"{target}:enum-member:{enumSurface.ComparisonKey}:{enumMember.Name}",
Kind: "enum-member",
TypeName: enumSurface.DisplayName,
RuntimeTypeName: enumSurface.DisplayName,
AssemblyName: ResolveAssemblyName(enumSurface.Namespace),
ObjectiveCName: null,
ContainerKind: "enum",
IsProtocol: false,
IsStatic: false,
MemberName: enumMember.Name,
BindingAttribute: enumMember.FieldValue is null ? null : "Field",
BindingValue: enumMember.FieldValue,
HasGetter: false,
HasSetter: false,
ParameterCount: 0,
ParameterTypes: [],
ReturnType: null,
UnderlyingType: enumSurface.UnderlyingType,
NativeSelectors: EmptySelectors,
SourceFile: enumMember.SourceFile,
Signature: $"{enumSurface.Name}.{enumMember.Name}");
}
}
foreach (var manualItem in snapshot.ManualItems)
{
if (helperFiles.Contains(manualItem.SourceFile))
{
continue;
}
if (manualItem.ManualAttributes.Any(static attribute =>
string.Equals(attribute, "Internal", StringComparison.Ordinal)))
{
continue;
}
var (bindingAttribute, bindingValue) = ParseManualMemberKey(manualItem.MatchMemberKey);
yield return new BindingSurfaceDescriptor(
Target: target,
SurfaceId: CreateManualSurfaceId(target, manualItem),
Kind: manualItem.Kind,
TypeName: manualItem.TypeName,
RuntimeTypeName: manualItem.TypeName,
AssemblyName: ResolveAssemblyName(ExtractNamespace(manualItem.TypeName)),
ObjectiveCName: manualItem.ObjectiveCName,
ContainerKind: manualItem.ContainerKind ?? "manual",
IsProtocol: false,
IsStatic: manualItem.IsStatic,
MemberName: manualItem.MemberName,
BindingAttribute: bindingAttribute,
BindingValue: bindingValue,
HasGetter: manualItem.HasGetter,
HasSetter: manualItem.HasSetter,
ParameterCount: manualItem.ParameterTypes.Count,
ParameterTypes: manualItem.ParameterTypes,
ReturnType: manualItem.ReturnType,
UnderlyingType: manualItem.UnderlyingType,
NativeSelectors: BuildManualNativeSelectors(manualItem, bindingAttribute, bindingValue),
SourceFile: manualItem.SourceFile,
Signature: manualItem.Signature);
}
}
private static HashSet<string> FindUsedDelegateNames(BindingSnapshot snapshot)
{
var usedDelegateNames = new HashSet<string>(StringComparer.Ordinal);
foreach (var boundType in snapshot.BoundTypes.Values)
{
foreach (var member in boundType.Members.Values)
{
AddTypeNameVariants(usedDelegateNames, member.ReturnType);
foreach (var parameter in member.Parameters)
{
AddTypeNameVariants(usedDelegateNames, parameter.Type);
}
}
}
foreach (var manualItem in snapshot.ManualItems)
{
AddTypeNameVariants(usedDelegateNames, manualItem.ReturnType);
foreach (var parameterType in manualItem.ParameterTypes)
{
AddTypeNameVariants(usedDelegateNames, parameterType);
}
}
return usedDelegateNames;
}
private static bool IsDelegateUsedByBoundSurface(DelegateSurface delegateSurface, IReadOnlySet<string> usedDelegateNames) =>
usedDelegateNames.Contains(delegateSurface.Name) ||
usedDelegateNames.Contains(delegateSurface.DisplayName) ||
usedDelegateNames.Contains(delegateSurface.ComparisonKey);
private static void AddTypeNameVariants(HashSet<string> typeNames, string? typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return;
}
var normalizedTypeName = NormalizeCoverageTypeName(typeName);
if (string.IsNullOrWhiteSpace(normalizedTypeName))
{
return;
}
typeNames.Add(normalizedTypeName);
typeNames.Add(normalizedTypeName.Split('.').Last());
}
private static string NormalizeCoverageTypeName(string typeName)
{
var normalized = typeName
.Replace("global::", string.Empty, StringComparison.Ordinal)
.Trim()
.TrimEnd('?');
while (normalized.EndsWith("[]", StringComparison.Ordinal))
{
normalized = normalized[..^2].TrimEnd();
}
return normalized;
}
private static IEnumerable<BindingSurfaceDescriptor> BuildPublicHelperSurfaces(string target, IReadOnlyList<string> helperFiles)
{
foreach (var helperFile in helperFiles)
{
if (!File.Exists(helperFile))
{
continue;
}
var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(helperFile), path: helperFile);
var root = syntaxTree.GetCompilationUnitRoot();
foreach (var delegateDeclaration in root.DescendantNodes().OfType<DelegateDeclarationSyntax>())
{
if (!IsEffectivelyPublic(delegateDeclaration))
{
continue;
}
var namespaceName = GetContainingNamespace(delegateDeclaration);
var typeName = GetQualifiedTypeName(delegateDeclaration, delegateDeclaration.Identifier.Text);
var parameterTypes = GetParameterTypes(delegateDeclaration.ParameterList);
var signature = $"delegate {delegateDeclaration.Identifier.Text}({string.Join(", ", parameterTypes)}) -> {delegateDeclaration.ReturnType.WithoutTrivia()}";
yield return CreatePublicHelperSurface(
target,
helperFile,
typeName,
namespaceName,
surfaceId: $"{target}:manual-delegate:{typeName}:{CreateSurfaceIdKey(signature)}",
memberName: null,
signature: signature,
parameterTypes: parameterTypes,
returnType: delegateDeclaration.ReturnType.WithoutTrivia().ToString(),
underlyingType: null,
isStatic: false,
kind: "manual-delegate",
containerKind: "delegate");
}
foreach (var typeDeclaration in root.DescendantNodes().OfType<TypeDeclarationSyntax>())
{
if (!IsEffectivelyPublic(typeDeclaration))
{
continue;
}
var namespaceName = GetContainingNamespace(typeDeclaration);
var typeName = GetQualifiedTypeName(typeDeclaration, typeDeclaration.Identifier.Text);
var containerKind = GetTypeDeclarationKind(typeDeclaration);
yield return CreatePublicHelperSurface(
target,
helperFile,
typeName,
namespaceName,
surfaceId: $"{target}:manual-type:{typeName}",
memberName: null,
signature: $"{containerKind} {typeDeclaration.Identifier.Text}",
parameterTypes: [],
returnType: null,
underlyingType: null,
isStatic: typeDeclaration.Modifiers.Any(static modifier => modifier.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.StaticKeyword)),
kind: "manual-type",
containerKind: containerKind);
foreach (var property in typeDeclaration.Members.OfType<PropertyDeclarationSyntax>())
{
if (!IsPublic(property))
{
continue;
}
yield return CreatePublicHelperSurface(
target,
helperFile,
typeName,
namespaceName,
surfaceId: $"{target}:manual:{typeName}:{property.Identifier.Text}:{CreateSurfaceIdKey($"{property.Type.WithoutTrivia()} {property.Identifier.Text}")}",
memberName: property.Identifier.Text,
signature: $"{property.Type.WithoutTrivia()} {property.Identifier.Text} {{ get; }}",
parameterTypes: [],
returnType: property.Type.WithoutTrivia().ToString(),
underlyingType: null,
isStatic: property.Modifiers.Any(static modifier => modifier.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.StaticKeyword)),
kind: "manual-property",
containerKind: containerKind,
hasGetter: HasGetter(property.AccessorList),
hasSetter: HasSetter(property.AccessorList));
}
foreach (var indexer in typeDeclaration.Members.OfType<IndexerDeclarationSyntax>())
{
if (!IsPublic(indexer))
{
continue;
}
var parameterTypes = GetParameterTypes(indexer.ParameterList);
var signature = $"{indexer.Type.WithoutTrivia()} this[{string.Join(", ", parameterTypes)}] {{ get; }}";
yield return CreatePublicHelperSurface(
target,
helperFile,
typeName,
namespaceName,
surfaceId: $"{target}:manual-indexer:{typeName}:{CreateSurfaceIdKey(signature)}",
memberName: "Item",
signature: signature,
parameterTypes: parameterTypes,
returnType: indexer.Type.WithoutTrivia().ToString(),
underlyingType: null,
isStatic: false,
kind: "manual-indexer",
containerKind: containerKind,
hasGetter: HasGetter(indexer.AccessorList),
hasSetter: HasSetter(indexer.AccessorList));
}
foreach (var constructor in typeDeclaration.Members.OfType<ConstructorDeclarationSyntax>())
{
if (!IsPublic(constructor))
{
continue;
}
var parameterTypes = GetParameterTypes(constructor.ParameterList);
var signature = $"{constructor.Identifier.Text}({string.Join(", ", parameterTypes)})";
yield return CreatePublicHelperSurface(
target,
helperFile,
typeName,
namespaceName,
surfaceId: $"{target}:manual-constructor:{typeName}:{constructor.ParameterList.Parameters.Count}:{CreateSurfaceIdKey(signature)}",
memberName: ".ctor",
signature: signature,
parameterTypes: parameterTypes,
returnType: null,
underlyingType: null,
isStatic: false,
kind: "manual-constructor",
containerKind: containerKind);
}
foreach (var method in typeDeclaration.Members.OfType<MethodDeclarationSyntax>())
{
if (!IsPublic(method))
{
continue;
}
var parameterTypes = GetParameterTypes(method.ParameterList);
var signature = $"{method.Identifier.Text}({string.Join(", ", parameterTypes)}) -> {method.ReturnType.WithoutTrivia()}";
yield return CreatePublicHelperSurface(
target,
helperFile,
typeName,
namespaceName,
surfaceId: $"{target}:manual:{typeName}:{method.Identifier.Text}:{method.ParameterList.Parameters.Count}:{CreateSurfaceIdKey(signature)}",
memberName: method.Identifier.Text,
signature: signature,
parameterTypes: parameterTypes,
returnType: method.ReturnType.WithoutTrivia().ToString(),
underlyingType: null,
isStatic: method.Modifiers.Any(static modifier => modifier.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.StaticKeyword)),
kind: "manual-method",
containerKind: containerKind);
}
foreach (var field in typeDeclaration.Members.OfType<FieldDeclarationSyntax>())
{
if (!IsPublic(field))
{
continue;
}
foreach (var variable in field.Declaration.Variables)
{
yield return CreatePublicHelperSurface(
target,
helperFile,
typeName,
namespaceName,
surfaceId: $"{target}:manual-field:{typeName}:{variable.Identifier.Text}:{CreateSurfaceIdKey($"{field.Declaration.Type.WithoutTrivia()} {variable.Identifier.Text}")}",
memberName: variable.Identifier.Text,
signature: $"{field.Declaration.Type.WithoutTrivia()} {variable.Identifier.Text}",
parameterTypes: [],
returnType: field.Declaration.Type.WithoutTrivia().ToString(),
underlyingType: null,
isStatic: field.Modifiers.Any(static modifier => modifier.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.StaticKeyword)) ||
field.Modifiers.Any(static modifier => modifier.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.ConstKeyword)),
kind: "manual-field",
containerKind: containerKind);
}
}
}
foreach (var enumDeclaration in root.DescendantNodes().OfType<EnumDeclarationSyntax>())
{
if (!IsEffectivelyPublic(enumDeclaration))
{
continue;
}
var namespaceName = GetContainingNamespace(enumDeclaration);
var typeName = GetQualifiedTypeName(enumDeclaration, enumDeclaration.Identifier.Text);
yield return CreatePublicHelperSurface(
target,
helperFile,
typeName,
namespaceName,
surfaceId: $"{target}:manual-type:{typeName}",
memberName: null,
signature: $"enum {enumDeclaration.Identifier.Text}",
parameterTypes: [],
returnType: null,
underlyingType: enumDeclaration.BaseList?.Types.FirstOrDefault()?.Type.WithoutTrivia().ToString(),
isStatic: false,
kind: "manual-type",
containerKind: "enum");
}
}
}
private static BindingSurfaceDescriptor CreatePublicHelperSurface(
string target,
string helperFile,
string typeName,
string namespaceName,
string surfaceId,
string? memberName,
string signature,
IReadOnlyList<string> parameterTypes,
string? returnType,
string? underlyingType,
bool isStatic,
string? kind = null,
string? containerKind = null,
bool hasGetter = false,
bool hasSetter = false) =>
new(
Target: target,
SurfaceId: surfaceId,
Kind: kind ?? (memberName is null ? "manual" : "manual-member"),
TypeName: typeName,
RuntimeTypeName: typeName,
AssemblyName: ResolveAssemblyName(namespaceName),
ObjectiveCName: null,
ContainerKind: containerKind ?? "manual",
IsProtocol: false,
IsStatic: isStatic,
MemberName: memberName,
BindingAttribute: null,
BindingValue: null,
HasGetter: hasGetter,
HasSetter: hasSetter,
ParameterCount: parameterTypes.Count,
ParameterTypes: parameterTypes,
ReturnType: returnType,
UnderlyingType: underlyingType,
NativeSelectors: EmptySelectors,
SourceFile: helperFile,
Signature: signature);
private static IReadOnlyList<string> GetParameterTypes(BaseParameterListSyntax parameterList) =>
parameterList.Parameters
.Select(GetParameterType)
.ToList();
private static string GetParameterType(ParameterSyntax parameter)
{
var parameterType = parameter.Type?.WithoutTrivia().ToString() ?? "object";
var modifier = parameter.Modifiers.FirstOrDefault(static modifier =>
modifier.IsKind(SyntaxKind.RefKeyword) ||
modifier.IsKind(SyntaxKind.OutKeyword) ||
modifier.IsKind(SyntaxKind.InKeyword));
return modifier.RawKind == 0 ? parameterType : $"{modifier.Text} {parameterType}";
}
private static bool IsEffectivelyPublic(MemberDeclarationSyntax member) =>
IsPublic(member) &&
member.Ancestors().OfType<TypeDeclarationSyntax>().All(IsPublic);
private static bool IsPublic(MemberDeclarationSyntax member)
{
if (member.Modifiers.Any(static modifier => modifier.IsKind(SyntaxKind.PublicKeyword)))
{
return true;
}
return member.Parent is InterfaceDeclarationSyntax &&
!member.Modifiers.Any(static modifier =>
modifier.IsKind(SyntaxKind.PrivateKeyword) ||
modifier.IsKind(SyntaxKind.ProtectedKeyword) ||
modifier.IsKind(SyntaxKind.InternalKeyword));
}
private static bool HasGetter(AccessorListSyntax? accessorList) =>
accessorList is null ||
accessorList.Accessors.Any(static accessor => accessor.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.GetAccessorDeclaration));
private static bool HasSetter(AccessorListSyntax? accessorList) =>
accessorList?.Accessors.Any(static accessor => accessor.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.SetAccessorDeclaration)) == true;
private static string GetQualifiedTypeName(SyntaxNode node, string typeName)
{
var containingTypes = new List<string>();
for (var current = node.Parent; current is not null; current = current.Parent)
{
if (current is TypeDeclarationSyntax typeDeclaration)
{
containingTypes.Insert(0, typeDeclaration.Identifier.Text);
}
}
containingTypes.Add(typeName);
var nestedTypeName = string.Join("+", containingTypes);
var namespaceName = GetContainingNamespace(node);
return string.IsNullOrWhiteSpace(namespaceName)
? nestedTypeName
: $"{namespaceName}.{nestedTypeName}";
}
private static string GetTypeDeclarationKind(TypeDeclarationSyntax typeDeclaration) =>
typeDeclaration switch
{
ClassDeclarationSyntax classDeclaration when classDeclaration.Modifiers.Any(static modifier => modifier.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.StaticKeyword)) => "static class",
ClassDeclarationSyntax => "class",
StructDeclarationSyntax => "struct",
InterfaceDeclarationSyntax => "interface",
RecordDeclarationSyntax => "record",
_ => "type"
};
private static IEnumerable<BindingSurfaceNativeSelector> BuildNativeSelectors(BoundTypeSurface boundType, BindingMemberSurface member)
{
if (!string.Equals(member.BindingAttribute, "Export", StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(member.BindingValue))
{
yield break;
}
if (string.Equals(member.Kind, "property", StringComparison.Ordinal))
{
if (member.HasGetter)
{
yield return new BindingSurfaceNativeSelector(
member.GetterBind ?? member.BindingValue,
member.IsStatic,
boundType.IsProtocol);
}
if (member.HasSetter)
{
yield return new BindingSurfaceNativeSelector(
member.SetterBind ?? CreateSetterSelector(member.BindingValue),
member.IsStatic,
boundType.IsProtocol);
}
yield break;
}
yield return new BindingSurfaceNativeSelector(member.BindingValue, member.IsStatic, boundType.IsProtocol);
}
private static IReadOnlyList<BindingSurfaceNativeSelector> BuildManualNativeSelectors(
ManualSurfaceItem manualItem,
string? bindingAttribute,
string? bindingValue)
{
if (string.IsNullOrWhiteSpace(manualItem.ObjectiveCName))
{
return EmptySelectors;
}
if (!string.Equals(bindingAttribute, "Export", StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(bindingValue))
{
return EmptySelectors;
}
if (string.Equals(manualItem.Kind, "manual-property", StringComparison.Ordinal))
{
var selectors = new List<BindingSurfaceNativeSelector>();
if (manualItem.HasGetter)
{
selectors.Add(new BindingSurfaceNativeSelector(bindingValue!, manualItem.IsStatic, IsProtocol: false));
}
if (manualItem.HasSetter)
{
selectors.Add(new BindingSurfaceNativeSelector(CreateSetterSelector(bindingValue!), manualItem.IsStatic, IsProtocol: false));
}
return selectors;
}