forked from flutter/packages
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswift_generator.dart
2849 lines (2622 loc) · 95.8 KB
/
swift_generator.dart
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 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:graphs/graphs.dart';
import 'package:pub_semver/pub_semver.dart';
import 'ast.dart';
import 'functional.dart';
import 'generator.dart';
import 'generator_tools.dart';
import 'swift/templates.dart';
/// Documentation comment open symbol.
const String _docCommentPrefix = '///';
/// Documentation comment spec.
const DocumentCommentSpecification _docCommentSpec =
DocumentCommentSpecification(_docCommentPrefix);
const String _overflowClassName = '${classNamePrefix}CodecOverflow';
/// Options that control how Swift code will be generated.
class SwiftOptions {
/// Creates a [SwiftOptions] object
const SwiftOptions({
this.copyrightHeader,
this.fileSpecificClassNameComponent,
this.errorClassName,
this.includeErrorClass = true,
});
/// A copyright header that will get prepended to generated code.
final Iterable<String>? copyrightHeader;
/// A String to augment class names to avoid cross file collisions.
final String? fileSpecificClassNameComponent;
/// The name of the error class used for passing custom error parameters.
final String? errorClassName;
/// Whether to include the error class in generation.
///
/// This should only ever be set to false if you have another generated
/// Swift file in the same directory.
final bool includeErrorClass;
/// Creates a [SwiftOptions] from a Map representation where:
/// `x = SwiftOptions.fromList(x.toMap())`.
static SwiftOptions fromList(Map<String, Object> map) {
return SwiftOptions(
copyrightHeader: map['copyrightHeader'] as Iterable<String>?,
fileSpecificClassNameComponent:
map['fileSpecificClassNameComponent'] as String?,
errorClassName: map['errorClassName'] as String?,
includeErrorClass: map['includeErrorClass'] as bool? ?? true,
);
}
/// Converts a [SwiftOptions] to a Map representation where:
/// `x = SwiftOptions.fromList(x.toMap())`.
Map<String, Object> toMap() {
final Map<String, Object> result = <String, Object>{
if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!,
if (fileSpecificClassNameComponent != null)
'fileSpecificClassNameComponent': fileSpecificClassNameComponent!,
if (errorClassName != null) 'errorClassName': errorClassName!,
'includeErrorClass': includeErrorClass,
};
return result;
}
/// Overrides any non-null parameters from [options] into this to make a new
/// [SwiftOptions].
SwiftOptions merge(SwiftOptions options) {
return SwiftOptions.fromList(mergeMaps(toMap(), options.toMap()));
}
}
/// Options that control how Swift code will be generated for a specific
/// ProxyApi.
class SwiftProxyApiOptions {
/// Constructs a [SwiftProxyApiOptions].
const SwiftProxyApiOptions({
this.name,
this.import,
this.minIosApi,
this.minMacosApi,
this.supportsIos = true,
this.supportsMacos = true,
});
/// The name of the Swift class.
///
/// By default, generated code will use the same name as the class in the Dart
/// pigeon file.
final String? name;
/// The name of the module that needs to be imported to access the class.
final String? import;
/// The API version requirement for iOS.
///
/// This adds `@available` annotations on top of any constructor, field, or
/// method that references this element.
final String? minIosApi;
/// The API version requirement for macOS.
///
/// This adds `@available` annotations on top of any constructor, field, or
/// method that references this element.
final String? minMacosApi;
/// Whether this ProxyApi class compiles on iOS.
///
/// This adds `#` annotations on top of any constructor, field, or
/// method that references this element.
///
/// Defaults to true.
final bool supportsIos;
/// Whether this ProxyApi class compiles on macOS.
///
/// Defaults to true.
final bool supportsMacos;
}
/// Class that manages all Swift code generation.
class SwiftGenerator extends StructuredGenerator<SwiftOptions> {
/// Instantiates a Swift Generator.
const SwiftGenerator();
@override
void writeFilePrologue(
SwiftOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
if (generatorOptions.copyrightHeader != null) {
addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// ');
}
indent.writeln('// ${getGeneratedCodeWarning()}');
indent.writeln('// $seeAlsoWarning');
indent.newln();
}
@override
void writeFileImports(
SwiftOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
indent.writeln('import Foundation');
_writeProxyApiImports(indent, root.apis.whereType<AstProxyApi>());
indent.newln();
indent.format('''
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#else
#error("Unsupported platform.")
#endif''');
}
@override
void writeEnum(
SwiftOptions generatorOptions,
Root root,
Indent indent,
Enum anEnum, {
required String dartPackageName,
}) {
indent.newln();
addDocumentationComments(
indent, anEnum.documentationComments, _docCommentSpec);
indent.write('enum ${anEnum.name}: Int ');
indent.addScoped('{', '}', () {
enumerate(anEnum.members, (int index, final EnumMember member) {
addDocumentationComments(
indent, member.documentationComments, _docCommentSpec);
indent.writeln('case ${_camelCase(member.name)} = $index');
});
});
}
@override
void writeGeneralCodec(
SwiftOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
final String codecName = _getMessageCodecName(generatorOptions);
final String readerWriterName = '${codecName}ReaderWriter';
final String readerName = '${codecName}Reader';
final String writerName = '${codecName}Writer';
final List<EnumeratedType> enumeratedTypes =
getEnumeratedTypes(root, excludeSealedClasses: true).toList();
void writeDecodeLogic(EnumeratedType customType) {
indent.writeln('case ${customType.enumeration}:');
indent.nest(1, () {
if (customType.type == CustomTypes.customEnum) {
indent.writeln(
'let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)');
indent.writeScoped('if let enumResultAsInt = enumResultAsInt {', '}',
() {
indent.writeln(
'return ${customType.name}(rawValue: enumResultAsInt)');
});
indent.writeln('return nil');
} else {
indent.writeln(
'return ${customType.name}.fromList(self.readValue() as! [Any?])');
}
});
}
final EnumeratedType overflowClass = EnumeratedType(
_overflowClassName, maximumCodecFieldKey, CustomTypes.customClass);
if (root.requiresOverflowClass) {
indent.newln();
_writeCodecOverflowUtilities(
generatorOptions, root, indent, enumeratedTypes,
dartPackageName: dartPackageName);
}
indent.newln();
// Generate Reader
indent.write('private class $readerName: FlutterStandardReader ');
indent.addScoped('{', '}', () {
if (enumeratedTypes.isNotEmpty) {
indent.write('override func readValue(ofType type: UInt8) -> Any? ');
indent.addScoped('{', '}', () {
indent.write('switch type ');
indent.addScoped('{', '}', nestCount: 0, () {
for (final EnumeratedType customType in enumeratedTypes) {
if (customType.enumeration < maximumCodecFieldKey) {
writeDecodeLogic(customType);
}
}
if (root.requiresOverflowClass) {
writeDecodeLogic(overflowClass);
}
indent.writeln('default:');
indent.nest(1, () {
indent.writeln('return super.readValue(ofType: type)');
});
});
});
}
});
// Generate Writer
indent.newln();
indent.write('private class $writerName: FlutterStandardWriter ');
indent.addScoped('{', '}', () {
if (enumeratedTypes.isNotEmpty) {
indent.write('override func writeValue(_ value: Any) ');
indent.addScoped('{', '}', () {
indent.write('');
for (final EnumeratedType customType in enumeratedTypes) {
indent.add('if let value = value as? ${customType.name} ');
indent.addScoped('{', '} else ', () {
final String encodeString =
customType.type == CustomTypes.customClass
? 'toList()'
: 'rawValue';
final String valueString =
customType.enumeration < maximumCodecFieldKey
? 'value.$encodeString'
: 'wrap.toList()';
final int enumeration =
customType.enumeration < maximumCodecFieldKey
? customType.enumeration
: maximumCodecFieldKey;
if (customType.enumeration >= maximumCodecFieldKey) {
indent.writeln(
'let wrap = $_overflowClassName(type: ${customType.enumeration - maximumCodecFieldKey}, wrapped: value.$encodeString)');
}
indent.writeln('super.writeByte($enumeration)');
indent.writeln('super.writeValue($valueString)');
}, addTrailingNewline: false);
}
indent.addScoped('{', '}', () {
indent.writeln('super.writeValue(value)');
});
});
}
});
indent.newln();
// Generate ReaderWriter
indent
.write('private class $readerWriterName: FlutterStandardReaderWriter ');
indent.addScoped('{', '}', () {
indent.write(
'override func reader(with data: Data) -> FlutterStandardReader ');
indent.addScoped('{', '}', () {
indent.writeln('return $readerName(data: data)');
});
indent.newln();
indent.write(
'override func writer(with data: NSMutableData) -> FlutterStandardWriter ');
indent.addScoped('{', '}', () {
indent.writeln('return $writerName(data: data)');
});
});
indent.newln();
// Generate Codec
indent.write(
'class $codecName: FlutterStandardMessageCodec, @unchecked Sendable ');
indent.addScoped('{', '}', () {
indent.writeln(
'static let shared = $codecName(readerWriter: $readerWriterName())');
});
indent.newln();
if (root.containsEventChannel) {
indent.writeln(
'var ${_getMethodCodecVarName(generatorOptions)} = FlutterStandardMethodCodec(readerWriter: $readerWriterName());');
indent.newln();
}
}
void _writeDataClassSignature(
Indent indent,
Class classDefinition, {
bool private = false,
}) {
final String privateString = private ? 'private ' : '';
final String extendsString = classDefinition.superClass != null
? ': ${classDefinition.superClass!.name}'
: '';
if (classDefinition.isSwiftClass) {
indent.write(
'${privateString}class ${classDefinition.name}$extendsString ');
} else if (classDefinition.isSealed) {
indent.write('protocol ${classDefinition.name} ');
} else {
indent.write(
'${privateString}struct ${classDefinition.name}$extendsString ');
}
indent.addScoped('{', '', () {
final Iterable<NamedType> fields =
getFieldsInSerializationOrder(classDefinition);
if (classDefinition.isSwiftClass) {
_writeClassInit(indent, fields.toList());
}
for (final NamedType field in fields) {
addDocumentationComments(
indent, field.documentationComments, _docCommentSpec);
indent.write('var ');
_writeClassField(indent, field, addNil: !classDefinition.isSwiftClass);
indent.newln();
}
}, addTrailingNewline: false);
}
void _writeCodecOverflowUtilities(
SwiftOptions generatorOptions,
Root root,
Indent indent,
List<EnumeratedType> types, {
required String dartPackageName,
}) {
final NamedType overflowInt = NamedType(
name: 'type',
type: const TypeDeclaration(baseName: 'Int', isNullable: false));
final NamedType overflowObject = NamedType(
name: 'wrapped',
type: const TypeDeclaration(baseName: 'Object', isNullable: true));
final List<NamedType> overflowFields = <NamedType>[
overflowInt,
overflowObject,
];
final Class overflowClass =
Class(name: _overflowClassName, fields: overflowFields);
indent.newln();
_writeDataClassSignature(indent, overflowClass, private: true);
indent.addScoped('', '}', () {
writeClassEncode(
generatorOptions,
root,
indent,
overflowClass,
dartPackageName: dartPackageName,
);
indent.format('''
// swift-format-ignore: AlwaysUseLowerCamelCase
static func fromList(_ ${varNamePrefix}list: [Any?]) -> Any? {
let type = ${varNamePrefix}list[0] as! Int
let wrapped: Any? = ${varNamePrefix}list[1]
let wrapper = $_overflowClassName(
type: type,
wrapped: wrapped
)
return wrapper.unwrap()
}
''');
indent.writeScoped('func unwrap() -> Any? {', '}', () {
indent.format('''
if (wrapped == nil) {
return nil;
}
''');
indent.writeScoped('switch type {', '}', () {
for (int i = totalCustomCodecKeysAllowed; i < types.length; i++) {
indent.writeScoped('case ${i - totalCustomCodecKeysAllowed}:', '',
() {
if (types[i].type == CustomTypes.customClass) {
indent.writeln(
'return ${types[i].name}.fromList(wrapped as! [Any?]);');
} else if (types[i].type == CustomTypes.customEnum) {
indent.writeln(
'return ${types[i].name}(rawValue: wrapped as! Int);');
}
}, addTrailingNewline: false);
}
indent.writeScoped('default: ', '', () {
indent.writeln('return nil');
}, addTrailingNewline: false);
});
});
});
}
@override
void writeDataClass(
SwiftOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
final List<String> generatedComments = <String>[
' Generated class from Pigeon that represents data sent in messages.'
];
if (classDefinition.isSealed) {
generatedComments.add(
' This protocol should not be extended by any user class outside of the generated file.');
}
indent.newln();
addDocumentationComments(
indent, classDefinition.documentationComments, _docCommentSpec,
generatorComments: generatedComments);
_writeDataClassSignature(indent, classDefinition);
indent.writeScoped('', '}', () {
if (classDefinition.isSealed) {
return;
}
indent.newln();
writeClassDecode(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
writeClassEncode(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
});
}
void _writeClassInit(Indent indent, List<NamedType> fields) {
indent.writeScoped('init(', ')', () {
for (int i = 0; i < fields.length; i++) {
indent.write('');
_writeClassField(indent, fields[i]);
if (i == fields.length - 1) {
indent.newln();
} else {
indent.addln(',');
}
}
}, addTrailingNewline: false);
indent.addScoped(' {', '}', () {
for (final NamedType field in fields) {
_writeClassFieldInit(indent, field);
}
});
}
void _writeClassField(Indent indent, NamedType field, {bool addNil = true}) {
indent.add('${field.name}: ${_nullSafeSwiftTypeForDartType(field.type)}');
final String defaultNil = field.type.isNullable && addNil ? ' = nil' : '';
indent.add(defaultNil);
}
void _writeClassFieldInit(Indent indent, NamedType field) {
indent.writeln('self.${field.name} = ${field.name}');
}
@override
void writeClassEncode(
SwiftOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
indent.write('func toList() -> [Any?] ');
indent.addScoped('{', '}', () {
indent.write('return ');
indent.addScoped('[', ']', () {
// Follow swift-format style, which is to use a trailing comma unless
// there is only one element.
final String separator = classDefinition.fields.length > 1 ? ',' : '';
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
indent.writeln('${field.name}$separator');
}
});
});
}
@override
void writeClassDecode(
SwiftOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
final String className = classDefinition.name;
indent.writeln('// swift-format-ignore: AlwaysUseLowerCamelCase');
indent.write(
'static func fromList(_ ${varNamePrefix}list: [Any?]) -> $className? ');
indent.addScoped('{', '}', () {
enumerate(getFieldsInSerializationOrder(classDefinition),
(int index, final NamedType field) {
final String listValue = '${varNamePrefix}list[$index]';
_writeGenericCasting(
indent: indent,
value: listValue,
variableName: field.name,
fieldType: _swiftTypeForDartType(field.type),
type: field.type,
);
});
indent.newln();
indent.write('return ');
indent.addScoped('$className(', ')', () {
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
final String comma =
getFieldsInSerializationOrder(classDefinition).last == field
? ''
: ',';
// Force-casting nullable enums in maps doesn't work the same as other types.
// It needs soft-casting followed by force unwrapping.
final String forceUnwrapMapWithNullableEnums =
(field.type.baseName == 'Map' &&
!field.type.isNullable &&
field.type.typeArguments
.any((TypeDeclaration type) => type.isEnum))
? '!'
: '';
indent.writeln(
'${field.name}: ${field.name}$forceUnwrapMapWithNullableEnums$comma');
}
});
});
}
@override
void writeApis(
SwiftOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
if (root.apis.any((Api api) =>
api is AstHostApi &&
api.methods.any((Method it) => it.isAsynchronous))) {
indent.newln();
}
super.writeApis(generatorOptions, root, indent,
dartPackageName: dartPackageName);
}
/// Writes the code for a flutter [Api], [api].
/// Example:
/// class Foo {
/// private let binaryMessenger: FlutterBinaryMessenger
/// init(binaryMessenger: FlutterBinaryMessenger) {...}
/// func add(x: Int32, y: Int32, completion: @escaping (Int32?) -> Void) {...}
/// }
@override
void writeFlutterApi(
SwiftOptions generatorOptions,
Root root,
Indent indent,
AstFlutterApi api, {
required String dartPackageName,
}) {
const List<String> generatedComments = <String>[
' Generated protocol from Pigeon that represents Flutter messages that can be called from Swift.'
];
addDocumentationComments(indent, api.documentationComments, _docCommentSpec,
generatorComments: generatedComments);
indent.addScoped('protocol ${api.name}Protocol {', '}', () {
for (final Method func in api.methods) {
addDocumentationComments(
indent, func.documentationComments, _docCommentSpec);
indent.writeln(_getMethodSignature(
name: func.name,
parameters: func.parameters,
returnType: func.returnType,
errorTypeName: _getErrorClassName(generatorOptions),
isAsynchronous: true,
swiftFunction: func.swiftFunction,
getParameterName: _getSafeArgumentName,
));
}
});
indent.write('class ${api.name}: ${api.name}Protocol ');
indent.addScoped('{', '}', () {
indent.writeln('private let binaryMessenger: FlutterBinaryMessenger');
indent.writeln('private let messageChannelSuffix: String');
indent.write(
'init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") ');
indent.addScoped('{', '}', () {
indent.writeln('self.binaryMessenger = binaryMessenger');
indent.writeln(
r'self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : ""');
});
final String codecName = _getMessageCodecName(generatorOptions);
indent.write('var codec: $codecName ');
indent.addScoped('{', '}', () {
indent.writeln('return $codecName.shared');
});
for (final Method func in api.methods) {
addDocumentationComments(
indent, func.documentationComments, _docCommentSpec);
_writeFlutterMethod(
indent,
generatorOptions: generatorOptions,
name: func.name,
channelName:
'${makeChannelName(api, func, dartPackageName)}\\(messageChannelSuffix)',
parameters: func.parameters,
returnType: func.returnType,
swiftFunction: func.swiftFunction,
);
}
});
}
/// Write the swift code that represents a host [Api], [api].
/// Example:
/// protocol Foo {
/// Int32 add(x: Int32, y: Int32)
/// }
@override
void writeHostApi(
SwiftOptions generatorOptions,
Root root,
Indent indent,
AstHostApi api, {
required String dartPackageName,
}) {
final String apiName = api.name;
const List<String> generatedComments = <String>[
' Generated protocol from Pigeon that represents a handler of messages from Flutter.'
];
addDocumentationComments(indent, api.documentationComments, _docCommentSpec,
generatorComments: generatedComments);
indent.write('protocol $apiName ');
indent.addScoped('{', '}', () {
for (final Method method in api.methods) {
addDocumentationComments(
indent, method.documentationComments, _docCommentSpec);
indent.writeln(_getMethodSignature(
name: method.name,
parameters: method.parameters,
returnType: method.returnType,
errorTypeName: 'Error',
isAsynchronous: method.isAsynchronous,
swiftFunction: method.swiftFunction,
));
}
});
indent.newln();
indent.writeln(
'$_docCommentPrefix Generated setup class from Pigeon to handle messages through the `binaryMessenger`.');
indent.write('class ${apiName}Setup ');
indent.addScoped('{', '}', () {
indent.writeln(
'static var codec: FlutterStandardMessageCodec { ${_getMessageCodecName(generatorOptions)}.shared }');
indent.writeln(
'$_docCommentPrefix Sets up an instance of `$apiName` to handle messages through the `binaryMessenger`.');
indent.write(
'static func setUp(binaryMessenger: FlutterBinaryMessenger, api: $apiName?, messageChannelSuffix: String = "") ');
indent.addScoped('{', '}', () {
indent.writeln(
r'let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : ""');
for (final Method method in api.methods) {
_writeHostMethodMessageHandler(
indent,
name: method.name,
channelName:
'${makeChannelName(api, method, dartPackageName)}\\(channelSuffix)',
parameters: method.parameters,
returnType: method.returnType,
isAsynchronous: method.isAsynchronous,
swiftFunction: method.swiftFunction,
documentationComments: method.documentationComments,
);
}
});
});
}
@override
void writeInstanceManager(
SwiftOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
indent.format(instanceManagerFinalizerDelegateTemplate(generatorOptions));
indent.format(instanceManagerFinalizerTemplate(generatorOptions));
indent.format(instanceManagerTemplate(generatorOptions));
}
@override
void writeInstanceManagerApi(
SwiftOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
final String instanceManagerApiName =
'${swiftInstanceManagerClassName(generatorOptions)}Api';
final String removeStrongReferenceName =
makeRemoveStrongReferenceChannelName(
dartPackageName,
);
indent.writeScoped('private class $instanceManagerApiName {', '}', () {
addDocumentationComments(
indent,
<String>[' The codec used for serializing messages.'],
_docCommentSpec,
);
indent.writeln(
'var codec: FlutterStandardMessageCodec { ${_getMessageCodecName(generatorOptions)}.shared }',
);
indent.newln();
addDocumentationComments(
indent,
<String>[' Handles sending and receiving messages with Dart.'],
_docCommentSpec,
);
indent.writeln('unowned let binaryMessenger: FlutterBinaryMessenger');
indent.newln();
indent.writeScoped(
'init(binaryMessenger: FlutterBinaryMessenger) {',
'}',
() {
indent.writeln('self.binaryMessenger = binaryMessenger');
},
);
indent.newln();
addDocumentationComments(
indent,
<String>[
' Sets up an instance of `$instanceManagerApiName` to handle messages through the `binaryMessenger`.',
],
_docCommentSpec,
);
indent.writeScoped(
'static func setUpMessageHandlers(binaryMessenger: FlutterBinaryMessenger, instanceManager: ${swiftInstanceManagerClassName(generatorOptions)}?) {',
'}',
() {
indent.writeln(
'let codec = ${_getMessageCodecName(generatorOptions)}.shared',
);
const String setHandlerCondition =
'let instanceManager = instanceManager';
_writeHostMethodMessageHandler(
indent,
name: 'removeStrongReference',
channelName: removeStrongReferenceName,
parameters: <Parameter>[
Parameter(
name: 'identifier',
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
),
),
],
returnType: const TypeDeclaration.voidDeclaration(),
swiftFunction: 'method(withIdentifier:)',
setHandlerCondition: setHandlerCondition,
isAsynchronous: false,
onCreateCall: (
List<String> safeArgNames, {
required String apiVarName,
}) {
return 'let _: AnyObject? = try instanceManager.removeInstance(${safeArgNames.single})';
},
);
_writeHostMethodMessageHandler(
indent,
name: 'clear',
channelName: makeClearChannelName(dartPackageName),
parameters: <Parameter>[],
returnType: const TypeDeclaration.voidDeclaration(),
setHandlerCondition: setHandlerCondition,
swiftFunction: null,
isAsynchronous: false,
onCreateCall: (
List<String> safeArgNames, {
required String apiVarName,
}) {
return 'try instanceManager.removeAllObjects()';
},
);
},
);
indent.newln();
addDocumentationComments(
indent,
<String>[
' Sends a message to the Dart `InstanceManager` to remove the strong reference of the instance associated with `identifier`.',
],
_docCommentSpec,
);
_writeFlutterMethod(
indent,
generatorOptions: generatorOptions,
name: 'removeStrongReference',
parameters: <Parameter>[
Parameter(
name: 'identifier',
type: const TypeDeclaration(baseName: 'int', isNullable: false),
)
],
returnType: const TypeDeclaration.voidDeclaration(),
channelName: removeStrongReferenceName,
swiftFunction: null,
);
});
}
@override
void writeProxyApiBaseCodec(
SwiftOptions generatorOptions,
Root root,
Indent indent,
) {
final Iterable<AstProxyApi> allProxyApis =
root.apis.whereType<AstProxyApi>();
_writeProxyApiRegistrar(
indent,
generatorOptions: generatorOptions,
allProxyApis: allProxyApis,
);
final String filePrefix =
generatorOptions.fileSpecificClassNameComponent ?? '';
final String registrarName = proxyApiRegistrarName(generatorOptions);
indent.writeScoped(
'private class ${proxyApiReaderWriterName(generatorOptions)}: FlutterStandardReaderWriter {',
'}',
() {
indent.writeln(
'unowned let pigeonRegistrar: $registrarName',
);
indent.newln();
indent.writeScoped(
'private class $filePrefix${classNamePrefix}ProxyApiCodecReader: ${_getMessageCodecName(generatorOptions)}Reader {',
'}',
() {
indent.writeln('unowned let pigeonRegistrar: $registrarName');
indent.newln();
indent.writeScoped(
'init(data: Data, pigeonRegistrar: $registrarName) {',
'}',
() {
indent.writeln('self.pigeonRegistrar = pigeonRegistrar');
indent.writeln('super.init(data: data)');
},
);
indent.newln();
indent.writeScoped(
'override func readValue(ofType type: UInt8) -> Any? {',
'}',
() {
indent.format(
'''
switch type {
case $proxyApiCodecInstanceManagerKey:
let identifier = self.readValue()
let instance: AnyObject? = pigeonRegistrar.instanceManager.instance(
forIdentifier: identifier is Int64 ? identifier as! Int64 : Int64(identifier as! Int32))
return instance
default:
return super.readValue(ofType: type)
}''',
);
},
);
},
);
indent.newln();
indent.writeScoped(
'private class $filePrefix${classNamePrefix}ProxyApiCodecWriter: ${_getMessageCodecName(generatorOptions)}Writer {',
'}',
() {
indent.writeln(
'unowned let pigeonRegistrar: $registrarName',
);
indent.newln();
indent.writeScoped(
'init(data: NSMutableData, pigeonRegistrar: $registrarName) {',
'}',
() {
indent.writeln('self.pigeonRegistrar = pigeonRegistrar');
indent.writeln('super.init(data: data)');
},
);
indent.newln();
indent.writeScoped(
'override func writeValue(_ value: Any) {',
'}',
() {
final List<String> nonProxyApiTypes = <String>[
'[Any]',
'Bool',
'Data',
'[AnyHashable: Any]',
'Double',
'FlutterStandardTypedData',
'Int64',
'String',
...root.enums.map((Enum anEnum) => anEnum.name),
];
final String isBuiltinExpression = nonProxyApiTypes
.map((String swiftType) => 'value is $swiftType')
.join(' || ');
// Non ProxyApi types are checked first to prevent the scenario
// where a client wraps the `NSObject` class which all the
// classes above extend.
indent.writeScoped('if $isBuiltinExpression {', '}', () {
indent.writeln('super.writeValue(value)');
indent.writeln('return');
});
indent.newln();
// Sort APIs where edges are an API's super class and interfaces.
//
// This sorts the APIs to have child classes be listed before their parent
// classes. This prevents the scenario where a method might return the super