Skip to main content

tpt_uir_ffi/
lib.rs

1#![doc = include_str!("../README.md")]
2
3//! C ABI for read-only inspection of TPT-UIR regions.
4//!
5//! The API is opaque-handle based: call [`tpt_uir_load`] to deserialize a
6//! postcard-encoded region into a heap-allocated handle, then query it with the
7//! accessor functions. Call [`tpt_uir_free`] when done. All functions return
8//! `0` on success and a non-zero code on error.
9
10use libc::{c_char, c_int, c_void, size_t};
11use std::ffi::CStr;
12
13use tpt_uir_core::ir::Region;
14use tpt_uir_core::validate_region;
15
16/// Opaque handle owning a deserialized [`Region`].
17///
18/// `strings` caches NUL-terminated `CString`s handed out by the accessors so the
19/// returned pointers stay valid until [`tpt_uir_free`] (the documented lifetime
20/// contract), without requiring the underlying `String`s to be NUL-terminated.
21struct Handle {
22    region: Region,
23    strings: std::cell::RefCell<Vec<std::ffi::CString>>,
24}
25
26/// Deserialize a postcard-encoded region from `data[0..len]` into a new handle.
27///
28/// On success, `*out_handle` receives the opaque pointer (free with
29/// [`tpt_uir_free`]). Returns `0` on success, `1` on a bad pointer, or `2` on a
30/// decode error.
31///
32/// # Safety
33/// `data` must point to `len` readable bytes.
34#[no_mangle]
35pub unsafe extern "C" fn tpt_uir_load(
36    data: *const u8,
37    len: size_t,
38    out_handle: *mut *mut c_void,
39) -> c_int {
40    if data.is_null() || out_handle.is_null() {
41        return 1;
42    }
43    let slice = std::slice::from_raw_parts(data, len);
44    match tpt_uir_serde::deserialize_region(slice) {
45        Ok(region) => {
46            let handle = Box::new(Handle {
47                region,
48                strings: std::cell::RefCell::new(Vec::new()),
49            });
50            *out_handle = Box::into_raw(handle) as *mut c_void;
51            0
52        }
53        Err(_) => 2,
54    }
55}
56
57/// Free a handle produced by [`tpt_uir_load`].
58///
59/// # Safety
60/// `handle` must be a pointer returned by [`tpt_uir_load`] and not previously
61/// freed. Passing a null pointer is a no-op.
62#[no_mangle]
63pub unsafe extern "C" fn tpt_uir_free(handle: *mut c_void) {
64    if !handle.is_null() {
65        drop(Box::from_raw(handle as *mut Handle));
66    }
67}
68
69/// Write the number of blocks in the region to `*out`.
70///
71/// # Safety
72/// `handle` must be a valid handle; `out` must be non-null.
73#[no_mangle]
74pub unsafe extern "C" fn tpt_uir_block_count(handle: *mut c_void, out: *mut size_t) -> c_int {
75    if handle.is_null() || out.is_null() {
76        return 1;
77    }
78    let h = &*(handle as *const Handle);
79    *out = h.region.blocks.len();
80    0
81}
82
83/// Write the number of operations in block `block_index` to `*out`.
84///
85/// # Safety
86/// `handle` must be a valid handle; `out` must be non-null.
87#[no_mangle]
88pub unsafe extern "C" fn tpt_uir_op_count(
89    handle: *mut c_void,
90    block_index: size_t,
91    out: *mut size_t,
92) -> c_int {
93    if handle.is_null() || out.is_null() {
94        return 1;
95    }
96    let h = &*(handle as *const Handle);
97    match h.region.blocks.get(block_index) {
98        Some(b) => {
99            *out = b.operations.len();
100            0
101        }
102        None => 1,
103    }
104}
105
106/// Write the dialect portion of operation `(block_index, op_index)` to `*out`.
107///
108/// The returned pointer references storage owned by the handle and is valid
109/// until [`tpt_uir_free`]. Returns `0` on success, `1` on a bad handle/index or
110/// `3` if the dialect name contains an interior NUL byte.
111///
112/// # Safety
113/// `handle` must be a valid handle; `out` must be non-null.
114#[no_mangle]
115pub unsafe extern "C" fn tpt_uir_op_dialect(
116    handle: *mut c_void,
117    block_index: size_t,
118    op_index: size_t,
119    out: *mut *const c_char,
120) -> c_int {
121    if handle.is_null() || out.is_null() {
122        return 1;
123    }
124    let h = &*(handle as *const Handle);
125    match h
126        .region
127        .blocks
128        .get(block_index)
129        .and_then(|b| b.operations.get(op_index))
130    {
131        Some(op) => match std::ffi::CString::new(op.op_name.dialect.as_bytes()) {
132            Ok(cs) => {
133                let ptr = cs.as_ptr();
134                h.strings.borrow_mut().push(cs);
135                *out = ptr;
136                0
137            }
138            // 3: string contains an interior NUL byte.
139            Err(_) => 3,
140        },
141        None => 1,
142    }
143}
144
145/// Write the op portion of operation `(block_index, op_index)` to `*out`.
146///
147/// See [`tpt_uir_op_dialect`] for lifetime and error-code semantics.
148///
149/// # Safety
150/// `handle` must be a valid handle; `out` must be non-null.
151#[no_mangle]
152pub unsafe extern "C" fn tpt_uir_op_op(
153    handle: *mut c_void,
154    block_index: size_t,
155    op_index: size_t,
156    out: *mut *const c_char,
157) -> c_int {
158    if handle.is_null() || out.is_null() {
159        return 1;
160    }
161    let h = &*(handle as *const Handle);
162    match h
163        .region
164        .blocks
165        .get(block_index)
166        .and_then(|b| b.operations.get(op_index))
167    {
168        Some(op) => match std::ffi::CString::new(op.op_name.op.as_bytes()) {
169            Ok(cs) => {
170                let ptr = cs.as_ptr();
171                h.strings.borrow_mut().push(cs);
172                *out = ptr;
173                0
174            }
175            // 3: string contains an interior NUL byte.
176            Err(_) => 3,
177        },
178        None => 1,
179    }
180}
181
182/// Write the number of operands of operation `(block_index, op_index)` to `*out`.
183///
184/// # Safety
185/// `handle` must be a valid handle; `out` must be non-null.
186#[no_mangle]
187pub unsafe extern "C" fn tpt_uir_op_operand_count(
188    handle: *mut c_void,
189    block_index: size_t,
190    op_index: size_t,
191    out: *mut size_t,
192) -> c_int {
193    if handle.is_null() || out.is_null() {
194        return 1;
195    }
196    let h = &*(handle as *const Handle);
197    match h
198        .region
199        .blocks
200        .get(block_index)
201        .and_then(|b| b.operations.get(op_index))
202    {
203        Some(op) => {
204            *out = op.operands.len();
205            0
206        }
207        None => 1,
208    }
209}
210
211/// Write operand `operand_index` of operation `(block_index, op_index)` to `*out`.
212///
213/// # Safety
214/// `handle` must be a valid handle; `out` must be non-null.
215#[no_mangle]
216pub unsafe extern "C" fn tpt_uir_op_operand(
217    handle: *mut c_void,
218    block_index: size_t,
219    op_index: size_t,
220    operand_index: size_t,
221    out: *mut u32,
222) -> c_int {
223    if handle.is_null() || out.is_null() {
224        return 1;
225    }
226    let h = &*(handle as *const Handle);
227    match h
228        .region
229        .blocks
230        .get(block_index)
231        .and_then(|b| b.operations.get(op_index))
232    {
233        Some(op) => match op.operands.get(operand_index) {
234            Some(v) => {
235                *out = *v;
236                0
237            }
238            None => 1,
239        },
240        None => 1,
241    }
242}
243
244/// Validate SSA well-formedness. Returns `0` if valid, `1` if invalid.
245///
246/// # Safety
247/// `handle` must be a valid handle.
248#[no_mangle]
249pub unsafe extern "C" fn tpt_uir_validate_ssa(handle: *mut c_void) -> c_int {
250    if handle.is_null() {
251        return 1;
252    }
253    let h = &*(handle as *const Handle);
254    match validate_region(&h.region) {
255        Ok(()) => 0,
256        Err(_) => 1,
257    }
258}
259
260/// Validate that every op's dialect starts with `prefix`. Returns `0` if all
261/// match, `1` otherwise (or on a bad `prefix` pointer).
262///
263/// # Safety
264/// `handle` must be a valid handle; `prefix` must be a valid NUL-terminated C string.
265#[no_mangle]
266pub unsafe extern "C" fn tpt_uir_validate_dialect(
267    handle: *mut c_void,
268    prefix: *const c_char,
269) -> c_int {
270    if handle.is_null() || prefix.is_null() {
271        return 1;
272    }
273    let h = &*(handle as *const Handle);
274    let prefix = match CStr::from_ptr(prefix).to_str() {
275        Ok(p) => p,
276        Err(_) => return 1,
277    };
278    for block in &h.region.blocks {
279        for op in &block.operations {
280            if !op.op_name.dialect.starts_with(prefix) {
281                return 1;
282            }
283        }
284    }
285    0
286}