Skip to main content

predsync_compiler/
c_codegen.rs

1//! Deterministic C declarations and matching Rust glue for typed message wrappers.
2
3use std::{fmt::Write as _, string::String, vec::Vec};
4
5use predsync_schema::{EnumDef, FieldType, MessageSchema, ScalarType, SchemaSet};
6
7use crate::codegen::{CodegenError, constant, pascal, snake};
8
9/// The two halves of a generated C wrapper: a C header fragment and Rust glue.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct GeneratedC {
12    /// C declarations for the generated structs, enums and pack/unpack helpers.
13    pub header: String,
14    /// Rust mirror types and `extern "C"` implementations, included by the FFI crate.
15    pub rust: String,
16}
17
18/// Generate C declarations and Rust implementations for every message in `set`.
19pub fn generate_c(set: &SchemaSet) -> Result<GeneratedC, CodegenError> {
20    let mut header_modules = Vec::new();
21    let mut rust_modules = Vec::new();
22    for message in &set.messages {
23        header_modules.push(generate_header_message(message)?);
24        rust_modules.push(generate_rust_message(message)?);
25    }
26
27    let mut header = String::from("/* @generated by predsync codegen. Do not edit. */\n");
28    header.push_str("#ifndef PREDSYNC_GENERATED_MESSAGES_H\n");
29    header.push_str("#define PREDSYNC_GENERATED_MESSAGES_H\n\n");
30    header.push_str("#include <stdbool.h>\n");
31    header.push_str("#include <stddef.h>\n");
32    header.push_str("#include <stdint.h>\n\n");
33    header.push_str("#include \"predsync.h\"\n\n");
34    for module in header_modules {
35        header.push_str(&module);
36    }
37    header.push_str("#endif\n");
38
39    let mut rust = String::from("// @generated by predsync codegen. Do not edit.\n");
40    for module in rust_modules {
41        rust.push_str(&module);
42    }
43    Ok(GeneratedC { header, rust })
44}
45
46fn struct_name(message: &MessageSchema) -> String {
47    match &message.namespace {
48        Some(namespace) => format!("{}{}", pascal(namespace), pascal(&message.name)),
49        None => pascal(&message.name),
50    }
51}
52
53fn function_prefix(message: &MessageSchema) -> String {
54    match &message.namespace {
55        Some(namespace) => format!("{}_{}", snake(namespace), snake(&message.name)),
56        None => snake(&message.name),
57    }
58}
59
60fn c_scalar_type(
61    scalar: &ScalarType,
62    structure: &str,
63    enums: &[EnumDef],
64) -> Result<String, CodegenError> {
65    Ok(match scalar {
66        ScalarType::Bool => String::from("bool"),
67        ScalarType::U8 => String::from("uint8_t"),
68        ScalarType::U16 => String::from("uint16_t"),
69        ScalarType::U32 => String::from("uint32_t"),
70        ScalarType::U64 => String::from("uint64_t"),
71        ScalarType::I8 => String::from("int8_t"),
72        ScalarType::I16 => String::from("int16_t"),
73        ScalarType::I32 => String::from("int32_t"),
74        ScalarType::I64 => String::from("int64_t"),
75        ScalarType::F32 => String::from("float"),
76        ScalarType::F64 => String::from("double"),
77        ScalarType::Enum(name) => {
78            check_enum(name, enums)?;
79            format!("{structure}{}", pascal(name))
80        }
81    })
82}
83
84fn check_enum(name: &str, enums: &[EnumDef]) -> Result<(), CodegenError> {
85    if enums.iter().any(|entry| entry.name == name) {
86        Ok(())
87    } else {
88        Err(CodegenError::UnknownEnum(name.to_owned()))
89    }
90}
91
92fn c_type(
93    field_type: &FieldType,
94    structure: &str,
95    enums: &[EnumDef],
96) -> Result<String, CodegenError> {
97    match field_type {
98        FieldType::Scalar(scalar) => c_scalar_type(scalar, structure, enums),
99        FieldType::String => Err(CodegenError::Unsupported("C string type".into())),
100        FieldType::List(_) => Err(CodegenError::Unsupported("C list type".into())),
101    }
102}
103
104fn rust_type(
105    scalar: &ScalarType,
106    structure: &str,
107    enums: &[EnumDef],
108) -> Result<String, CodegenError> {
109    Ok(match scalar {
110        ScalarType::Bool => String::from("bool"),
111        ScalarType::U8 => String::from("u8"),
112        ScalarType::U16 => String::from("u16"),
113        ScalarType::U32 => String::from("u32"),
114        ScalarType::U64 => String::from("u64"),
115        ScalarType::I8 => String::from("i8"),
116        ScalarType::I16 => String::from("i16"),
117        ScalarType::I32 => String::from("i32"),
118        ScalarType::I64 => String::from("i64"),
119        ScalarType::F32 => String::from("f32"),
120        ScalarType::F64 => String::from("f64"),
121        ScalarType::Enum(name) => {
122            check_enum(name, enums)?;
123            format!("{structure}{}", pascal(name))
124        }
125    })
126}
127
128fn enum_prefix(structure: &str, enum_name: &str) -> String {
129    format!("{}_{}", constant(&snake(structure)), constant(enum_name))
130}
131
132fn generate_header_message(message: &MessageSchema) -> Result<String, CodegenError> {
133    let structure = struct_name(message);
134    let prefix = function_prefix(message);
135    let mut out = String::new();
136
137    for enum_def in &message.enums {
138        let name = format!("{structure}{}", pascal(&enum_def.name));
139        let enum_prefix = enum_prefix(&structure, &enum_def.name);
140        let _ = writeln!(
141            out,
142            "/** Generated enum for schema enum `{}`. */",
143            enum_def.name
144        );
145        let _ = writeln!(out, "typedef enum {name} {{");
146        for (index, variant) in enum_def.variants.iter().enumerate() {
147            let _ = writeln!(out, "    {}_{} = {index},", enum_prefix, constant(variant));
148        }
149        let _ = writeln!(out, "}} {name};\n");
150    }
151
152    let _ = writeln!(
153        out,
154        "/** Fixed-capacity message struct for schema message `{}`. */",
155        message.name
156    );
157    let _ = writeln!(out, "typedef struct {structure} {{");
158    for field in &message.fields {
159        match &field.ty {
160            FieldType::Scalar(_) => {
161                let _ = writeln!(
162                    out,
163                    "    {} field_{};",
164                    c_type(&field.ty, &structure, &message.enums)?,
165                    snake(&field.name)
166                );
167            }
168            FieldType::String => {
169                let capacity = field.max_len.unwrap_or(0) as usize + 1;
170                let _ = writeln!(out, "    char field_{}[{}];", snake(&field.name), capacity);
171                let _ = writeln!(out, "    size_t field_{}_len;", snake(&field.name));
172            }
173            FieldType::List(scalar) => {
174                let capacity = field.max_len.unwrap_or(0) as usize;
175                let _ = writeln!(
176                    out,
177                    "    {} field_{}[{}];",
178                    c_scalar_type(scalar, &structure, &message.enums)?,
179                    snake(&field.name),
180                    capacity
181                );
182                let _ = writeln!(out, "    size_t field_{}_len;", snake(&field.name));
183            }
184        }
185    }
186    let _ = writeln!(out, "}} {structure};\n");
187    let _ = writeln!(out, "/**");
188    let _ = writeln!(out, " * Convert a typed message into engine values.");
189    let _ = writeln!(
190        out,
191        " * `out` holds at most `cap` values; `scratch` holds at most `scratch_cap` words."
192    );
193    let _ = writeln!(out, " */");
194    let _ = writeln!(
195        out,
196        "PredsyncStatus {prefix}_pack(const {structure} *msg, PredsyncValue *out, size_t cap, size_t *out_len, uint64_t *scratch, size_t scratch_cap);"
197    );
198    let _ = writeln!(out, "/**");
199    let _ = writeln!(out, " * Fill a typed message from engine values.");
200    let _ = writeln!(
201        out,
202        " * `values` holds `len` entries; `out` is caller-owned."
203    );
204    let _ = writeln!(out, " */");
205    let _ = writeln!(
206        out,
207        "PredsyncStatus {prefix}_unpack(const PredsyncValue *values, size_t len, {structure} *out);\n"
208    );
209    Ok(out)
210}
211
212fn generate_rust_message(message: &MessageSchema) -> Result<String, CodegenError> {
213    let structure = struct_name(message);
214    let prefix = function_prefix(message);
215    let mut out = String::new();
216
217    for enum_def in &message.enums {
218        let name = format!("{structure}{}", pascal(&enum_def.name));
219        let _ = writeln!(out, "#[repr(u32)]");
220        let _ = writeln!(out, "#[derive(Debug, Clone, Copy, PartialEq, Eq)]");
221        let _ = writeln!(out, "pub enum {name} {{");
222        for (index, variant) in enum_def.variants.iter().enumerate() {
223            let _ = writeln!(out, "    {} = {index},", pascal(variant));
224        }
225        let _ = writeln!(out, "}}");
226        let _ = writeln!(out, "impl {name} {{");
227        let _ = writeln!(out, "    pub const fn index(self) -> u64 {{");
228        let _ = writeln!(out, "        self as u64");
229        let _ = writeln!(out, "    }}");
230        let _ = writeln!(
231            out,
232            "    pub const fn from_index(index: u64) -> Option<Self> {{"
233        );
234        let _ = writeln!(out, "        match index {{");
235        for (index, variant) in enum_def.variants.iter().enumerate() {
236            let _ = writeln!(
237                out,
238                "            {index} => Some(Self::{}),",
239                pascal(variant)
240            );
241        }
242        let _ = writeln!(out, "            _ => None,");
243        let _ = writeln!(out, "        }}");
244        let _ = writeln!(out, "    }}");
245        let _ = writeln!(out, "}}\n");
246    }
247
248    let _ = writeln!(out, "#[repr(C)]");
249    let _ = writeln!(out, "pub struct {structure} {{");
250    for field in &message.fields {
251        let name = snake(&field.name);
252        match &field.ty {
253            FieldType::Scalar(scalar) => {
254                let _ = writeln!(
255                    out,
256                    "    pub field_{name}: {},",
257                    rust_type(scalar, &structure, &message.enums)?
258                );
259            }
260            FieldType::String => {
261                let capacity = field.max_len.unwrap_or(0) as usize + 1;
262                let _ = writeln!(
263                    out,
264                    "    pub field_{name}: [::core::ffi::c_char; {capacity}],"
265                );
266                let _ = writeln!(out, "    pub field_{name}_len: usize,");
267            }
268            FieldType::List(scalar) => {
269                let capacity = field.max_len.unwrap_or(0) as usize;
270                let _ = writeln!(
271                    out,
272                    "    pub field_{name}: [{}; {capacity}],",
273                    rust_type(scalar, &structure, &message.enums)?
274                );
275                let _ = writeln!(out, "    pub field_{name}_len: usize,");
276            }
277        }
278    }
279    let _ = writeln!(out, "}}\n");
280
281    out.push_str(&generate_rust_pack(message, &structure, &prefix)?);
282    out.push('\n');
283    out.push_str(&generate_rust_unpack(message, &structure, &prefix)?);
284    Ok(out)
285}
286
287fn slot_expression(
288    scalar: &ScalarType,
289    expression: &str,
290    enums: &[EnumDef],
291) -> Result<String, CodegenError> {
292    Ok(match scalar {
293        ScalarType::Bool => format!("predsync_core::Slot::from_bool({expression}).0"),
294        ScalarType::U8 => format!("predsync_core::Slot::from_u8({expression}).0"),
295        ScalarType::U16 => format!("predsync_core::Slot::from_u16({expression}).0"),
296        ScalarType::U32 => format!("predsync_core::Slot::from_u32({expression}).0"),
297        ScalarType::U64 => format!("predsync_core::Slot::from_u64({expression}).0"),
298        ScalarType::I8 => format!("predsync_core::Slot::from_i8({expression}).0"),
299        ScalarType::I16 => format!("predsync_core::Slot::from_i16({expression}).0"),
300        ScalarType::I32 => format!("predsync_core::Slot::from_i32({expression}).0"),
301        ScalarType::I64 => format!("predsync_core::Slot::from_i64({expression}).0"),
302        ScalarType::F32 => format!("predsync_core::Slot::from_f32({expression}).0"),
303        ScalarType::F64 => format!("predsync_core::Slot::from_f64({expression}).0"),
304        ScalarType::Enum(name) => {
305            check_enum(name, enums)?;
306            format!("({expression}).index()")
307        }
308    })
309}
310
311fn slot_access(
312    scalar: &ScalarType,
313    expression: &str,
314    enums: &[EnumDef],
315) -> Result<String, CodegenError> {
316    Ok(match scalar {
317        ScalarType::Bool => format!("predsync_core::Slot({expression}).as_bool()"),
318        ScalarType::U8 => format!("predsync_core::Slot({expression}).as_u8()"),
319        ScalarType::U16 => format!("predsync_core::Slot({expression}).as_u16()"),
320        ScalarType::U32 => format!("predsync_core::Slot({expression}).as_u32()"),
321        ScalarType::U64 => format!("predsync_core::Slot({expression}).as_u64()"),
322        ScalarType::I8 => format!("predsync_core::Slot({expression}).as_i8()"),
323        ScalarType::I16 => format!("predsync_core::Slot({expression}).as_i16()"),
324        ScalarType::I32 => format!("predsync_core::Slot({expression}).as_i32()"),
325        ScalarType::I64 => format!("predsync_core::Slot({expression}).as_i64()"),
326        ScalarType::F32 => format!("predsync_core::Slot({expression}).as_f32()"),
327        ScalarType::F64 => format!("predsync_core::Slot({expression}).as_f64()"),
328        ScalarType::Enum(name) => {
329            check_enum(name, enums)?;
330            format!("predsync_core::Slot({expression}).as_u64()")
331        }
332    })
333}
334
335fn generate_rust_pack(
336    message: &MessageSchema,
337    structure: &str,
338    prefix: &str,
339) -> Result<String, CodegenError> {
340    let count = message.fields.len();
341    let has_list = message
342        .fields
343        .iter()
344        .any(|field| matches!(field.ty, FieldType::List(_)));
345    let mut out = String::new();
346    let _ = writeln!(out, "/// # Safety");
347    let _ = writeln!(
348        out,
349        "/// All pointers must be valid for the declared capacities; `scratch` must hold `scratch_cap` elements."
350    );
351    let _ = writeln!(
352        out,
353        "#[unsafe(no_mangle)] pub unsafe extern \"C\" fn {prefix}_pack(msg: *const {structure}, out: *mut crate::PredsyncValue, cap: usize, out_len: *mut usize, scratch: *mut u64, scratch_cap: usize) -> crate::PredsyncStatus {{"
354    );
355    let _ = writeln!(out, "    crate::guard(|| {{");
356    let _ = writeln!(
357        out,
358        "        if msg.is_null() || out.is_null() || out_len.is_null() || ({has_list} && scratch.is_null()) {{ return crate::PredsyncStatus::NullPointer; }}"
359    );
360    let _ = writeln!(
361        out,
362        "        if cap < {count} {{ return crate::PredsyncStatus::BufferTooSmall; }}"
363    );
364    let _ = writeln!(out, "        let msg = unsafe {{ &*msg }};");
365    let _ = writeln!(
366        out,
367        "        let out = unsafe {{ core::slice::from_raw_parts_mut(out, {count}) }};"
368    );
369    let _ = writeln!(out, "        let out_len = unsafe {{ &mut *out_len }};");
370
371    for (index, field) in message.fields.iter().enumerate() {
372        let name = snake(&field.name);
373        match &field.ty {
374            FieldType::Scalar(scalar) => {
375                let expression =
376                    slot_expression(scalar, &format!("msg.field_{name}"), &message.enums)?;
377                let element = enum_element(scalar);
378                let _ = writeln!(
379                    out,
380                    "        out[{index}] = crate::value_scalar({expression}, crate::PredsyncScalarKind::{element});"
381                );
382            }
383            FieldType::String => {
384                let _ = writeln!(
385                    out,
386                    "        if msg.field_{name}_len > msg.field_{name}.len() {{ return crate::PredsyncStatus::BufferTooSmall; }}"
387                );
388                let _ = writeln!(
389                    out,
390                    "        out[{index}] = crate::value_str(msg.field_{name}.as_ptr(), msg.field_{name}_len);"
391                );
392            }
393            FieldType::List(scalar) => {
394                let capacity = field.max_len.unwrap_or(0) as usize;
395                let element = enum_element(scalar);
396                let _ = writeln!(
397                    out,
398                    "        if msg.field_{name}_len > {capacity} {{ return crate::PredsyncStatus::BufferTooSmall; }}"
399                );
400                if matches!(scalar, ScalarType::Enum(_)) {
401                    check_enum_name(scalar, &message.enums)?;
402                    let _ = writeln!(out, "        let mut items_{index} = [0u64; {capacity}];");
403                    let _ = writeln!(
404                        out,
405                        "        for (index, item) in msg.field_{name}[..msg.field_{name}_len].iter().enumerate() {{"
406                    );
407                    let _ = writeln!(out, "            items_{index}[index] = (item.index());");
408                    let _ = writeln!(out, "        }}");
409                } else {
410                    let _ = writeln!(out, "        let mut items_{index} = [0u64; {capacity}];");
411                    let _ = writeln!(
412                        out,
413                        "        for (index, item) in msg.field_{name}[..msg.field_{name}_len].iter().enumerate() {{"
414                    );
415                    let bits = slot_expression(scalar, "*item", &message.enums)?;
416                    let _ = writeln!(out, "            items_{index}[index] = {bits};");
417                    let _ = writeln!(out, "        }}");
418                }
419                let _ = writeln!(
420                    out,
421                    "        crate::ffi_try!(unsafe {{ crate::value_list_into(&mut out[{index}], &items_{index}[..msg.field_{name}_len], scratch, scratch_cap, crate::PredsyncScalarKind::{element}) }});"
422                );
423            }
424        }
425    }
426    let _ = writeln!(out, "        *out_len = {count};");
427    let _ = writeln!(out, "        crate::PredsyncStatus::Ok");
428    let _ = writeln!(out, "    }})");
429    let _ = writeln!(out, "}}");
430    Ok(out)
431}
432
433fn generate_rust_unpack(
434    message: &MessageSchema,
435    structure: &str,
436    prefix: &str,
437) -> Result<String, CodegenError> {
438    let count = message.fields.len();
439    let mut out = String::new();
440    let _ = writeln!(out, "/// # Safety");
441    let _ = writeln!(
442        out,
443        "/// `values` must point to `len` values and `out` to a writable structure."
444    );
445    let _ = writeln!(
446        out,
447        "#[unsafe(no_mangle)] pub unsafe extern \"C\" fn {prefix}_unpack(values: *const crate::PredsyncValue, len: usize, out: *mut {structure}) -> crate::PredsyncStatus {{"
448    );
449    let _ = writeln!(out, "    crate::guard(|| {{");
450    let _ = writeln!(
451        out,
452        "        if values.is_null() || out.is_null() {{ return crate::PredsyncStatus::NullPointer; }}"
453    );
454    let _ = writeln!(
455        out,
456        "        if len != {count} {{ return crate::PredsyncStatus::InvalidValue; }}"
457    );
458    let _ = writeln!(
459        out,
460        "        let values = unsafe {{ core::slice::from_raw_parts(values, len) }};"
461    );
462    let _ = writeln!(out, "        let out = unsafe {{ &mut *out }};");
463
464    for (index, field) in message.fields.iter().enumerate() {
465        let name = snake(&field.name);
466        match &field.ty {
467            FieldType::Scalar(ScalarType::Enum(enum_name)) => {
468                check_enum_name(&ScalarType::Enum(enum_name.clone()), &message.enums)?;
469                let enum_type = format!("{structure}{}", pascal(enum_name));
470                let _ = writeln!(
471                    out,
472                    "        let bits = crate::ffi_try!(crate::read_bits(&values[{index}]));"
473                );
474                let _ = writeln!(
475                    out,
476                    "        out.field_{name} = crate::ffi_try!({enum_type}::from_index(bits).ok_or(crate::PredsyncStatus::InvalidValue));"
477                );
478            }
479            FieldType::Scalar(scalar) => {
480                let access = slot_access(scalar, "bits", &message.enums)?;
481                let _ = writeln!(
482                    out,
483                    "        let bits = crate::ffi_try!(crate::read_bits(&values[{index}]));"
484                );
485                let _ = writeln!(out, "        out.field_{name} = {access};");
486            }
487            FieldType::String => {
488                let capacity = field.max_len.unwrap_or(0) as usize;
489                let _ = writeln!(
490                    out,
491                    "        let text = crate::ffi_try!(crate::read_str(&values[{index}]));"
492                );
493                let _ = writeln!(
494                    out,
495                    "        if text.len() > {capacity} {{ return crate::PredsyncStatus::BufferTooSmall; }}"
496                );
497                let _ = writeln!(
498                    out,
499                    "        for (index, byte) in text.iter().enumerate() {{ out.field_{name}[index] = *byte as ::core::ffi::c_char; }}"
500                );
501                let _ = writeln!(out, "        out.field_{name}[text.len()] = 0;");
502                let _ = writeln!(out, "        out.field_{name}_len = text.len();");
503            }
504            FieldType::List(scalar) => {
505                let capacity = field.max_len.unwrap_or(0) as usize;
506                let _ = writeln!(
507                    out,
508                    "        let items = crate::ffi_try!(crate::read_list(&values[{index}]));"
509                );
510                let _ = writeln!(
511                    out,
512                    "        if items.len() > {capacity} {{ return crate::PredsyncStatus::BufferTooSmall; }}"
513                );
514                if let ScalarType::Enum(enum_name) = scalar {
515                    let enum_type = format!("{structure}{}", pascal(enum_name));
516                    let _ = writeln!(
517                        out,
518                        "        for (index, bits) in items.iter().enumerate() {{ out.field_{name}[index] = crate::ffi_try!({enum_type}::from_index(*bits).ok_or(crate::PredsyncStatus::InvalidValue)); }}"
519                    );
520                } else {
521                    let access = slot_access(scalar, "*bits", &message.enums)?;
522                    let _ = writeln!(
523                        out,
524                        "        for (index, bits) in items.iter().enumerate() {{ out.field_{name}[index] = {access}; }}"
525                    );
526                }
527                let _ = writeln!(out, "        out.field_{name}_len = items.len();");
528            }
529        }
530    }
531    let _ = writeln!(out, "        crate::PredsyncStatus::Ok");
532    let _ = writeln!(out, "    }})");
533    let _ = writeln!(out, "}}");
534    Ok(out)
535}
536
537fn enum_element(scalar: &ScalarType) -> &'static str {
538    match scalar {
539        ScalarType::Bool => "Bool",
540        ScalarType::U8 => "U8",
541        ScalarType::U16 => "U16",
542        ScalarType::U32 => "U32",
543        ScalarType::U64 => "U64",
544        ScalarType::I8 => "I8",
545        ScalarType::I16 => "I16",
546        ScalarType::I32 => "I32",
547        ScalarType::I64 => "I64",
548        ScalarType::F32 => "F32",
549        ScalarType::F64 => "F64",
550        ScalarType::Enum(_) => "Enum",
551    }
552}
553
554fn check_enum_name(scalar: &ScalarType, enums: &[EnumDef]) -> Result<(), CodegenError> {
555    if let ScalarType::Enum(name) = scalar {
556        check_enum(name, enums)?;
557    }
558    Ok(())
559}