Skip to content

Commit da40eaf

Browse files
authored
[pigeon]add support for sealed classes in native interop (#13175)
fixes broken generation and unblocks sealed classes for native interop. Forward work for event channels
1 parent 8bd95a5 commit da40eaf

24 files changed

Lines changed: 4997 additions & 161 deletions

‎packages/pigeon/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 29.0.10
2+
3+
* [swift] [kotlin] Allows `sealed` classes in native interop files.
4+
15
## 29.0.9
26

37
* [kotlin] Stops generating unused JNI bindings for host API interfaces, significantly

‎packages/pigeon/example/app/ios/Runner/EventChannelMessages.g.swift‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ protocol PlatformEvent {
149149
}
150150

151151
/// Generated class from Pigeon that represents data sent in messages.
152-
struct IntEvent: PlatformEvent {
152+
struct IntEvent: PlatformEvent, Hashable, CustomStringConvertible {
153153
var data: Int64
154154

155155
// swift-format-ignore: AlwaysUseLowerCamelCase
@@ -183,7 +183,7 @@ struct IntEvent: PlatformEvent {
183183
}
184184

185185
/// Generated class from Pigeon that represents data sent in messages.
186-
struct StringEvent: PlatformEvent {
186+
struct StringEvent: PlatformEvent, Hashable, CustomStringConvertible {
187187
var data: String
188188

189189
// swift-format-ignore: AlwaysUseLowerCamelCase

‎packages/pigeon/lib/src/dart/dart_generator.dart‎

Lines changed: 66 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,7 @@ class DartGenerator extends StructuredGenerator<InternalDartOptions> {
870870
indent.write('${sealed}class ${classDefinition.name} $implements');
871871
indent.addScoped('{', '}', () {
872872
if (classDefinition.isSealed) {
873+
_writeSealedClassNativeInteropConversions(generatorOptions, indent, classDefinition);
873874
return;
874875
}
875876
_writeConstructor(indent, classDefinition);
@@ -958,7 +959,59 @@ class DartGenerator extends StructuredGenerator<InternalDartOptions> {
958959
});
959960
}
960961

962+
/// Writes the native interop conversions of a sealed class.
963+
///
964+
/// A sealed class has no native object of its own. Its subclasses implement
965+
/// `toJni` and `toFfi`, and `fromJni` and `fromFfi` pick the subclass from
966+
/// the runtime type of the native object.
967+
void _writeSealedClassNativeInteropConversions(
968+
InternalDartOptions generatorOptions,
969+
Indent indent,
970+
Class classDefinition,
971+
) {
972+
if (generatorOptions.useJni) {
973+
final String jniName = _JniType.fromClass(classDefinition).jniName;
974+
indent.writeln('$jniName toJni();');
975+
indent.newln();
976+
indent.writeScoped('static ${classDefinition.name}? fromJni($jniName? jniClass) {', '}', () {
977+
indent.writeScoped('if (jniClass == null) {', '}', () {
978+
indent.writeln('return null;');
979+
});
980+
for (final Class child in classDefinition.children) {
981+
final String childJniName = _JniType.fromClass(child).jniName;
982+
indent.writeScoped('if (jniClass.isA<$childJniName>($childJniName.type)) {', '}', () {
983+
indent.writeln('return ${child.name}.fromJni(jniClass.as($childJniName.type));');
984+
});
985+
}
986+
indent.writeln('throw ArgumentError.value(jniClass);');
987+
});
988+
}
989+
if (generatorOptions.useFfi) {
990+
if (generatorOptions.useJni) {
991+
indent.newln();
992+
}
993+
final String ffiName = _FfiType.fromClass(classDefinition).getFfiName();
994+
indent.writeln('$ffiName toFfi();');
995+
indent.newln();
996+
indent.writeScoped('static ${classDefinition.name}? fromFfi($ffiName? ffiClass) {', '}', () {
997+
indent.writeScoped('if (ffiClass == null) {', '}', () {
998+
indent.writeln('return null;');
999+
});
1000+
for (final Class child in classDefinition.children) {
1001+
final String childFfiName = _FfiType.fromClass(child).getFfiName();
1002+
indent.writeScoped('if ($childFfiName.isA(ffiClass)) {', '}', () {
1003+
indent.writeln('return ${child.name}.fromFfi($childFfiName.as(ffiClass));');
1004+
});
1005+
}
1006+
indent.writeln('throw ArgumentError.value(ffiClass);');
1007+
});
1008+
}
1009+
}
1010+
9611011
void _writeToJni(Indent indent, Class classDefinition) {
1012+
if (classDefinition.superClass != null) {
1013+
indent.writeln('@override');
1014+
}
9621015
indent.writeScoped('$_jniBridgePrefix.${classDefinition.name} toJni() {', '}', () {
9631016
indent.writeScoped('return $_jniBridgePrefix.${classDefinition.name} (', ');', () {
9641017
for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) {
@@ -971,6 +1024,9 @@ class DartGenerator extends StructuredGenerator<InternalDartOptions> {
9711024

9721025
void _writeToFfi(Indent indent, Class classDefinition) {
9731026
final _FfiType ffiClass = _FfiType.fromClass(classDefinition);
1027+
if (classDefinition.superClass != null) {
1028+
indent.writeln('@override');
1029+
}
9741030
indent.writeScoped('${ffiClass.getFfiName()} toFfi() {', '}', () {
9751031
final Iterable<NamedType> fields = getFieldsInSerializationOrder(classDefinition);
9761032
if (fields.isEmpty) {
@@ -2525,6 +2581,9 @@ ${api.name}({
25252581
}
25262582

25272583
void _writeJniCodec(Indent indent, Root root) {
2584+
// Sealed classes have no native object of their own, and the branches for
2585+
// their subclasses already match every value they can hold.
2586+
final Iterable<Class> concreteClasses = root.classes.where((Class c) => !c.isSealed);
25282587
indent.newln();
25292588
indent.format('''
25302589
class _PigeonJniCodec {
@@ -2581,7 +2640,7 @@ class _PigeonJniCodec {
25812640
res[readValue(entry.key)] = readValue(entry.value);
25822641
}
25832642
return res;
2584-
${root.classes.map((Class dataClass) {
2643+
${concreteClasses.map((Class dataClass) {
25852644
final _JniType jniType = _JniType.fromClass(dataClass);
25862645
return '''
25872646
} else if (value.isA<${jniType.jniName}>(
@@ -2675,7 +2734,7 @@ class _PigeonJniCodec {
26752734
.map<JObject?, JObject?>((k, v) =>
26762735
MapEntry(writeValue<JObject?>(k), writeValue<JObject?>(v)))
26772736
.toJMap() as T;
2678-
${root.classes.map((Class dataClass) {
2737+
${concreteClasses.map((Class dataClass) {
26792738
final _JniType jniType = _JniType.fromClass(dataClass);
26802739
return '''
26812740
} else if (value is ${jniType.type.baseName}) {
@@ -2750,6 +2809,9 @@ class _PigeonJniCodec {
27502809
}
27512810

27522811
void _writeFfiCodec(Indent indent, Root root) {
2812+
// Sealed classes have no native object of their own, and the branches for
2813+
// their subclasses already match every value they can hold.
2814+
final Iterable<Class> concreteClasses = root.classes.where((Class c) => !c.isSealed);
27532815
indent.newln();
27542816
indent.format('''
27552817
class _PigeonFfiCodec {
@@ -2791,7 +2853,7 @@ class _PigeonFfiCodec {
27912853
return res;
27922854
} else if ($_ffiBridgePrefix.${_classNamePrefix}NumberWrapper.isA(value)) {
27932855
return _convertNumberWrapperToDart($_ffiBridgePrefix.${_classNamePrefix}NumberWrapper.as(value));
2794-
${root.classes.map((Class dataClass) {
2856+
${concreteClasses.map((Class dataClass) {
27952857
final _FfiType ffiType = _FfiType.fromClass(dataClass);
27962858
return '''
27972859
} else if (${ffiType.getFfiName()}.isA(value)) {
@@ -2876,7 +2938,7 @@ class _PigeonFfiCodec {
28762938
res.setObject(writeValue(entry.value, generic: true), forKey: NSCopying.as(writeValue(entry.key, generic: true)));
28772939
}
28782940
return res as T;
2879-
${root.classes.map((Class dataClass) {
2941+
${concreteClasses.map((Class dataClass) {
28802942
final _FfiType ffiType = _FfiType.fromClass(dataClass);
28812943
return '''
28822944
} else if (value is ${ffiType.type.baseName}) {

‎packages/pigeon/lib/src/generator_tools.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import 'generator.dart';
1616
/// The current version of pigeon.
1717
///
1818
/// This must match the version in pubspec.yaml.
19-
const String pigeonVersion = '29.0.9';
19+
const String pigeonVersion = '29.0.10';
2020

2121
/// Default plugin package name.
2222
const String defaultPluginPackageName = 'dev.flutter.pigeon';

‎packages/pigeon/lib/src/pigeon_lib_internal.dart‎

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -436,14 +436,6 @@ void _errorOnSwiftFfiUnsupportedFeatures(
436436
}
437437
}
438438
for (final Class classDefinition in root.classes) {
439-
if (classDefinition.isSealed) {
440-
errors.add(
441-
Error(
442-
message:
443-
'Swift FFI does not support sealed classes yet (class "${classDefinition.name}"). $_moveToNonFfiFileSuggestion',
444-
),
445-
);
446-
}
447439
for (final NamedType field in classDefinition.fields) {
448440
// `description` has its own error for all Swift generation.
449441
if (field.name != 'description' && _swiftFfiReservedFieldNames.contains(field.name)) {
@@ -487,14 +479,6 @@ void _errorOnKotlinJniUnsupportedFeatures(List<Error> errors, Root root) {
487479
);
488480
}
489481
}
490-
for (final Class classDefinition in root.classes.where((Class c) => c.isSealed)) {
491-
errors.add(
492-
Error(
493-
message:
494-
'Kotlin JNI does not support sealed classes yet (class "${classDefinition.name}"). $_moveToNonJniFileSuggestion',
495-
),
496-
);
497-
}
498482
}
499483

500484
/// A [GeneratorAdapter] that generates the AST.

‎packages/pigeon/lib/src/swift/swift_generator.dart‎

Lines changed: 67 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,9 @@ class SwiftGenerator extends StructuredGenerator<InternalSwiftOptions> {
382382
}
383383

384384
void _writeFfiCodec(Indent indent, Root root) {
385+
// Sealed classes have no bridge object of their own, and the branches for
386+
// their subclasses already match every value they can hold.
387+
final Iterable<Class> concreteClasses = root.classes.where((Class c) => !c.isSealed);
385388
indent.newln();
386389
indent.format('''
387390
@objc class ${_classNamePrefix}PigeonInternalNull: NSObject {}
@@ -444,7 +447,7 @@ private class _PigeonFfiCodec {
444447
}
445448
if (value is NSString) {
446449
return value as! NSString
447-
${root.classes.map((Class dataClass) {
450+
${concreteClasses.map((Class dataClass) {
448451
return '''
449452
} else if (value is ${dataClass.name}Bridge) {
450453
return (value! as! ${dataClass.name}Bridge).toSwift();
@@ -511,7 +514,7 @@ private class _PigeonFfiCodec {
511514
}
512515
if (value is String) {
513516
return value as! NSString
514-
${root.classes.map((Class dataClass) {
517+
${concreteClasses.map((Class dataClass) {
515518
return '''
516519
} else if (value is ${dataClass.name}) {
517520
return ${dataClass.name}Bridge.fromSwift(value as? ${dataClass.name});
@@ -683,15 +686,21 @@ private class _PigeonFfiCodec {
683686
final bridge = useFfi ? 'Bridge' : '';
684687
final protocols = <String>[];
685688
if (useFfi) {
686-
protocols.add('NSObject');
687-
}
688-
if (classDefinition.superClass != null) {
689-
protocols.add(classDefinition.superClass!.name);
689+
// A subclass's bridge extends its sealed parent's bridge, so it can cross
690+
// wherever the sealed class can.
691+
protocols.add(
692+
classDefinition.superClass == null
693+
? 'NSObject'
694+
: '${classDefinition.superClass!.name}Bridge',
695+
);
690696
} else {
697+
if (classDefinition.superClass != null) {
698+
protocols.add(classDefinition.superClass!.name);
699+
}
691700
if (hashable) {
692701
protocols.add('Hashable');
693702
}
694-
if (customStringConvertible && !useFfi) {
703+
if (customStringConvertible) {
695704
protocols.add('CustomStringConvertible');
696705
}
697706
}
@@ -898,6 +907,7 @@ if (wrapped == nil) {
898907
_writeDataClassSignature(indent, classDefinition, useFfi: true, hashable: false);
899908
indent.writeScoped('', '}', () {
900909
if (classDefinition.isSealed) {
910+
_writeSealedFfiBridgeConversions(indent, classDefinition);
901911
return;
902912
}
903913
indent.writeln('// swift-format-ignore: AlwaysUseLowerCamelCase');
@@ -931,6 +941,53 @@ if (wrapped == nil) {
931941
});
932942
}
933943

944+
/// Writes the conversions of a sealed class's bridge.
945+
///
946+
/// Both pick the subclass by its runtime type. `toSwift` is static because an
947+
/// instance method would make each subclass bridge's own `toSwift()`
948+
/// ambiguous wherever the expected type isn't that subclass.
949+
void _writeSealedFfiBridgeConversions(Indent indent, Class classDefinition) {
950+
final String name = classDefinition.name;
951+
indent.writeln('// swift-format-ignore: AlwaysUseLowerCamelCase');
952+
indent.writeScoped(
953+
'static func fromSwift(_ ${varNamePrefix}Class: $name?) -> ${name}Bridge? {',
954+
'}',
955+
() {
956+
indent.writeScoped('switch ${varNamePrefix}Class {', '}', () {
957+
for (final Class child in classDefinition.children) {
958+
indent.writeln('case let ${varNamePrefix}value as ${child.name}:');
959+
indent.nest(1, () {
960+
indent.writeln('return ${child.name}Bridge.fromSwift(${varNamePrefix}value)');
961+
});
962+
}
963+
indent.writeln('default:');
964+
indent.nest(1, () {
965+
indent.writeln('return nil');
966+
});
967+
});
968+
},
969+
);
970+
indent.writeln('// swift-format-ignore: AlwaysUseLowerCamelCase');
971+
indent.writeScoped(
972+
'static func toSwift(_ ${varNamePrefix}bridge: ${name}Bridge?) -> $name? {',
973+
'}',
974+
() {
975+
indent.writeScoped('switch ${varNamePrefix}bridge {', '}', () {
976+
for (final Class child in classDefinition.children) {
977+
indent.writeln('case let ${varNamePrefix}value as ${child.name}Bridge:');
978+
indent.nest(1, () {
979+
indent.writeln('return ${varNamePrefix}value.toSwift()');
980+
});
981+
}
982+
indent.writeln('default:');
983+
indent.nest(1, () {
984+
indent.writeln('return nil');
985+
});
986+
});
987+
},
988+
);
989+
}
990+
934991
String _varToObjc(String varName, TypeDeclaration type, {bool forceNullable = false}) {
935992
final nullable = type.isNullable || forceNullable ? '?' : '';
936993
final getter = type.isNullable ? '!' : '';
@@ -1026,6 +1083,9 @@ if (wrapped == nil) {
10261083
: varName;
10271084
}
10281085
if (type.isClass) {
1086+
if (type.associatedClass!.isSealed) {
1087+
return '${type.baseName}Bridge.toSwift($varName)${type.isNullable || forceNullable ? '' : '!'}';
1088+
}
10291089
return '$checkNullish$varName${nullable.isEmpty ? '' : '!'}.toSwift()';
10301090
}
10311091
return varName;

0 commit comments

Comments
 (0)