Skip to main content

logicaffeine_compile/codegen/
marshal.rs

1use std::collections::HashSet;
2use std::fmt::Write;
3
4use crate::analysis::types::RustNames;
5use crate::ast::stmt::{Stmt, TypeExpr};
6use crate::intern::{Interner, Symbol};
7
8use super::context::{analyze_variable_capabilities, replace_word, RefinementContext};
9use super::detection::{collect_mutable_vars, is_result_type};
10use super::types::codegen_type_expr;
11use super::{
12    classify_type_for_c_abi, codegen_assertion, codegen_stmt, try_emit_for_range_pattern,
13    try_emit_prefix_reverse, try_emit_swap_pattern, try_emit_vec_fill_pattern, CAbiClass,
14};
15
16pub(super) fn is_text_type(ty: &TypeExpr, interner: &Interner) -> bool {
17    match ty {
18        TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
19            matches!(interner.resolve(*sym), "Text" | "String")
20        }
21        TypeExpr::Refinement { base, .. } => is_text_type(base, interner),
22        _ => false,
23    }
24}
25
26/// FFI: `Char` is declared `uint32_t` in the C header, so it must cross the
27/// boundary as `u32` (validated via `char::from_u32`), never as a bare Rust
28/// `char` — an out-of-range `u32` from C materialized as a `char` is UB.
29pub(super) fn is_char_type(ty: &TypeExpr, interner: &Interner) -> bool {
30    match ty {
31        TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => interner.resolve(*sym) == "Char",
32        TypeExpr::Refinement { base, .. } => is_char_type(base, interner),
33        _ => false,
34    }
35}
36
37/// Whether `ty` is a scalar that crosses the AOT-native boundary BY VALUE — the sound,
38/// hazard-free subset (no `Rc`/pointer marshaling). `Seq`/`Map`/`Text` are deferred:
39/// they would cross `*mut LogosSeq<T>` etc., which needs the borrow-not-own protocol
40/// (HOTSWAP §Axis-3 B4). A function outside this subset gets no shim and falls through.
41pub(super) fn is_native_scalar(ty: &TypeExpr, interner: &Interner) -> bool {
42    match ty {
43        TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
44            matches!(interner.resolve(*sym), "Int" | "Float" | "Bool")
45        }
46        TypeExpr::Refinement { base, .. } => is_native_scalar(base, interner),
47        _ => false,
48    }
49}
50
51/// Emit the AOT-native export shim (HOTSWAP §Axis-3): a thin `#[no_mangle] extern "C"`
52/// calling-convention wrapper over the inner Rust fn that crosses our ACTUAL values —
53/// scalars BY VALUE — with NO `CString`/handle marshaling (unlike
54/// `codegen_c_export_with_marshaling`). The interpreter marshals VM `Value`s to these
55/// scalar args, calls the loaded symbol, and re-boxes the scalar result.
56///
57/// Returns `None` unless every param AND the return are in the sound scalar subset
58/// (`is_native_scalar`): the caller then falls through to VM+JIT, so a function the
59/// shim cannot represent simply isn't AOT-native — no gap at the seam.
60pub fn codegen_native_tier_export(
61    name: Symbol,
62    params: &[(Symbol, &TypeExpr)],
63    return_type: Option<&TypeExpr>,
64    interner: &Interner,
65) -> Option<String> {
66    if !params.iter().all(|(_, t)| is_native_scalar(t, interner)) {
67        return None;
68    }
69    if let Some(rt) = return_type {
70        if !is_native_scalar(rt, interner) {
71            return None;
72        }
73    }
74    let names = RustNames::new(interner);
75    let inner = names.ident(name);
76    let export = format!("logos_native_{}", names.raw(name));
77    let params_sig = params
78        .iter()
79        .map(|(p, t)| {
80            format!(
81                "{}: {}",
82                interner.resolve(*p),
83                codegen_type_expr(t, interner)
84            )
85        })
86        .collect::<Vec<_>>()
87        .join(", ");
88    let args = params
89        .iter()
90        .map(|(p, _)| interner.resolve(*p).to_string())
91        .collect::<Vec<_>>()
92        .join(", ");
93    let ret = return_type
94        .map(|t| codegen_type_expr(t, interner))
95        .unwrap_or_else(|| "()".to_string());
96    let ret_sig = if ret == "()" {
97        String::new()
98    } else {
99        format!(" -> {ret}")
100    };
101    // A failure inside the function (a broken contract, `Fail with`, a zero divisor) must never abort
102    // the host: the shim catches it silently, records it in `{export}__failed`, and returns a
103    // placeholder the caller discards — the VM re-runs the call on bytecode (see `aot_tier`), where
104    // the exact error is raised at the exact point.
105    let mut out = String::new();
106    let _ = writeln!(out, "static {export}__FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);");
107    let _ = writeln!(out, "#[no_mangle]");
108    let _ = writeln!(out, "pub extern \"C\" fn {export}__failed() -> i64 {{");
109    let _ = writeln!(
110        out,
111        "    {export}__FAILED.swap(false, std::sync::atomic::Ordering::Relaxed) as i64"
112    );
113    let _ = writeln!(out, "}}");
114    let _ = writeln!(out, "#[no_mangle]");
115    let _ = writeln!(
116        out,
117        "pub extern \"C\" fn {export}({params_sig}){ret_sig} {{"
118    );
119    let _ = writeln!(
120        out,
121        "    static SILENT: std::sync::Once = std::sync::Once::new();"
122    );
123    let _ = writeln!(
124        out,
125        "    SILENT.call_once(|| std::panic::set_hook(::std::boxed::Box::new(|_| {{}})));"
126    );
127    let _ = writeln!(
128        out,
129        "    match std::panic::catch_unwind(|| {inner}({args})) {{"
130    );
131    let _ = writeln!(out, "        Ok(v) => v,");
132    let _ = writeln!(out, "        Err(_) => {{");
133    let _ = writeln!(
134        out,
135        "            {export}__FAILED.store(true, std::sync::atomic::Ordering::Relaxed);"
136    );
137    let _ = writeln!(out, "            Default::default()");
138    let _ = writeln!(out, "        }}");
139    let _ = writeln!(out, "    }}");
140    let _ = writeln!(out, "}}");
141    Some(out)
142}
143
144/// FFI: Generate a C-exported function with Universal ABI marshaling.
145///
146/// Produces: 1) an inner function with normal Rust types, 2) a #[no_mangle] extern "C" wrapper.
147///
148/// The wrapper handles:
149/// - Text param/return marshaling (*const c_char <-> String)
150/// - Reference type params/returns via opaque LogosHandle
151/// - Result<T, E> returns via status code + out-parameter
152/// - Refinement type boundary guards
153pub(super) fn codegen_c_export_with_marshaling(
154    name: Symbol,
155    params: &[(Symbol, &TypeExpr)],
156    body: &[Stmt],
157    return_type: Option<&TypeExpr>,
158    interner: &Interner,
159    lww_fields: &HashSet<(String, String)>,
160    mv_fields: &HashSet<(String, String)>,
161    async_functions: &HashSet<Symbol>,
162    boxed_fields: &HashSet<(String, String, String)>,
163    registry: &crate::analysis::registry::TypeRegistry,
164    type_env: &crate::analysis::types::TypeEnv,
165) -> String {
166    let mut output = String::new();
167    let names = RustNames::new(interner);
168    let raw_name = names.raw(name);
169    // All exported C ABI symbols use the `logos_` prefix to avoid keyword
170    // collisions in target languages (C, Python, JS, etc.) and to provide
171    // a consistent namespace for the generated library.
172    let func_name = format!("logos_{}", raw_name);
173    let inner_name = names.ident(name);
174
175    // Classify return type
176    let has_ref_return = return_type.map_or(false, |ty| {
177        classify_type_for_c_abi(ty, interner, registry) == CAbiClass::ReferenceType
178    });
179    let has_result_return = return_type.map_or(false, |ty| is_result_type(ty, interner));
180    let has_text_return = return_type.map_or(false, |t| is_text_type(t, interner));
181
182    // Determine if we need status-code return pattern
183    // Status code is needed when the return value requires an out-parameter (ref/text/result)
184    // or when refinement parameters need validation error paths.
185    // Ref-type parameters do NOT force status code — catch_unwind handles invalid handle panics.
186    let uses_status_code = has_ref_return
187        || has_result_return
188        || has_text_return
189        || params
190            .iter()
191            .any(|(_, ty)| matches!(ty, TypeExpr::Refinement { .. }));
192
193    // 1) Emit the inner function with normal Rust types
194    let inner_params: Vec<String> = params
195        .iter()
196        .map(|(pname, ptype)| {
197            format!(
198                "{}: {}",
199                interner.resolve(*pname),
200                codegen_type_expr(ptype, interner)
201            )
202        })
203        .collect();
204    let inner_ret = return_type.map(|t| codegen_type_expr(t, interner));
205
206    let inner_sig = if let Some(ref ret) = inner_ret {
207        if ret != "()" {
208            format!("fn {}({}) -> {}", inner_name, inner_params.join(", "), ret)
209        } else {
210            format!("fn {}({})", inner_name, inner_params.join(", "))
211        }
212    } else {
213        format!("fn {}({})", inner_name, inner_params.join(", "))
214    };
215
216    writeln!(output, "{} {{", inner_sig).unwrap();
217    let func_mutable_vars = collect_mutable_vars(body);
218    let mut func_ctx = RefinementContext::new();
219    let mut func_synced_vars = HashSet::new();
220    let func_var_caps = analyze_variable_capabilities(body, interner);
221    for (param_name, param_type) in params {
222        let type_name = codegen_type_expr(param_type, interner);
223        func_ctx.register_variable_type(*param_name, type_name);
224    }
225    let func_pipe_vars = HashSet::new();
226    {
227        let stmt_refs: Vec<&Stmt> = body.iter().collect();
228        let mut si = 0;
229        while si < stmt_refs.len() {
230            if let Some((code, skip)) =
231                try_emit_vec_fill_pattern(&stmt_refs, si, interner, 1, &mut func_ctx)
232            {
233                output.push_str(&code);
234                si += 1 + skip;
235                continue;
236            }
237            if let Some((code, skip)) = try_emit_for_range_pattern(
238                &stmt_refs,
239                si,
240                interner,
241                1,
242                &func_mutable_vars,
243                &mut func_ctx,
244                lww_fields,
245                mv_fields,
246                &mut func_synced_vars,
247                &func_var_caps,
248                async_functions,
249                &func_pipe_vars,
250                boxed_fields,
251                registry,
252                type_env,
253            ) {
254                output.push_str(&code);
255                si += 1 + skip;
256                continue;
257            }
258            if let Some((code, skip)) =
259                try_emit_prefix_reverse(&stmt_refs, si, interner, 1, func_ctx.get_variable_types())
260            {
261                output.push_str(&code);
262                si += 1 + skip;
263                continue;
264            }
265            if let Some((code, skip)) = try_emit_swap_pattern(
266                &stmt_refs,
267                si,
268                interner,
269                1,
270                func_ctx.get_variable_types(),
271                func_ctx.oracle(),
272            ) {
273                output.push_str(&code);
274                si += 1 + skip;
275                continue;
276            }
277            output.push_str(&codegen_stmt(
278                stmt_refs[si],
279                interner,
280                1,
281                &func_mutable_vars,
282                &mut func_ctx,
283                lww_fields,
284                mv_fields,
285                &mut func_synced_vars,
286                &func_var_caps,
287                async_functions,
288                &func_pipe_vars,
289                boxed_fields,
290                registry,
291                type_env,
292            ));
293            si += 1;
294        }
295    }
296    writeln!(output, "}}\n").unwrap();
297
298    // 2) Build the C ABI wrapper parameters
299    let mut c_params: Vec<String> = Vec::new();
300
301    for (pname, ptype) in params.iter() {
302        let pn = names.ident(*pname);
303        if classify_type_for_c_abi(ptype, interner, registry) == CAbiClass::ReferenceType {
304            c_params.push(format!("{}: LogosHandle", pn));
305        } else if is_text_type(ptype, interner) {
306            c_params.push(format!("{}: *const std::os::raw::c_char", pn));
307        } else if is_char_type(ptype, interner) {
308            // Char crosses the ABI as uint32_t; validated to a `char` in the body.
309            c_params.push(format!("{}: u32", pn));
310        } else {
311            c_params.push(format!("{}: {}", pn, codegen_type_expr(ptype, interner)));
312        }
313    }
314
315    // Add out-parameter if using status-code pattern with return value
316    if uses_status_code {
317        if let Some(ret_ty) = return_type {
318            if has_result_return {
319                // Result<T, E>: out param for the Ok(T) type
320                if let TypeExpr::Generic {
321                    params: ref rparams,
322                    ..
323                } = ret_ty
324                {
325                    if !rparams.is_empty() {
326                        let ok_ty = &rparams[0];
327                        if classify_type_for_c_abi(ok_ty, interner, registry)
328                            == CAbiClass::ReferenceType
329                        {
330                            c_params.push("out: *mut LogosHandle".to_string());
331                        } else if is_text_type(ok_ty, interner) {
332                            c_params.push("out: *mut *mut std::os::raw::c_char".to_string());
333                        } else {
334                            let ty_str = codegen_type_expr(ok_ty, interner);
335                            c_params.push(format!("out: *mut {}", ty_str));
336                        }
337                    }
338                }
339            } else if has_ref_return {
340                c_params.push("out: *mut LogosHandle".to_string());
341            } else if has_text_return {
342                c_params.push("out: *mut *mut std::os::raw::c_char".to_string());
343            }
344        }
345    }
346
347    // Build the wrapper signature
348    let c_sig = if uses_status_code {
349        format!(
350            "pub extern \"C\" fn {}({}) -> LogosStatus",
351            func_name,
352            c_params.join(", ")
353        )
354    } else if has_text_return {
355        format!(
356            "pub extern \"C\" fn {}({}) -> *mut std::os::raw::c_char",
357            func_name,
358            c_params.join(", ")
359        )
360    } else if let Some(ret_ty) = return_type {
361        // Char returns cross the ABI as uint32_t (see is_char_type).
362        let ret_str = if is_char_type(ret_ty, interner) {
363            "u32".to_string()
364        } else {
365            codegen_type_expr(ret_ty, interner)
366        };
367        if ret_str != "()" {
368            format!(
369                "pub extern \"C\" fn {}({}) -> {}",
370                func_name,
371                c_params.join(", "),
372                ret_str
373            )
374        } else {
375            format!("pub extern \"C\" fn {}({})", func_name, c_params.join(", "))
376        }
377    } else {
378        format!("pub extern \"C\" fn {}({})", func_name, c_params.join(", "))
379    };
380
381    writeln!(output, "#[no_mangle]").unwrap();
382    writeln!(output, "{} {{", c_sig).unwrap();
383
384    // 3) Marshal parameters
385    let call_args: Vec<String> = params.iter()
386        .map(|(pname, ptype)| {
387            let pname_str = names.ident(*pname);
388            if classify_type_for_c_abi(ptype, interner, registry) == CAbiClass::ReferenceType {
389                // Look up handle in registry, dereference, and clone for inner.
390                // A NULL/stale handle must surface as an error and return
391                // gracefully — NOT panic via `.expect()` OUTSIDE the catch_unwind
392                // boundary, which would unwind across the `extern "C"` frame (UB /
393                // abort). Mirrors the graceful accessors (codegen/ffi.rs).
394                let rust_ty = codegen_type_expr(ptype, interner);
395                let err_return = if uses_status_code {
396                    "return LogosStatus::InvalidHandle;".to_string()
397                } else if return_type.map_or(false, |t| codegen_type_expr(t, interner) != "()") {
398                    "return Default::default();".to_string()
399                } else {
400                    "return;".to_string()
401                };
402                writeln!(output, "    let {pn} = {{", pn = pname_str).unwrap();
403                writeln!(output, "        let __id = {pn} as u64;", pn = pname_str).unwrap();
404                writeln!(output, "        let __reg = logos_handle_registry().lock().unwrap_or_else(|e| e.into_inner());").unwrap();
405                writeln!(output, "        match __reg.deref(__id) {{").unwrap();
406                writeln!(output, "            Some(__ptr) => {{ let __v = unsafe {{ &*(__ptr as *const {ty}) }}.clone(); drop(__reg); __v }}", ty = rust_ty).unwrap();
407                writeln!(output, "            None => {{ drop(__reg); logos_set_last_error(\"InvalidHandle: handle '{pn}' not found in registry\".to_string()); {ret} }}", pn = pname_str, ret = err_return).unwrap();
408                writeln!(output, "        }}").unwrap();
409                writeln!(output, "    }};").unwrap();
410            } else if is_text_type(ptype, interner) {
411                // Null-safety: check for NULL *const c_char before CStr::from_ptr
412                if uses_status_code {
413                    writeln!(output, "    if {pn}.is_null() {{ logos_set_last_error(\"NullPointer: text parameter '{pn}' is null\".to_string()); return LogosStatus::NullPointer; }}",
414                        pn = pname_str).unwrap();
415                    writeln!(output, "    let {pn} = unsafe {{ std::ffi::CStr::from_ptr({pn}).to_string_lossy().into_owned() }};",
416                        pn = pname_str).unwrap();
417                } else {
418                    // Non-status-code function: substitute empty string for NULL
419                    writeln!(output, "    let {pn} = if {pn}.is_null() {{ String::new() }} else {{ unsafe {{ std::ffi::CStr::from_ptr({pn}).to_string_lossy().into_owned() }} }};",
420                        pn = pname_str).unwrap();
421                }
422            } else if is_char_type(ptype, interner) {
423                // Validate the incoming uint32_t scalar; an out-of-range value is
424                // UB if materialized as a Rust `char`. Use U+FFFD on invalid input.
425                writeln!(output, "    let {pn} = char::from_u32({pn}).unwrap_or('\\u{{FFFD}}');",
426                    pn = pname_str).unwrap();
427            }
428            pname_str.to_string()
429        })
430        .collect();
431
432    // 4) Emit refinement guards for parameters
433    for (pname, ptype) in params.iter() {
434        if let TypeExpr::Refinement {
435            base: _,
436            var,
437            predicate,
438        } = ptype
439        {
440            let pname_str = interner.resolve(*pname);
441            let bound = interner.resolve(*var);
442            let assertion = codegen_assertion(predicate, interner);
443            let check = if bound == pname_str {
444                assertion
445            } else {
446                replace_word(&assertion, bound, pname_str)
447            };
448            writeln!(output, "    if !({}) {{", check).unwrap();
449            writeln!(output, "        logos_set_last_error(format!(\"Refinement violation: expected {check}, got {pn} = {{}}\", {pn}));",
450                check = check, pn = pname_str).unwrap();
451            writeln!(output, "        return LogosStatus::RefinementViolation;").unwrap();
452            writeln!(output, "    }}").unwrap();
453        }
454    }
455
456    // 4b) Null out-parameter check (before catch_unwind to avoid calling inner fn)
457    if uses_status_code && (has_ref_return || has_text_return || has_result_return) {
458        writeln!(output, "    if out.is_null() {{ logos_set_last_error(\"NullPointer: output parameter is null\".to_string()); return LogosStatus::NullPointer; }}").unwrap();
459    }
460
461    // 5) Determine panic default for catch_unwind error arm
462    let panic_default = if uses_status_code {
463        "LogosStatus::ThreadPanic"
464    } else if has_text_return {
465        "std::ptr::null_mut()"
466    } else if return_type.map_or(false, |t| codegen_type_expr(t, interner) != "()") {
467        "Default::default()"
468    } else {
469        "" // void function
470    };
471
472    // 6) Open catch_unwind panic boundary
473    writeln!(
474        output,
475        "    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {{"
476    )
477    .unwrap();
478
479    // 7) Call inner and marshal return (inside catch_unwind closure)
480    if uses_status_code {
481        if has_result_return {
482            // Result<T, E>: match on Ok/Err
483            writeln!(
484                output,
485                "    match {}({}) {{",
486                inner_name,
487                call_args.join(", ")
488            )
489            .unwrap();
490            writeln!(output, "        Ok(val) => {{").unwrap();
491
492            if let Some(TypeExpr::Generic {
493                params: ref rparams,
494                ..
495            }) = return_type
496            {
497                if !rparams.is_empty() {
498                    let ok_ty = &rparams[0];
499                    if classify_type_for_c_abi(ok_ty, interner, registry)
500                        == CAbiClass::ReferenceType
501                    {
502                        writeln!(
503                            output,
504                            "            let __ptr = Box::into_raw(Box::new(val)) as usize;"
505                        )
506                        .unwrap();
507                        writeln!(output, "            let mut __reg = logos_handle_registry().lock().unwrap_or_else(|e| e.into_inner());").unwrap();
508                        writeln!(output, "            let (__id, _) = __reg.register(__ptr);")
509                            .unwrap();
510                        writeln!(
511                            output,
512                            "            unsafe {{ *out = __id as LogosHandle; }}"
513                        )
514                        .unwrap();
515                    } else if is_text_type(ok_ty, interner) {
516                        writeln!(output, "            match std::ffi::CString::new(val) {{")
517                            .unwrap();
518                        writeln!(
519                            output,
520                            "                Ok(cstr) => unsafe {{ *out = cstr.into_raw(); }},"
521                        )
522                        .unwrap();
523                        writeln!(output, "                Err(_) => {{").unwrap();
524                        writeln!(output, "                    logos_set_last_error(\"Return value contains null byte\".to_string());").unwrap();
525                        writeln!(
526                            output,
527                            "                    return LogosStatus::ContainsNullByte;"
528                        )
529                        .unwrap();
530                        writeln!(output, "                }}").unwrap();
531                        writeln!(output, "            }}").unwrap();
532                    } else {
533                        writeln!(output, "            unsafe {{ *out = val; }}").unwrap();
534                    }
535                }
536            }
537
538            writeln!(output, "            LogosStatus::Ok").unwrap();
539            writeln!(output, "        }}").unwrap();
540            writeln!(output, "        Err(e) => {{").unwrap();
541            writeln!(
542                output,
543                "            logos_set_last_error(format!(\"{{}}\", e));"
544            )
545            .unwrap();
546            writeln!(output, "            LogosStatus::Error").unwrap();
547            writeln!(output, "        }}").unwrap();
548            writeln!(output, "    }}").unwrap();
549        } else if has_ref_return {
550            // Reference type return -> box, register in handle registry, and write to out-parameter
551            writeln!(
552                output,
553                "    let result = {}({});",
554                inner_name,
555                call_args.join(", ")
556            )
557            .unwrap();
558            writeln!(
559                output,
560                "    let __ptr = Box::into_raw(Box::new(result)) as usize;"
561            )
562            .unwrap();
563            writeln!(output, "    let mut __reg = logos_handle_registry().lock().unwrap_or_else(|e| e.into_inner());").unwrap();
564            writeln!(output, "    let (__id, _) = __reg.register(__ptr);").unwrap();
565            writeln!(output, "    unsafe {{ *out = __id as LogosHandle; }}").unwrap();
566            writeln!(output, "    LogosStatus::Ok").unwrap();
567        } else if has_text_return {
568            // Text return with status code -> write to out-parameter
569            writeln!(
570                output,
571                "    let result = {}({});",
572                inner_name,
573                call_args.join(", ")
574            )
575            .unwrap();
576            writeln!(output, "    match std::ffi::CString::new(result) {{").unwrap();
577            writeln!(output, "        Ok(cstr) => {{").unwrap();
578            writeln!(output, "            unsafe {{ *out = cstr.into_raw(); }}").unwrap();
579            writeln!(output, "            LogosStatus::Ok").unwrap();
580            writeln!(output, "        }}").unwrap();
581            writeln!(output, "        Err(_) => {{").unwrap();
582            writeln!(output, "            logos_set_last_error(\"Return value contains null byte\".to_string());").unwrap();
583            writeln!(output, "            LogosStatus::ContainsNullByte").unwrap();
584            writeln!(output, "        }}").unwrap();
585            writeln!(output, "    }}").unwrap();
586        } else {
587            // No return value but status code (e.g., refinement-only)
588            writeln!(output, "    {}({});", inner_name, call_args.join(", ")).unwrap();
589            writeln!(output, "    LogosStatus::Ok").unwrap();
590        }
591    } else if has_text_return {
592        // Text-only marshaling (legacy path, no status code)
593        writeln!(
594            output,
595            "    let result = {}({});",
596            inner_name,
597            call_args.join(", ")
598        )
599        .unwrap();
600        writeln!(output, "    match std::ffi::CString::new(result) {{").unwrap();
601        writeln!(output, "        Ok(cstr) => cstr.into_raw(),").unwrap();
602        writeln!(output, "        Err(_) => {{ logos_set_last_error(\"Return value contains null byte\".to_string()); std::ptr::null_mut() }}").unwrap();
603        writeln!(output, "    }}").unwrap();
604    } else if let Some(ret_ty) = return_type {
605        // A Char return crosses the ABI as uint32_t.
606        if is_char_type(ret_ty, interner) {
607            writeln!(
608                output,
609                "    {}({}) as u32",
610                inner_name,
611                call_args.join(", ")
612            )
613            .unwrap();
614        } else {
615            writeln!(output, "    {}({})", inner_name, call_args.join(", ")).unwrap();
616        }
617    } else {
618        writeln!(output, "    {}({})", inner_name, call_args.join(", ")).unwrap();
619    }
620
621    // 8) Close catch_unwind with panic handler
622    writeln!(output, "    }})) {{").unwrap();
623    writeln!(output, "        Ok(__v) => __v,").unwrap();
624    writeln!(output, "        Err(__panic) => {{").unwrap();
625    writeln!(output, "            let __msg = if let Some(s) = __panic.downcast_ref::<String>() {{ s.clone() }} else if let Some(s) = __panic.downcast_ref::<&str>() {{ s.to_string() }} else {{ \"Unknown panic\".to_string() }};").unwrap();
626    writeln!(output, "            logos_set_last_error(__msg);").unwrap();
627    if !panic_default.is_empty() {
628        writeln!(output, "            {}", panic_default).unwrap();
629    }
630    writeln!(output, "        }}").unwrap();
631    writeln!(output, "    }}").unwrap();
632
633    writeln!(output, "}}\n").unwrap();
634
635    output
636}