| @@ -0,0 +1,964 @@ |
| 1 | +//! From parsed declarations to the tilcayo module and its C shim. |
| 2 | + |
| 3 | +use std::collections::{BTreeMap, HashMap, HashSet}; |
| 4 | +use std::fmt::Write; |
| 5 | + |
| 6 | +use crate::parse::{self, Item, Param, Signature, TypeSyntax}; |
| 7 | + |
| 8 | +/// The generated files, and what was left out. |
| 9 | +#[derive(Debug)] |
| 10 | +pub struct Bindings { |
| 11 | + /// The tilcayo module: `@extern` declarations and opaque types. |
| 12 | + pub til: String, |
| 13 | + /// The C shim the declarations call. |
| 14 | + pub c: String, |
| 15 | + pub skipped: Vec<Skipped>, |
| 16 | +} |
| 17 | + |
| 18 | +/// A declaration that was not bound, or a remark about one. |
| 19 | +#[derive(Clone, Debug, PartialEq)] |
| 20 | +pub struct Skipped { |
| 21 | + pub line: u32, |
| 22 | + /// The C name, or the declaration as written. |
| 23 | + pub what: String, |
| 24 | + pub reason: String, |
| 25 | +} |
| 26 | + |
| 27 | +/// Bindings for `header` (its text), which the shim includes as |
| 28 | +/// `#include "<include>"`. |
| 29 | +pub fn generate(header: &str, include: &str) -> Bindings { |
| 30 | + let items = parse::parse(header); |
| 31 | + let mut g = Generator::new(&items); |
| 32 | + for located in &items { |
| 33 | + g.item(located.line, &located.item); |
| 34 | + } |
| 35 | + g.finish(include) |
| 36 | +} |
| 37 | + |
| 38 | +/// Shim functions and trampolines are prefixed so they cannot collide with |
| 39 | +/// the library's names, nor with the runtime's (`tl_`). |
| 40 | +const PREFIX: &str = "tilcayo_"; |
| 41 | + |
| 42 | +const CONSTRUCTOR_SUFFIXES: &[&str] = &["_new", "_create", "_open", "_copy", "_clone"]; |
| 43 | +const FINALIZER_SUFFIXES: &[&str] = &["_free", "_destroy", "_delete", "_release"]; |
| 44 | + |
| 45 | +const INT_WORDS: &[&str] = &["signed", "unsigned", "short", "long", "int", "char"]; |
| 46 | +const INT_TYPEDEFS: &[&str] = &[ |
| 47 | + "int8_t", |
| 48 | + "int16_t", |
| 49 | + "int32_t", |
| 50 | + "int64_t", |
| 51 | + "uint8_t", |
| 52 | + "uint16_t", |
| 53 | + "uint32_t", |
| 54 | + "uint64_t", |
| 55 | + "size_t", |
| 56 | + "ssize_t", |
| 57 | + "ptrdiff_t", |
| 58 | + "intptr_t", |
| 59 | + "uintptr_t", |
| 60 | + "intmax_t", |
| 61 | + "uintmax_t", |
| 62 | +]; |
| 63 | + |
| 64 | +/// A value C and tilcayo exchange directly. `c` is its C spelling. |
| 65 | +#[derive(Clone, Debug, PartialEq)] |
| 66 | +enum Scalar { |
| 67 | + Int { c: String }, |
| 68 | + Float { c: String }, |
| 69 | + Bool, |
| 70 | +} |
| 71 | + |
| 72 | +/// What a C type means for a binding. |
| 73 | +#[derive(Clone, Debug, PartialEq)] |
| 74 | +enum Kind { |
| 75 | + Void, |
| 76 | + Scalar(Scalar), |
| 77 | + /// `const char *`. |
| 78 | + CStr, |
| 79 | + /// `void *`: a callback's environment. |
| 80 | + Env, |
| 81 | + /// A pointer to an opaque struct; `til` is the tilcayo type's name. |
| 82 | + Opaque { |
| 83 | + c: String, |
| 84 | + til: String, |
| 85 | + }, |
| 86 | + Callback(Box<Callback>), |
| 87 | +} |
| 88 | + |
| 89 | +#[derive(Clone, Debug, PartialEq)] |
| 90 | +struct Callback { |
| 91 | + /// C parameter types (the environment is `None`). |
| 92 | + params: Vec<Option<Arg>>, |
| 93 | + ret: Option<Scalar>, |
| 94 | + /// The function pointer type, for comments. |
| 95 | + shown: String, |
| 96 | +} |
| 97 | + |
| 98 | +/// A callback's argument. |
| 99 | +#[derive(Clone, Debug, PartialEq)] |
| 100 | +enum Arg { |
| 101 | + Scalar(Scalar), |
| 102 | + CStr, |
| 103 | +} |
| 104 | + |
| 105 | +struct OpaqueType { |
| 106 | + til: String, |
| 107 | + line: u32, |
| 108 | + finalizer: Option<String>, |
| 109 | +} |
| 110 | + |
| 111 | +struct Generator<'a> { |
| 112 | + /// Struct names and typedef names of opaque structs, to their key in |
| 113 | + /// `opaque` (the struct's name). |
| 114 | + opaque_names: HashMap<String, String>, |
| 115 | + opaque: BTreeMap<String, OpaqueType>, |
| 116 | + /// Structs with fields (struct names and aliases). |
| 117 | + defined: HashSet<String>, |
| 118 | + typedefs: HashMap<String, &'a TypeSyntax>, |
| 119 | + fn_typedefs: HashMap<String, &'a Signature>, |
| 120 | + /// Functions used as finalizers. |
| 121 | + finalizers: HashSet<String>, |
| 122 | + til: String, |
| 123 | + c: String, |
| 124 | + /// Trampolines by C signature: their index and code. |
| 125 | + trampolines: BTreeMap<String, (usize, String)>, |
| 126 | + uses_resource: bool, |
| 127 | + skipped: Vec<Skipped>, |
| 128 | +} |
| 129 | + |
| 130 | +impl<'a> Generator<'a> { |
| 131 | + fn new(items: &'a [parse::Located]) -> Self { |
| 132 | + let mut g = Generator { |
| 133 | + opaque_names: HashMap::new(), |
| 134 | + opaque: BTreeMap::new(), |
| 135 | + defined: HashSet::new(), |
| 136 | + typedefs: HashMap::new(), |
| 137 | + fn_typedefs: HashMap::new(), |
| 138 | + finalizers: HashSet::new(), |
| 139 | + til: String::new(), |
| 140 | + c: String::new(), |
| 141 | + trampolines: BTreeMap::new(), |
| 142 | + uses_resource: false, |
| 143 | + skipped: Vec::new(), |
| 144 | + }; |
| 145 | + // Types first, so declarations may use them in any order. |
| 146 | + for l in items { |
| 147 | + match &l.item { |
| 148 | + Item::StructDef { name, alias } => { |
| 149 | + g.defined.extend(name.iter().chain(alias).cloned()); |
| 150 | + } |
| 151 | + Item::Typedef { name, ty } => { |
| 152 | + g.typedefs.insert(name.clone(), ty); |
| 153 | + } |
| 154 | + Item::FnTypedef { name, sig } => { |
| 155 | + g.fn_typedefs.insert(name.clone(), sig); |
| 156 | + } |
| 157 | + _ => {} |
| 158 | + } |
| 159 | + } |
| 160 | + for l in items { |
| 161 | + if let Item::StructDecl { name, alias } = &l.item |
| 162 | + && !g.defined.contains(name) |
| 163 | + { |
| 164 | + g.opaque_names |
| 165 | + .insert(format!("struct {name}"), name.clone()); |
| 166 | + if let Some(a) = alias { |
| 167 | + g.opaque_names.insert(a.clone(), name.clone()); |
| 168 | + } |
| 169 | + g.opaque.entry(name.clone()).or_insert(OpaqueType { |
| 170 | + til: type_name(name), |
| 171 | + line: l.line, |
| 172 | + finalizer: None, |
| 173 | + }); |
| 174 | + } |
| 175 | + } |
| 176 | + g.find_finalizers(items); |
| 177 | + g |
| 178 | + } |
| 179 | + |
| 180 | + /// Each opaque type's finalizer: the one `void f(T *)` named like one. |
| 181 | + fn find_finalizers(&mut self, items: &[parse::Located]) { |
| 182 | + let mut found: BTreeMap<String, Vec<String>> = BTreeMap::new(); |
| 183 | + for l in items { |
| 184 | + let Item::Function { name, sig } = &l.item else { |
| 185 | + continue; |
| 186 | + }; |
| 187 | + if !FINALIZER_SUFFIXES.iter().any(|s| name.ends_with(s)) |
| 188 | + || sig.params.len() != 1 |
| 189 | + || self.kind(&sig.ret) != Ok(Kind::Void) |
| 190 | + { |
| 191 | + continue; |
| 192 | + } |
| 193 | + if let Ok(Kind::Opaque { til, .. }) = self.kind(&sig.params[0].ty) |
| 194 | + && let Some(key) = self |
| 195 | + .opaque |
| 196 | + .iter() |
| 197 | + .find(|(_, o)| o.til == til) |
| 198 | + .map(|(k, _)| k) |
| 199 | + { |
| 200 | + found.entry(key.clone()).or_default().push(name.clone()); |
| 201 | + } |
| 202 | + } |
| 203 | + for (key, fns) in found { |
| 204 | + if let [f] = fns.as_slice() { |
| 205 | + self.finalizers.insert(f.clone()); |
| 206 | + if let Some(o) = self.opaque.get_mut(&key) { |
| 207 | + o.finalizer = Some(f.clone()); |
| 208 | + } |
| 209 | + } |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + fn skip(&mut self, line: u32, what: &str, reason: impl Into<String>) { |
| 214 | + self.skipped.push(Skipped { |
| 215 | + line, |
| 216 | + what: what.to_owned(), |
| 217 | + reason: reason.into(), |
| 218 | + }); |
| 219 | + } |
| 220 | + |
| 221 | + fn item(&mut self, line: u32, item: &Item) { |
| 222 | + match item { |
| 223 | + Item::Function { name, sig } => { |
| 224 | + if self.finalizers.contains(name) { |
| 225 | + let til = self |
| 226 | + .opaque |
| 227 | + .values() |
| 228 | + .find(|o| o.finalizer.as_ref() == Some(name)) |
| 229 | + .map(|o| o.til.clone()) |
| 230 | + .unwrap_or_default(); |
| 231 | + self.skip(line, name, format!("the finalizer of `{til}`, not bound")); |
| 232 | + } else if let Err(reason) = self.function(name, sig) { |
| 233 | + self.skip(line, name, reason); |
| 234 | + } |
| 235 | + } |
| 236 | + Item::StructDef { name, alias } => { |
| 237 | + let shown = name |
| 238 | + .as_ref() |
| 239 | + .or(alias.as_ref()) |
| 240 | + .cloned() |
| 241 | + .unwrap_or_default(); |
| 242 | + self.skip(line, &format!("struct {shown}"), "a struct with fields"); |
| 243 | + } |
| 244 | + Item::Other(text) => self.skip(line, text, "not a supported declaration"), |
| 245 | + Item::StructDecl { .. } | Item::FnTypedef { .. } | Item::Typedef { .. } => {} |
| 246 | + } |
| 247 | + } |
| 248 | + |
| 249 | + /// What `ty` means for a binding, or why it is not supported. |
| 250 | + fn kind(&self, ty: &TypeSyntax) -> Result<Kind, String> { |
| 251 | + let (words, is_const, pointers) = match ty { |
| 252 | + TypeSyntax::Plain { |
| 253 | + words, |
| 254 | + is_const, |
| 255 | + pointers, |
| 256 | + } => (words, *is_const, *pointers), |
| 257 | + TypeSyntax::FnPointer(sig) => return self.callback(sig, &shown_fn(sig)), |
| 258 | + TypeSyntax::Unsupported(text) => return Err(format!("unsupported type `{text}`")), |
| 259 | + }; |
| 260 | + let spelled = words.join(" "); |
| 261 | + let shown = format!( |
| 262 | + "{}{spelled}{}{}", |
| 263 | + if is_const { "const " } else { "" }, |
| 264 | + if pointers > 0 { " " } else { "" }, |
| 265 | + "*".repeat(pointers) |
| 266 | + ); |
| 267 | + if let [one] = words.as_slice() { |
| 268 | + if let Some(target) = self.typedefs.get(one) { |
| 269 | + // A typedef of a scalar keeps its own name in C. |
| 270 | + return match (self.kind(target)?, pointers) { |
| 271 | + (Kind::Scalar(Scalar::Int { .. }), 0) => { |
| 272 | + Ok(Kind::Scalar(Scalar::Int { c: spelled })) |
| 273 | + } |
| 274 | + (Kind::Scalar(Scalar::Float { .. }), 0) => { |
| 275 | + Ok(Kind::Scalar(Scalar::Float { c: spelled })) |
| 276 | + } |
| 277 | + (Kind::Scalar(Scalar::Bool), 0) => Ok(Kind::Scalar(Scalar::Bool)), |
| 278 | + _ => Err(format!("unsupported type `{shown}`")), |
| 279 | + }; |
| 280 | + } |
| 281 | + if let Some(sig) = self.fn_typedefs.get(one) { |
| 282 | + return match pointers { |
| 283 | + 0 => self.callback(sig, one), |
| 284 | + _ => Err(format!("a pointer to the function pointer `{one}`")), |
| 285 | + }; |
| 286 | + } |
| 287 | + } |
| 288 | + if let Some(key) = self.opaque_names.get(&spelled) { |
| 289 | + return match pointers { |
| 290 | + 1 => Ok(Kind::Opaque { |
| 291 | + c: format!("{}{spelled} *", if is_const { "const " } else { "" }), |
| 292 | + til: self.opaque[key].til.clone(), |
| 293 | + }), |
| 294 | + 0 => Err(format!("the struct `{spelled}` by value")), |
| 295 | + _ => Err(format!("unsupported type `{shown}`")), |
| 296 | + }; |
| 297 | + } |
| 298 | + let struct_name = words.get(1).filter(|_| words[0] == "struct"); |
| 299 | + if self.defined.contains(&spelled) || struct_name.is_some_and(|n| self.defined.contains(n)) |
| 300 | + { |
| 301 | + return Err(format!( |
| 302 | + "`{shown}`: only pointers to opaque structs are supported" |
| 303 | + )); |
| 304 | + } |
| 305 | + let scalar = if words.iter().all(|w| INT_WORDS.contains(&w.as_str())) |
| 306 | + || (words.len() == 1 && INT_TYPEDEFS.contains(&spelled.as_str())) |
| 307 | + { |
| 308 | + Some(Scalar::Int { c: spelled.clone() }) |
| 309 | + } else { |
| 310 | + match spelled.as_str() { |
| 311 | + "float" | "double" => Some(Scalar::Float { c: spelled.clone() }), |
| 312 | + "bool" | "_Bool" => Some(Scalar::Bool), |
| 313 | + _ => None, |
| 314 | + } |
| 315 | + }; |
| 316 | + match (scalar, spelled.as_str(), pointers) { |
| 317 | + (Some(s), _, 0) => Ok(Kind::Scalar(s)), |
| 318 | + (_, "void", 0) => Ok(Kind::Void), |
| 319 | + (_, "void", 1) => Ok(Kind::Env), |
| 320 | + (_, "char", 1) if is_const => Ok(Kind::CStr), |
| 321 | + (_, "char", 1) => { |
| 322 | + Err("`char *`, which C may write to (only `const char *` is supported)".into()) |
| 323 | + } |
| 324 | + _ if words[0] == "enum" => Err(format!("the enum `{spelled}`")), |
| 325 | + _ if words.iter().any(|w| !self.known_word(w)) => Err(format!( |
| 326 | + "unknown type `{spelled}` (macros are not expanded)" |
| 327 | + )), |
| 328 | + _ => Err(format!("unsupported type `{shown}`")), |
| 329 | + } |
| 330 | + } |
| 331 | + |
| 332 | + /// A word that can be part of a type in this header. |
| 333 | + fn known_word(&self, w: &str) -> bool { |
| 334 | + INT_WORDS.contains(&w) |
| 335 | + || INT_TYPEDEFS.contains(&w) |
| 336 | + || [ |
| 337 | + "void", "float", "double", "bool", "_Bool", "struct", "union", |
| 338 | + ] |
| 339 | + .contains(&w) |
| 340 | + || self.typedefs.contains_key(w) |
| 341 | + || self.fn_typedefs.contains_key(w) |
| 342 | + || self.opaque.contains_key(w) |
| 343 | + || self.opaque_names.contains_key(w) |
| 344 | + || self.defined.contains(w) |
| 345 | + } |
| 346 | + |
| 347 | + fn callback(&self, sig: &Signature, shown: &str) -> Result<Kind, String> { |
| 348 | + let unsupported = |why: &str| Err(format!("the callback `{shown}` {why}")); |
| 349 | + if sig.variadic { |
| 350 | + return unsupported("is variadic"); |
| 351 | + } |
| 352 | + let mut params = Vec::new(); |
| 353 | + for p in &sig.params { |
| 354 | + params.push(match self.kind(&p.ty) { |
| 355 | + Ok(Kind::Scalar(s)) => Some(Arg::Scalar(s)), |
| 356 | + Ok(Kind::CStr) => Some(Arg::CStr), |
| 357 | + Ok(Kind::Env) => None, |
| 358 | + _ => return unsupported("takes a type bindings cannot pass it"), |
| 359 | + }); |
| 360 | + } |
| 361 | + if params.iter().filter(|p| p.is_none()).count() != 1 { |
| 362 | + return unsupported("needs exactly one `void *` parameter, its environment"); |
| 363 | + } |
| 364 | + let ret = match self.kind(&sig.ret) { |
| 365 | + Ok(Kind::Void) => None, |
| 366 | + Ok(Kind::Scalar(s)) => Some(s), |
| 367 | + _ => return unsupported("returns a type bindings cannot convert"), |
| 368 | + }; |
| 369 | + Ok(Kind::Callback(Box::new(Callback { |
| 370 | + params, |
| 371 | + ret, |
| 372 | + shown: shown.to_owned(), |
| 373 | + }))) |
| 374 | + } |
| 375 | + |
| 376 | + /// Bind one function, or say why not. |
| 377 | + fn function(&mut self, name: &str, sig: &Signature) -> Result<(), String> { |
| 378 | + if !is_til_name(name) { |
| 379 | + return Err("its name is not a tilcayo function name".into()); |
| 380 | + } |
| 381 | + if sig.variadic { |
| 382 | + return Err("a variadic function".into()); |
| 383 | + } |
| 384 | + let kinds = sig |
| 385 | + .params |
| 386 | + .iter() |
| 387 | + .map(|p| self.kind(&p.ty)) |
| 388 | + .collect::<Result<Vec<_>, _>>()?; |
| 389 | + if kinds.contains(&Kind::Void) { |
| 390 | + return Err("a `void` parameter".into()); |
| 391 | + } |
| 392 | + let ret = match self.kind(&sig.ret)? { |
| 393 | + Kind::Opaque { c, til } => { |
| 394 | + if !CONSTRUCTOR_SUFFIXES.iter().any(|s| name.ends_with(s)) { |
| 395 | + return Err(format!( |
| 396 | + "returns a pointer it may still own: only functions named like constructors ({}) return a `Resource`", |
| 397 | + CONSTRUCTOR_SUFFIXES.join(", ") |
| 398 | + )); |
| 399 | + } |
| 400 | + let finalizer = self |
| 401 | + .opaque |
| 402 | + .values() |
| 403 | + .find(|o| o.til == til) |
| 404 | + .and_then(|o| o.finalizer.clone()); |
| 405 | + Result_::Opaque { c, til, finalizer } |
| 406 | + } |
| 407 | + Kind::Void => Result_::Void, |
| 408 | + Kind::Scalar(s) => Result_::Scalar(s), |
| 409 | + Kind::CStr => Result_::CStr, |
| 410 | + Kind::Env | Kind::Callback(_) => { |
| 411 | + return Err("returns a pointer bindings cannot convert".into()); |
| 412 | + } |
| 413 | + }; |
| 414 | + let callbacks = kinds |
| 415 | + .iter() |
| 416 | + .filter(|k| matches!(k, Kind::Callback(_))) |
| 417 | + .count(); |
| 418 | + let envs = kinds.iter().filter(|k| **k == Kind::Env).count(); |
| 419 | + match (callbacks, envs) { |
| 420 | + (0, 0) | (1, 1) => {} |
| 421 | + (0, _) => return Err("a `void *` parameter".into()), |
| 422 | + (1, _) => { |
| 423 | + return Err( |
| 424 | + "a callback needs exactly one `void *` parameter, its environment".into(), |
| 425 | + ); |
| 426 | + } |
| 427 | + _ => return Err("more than one callback".into()), |
| 428 | + } |
| 429 | + // Valid: emit it. |
| 430 | + if matches!(ret, Result_::Opaque { .. }) { |
| 431 | + self.uses_resource = true; |
| 432 | + } |
| 433 | + let mut f = Function::new(name, sig); |
| 434 | + let mut i = 0; |
| 435 | + while i < kinds.len() { |
| 436 | + let p = &sig.params[i]; |
| 437 | + match &kinds[i] { |
| 438 | + Kind::Scalar(s) => f.scalar_param(p, s), |
| 439 | + Kind::CStr => match (kinds.get(i + 1), sig.params.get(i + 1)) { |
| 440 | + (Some(Kind::Scalar(Scalar::Int { c })), Some(len)) if is_length(len) => { |
| 441 | + f.string_param(p, Some(c)); |
| 442 | + i += 1; |
| 443 | + } |
| 444 | + _ => f.string_param(p, None), |
| 445 | + }, |
| 446 | + Kind::Opaque { til, .. } => { |
| 447 | + self.uses_resource = true; |
| 448 | + f.param(p, &format!("Resource<{til}>"), "tl_resource_get({})"); |
| 449 | + } |
| 450 | + Kind::Env => f.c_args.push("&cb".into()), |
| 451 | + Kind::Callback(cb) => { |
| 452 | + let trampoline = self.trampoline(cb); |
| 453 | + f.callback_param(p, cb, &trampoline); |
| 454 | + } |
| 455 | + Kind::Void => unreachable!("rejected above"), |
| 456 | + } |
| 457 | + i += 1; |
| 458 | + } |
| 459 | + f.emit(&ret, &mut self.til, &mut self.c); |
| 460 | + Ok(()) |
| 461 | + } |
| 462 | + |
| 463 | + /// The trampoline for callbacks of this C signature. |
| 464 | + fn trampoline(&mut self, cb: &Callback) -> String { |
| 465 | + let ret_c = cb.ret.as_ref().map_or("void".to_owned(), scalar_c); |
| 466 | + let params: Vec<String> = cb |
| 467 | + .params |
| 468 | + .iter() |
| 469 | + .enumerate() |
| 470 | + .map(|(i, p)| match p { |
| 471 | + None => "void *env".to_owned(), |
| 472 | + Some(Arg::Scalar(s)) => format!("{} a{i}", scalar_c(s)), |
| 473 | + Some(Arg::CStr) => format!("const char *a{i}"), |
| 474 | + }) |
| 475 | + .collect(); |
| 476 | + let key = format!("{ret_c}({})", params.join(", ")); |
| 477 | + let next = self.trampolines.len(); |
| 478 | + let (index, _) = self.trampolines.entry(key).or_insert_with(|| { |
| 479 | + let name = format!("{PREFIX}trampoline_{next}"); |
| 480 | + let fail = if cb.ret.is_some() { "return 0;" } else { "return;" }; |
| 481 | + let mut c = String::new(); |
| 482 | + let _ = writeln!(c, "/* {} */", cb.shown); |
| 483 | + let _ = writeln!(c, "static {ret_c} {name}({}) {{", params.join(", ")); |
| 484 | + let _ = writeln!(c, " const tl_callback *cb = env;"); |
| 485 | + let _ = writeln!(c, " if (tl_callback_failed(cb)) {fail}"); |
| 486 | + let mut args = Vec::new(); |
| 487 | + for (i, p) in cb.params.iter().enumerate() { |
| 488 | + match p { |
| 489 | + None => {} |
| 490 | + Some(Arg::Scalar(Scalar::Int { .. })) => { |
| 491 | + let _ = writeln!( |
| 492 | + c, |
| 493 | + " if (!TILCAYO_INT_OK(a{i})) {{ tl_panic_str(cb->ctx, \"a callback argument is out of Int's range\"); {fail} }}" |
| 494 | + ); |
| 495 | + args.push(format!("tl_int((int64_t)a{i})")); |
| 496 | + } |
| 497 | + Some(Arg::Scalar(Scalar::Float { .. })) => { |
| 498 | + args.push(format!("tl_float_from(cb->ctx, (double)a{i})")); |
| 499 | + } |
| 500 | + Some(Arg::Scalar(Scalar::Bool)) => args.push(format!("tl_bool(a{i})")), |
| 501 | + Some(Arg::CStr) => { |
| 502 | + let _ = writeln!( |
| 503 | + c, |
| 504 | + " if (!a{i}) {{ tl_panic_str(cb->ctx, \"a callback argument is NULL\"); {fail} }}" |
| 505 | + ); |
| 506 | + args.push(format!("tl_string_cstr(cb->ctx, a{i})")); |
| 507 | + } |
| 508 | + } |
| 509 | + } |
| 510 | + let n = args.len(); |
| 511 | + if args.is_empty() { |
| 512 | + args.push("TL_UNIT".into()); |
| 513 | + } |
| 514 | + let _ = writeln!(c, " tl_value args[] = {{{}}};", args.join(", ")); |
| 515 | + let _ = writeln!(c, " tl_value r = tl_callback_call(cb, {n}, args);"); |
| 516 | + match &cb.ret { |
| 517 | + None => { |
| 518 | + let _ = writeln!(c, " tl_drop(cb->ctx, r);"); |
| 519 | + } |
| 520 | + Some(s) => { |
| 521 | + let _ = writeln!(c, " if (tl_callback_failed(cb)) {fail}"); |
| 522 | + match s { |
| 523 | + Scalar::Int { c: t } => { |
| 524 | + let _ = writeln!( |
| 525 | + c, |
| 526 | + " if (!TILCAYO_FITS({t}, tl_int_get(r))) {{ tl_panic_str(cb->ctx, \"a callback result is out of range for {t}\"); {fail} }}" |
| 527 | + ); |
| 528 | + let _ = writeln!(c, " return ({t})tl_int_get(r);"); |
| 529 | + } |
| 530 | + Scalar::Float { c: t } => { |
| 531 | + let _ = writeln!(c, " double x = tl_float_get(r);"); |
| 532 | + let _ = writeln!(c, " tl_drop(cb->ctx, r);"); |
| 533 | + let _ = writeln!(c, " return ({t})x;"); |
| 534 | + } |
| 535 | + Scalar::Bool => { |
| 536 | + let _ = writeln!(c, " return r == TL_TRUE;"); |
| 537 | + } |
| 538 | + } |
| 539 | + } |
| 540 | + } |
| 541 | + c.push_str("}\n\n"); |
| 542 | + (next, c) |
| 543 | + }); |
| 544 | + format!("{PREFIX}trampoline_{index}") |
| 545 | + } |
| 546 | + |
| 547 | + fn finish(mut self, include: &str) -> Bindings { |
| 548 | + // Opaque types without a finalizer leak their values. |
| 549 | + let leaky: Vec<(u32, String)> = self |
| 550 | + .opaque |
| 551 | + .iter() |
| 552 | + .filter(|(_, o)| o.finalizer.is_none()) |
| 553 | + .map(|(k, o)| (o.line, k.clone())) |
| 554 | + .collect(); |
| 555 | + for (line, name) in leaky { |
| 556 | + let til = self.opaque[&name].til.clone(); |
| 557 | + self.skip( |
| 558 | + line, |
| 559 | + &format!("struct {name}"), |
| 560 | + format!("no finalizer found: `{til}` resources are never freed"), |
| 561 | + ); |
| 562 | + } |
| 563 | + self.skipped.sort_by_key(|s| s.line); |
| 564 | + |
| 565 | + let mut til = String::new(); |
| 566 | + let _ = writeln!( |
| 567 | + til, |
| 568 | + "/// Bindings for `{include}`, generated by `tilc bindgen` with their C shim:" |
| 569 | + ); |
| 570 | + let _ = writeln!(til, "/// do not edit, regenerate."); |
| 571 | + if !self.skipped.is_empty() { |
| 572 | + let _ = writeln!(til, "///\n/// Not bound, or worth knowing:"); |
| 573 | + for s in &self.skipped { |
| 574 | + let _ = writeln!(til, "/// - line {}, `{}`: {}.", s.line, s.what, s.reason); |
| 575 | + } |
| 576 | + } |
| 577 | + til.push('\n'); |
| 578 | + if self.uses_resource { |
| 579 | + til.push_str("import std/ffi.{type Resource}\n\n"); |
| 580 | + } |
| 581 | + for (name, o) in &self.opaque { |
| 582 | + let _ = writeln!( |
| 583 | + til, |
| 584 | + "/// `struct {name}`, opaque.\npub type {} {{}}\n", |
| 585 | + o.til |
| 586 | + ); |
| 587 | + } |
| 588 | + til.push_str(&self.til); |
| 589 | + let til = til.trim_end().to_owned() + "\n"; |
| 590 | + |
| 591 | + let mut c = String::new(); |
| 592 | + let _ = writeln!( |
| 593 | + c, |
| 594 | + "/* The C shim of the bindings for {include}, generated by `tilc bindgen`:\n * do not edit, regenerate. */" |
| 595 | + ); |
| 596 | + c.push_str("#include <stdbool.h>\n#include <stdint.h>\n\n#include \"tilrt.h\"\n"); |
| 597 | + let _ = writeln!(c, "#include \"{include}\"\n"); |
| 598 | + c.push_str(CONVERSIONS); |
| 599 | + for o in self.opaque.values() { |
| 600 | + if let Some(f) = &o.finalizer { |
| 601 | + let _ = writeln!( |
| 602 | + c, |
| 603 | + "static void {PREFIX}finalize_{}(void *p) {{ {f}(p); }}\n", |
| 604 | + o.til |
| 605 | + ); |
| 606 | + } |
| 607 | + } |
| 608 | + let mut trampolines: Vec<&(usize, String)> = self.trampolines.values().collect(); |
| 609 | + trampolines.sort_by_key(|(i, _)| *i); |
| 610 | + for (_, code) in trampolines { |
| 611 | + c.push_str(code); |
| 612 | + } |
| 613 | + c.push_str(&self.c); |
| 614 | + Bindings { |
| 615 | + til, |
| 616 | + c: c.trim_end().to_owned() + "\n", |
| 617 | + skipped: self.skipped, |
| 618 | + } |
| 619 | + } |
| 620 | +} |
| 621 | + |
| 622 | +const CONVERSIONS: &str = r#"/* Int to the C integer type T and back: a value out of range panics. */ |
| 623 | +#define TILCAYO_FITS(T, x) ((int64_t)(T)(x) == (x) && ((T)(x) < 0) == ((x) < 0)) |
| 624 | +#define TILCAYO_INT_OK(x) \ |
| 625 | + ((x) >= 0 ? (uint64_t)(x) <= (uint64_t)TL_INT_MAX : (int64_t)(x) >= TL_INT_MIN) |
| 626 | + |
| 627 | +"#; |
| 628 | + |
| 629 | +/// A function's result. |
| 630 | +enum Result_ { |
| 631 | + Void, |
| 632 | + Scalar(Scalar), |
| 633 | + CStr, |
| 634 | + Opaque { |
| 635 | + c: String, |
| 636 | + til: String, |
| 637 | + finalizer: Option<String>, |
| 638 | + }, |
| 639 | +} |
| 640 | + |
| 641 | +/// One bound function, built parameter by parameter. |
| 642 | +struct Function<'s> { |
| 643 | + name: &'s str, |
| 644 | + sig: &'s Signature, |
| 645 | + /// tilcayo parameters: name and type. |
| 646 | + til_params: Vec<(String, String)>, |
| 647 | + /// Range checks before the call. |
| 648 | + checks: Vec<String>, |
| 649 | + /// The C call's arguments, in order. |
| 650 | + c_args: Vec<String>, |
| 651 | + /// The callback's tilcayo parameter (C name `p<i>`). |
| 652 | + callback: Option<String>, |
| 653 | +} |
| 654 | + |
| 655 | +impl<'s> Function<'s> { |
| 656 | + fn new(name: &'s str, sig: &'s Signature) -> Self { |
| 657 | + Function { |
| 658 | + name, |
| 659 | + sig, |
| 660 | + til_params: Vec::new(), |
| 661 | + checks: Vec::new(), |
| 662 | + c_args: Vec::new(), |
| 663 | + callback: None, |
| 664 | + } |
| 665 | + } |
| 666 | + |
| 667 | + /// The next tilcayo parameter, named after `p`; returns its C name. |
| 668 | + fn param(&mut self, p: &Param, ty: &str, arg: &str) -> String { |
| 669 | + let i = self.til_params.len(); |
| 670 | + let name = match &p.name { |
| 671 | + Some(n) if is_til_name(n) && !self.til_params.iter().any(|(m, _)| m == n) => n.clone(), |
| 672 | + _ => format!("a{i}"), |
| 673 | + }; |
| 674 | + self.til_params.push((name, ty.to_owned())); |
| 675 | + let c = format!("p{i}"); |
| 676 | + if !arg.is_empty() { |
| 677 | + self.c_args.push(arg.replace("{}", &c)); |
| 678 | + } |
| 679 | + c |
| 680 | + } |
| 681 | + |
| 682 | + fn til_name(&self, c: &str) -> &str { |
| 683 | + let i: usize = c[1..].parse().unwrap_or(0); |
| 684 | + &self.til_params[i].0 |
| 685 | + } |
| 686 | + |
| 687 | + fn scalar_param(&mut self, p: &Param, s: &Scalar) { |
| 688 | + match s { |
| 689 | + Scalar::Int { c: t } => { |
| 690 | + let c = self.param(p, "Int", &format!("({t})tl_int_get({{}})")); |
| 691 | + let check = format!( |
| 692 | + "if (!TILCAYO_FITS({t}, tl_int_get({c}))) return tl_panic_str(ctx, \"{}: `{}` is out of range for {t}\");", |
| 693 | + self.name, |
| 694 | + self.til_name(&c) |
| 695 | + ); |
| 696 | + self.checks.push(check); |
| 697 | + } |
| 698 | + Scalar::Float { c: t } => { |
| 699 | + self.param(p, "Float", &format!("({t})tl_float_get({{}})")); |
| 700 | + } |
| 701 | + Scalar::Bool => { |
| 702 | + self.param(p, "Bool", "({} == TL_TRUE)"); |
| 703 | + } |
| 704 | + } |
| 705 | + } |
| 706 | + |
| 707 | + /// `const char *`, with its length parameter (of type `len`) if any. |
| 708 | + fn string_param(&mut self, p: &Param, len: Option<&String>) { |
| 709 | + let c = self.param(p, "String", "tl_string_ptr({})"); |
| 710 | + if let Some(t) = len { |
| 711 | + self.c_args.push(format!("({t})tl_string_len({c})")); |
| 712 | + let check = format!( |
| 713 | + "if (!TILCAYO_FITS({t}, (int64_t)tl_string_len({c}))) return tl_panic_str(ctx, \"{}: `{}` is too long\");", |
| 714 | + self.name, |
| 715 | + self.til_name(&c) |
| 716 | + ); |
| 717 | + self.checks.push(check); |
| 718 | + } |
| 719 | + } |
| 720 | + |
| 721 | + fn callback_param(&mut self, p: &Param, cb: &Callback, trampoline: &str) { |
| 722 | + let params: Vec<&str> = cb |
| 723 | + .params |
| 724 | + .iter() |
| 725 | + .flatten() |
| 726 | + .map(|a| match a { |
| 727 | + Arg::Scalar(s) => til_scalar(s), |
| 728 | + Arg::CStr => "String", |
| 729 | + }) |
| 730 | + .collect(); |
| 731 | + let ret = cb.ret.as_ref().map_or("()", til_scalar); |
| 732 | + let ty = format!("fn({}) -> {ret} / <ffi>", params.join(", ")); |
| 733 | + let c = self.param(p, &ty, ""); |
| 734 | + self.c_args.push(trampoline.to_owned()); |
| 735 | + self.callback = Some(c); |
| 736 | + } |
| 737 | + |
| 738 | + fn emit(&self, ret: &Result_, til: &mut String, out: &mut String) { |
| 739 | + let prototype = shown_fn_named(self.sig, self.name); |
| 740 | + let til_ret = match ret { |
| 741 | + Result_::Void => "()".to_owned(), |
| 742 | + Result_::Scalar(s) => til_scalar(s).to_owned(), |
| 743 | + Result_::CStr => "String".to_owned(), |
| 744 | + Result_::Opaque { til, .. } => format!("Resource<{til}>"), |
| 745 | + }; |
| 746 | + let params: Vec<String> = self |
| 747 | + .til_params |
| 748 | + .iter() |
| 749 | + .map(|(n, t)| format!("{n}: {t}")) |
| 750 | + .collect(); |
| 751 | + let _ = writeln!(til, "/// C: `{prototype}`"); |
| 752 | + let _ = writeln!(til, "@extern(c, \"{PREFIX}{}\")", self.name); |
| 753 | + let _ = writeln!( |
| 754 | + til, |
| 755 | + "pub fn {}({}) -> {til_ret} / <ffi>\n", |
| 756 | + self.name, |
| 757 | + params.join(", ") |
| 758 | + ); |
| 759 | + |
| 760 | + let c_params: String = (0..self.til_params.len()) |
| 761 | + .map(|i| format!(", tl_value p{i}")) |
| 762 | + .collect(); |
| 763 | + let _ = writeln!(out, "/* {prototype} */"); |
| 764 | + let _ = writeln!( |
| 765 | + out, |
| 766 | + "tl_value {PREFIX}{}(tl_ctx *ctx{c_params}) {{", |
| 767 | + self.name |
| 768 | + ); |
| 769 | + // `ctx` is unused only by functions that cannot fail. |
| 770 | + let uses_ctx = !self.checks.is_empty() |
| 771 | + || self.callback.is_some() |
| 772 | + || !matches!(ret, Result_::Void | Result_::Scalar(Scalar::Bool)); |
| 773 | + if !uses_ctx { |
| 774 | + let _ = writeln!(out, " (void)ctx;"); |
| 775 | + } |
| 776 | + for check in &self.checks { |
| 777 | + let _ = writeln!(out, " {check}"); |
| 778 | + } |
| 779 | + if let Some(f) = &self.callback { |
| 780 | + let _ = writeln!( |
| 781 | + out, |
| 782 | + " tl_callback cb;\n tl_callback_begin(ctx, &cb, {f});" |
| 783 | + ); |
| 784 | + } |
| 785 | + let call = format!("{}({})", self.name, self.c_args.join(", ")); |
| 786 | + let declared = match ret { |
| 787 | + Result_::Void => format!("{call};"), |
| 788 | + Result_::Scalar(s) => format!("{} r = {call};", scalar_c(s)), |
| 789 | + Result_::CStr => format!("const char *r = {call};"), |
| 790 | + Result_::Opaque { c, .. } => format!("{c}r = {call};"), |
| 791 | + }; |
| 792 | + let _ = writeln!(out, " {declared}"); |
| 793 | + if self.callback.is_some() && matches!(ret, Result_::Void) { |
| 794 | + let _ = writeln!(out, " return tl_callback_end(&cb, TL_UNIT);\n}}\n"); |
| 795 | + return; |
| 796 | + } |
| 797 | + if self.callback.is_some() { |
| 798 | + // A callback panicked: the caller unwinds, the result is unused. |
| 799 | + let release = match ret { |
| 800 | + Result_::Opaque { |
| 801 | + finalizer: Some(f), .. |
| 802 | + } => format!("if (r) {f}(r); "), |
| 803 | + _ => String::new(), |
| 804 | + }; |
| 805 | + let _ = writeln!(out, " tl_callback_end(&cb, TL_UNIT);"); |
| 806 | + let _ = writeln!( |
| 807 | + out, |
| 808 | + " if (tl_callback_failed(&cb)) {{ {release}return TL_UNIT; }}" |
| 809 | + ); |
| 810 | + } |
| 811 | + let name = self.name; |
| 812 | + match ret { |
| 813 | + Result_::Void => { |
| 814 | + let _ = writeln!(out, " return TL_UNIT;"); |
| 815 | + } |
| 816 | + Result_::Scalar(Scalar::Int { .. }) => { |
| 817 | + let _ = writeln!( |
| 818 | + out, |
| 819 | + " if (!TILCAYO_INT_OK(r)) return tl_panic_str(ctx, \"{name}: the result is out of Int's range\");\n return tl_int((int64_t)r);" |
| 820 | + ); |
| 821 | + } |
| 822 | + Result_::Scalar(Scalar::Float { .. }) => { |
| 823 | + let _ = writeln!(out, " return tl_float_from(ctx, (double)r);"); |
| 824 | + } |
| 825 | + Result_::Scalar(Scalar::Bool) => { |
| 826 | + let _ = writeln!(out, " return tl_bool(r);"); |
| 827 | + } |
| 828 | + Result_::CStr => { |
| 829 | + let _ = writeln!( |
| 830 | + out, |
| 831 | + " if (!r) return tl_panic_str(ctx, \"{name} returned NULL\");\n return tl_string_cstr(ctx, r);" |
| 832 | + ); |
| 833 | + } |
| 834 | + Result_::Opaque { til, finalizer, .. } => { |
| 835 | + let fin = finalizer |
| 836 | + .as_ref() |
| 837 | + .map_or("NULL".to_owned(), |_| format!("{PREFIX}finalize_{til}")); |
| 838 | + let _ = writeln!( |
| 839 | + out, |
| 840 | + " if (!r) return tl_panic_str(ctx, \"{name} returned NULL\");\n return tl_resource_new(ctx, (void *)r, {fin}, false);" |
| 841 | + ); |
| 842 | + } |
| 843 | + } |
| 844 | + out.push_str("}\n\n"); |
| 845 | + } |
| 846 | +} |
| 847 | + |
| 848 | +fn scalar_c(s: &Scalar) -> String { |
| 849 | + match s { |
| 850 | + Scalar::Int { c } | Scalar::Float { c } => c.clone(), |
| 851 | + Scalar::Bool => "bool".into(), |
| 852 | + } |
| 853 | +} |
| 854 | + |
| 855 | +fn til_scalar(s: &Scalar) -> &'static str { |
| 856 | + match s { |
| 857 | + Scalar::Int { .. } => "Int", |
| 858 | + Scalar::Float { .. } => "Float", |
| 859 | + Scalar::Bool => "Bool", |
| 860 | + } |
| 861 | +} |
| 862 | + |
| 863 | +/// Whether `p` names the length of the string before it. |
| 864 | +fn is_length(p: &Param) -> bool { |
| 865 | + p.name.as_deref().is_some_and(|n| { |
| 866 | + let n = n.to_ascii_lowercase(); |
| 867 | + n == "n" || n.ends_with("len") || n.ends_with("length") || n.ends_with("size") |
| 868 | + }) |
| 869 | +} |
| 870 | + |
| 871 | +/// A lowercase identifier that is not a keyword. |
| 872 | +fn is_til_name(name: &str) -> bool { |
| 873 | + name.chars() |
| 874 | + .next() |
| 875 | + .is_some_and(|c| c.is_ascii_lowercase() || c == '_') |
| 876 | + && name |
| 877 | + .chars() |
| 878 | + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') |
| 879 | + && tilc_syntax::SyntaxKind::keyword(name).is_none() |
| 880 | +} |
| 881 | + |
| 882 | +/// `sk_vec` and `sk_vec_t` become `SkVec`. |
| 883 | +fn type_name(c: &str) -> String { |
| 884 | + c.trim_end_matches("_t") |
| 885 | + .split('_') |
| 886 | + .filter(|p| !p.is_empty()) |
| 887 | + .map(|p| { |
| 888 | + let mut cs = p.chars(); |
| 889 | + cs.next() |
| 890 | + .map(|f| f.to_ascii_uppercase().to_string() + cs.as_str()) |
| 891 | + .unwrap_or_default() |
| 892 | + }) |
| 893 | + .collect() |
| 894 | +} |
| 895 | + |
| 896 | +fn shown_type(ty: &TypeSyntax) -> String { |
| 897 | + match ty { |
| 898 | + TypeSyntax::Plain { |
| 899 | + words, |
| 900 | + is_const, |
| 901 | + pointers, |
| 902 | + } => format!( |
| 903 | + "{}{}{}{}", |
| 904 | + if *is_const { "const " } else { "" }, |
| 905 | + words.join(" "), |
| 906 | + if *pointers > 0 { " " } else { "" }, |
| 907 | + "*".repeat(*pointers) |
| 908 | + ), |
| 909 | + TypeSyntax::FnPointer(sig) => shown_fn(sig), |
| 910 | + TypeSyntax::Unsupported(text) => text.clone(), |
| 911 | + } |
| 912 | +} |
| 913 | + |
| 914 | +fn shown_params(sig: &Signature) -> String { |
| 915 | + let mut params: Vec<String> = sig |
| 916 | + .params |
| 917 | + .iter() |
| 918 | + .map(|p| match (&p.ty, &p.name) { |
| 919 | + (TypeSyntax::FnPointer(sig), Some(n)) => { |
| 920 | + format!("{} (*{n})({})", shown_type(&sig.ret), shown_params(sig)) |
| 921 | + } |
| 922 | + (ty, Some(n)) => { |
| 923 | + let ty = shown_type(ty); |
| 924 | + let sep = if ty.ends_with('*') { "" } else { " " }; |
| 925 | + format!("{ty}{sep}{n}") |
| 926 | + } |
| 927 | + (ty, None) => shown_type(ty), |
| 928 | + }) |
| 929 | + .collect(); |
| 930 | + if sig.variadic { |
| 931 | + params.push("...".into()); |
| 932 | + } |
| 933 | + if params.is_empty() { |
| 934 | + "void".into() |
| 935 | + } else { |
| 936 | + params.join(", ") |
| 937 | + } |
| 938 | +} |
| 939 | + |
| 940 | +/// `int (*)(int64_t, void *)` |
| 941 | +fn shown_fn(sig: &Signature) -> String { |
| 942 | + format!("{} (*)({})", shown_type(&sig.ret), shown_params(sig)) |
| 943 | +} |
| 944 | + |
| 945 | +/// `size_t sk_vec_len(const sk_vec *v)` |
| 946 | +fn shown_fn_named(sig: &Signature, name: &str) -> String { |
| 947 | + let ret = shown_type(&sig.ret); |
| 948 | + let sep = if ret.ends_with('*') { "" } else { " " }; |
| 949 | + format!("{ret}{sep}{name}({})", shown_params(sig)) |
| 950 | +} |
| 951 | + |
| 952 | +#[cfg(test)] |
| 953 | +mod tests { |
| 954 | + use super::*; |
| 955 | + |
| 956 | + #[test] |
| 957 | + fn names() { |
| 958 | + assert_eq!(type_name("sk_vec"), "SkVec"); |
| 959 | + assert_eq!(type_name("sk_vec_t"), "SkVec"); |
| 960 | + assert!(is_til_name("sk_vec_new")); |
| 961 | + assert!(!is_til_name("SDL_Init")); |
| 962 | + assert!(!is_til_name("match")); |
| 963 | + } |
| 964 | +} |