-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmetadata_cache.cpp
1152 lines (1005 loc) · 39.7 KB
/
metadata_cache.cpp
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
#include "pch.h"
#include "types.h"
#include "abi_writer.h"
#include "metadata_cache.h"
#include "metadata_filter.h"
#include "task_group.h"
#include "helpers.h"
#include "versioning.h"
using namespace std::literals;
using namespace winmd::reader;
using namespace swiftwinrt;
metadata_cache::metadata_cache(winmd::reader::cache const& c)
{
// We need to initialize in two phases. The first phase creates the collection of all type defs. The second phase
// processes dependencies and initializes generic types
// NOTE: We may only need to do this for a subset of types, but that would introduce a fair amount of complexity and
// the runtime cost of processing everything is relatively insignificant
task_group group;
for (auto const& [ns, members] : c.namespaces())
{
// We don't do any synchronization of access to this type's data structures, so reserve space on the "main"
// thread. Note that set/map iterators are not invalidated on insert/emplace
auto [nsItr, nsAdded] = namespaces.emplace(std::piecewise_construct,
std::forward_as_tuple(ns),
std::forward_as_tuple());
XLANG_ASSERT(nsAdded);
auto [tableItr, tableAdded] = m_typeTable.emplace(std::piecewise_construct,
std::forward_as_tuple(ns),
std::forward_as_tuple());
XLANG_ASSERT(tableAdded);
group.add([&, &members = members, &nsTypes = nsItr->second, &table = tableItr->second]()
{
process_namespace_types(members, nsTypes, table);
});
}
group.get();
for (auto& [ns, nsCache] : namespaces)
{
group.add([&, &nsCache = nsCache]()
{
process_namespace_dependencies(nsCache);
});
}
group.get();
}
void metadata_cache::process_namespace_types(
cache::namespace_members const& members,
namespace_cache& target,
std::map<std::string_view, metadata_type const&>& table)
{
// Mapped types are only in the 'Windows.Foundation' namespace, so pre-compute
bool isFoundationNamespace = members.types.begin()->second.TypeNamespace() == winrt_foundation_namespace;
target.enums.reserve(members.enums.size());
for (auto const& e : members.enums)
{
target.enums.emplace_back(e);
[[maybe_unused]] auto [itr, added] = table.emplace(e.TypeName(), target.enums.back());
XLANG_ASSERT(added);
}
target.structs.reserve(members.structs.size());
for (auto const& s : members.structs)
{
// 'EventRegistrationToken' and 'HResult' are structs
if (isFoundationNamespace)
{
if (auto ptr = mapped_type::from_typedef(s))
{
[[maybe_unused]] auto [itr, added] = table.emplace(s.TypeName(), *ptr);
XLANG_ASSERT(added);
continue;
}
}
target.structs.emplace_back(s);
[[maybe_unused]] auto [itr, added] = table.emplace(s.TypeName(), target.structs.back());
XLANG_ASSERT(added);
}
target.delegates.reserve(members.delegates.size());
for (auto const& d : members.delegates)
{
target.delegates.emplace_back(d);
[[maybe_unused]] auto [itr, added] = table.emplace(d.TypeName(), target.delegates.back());
XLANG_ASSERT(added);
// emplace the generic parameters for the delegate. these are dummy types like "T" or "V"
// and are used for later resolution of types
for (auto& param : d.GenericParam())
{
target.delegates.back().generic_params.emplace_back(param.Name());
table.emplace(param.Name(), target.delegates.back().generic_params.back());
}
}
target.interfaces.reserve(members.interfaces.size());
for (auto const& i : members.interfaces)
{
target.interfaces.emplace_back(i);
[[maybe_unused]] auto [itr, added] = table.emplace(i.TypeName(), target.interfaces.back());
XLANG_ASSERT(added);
// emplace the generic parameters for the interface. these are dummy types like "T" or "V"
// and are used for later resolution of types
for (auto& param : i.GenericParam())
{
target.interfaces.back().generic_params.emplace_back(param.Name());
table.emplace(param.Name(), target.interfaces.back().generic_params.back());
}
}
target.classes.reserve(members.classes.size());
for (auto const& c : members.classes)
{
target.classes.emplace_back(c);
[[maybe_unused]] auto [itr, added] = table.emplace(c.TypeName(), target.classes.back());
XLANG_ASSERT(added);
}
for (auto const& contract : members.contracts)
{
// Contract versions are attributes on the contract type itself
auto attr = get_attribute(contract, metadata_namespace, "ContractVersionAttribute"sv);
XLANG_ASSERT(attr);
XLANG_ASSERT(attr.Value().FixedArgs().size() == 1);
target.contracts.push_back(api_contract{
contract,
std::get<uint32_t>(std::get<ElemSig>(attr.Value().FixedArgs()[0].value).value)
});
}
}
void metadata_cache::process_namespace_dependencies(namespace_cache& target)
{
init_state state{ &target };
for (auto& enumType : target.enums)
{
process_enum_dependencies(state, enumType);
XLANG_ASSERT(!state.parent_generic_iface_or_delegate);
XLANG_ASSERT(!state.parent_generic_inst);
}
for (auto& structType : target.structs)
{
process_struct_dependencies(state, structType);
XLANG_ASSERT(!state.parent_generic_iface_or_delegate);
XLANG_ASSERT(!state.parent_generic_inst);
}
for (auto& delegateType : target.delegates)
{
process_delegate_dependencies(state, delegateType);
XLANG_ASSERT(!state.parent_generic_iface_or_delegate);
XLANG_ASSERT(!state.parent_generic_inst);
}
for (auto& interfaceType : target.interfaces)
{
process_interface_dependencies(state, interfaceType);
XLANG_ASSERT(!state.parent_generic_iface_or_delegate);
XLANG_ASSERT(!state.parent_generic_inst);
}
for (auto& classType : target.classes)
{
process_class_dependencies(state, classType);
XLANG_ASSERT(!state.parent_generic_iface_or_delegate);
XLANG_ASSERT(!state.parent_generic_inst);
}
}
template <typename T>
static void process_contract_dependencies(namespace_cache& target, T const& type)
{
if (auto attr = swiftwinrt::get_contract_history(type))
{
target.dependent_namespaces.emplace(decompose_type(attr->current_contract.name).first);
for (auto const& prevContract : attr->previous_contracts)
{
target.dependent_namespaces.emplace(decompose_type(prevContract.contract_from).first);
}
}
if (auto info = is_deprecated(type))
{
target.dependent_namespaces.emplace(decompose_type(info->contract_type).first);
}
}
interface_info* metadata_cache::find(get_interfaces_t& interfaces, std::string_view const& name)
{
auto pair = std::find_if(interfaces.begin(), interfaces.end(), [&](auto&& pair)
{
return pair.first == name;
});
if (pair == interfaces.end())
{
return nullptr;
}
return &pair->second;
}
void metadata_cache::insert_or_assign(get_interfaces_t& interfaces, std::string_view const& name, interface_info&& info)
{
if (auto existing = find(interfaces, name))
{
*existing = std::move(info);
}
else
{
interfaces.emplace_back(name, std::move(info));
}
}
void metadata_cache::get_interfaces_impl(init_state& state, writer& w, get_interfaces_t& result, bool defaulted, bool overridable, bool base, std::pair<InterfaceImpl, InterfaceImpl>&& children)
{
for (auto&& impl : children)
{
interface_info info;
auto type = impl.Interface();
info.type = &find_dependent_type(state, type);
info.is_default = has_attribute(impl, "Windows.Foundation.Metadata", "DefaultAttribute");
info.defaulted = !base && (defaulted || info.is_default);
writer::generic_param_guard guard;
if (auto genericInst = dynamic_cast<const generic_inst*>(info.type))
{
guard = w.push_generic_params(*genericInst);
info.generic_params = w.generic_param_stack.back();
}
auto name = w.write_temp("%", info.type);
{
// This is for correctness rather than an optimization (but helps performance as well).
// If the interface was not previously inserted, carry on and recursively insert it.
// If a previous insertion was defaulted we're done as it is correctly captured.
// If a newly discovered instance of a previous insertion is not defaulted, we're also done.
// If it was previously captured as non-defaulted but now found as defaulted, we carry on and
// rediscover it as we need it to be defaulted recursively.
if (auto found = find(result, name))
{
if (found->defaulted || !info.defaulted)
{
continue;
}
}
}
info.overridable = overridable || has_attribute(impl, metadata_namespace, "OverridableAttribute");
info.base = base;
if (auto typeBase = dynamic_cast<const interface_type*>(info.type))
{
info.exclusive = has_attribute(typeBase->type(), "Windows.Foundation.Metadata", "ExclusiveToAttribute");
process_contract_dependencies(*state.target, impl);
get_interfaces_impl(state, w, result, info.defaulted, info.overridable, base, typeBase->type().InterfaceImpl());
try_insert_buffer_byte_access(typeBase->type(), result, info.defaulted);
}
insert_or_assign(result, name, std::move(info));
}
};
void metadata_cache::try_insert_buffer_byte_access(winmd::reader::TypeDef const& type, get_interfaces_t& result, bool defaulted = false)
{
if (type.TypeNamespace() == "Windows.Foundation" && type.TypeName() == "IMemoryBufferReference")
{
insert_or_assign(result, "IMemoryBufferByteAccess", { &system_type::from_name("IMemoryBufferByteAccess"), false, defaulted });
}
else if (type.TypeNamespace() == "Windows.Storage.Streams" && type.TypeName() == "IBuffer")
{
insert_or_assign(result, "IBufferByteAccess", { &system_type::from_name("IBufferByteAccess"), false, defaulted });
}
}
metadata_cache::get_interfaces_t metadata_cache::get_interfaces(init_state& state, TypeDef const& type)
{
get_interfaces_t result;
writer w;
w.type_namespace = type.TypeNamespace();
get_interfaces_impl(state, w, result, false, false, false, type.InterfaceImpl());
for (auto&& base : get_bases(type))
{
get_interfaces_impl(state,w, result, false, false, true, base.InterfaceImpl());
}
try_insert_buffer_byte_access(type, result);
if (!has_fastabi(type))
{
return result;
}
size_t count = 0;
auto get_interface_type = [](const metadata_type* metadataType) -> TypeDef {
TypeDef interfaceType{};
if (auto genericInst = dynamic_cast<const generic_inst*>(metadataType))
{
interfaceType = genericInst->generic_type()->type();
}
else if (auto iFaceType = dynamic_cast<const interface_type*>(metadataType))
{
interfaceType = iFaceType->type();
}
else
{
interfaceType = dynamic_cast<const mapped_type*>(metadataType)->type();
}
assert(interfaceType);
return interfaceType;
};
if (auto history = get_contract_history(type))
{
for (auto& pair : result)
{
if (pair.second.exclusive && !pair.second.base && !pair.second.overridable)
{
++count;
auto interfaceType = get_interface_type(pair.second.type);
auto introduced = get_initial_contract_version(interfaceType);
pair.second.relative_version.second = introduced.version;
auto itr = std::find_if(history->previous_contracts.begin(), history->previous_contracts.end(), [&](previous_contract const& prev)
{
return prev.contract_from == introduced.name;
});
if (itr != history->previous_contracts.end())
{
pair.second.relative_version.first = static_cast<uint32_t>(itr - history->previous_contracts.begin());
}
else
{
assert(history->current_contract.name == introduced.name);
pair.second.relative_version.first = static_cast<uint32_t>(history->previous_contracts.size());
}
}
}
}
std::partial_sort(result.begin(), result.begin() + count, result.end(), [&get_interface_type](auto&& left_pair, auto&& right_pair)
{
auto& left = left_pair.second;
auto& right = right_pair.second;
// Sort by base before is_default because each base will have a default.
if (left.base != right.base)
{
return !left.base;
}
if (left.is_default != right.is_default)
{
return left.is_default;
}
if (left.overridable != right.overridable)
{
return !left.overridable;
}
if (left.exclusive != right.exclusive)
{
return left.exclusive;
}
auto left_enabled = is_always_enabled(get_interface_type(left.type));
auto right_enabled = is_always_enabled(get_interface_type(right.type));
if (left_enabled != right_enabled)
{
return left_enabled;
}
if (left.relative_version != right.relative_version)
{
return left.relative_version < right.relative_version;
}
return left_pair.first < right_pair.first;
});
std::for_each_n(result.begin(), count, [](auto&& pair)
{
pair.second.fastabi = true;
});
return result;
}
void metadata_cache::process_enum_dependencies(init_state& state, enum_type& type)
{
// There's no pre-processing that we need to do for enums. Just take note of the namespace dependencies that come
// from contract version(s)/deprecations
process_contract_dependencies(*state.target, type.type());
for (auto const& field : type.type().FieldList())
{
process_contract_dependencies(*state.target, field);
}
}
void metadata_cache::process_struct_dependencies(init_state& state, struct_type& type)
{
process_contract_dependencies(*state.target, type.type());
for (auto const& field : type.type().FieldList())
{
process_contract_dependencies(*state.target, field);
type.members.push_back(struct_member{ field, &find_dependent_type(state, field.Signature().Type()) });
}
}
void metadata_cache::process_delegate_dependencies(init_state& state, delegate_type& type)
{
process_contract_dependencies(*state.target, type.type());
// We only care about instantiations of generic types, so early exit as we won't be able to resolve references
if (type.is_generic())
{
state.parent_generic_iface_or_delegate = &type;
}
// Delegates only have a single function - Invoke - that we care about
for (auto const& method : type.type().MethodList())
{
if (method.Name() != ".ctor"sv)
{
XLANG_ASSERT(method.Name() == "Invoke"sv);
process_contract_dependencies(*state.target, method);
type.functions.push_back(process_function(state, method));
break;
}
}
// Should be exactly one function named 'Invoke'
XLANG_ASSERT(type.functions.size() == 1);
state.parent_generic_iface_or_delegate = nullptr;
}
void metadata_cache::process_interface_dependencies(init_state& state, interface_type& type)
{
process_contract_dependencies(*state.target, type.type());
if (type.is_generic())
{
state.parent_generic_iface_or_delegate = &type;
}
for (auto const& interfaces : get_interfaces(state, type.type()))
{
type.required_interfaces.push_back(interfaces);
}
for (auto const& method : type.type().MethodList())
{
process_contract_dependencies(*state.target, method);
type.functions.push_back(process_function(state, method));
}
for (auto const& prop : type.type().PropertyList())
{
type.properties.push_back(process_property(state, prop));
}
for (auto const& event : type.type().EventList())
{
type.events.push_back(process_event(state, event));
}
state.parent_generic_iface_or_delegate = nullptr;
}
void metadata_cache::process_class_dependencies(init_state& state, class_type& type)
{
process_contract_dependencies(*state.target, type.type());
// We only care about instantiations of generic types, so early exit as we won't be able to resolve references
if (type.is_generic())
{
return;
}
if (auto base = get_base_class(type.type()))
{
type.base_class = &dynamic_cast<class_type const&>(this->find(base.TypeNamespace(), base.TypeName()));
}
for (auto const& iface : get_interfaces(state, type.type()))
{
type.required_interfaces.push_back(iface);
// NOTE: Types can have more than one default interface so long as they apply to different platforms. This is
// not very useful, as we have to choose one to use for function argument types, but it technically is
// allowed... If that's the case, just use the first one we encounter as this has the highest probability
// of matching MIDLRT's behavior
if (iface.second.is_default && !type.default_interface)
{
type.default_interface = iface.second.type;
}
}
type.factories = get_attributed_types(type.type());
if (auto fastAttr = get_attribute(type.type(), metadata_namespace, "FastAbiAttribute"sv))
{
auto attrVer = version_from_attribute(fastAttr);
interface_type* fastInterface = nullptr;
relative_version_map rankingMap;
for (auto const& ifaceImpl : type.type().InterfaceImpl())
{
// If the interface is not exclusive to this class, ignore
auto iface = dynamic_cast<interface_type const*>(&find_dependent_type(state, ifaceImpl.Interface()));
if (!iface || !is_exclusive(iface->type()))
{
continue;
}
// Make sure that this interface reference applies for the same versioning "scheme" as the attribute
auto verMatch = match_versioning_scheme(attrVer, ifaceImpl);
if (!verMatch)
{
// No match on the interface reference is okay so long as there is _no_ versioning information on the
// reference. If there's not, then the requirement applies to all versioning schemes, so we look at the
// interface for the versioning information
if (get_attribute(ifaceImpl, metadata_namespace, "ContractVersionAttribute"sv) ||
get_attribute(ifaceImpl, metadata_namespace, "VersionAttribute"sv))
{
continue;
}
verMatch = match_versioning_scheme(attrVer, iface->type());
if (!verMatch)
{
XLANG_ASSERT(false);
continue;
}
}
// Take note if this is the default interface
if (is_default(ifaceImpl))
{
XLANG_ASSERT(!fastInterface);
XLANG_ASSERT(!iface->fast_class);
// NOTE: 'find_dependent_type' returns a const-ref since there are some items that it returns that may
// actually be const. This is not true for 'interface_type', hence the 'const_cast' here is appropriate
fastInterface = const_cast<interface_type*>(iface);
fastInterface->fast_class = &type;
continue;
}
// Ignore this interface if it's overridable, experimental, or in a disabled state
if (is_overridable(ifaceImpl))
{
continue;
}
else if (is_experimental(ifaceImpl) || is_experimental(iface->type()))
{
continue;
}
// Determine how this interface's inclusion in the class relates to the class' version history
relative_version relVer = {};
call(*verMatch,
[&](contract_version const& ver)
{
relVer.first = *type.contract_index(ver.name, ver.version);
relVer.second = ver.version;
},
[&](platform_version const& ver)
{
// For platform versioning, the "relative contract" (relVer.first) is always zero
relVer.second = ver.version;
});
process_fastabi_required_interfaces(state, iface, relVer, rankingMap);
}
if (fastInterface)
{
// The fast default interface may have gotten added to the map as a required interface. If so, remove it
if (auto itr = rankingMap.find(fastInterface); itr != rankingMap.end())
{
rankingMap.erase(itr);
}
for (auto& [iface, rank] : rankingMap)
{
version ver;
if (std::holds_alternative<contract_version>(attrVer))
{
ver = contract_version{ type.contract_from_index(rank.first)->name, rank.second };
}
else // platform_version
{
ver = platform_version{ std::get<platform_version>(attrVer).platform, rank.second };
}
type.supplemental_fast_interfaces.push_back({ iface, ver });
}
std::sort(type.supplemental_fast_interfaces.begin(), type.supplemental_fast_interfaces.end(),
[&](auto const& lhs, auto const& rhs)
{
auto& [lhsPtr, lhsRank] = *rankingMap.find(lhs.first);
auto& [rhsPtr, rhsRank] = *rankingMap.find(rhs.first);
if (lhsRank == rhsRank)
{
// Same ranking; sort by type name
return lhsPtr->swift_full_name() < rhsPtr->swift_full_name();
}
return lhsRank < rhsRank;
});
}
else
{
XLANG_ASSERT(rankingMap.empty());
}
}
}
void metadata_cache::process_fastabi_required_interfaces(
init_state& state,
interface_type const* currentInterface,
relative_version rank,
relative_version_map& interfaceMap)
{
if (!is_exclusive(currentInterface->type()))
{
return; // Not exclusive-to, so can safely ignore
}
// NOTE: We should also ignore if this is the default interface that we are extending, however we may not have
// enough information at this point to make that determination, so just allow it and remove later
if (auto itr = interfaceMap.find(currentInterface); itr != interfaceMap.end())
{
if (itr->second <= rank)
{
return; // Already processed with at least as good a match
}
}
interfaceMap[currentInterface] = rank;
for (auto const& ifaceImpl : currentInterface->type().InterfaceImpl())
{
auto type = &find_dependent_type(state, ifaceImpl.Interface());
if (auto iface = dynamic_cast<interface_type const*>(type))
{
process_fastabi_required_interfaces(state, iface, rank, interfaceMap);
}
}
}
function_def metadata_cache::process_function(init_state& state, MethodDef const& def)
{
auto paramNames = def.ParamList();
auto sig = def.Signature();
XLANG_ASSERT(sig.GenericParamCount() == 0);
std::optional<function_return_type> return_type;
if (sig.ReturnType())
{
std::string_view name = "result"sv;
if ((paramNames.first != paramNames.second) && (paramNames.first.Sequence() == 0))
{
name = paramNames.first.Name();
++paramNames.first;
}
return_type = function_return_type{ sig.ReturnType(), name, &find_dependent_type(state, sig.ReturnType().Type()) };
}
std::vector<function_param> params;
for (auto const& param : sig.Params())
{
XLANG_ASSERT(paramNames.first != paramNames.second);
params.push_back(function_param{ paramNames.first, param, paramNames.first.Name(), &find_dependent_type(state, param.Type()) });
++paramNames.first;
}
return function_def{ def, std::move(return_type), std::move(params) };
}
property_def metadata_cache::process_property(init_state& state, Property const& def)
{
auto [getter, setter] = get_property_methods(def);
auto type = &find_dependent_type(state, def.Type().Type());
if (getter && setter)
{
return property_def{ def, type, process_function(state, getter), process_function(state, setter) };
}
else if (getter)
{
return property_def{ def, type, process_function(state, getter), {} };
}
else
{
return property_def{ def, type, {}, process_function(state, setter) };
}
}
event_def metadata_cache::process_event(init_state& state, Event const& def)
{
return event_def{ def, &find_dependent_type(state, def.EventType()) };
}
metadata_type const& metadata_cache::find_dependent_type(init_state& state, TypeSig const& type)
{
metadata_type const* result;
call(type.Type(),
[&](ElementType t)
{
result = &element_type::from_type(t);
},
[&](coded_index<TypeDefOrRef> const& t)
{
result = &find_dependent_type(state, t);
},
[&](GenericTypeIndex t)
{
if (state.parent_generic_inst)
{
if (t.index < state.parent_generic_inst->generic_params().size())
{
result = state.parent_generic_inst->generic_params()[t.index];
}
else
{
XLANG_ASSERT(false);
swiftwinrt::throw_invalid("GenericTypeIndex out of range");
}
}
else if (state.parent_generic_iface_or_delegate)
{
if (t.index < state.parent_generic_iface_or_delegate->generic_params.size())
{
result = &state.parent_generic_iface_or_delegate->generic_params[t.index];
}
else
{
XLANG_ASSERT(false);
swiftwinrt::throw_invalid("GenericTypeIndex out of range");
}
}
else
{
XLANG_ASSERT(false);
swiftwinrt::throw_invalid("GenericTypeIndex encountered with no generic instantiation to refer to");
}
},
[&](GenericTypeInstSig const& t)
{
result = &find_dependent_type(state, t);
},
[&](GenericMethodTypeIndex)
{
swiftwinrt::throw_invalid("Generic methods not supported");
}, [](auto&&) {});
return *result;
}
metadata_type const& metadata_cache::find_dependent_type(init_state& state, coded_index<TypeDefOrRef> const& type)
{
metadata_type const* result = nullptr;
switch (type.type())
{
case TypeDefOrRef::TypeSpec:
result = &find_dependent_type(state, type.TypeSpec().Signature().GenericTypeInst());
break;
case TypeDefOrRef::TypeDef:
case TypeDefOrRef::TypeRef:
auto [ns, name] = type_name::get_namespace_and_name(type);
result = &find(ns, name);
if (auto typeDef = dynamic_cast<typedef_base const*>(result))
{
auto swift_namespace = result->swift_abi_namespace();
state.target->dependent_namespaces.insert(swift_namespace);
if (!typeDef->is_generic())
{
state.target->type_dependencies.emplace(*typeDef);
}
}
break;
}
return *result;
}
metadata_type const& metadata_cache::find_dependent_type(init_state& state, GenericTypeInstSig const& type)
{
auto genericType = dynamic_cast<typedef_base const*>(&find_dependent_type(state, type.GenericType()));
if (!genericType)
{
XLANG_ASSERT(false);
swiftwinrt::throw_invalid("Generic types must be TypeDefs");
}
std::vector<metadata_type const*> genericParams;
for (auto const& param : type.GenericArgs())
{
genericParams.push_back(&find_dependent_type(state, param));
}
if (state.parent_generic_iface_or_delegate != nullptr)
{
// not a generic_inst, but an interface type, just return the generic type
return *genericType;
}
else
{
generic_inst inst{ genericType, std::move(genericParams) };
auto [itr, added] = state.target->generic_instantiations.emplace(inst.swift_full_name(), std::move(inst));
if (added)
{
auto restore = std::exchange(state.parent_generic_inst, &itr->second);
auto check_dependency = [&, &itr = itr](auto const& t)
{
auto mdType = &find_dependent_type(state, t);
if (auto genericType = dynamic_cast<generic_inst const*>(mdType))
{
itr->second.dependencies.push_back(genericType);
}
};
for (auto&& iface : get_interfaces(state, genericType->type()))
{
itr->second.required_interfaces.push_back(iface);
if (auto genericType = dynamic_cast<generic_inst const*>(iface.second.type))
{
itr->second.dependencies.push_back(genericType);
for (auto&& iface: get_interfaces(state, genericType->generic_type()->type()))
{
itr->second.required_interfaces.push_back(iface);
}
}
}
for (auto const& fn : genericType->type().MethodList())
{
if (fn.Name() == ".ctor"sv)
{
continue;
}
// TODO: Duplicated effort!
itr->second.functions.push_back(process_function(state, fn));
auto sig = fn.Signature();
if (sig.ReturnType())
{
check_dependency(sig.ReturnType().Type());
}
for (auto const& param : sig.Params())
{
check_dependency(param.Type());
}
}
for (auto const& prop : genericType->type().PropertyList())
{
itr->second.properties.push_back(process_property(state, prop));
}
for (auto const& event : genericType->type().EventList())
{
itr->second.events.push_back(process_event(state, event));
}
state.parent_generic_inst = restore;
}
return itr->second;
}
}
template <typename T>
static void merge_into(std::vector<T>& from, std::vector<std::reference_wrapper<T const>>& to, metadata_filter const& f)
{
std::vector<std::reference_wrapper<T const>> result;
to.reserve(from.size() + to.size());
for (auto& cp : from)
{
if (f.includes(cp.type()))
{
to.emplace_back(cp);
}
}
to.shrink_to_fit();
}
std::set<std::string_view> metadata_cache::get_dependent_namespaces(std::vector<std::string_view> const& targetNamespaces, metadata_filter const& f)
{
std::set<std::string_view> result;
for (auto ns : targetNamespaces)
{
auto itr = namespaces.find(ns);
if (itr == namespaces.end())
{
XLANG_ASSERT(false);
swiftwinrt::throw_invalid("Namespace '", ns, "' not found");
}
for (auto& dependent : itr->second.dependent_namespaces)
{
if (f.includes_ns(dependent))
{
result.insert(dependent);
}
}
}
return result;
}
type_cache metadata_cache::compile_namespaces(std::vector<std::string_view> const& targetNamespaces, metadata_filter const& f)
{
type_cache result{ this };
auto includes_namespace = [&](std::string_view ns)
{
return std::find(targetNamespaces.begin(), targetNamespaces.end(), ns) != targetNamespaces.end();
};
for (auto ns : targetNamespaces)
{
auto itr = namespaces.find(ns);
if (itr == namespaces.end())
{
XLANG_ASSERT(false);
swiftwinrt::throw_invalid("Namespace '", ns, "' not found");
}
// Merge the type definitions together
merge_into(itr->second.enums, result.enums, f);
merge_into(itr->second.structs, result.structs, f);
merge_into(itr->second.delegates, result.delegates, f);
merge_into(itr->second.interfaces, result.interfaces, f);
merge_into(itr->second.classes, result.classes, f);
// Merge the dependencies together
for (auto& dependent : itr->second.dependent_namespaces)
{
if (f.includes_ns(dependent))
{
result.dependent_namespaces.insert(dependent);
}
}
for (auto& generic : itr->second.generic_instantiations)
{
if (f.includes_generic(generic.first))
{
result.generic_instantiations.insert(generic);
}
}
for (auto& depends : itr->second.type_dependencies)
{
if (f.includes(depends.get().type()))
{
if (includes_namespace(depends.get().swift_logical_namespace()))
{
result.internal_dependencies.insert(depends);
}
else
{
result.external_dependencies.insert(depends);
}
}
}
for (auto& iface : result.interfaces)
{
if (!is_exclusive(iface.get()) && !iface.get().events.empty())
{
for (auto& event : iface.get().events)
{
if (result.implementable_event_types.find(event.type->swift_full_name()) == result.implementable_event_types.end())
{