Skip to content

Commit 1a933fc

Browse files
committed
Swift SIL: add Type.getIndexOfEnumCase(withName:)
... to get the enum case index with a given name.
1 parent b0003d5 commit 1a933fc

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

SwiftCompilerSources/Sources/SIL/Type.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,14 @@ public struct Type : CustomStringConvertible, CustomReflectable {
4242
public func getNominalFields(in function: Function) -> NominalFieldsArray {
4343
NominalFieldsArray(type: self, function: function)
4444
}
45-
45+
46+
public func getIndexOfEnumCase(withName name: String) -> Int? {
47+
let idx = name.withBridgedStringRef {
48+
SILType_getCaseIdxOfEnumType(bridged, $0)
49+
}
50+
return idx >= 0 ? idx : nil
51+
}
52+
4653
public var description: String { SILType_debugDescription(bridged).takeString() }
4754

4855
public var customMirror: Mirror { Mirror(self, children: []) }

include/swift/SIL/SILBridging.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,8 @@ BridgedType SILType_getNominalFieldType(BridgedType type, SwiftInt index,
252252
BridgedFunction function);
253253
SwiftInt SILType_getFieldIdxOfNominalType(BridgedType type,
254254
BridgedStringRef fieldName);
255+
SwiftInt SILType_getCaseIdxOfEnumType(BridgedType type,
256+
BridgedStringRef caseName);
255257

256258
BridgedSubstitutionMap SubstitutionMap_getEmpty();
257259

lib/SIL/Utils/SILBridging.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,23 @@ SwiftInt SILType_getFieldIdxOfNominalType(BridgedType type,
489489
return -1;
490490
}
491491

492+
SwiftInt SILType_getCaseIdxOfEnumType(BridgedType type,
493+
BridgedStringRef caseName) {
494+
SILType ty = castToSILType(type);
495+
auto *enumDecl = ty.getEnumOrBoundGenericEnum();
496+
if (!enumDecl)
497+
return -1;
498+
499+
SwiftInt idx = 0;
500+
for (EnumElementDecl *elem : enumDecl->getAllElements()) {
501+
if (elem->getNameStr() == getStringRef(caseName))
502+
return idx;
503+
idx++;
504+
}
505+
return -1;
506+
}
507+
508+
492509
//===----------------------------------------------------------------------===//
493510
// SubstitutionMap
494511
//===----------------------------------------------------------------------===//

0 commit comments

Comments
 (0)