Skip to main content

graphics_bindgen/
guest.rs

1//! The guest API surface: every supported call as a typed function.
2//!
3//! One description of each call (its name, its arguments as the guest sees
4//! them, how each becomes a call word, its result) feeds every guest
5//! transport, so the Wasm and native guest APIs cannot differ in names or
6//! types. This module builds that description from the registry and emits
7//! the native transport's bindings: Rust functions, the C-ABI declarations a
8//! header is generated from, and their C definitions. Hand-written code is
9//! only the transport's raw call.
10
11use crate::{
12    enumeration::get_variant_identifier,
13    function::{get_function_identifier, is_public_input},
14    naming::snake_to_upper_camel_case,
15    registry::GraphicsRegistry,
16};
17use proc_macro2::TokenStream;
18use quote::{ToTokens, format_ident, quote};
19use std::fmt::Write;
20use syn::{FnArg, Ident, ReturnType, Signature, Type};
21
22/// Guest-visible types, as Rust source. Every transport's bindings include it.
23pub const TYPES_SOURCE: &str = include_str!("guest_types.rs");
24
25/// The prefix of every exported C name and of every C type.
26pub const C_PREFIX: &str = "XilaGraphics";
27
28/// How a guest value becomes one call word.
29#[derive(Clone, Copy, PartialEq, Eq, Debug)]
30pub enum Word {
31    /// A scalar or pointer: converted as a number.
32    Number,
33    /// A word-sized register value whose bytes are copied, such as a color.
34    Bytes,
35}
36
37/// One argument as the guest sees it.
38pub struct Input {
39    pub name: Ident,
40    /// The guest type, with LVGL's names replaced by the guest API's.
41    pub ty: Type,
42    pub word: Word,
43}
44
45/// One call as the guest sees it.
46pub struct GuestCall {
47    /// The Rust function, which is the catalog name without LVGL's prefix.
48    pub function: Ident,
49    /// The call enum's variant.
50    pub variant: Ident,
51    pub inputs: Vec<Input>,
52    /// The guest type of the result, if the call returns one.
53    pub output: Option<Type>,
54}
55
56impl GuestCall {
57    /// The C function name: `xila_graphics_` and the Rust name.
58    pub fn c_function(&self) -> Ident {
59        format_ident!("xila_graphics_{}", self.function)
60    }
61
62    fn c_variant(&self) -> String {
63        let name = self.variant.to_string();
64        let mut upper = String::new();
65        for (index, character) in name.chars().enumerate() {
66            if character.is_uppercase() && index != 0 {
67                upper.push('_');
68            }
69            upper.push(character.to_ascii_uppercase());
70        }
71        format!("XILA_GRAPHICS_FUNCTION_CALL_{upper}")
72    }
73}
74
75fn convert_type(mut ty: Type) -> Type {
76    match &mut ty {
77        Type::Path(path) => {
78            if let Some(last) = path.path.segments.last_mut() {
79                let identifier = match last.ident.to_string().as_str() {
80                    "lv_obj_t" | "_lv_obj_t" => "Object".to_string(),
81                    "lv_obj_class_t" => "ObjectClass".to_string(),
82                    "lv_obj_flag_t" => "ObjectFlag".to_string(),
83                    "lv_obj_point_transform_flag_t" => "ObjectPointTransformFlag".to_string(),
84                    "lv_result_t" => "LvglResult".to_string(),
85                    "WasmPointer" => "c_void".to_string(),
86                    name => match name.strip_prefix("lv_") {
87                        Some(name) => {
88                            snake_to_upper_camel_case(name.strip_suffix("_t").unwrap_or(name))
89                        }
90                        None => name.to_string(),
91                    },
92                };
93                last.ident = Ident::new(&identifier, last.ident.span());
94            }
95        }
96        Type::Ptr(pointer) => *pointer.elem = convert_type((*pointer.elem).clone()),
97        other => panic!("Unsupported argument type : {other:?}"),
98    }
99    ty
100}
101
102/// Handles are one word on the wire: `object_delete` takes 32 bits where the
103/// catalog's C signature has 16.
104fn widen_object_delete_handle(signature: &mut Signature) {
105    for input in &mut signature.inputs {
106        let FnArg::Typed(typed) = input else { continue };
107        if !matches!(&*typed.pat, syn::Pat::Ident(pattern) if pattern.ident.to_string().starts_with("__"))
108            && let Type::Path(path) = &*typed.ty
109            && path.path.is_ident("u16")
110        {
111            *typed.ty = syn::parse_quote!(u32);
112        }
113    }
114}
115
116fn word(ty: &Type) -> Word {
117    match ty {
118        Type::Path(path) => match path.to_token_stream().to_string().as_str() {
119            "lv_color_t" | "lv_color32_t" | "lv_color16_t" | "lv_style_value_t" => Word::Bytes,
120            _ => Word::Number,
121        },
122        Type::Ptr(_) => Word::Number,
123        other => panic!("Unsupported argument type : {other:?}"),
124    }
125}
126
127/// The guest description of every call in the registry, in catalog order.
128pub fn calls(registry: &GraphicsRegistry<'_>) -> Vec<GuestCall> {
129    registry
130        .calls()
131        .iter()
132        .map(|call| {
133            let mut signature = call.signature.clone();
134            if call.name == "object_delete" {
135                widen_object_delete_handle(&mut signature);
136            }
137            let inputs = signature
138                .inputs
139                .iter()
140                .filter(is_public_input)
141                .map(|input| {
142                    let FnArg::Typed(typed) = input else {
143                        panic!("Unsupported argument type : {input:?}");
144                    };
145                    let syn::Pat::Ident(pattern) = &*typed.pat else {
146                        panic!("Unsupported argument pattern : {:?}", typed.pat);
147                    };
148                    Input {
149                        name: pattern.ident.clone(),
150                        word: word(&typed.ty),
151                        ty: convert_type((*typed.ty).clone()),
152                    }
153                })
154                .collect();
155            let output = match &signature.output {
156                ReturnType::Type(_, ty) => Some(convert_type((**ty).clone())),
157                ReturnType::Default => None,
158            };
159            GuestCall {
160                function: get_function_identifier("", &signature.ident),
161                variant: get_variant_identifier(&signature.ident),
162                inputs,
163                output,
164            }
165        })
166        .collect()
167}
168
169/// Rust functions over a transport's `call::<T>(FunctionCall, &[usize])`,
170/// which returns the call's result or its non-zero status.
171pub fn rust_functions(calls: &[GuestCall]) -> TokenStream {
172    let functions = calls.iter().map(|call| {
173        let function = &call.function;
174        let variant = &call.variant;
175        let parameters = call.inputs.iter().map(|input| {
176            let (name, ty) = (&input.name, &input.ty);
177            quote! { #name: #ty }
178        });
179        let words = call.inputs.iter().map(|input| {
180            let name = &input.name;
181            match input.word {
182                Word::Bytes => quote! { as_usize(#name) },
183                Word::Number if is_usize(&input.ty) => quote! { #name },
184                Word::Number => quote! { #name as usize },
185            }
186        });
187        let output = match &call.output {
188            Some(ty) => quote! { #ty },
189            None => quote! { () },
190        };
191        quote! {
192            /// # Safety
193            /// Pointers must be valid for the call, and the call must run in a native process.
194            pub unsafe fn #function(#(#parameters),*) -> Result<#output> {
195                unsafe { call(FunctionCall::#variant, &[#(#words),*]) }
196            }
197        }
198    });
199    quote! { #(#functions)* }
200}
201
202fn is_usize(ty: &Type) -> bool {
203    matches!(ty, Type::Path(path) if path.path.is_ident("usize"))
204}
205
206/// The C-ABI declarations a header generator reads: names and types only.
207/// The bodies are never compiled.
208pub fn c_declarations(calls: &[GuestCall]) -> TokenStream {
209    let functions = calls.iter().map(|call| {
210        let function = call.c_function();
211        let mut parameters: Vec<_> = call
212            .inputs
213            .iter()
214            .map(|input| {
215                let (name, ty) = (&input.name, &input.ty);
216                quote! { #name: #ty }
217            })
218            .collect();
219        if let Some(ty) = &call.output {
220            parameters.push(quote! { __result_pointer: *mut #ty });
221        }
222        quote! {
223            #[unsafe(no_mangle)]
224            pub extern "C" fn #function(#(#parameters),*) -> i32 { 0 }
225        }
226    });
227    quote! { #(#functions)* }
228}
229
230fn c_type(ty: &Type) -> String {
231    match ty {
232        Type::Ptr(pointer) => {
233            let target = c_type(&pointer.elem);
234            if matches!(pointer.mutability, syn::PointerMutability::Const(_)) {
235                format!("{target} const *")
236            } else {
237                format!("{target} *")
238            }
239        }
240        Type::Path(path) => {
241            let name = path
242                .path
243                .segments
244                .last()
245                .expect("a type has a name")
246                .ident
247                .to_string();
248            match name.as_str() {
249                "bool" => "bool".into(),
250                "i8" => "int8_t".into(),
251                "u8" => "uint8_t".into(),
252                "u16" => "uint16_t".into(),
253                "u32" => "uint32_t".into(),
254                "i32" => "int32_t".into(),
255                "usize" => "size_t".into(),
256                "c_char" => "char".into(),
257                "c_void" => "void".into(),
258                _ => format!("{C_PREFIX}{name}"),
259            }
260        }
261        other => panic!("Unsupported argument type : {other:?}"),
262    }
263}
264
265/// The C definitions of [`c_declarations`]: each packs its arguments into
266/// words and makes one call through the transport's raw `xila_graphics_call`,
267/// whose first argument the transport names (`process`).
268pub fn c_definitions(calls: &[GuestCall], process: &str) -> String {
269    let mut source = String::new();
270    for call in calls {
271        let mut parameters: Vec<_> = call
272            .inputs
273            .iter()
274            .map(|input| format!("{} {}", c_type(&input.ty), input.name))
275            .collect();
276        let result = match &call.output {
277            Some(ty) => {
278                parameters.push(format!("{} *__result_pointer", c_type(ty)));
279                "__result_pointer"
280            }
281            None => "NULL",
282        };
283        let parameters = if parameters.is_empty() {
284            "void".to_string()
285        } else {
286            parameters.join(", ")
287        };
288        let words: Vec<_> = call
289            .inputs
290            .iter()
291            .map(|input| match input.word {
292                Word::Bytes => format!("xila_graphics_pack(&{0}, sizeof({0}))", input.name),
293                Word::Number => format!("(size_t){}", input.name),
294            })
295            .collect();
296        writeln!(source, "\nint32_t {}({parameters}) {{", call.c_function())
297            .expect("write to a string");
298        let arguments = if words.is_empty() {
299            "NULL".to_string()
300        } else {
301            writeln!(source, "    size_t arguments[] = {{{}}};", words.join(", "))
302                .expect("write to a string");
303            "arguments".to_string()
304        };
305        writeln!(
306            source,
307            "    return (int32_t)xila_graphics_call({process}, {}, {arguments}, {}, {result});\n}}",
308            call.c_variant(),
309            words.len(),
310        )
311        .expect("write to a string");
312    }
313    source
314}