Skip to main content

swift_runtime/
metadata.rs

1//! Safe metadata introspection.
2
3use core::ffi::c_void;
4use swift_runtime_sys::SwiftABI::*;
5
6/// A safe wrapper around a Swift type metadata pointer.
7#[derive(Clone, Copy)]
8pub struct Metadata(*const c_void);
9
10impl Metadata {
11    /// Create from a raw pointer. Returns None if null.
12    pub fn from_raw(ptr: *const c_void) -> Option<Self> {
13        if ptr.is_null() {
14            None
15        } else {
16            Some(Self(ptr))
17        }
18    }
19
20    /// Get the raw pointer.
21    pub fn as_raw(&self) -> *const c_void {
22        self.0
23    }
24
25    /// Get the metadata kind.
26    pub fn kind(&self) -> MetadataKind {
27        let raw = unsafe { *(self.0 as *const usize) };
28        get_enumerated_metadata_kind(raw)
29    }
30
31    /// Get the value witness table.
32    pub fn value_witness_table(&self) -> &ValueWitnessTable {
33        unsafe { &*get_value_witness_table(self.0) }
34    }
35
36    /// Get the size of values of this type.
37    pub fn size(&self) -> usize {
38        self.value_witness_table().get_size()
39    }
40
41    /// Get the stride of values of this type.
42    pub fn stride(&self) -> usize {
43        self.value_witness_table().get_stride()
44    }
45
46    /// Get the alignment of values of this type.
47    pub fn alignment(&self) -> usize {
48        self.value_witness_table().get_alignment()
49    }
50
51    /// Check if this type is POD (trivially copyable/destroyable).
52    pub fn is_pod(&self) -> bool {
53        self.value_witness_table().is_pod()
54    }
55
56    /// Get the human-readable type name.
57    pub fn type_name(&self, qualified: bool) -> Option<String> {
58        let result =
59            unsafe { swift_runtime_sys::SwiftCCThunks::swift_getTypeName(self.0, qualified) };
60        match result {
61            Ok((name, len)) if len > 0 => Some(name.to_string()),
62            _ => None,
63        }
64    }
65
66    /// Get the type context descriptor.
67    pub fn descriptor(&self) -> Option<*const c_void> {
68        let result =
69            unsafe { swift_runtime_sys::SwiftCCThunks::swift_getTypeContextDescriptor(self.0) };
70        match result {
71            Ok(ptr) if !ptr.is_null() => Some(ptr),
72            _ => None,
73        }
74    }
75
76    /// Get the descriptor name (e.g., "Int", "String").
77    pub fn descriptor_name(&self) -> Option<String> {
78        let desc = self.descriptor()?;
79        let tcd = unsafe { &*(desc as *const TypeContextDescriptor) };
80        let name = unsafe { tcd.get_name() };
81        name.to_str().ok().map(|s| s.to_string())
82    }
83}
84
85impl std::fmt::Debug for Metadata {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        let name = self
88            .type_name(true)
89            .unwrap_or_else(|| format!("{:?}", self.0));
90        write!(
91            f,
92            "Metadata({}, kind={:?}, size={})",
93            name,
94            self.kind(),
95            self.size()
96        )
97    }
98}
99
100/// Look up a type by mangled name.
101pub fn lookup_type(mangled: &[u8]) -> Option<Metadata> {
102    let ptr = unsafe {
103        swift_runtime_sys::RuntimeRaw::swift_getTypeByMangledNameInEnvironment(
104            mangled.as_ptr(),
105            mangled.len(),
106            core::ptr::null(),
107            0,
108        )
109    };
110    Metadata::from_raw(ptr)
111}