Skip to content

Commit 7dd04a5

Browse files
committed
Add SwiftKit.nameOfSwiftType() to get the name from Swift type metadata
Use this new API to give a name to the memory layout we create for a Swift type.
1 parent 968b3bc commit 7dd04a5

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

JavaSwiftKitDemo/src/main/java/org/swift/javakit/SwiftKit.java

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.util.Arrays;
2323
import java.util.stream.Collectors;
2424

25+
import static java.lang.foreign.ValueLayout.ADDRESS;
2526
import static java.lang.foreign.ValueLayout.JAVA_BYTE;
2627

2728
public class SwiftKit {
@@ -349,6 +350,46 @@ public static long alignmentOfSwiftType(MemorySegment typeMetadata) {
349350
return (flags & 0xFF) + 1;
350351
}
351352

353+
/**
354+
* Descriptor for the swift_getTypeName runtime function.
355+
*/
356+
public static final FunctionDescriptor swift_getTypeName$descriptor = FunctionDescriptor.of(
357+
/*returns=*/MemoryLayout.structLayout(
358+
SWIFT_POINTER.withName("utf8Chars"),
359+
SWIFT_INT.withName("length")
360+
),
361+
ValueLayout.ADDRESS,
362+
ValueLayout.JAVA_BOOLEAN
363+
);
364+
365+
/**
366+
* Address of the swift_getTypeName runtime function.
367+
*/
368+
public static final MemorySegment swift_getTypeName$addr = findOrThrow("swift_getTypeName");
369+
370+
/**
371+
* Handle for the swift_getTypeName runtime function.
372+
*/
373+
public static final MethodHandle swift_getTypeName$handle = Linker.nativeLinker().downcallHandle(swift_getTypeName$addr, swift_getTypeName$descriptor);
374+
375+
/**
376+
* Produce the name of the Swift type given its Swift type metadata.
377+
*
378+
* If 'qualified' is true, leave all of the qualification in place to
379+
* disambiguate the type, producing a more complete (but longer) type name.
380+
*/
381+
public static String nameOfSwiftType(MemorySegment typeMetadata, boolean qualified) {
382+
try {
383+
try (Arena arena = Arena.ofConfined()) {
384+
MemorySegment charsAndLength = (MemorySegment)swift_getTypeName$handle.invokeExact((SegmentAllocator)arena, typeMetadata, qualified);
385+
MemorySegment utf8Chars = charsAndLength.get(SWIFT_POINTER, 0);
386+
return utf8Chars.getString(0);
387+
}
388+
} catch (Throwable ex$) {
389+
throw new AssertionError("should not reach here", ex$);
390+
}
391+
}
392+
352393
/**
353394
* Produce a layout that describes a Swift type based on its
354395
* type metadata. The resulting layout is completely opaque to Java, but
@@ -365,6 +406,6 @@ public static MemoryLayout layoutOfSwiftType(MemorySegment typeMetadata) {
365406
MemoryLayout.sequenceLayout(size, JAVA_BYTE)
366407
.withByteAlignment(alignmentOfSwiftType(typeMetadata)),
367408
MemoryLayout.paddingLayout(stride - size)
368-
);
409+
).withName(nameOfSwiftType(typeMetadata, true));
369410
}
370411
}

0 commit comments

Comments
 (0)