Skip to main content

graphics_bindgen/
catalog.rs

1use crate::{MAX_ARGUMENTS, context::LvglContext, function::get_function_identifier};
2use quote::ToTokens;
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    fmt,
6};
7use syn::{FnArg, Pat, ReturnType, Signature, Type};
8
9// Append-only IDs for new Xila helpers. Inserting these into the legacy
10// alphabetical table would renumber existing guest calls, including Calculator.
11fn extension_id(name: &str) -> Option<u16> {
12    Some(match name {
13        "indexed_canvas_create" => 0xf000,
14        "indexed_canvas_set_pixels" => 0xf001,
15        "window_pop_pointer_event" => 0xf002,
16        "keyboard_create" => 0xf003,
17        "keyboard_set_textarea" => 0xf004,
18        "object_set_padding" => 0xf005,
19        "grid_fr" => 0xf006,
20        "object_set_background" => 0xf007,
21        "object_set_text_color" => 0xf008,
22        "object_set_border" => 0xf009,
23        "object_set_radius" => 0xf00a,
24        "object_set_text_align" => 0xf00b,
25        "object_set_font" => 0xf00c,
26        "object_set_surface" => 0xf00d,
27        "object_set_min_max_size" => 0xf00e,
28        "bar_create" => 0xf00f,
29        "switch_create" => 0xf010,
30        "spinner_create" => 0xf011,
31        "range_set_range" => 0xf012,
32        "range_set_value" => 0xf013,
33        "range_get_value" => 0xf014,
34        "range_get_start_value" => 0xf015,
35        "range_set_mode" => 0xf016,
36        "range_set_orientation" => 0xf017,
37        "spinner_set_animation" => 0xf018,
38        "spinner_get_animation_duration" => 0xf019,
39        "spinner_get_arc_sweep" => 0xf01a,
40        "dropdown_get_selected_string" => 0xf01b,
41        "roller_get_selected_string" => 0xf01c,
42        "dropdown_get_highlight" => 0xf01d,
43        "dropdown_is_open_state" => 0xf01e,
44        "calendar_set_today" => 0xf01f,
45        "calendar_set_highlights" => 0xf020,
46        "calendar_get_shown_date" => 0xf021,
47        "chart_add_series_slot" => 0xf022,
48        "chart_set_values" => 0xf023,
49        "chart_get_value" => 0xf024,
50        "list_create" => 0xf025,
51        "list_add_text" => 0xf026,
52        "list_add_text_button" => 0xf027,
53        "list_set_button_text" => 0xf028,
54        "object_set_theme_variant" => 0xf029,
55        "object_set_theme_error" => 0xf02a,
56        "badge_create" => 0xf02b,
57        "card_create" => 0xf02c,
58        "file_picker_create" => 0xf02d,
59        "file_picker_get_status" => 0xf02e,
60        "file_picker_get_path" => 0xf02f,
61        "file_picker_reset" => 0xf030,
62        _ => return None,
63    })
64}
65
66#[derive(Debug)]
67pub struct GeneratorError(String);
68
69impl GeneratorError {
70    pub(crate) fn new(message: impl Into<String>) -> Self {
71        Self(message.into())
72    }
73}
74
75impl fmt::Display for GeneratorError {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        self.0.fmt(f)
78    }
79}
80impl std::error::Error for GeneratorError {}
81
82#[derive(Debug)]
83pub struct Call {
84    pub id: u16,
85    pub name: String,
86    pub signature: Signature,
87    pub argument_count: usize,
88    pub host_arguments: Vec<String>,
89}
90
91impl Call {
92    /// Ensure a handwritten adapter still agrees with the discovered C ABI.
93    /// Context-only helper arguments are not part of the guest contract.
94    pub fn validate_signature(
95        &self,
96        arguments: &[&str],
97        output: Option<&str>,
98    ) -> Result<(), GeneratorError> {
99        fn normalize(text: &str) -> String {
100            text.chars().filter(|c| !c.is_whitespace()).collect()
101        }
102        let actual: Vec<_> = self
103            .signature
104            .inputs
105            .iter()
106            .filter_map(|arg| {
107                let FnArg::Typed(arg) = arg else { return None };
108                let Pat::Ident(name) = &*arg.pat else {
109                    return None;
110                };
111                if name.ident.to_string().starts_with("__") {
112                    return None;
113                }
114                Some(normalize(&arg.ty.to_token_stream().to_string()))
115            })
116            .collect();
117        let result = match &self.signature.output {
118            ReturnType::Default => None,
119            ReturnType::Type(_, ty) => Some(normalize(&ty.to_token_stream().to_string())),
120        };
121        if self.signature.variadic.is_some()
122            || actual
123                != arguments
124                    .iter()
125                    .map(|arg| normalize(arg))
126                    .collect::<Vec<_>>()
127            || result != output.map(normalize)
128        {
129            return Err(GeneratorError(format!(
130                "adapter signature changed for {}",
131                self.name
132            )));
133        }
134        Ok(())
135    }
136
137    /// The type of the guest argument at `index`, skipping context-only helpers.
138    fn guest_argument(&self, index: usize) -> Option<&Type> {
139        self.signature
140            .inputs
141            .iter()
142            .filter(|argument| match argument {
143                FnArg::Typed(argument) => !matches!(
144                    &*argument.pat,
145                    Pat::Ident(name) if name.ident.to_string().starts_with("__")
146                ),
147                FnArg::Receiver(_) => true,
148            })
149            .nth(index)
150            .and_then(|argument| match argument {
151                FnArg::Typed(argument) => Some(&*argument.ty),
152                FnArg::Receiver(_) => None,
153            })
154    }
155
156    /// Whether the guest argument at `index` is an LVGL object pointer.
157    pub fn argument_is_object(&self, index: usize) -> bool {
158        matches!(
159            self.guest_argument(index),
160            Some(Type::Ptr(pointer)) if pointer.elem.to_token_stream().to_string() == "lv_obj_t"
161        )
162    }
163
164    /// Whether the guest argument at `index` is a non-pointer integer: a
165    /// primitive or C integer type, or one of the catalog's integer aliases.
166    pub fn argument_is_integer(&self, index: usize, catalog: &CallCatalog) -> bool {
167        self.signature.variadic.is_none()
168            && self
169                .guest_argument(index)
170                .is_some_and(|argument| catalog.is_integer(argument))
171    }
172
173    /// Conservative policy: pointer lifetimes cannot be inferred from a C signature.
174    /// Strings, arrays, native structures and unions need explicit adapters.
175    pub fn generic_safe(&self) -> bool {
176        fn safe_type(ty: &Type) -> bool {
177            match ty {
178                Type::Path(path) => {
179                    let name = path.to_token_stream().to_string();
180                    matches!(
181                        name.as_str(),
182                        "u8" | "u16"
183                            | "u32"
184                            | "u64"
185                            | "i8"
186                            | "i16"
187                            | "i32"
188                            | "i64"
189                            | "bool"
190                            | "usize"
191                            | "isize"
192                            | "lv_coord_t"
193                            | "lv_state_t"
194                            | "lv_obj_flag_t"
195                            | "lv_style_selector_t"
196                            | "lv_flex_flow_t"
197                            | "lv_opa_t"
198                    )
199                }
200                Type::Ptr(ptr) => ptr.elem.to_token_stream().to_string() == "lv_obj_t",
201                _ => false,
202            }
203        }
204        self.signature.variadic.is_none()
205            && self.signature.inputs.iter().all(|arg| {
206                let FnArg::Typed(arg) = arg else { return false };
207                let Pat::Ident(name) = &*arg.pat else {
208                    return false;
209                };
210                !name.ident.to_string().starts_with("__") && safe_type(&arg.ty)
211            })
212            && match &self.signature.output {
213                ReturnType::Default => true,
214                ReturnType::Type(_, ty) => safe_type(ty),
215            }
216    }
217}
218
219/// The last path segment of a plain, non-generic type such as `c_uint`.
220fn plain_type_name(ty: &Type) -> Option<String> {
221    let Type::Path(path) = ty else { return None };
222    let last = path.path.segments.last()?;
223    (path.qself.is_none() && last.arguments.is_none()).then(|| last.ident.to_string())
224}
225
226fn is_integer_name(name: &str) -> bool {
227    matches!(
228        name,
229        "u8" | "u16"
230            | "u32"
231            | "u64"
232            | "usize"
233            | "i8"
234            | "i16"
235            | "i32"
236            | "i64"
237            | "isize"
238            | "c_char"
239            | "c_schar"
240            | "c_uchar"
241            | "c_short"
242            | "c_ushort"
243            | "c_int"
244            | "c_uint"
245            | "c_long"
246            | "c_ulong"
247            | "c_longlong"
248            | "c_ulonglong"
249    )
250}
251
252#[derive(Debug)]
253pub struct CallCatalog {
254    calls: Vec<Call>,
255    /// Type aliases that resolve to an integer, such as LVGL's enumerations.
256    integer_aliases: BTreeSet<String>,
257    /// Every LVGL function, by name, including those guests cannot call.
258    natives: BTreeMap<String, Signature>,
259}
260
261impl CallCatalog {
262    pub fn parse(source: &str) -> Result<Self, GeneratorError> {
263        let context =
264            LvglContext::parse(source).map_err(|error| GeneratorError(error.to_string()))?;
265        let mut catalog = Self::from_signatures(context.get_signatures())?;
266        catalog.integer_aliases = integer_aliases(&context.get_aliases());
267        catalog.natives = context.get_natives();
268        Ok(catalog)
269    }
270
271    /// Whether the LVGL function `name` takes `(object, integer)`, so a
272    /// generated `v as _` cast from a guest word is an integer conversion.
273    pub fn native_sets_integer(&self, name: &str) -> bool {
274        let Some(signature) = self.natives.get(name) else {
275            return false;
276        };
277        let arguments: Vec<_> = signature
278            .inputs
279            .iter()
280            .filter_map(|argument| match argument {
281                FnArg::Typed(argument) => Some(&*argument.ty),
282                FnArg::Receiver(_) => None,
283            })
284            .collect();
285        signature.variadic.is_none()
286            && signature.inputs.len() == 2
287            && matches!(
288                arguments[..],
289                [Type::Ptr(object), value]
290                    if object.elem.to_token_stream().to_string() == "lv_obj_t"
291                        && self.is_integer(value)
292            )
293    }
294
295    /// Whether `ty` is a non-pointer integer, directly or through an alias.
296    pub fn is_integer(&self, ty: &Type) -> bool {
297        plain_type_name(ty)
298            .is_some_and(|name| is_integer_name(&name) || self.integer_aliases.contains(&name))
299    }
300
301    pub fn from_signatures(mut signatures: Vec<Signature>) -> Result<Self, GeneratorError> {
302        signatures.sort_by_key(|sig| {
303            let name = sig.ident.to_string();
304            (extension_id(&name).is_some(), name.to_lowercase())
305        });
306        let mut names = BTreeSet::new();
307        let mut legacy_id = 0u16;
308        let calls = signatures
309            .into_iter()
310            .map(|signature| {
311                let id = if let Some(id) = extension_id(&signature.ident.to_string()) {
312                    id
313                } else {
314                    if legacy_id >= 0xf000 {
315                        return Err(GeneratorError("too many legacy call IDs".into()));
316                    }
317                    let id = legacy_id;
318                    legacy_id += 1;
319                    id
320                };
321                let name = get_function_identifier("", &signature.ident).to_string();
322                if !names.insert(name.clone()) {
323                    return Err(GeneratorError(format!("duplicate guest call {name}")));
324                }
325                let mut argument_count = 0;
326                let mut host_arguments = Vec::new();
327                for argument in &signature.inputs {
328                    let FnArg::Typed(argument) = argument else {
329                        return Err(GeneratorError(format!("receiver in {name}")));
330                    };
331                    let Pat::Ident(ident) = &*argument.pat else {
332                        return Err(GeneratorError(format!("unnamed argument in {name}")));
333                    };
334                    let ident = ident.ident.to_string();
335                    if ident.starts_with("__") {
336                        host_arguments.push(ident);
337                    } else {
338                        argument_count += 1;
339                    }
340                }
341                if argument_count > MAX_ARGUMENTS {
342                    return Err(GeneratorError(format!(
343                        "{name} exceeds seven guest arguments"
344                    )));
345                }
346                Ok(Call {
347                    id,
348                    name,
349                    signature,
350                    argument_count,
351                    host_arguments,
352                })
353            })
354            .collect::<Result<Vec<_>, _>>()?;
355        Ok(Self {
356            calls,
357            integer_aliases: BTreeSet::new(),
358            natives: BTreeMap::new(),
359        })
360    }
361
362    pub fn calls(&self) -> &[Call] {
363        &self.calls
364    }
365
366    /// Select a registry subset by normalized call name without changing catalog IDs.
367    pub fn select(&self, names: &[&str]) -> Result<Vec<&Call>, GeneratorError> {
368        let mut selected = Vec::with_capacity(names.len());
369        let mut unique = BTreeSet::new();
370        for name in names {
371            if !unique.insert(*name) {
372                return Err(GeneratorError(format!("duplicate supported call {name}")));
373            }
374            let call = self
375                .calls
376                .iter()
377                .find(|call| call.name == *name)
378                .ok_or_else(|| {
379                    GeneratorError(format!("supported call {name} is not in the LVGL catalog"))
380                })?;
381            selected.push(call);
382        }
383        Ok(selected)
384    }
385
386    pub fn signatures(&self) -> Vec<Signature> {
387        self.calls
388            .iter()
389            .map(|call| call.signature.clone())
390            .collect()
391    }
392}
393
394/// The aliases that resolve, possibly through other aliases, to an integer.
395fn integer_aliases(aliases: &BTreeMap<String, Type>) -> BTreeSet<String> {
396    let mut integers = BTreeSet::new();
397    loop {
398        let before = integers.len();
399        for (alias, target) in aliases {
400            if let Some(name) = plain_type_name(target)
401                && (is_integer_name(&name) || integers.contains(&name))
402            {
403                integers.insert(alias.clone());
404            }
405        }
406        if integers.len() == before {
407            return integers;
408        }
409    }
410}