Skip to content

Commit 898141e

Browse files
authored
[swift2objc] feat: support operator overloading (dart-lang#2972)
1 parent 0e06fcf commit 898141e

13 files changed

Lines changed: 436 additions & 37 deletions

File tree

‎pkgs/swift2objc/lib/src/ast/declarations/built_in/built_in_declaration.dart‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ const _objectDecl = BuiltInDeclaration(
4242
name: 'NSObject',
4343
);
4444
const _stringDecl = BuiltInDeclaration(id: 's:SS', name: 'String');
45+
const _selfDecl = BuiltInDeclaration(id: '', name: 'Self');
4546

4647
final objectType = _objectDecl.asDeclaredType;
4748
final stringType = _stringDecl.asDeclaredType;
@@ -50,6 +51,7 @@ final floatType = _floatDecl.asDeclaredType;
5051
final doubleType = _doubleDecl.asDeclaredType;
5152
final boolType = _boolDecl.asDeclaredType;
5253
final voidType = _voidDecl.asDeclaredType;
54+
final selfType = _selfDecl.asDeclaredType;
5355

5456
const builtInDeclarations = [
5557
_boolDecl,

‎pkgs/swift2objc/lib/src/ast/declarations/compounds/members/method_declaration.dart‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ class MethodDeclaration extends AstNode
5454
bool isStatic;
5555

5656
bool mutating;
57+
bool isOperator = false;
5758

5859
String get fullName => [name, for (final p in params) p.name].join(':');
5960

@@ -72,6 +73,7 @@ class MethodDeclaration extends AstNode
7273
this.throws = false,
7374
this.async = false,
7475
this.mutating = false,
76+
this.isOperator = false,
7577
}) : assert(!isStatic || !isOverriding);
7678

7779
@override

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,13 @@ import '../../ast/_core/interfaces/can_throw.dart';
1010
import '../../ast/_core/interfaces/declaration.dart';
1111
import '../../ast/_core/shared/parameter.dart';
1212

13-
String generateParameters(List<Parameter> params) {
13+
String generateParameters(List<Parameter> params, {bool isOperator = false}) {
1414
return params
1515
.map((param) {
1616
final String labels;
17-
if (param.internalName != null) {
17+
if (isOperator) {
18+
labels = param.internalName ?? param.name;
19+
} else if (param.internalName != null) {
1820
labels = '${param.name} ${param.internalName}';
1921
} else {
2022
labels = param.name;

‎pkgs/swift2objc/lib/src/parser/parsers/declaration_parsers/parse_function_declaration.dart‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,13 @@ MethodDeclaration parseMethodDeclaration(
4040
ParsedSymbol symbol,
4141
ParsedSymbolgraph symbolgraph, {
4242
bool isStatic = false,
43+
bool isOperator = false,
4344
}) {
4445
final info = parseFunctionInfo(
4546
context,
4647
symbol.json['declarationFragments'],
4748
symbolgraph,
49+
isOperator: isOperator,
4850
);
4951
return MethodDeclaration(
5052
id: parseSymbolId(symbol.json),
@@ -58,6 +60,7 @@ MethodDeclaration parseMethodDeclaration(
5860
throws: info.throws,
5961
async: info.async,
6062
mutating: info.mutating,
63+
isOperator: isOperator,
6164
);
6265
}
6366

@@ -73,6 +76,7 @@ ParsedFunctionInfo parseFunctionInfo(
7376
Json declarationFragments,
7477
ParsedSymbolgraph symbolgraph, {
7578
bool isEnumCase = false,
79+
bool isOperator = false,
7680
}) {
7781
// `declarationFragments` describes each part of the function declaration,
7882
// things like the `func` keyword, brackets, spaces, etc.
@@ -111,6 +115,15 @@ ParsedFunctionInfo parseFunctionInfo(
111115
final keyword = maybeConsume('keyword');
112116
if (keyword != null) {
113117
if (keyword == 'func' || keyword == 'init' || keyword == 'case') {
118+
if (keyword == 'func' && isOperator) {
119+
final ws1 = maybeConsume('text');
120+
final op = maybeConsume('identifier');
121+
final ws2 = maybeConsume('text');
122+
123+
if (ws1 == null || op == null || ws2 == null) {
124+
throw malformedInitializerException;
125+
}
126+
}
114127
break;
115128
} else {
116129
prefixAnnotations.add(keyword);
@@ -146,6 +159,14 @@ ParsedFunctionInfo parseFunctionInfo(
146159
if (sep != ':') {
147160
throw malformedInitializerException;
148161
}
162+
} else if (isOperator) {
163+
internalParam = maybeConsume('internalParam');
164+
if (internalParam == null) {
165+
throw malformedInitializerException;
166+
}
167+
if (maybeConsume('text') != ':') {
168+
throw malformedInitializerException;
169+
}
149170
} else if (!isEnumCase) {
150171
// Enum cases are allowed to omit both param names. Other param lists
151172
// must at least specify the external name.
@@ -156,8 +177,8 @@ ParsedFunctionInfo parseFunctionInfo(
156177

157178
parameters.add(
158179
Parameter(
159-
name: externalParam ?? '',
160-
internalName: internalParam,
180+
name: isOperator ? (internalParam ?? '') : (externalParam ?? ''),
181+
internalName: isOperator ? null : internalParam,
161182
type: type,
162183
),
163184
);

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,13 @@ Declaration parseDeclaration(
8282
symbolgraph,
8383
isStatic: true,
8484
),
85+
'swift.func.op' => parseMethodDeclaration(
86+
context,
87+
parsedSymbol,
88+
symbolgraph,
89+
isStatic: true,
90+
isOperator: true,
91+
),
8592
'swift.property' => parsePropertyDeclaration(
8693
context,
8794
parsedSymbol,
@@ -120,11 +127,6 @@ Declaration parseDeclaration(
120127
parsedSymbol,
121128
symbolgraph,
122129
),
123-
'swift.func.op' => throw UnsupportedSymbolException(
124-
'Operator overloading is not supported yet: '
125-
'${parseSymbolId(symbolJson)}',
126-
isWarning: true,
127-
),
128130
_ => throw UnsupportedSymbolException(
129131
'Symbol of type $symbolType is not supported yet: '
130132
'${parseSymbolId(symbolJson)}',

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,18 @@ typedef PrefixParselet =
9999
Json token,
100100
TokenList fragments,
101101
) {
102-
final id = token['preciseIdentifier'].get<String>();
102+
final preciseIdJson = token['preciseIdentifier'];
103+
if (!preciseIdJson.exists) {
104+
final spelling = token['spelling'].get<String>();
105+
if (spelling == 'Self') {
106+
return (selfType, fragments);
107+
}
108+
throw Exception(
109+
'Type at "${token.path}" has no preciseIdentifier '
110+
'and is not Self: $token',
111+
);
112+
}
113+
final id = preciseIdJson.get<String>();
103114
final symbol = symbolgraph.symbols[id];
104115

105116
if (symbol == null) {

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

Lines changed: 71 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,58 @@ import '../../ast/_core/interfaces/compound_declaration.dart';
66

77
class UniqueNamer {
88
final Set<String> _usedNames;
9+
final Map<String, String> operatorNames = {
10+
'+': 'add',
11+
'-': 'subtract',
12+
'*': 'multiply',
13+
'/': 'divide',
14+
'%': 'modulo',
15+
16+
'==': 'equals',
17+
'!=': 'notEquals',
18+
'===': 'strictEquals',
19+
'!==': 'strictNotEquals',
20+
21+
'<': 'lessThan',
22+
'<=': 'lessThanOrEquals',
23+
'>': 'greaterThan',
24+
'>=': 'greaterThanOrEquals',
25+
26+
'!': 'not',
27+
'&&': 'logicalAnd',
28+
'||': 'logicalOr',
29+
30+
'&': 'and',
31+
'|': 'or',
32+
'^': 'xor',
33+
'~': 'bitwiseNot',
34+
35+
'<<': 'shiftLeft',
36+
'>>': 'shiftRight',
37+
38+
'=': 'assign',
39+
'+=': 'addAssign',
40+
'-=': 'subtractAssign',
41+
'*=': 'multiplyAssign',
42+
'/=': 'divideAssign',
43+
'%=': 'moduloAssign',
44+
'&=': 'andAssign',
45+
'|=': 'orAssign',
46+
'^=': 'xorAssign',
47+
'<<=': 'shiftLeftAssign',
48+
'>>=': 'shiftRightAssign',
49+
50+
'++': 'increment',
51+
'--': 'decrement',
52+
53+
'??': 'nilCoalescing',
54+
'?': 'question',
55+
56+
'...': 'closedRange',
57+
'..<': 'halfOpenRange',
58+
59+
'.': 'dot',
60+
};
961

1062
UniqueNamer([Iterable<String> usedNames = const <String>[]])
1163
: _usedNames = usedNames.toSet();
@@ -17,24 +69,32 @@ class UniqueNamer {
1769
};
1870

1971
String makeUnique(String name) {
20-
if (name.isEmpty) {
21-
name = 'unamed';
22-
}
72+
final uniqueName = _sanitize(name);
2373

24-
if (!_usedNames.contains(name)) {
25-
_usedNames.add(name);
26-
return name;
74+
if (!_usedNames.contains(uniqueName)) {
75+
_usedNames.add(uniqueName);
76+
return uniqueName;
2777
}
2878

2979
var counter = 0;
30-
var uniqueName = name;
80+
var candidateName = uniqueName;
3181

3282
do {
3383
counter++;
34-
uniqueName = '$name$counter';
35-
} while (_usedNames.contains(uniqueName));
84+
candidateName = '$uniqueName$counter';
85+
} while (_usedNames.contains(candidateName));
86+
87+
_usedNames.add(candidateName);
88+
return candidateName;
89+
}
90+
91+
String _sanitize(String name) {
92+
if (name.isEmpty) return 'unnamed';
93+
94+
if (operatorNames.containsKey(name)) {
95+
return operatorNames[name]!;
96+
}
3697

37-
_usedNames.add(uniqueName);
38-
return uniqueName;
98+
return RegExp(r'\W').hasMatch(name) ? 'operatorOverload' : name;
3999
}
40100
}

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

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import '../../ast/_core/interfaces/function_declaration.dart';
66
import '../../ast/_core/shared/parameter.dart';
77
import '../../ast/_core/shared/referred_type.dart';
8+
import '../../ast/declarations/built_in/built_in_declaration.dart';
89
import '../../ast/declarations/compounds/members/method_declaration.dart';
910
import '../../ast/declarations/compounds/members/property_declaration.dart';
1011
import '../../ast/declarations/globals/globals.dart';
@@ -29,16 +30,32 @@ MethodDeclaration? transformMethod(
2930
if (disallowedMethods.contains(originalMethod.name)) {
3031
return null;
3132
}
33+
if (originalMethod.isOperator &&
34+
originalMethod.params.any((p) => p.type.sameAs(selfType))) {
35+
return null;
36+
}
37+
38+
final wrapperMethodName = originalMethod.isOperator
39+
? globalNamer.makeUnique(originalMethod.name)
40+
: originalMethod.name;
3241

3342
return _transformFunction(
3443
originalMethod,
3544
globalNamer,
3645
state,
37-
wrapperMethodName: originalMethod.name,
46+
wrapperMethodName: wrapperMethodName,
3847
originalCallStatementGenerator: (arguments) {
3948
final methodSource = originalMethod.isStatic
4049
? wrappedClassInstance.type.swiftType
4150
: wrappedClassInstance.name;
51+
52+
if (originalMethod.isOperator) {
53+
final params = originalMethod.params;
54+
return '${params[0].internalName ?? params[0].name}.wrappedInstance '
55+
'${originalMethod.name} '
56+
'${params[1].internalName ?? params[1].name}.wrappedInstance';
57+
}
58+
4259
return '$methodSource.${originalMethod.name}($arguments)';
4360
},
4461
);
@@ -173,7 +190,9 @@ List<String> _generateStatements(
173190
originalFunction.params,
174191
transformedMethod.params,
175192
);
193+
176194
var originalMethodCall = originalCallGenerator(arguments);
195+
177196
if (transformedMethod.async) {
178197
originalMethodCall = 'await $originalMethodCall';
179198
}

‎pkgs/swift2objc/test/integration/enum_input.swift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ public enum Barcode {
3131
}
3232

3333
// Indirect (recursive) enums.
34+
// TODO(swift2objc): indirect recursive enums are not supported yet.
3435
public indirect enum ArithmeticExpression {
3536
case number(Int)
3637
case addition(ArithmeticExpression, ArithmeticExpression)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
infix operator ***: MultiplicationPrecedence
2+
3+
4+
public class Vec2 {
5+
public var x: Double
6+
public var y: Double
7+
8+
public init(x: Double, y: Double) {
9+
self.x = x
10+
self.y = y
11+
}
12+
13+
public static func + (lhs: Vec2, rhs: Vec2) -> Vec2 {
14+
return Vec2(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
15+
}
16+
17+
public static func == (lhs: Vec2, rhs: Vec2) -> Bool {
18+
return lhs.x == rhs.x && lhs.y == rhs.y
19+
}
20+
21+
public static func *** (lhs: Vec2, rhs: Vec2) -> Double {
22+
return (lhs.x * rhs.x) + (lhs.y * rhs.y)
23+
}
24+
}

0 commit comments

Comments
 (0)