Skip to content

Commit 269d65c

Browse files
authored
[swift2objc] feat:support swift tuples(return types) (dart-lang#3158)
1 parent 4a40b82 commit 269d65c

10 files changed

Lines changed: 901 additions & 6 deletions

File tree

‎pkgs/swift2objc/lib/src/ast/_core/shared/referred_type.dart‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,3 +174,63 @@ class InoutType extends AstNode implements ReferredType {
174174
visitor.visit(child);
175175
}
176176
}
177+
178+
/// Describes a reference to a Swift Tuple type (e.g., `(Int, String)`).
179+
class TupleType extends AstNode implements ReferredType {
180+
final List<TupleElement> elements;
181+
182+
@override
183+
bool get isObjCRepresentable => false;
184+
185+
@override
186+
String get swiftType {
187+
final elementStrings = elements
188+
.map((e) {
189+
final label = e.label != null ? '${e.label}: ' : '';
190+
return '$label${e.type.swiftType}';
191+
})
192+
.join(', ');
193+
return '($elementStrings)';
194+
}
195+
196+
@override
197+
bool _sameAs(ReferredType other) {
198+
if (other is! TupleType) return false;
199+
if (elements.length != other.elements.length) return false;
200+
for (var i = 0; i < elements.length; i++) {
201+
if (!elements[i].type.sameAs(other.elements[i].type)) return false;
202+
if (elements[i].label != other.elements[i].label) return false;
203+
}
204+
return true;
205+
}
206+
207+
@override
208+
ReferredType get aliasedType =>
209+
TupleType(elements.map((e) => e.aliasedElement).toList());
210+
211+
TupleType(this.elements);
212+
213+
@override
214+
String toString() => swiftType;
215+
216+
@override
217+
void visit(Visitation visitation) => visitation.visitTupleType(this);
218+
219+
@override
220+
void visitChildren(Visitor visitor) {
221+
super.visitChildren(visitor);
222+
for (final element in elements) {
223+
visitor.visit(element.type);
224+
}
225+
}
226+
}
227+
228+
class TupleElement {
229+
final String? label;
230+
final ReferredType type;
231+
232+
TupleElement({this.label, required this.type});
233+
234+
TupleElement get aliasedElement =>
235+
TupleElement(label: label, type: type.aliasedType);
236+
}

‎pkgs/swift2objc/lib/src/ast/visitor.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ abstract class Visitation {
108108
visitCompoundDeclaration(node);
109109
void visitTypealiasDeclaration(TypealiasDeclaration node) =>
110110
visitDeclaration(node);
111+
void visitTupleType(TupleType node) => visitReferredType(node);
111112

112113
/// Default behavior for all visit methods.
113114
void visitAstNode(AstNode node) => node.visitChildren(visitor);

‎pkgs/swift2objc/lib/src/generator/generators/class_generator.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ List<String> _generateClassProperty(PropertyDeclaration property) {
154154
if (property.isStatic) {
155155
header.write('static ');
156156
}
157+
157158
final prefixes = [if (property.unowned) 'unowned', if (property.weak) 'weak'];
158159

159160
var prefix = prefixes.isEmpty ? '' : '${prefixes.join(' ')} ';

‎pkgs/swift2objc/lib/src/parser/parsers/parse_type.dart‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,11 +129,50 @@ typedef PrefixParselet =
129129
Json token,
130130
TokenList fragments,
131131
) {
132-
final nextToken = fragments[0];
133-
if (_tokenId(nextToken) != 'text: )') {
134-
throw Exception('Tuples not supported yet, at ${token.path}');
132+
var currentFragments = fragments;
133+
final elements = <TupleElement>[];
134+
135+
while (currentFragments.isNotEmpty &&
136+
_tokenId(currentFragments[0]) != 'text: )') {
137+
String? label;
138+
139+
if (currentFragments.length > 1 &&
140+
_tokenId(currentFragments[1]) == 'text: :') {
141+
label = currentFragments[0]['spelling'].get<String>();
142+
currentFragments = currentFragments.slice(2);
143+
}
144+
145+
final (elementType, nextFragments) = parseType(
146+
context,
147+
symbolgraph,
148+
currentFragments,
149+
);
150+
151+
elements.add(TupleElement(label: label, type: elementType));
152+
currentFragments = nextFragments;
153+
154+
if (currentFragments.isNotEmpty &&
155+
_tokenId(currentFragments[0]) == 'text: ,') {
156+
currentFragments = currentFragments.slice(1);
157+
}
158+
}
159+
160+
if (currentFragments.isNotEmpty &&
161+
_tokenId(currentFragments[0]) == 'text: )') {
162+
currentFragments = currentFragments.slice(1);
163+
} else {
164+
throw Exception('Expected closing parenthesis for tuple at ${token.path}');
165+
}
166+
167+
if (elements.isEmpty) {
168+
return (voidType, currentFragments);
169+
}
170+
171+
if (elements.length == 1) {
172+
return (elements[0].type, currentFragments);
135173
}
136-
return (voidType, fragments.slice(1));
174+
175+
return (TupleType(elements), currentFragments);
137176
}
138177

139178
(ReferredType, TokenList) _inoutParselet(

‎pkgs/swift2objc/lib/src/transformer/_core/utils.dart‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import '../../ast/declarations/compounds/members/property_declaration.dart';
1111
import '../../ast/declarations/typealias_declaration.dart';
1212
import '../../transformer/_core/primitive_wrappers.dart';
1313
import '../transform.dart';
14+
import '../transformers/transform_referred_type.dart';
1415
import 'unique_namer.dart';
1516

1617
// TODO(https://github.com/dart-lang/native/issues/1358): These functions should
@@ -35,6 +36,11 @@ import 'unique_namer.dart';
3536
return (newValue, InoutType(newType));
3637
}
3738

39+
// Handle tuple types first
40+
if (type is TupleType) {
41+
return _wrapTupleValue(type, value, globalNamer, state);
42+
}
43+
3844
final (wrappedPrimitiveType, returnsWrappedPrimitive) =
3945
maybeGetPrimitiveWrapper(type, shouldWrapPrimitives, state);
4046
if (returnsWrappedPrimitive) {
@@ -100,6 +106,19 @@ import 'unique_namer.dart';
100106
}
101107
}
102108

109+
(String, ReferredType) _wrapTupleValue(
110+
TupleType tupleType,
111+
String tupleExpression,
112+
UniqueNamer globalNamer,
113+
TransformationState state,
114+
) {
115+
final wrapperType = transformReferredType(tupleType, globalNamer, state);
116+
final wrapperClass =
117+
(wrapperType as DeclaredType).declaration as ClassDeclaration;
118+
119+
return ('${wrapperClass.name}($tupleExpression)', wrapperType);
120+
}
121+
103122
(String value, ReferredType type) maybeUnwrapValue(
104123
ReferredType type,
105124
String value,

‎pkgs/swift2objc/lib/src/transformer/transform.dart‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ class TransformationState {
3333
final stubs = <Declaration>{};
3434

3535
late final UniqueNamer globalNamer;
36+
37+
// Map from tuple signature to generated wrapper class
38+
final tupleWrappers = <String, ClassDeclaration>{};
3639
}
3740

3841
/// Transforms the given declarations into the desired ObjC wrapped declarations
@@ -82,6 +85,7 @@ List<Declaration> transform(
8285
return [
8386
...transformedDeclarations,
8487
..._getPrimitiveWrapperClasses(state),
88+
...state.tupleWrappers.values,
8589
].sortedById();
8690
}
8791

@@ -127,7 +131,14 @@ Declaration? maybeTransformDeclaration(
127131

128132
// Now that the parents are transformed, this declaration should haven been
129133
// transformed, and will be in the cache.
130-
return state.map[declaration]!;
134+
// TODO(https://github.com/dart-lang/native/issues/1358): This is brittle. Switch naming to a transformer.
135+
return state.map[declaration] ??
136+
maybeTransformDeclaration(
137+
declaration,
138+
parentNamer,
139+
state,
140+
nested: true,
141+
);
131142
}
132143

133144
return switch (declaration) {

‎pkgs/swift2objc/lib/src/transformer/transformers/transform_referred_type.dart‎

Lines changed: 146 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,13 @@
44

55
import '../../ast/_core/interfaces/declaration.dart';
66
import '../../ast/_core/shared/referred_type.dart';
7+
import '../../ast/declarations/built_in/built_in_declaration.dart';
8+
import '../../ast/declarations/compounds/class_declaration.dart';
9+
import '../../ast/declarations/compounds/members/property_declaration.dart';
710
import '../../ast/declarations/typealias_declaration.dart';
811
import '../_core/primitive_wrappers.dart';
912
import '../_core/unique_namer.dart';
13+
import '../_core/utils.dart';
1014
import '../transform.dart';
1115

1216
// TODO(https://github.com/dart-lang/native/issues/1358): Refactor this as a
@@ -42,7 +46,9 @@ ReferredType transformReferredType(
4246

4347
if (type.isObjCRepresentable) return type;
4448

45-
if (type is GenericType) {
49+
if (type is TupleType) {
50+
return _transformTupleType(type, globalNamer, state);
51+
} else if (type is GenericType) {
4652
throw UnimplementedError('Generic types are not supported yet');
4753
} else if (type is DeclaredType) {
4854
final decl = type.declaration;
@@ -56,3 +62,142 @@ ReferredType transformReferredType(
5662
throw UnimplementedError('Unknown type: $type');
5763
}
5864
}
65+
66+
DeclaredType _transformTupleType(
67+
TupleType tupleType,
68+
UniqueNamer globalNamer,
69+
TransformationState state,
70+
) {
71+
final signature = tupleType.swiftType;
72+
73+
if (state.tupleWrappers.containsKey(signature)) {
74+
return state.tupleWrappers[signature]!.asDeclaredType;
75+
}
76+
77+
final className = _generateTupleClassName(tupleType, globalNamer, state);
78+
79+
final wrapperClass = _generateTupleWrapperClass(
80+
tupleType,
81+
className,
82+
globalNamer,
83+
state,
84+
);
85+
86+
return wrapperClass.asDeclaredType;
87+
}
88+
89+
String _generateTupleClassName(
90+
TupleType tuple,
91+
UniqueNamer globalNamer,
92+
TransformationState state,
93+
) {
94+
final parts = <String>[];
95+
96+
for (var i = 0; i < tuple.elements.length; i++) {
97+
final element = tuple.elements[i];
98+
if (element.label != null) {
99+
parts.add('${element.label}_${_sanitizeTypeName(element.type)}');
100+
} else {
101+
parts.add(_sanitizeTypeName(element.type));
102+
}
103+
}
104+
105+
return globalNamer.makeUnique('Tuple_${parts.join('_')}');
106+
}
107+
108+
String _sanitizeTypeName(ReferredType type) {
109+
return type.swiftType
110+
.replaceAll('<', '_')
111+
.replaceAll('?', 'Optional')
112+
.replaceAll('[', 'Array_')
113+
.replaceAll(RegExp(r'[^\w]'), '');
114+
}
115+
116+
ClassDeclaration _generateTupleWrapperClass(
117+
TupleType tupleType,
118+
String className,
119+
UniqueNamer globalNamer,
120+
TransformationState state,
121+
) {
122+
final wrappedInstanceProperty = PropertyDeclaration(
123+
id: 'tuple_${className}_wrappedInstance',
124+
name: 'wrappedInstance',
125+
source: null,
126+
availability: const [],
127+
type: tupleType,
128+
hasSetter: false,
129+
isConstant: false,
130+
hasObjCAnnotation: false,
131+
isStatic: false,
132+
throws: false,
133+
async: false,
134+
unowned: false,
135+
lazy: false,
136+
weak: false,
137+
);
138+
139+
final wrapperClass = ClassDeclaration(
140+
id: 'tuple_wrapper_$className',
141+
name: className,
142+
source: null,
143+
availability: const [],
144+
superClass: objectType,
145+
wrappedInstance: wrappedInstanceProperty,
146+
wrapperInitializer: buildWrapperInitializer(wrappedInstanceProperty),
147+
hasObjCAnnotation: true,
148+
);
149+
150+
state.tupleWrappers[tupleType.swiftType] = wrapperClass;
151+
152+
final properties = <PropertyDeclaration>[];
153+
154+
for (var i = 0; i < tupleType.elements.length; i++) {
155+
final element = tupleType.elements[i];
156+
final propertyName = element.label ?? '_$i';
157+
158+
final transformedType = transformReferredType(
159+
element.type,
160+
globalNamer,
161+
state,
162+
);
163+
164+
final property = PropertyDeclaration(
165+
id: 'tuple_${className}_$propertyName',
166+
name: propertyName,
167+
source: null,
168+
availability: const [],
169+
type: transformedType,
170+
hasSetter: true,
171+
isConstant: false,
172+
hasObjCAnnotation: true,
173+
isStatic: false,
174+
throws: false,
175+
async: false,
176+
unowned: false,
177+
lazy: false,
178+
weak: false,
179+
);
180+
181+
final accessor = element.label != null
182+
? 'wrappedInstance.${element.label}'
183+
: 'wrappedInstance.$i';
184+
185+
final (wrappedValue, _) = maybeWrapValue(
186+
element.type,
187+
accessor,
188+
globalNamer,
189+
state,
190+
);
191+
192+
property.getter = PropertyStatements([wrappedValue]);
193+
194+
final (unwrappedValue, _) = maybeUnwrapValue(transformedType, 'newValue');
195+
property.setter = PropertyStatements(['$accessor = $unwrappedValue']);
196+
197+
properties.add(property);
198+
}
199+
200+
wrapperClass.properties = properties;
201+
202+
return wrapperClass;
203+
}

0 commit comments

Comments
 (0)