Skip to main content

graphics_bindgen/
registry.rs

1//! Build-time support registry for the WASM graphics ABI.
2//!
3//! This stores no runtime metadata. The build script uses the selected calls
4//! and adapter policies to emit Rust code and discard the registry.
5
6use crate::{Call, CallCatalog, GeneratorError};
7use quote::ToTokens;
8use std::collections::{BTreeMap, BTreeSet};
9use syn::ReturnType;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum AutoObjectScalar {
13    SetI32,
14    SetPairI32,
15    GetI32,
16}
17
18/// What a generated object call does with its argument words. The object is
19/// always the first word, resolved (and checked against the rule's kind)
20/// before anything else is read.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum ObjectOperation {
23    /// `(object)`.
24    Call,
25    /// `(object, bool)`; a word above 1 is invalid.
26    SetBool,
27    /// `(object, u8)`.
28    SetU8,
29    /// `(object, u32)`, the word within `min..=max`.
30    SetU32 { min: u32, max: u32 },
31    /// `(object, u32)`, a word made of the bits in `mask` only.
32    SetMask { mask: u32 },
33    /// `(object) -> u32`.
34    GetU32,
35    /// `(object) -> bool`, widened to a `u32` result.
36    GetBool,
37    /// `(object) -> i32`.
38    GetI32,
39    /// `(object, u32)`, at most the LVGL enumeration constant `max`.
40    SetEnum { max: &'static str },
41    /// `(object, u32)`, above `max` is a resource limit, not an invalid value.
42    SetU32Limit { max: u32 },
43    /// `(object, text)`: a string of at most the marshal constant `limit`
44    /// bytes, NUL included, which LVGL copies.
45    SetText { limit: &'static str },
46    /// `(object, min, max)`: signed words with `min < max`, both within the
47    /// range limit.
48    SetRange,
49    /// `(object, value, selector)`: a local style property.
50    SetStyle(StyleValue),
51    /// `(object) -> i32`, by the object's kind: the kind and LVGL function
52    /// pairs. Any other kind is an invalid handle.
53    GetI32ByKind(KindTable),
54    /// `(object, u32)`, at most `max`, then by the object's kind.
55    SetEnumByKind { max: u32, table: KindTable },
56    /// `(object, min, max)` as [`ObjectOperation::SetRange`], then by kind.
57    SetRangeByKind(KindTable),
58}
59
60/// The kinds a by-kind operation accepts, each with its LVGL function.
61pub type KindTable = &'static [(&'static str, &'static str)];
62
63/// How a style call's value word becomes the property's native value.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum StyleValue {
66    /// A 24-bit RGB word, made into an LVGL color.
67    Color,
68    /// A signed word within `min..=max`.
69    I32 { min: i32, max: i32 },
70    /// An unsigned word of at most the LVGL enumeration constant `max`.
71    Enum { max: &'static str },
72    /// The index of one of Xila's fonts.
73    Font,
74}
75
76impl ObjectOperation {
77    /// Arguments after the object, and whether the call returns a value.
78    fn shape(self) -> (usize, bool) {
79        match self {
80            Self::Call => (0, false),
81            Self::SetBool
82            | Self::SetU8
83            | Self::SetU32 { .. }
84            | Self::SetMask { .. }
85            | Self::SetEnum { .. }
86            | Self::SetU32Limit { .. }
87            | Self::SetText { .. }
88            | Self::SetEnumByKind { .. } => (1, false),
89            Self::SetRange | Self::SetRangeByKind(_) | Self::SetStyle(_) => (2, false),
90            Self::GetU32 | Self::GetBool | Self::GetI32 | Self::GetI32ByKind(_) => (0, true),
91        }
92    }
93}
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum AdapterPolicy {
97    /// Existing handwritten dispatch arm; used until it is migrated.
98    Manual,
99    /// Generated scalar call. Object arguments are explicitly guest handles.
100    AutoObjectScalar(AutoObjectScalar),
101    /// Generated dispatch arm calls this named handwritten adapter.
102    Custom(&'static str),
103    /// Generated call on one object of an optional kind (`None`: any object).
104    /// The native function is called through a shared helper per operation.
105    Object {
106        kind: Option<&'static str>,
107        operation: ObjectOperation,
108        /// The LVGL function, when it is not the call's own name with `lv_`.
109        native: Option<&'static str>,
110    },
111    /// Generated constructor: the native `(parent) -> object` function plus the
112    /// kind the new object is registered under.
113    Create(&'static str),
114}
115
116#[derive(Clone, Copy, Debug)]
117pub struct AdapterRule {
118    name: &'static str,
119    policy: AdapterPolicy,
120}
121
122impl AdapterRule {
123    pub const fn automatic(name: &'static str, adapter: AutoObjectScalar) -> Self {
124        Self {
125            name,
126            policy: AdapterPolicy::AutoObjectScalar(adapter),
127        }
128    }
129
130    pub const fn object(
131        name: &'static str,
132        kind: Option<&'static str>,
133        operation: ObjectOperation,
134        native: Option<&'static str>,
135    ) -> Self {
136        Self {
137            name,
138            policy: AdapterPolicy::Object {
139                kind,
140                operation,
141                native,
142            },
143        }
144    }
145
146    pub const fn create(name: &'static str, kind: &'static str) -> Self {
147        Self {
148            name,
149            policy: AdapterPolicy::Create(kind),
150        }
151    }
152
153    pub const fn custom(name: &'static str, handler: &'static str) -> Self {
154        Self {
155            name,
156            policy: AdapterPolicy::Custom(handler),
157        }
158    }
159}
160
161pub struct GraphicsRegistry<'a> {
162    calls: Vec<&'a Call>,
163    adapters: BTreeMap<String, AdapterPolicy>,
164}
165
166impl<'a> GraphicsRegistry<'a> {
167    pub fn new(
168        catalog: &'a CallCatalog,
169        supported_names: &[&str],
170        rules: &[AdapterRule],
171    ) -> Result<Self, GeneratorError> {
172        let calls = catalog.select(supported_names)?;
173        let supported: BTreeSet<_> = calls.iter().map(|call| call.name.as_str()).collect();
174        let mut adapters: BTreeMap<_, _> = calls
175            .iter()
176            .map(|call| (call.name.clone(), AdapterPolicy::Manual))
177            .collect();
178        let mut seen_rules = BTreeSet::new();
179
180        for rule in rules {
181            if !supported.contains(rule.name) {
182                return Err(GeneratorError::new(format!(
183                    "adapter policy for unregistered call {}",
184                    rule.name
185                )));
186            }
187            if !seen_rules.insert(rule.name) {
188                return Err(GeneratorError::new(format!(
189                    "duplicate adapter policy for {}",
190                    rule.name
191                )));
192            }
193            adapters.insert(rule.name.to_string(), rule.policy);
194            if let AdapterPolicy::AutoObjectScalar(adapter) = rule.policy {
195                let call = calls
196                    .iter()
197                    .find(|call| call.name == rule.name)
198                    .expect("validated supported name");
199                validate_auto_object_scalar(call, adapter)?;
200            }
201            if let AdapterPolicy::Object { operation, .. } = rule.policy {
202                let call = calls
203                    .iter()
204                    .find(|call| call.name == rule.name)
205                    .expect("validated supported name");
206                let (extra, returns) = operation.shape();
207                // A string is the one pointer argument a generated call takes:
208                // LVGL copies it, and the declaration pins its exact type.
209                let scalar = match operation {
210                    ObjectOperation::SetText { .. } => call
211                        .validate_signature(&["*mut lv_obj_t", "*const core::ffi::c_char"], None)
212                        .is_ok(),
213                    // An enumeration argument is an integer, whatever its alias.
214                    ObjectOperation::SetEnum { .. } => {
215                        call.argument_is_object(0) && call.argument_is_integer(1, catalog)
216                    }
217                    // The helper takes a `u32`; each native's argument is cast
218                    // from it, so it must be an integer too.
219                    ObjectOperation::SetEnumByKind { table, .. } => {
220                        call.validate_signature(&["*mut lv_obj_t", "u32"], None)
221                            .is_ok()
222                            && table
223                                .iter()
224                                .all(|(_, native)| catalog.native_sets_integer(native))
225                    }
226                    _ => call.generic_safe(),
227                };
228                if !scalar
229                    || call.argument_count != 1 + extra
230                    || matches!(call.signature.output, ReturnType::Type(..)) != returns
231                {
232                    return Err(GeneratorError::new(format!(
233                        "object adapter for {} does not match its signature",
234                        rule.name
235                    )));
236                }
237            }
238            if let AdapterPolicy::Create(_) = rule.policy {
239                let call = calls
240                    .iter()
241                    .find(|call| call.name == rule.name)
242                    .expect("validated supported name");
243                call.validate_signature(&["*mut lv_obj_t"], Some("*mut lv_obj_t"))?;
244            }
245            if let AdapterPolicy::Custom(handler) = rule.policy
246                && handler.trim().is_empty()
247            {
248                return Err(GeneratorError::new(format!(
249                    "empty custom handler for {}",
250                    rule.name
251                )));
252            }
253        }
254
255        Ok(Self { calls, adapters })
256    }
257
258    pub fn calls(&self) -> &[&'a Call] {
259        &self.calls
260    }
261
262    pub fn adapter_for(&self, name: &str) -> Option<AdapterPolicy> {
263        self.adapters.get(name).copied()
264    }
265
266    /// Deterministic build artifact inventory. It is emitted to OUT_DIR only;
267    /// no registry or metadata table is linked into the runtime.
268    pub fn inventory_json(&self, catalog: &CallCatalog) -> String {
269        fn escape(value: &str) -> String {
270            let mut escaped = String::with_capacity(value.len());
271            for character in value.chars() {
272                match character {
273                    '"' => escaped.push_str("\\\""),
274                    '\\' => escaped.push_str("\\\\"),
275                    '\n' => escaped.push_str("\\n"),
276                    '\r' => escaped.push_str("\\r"),
277                    '\t' => escaped.push_str("\\t"),
278                    character if character.is_control() => {
279                        use core::fmt::Write;
280                        let _ = write!(escaped, "\\u{:04x}", character as u32);
281                    }
282                    character => escaped.push(character),
283                }
284            }
285            escaped
286        }
287
288        let mut json = String::from("{\"calls\":[");
289        for (index, call) in catalog.calls().iter().enumerate() {
290            if index != 0 {
291                json.push(',');
292            }
293            let signature = call.signature.to_token_stream().to_string();
294            let return_type = match &call.signature.output {
295                ReturnType::Default => "void".to_string(),
296                ReturnType::Type(_, output) => output.to_token_stream().to_string(),
297            };
298            let (guest, adapter, handler, reason, ownership) = match self.adapter_for(&call.name) {
299                Some(AdapterPolicy::Manual) => (true, "manual", "null", "null", "handwritten"),
300                Some(AdapterPolicy::AutoObjectScalar(_)) => (
301                    true,
302                    "auto_object_scalar",
303                    "null",
304                    "null",
305                    "scalar_no_retention",
306                ),
307                Some(AdapterPolicy::Custom(handler)) => {
308                    (true, "custom", handler, "null", "handwritten")
309                }
310                Some(AdapterPolicy::Object {
311                    operation: ObjectOperation::SetText { .. },
312                    ..
313                }) => (true, "object", "null", "null", "copied_string_no_retention"),
314                Some(AdapterPolicy::Object { .. }) => {
315                    (true, "object", "null", "null", "scalar_no_retention")
316                }
317                Some(AdapterPolicy::Create(_)) => {
318                    (true, "create", "null", "null", "host_object_creation")
319                }
320                None => (
321                    false,
322                    "null",
323                    "null",
324                    "\"No host adapter registered\"",
325                    "unknown_or_not_supported",
326                ),
327            };
328            use core::fmt::Write;
329            let _ = write!(
330                json,
331                "{{\"name\":\"{}\",\"id\":{},\"argument_count\":{},\"return\":\"{}\",\"signature\":\"{}\",\"discovered\":true,\"guest_wrapper\":{},\"host_adapter\":{},\"custom_handler\":{},\"ownership\":\"{}\",\"unsupported_reason\":{}}}",
332                escape(&call.name),
333                call.id,
334                call.argument_count,
335                escape(&return_type),
336                escape(&signature),
337                guest,
338                if adapter == "null" {
339                    "null".to_string()
340                } else {
341                    format!("\"{adapter}\"")
342                },
343                if handler == "null" {
344                    "null".to_string()
345                } else {
346                    format!("\"{}\"", escape(handler))
347                },
348                ownership,
349                reason,
350            );
351        }
352        json.push_str("]}\n");
353        json
354    }
355}
356
357fn validate_auto_object_scalar(
358    call: &Call,
359    adapter: AutoObjectScalar,
360) -> Result<(), GeneratorError> {
361    if !call.generic_safe() {
362        return Err(GeneratorError::new(format!(
363            "automatic adapter for {} uses a non-scalar or pointer-retaining signature",
364            call.name
365        )));
366    }
367    let (arguments, output): (&[&str], Option<&str>) = match adapter {
368        AutoObjectScalar::SetI32 => (&["*mut lv_obj_t", "i32"], None),
369        AutoObjectScalar::SetPairI32 => (&["*mut lv_obj_t", "i32", "i32"], None),
370        AutoObjectScalar::GetI32 => (&["*const lv_obj_t"], Some("i32")),
371    };
372    call.validate_signature(arguments, output)
373}