Skip to main content

graphics_bindgen/
context.rs

1use quote::ToTokens;
2use std::collections::BTreeMap;
3use syn::{ForeignItemFn, ItemFn, ItemType, Signature, Type, visit::Visit};
4
5#[derive(Default)]
6pub struct LvglContext {
7    signatures: Vec<Signature>,
8    definitions: Vec<ItemFn>,
9    /// Plain type aliases, such as bindgen's `pub type lv_arc_mode_t = c_uint;`.
10    aliases: BTreeMap<String, Type>,
11    /// Every foreign function, including those the filter keeps from guests.
12    natives: BTreeMap<String, Signature>,
13    function_filtering: Option<fn(&Signature) -> bool>,
14}
15
16impl LvglContext {
17    pub fn parse(source: &str) -> syn::Result<Self> {
18        let mut context = Self::default();
19        context.set_function_filtering(Some(Self::filter_function));
20        context.visit_file(&syn::parse_file(source)?);
21        context.set_function_filtering(None);
22        context.visit_file(&syn::parse2(crate::additional::get())?);
23        Ok(context)
24    }
25
26    pub fn set_function_filtering(&mut self, function_filtering: Option<fn(&Signature) -> bool>) {
27        self.function_filtering = function_filtering;
28    }
29
30    pub fn get_signatures(&self) -> Vec<Signature> {
31        self.signatures.clone()
32    }
33
34    pub fn get_definitions(&self) -> Vec<ItemFn> {
35        self.definitions.clone()
36    }
37
38    pub fn get_aliases(&self) -> BTreeMap<String, Type> {
39        self.aliases.clone()
40    }
41
42    pub fn get_natives(&self) -> BTreeMap<String, Signature> {
43        self.natives.clone()
44    }
45
46    fn contains_excluded_type(signature: &Signature) -> bool {
47        signature.inputs.iter().any(|input| match input {
48            syn::FnArg::Typed(pat_type) => match &*pat_type.ty {
49                syn::Type::Path(type_path) => {
50                    let path = type_path.path.to_token_stream().to_string();
51
52                    path.contains("_cb_")
53                }
54                syn::Type::Ptr(type_ptr) => {
55                    let element = type_ptr.elem.to_token_stream().to_string();
56
57                    element.contains("lv_event_t")
58                        || element.ends_with("_dsc_t")
59                        || element.ends_with("_cursor_t")
60                        || element.ends_with("_font_t")
61                        || element.ends_with("_group_t")
62                        || element.ends_with("_layer_t")
63                }
64                _ => false,
65            },
66            _ => false,
67        }) || match &signature.output {
68            syn::ReturnType::Type(_, type_value) => match &**type_value {
69                syn::Type::Path(type_path) => {
70                    let path = type_path.path.to_token_stream().to_string();
71
72                    path.contains("_cb_")
73                }
74                syn::Type::Ptr(type_ptr) => {
75                    let element = type_ptr.elem.to_token_stream().to_string();
76
77                    element.contains("lv_event_t")
78                        || element.ends_with("_dsc_t")
79                        || element.ends_with("_cursor_t")
80                        || element.ends_with("_font_t")
81                        || element.ends_with("_group_t")
82                        || element.ends_with("_layer_t")
83                }
84                _ => false,
85            },
86            _ => false,
87        }
88    }
89
90    pub fn filter_function(signature: &Signature) -> bool {
91        let unauthorized_functions = [
92            // Object IDs now belong exclusively to lvgl-rust's registry. These
93            // declarations were absent from the legacy ABI (LV_USE_OBJ_ID=0);
94            // exposing them would both corrupt the registry and shift call IDs.
95            "lv_obj_assign_id",
96            "lv_obj_free_id",
97            "lv_obj_set_id",
98            "lv_obj_get_id",
99            "lv_obj_find_by_id",
100            "lv_obj_id_compare",
101            "lv_obj_stringify_id",
102            "lv_obj_delete",
103            "lv_obj_get_display",
104            "lv_obj_delete_delayed",
105            "lv_obj_delete_async",
106            "lv_obj_null_on_delete",
107            "lv_buttonmatrix_get_map",
108            "lv_textarea_get_text",
109            "lv_obj_get_layer_type",
110            // Internal/private object functions are visible because private LVGL API is
111            // enabled for Core, but are not safe to expose through the wasm ABI.
112            "lv_obj_allocate_spec_attr",
113            "lv_obj_destruct",
114            "lv_obj_add_child",
115            "lv_obj_remove_child",
116            "lv_obj_invalidate_expand_blur",
117            // LVGL's variadic API uses va_list, which cannot cross this ABI.
118            "lv_label_set_text_vfmt",
119            // These APIs use LVGL types not available in the wasm translation layer.
120            "lv_style_set_image_colorkey",
121            "lv_obj_get_style_image_colorkey",
122            "lv_obj_set_style_image_colorkey",
123            "lv_obj_add_play_timeline_event",
124        ];
125
126        let signature_ident_str = signature.ident.to_string();
127
128        if unauthorized_functions.contains(&signature_ident_str.as_str()) {
129            return false;
130        }
131
132        let authorized_prefixes = [
133            "lv_point_",
134            "lv_color",
135            "lv_label",
136            "lv_style_",
137            "lv_obj_",
138            "lv_style_",
139            "lv_arc_",
140            "lv_coord_",
141            "lv_button_",
142            "lv_buttonmatrix_",
143            "lv_calendar_",
144            "lv_chart_",
145            "lv_checkbox_",
146            "lv_dropdown_",
147            "lv_led_",
148            "lv_line_",
149            "lv_menu_",
150            "lv_msgbox_",
151            "lv_roller_",
152            "lv_scale_",
153            "lv_slider_",
154            "lv_textarea_",
155            "lv_spinbox_",
156            "lv_table_",
157            "lv_tabview_",
158            "lv_tileview_",
159            "lv_subject_",
160            "lv_screen_",
161            "Window_",
162            "Object_",
163        ];
164
165        if !authorized_prefixes
166            .iter()
167            .any(|&prefix| signature_ident_str.starts_with(prefix))
168        {
169            return false;
170        }
171
172        // Check if on of the function parameter contains a function pointer
173        if Self::contains_excluded_type(signature) {
174            return false;
175        }
176
177        true
178    }
179}
180
181impl Visit<'_> for LvglContext {
182    fn visit_foreign_item_fn(&mut self, foreign_item_function: &ForeignItemFn) {
183        self.natives.insert(
184            foreign_item_function.sig.ident.to_string(),
185            foreign_item_function.sig.clone(),
186        );
187        if let Some(filter_function) = self.function_filtering
188            && !filter_function(&foreign_item_function.sig)
189        {
190            return;
191        }
192
193        self.signatures.push(foreign_item_function.sig.clone());
194    }
195
196    fn visit_item_type(&mut self, item: &ItemType) {
197        if item.generics.params.is_empty() {
198            self.aliases
199                .insert(item.ident.to_string(), (*item.ty).clone());
200        }
201    }
202
203    fn visit_item_fn(&mut self, i: &'_ syn::ItemFn) {
204        if let Some(filter_function) = self.function_filtering
205            && !filter_function(&i.sig)
206        {
207            return;
208        }
209
210        self.signatures.push(i.sig.clone());
211        self.definitions.push(i.clone());
212    }
213}