22
22
import java .util .Arrays ;
23
23
import java .util .stream .Collectors ;
24
24
25
+ import static java .lang .foreign .ValueLayout .ADDRESS ;
25
26
import static java .lang .foreign .ValueLayout .JAVA_BYTE ;
26
27
27
28
public class SwiftKit {
@@ -349,6 +350,46 @@ public static long alignmentOfSwiftType(MemorySegment typeMetadata) {
349
350
return (flags & 0xFF ) + 1 ;
350
351
}
351
352
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
+
352
393
/**
353
394
* Produce a layout that describes a Swift type based on its
354
395
* type metadata. The resulting layout is completely opaque to Java, but
@@ -365,6 +406,6 @@ public static MemoryLayout layoutOfSwiftType(MemorySegment typeMetadata) {
365
406
MemoryLayout .sequenceLayout (size , JAVA_BYTE )
366
407
.withByteAlignment (alignmentOfSwiftType (typeMetadata )),
367
408
MemoryLayout .paddingLayout (stride - size )
368
- );
409
+ ). withName ( nameOfSwiftType ( typeMetadata , true )) ;
369
410
}
370
411
}
0 commit comments