Skip to main content

graphics_bindgen/
executor.rs

1//! The executor's call table, generated from the registry.
2//!
3//! The output is one `Function` enum with its ID, argument count and result
4//! kind lookups, and one `run` function: a single `match` on the call that
5//! either expands a scalar adapter inline, calls a named handler, or falls
6//! through to the executor's handwritten match. Besides that code, only the
7//! ID and metadata tables (three bytes a call) are stored at runtime.
8//!
9//! The generated code is included by `xila-graphics` and refers to its
10//! `handlers` module, `Kind` enum, `State`, `Transport`, `Call` and
11//! `ResultKind` types.
12
13use crate::{
14    GeneratorError,
15    enumeration::get_variant_identifier,
16    registry::{
17        AdapterPolicy, AutoObjectScalar, GraphicsRegistry, KindTable, ObjectOperation, StyleValue,
18    },
19};
20use proc_macro2::TokenStream;
21use quote::{format_ident, quote};
22
23/// Generate the call table source for the executor from LVGL's own bindings
24/// (the Rust source `lvgl_rust_sys` generated for the build target).
25pub fn source(bindings: &str) -> Result<String, GeneratorError> {
26    let catalog = crate::abi::catalog(bindings)?;
27    let registry = crate::abi::registry(&catalog)?;
28    Ok(generate(&registry)?.to_string())
29}
30
31pub fn generate(registry: &GraphicsRegistry<'_>) -> Result<TokenStream, GeneratorError> {
32    // One row per call, sorted by ID: the ID and a byte holding the argument
33    // count (low nibble) and result kind. Three bytes of read-only data per
34    // call replace a `match` per property, each of which is a code table.
35    let mut variants = Vec::new();
36    let mut rows = Vec::new();
37    for call in registry.calls() {
38        let (_, arguments, result, _) = crate::abi::declaration(&call.name).ok_or_else(|| {
39            GeneratorError::new(format!(
40                "registry call {} has no ABI declaration",
41                call.name
42            ))
43        })?;
44        let variant = get_variant_identifier(&call.signature.ident);
45        let id = i32::from(call.id);
46        let kind: u8 = match *result {
47            "None" => 0,
48            "Word" => 1,
49            "U32" => 2,
50            "I32" => 3,
51            other => {
52                return Err(GeneratorError::new(format!(
53                    "{}: unknown result kind {other}",
54                    call.name
55                )));
56            }
57        };
58        variants.push(quote!(#variant = #id));
59        rows.push((call.id, (kind << 4) | arguments.len() as u8));
60    }
61    rows.sort_by_key(|(id, _)| *id);
62    let ids = rows.iter().map(|(id, _)| *id);
63    let meta = rows.iter().map(|(_, meta)| *meta);
64    let count = rows.len();
65    let mut arms = Vec::new();
66    for call in registry.calls() {
67        let Some(policy) = registry.adapter_for(&call.name) else {
68            continue;
69        };
70        let variant = get_variant_identifier(&call.signature.ident);
71        let native = &call.signature.ident;
72        // Xila's own widgets are declared without the `lv_` prefix.
73        let native = if native.to_string().starts_with("lv_") {
74            native.clone()
75        } else {
76            format_ident!("lv_{native}")
77        };
78        arms.push(match policy {
79            AdapterPolicy::AutoObjectScalar(AutoObjectScalar::SetI32) => quote! {
80                Function::#variant => handlers::object_set_i32(
81                    state, memory, call, None, |o, v| unsafe { crate::lvgl::#native(o, v) },
82                )
83            },
84            AdapterPolicy::AutoObjectScalar(AutoObjectScalar::SetPairI32) => quote! {
85                Function::#variant => handlers::object_set_i32_pair(
86                    state, memory, call, |o, x, y| unsafe { crate::lvgl::#native(o, x, y) },
87                )
88            },
89            AdapterPolicy::AutoObjectScalar(AutoObjectScalar::GetI32) => quote! {
90                Function::#variant => handlers::object_get_i32(
91                    state, memory, call, None, |o| unsafe { crate::lvgl::#native(o) },
92                )
93            },
94            AdapterPolicy::Object {
95                kind,
96                operation,
97                native: renamed,
98            } => {
99                let native = renamed.map_or(native, |name| format_ident!("{name}"));
100                let kind = match kind {
101                    Some(kind) => {
102                        let kind = format_ident!("{kind}");
103                        quote!(Some(Kind::#kind))
104                    }
105                    None => quote!(None),
106                };
107                match operation {
108                    ObjectOperation::Call => quote! {
109                        Function::#variant => handlers::object_call(
110                            state, call, #kind, |o| unsafe { crate::lvgl::#native(o) },
111                        )
112                    },
113                    ObjectOperation::SetBool => quote! {
114                        Function::#variant => handlers::object_set_bool(
115                            state, call, #kind, |o, v| unsafe { crate::lvgl::#native(o, v) },
116                        )
117                    },
118                    ObjectOperation::SetU8 => quote! {
119                        Function::#variant => handlers::object_set_u8(
120                            state, call, #kind, |o, v| unsafe { crate::lvgl::#native(o, v) },
121                        )
122                    },
123                    ObjectOperation::SetU32 { min, max } => quote! {
124                        Function::#variant => handlers::object_set_u32(
125                            state, call, #kind, #min..=#max,
126                            |o, v| unsafe { crate::lvgl::#native(o, v) },
127                        )
128                    },
129                    ObjectOperation::SetMask { mask } => quote! {
130                        Function::#variant => handlers::object_set_mask(
131                            state, call, #kind, #mask,
132                            |o, v| unsafe { crate::lvgl::#native(o, v) },
133                        )
134                    },
135                    ObjectOperation::GetU32 => quote! {
136                        Function::#variant => handlers::object_get_u32(
137                            state, memory, call, #kind, |o| unsafe { crate::lvgl::#native(o) },
138                        )
139                    },
140                    ObjectOperation::GetBool => quote! {
141                        Function::#variant => handlers::object_get_u32(
142                            state, memory, call, #kind,
143                            |o| u32::from(unsafe { crate::lvgl::#native(o) }),
144                        )
145                    },
146                    ObjectOperation::GetI32 => quote! {
147                        Function::#variant => handlers::object_get_i32(
148                            state, memory, call, #kind, |o| unsafe { crate::lvgl::#native(o) },
149                        )
150                    },
151                    ObjectOperation::SetEnum { max } => {
152                        let max = format_ident!("{max}");
153                        quote! {
154                            Function::#variant => handlers::object_set_u32(
155                                state, call, #kind, 0..=crate::lvgl::#max,
156                                |o, v| unsafe { crate::lvgl::#native(o, v) },
157                            )
158                        }
159                    }
160                    ObjectOperation::SetU32Limit { max } => quote! {
161                        Function::#variant => handlers::object_set_u32_limit(
162                            state, call, #kind, #max,
163                            |o, v| unsafe { crate::lvgl::#native(o, v) },
164                        )
165                    },
166                    ObjectOperation::SetText { limit } => {
167                        let limit = format_ident!("{limit}");
168                        quote! {
169                            Function::#variant => handlers::object_set_text(
170                                state, memory, call, #kind, marshal::#limit,
171                                |o, t| unsafe { crate::lvgl::#native(o, t) },
172                            )
173                        }
174                    }
175                    ObjectOperation::SetRange => quote! {
176                        Function::#variant => handlers::object_set_range(
177                            state, memory, call, #kind,
178                            |o, min, max| unsafe { crate::lvgl::#native(o, min, max) },
179                        )
180                    },
181                    ObjectOperation::SetStyle(value) => {
182                        let convert = match value {
183                            StyleValue::Color => quote!(handlers::style_color),
184                            StyleValue::Font => quote!(handlers::style_font),
185                            StyleValue::I32 { min, max } => quote! {
186                                |v, bits| handlers::i32_between(v, bits, #min, #max)
187                            },
188                            StyleValue::Enum { max } => {
189                                let max = format_ident!("{max}");
190                                quote! { |v, _| handlers::u32_at_most(v, crate::lvgl::#max) }
191                            }
192                        };
193                        quote! {
194                            Function::#variant => handlers::object_set_style(
195                                state, memory, call, #kind, #convert,
196                                |o, v, selector| unsafe { crate::lvgl::#native(o, v, selector) },
197                            )
198                        }
199                    }
200                    ObjectOperation::GetI32ByKind(table) => {
201                        let arms = kind_arms(table, true, |native| quote!(#native(o)));
202                        quote! {
203                            Function::#variant => handlers::object_get_i32_by_kind(
204                                state, memory, call,
205                                |o, kind| match kind { #arms _ => None },
206                            )
207                        }
208                    }
209                    ObjectOperation::SetEnumByKind { max, table } => {
210                        let arms = kind_arms(table, false, |native| quote!(#native(o, v as _)));
211                        quote! {
212                            Function::#variant => handlers::object_set_enum_by_kind(
213                                state, call, #max,
214                                |o, kind, v| match kind { #arms _ => None },
215                            )
216                        }
217                    }
218                    ObjectOperation::SetRangeByKind(table) => {
219                        let arms = kind_arms(table, false, |native| quote!(#native(o, min, max)));
220                        quote! {
221                            Function::#variant => handlers::object_set_range_by_kind(
222                                state, memory, call,
223                                |o, kind, min, max| match kind { #arms _ => None },
224                            )
225                        }
226                    }
227                }
228            }
229            AdapterPolicy::Create(kind) => {
230                let kind = format_ident!("{kind}");
231                quote! {
232                    Function::#variant => {
233                        handlers::create(state, memory, call, Kind::#kind, crate::lvgl::#native)
234                    }
235                }
236            }
237            AdapterPolicy::Custom(handler) => {
238                let handler = format_ident!("{handler}");
239                quote! { Function::#variant => handlers::#handler(state, memory, call) }
240            }
241            AdapterPolicy::Manual => continue,
242        });
243    }
244    let maximum = crate::MAX_ARGUMENTS;
245    Ok(quote! {
246        /// The most argument words one call carries.
247        pub const MAX_ARGUMENTS: usize = #maximum;
248
249        /// Every call the executor implements, with its catalog ID.
250        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
251        #[repr(i32)]
252        pub enum Function { #(#variants,)* }
253
254        /// Call IDs in ascending order, and each call's argument count and
255        /// result kind packed into a byte.
256        static IDS: [u16; #count] = [#(#ids),*];
257        static META: [u8; #count] = [#(#meta),*];
258
259        impl Function {
260            pub const fn id(self) -> i32 { self as i32 }
261
262            /// The call with this ID, if any.
263            pub fn from_id(id: i32) -> Option<Self> {
264                Some(lookup(id)?.0)
265            }
266        }
267
268        /// The call with this ID, its argument count and its result kind.
269        pub(crate) fn lookup(id: i32) -> Option<(Function, i32, ResultKind)> {
270            let index = IDS.binary_search(&u16::try_from(id).ok()?).ok()?;
271            let result = match META[index] >> 4 {
272                0 => ResultKind::None,
273                1 => ResultKind::Word,
274                2 => ResultKind::U32,
275                _ => ResultKind::I32,
276            };
277            // SAFETY: `IDS` lists exactly the discriminants of `Function`, in
278            // this table's generation, and `id` was found in it.
279            let function = unsafe { core::mem::transmute::<i32, Function>(id) };
280            Some((function, i32::from(META[index] & 0xf), result))
281        }
282
283        pub(crate) fn run(
284            state: &mut State,
285            memory: &mut dyn Transport,
286            call: &Call,
287            function: Function,
288            lvgl: &mut crate::lvgl_rust::Lvgl,
289        ) -> Result<()> {
290            match function {
291                #(#arms,)*
292                _ => handlers::manual(state, memory, call, function, lvgl),
293            }
294        }
295    })
296}
297
298/// One arm per kind in the table: the kind's LVGL function, which `call`
299/// builds from its name, returning its value or nothing.
300fn kind_arms(
301    table: KindTable,
302    returns: bool,
303    call: impl Fn(proc_macro2::Ident) -> TokenStream,
304) -> TokenStream {
305    let arms = table.iter().map(|(kind, native)| {
306        let kind = format_ident!("{kind}");
307        let call = call(format_ident!("{native}"));
308        if returns {
309            quote!(Kind::#kind => Some(unsafe { crate::lvgl::#call }),)
310        } else {
311            quote!(Kind::#kind => { unsafe { crate::lvgl::#call }; Some(()) })
312        }
313    });
314    quote!(#(#arms)*)
315}