-
-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathpatch-cocoa-bindings.cs
More file actions
544 lines (496 loc) · 21 KB
/
Copy pathpatch-cocoa-bindings.cs
File metadata and controls
544 lines (496 loc) · 21 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
#:package Microsoft.CodeAnalysis.CSharp@4.10.0
#:package Microsoft.CodeAnalysis.CSharp.Workspaces@4.10.0
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using CodeFormatter = Microsoft.CodeAnalysis.Formatting.Formatter;
if (args.Length != 1)
{
Console.Error.WriteLine("Usage: patch-cocoa-bindings.cs <path/to/ApiDefinitions.cs>");
return;
}
const string Header = @"// -----------------------------------------------------------------------------
// This file is auto-generated by Objective Sharpie and patched via the script
// at /scripts/patch-cocoa-bindings.cs. Do not edit this file directly.
// If changes are required, update the script instead.
// -----------------------------------------------------------------------------
";
var code = Header + File.ReadAllText(args[0]);
// Fix broken multi-line comments
code = Regex.Replace(code, @"(DEPRECATED_MSG_ATTRIBUTE\()\n\s*", "$1");
code = Regex.Replace(code, @"(DEPRECATED_MSG_ATTRIBUTE\([^)]*?)""\s*\r?\n\s*""", "$1 ");
var tree = CSharpSyntaxTree.ParseText(code);
var nodes = tree.GetCompilationUnitRoot()
.WithNamespace("Sentry.CocoaSdk")
.RemoveClass("CFunctions")
// Make enums, interfaces, and delegates internal
.AsInternal("Sentry*", "internal")
.WithAttribute("*Sentry*", "Internal")
// Adjust protocols (some are models)
.VerifyModel("SentryRedactOptions")
.VerifyModel("SentrySerializable")
.VerifyModel("SentrySpan")
.RemoveComment("SentryRRWebEvent", "[Model]")
.RemoveComment("SentryReplayBreadcrumbConverter", "[Model]")
.RemoveComment("SentryViewScreenshotProvider", "[Model]")
// Adjust base types
.WithAttribute("SentrySpan", "BaseType (typeof(NSObject))")
.WithAttribute("SentryRedactOptions", "BaseType (typeof(NSObject))")
// Remove INSCopying due to https://github.com/xamarin/xamarin-macios/issues/17130
.RemoveBaseType("INSCopying")
// Fix property-to-method conversions
.PropertyToMethod("Sentry*", "Serialize")
.PropertyToMethod("SentrySpan", "ToTraceHeader")
.PropertyToMethod("SentryTraceContext", "ToBaggage")
.PropertyToMethod("PrivateSentrySDKOnly", "Capture*")
// Verify the rest
.VerifyProperty("*Sentry*", "*", "MethodToProperty") // TODO: replace broad patterns with one-by-one verification
.VerifyProperty("SentryOptions", "*Targets", "StronglyTypedNSArray")
// Fix delegate argument names
.RenameParameter("NSError", "arg*", "error")
.RenameParameter("NSHttpUrlResponse", "arg*", "response")
.RenameParameter("SentryEvent", "arg*", "@event")
.RenameParameter("SentrySamplingContext", "arg*", "samplingContext")
.RenameParameter("SentryBreadcrumb", "arg*", "breadcrumb")
.RenameParameter("SentrySpan", "arg*", "span")
.RenameParameter("SentryLog", "arg*", "log")
.RenameParameter("SentryProfileOptions", "arg*", "options")
// Fix interface names
.RenameInterface("ISentrySerializable", "SentrySerializable")
.RenameInterface("ISentryRedactOptions", "SentryRedactOptions")
.RenameBaseType("ISentrySerializable", "SentrySerializable")
.RenameBaseType("ISentryRedactOptions", "SentryRedactOptions")
// Rename conflicting SentryRRWebEvent (protocol vs. interface)
.RenameProtocol("SentryRRWebEvent", "ISentryRRWebEvent")
// Adjust nullable return delegates (though broken until this is fixed: https://github.com/xamarin/xamarin-macios/issues/17109)
.WithAttribute("SentryBeforeBreadcrumbCallback", "return: NullAllowed")
.WithAttribute("SentryBeforeSendEventCallback", "return: NullAllowed")
.WithAttribute("SentryTracesSamplerCallback", "return: NullAllowed")
// For PrivateApiDefinitions.cs
.WithModifier("SentryScope", "partial")
// error CS0246: The type or namespace name 'iOS' could not be found
.RemoveAttribute("iOS")
// error CS0246: The type or namespace name 'Mac' could not be found
.RemoveAttribute("Mac")
// error CS0117: 'PlatformName' does not contain a definition for 'iOSAppExtension'
.RemoveAttribute("Unavailable")
// error CS0114: 'SentryXxx.IsEqual(NSObject?)' hides inherited member 'NSObject.IsEqual(NSObject?)'.
.RemoveMethod("Sentry*", "IsEqual")
// error CS0246: The type or namespace name '_NSZone' could not be found
.RemoveMethod("Sentry*", "CopyWithZone")
// SentryEnvelope* is not whitelisted
.RemoveMethod("PrivateSentrySDKOnly", "CaptureEnvelope")
.RemoveMethod("PrivateSentrySDKOnly", "EnvelopeWithData")
.RemoveMethod("PrivateSentrySDKOnly", "StoreEnvelope")
// deprecated
.RemoveMethod("Sentry*", "CaptureUserFeedback")
// SentryAppStartMeasurement is not whitelisted
.RemoveDelegate("SentryOnAppStartMeasurementAvailable")
// deprecated
.RemoveDelegate("SentryUserFeedbackConfigurationBlock")
// error CS0114: 'SentryXxx.Description' hides inherited member 'NSObject.Description'.
.RemoveProperty("Sentry*", "Description")
// SentryAppStartMeasurement is not whitelisted
.RemoveProperty("PrivateSentrySDKOnly", "*AppStartMeasurement*")
// SentryStructuredLogAttribute is not whitelisted
.RemoveProperty("SentryLog", "Attributes")
// deprecated
.RemoveProperty("SentryOptions", "ConfigureUserFeedback")
.KeepInterfaces(
"ISentryRRWebEvent",
"PrivateSentrySDKOnly",
"SentryAttachment",
"SentryBaggage",
"SentryBreadcrumb",
"SentryClient",
"SentryDebugImageProvider",
"SentryDebugMeta",
"SentryDsn",
"SentryEvent",
"SentryException",
"SentryExperimentalOptions",
"SentryFeedback",
"SentryFeedbackAPI",
"SentryFrame",
"SentryGeo",
"SentryHttpStatusCodeRange",
"SentryHub",
"SentryId",
"SentryLog",
"SentryLogger",
"SentryMeasurementUnit",
"SentryMeasurementUnitDuration",
"SentryMeasurementUnitFraction",
"SentryMeasurementUnitInformation",
"SentryMechanism",
"SentryMechanismMeta",
"SentryMessage",
"SentryNSError",
"SentryOptions",
"SentryProfileOptions",
"SentryRedactOptions",
"SentryReplayApi",
"SentryReplayBreadcrumbConverter",
"SentryReplayOptions",
"SentryRequest",
"SentryRRWebEvent",
"SentrySamplingContext",
"SentryScope",
"SentryScreenFrames",
"SentrySDK",
"SentrySerializable",
"SentrySpan",
"SentrySpanContext",
"SentrySpanId",
"SentryStacktrace",
"SentryThread",
"SentryTraceContext",
"SentryTraceHeader",
"SentryTransactionContext",
"SentryUser",
"SentryViewScreenshotOptions",
"SentryViewScreenshotProvider"
)
// Rename and retarget the experimental options property
.RenameProperty("SentryOptions", "_swiftExperimentalOptions", "Experimental")
.ChangePropertyType("SentryOptions", "Experimental", "SentryExperimentalOptions");
var formatted = CodeFormatter.Format(nodes, new AdhocWorkspace());
File.WriteAllText(args[0], formatted.ToFullString() + "\n");
internal static class FilterExtensions
{
public static CompilationUnitSyntax KeepInterfaces(
this CompilationUnitSyntax root,
params string[] names)
{
var nodes = root.DescendantNodes()
.OfType<InterfaceDeclarationSyntax>()
.Where(node => !names.Any(name => node.Identifier.Matches(name)));
return root.RemoveNodes(nodes, SyntaxRemoveOptions.KeepNoTrivia)!;
}
public static CompilationUnitSyntax WithNamespace(
this CompilationUnitSyntax root,
string name)
{
var node = SyntaxFactory.FileScopedNamespaceDeclaration(SyntaxFactory.ParseName(name));
return SyntaxFactory.CompilationUnit()
.WithUsings(root.Usings)
.AddMembers(node.WithMembers(root.Members));
}
private static CompilationUnitSyntax RemoveByPredicate<T>(
this CompilationUnitSyntax root,
Func<T, bool> predicate) where T : SyntaxNode
{
var nodes = root.DescendantNodes()
.OfType<T>()
.Where(node => predicate(node));
return root.RemoveNodes(nodes, SyntaxRemoveOptions.KeepNoTrivia)!;
}
public static CompilationUnitSyntax RemoveClass(
this CompilationUnitSyntax root,
string name)
{
return root.RemoveByPredicate<ClassDeclarationSyntax>(node => node.Identifier.Matches(name));
}
public static CompilationUnitSyntax RemoveDelegate(
this CompilationUnitSyntax root,
string name)
{
return root.RemoveByPredicate<DelegateDeclarationSyntax>(node => node.Identifier.Matches(name));
}
public static CompilationUnitSyntax RemoveAttribute(
this CompilationUnitSyntax root,
string name)
{
return root
.RemoveByPredicate<AttributeSyntax>(node => node.Name.Matches(name))
.RemoveByPredicate<AttributeListSyntax>(node => node.Attributes.Count == 0);
}
public static CompilationUnitSyntax RemoveBaseType(
this CompilationUnitSyntax root,
string name)
{
return root
.RemoveByPredicate<BaseTypeSyntax>(node => node.Type.Matches(name))
.RemoveByPredicate<BaseListSyntax>(node => node.Types.Count == 0);
}
public static CompilationUnitSyntax RemoveMethod(
this CompilationUnitSyntax root,
string type,
string name)
{
return root.RemoveByPredicate<MethodDeclarationSyntax>(node => node.Identifier.Matches(name) && node.HasParent(type));
}
public static CompilationUnitSyntax KeepMethods(
this CompilationUnitSyntax root,
string type,
params string[] names)
{
return root.RemoveByPredicate<MethodDeclarationSyntax>(node => !names.Any(name => node.Identifier.Matches(name)) && node.HasParent(type));
}
public static CompilationUnitSyntax RemoveProperty(
this CompilationUnitSyntax root,
string type,
string name)
{
return root.RemoveByPredicate<PropertyDeclarationSyntax>(node => node.Identifier.Matches(name) && node.HasParent(type));
}
public static CompilationUnitSyntax KeepProperties(
this CompilationUnitSyntax root,
string type,
params string[] names)
{
return root.RemoveByPredicate<PropertyDeclarationSyntax>(node => !names.Any(name => node.Identifier.Matches(name)) && node.HasParent(type));
}
public static CompilationUnitSyntax WithAttribute(
this CompilationUnitSyntax root,
string type,
string attribute)
{
var nodes = root.DescendantNodes()
.OfType<InterfaceDeclarationSyntax>()
.Where(node => node.Identifier.Matches(type) && !node.HasAttribute(attribute))
.Cast<SyntaxNode>()
.Concat(root.DescendantNodes()
.OfType<DelegateDeclarationSyntax>()
.Where(node => node.Identifier.Matches(type) && !node.HasAttribute(attribute)));
return root.ReplaceNodes(nodes, (node, _) => node.WithAttribute(attribute));
}
public static CompilationUnitSyntax AsInternal(
this CompilationUnitSyntax root,
string name,
string modifier)
{
var nodes = root.DescendantNodes()
.OfType<EnumDeclarationSyntax>()
.Where(node => node.Identifier.Matches(name));
return root.ReplaceNodes(nodes, (node, _) => node.WithModifier(modifier));
}
public static CompilationUnitSyntax WithModifier(
this CompilationUnitSyntax root,
string name,
string modifier)
{
var nodes = root.DescendantNodes()
.OfType<InterfaceDeclarationSyntax>()
.Where(node => node.Identifier.Matches(name));
return root.ReplaceNodes(nodes, (node, _) => node.WithModifier(modifier));
}
public static CompilationUnitSyntax VerifyModel(
this CompilationUnitSyntax root,
string name)
{
var nodes = root.DescendantNodes()
.OfType<InterfaceDeclarationSyntax>()
.Where(node => node.Identifier.Matches(name) && node.HasAttribute("Protocol"));
return root.ReplaceNodes(nodes, (node, _) => node.WithAttribute("Model").RemoveComment("[Model]"));
}
public static CompilationUnitSyntax RemoveComment(
this CompilationUnitSyntax root,
string name,
string comment)
{
var nodes = root.DescendantNodes()
.OfType<InterfaceDeclarationSyntax>()
.Where(node => node.Identifier.Matches(name) && node.HasComment(comment));
return root.ReplaceNodes(nodes, (node, _) => node.RemoveComment(comment));
}
public static CompilationUnitSyntax RenameBaseType(
this CompilationUnitSyntax root,
string from,
string to)
{
var nodes = root.DescendantNodes()
.OfType<BaseTypeSyntax>()
.Where(node => node.Type.Matches(from));
return root.ReplaceNodes(nodes, (node, _) => node.WithType(SyntaxFactory.ParseTypeName(to)));
}
public static CompilationUnitSyntax RenameInterface(
this CompilationUnitSyntax root,
string from,
string to)
{
var nodes = root.DescendantNodes()
.OfType<InterfaceDeclarationSyntax>()
.Where(node => node.Identifier.Matches(from));
return root.ReplaceNodes(nodes, (node, _) => node.WithIdentifier(SyntaxFactory.Identifier(to)));
}
public static CompilationUnitSyntax RenameProtocol(
this CompilationUnitSyntax root,
string from,
string to)
{
var nodes = root.DescendantNodes()
.OfType<InterfaceDeclarationSyntax>()
.Where(node => node.Identifier.Matches(from) && node.HasAttribute("Protocol"));
return root.ReplaceNodes(nodes, (node, _) => node.WithIdentifier(SyntaxFactory.Identifier(to)));
}
public static CompilationUnitSyntax RenameParameter(
this CompilationUnitSyntax root,
string type,
string from,
string to)
{
var nodes = root.DescendantNodes()
.OfType<ParameterSyntax>()
.Where(node => node.Identifier.Matches(from) && node.Type?.Matches(type) == true);
return root.ReplaceNodes(nodes, (node, _) => node.WithIdentifier(SyntaxFactory.Identifier(to)));
}
public static CompilationUnitSyntax PropertyToMethod(
this CompilationUnitSyntax root,
string type,
string name)
{
var nodes = root.DescendantNodes()
.OfType<PropertyDeclarationSyntax>()
.Where(node => node.Identifier.Matches(name) && node.HasParent(type) && node.HasAttribute("Verify", "MethodToProperty"));
return root.ReplaceNodes(nodes, (node, _) =>
{
var attributes = node.AttributeLists.RemoveAttribute("Verify", "MethodToProperty");
return SyntaxFactory.MethodDeclaration(node.Type, SyntaxFactory.Identifier(node.Identifier.Text))
.WithModifiers(node.Modifiers)
.WithAttributeLists(attributes)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
});
}
public static CompilationUnitSyntax VerifyProperty(
this CompilationUnitSyntax root,
string type,
string property,
string verify)
{
var nodes = root.DescendantNodes()
.OfType<PropertyDeclarationSyntax>()
.Where(node => node.Identifier.Matches(property) && node.HasParent(type));
return root.ReplaceNodes(nodes, (node, _) => node.WithAttributeLists(node.AttributeLists.RemoveAttribute("Verify", verify)));
}
public static CompilationUnitSyntax RenameProperty(
this CompilationUnitSyntax root,
string type,
string from,
string to)
{
var nodes = root.DescendantNodes()
.OfType<PropertyDeclarationSyntax>()
.Where(node => node.Identifier.Matches(from) && node.HasParent(type));
return root.ReplaceNodes(nodes, (node, _) => node.WithIdentifier(SyntaxFactory.Identifier(to)));
}
public static CompilationUnitSyntax ChangePropertyType(
this CompilationUnitSyntax root,
string type,
string property,
string newType)
{
var nodes = root.DescendantNodes()
.OfType<PropertyDeclarationSyntax>()
.Where(node => node.Identifier.Matches(property) && node.HasParent(type));
return root.ReplaceNodes(nodes, (node, _) => node.WithType(SyntaxFactory.ParseTypeName(newType)));
}
}
internal static class SyntaxNodeExtensions
{
public static bool HasParent(this SyntaxNode node, string name)
{
return node.Parent is TypeDeclarationSyntax parent && parent.Identifier.Matches(name);
}
public static bool HasAttribute(this SyntaxNode node, string attribute, string? arguments = null)
{
return node.GetAttributes()
.SelectMany(al => al.Attributes)
.Any(attr => attr.Name.Matches(attribute) && (arguments == null || attr.ArgumentList?.Arguments.ToString().Contains(arguments) == true));
}
public static SyntaxList<AttributeListSyntax> GetAttributes(this SyntaxNode node)
{
return node switch
{
BaseTypeDeclarationSyntax type => type.AttributeLists,
DelegateDeclarationSyntax del => del.AttributeLists,
MethodDeclarationSyntax method => method.AttributeLists,
PropertyDeclarationSyntax property => property.AttributeLists,
_ => throw new NotSupportedException(node.GetType().Name)
};
}
public static SyntaxNode WithAttribute(this SyntaxNode node, string attribute)
{
var attributes = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(SyntaxFactory.IdentifierName(attribute))));
var existingAttributes = node.GetAttributes();
var add = new Func<SyntaxNode, AttributeListSyntax, SyntaxNode>((n, attr) => n switch
{
BaseTypeDeclarationSyntax type => type.AddAttributeLists(attr),
DelegateDeclarationSyntax del => del.AddAttributeLists(attr),
MethodDeclarationSyntax method => method.AddAttributeLists(attr),
PropertyDeclarationSyntax property => property.AddAttributeLists(attr),
_ => throw new NotSupportedException(n.GetType().Name)
});
if (existingAttributes.Count > 0)
{
return add(node, attributes);
}
return add(node.WithLeadingTrivia(SyntaxFactory.TriviaList()), attributes.WithLeadingTrivia(node.GetLeadingTrivia()));
}
public static SyntaxNode WithModifier(this SyntaxNode node, string modifier)
{
var modifiers = SyntaxFactory.TokenList(SyntaxFactory.ParseToken(modifier));
return node switch
{
InterfaceDeclarationSyntax iface => iface.WithModifiers(modifiers),
EnumDeclarationSyntax enm => enm.WithModifiers(modifiers),
_ => throw new NotSupportedException(node.GetType().Name)
};
}
public static bool HasComment(this SyntaxNode node, string comment)
{
var trivia = node.GetLeadingTrivia();
return trivia.Any(t =>
t.IsKind(SyntaxKind.MultiLineCommentTrivia) &&
t.ToString().Contains(comment));
}
public static SyntaxNode RemoveComment(this SyntaxNode node, string comment)
{
var trivia = SyntaxFactory.TriviaList(
node.GetLeadingTrivia().Where(t =>
!(t.IsKind(SyntaxKind.MultiLineCommentTrivia) && t.ToString().Contains(comment))));
return node.WithLeadingTrivia(trivia);
}
}
internal static class AttributeListExtensions
{
public static SyntaxList<AttributeListSyntax> RemoveAttribute(this SyntaxList<AttributeListSyntax> lists, string attribute, string? arguments = null)
{
var attributes = lists
.Select(al => al.WithAttributes(
SyntaxFactory.SeparatedList(al.Attributes.Where(attr => !(attr.Name.ToString() == attribute && (arguments == null || attr.ArgumentList?.Arguments.ToString().Contains(arguments) == true))))
))
.Where(al => al.Attributes.Count > 0);
return SyntaxFactory.List(attributes);
}
}
internal static class WildcardExtensions
{
public static bool Matches(this NameSyntax syntax, string pattern)
{
return syntax.ToString().Matches(pattern);
}
public static bool Matches(this TypeSyntax syntax, string pattern)
{
return syntax.ToString().Matches(pattern);
}
public static bool Matches(this SyntaxToken token, string pattern)
{
return token.Text.Matches(pattern);
}
public static bool Matches(this string str, string pattern)
{
var negate = pattern.StartsWith('!');
var actual = pattern.TrimStart('!');
if (actual == str)
{
return !negate;
}
if (!actual.Contains('*') && !actual.Contains('?'))
{
return negate;
}
var regex = Regex.Escape(actual).Replace("\\*", ".*").Replace("\\?", ".");
return Regex.IsMatch(str, $"^{regex}$") != negate;
}
}