-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHaxeSwiftBridge.hx
643 lines (562 loc) · 19.5 KB
/
HaxeSwiftBridge.hx
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
#if (haxe_ver < 4.0) #error "Haxe 4.0 required" #end
#if macro
// fast path for when code gen isn't required
// disable this to get auto-complete when editing this file
#if (display || display_details || !sys || cppia)
class HaxeSwiftBridge {
public static function expose(?namespace: String)
return haxe.macro.Context.getBuildFields();
@:noCompletion
static macro function runUserMain()
return macro null;
}
#else
import HaxeCBridge.CodeTools.*;
import haxe.ds.ReadOnlyArray;
import haxe.io.Path;
import haxe.macro.Compiler;
import haxe.macro.ComplexTypeTools;
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.ExprTools;
import haxe.macro.PositionTools;
import haxe.macro.Printer;
import haxe.macro.Type;
import haxe.macro.TypeTools;
import haxe.macro.TypedExprTools;
import sys.FileSystem;
import sys.io.File;
using Lambda;
using StringTools;
class HaxeSwiftBridge {
static final noOutput = Sys.args().has('--no-output');
static final printer = new Printer();
static var firstRun = true;
static var libName: Null<String> = getLibNameFromHaxeArgs(); // null if no libName determined from args
static final compilerOutputDir = Compiler.getOutput();
// paths relative to the compiler output directory
static final implementationPath = Path.join([hx.strings.Strings.toUpperCamel(libName) + '.swift']);
static final queuedClasses = new Array<{
cls: Ref<ClassType>,
namespace: String,
}>();
static final knownEnums: Map<String,String> = [];
static public function expose(?namespace: String) {
var clsRef = Context.getLocalClass();
var cls = clsRef.get();
var fields = Context.getBuildFields();
if (libName == null) {
// if we cannot determine a libName from --main or -D, we use the first exposed class
libName = if (namespace != null) {
namespace;
} else {
cls.name;
}
}
queuedClasses.push({
cls: clsRef,
namespace: namespace
});
// add @:keep
cls.meta.add(':keep', [], Context.currentPos());
if (firstRun) {
var HaxeSwiftBridgeType = Context.resolveType(macro :HaxeSwiftBridge, Context.currentPos());
switch HaxeSwiftBridgeType {
case TInst(_.get().meta => meta, params):
if (!meta.has(':buildXml')) {
meta.add(':buildXml', [
macro $v{code('
<!-- HaxeSwiftBridge -->
<files id="haxe">
<depend name="$implementationPath"/>
</files>
')}
], Context.currentPos());
}
default: throw 'Internal error';
}
Context.onAfterTyping(_ -> {
var implementation = generateImplementation();
function saveFile(path: String, content: String) {
var directory = Path.directory(path);
if (!FileSystem.exists(directory)) {
FileSystem.createDirectory(directory);
}
// only save if there's a difference (save C++ compilation by not changing the file if not needed)
if (FileSystem.exists(path)) {
if (content == sys.io.File.getContent(path)) {
return;
}
}
sys.io.File.saveContent(path, content);
}
if (!noOutput) {
saveFile(Path.join([compilerOutputDir, implementationPath]), implementation);
}
});
firstRun = false;
}
return fields;
}
static function getHxcppNativeName(t: BaseType) {
var nativeMeta = t.meta.extract(':native')[0];
var nativeMetaValue = nativeMeta != null ? ExprTools.getValue(nativeMeta.params[0]) : null;
var nativeName = (nativeMetaValue != null ? nativeMetaValue : t.pack.concat([t.name]).join('.'));
return nativeName;
}
static function getSwiftType(type, arg = false) {
return switch type {
case TInst(_.get().name => "String", params):
return "String";
case TInst(_.get().name => "Array", [param]):
return "Array<" + getSwiftType(param, arg) + ">";
case TInst(_.get() => t, params):
return t.name;
case TAbstract(_.get().name => "Null", [param]):
return getSwiftType(param) + "?";
case TAbstract(_.get().name => "Int", []):
return "Int32";
case TAbstract(_.get() => t, []):
final isPublicEnumAbstract = t.meta.has(':enum') && !t.isPrivate;
final isIntEnumAbstract = if (isPublicEnumAbstract) {
final underlyingRootType = TypeTools.followWithAbstracts(t.type, false);
Context.unify(underlyingRootType, Context.resolveType(macro :Int, Context.currentPos()));
} else false;
if (isIntEnumAbstract) {
knownEnums[t.name] = hx.strings.Strings.toLowerUnderscore(safeIdent(TypeTools.toString(type)));
}
return t.name;
case TAbstract(_.get() => t, params):
return getSwiftType(TypeTools.followWithAbstracts(type, false), arg);
case TFun(args, ret):
final builder = new hx.strings.StringBuilder(arg ? "@escaping (" : "(");
for (i => arg in args) {
if (i > 0) builder.add(", ");
builder.add(getSwiftType(arg.t));
}
builder.add(")->");
builder.add(getSwiftType(ret));
return builder.toString();
case TType(_.get() => t, params):
return getSwiftType(TypeTools.follow(type, true), arg);
default:
Context.fatalError("No implemented Swift type conversion for: " + type, Context.currentPos());
}
}
static function convertArgs(builder: hx.strings.StringBuilder, args: Array<{ name: String, opt: Bool, t: haxe.macro.Type }>) {
for (i => arg in args) {
if (i > 0) builder.add(", ");
builder.add(arg.name);
builder.add(": ");
builder.add(getSwiftType(arg.t, true));
if (arg.opt) {
Context.fatalError("default? " + arg.name, Context.currentPos());
}
}
}
static function castToSwift(item: String, type: haxe.macro.Type, canNull = false, isRet = false) {
return switch type {
case TInst(_.get().name => "String", params):
return "useString(" + item + ")" + (canNull ? "" : "!");
case TInst(_.get().name => "Array", [param]):
final ptrType = switch getSwiftType(param) {
case "String": "UnsafePointer<CChar>?";
case "Int16": "Int16";
default: "UnsafeMutableRawPointer?";
}
if (isRet) {
return
"{" +
"var __ret: UnsafeMutablePointer<" + ptrType + ">? = nil;" +
"let __ret_length = " + ~/\)$/.replace(item, ", &__ret);") +
"return " + castToSwift("__ret", type, canNull, false) + ";" +
"}()";
} else {
return
"{" +
"let __r = UnsafeMutableBufferPointer<" + ptrType + ">(start: " + item + ", count: " + item + "_length).map({" +
castToSwift("$0", param) +
"});" +
"c_" + libName + "." + libName + "_release(" + item + ");" +
"return __r;" +
"}()";
}
case TInst(_.get() => t, params):
final wrapper = t.isInterface ? 'Any${t.name}' : t.name;
if (canNull) {
return "(" + item + ").map({ " + wrapper + "($0) })";
} else {
return wrapper + "(" + item + "!)";
}
case TAbstract(_.get().name => "Null", [param]):
return castToSwift(item, param, true);
case TAbstract(_.get() => t, []):
return item;
case TAbstract(_.get() => t, params):
return castToSwift(item, TypeTools.followWithAbstracts(type, false), canNull, isRet);
case TType(_.get() => t, params):
return castToSwift(item, TypeTools.follow(type, true), canNull);
default:
Context.fatalError("No implemented Swift cast for: " + type, Context.currentPos());
}
}
static function castToC(item: String, type: haxe.macro.Type, canNull = false) {
return switch type {
case TInst(_.get().name => "String", params):
return item;
case TInst(_.get().name => "Array", [TInst(_)]):
return item + ".map { $0.o }";
case TInst(_.get().name => "Array", [param]):
return item;
case TInst(_.get() => t, []):
return item + (canNull ? "?" : "") + ".o";
case TAbstract(_.get().name => "Null", [param]):
return castToC(item, param, true);
case TAbstract(_.get() => t, []):
return item;
case TType(_.get() => t, params):
return castToC(item, TypeTools.follow(type, true));
default:
Context.fatalError("No implemented C cast for: " + type, Context.currentPos());
}
}
static function metaIsSwiftExpose(e: ExprDef) {
return switch (e) {
case ECall(call, args):
switch (call.expr) {
case EField(l, r):
switch (l.expr) {
case EConst(CIdent("HaxeSwiftBridge")):
r == "expose";
default: false;
}
default: false;
}
default: false;
}
}
static function convertQueuedClass(clsRef: Ref<ClassType>, namespace: String) {
var cls = clsRef.get();
// validate
if (cls.isExtern) Context.error('Cannot expose extern directly to Swift', cls.pos);
var classPrefix = cls.pack.concat([namespace == null ? cls.name : namespace]);
var cNameMeta = getCNameMeta(cls.meta);
var functionPrefix =
if (cNameMeta != null)
[cNameMeta];
else
[false ? libName : ""] // NOTE: probably want this if we get packages with differnt name?
.concat(safeIdent(classPrefix.join('.')) != libName ? classPrefix : [])
.filter(s -> s != '');
final builder = new hx.strings.StringBuilder(cls.isInterface ? "public protocol " : "public class ");
builder.add(cls.name);
final superClass = if (cls.superClass == null) {
null;
} else {
final buildMeta = cls.superClass.t.get().meta.extract(":build");
if (buildMeta.exists(meta -> metaIsSwiftExpose(meta.params[0]?.expr))) {
cls.superClass.t.get();
} else {
null;
}
}
if (superClass == null) {
builder.add(": SDKObject");
} else {
builder.add(": ");
builder.add(superClass.name);
}
for (iface in cls.interfaces) {
builder.add(", ");
builder.add(iface.t.get().name);
}
builder.add(" {\n");
if (!cls.isInterface && superClass == null) {
// We don't want this to be public, but it needs to be for the protocol, hmm
builder.add("\tpublic let o: UnsafeMutableRawPointer\n\n\tinternal init(_ ptr: UnsafeMutableRawPointer) {\n\t\to = ptr\n\t}\n\n");
}
function convertVar(f: ClassField, read: VarAccess, write: VarAccess) {
final noemit = f.meta.extract("HaxeCBridge.noemit")[0];
var isConvertibleMethod = f.isPublic && !f.isExtern && (noemit == null || (noemit.params != null && noemit.params.length > 0));
if (!isConvertibleMethod) return;
if (cls.isInterface) return;
if (read != AccNormal && read != AccCall) return; // Swift doesn't allow write-only
final cNameMeta = getCNameMeta(f.meta);
final cFuncNameGet = hx.strings.Strings.toLowerUnderscore(functionPrefix.concat([f.name]).join('_'));
final cFuncNameSet = hx.strings.Strings.toLowerUnderscore(functionPrefix.concat(["set", f.name]).join('_'));
final cleanDoc = f.doc != null ? StringTools.trim(removeIndentation(f.doc)) : null;
if (cleanDoc != null) builder.add('\t/**\n${cleanDoc.split('\n').map(l -> '\t ' + l).join('\n')}\n\t */\n');
builder.add("\tpublic var ");
builder.add(f.name);
builder.add(": ");
builder.add(getSwiftType(f.type));
builder.add(" {\n");
if (read == AccNormal || read == AccCall) {
builder.add("\t\tget {\n\t\t\t");
builder.add(castToSwift('c_${libName}.${cFuncNameGet}(o)', f.type, false, true));
builder.add("\n\t\t}\n");
}
if (write == AccNormal || write == AccCall) {
builder.add("\t\tset {\n\t\t\tc_");
builder.add(libName);
builder.add(".");
builder.add(cFuncNameSet);
builder.add("(o, ");
builder.add(castToC("newValue", f.type));
builder.add(")\n\t\t}\n");
}
builder.add("\t}\n\n");
}
function convertFunction(f: ClassField, kind: SwiftFunctionInfoKind) {
final noemit = f.meta.extract("HaxeCBridge.noemit")[0];
var isConvertibleMethod = f.isPublic && !f.isExtern && !f.meta.has("HaxeCBridge.wrapper") && (noemit == null || (noemit.params != null && noemit.params.length > 0));
if (!isConvertibleMethod) return;
if (cls.isInterface) return;
switch f.type {
case TFun(targs, tret):
final cNameMeta = getCNameMeta(f.meta);
var cFuncName: String =
if (cNameMeta != null)
cNameMeta;
else if (f.meta.has("HaxeCBridge.wrapper"))
functionPrefix.concat([f.name.substring(0, f.name.length - 7)]).join('_');
else
functionPrefix.concat([f.name]).join('_');
var funcName: String =
if (f.meta.has("HaxeCBridge.wrapper"))
f.name.substring(0, f.name.length - 7);
else
f.name;
cFuncName = hx.strings.Strings.toLowerUnderscore(cFuncName);
final cleanDoc = f.doc != null ? StringTools.trim(removeIndentation(f.doc)) : null;
if (cleanDoc != null) builder.add('\t/**\n${cleanDoc.split('\n').map(l -> '\t ' + l).join('\n')}\n\t */\n');
switch kind {
case Constructor:
builder.add("\tpublic init(");
convertArgs(builder, targs);
builder.add(") {\n\t\to = c_");
builder.add(libName);
builder.add(".");
builder.add(cFuncName);
builder.add("(");
for (i => arg in targs) {
if (i > 0) builder.add(", ");
builder.add(castToC(arg.name, arg.t));
}
builder.add(")\n\t}\n\n");
case Member:
builder.add("\tpublic func ");
builder.add(funcName);
builder.add("(");
convertArgs(builder, targs);
builder.add(") -> ");
builder.add(getSwiftType(tret));
builder.add(" {\n\t\t");
for (arg in targs) {
switch (arg.t) {
case TFun(fargs, fret):
builder.add("let __");
builder.add(arg.name);
builder.add("_ptr = UnsafeMutableRawPointer(Unmanaged.passRetained(");
builder.add(arg.name);
builder.add(" as AnyObject).toOpaque())\n\t\t");
default:
}
}
final ibuilder = new hx.strings.StringBuilder("c_");
ibuilder.add(libName);
ibuilder.add(".");
ibuilder.add(cFuncName);
ibuilder.add("(\n\t\t\tself.o");
for (arg in targs) {
ibuilder.add(",\n\t\t\t");
switch (arg.t) {
case TFun(fargs, fret):
ibuilder.add("{ (");
for (i => farg in fargs) {
if (i > 0) ibuilder.add(", ");
ibuilder.add("a" + i);
switch (farg.t) {
case TInst(_.get().name => "Array", params):
ibuilder.add(", a" + i + "_length");
default:
}
}
if (fargs.length > 0) ibuilder.add(", ");
ibuilder.add("ctx");
// TODO unretained vs retained
ibuilder.add(") in\n\t\t\t\tlet ");
ibuilder.add(arg.name);
ibuilder.add(" = Unmanaged<AnyObject>.fromOpaque(ctx!).takeUnretainedValue() as! ");
ibuilder.add(getSwiftType(arg.t));
ibuilder.add("\n\t\t\t\t");
final cbuilder = new hx.strings.StringBuilder(arg.name);
cbuilder.add("(");
for (i => farg in fargs) {
if (i > 0) cbuilder.add(", ");
cbuilder.add(castToSwift("a" + i, farg.t));
}
cbuilder.add(")");
ibuilder.add(castToSwift(cbuilder.toString(), fret, false, true));
ibuilder.add("\n\t\t\t},\n\t\t\t__");
ibuilder.add(arg.name);
ibuilder.add("_ptr");
case TInst(_.get().name => "Array", [param]):
ibuilder.add(castToC(arg.name, arg.t));
ibuilder.add(", ");
ibuilder.add(arg.name + ".count");
default:
ibuilder.add(castToC(arg.name, arg.t));
}
}
ibuilder.add("\n\t\t)");
builder.add(castToSwift(ibuilder.toString(), tret, false, true));
builder.add("\n\t}\n\n");
case Static:
Context.fatalError('Swift bridging for statics not implemented yet', f.pos);
}
default: Context.fatalError('Internal error: Expected function expression for ${f.name} got: ' + f.type, f.pos);
}
}
if (cls.constructor != null) {
convertFunction(cls.constructor.get(), Constructor);
}
for (f in cls.statics.get()) {
// TODO: this also includes everything on an abstract?
}
for (f in cls.fields.get()) {
switch (f.kind) {
case FMethod(MethMacro):
case FMethod(_): convertFunction(f, Member);
case FVar(read, write): convertVar(f, read, write);
}
}
if (!cls.isInterface && superClass == null) {
builder.add("\tdeinit {\n\t\tc_");
builder.add(libName);
builder.add(".");
builder.add(libName);
builder.add("_release(o)\n\t}\n");
}
builder.add("}\n");
if (cls.isInterface) {
// TODO: extension with defaults for all exposed methods
builder.add("\npublic class Any");
builder.add(cls.name);
builder.add(": ");
builder.add(cls.name);
builder.add(" {\n");
builder.add("\tpublic let o: UnsafeMutableRawPointer\n\n\tinternal init(_ ptr: UnsafeMutableRawPointer) {\n\t\to = ptr\n\t}\n\n");
builder.add("\tdeinit {\n\t\tc_");
builder.add(libName);
builder.add(".");
builder.add(libName);
builder.add("_release(o)\n\t}\n");
builder.add("\n}\n");
}
return builder.toString();
}
static macro function runUserMain() {
var mainClassPath = getMainFromHaxeArgs(Sys.args());
if (mainClassPath == null) {
return macro null;
} else {
return Context.parse('$mainClassPath.main()', Context.currentPos());
}
}
static function isLibraryBuild() {
return Context.defined('dll_link') || Context.defined('static_link');
}
static function isDynamicLink() {
return Context.defined('dll_link');
}
static function getCNameMeta(meta: MetaAccess): Null<String> {
var cNameMeta = meta.extract('HaxeCBridge.name')[0];
return if (cNameMeta != null) {
switch cNameMeta.params {
case [{expr: EConst(CString(name))}]:
safeIdent(name);
default:
Context.error('Incorrect usage, syntax is @${cNameMeta.name}(name: String)', cNameMeta.pos);
}
} else null;
}
static function generateImplementation() {
return code('
import c_' + libName + '
func setup(_ handler: @convention(c) @escaping (UnsafePointer<CChar>?)->Void) {
c_' + libName + '.' + libName + '_setup(handler)
}
func stop(_ wait: Bool) {
c_' + libName + '.' + libName + '_stop(wait)
}
public protocol SDKObject {
var o: UnsafeMutableRawPointer {get}
}
internal func useString(_ mptr: UnsafePointer<CChar>?) -> String? {
if let ptr = mptr {
let r = String(cString: ptr)
c_' + libName + '.' + libName + '_release(ptr)
return r
} else {
return nil
}
}
internal func useString(_ mptr: UnsafeMutableRawPointer?) -> String? {
return useString(UnsafePointer(mptr?.assumingMemoryBound(to: CChar.self)))
}
')
+ queuedClasses.map(c -> convertQueuedClass(c.cls, c.namespace)).join("\n") + "\n"
+ { iterator: () -> knownEnums.keyValueIterator() }.map(e -> "public typealias " + e.key + " = " + e.value + "\n").join("\n")
;
}
/**
We determine a project name to be the `--main` startup class
The user can override this with `-D HaxeCBridge.name=ExampleName`
This isn't rigorously defined but hopefully will produced nicely namespaced and unsurprising function names
**/
static function getLibNameFromHaxeArgs(): Null<String> {
var overrideName = Context.definedValue('HaxeCBridge.name');
if (overrideName != null && overrideName != '') {
return safeIdent(overrideName);
}
var args = Sys.args();
var mainClassPath = getMainFromHaxeArgs(args);
if (mainClassPath != null) {
return safeIdent(mainClassPath);
}
// no lib name indicator found in args
return null;
}
static function getMainFromHaxeArgs(args: Array<String>): Null<String> {
for (i in 0...args.length) {
var arg = args[i];
switch arg {
case '-m', '-main', '--main':
var classPath = args[i + 1];
return classPath;
default:
}
}
return null;
}
static function safeIdent(str: String) {
// replace non a-z0-9_ with _
str = ~/[^\w]/gi.replace(str, '_');
// replace leading number with _
str = ~/^[^a-z_]/i.replace(str, '_');
// replace empty string with _
str = str == '' ? '_' : str;
return str;
}
}
enum SwiftFunctionInfoKind {
Constructor;
Member;
Static;
}
#end // (display || display_details || target.name != cpp)
#elseif (cpp && !cppia)
// runtime HaxeSwiftBridge
class HaxeSwiftBridge {}
#end