-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathcode_writers.h
3218 lines (2901 loc) · 119 KB
/
code_writers.h
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
#pragma once
#include "code_writers/common_writers.h"
#include "code_writers/type_writers.h"
#include "code_writers/can_write.h"
#include "metadata_cache.h"
namespace swiftwinrt
{
static void write_enum_def(writer& w, enum_type const& type)
{
// Metadata attributes don't have backing code
if (type.swift_logical_namespace() == "Windows.Foundation.Metadata" || !can_write(w, type))
{
return;
}
write_documentation_comment(w, type);
w.write("public typealias % = %\n", type, bind_type_mangled(type));
}
static void write_enum_extension(writer& w, enum_type const& type)
{
if (type.swift_logical_namespace() == "Windows.Foundation.Metadata" || !can_write(w, type))
{
return;
}
w.write("extension % {\n", get_full_swift_type_name(w, type));
{
auto format = R"( public static var % : % {
%_%
}
)";
for (const auto& field : type.type().FieldList())
{
if (field.Constant())
{
// this enum is not written by our ABI tool, so it doesn't use a mangled name
if (get_full_type_name(type) == "Windows.Foundation.Collections.CollectionChange")
{
w.write(format, get_swift_name(field), get_full_swift_type_name(w, type), type, field.Name());
}
else
{
// we use mangled names for enums because otherwise the WinAppSDK enums collide with the Windows ones
w.write(format, get_swift_name(field), get_full_swift_type_name(w, type), bind_type_mangled(type), field.Name());
}
}
}
}
w.write("}\n");
w.write("extension %: ^@retroactive Hashable, ^@retroactive Codable, ^@retroactive ^@unchecked Sendable {}\n\n", get_full_swift_type_name(w, type));
}
static void write_guid_value(writer& w, std::vector<FixedArgSig> const& args)
{
using std::get;
w.write_printf("Data1: 0x%08X, Data2: 0x%04X, Data3: 0x%04X, Data4: ( 0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X )",
get<uint32_t>(get<ElemSig>(args[0].value).value),
get<uint16_t>(get<ElemSig>(args[1].value).value),
get<uint16_t>(get<ElemSig>(args[2].value).value),
get<uint8_t>(get<ElemSig>(args[3].value).value),
get<uint8_t>(get<ElemSig>(args[4].value).value),
get<uint8_t>(get<ElemSig>(args[5].value).value),
get<uint8_t>(get<ElemSig>(args[6].value).value),
get<uint8_t>(get<ElemSig>(args[7].value).value),
get<uint8_t>(get<ElemSig>(args[8].value).value),
get<uint8_t>(get<ElemSig>(args[9].value).value),
get<uint8_t>(get<ElemSig>(args[10].value).value));
}
static void write_guid_comment(writer& w, std::vector<FixedArgSig> const& args)
{
using std::get;
w.write_printf("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
get<uint32_t>(get<ElemSig>(args[0].value).value),
get<uint16_t>(get<ElemSig>(args[1].value).value),
get<uint16_t>(get<ElemSig>(args[2].value).value),
get<uint8_t>(get<ElemSig>(args[3].value).value),
get<uint8_t>(get<ElemSig>(args[4].value).value),
get<uint8_t>(get<ElemSig>(args[5].value).value),
get<uint8_t>(get<ElemSig>(args[6].value).value),
get<uint8_t>(get<ElemSig>(args[7].value).value),
get<uint8_t>(get<ElemSig>(args[8].value).value),
get<uint8_t>(get<ElemSig>(args[9].value).value),
get<uint8_t>(get<ElemSig>(args[10].value).value));
}
static void write_guid_value_hash(writer& w, std::array<uint8_t, 20ui64> const& iidHash)
{
w.write_printf("Data1: 0x%02x%02x%02x%02x, Data2: 0x%02x%02x, Data3: 0x%02x%02x, Data4: ( 0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x )",
iidHash[0], iidHash[1], iidHash[2], iidHash[3],
iidHash[4], iidHash[5],
iidHash[6], iidHash[7],
iidHash[8], iidHash[9],
iidHash[10], iidHash[11], iidHash[12], iidHash[13], iidHash[14], iidHash[15]);
}
static void write_guid_comment_hash(writer& w, std::array<uint8_t, 20ui64> const& iidHash)
{
w.write_printf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
iidHash[0], iidHash[1], iidHash[2], iidHash[3],
iidHash[4], iidHash[5],
iidHash[6], iidHash[7],
iidHash[8], iidHash[9],
iidHash[10], iidHash[11], iidHash[12], iidHash[13], iidHash[14], iidHash[15]);
}
static void write_guid(writer& w, typedef_base const& type)
{
auto attribute = get_attribute(type.type(), "Windows.Foundation.Metadata", "GuidAttribute");
if (!attribute)
{
throw_invalid("'Windows.Foundation.Metadata.GuidAttribute' attribute for type '", type.swift_full_name(), "' not found");
}
auto abi_guard = w.push_mangled_names(true);
auto mangled = w.push_abi_types(true);
auto guid = attribute.Value().FixedArgs();
auto format = R"(private var IID_%: %.IID {
.init(%)// %
}
)";
w.write(format,
type,
w.support,
bind<write_guid_value>(guid),
bind<write_guid_comment>(guid));
}
static void write_guid_generic(writer& w, generic_inst const& type)
{
auto abi_guard = w.push_mangled_names(true);
static constexpr std::uint8_t namespaceGuidBytes[] =
{
0x11, 0xf4, 0x7a, 0xd5,
0x7b, 0x73,
0x42, 0xc0,
0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee
};
sha1 signatureHash;
signatureHash.append(namespaceGuidBytes, std::size(namespaceGuidBytes));
type.append_signature(signatureHash);
auto iidHash = signatureHash.finalize();
iidHash[6] = (iidHash[6] & 0x0F) | 0x50;
iidHash[8] = (iidHash[8] & 0x3F) | 0x80;
auto format = R"(private var IID_%: %.IID {
.init(%)// %
}
)";
w.write(format,
type.mangled_name(),
w.support,
bind<write_guid_value_hash>(iidHash),
bind<write_guid_comment_hash>(iidHash));
}
static void write_array_size_name(writer& w, Param const& param)
{
w.write(" __%Size", get_swift_name(param));
}
static void write_function_params2(writer& w, std::vector<function_param> const& params, write_type_params const& type_params)
{
separator s{ w };
for (const auto& param : params)
{
s();
w.write("_ %: ", get_swift_name(param));
if (param.out()) w.write("inout ");
const bool is_array = param.is_array();
if (is_array && type_params.layer == projection_layer::swift)
{
// Can't allow for implicit unwrap in arrays
w.write("[%]", bind<write_type>(*param.type, write_type_params::swift));
}
else
{
write_type(w, *param.type, type_params);
}
}
}
static void write_function_params(writer& w, function_def const& function, write_type_params const& type_params)
{
write_function_params2(w, function.params, type_params);
}
template <typename Param>
static void write_convert_to_abi_arg(writer& w, Param const& param)
{
TypeDef signature_type;
auto type = param.type;
auto param_name = param.name;
auto is_out = param.out();
auto category = get_category(type, &signature_type);
auto local_name = local_swift_param_name(param_name);
if (param.is_array())
{
if (is_out)
{
w.write("%");
}
else
{
// Arrays are all converted from the swift array to a c array, so they
// use the local_param_name
w.write("count, %", local_name);
}
}
else if (category == param_category::object_type)
{
if (is_out) throw std::exception("out parameters of reference types should not be converted directly to abi types");
if (is_class(signature_type))
{
w.write("RawPointer(%)", param_name);
}
else
{
w.write("%", local_name);
}
}
else if (category == param_category::string_type)
{
if (!is_out)
{
w.write("%.get()", local_name);
}
else
{
auto format = "try! HString(%).detach()";
w.write(format, param_name);
}
}
else if (category == param_category::struct_type)
{
if (!is_out && type->swift_type_name() == "EventRegistrationToken")
{
w.write(param_name);
}
else if (is_struct_blittable(signature_type))
{
w.write(".from(swift: %)", param_name);
}
else
{
if (!is_out)
{
w.write("%.val", local_name);
}
else
{
w.write("%.detach()", local_name);
}
}
}
else if(category == param_category::generic_type)
{
if (is_out) throw std::exception("out parameters of generic types should not be converted directly to abi types");
// When passing generics to the ABI we wrap them before making the
// api call for easy passing to the ABI
w.write("%", local_name);
}
else if (is_type_blittable(category))
{
// fundamentals and enums can be simply copied
w.write(param_name);
}
else
{
w.write(".init(from: %)", param_name);
}
}
static void write_implementation_args(writer& w, function_def const& function)
{
separator s{ w };
for (const auto& param : function.params)
{
s();
if (param.def.Flags().In())
{
w.write(get_swift_name(param));
}
else
{
w.write("&%", get_swift_name(param));
}
}
}
static void write_abi_args(writer& w, function_def const& function)
{
separator s{ w };
w.write("pThis");
s();
for (auto& param: function.params)
{
auto param_name = get_swift_name(param);
auto local_param_name = local_swift_param_name(param_name);
s();
if (param.is_array())
{
if (param.in())
{
w.write("%.count, %.start", local_param_name, local_param_name);
}
else if (param.signature.ByRef())
{
w.write("&%.count, &%.start", local_param_name, local_param_name);
}
else
{
w.write("%.count, %.start", local_param_name, local_param_name);
}
}
else if (param.in())
{
write_convert_to_abi_arg(w, param);
}
else
{
auto category = get_category(param.type);
bool is_blittable = is_type_blittable(param.signature.Type());
if (needs_wrapper(category))
{
w.write("&%Abi", local_param_name);
}
else if (category == param_category::struct_type)
{
if (is_blittable)
{
w.write("&%", local_param_name);
}
else
{
w.write("&%.val", local_param_name);
}
}
else if (is_blittable)
{
w.write("&%", param_name);
}
else
{
w.write("&%", local_param_name);
}
}
}
if (function.return_type)
{
s();
auto param_name = function.return_type.value().name;
if (function.return_type.value().is_array())
{
w.write("&%.count, &%.start", param_name, param_name);
}
else if (needs_wrapper(get_category(function.return_type->type)))
{
w.write("&%Abi", param_name);
}
else
{
w.write("&%", param_name);
}
}
}
static std::optional<writer::indent_guard> write_init_return_val_abi(writer& w, function_return_type const& signature)
{
auto category = get_category(signature.type);
if (signature.is_array())
{
w.write("var %: WinRTArrayAbi<%> = (0, nil)\n",
signature.name,
bind<write_type>(*signature.type, write_type_params::c_abi));
return std::optional<writer::indent_guard>();
}
else if (needs_wrapper(category))
{
w.write("let (%) = try ComPtrs.initialize { %Abi in\n", signature.name, signature.name);
return writer::indent_guard(w, 1);
}
else
{
w.write("var %: ", signature.name);
auto guard{ w.push_mangled_names_if_needed(category) };
write_type(w, *signature.type, write_type_params::c_abi);
write_default_init_assignment(w, *signature.type, projection_layer::c_abi);
w.write("\n");
return std::optional<writer::indent_guard>();
}
}
static void write_consume_return_statement(writer& w, function_def const& signature);
static void write_return_type_declaration(writer& w, function_def function, write_type_params const& type_params)
{
if (!function.return_type)
{
return;
}
w.write(" -> ");
if (function.return_type->is_array() && type_params.layer == projection_layer::swift)
{
w.write("[%]", bind<write_type>(*function.return_type->type, write_type_params::swift));
}
else
{
write_type(w, *function.return_type->type, type_params);
}
}
static std::vector<function_param> get_projected_params(attributed_type const& factory, function_def const& func);
static write_scope_guard<writer> write_local_param_wrappers(writer& w, std::vector<function_param> const& params);
static void do_write_interface_abi(writer& w, typedef_base const& type, std::vector<function_def> const& methods)
{
auto factory_info = try_get_factory_info(w, type);
auto classType = try_get_exclusive_to(w, type);
if (classType && !can_write(w, classType))
{
return;
}
const bool isInitializer = factory_info.has_value() && (factory_info->activatable || factory_info->composable);
const bool composableFactory = factory_info.has_value() && factory_info->composable;
auto name = w.write_temp("%", type);
auto baseClass = (is_delegate(type) || !type.type().Flags().WindowsRuntime()) ? "IUnknown" : "IInspectable";
w.write("public class %: %.% {\n",
bind_type_abi(type),
w.support,
baseClass);
auto class_indent_guard = w.push_indent();
auto iid_format = "override public class var IID: %.IID { IID_% }\n\n";
w.write(iid_format, w.support, bind_type_mangled(type));
for (const auto& function : methods)
{
if (!can_write(w, function, true)) continue;
try
{
auto func_name = get_abi_name(function);
auto full_names = w.push_full_type_names(true);
auto returnStatement = isInitializer ?
w.write_temp(" -> %", bind_type_abi(classType->default_interface)) :
w.write_temp("%", bind<write_return_type_declaration>(function, write_type_params::swift));
std::vector<function_param> params = composableFactory ? get_projected_params(factory_info.value(), function) : function.params;
std::string written_params = w.write_temp("%", bind<write_function_params2>(params, write_type_params::swift));
if (composableFactory)
{
if (params.size() > 0) written_params.append(", ");
written_params.append(w.write_temp("_ baseInterface: UnsealedWinRTClassWrapper<%.Composable>?, _ innerInterface: inout %.IInspectable?", bind_bridge_name(*classType), w.support));
}
w.write("% func %(%) throws% {\n",
is_exclusive(type) ? "public" : "open",
func_name,
written_params,
returnStatement);
{
auto function_indent_guard = w.push_indent();
std::vector<writer::indent_guard> initialize_result_indent;
if (function.return_type)
{
if (auto result = write_init_return_val_abi(w, function.return_type.value()))
{
initialize_result_indent.push_back(std::move(result.value()));
}
}
{
auto guard = write_local_param_wrappers(w, params);
if (composableFactory)
{
w.write("let _baseInterface = baseInterface?.toIInspectableABI { $0 }\n");
w.write("let (_innerInterface) = try ComPtrs.initialize { _innerInterfaceAbi in\n");
guard.push_indent();
guard.push("}\n");
guard.push("innerInterface = %.IInspectable(_innerInterface!)\n", w.support);
}
w.write(R"(_ = try perform(as: %.self) { pThis in
try CHECKED(pThis.pointee.lpVtbl.pointee.%(%))
}
)",
bind_type_mangled(type),
func_name,
bind<write_abi_args>(function));
}
for (auto&& guard : initialize_result_indent)
{
guard.end();
w.write("}\n");
}
if (function.return_type && !isInitializer)
{
w.write("%\n", bind<write_consume_return_statement>(function));
}
else if (isInitializer)
{
w.write("return %(%!)\n", bind_type_abi(classType->default_interface), function.return_type->name);
}
}
w.write("}\n\n");
}
catch (std::exception const& e)
{
throw_invalid(e.what(),
"\n method: ", get_name(function),
"\n type: ", get_full_type_name(type),
"\n database: ", type.type().get_database().path());
}
}
class_indent_guard.end();
w.write("}\n\n");
}
static void write_implementable_interface(writer& w, interface_type const& type);
static void write_interface_generic(writer& w, generic_inst const& type)
{
type.write_swift_declaration(w);
if (!is_winrt_ireference(type))
{
auto generic_params = w.push_generic_params(type);
do_write_interface_abi(w, *type.generic_type(), type.functions);
}
}
static void write_ireference_init_extension(writer& w, generic_inst const& type)
{
if (!is_winrt_ireference(type)) return;
auto generic_param = type.generic_params()[0];
w.add_depends(*generic_param);
auto impl_names = w.push_impl_names(true);
w.write(R"(internal enum %: ReferenceBridge {
typealias CABI = %
typealias SwiftProjection = %
static var IID: %.IID { IID_% }
static func from(abi: ComPtr<CABI>?) -> SwiftProjection? {
guard let val = abi else { return nil }
var result: %%
try! CHECKED(val.get().pointee.lpVtbl.pointee.get_Value(val.get(), &result))
return %
}
static func makeAbi() -> CABI {
let vtblPtr = withUnsafeMutablePointer(to: &%VTable) { $0 }
return .init(lpVtbl: vtblPtr)
}
}
)", bind_bridge_name(type),
type.mangled_name(),
get_full_swift_type_name(w, generic_param),
w.support,
type.mangled_name(),
bind<write_type>(*generic_param, write_type_params::c_abi),
bind<write_default_init_assignment>(*generic_param, projection_layer::c_abi),
bind<write_consume_type>(generic_param, "result", true),
type.mangled_name());
}
static void write_class_func_body(writer& w, function_def const& function, interface_info const& iface, bool is_noexcept);
static void write_comma_param_names(writer& w, std::vector<function_param> const& params);
template <typename T>
static void write_delegate_extension(writer& w, T const& inst, function_def const& invoke_method)
{
auto delegate_abi_name = w.write_temp("%", bind_type_mangled(inst));
constexpr bool is_generic = std::is_same_v<T, generic_inst>;
w.write(R"(% extension WinRTDelegateBridge where CABI == % {
static func makeAbi() -> CABI {
let vtblPtr = withUnsafeMutablePointer(to: &%.%VTable) { $0 }
return .init(lpVtbl:vtblPtr)
}
}
)", is_generic ? "internal" : "public",
delegate_abi_name,
is_generic ? w.swift_module : abi_namespace(w.type_namespace),
is_generic ? delegate_abi_name : w.write_temp("%", inst));
}
static void write_generic_extension(writer& w, generic_inst const& inst)
{
if (is_winrt_ireference(inst))
{
write_ireference_init_extension(w, inst);
}
else if (is_delegate(inst))
{
auto guard{ w.push_generic_params(inst) };
write_delegate_extension(w, inst, inst.functions[0]);
}
}
static void write_interface_abi(writer& w, interface_type const& type)
{
// Don't write generic interfaces defintions at the ABI layer, we need an actual
// instantiation of the type in order to create vtables and actual implementations
if (!can_write(w, type) || type.is_generic()) return;
do_write_interface_abi(w, type, type.functions);
if (!is_exclusive(type))
{
write_implementable_interface(w, type);
}
}
static void write_vtable(writer& w, interface_type const& type);
static void write_vtable(writer& w, delegate_type const& type);
template <typename T>
static void write_delegate_wrapper(writer& w, T const& type)
{
auto impl_name = w.write_temp("%", bind_bridge_fullname(type));
auto wrapper_name = w.write_temp("%", bind_wrapper_name(type));
auto format = R"(
typealias % = InterfaceWrapperBase<%>
)";
w.write(format, wrapper_name, impl_name);
}
static void write_generic_delegate_wrapper(writer& w, generic_inst const& generic)
{
write_delegate_wrapper(w, generic);
}
static void write_delegate_abi(writer& w, delegate_type const& type)
{
if (type.is_generic()) return;
w.write("// MARK - %\n", type);
w.write("extension % {\n", abi_namespace(w.type_namespace));
{
auto guard(w.push_indent());
do_write_interface_abi(w, type, type.functions);
write_delegate_wrapper(w, type);
write_vtable(w, type);
}
w.write("}\n");
write_delegate_extension(w, type, type.functions[0]);
}
static void write_struct_abi(writer& w, struct_type const& type)
{
bool is_blittable = is_struct_blittable(type);
if (is_blittable)
{
return;
}
// for non blittable structs we need to create a type which helps us convert between
// swift and C land
w.write("public class _ABI_% {\n", type.swift_type_name());
{
auto class_indent_guard = w.push_indent();
w.write("public var val: % = .init()\n", bind_type_mangled(type));
w.write("public init() { }\n");
w.write("public init(from swift: %) {\n", get_full_swift_type_name(w, type));
{
auto push_abi = w.push_abi_types(true);
auto indent = w.push_indent();
for (const auto& field : type.members)
{
// WIN-64 - swiftwinrt: support boxing/unboxing
// WIN-65 - swiftwinrt: support generic types
if (can_write(w, field.type))
{
std::string from = std::string("swift.").append(get_swift_name(field));
if (is_winrt_ireference(field.type))
{
w.write("let %Wrapper = %(%)\n", get_abi_name(field), bind_wrapper_fullname(field.type), from);
w.write("%Wrapper?.copyTo(&val.%)\n", get_abi_name(field), get_abi_name(field));
}
else
{
w.write("val.% = %\n",
get_abi_name(field),
bind<write_consume_type>(field.type, from, false)
);
}
}
}
}
w.write("}\n\n");
w.write("public func detach() -> % {\n", bind_type_mangled(type));
{
auto indent = w.push_indent();
w.write("let result = val\n");
for (const auto& member : type.members)
{
auto field = member.field;
if (get_category(member.type) == param_category::string_type ||
is_winrt_ireference(member.type))
{
w.write("val.% = nil\n", get_abi_name(member));
}
}
w.write("return result\n");
}
w.write("}\n\n");
w.write("deinit {\n");
{
auto indent = w.push_indent();
for (const auto& member : type.members)
{
if (get_category(member.type) == param_category::string_type)
{
w.write("WindowsDeleteString(val.%)\n", get_abi_name(member));
}
else if (is_winrt_ireference(member.type))
{
w.write("_ = val.%?.pointee.lpVtbl.pointee.Release(val.%)\n", get_abi_name(member), get_abi_name(member));
}
}
}
w.write("}\n");
}
w.write("}\n");
}
static void write_convert_vtable_params(writer& w, function_def const& signature)
{
int param_number = 1;
auto full_type_names = w.push_full_type_names(true);
for (auto& param : signature.params)
{
std::string param_name = "$" + std::to_string(param_number);
if (param.is_array())
{
auto array_param_name = "$" + std::to_string(param_number + 1);
auto count_param_name = param_name;
if (param.in())
{
w.write("let %: [%] = %\n",
get_swift_name(param),
bind<write_type>(*param.type, write_type_params::swift),
bind<write_convert_array_from_abi>(*param.type, w.write_temp("(count: %, start: %)", count_param_name, array_param_name)));
}
else if (param.signature.ByRef())
{
w.write("var % = [%]()\n",
get_swift_name(param),
bind<write_type>(*param.type, write_type_params::swift));
}
else
{
w.write("var %: [%] = %\n",
get_swift_name(param),
bind<write_type>(*param.type, write_type_params::swift),
bind<write_convert_array_from_abi>(*param.type, w.write_temp("(count: %, start: %)", count_param_name, array_param_name)));
}
++param_number;
}
else if (param.in())
{
assert(!param.out());
if (is_delegate(param.type))
{
w.write("guard let % = % else { return E_INVALIDARG }\n",
get_swift_name(param),
bind<write_consume_type>(param.type, param_name, false));
}
else
{
w.write("let %: % = %\n",
get_swift_name(param),
bind<write_type>(*param.type, write_type_params::swift),
bind<write_consume_type>(param.type, param_name, false));
}
}
else
{
assert(!param.in());
assert(param.out());
w.write("var %: %%\n",
get_swift_name(param),
bind<write_type>(*param.type, write_type_params::swift),
bind<write_default_init_assignment>(*param.type, projection_layer::swift));
}
++param_number;
}
}
static void write_consume_return_statement(writer& w, function_def const& signature)
{
if (!signature.return_type)
{
return;
}
auto return_type = signature.return_type.value();
auto return_param_name = put_in_backticks_if_needed(std::string(return_type.name));
if (return_type.is_array())
{
w.write("defer { CoTaskMemFree(%.start) }\n", return_param_name);
w.write("return %\n", bind<write_convert_array_from_abi>(*return_type.type, return_param_name));
}
else
{
w.write("return %", bind<write_consume_type>(return_type.type, return_param_name, true));
}
}
static void write_consume_args(writer& w, function_def const& function)
{
separator s{ w };
for (auto& param : function.params)
{
s();
if (param.in())
{
w.write(get_swift_name(param));
}
else
{
w.write("&%", get_swift_name(param));
}
}
}
static void write_implementable_interface(writer& w, interface_type const& type)
{
write_vtable(w, type);
// Define a struct that matches a C++ object with a vtable. As background:
//
// in C++ this looks like:
//
// class CMyObject : public IMyInterface {
// {
// HRESULT Foo(int number);
// }
//
// in C it looks
//
// struct __x_ABI_MyObjectVTable {
// ... AddRef, Release, QI, ...
// HRESULT (STDMETHODCALLTYPE * Foo)(__x_ABI_IMyInterface* pThis, int number)
// }
//
// struct __x_ABI_IMyInterface {
// const __x_ABI_MyObjectVTable* lpVtbl;
// }
//
// so in Swift we're using the pattern:
//
// protocol IMyInterface
// {
// func Foo(number: Int32)
// }
//
// private var myInterfaceVTable: __x_ABI_MyObjectVTable {
// Foo: {
// // In C, 'pThis' is always the first param
// guard let instance = MyInterfaceWrapper.try_unwrap_raw($0)?.takeUnretainedValue().swiftObj else {
// return E_INVALIDARG
// }
// let number = $1
// instance.Foo(number)
// }
// }
// ...
// class MyInterfaceWrapper : WinRTWrapperBase<__x_ABI_IMyInterface, IMyInterface> {
// init(impl: IMyInterface) {
// let abi = withUnsafeMutablePointer(to: &myInterfaceVTable) {
// __x_ABI_IMyInterface(lpVtbl: $0)
// }
// super.init(abi, impl)
// }
// Where the WinRTWrapperBase defines the behavior for all objects which need to wrap a
// swift object and pass it down to WinRT:
// open class WinRTWrapperBase<CInterface, Prototype> {
// public struct ComObject {
// public var comInterface : CInterface
// public var wrapper : Unmanaged<WinRTWrapperBase>?
// }
// public var instance : ComObject
// public var swiftObj : Prototype
// ...
// }
w.write(R"(
public typealias % = InterfaceWrapperBase<%>
)",
bind_wrapper_name(type),
bind_bridge_fullname(type));
}
static void write_class_impl_func(writer& w, function_def const& method, interface_info const& iface, typedef_base const& type_definition);
static void write_class_impl_property(writer& w, property_def const& prop, interface_info const& iface, typedef_base const& type_definition);
static void write_class_impl_event(writer& w, event_def const& event, interface_info const& iface, typedef_base const& type_definition);
static void write_property_value_impl(writer& w)
{
auto winrtInterfaceConformance = w.write_temp(R"(
public func queryInterface(_ iid: %.IID) -> IUnknownRef? {
guard iid == __ABI_Windows_Foundation.IPropertyValueWrapper.IID else { return nil }
guard let thisAsIPropValue = __ABI_Windows_Foundation.IPropertyValueWrapper(self) else { fatalError("creating non-nil wrapper shouldn't fail") }
return thisAsIPropValue.queryInterface(iid)
}
)", w.support);
w.write(R"(public class IPropertyValueImpl : IPropertyValue, IReference {
public typealias T = Any
var _value: Any
var propertyType : PropertyType
fileprivate init(_ abi: ComPtr<__x_ABI_CWindows_CFoundation_CIPropertyValue>) { fatalError("not implemented") }
public init(value: Any) {
_value = value
propertyType = switch value {
case is UInt8: .uint8
case is Int16: .int16
case is UInt16: .uint16
case is Int32: .int32
case is UInt32: .uint32
case is Int64: .int64
case is UInt64: .uint64
case is Float: .single
case is Double: .double
case is Character: .char16
case is Bool: .boolean
case is String: .string
case is DateTime: .dateTime
case is TimeSpan: .timeSpan
case is Foundation.UUID: .guid
case is Point: .point
case is Size: .size
case is Rect: .rect
case is IWinRTObject: .inspectable
case is IInspectable: .inspectable
case is [UInt8]: .uint8Array
case is [Int16]: .int16Array
case is [UInt16]: .uint16Array
case is [Int32]: .int32Array
case is [UInt32]: .uint32Array
case is [Int64]: .int64Array
case is [UInt64]: .uint64Array
case is [Float]: .singleArray
case is [Double]: .doubleArray
case is [Character]: .char16Array
case is [Bool]: .booleanArray
case is [String]: .stringArray
case is [DateTime]: .dateTimeArray
case is [TimeSpan]: .timeSpanArray
case is [Foundation.UUID]: .guidArray
case is [Point]: .pointArray
case is [Size]: .sizeArray
case is [Rect]: .rectArray
case is [Any?]: .inspectableArray
default: .otherType
}
}
public var type: PropertyType { propertyType }
public var isNumericScalar: Bool {
switch propertyType {
case .int16, .int32, .int64, .uint8, .uint16, .uint32, .uint64, .single, .double: return true
default: return false