tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

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