1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum ObjectOperation {
23 Call,
25 SetBool,
27 SetU8,
29 SetU32 { min: u32, max: u32 },
31 SetMask { mask: u32 },
33 GetU32,
35 GetBool,
37 GetI32,
39 SetEnum { max: &'static str },
41 SetU32Limit { max: u32 },
43 SetText { limit: &'static str },
46 SetRange,
49 SetStyle(StyleValue),
51 GetI32ByKind(KindTable),
54 SetEnumByKind { max: u32, table: KindTable },
56 SetRangeByKind(KindTable),
58}
59
60pub type KindTable = &'static [(&'static str, &'static str)];
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum StyleValue {
66 Color,
68 I32 { min: i32, max: i32 },
70 Enum { max: &'static str },
72 Font,
74}
75
76impl ObjectOperation {
77 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 Manual,
99 AutoObjectScalar(AutoObjectScalar),
101 Custom(&'static str),
103 Object {
106 kind: Option<&'static str>,
107 operation: ObjectOperation,
108 native: Option<&'static str>,
110 },
111 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 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 ObjectOperation::SetEnum { .. } => {
215 call.argument_is_object(0) && call.argument_is_integer(1, catalog)
216 }
217 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 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}