//! From parsed declarations to the Louise module and its C shim. use std::collections::{BTreeMap, HashMap, HashSet}; use std::fmt::Write; use crate::parse::{self, Item, Param, Signature, TypeSyntax}; /// The generated files, and what was left out. #[derive(Debug)] pub struct Bindings { /// The Louise module: `@extern` declarations and opaque types. pub louise: String, /// The C shim the declarations call. pub c: String, pub skipped: Vec, } /// A declaration that was not bound, or a remark about one. #[derive(Clone, Debug, PartialEq)] pub struct Skipped { pub line: u32, /// The C name, or the declaration as written. pub what: String, pub reason: String, } /// Bindings for `header` (its text), which the shim includes as /// `#include ""`. pub fn generate(header: &str, include: &str) -> Bindings { let items = parse::parse(header); let mut g = Generator::new(&items); for located in &items { g.item(located.line, &located.item); } g.finish(include) } /// Shim functions and trampolines are prefixed so they cannot collide with /// the library's names, nor with the runtime's (`tl_`). const PREFIX: &str = "louise_"; const CONSTRUCTOR_SUFFIXES: &[&str] = &["_new", "_create", "_open", "_copy", "_clone"]; const FINALIZER_SUFFIXES: &[&str] = &["_free", "_destroy", "_delete", "_release"]; const INT_WORDS: &[&str] = &["signed", "unsigned", "short", "long", "int", "char"]; const INT_TYPEDEFS: &[&str] = &[ "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t", "size_t", "ssize_t", "ptrdiff_t", "intptr_t", "uintptr_t", "intmax_t", "uintmax_t", ]; /// A value C and Louise exchange directly. `c` is its C spelling. #[derive(Clone, Debug, PartialEq)] enum Scalar { Int { c: String }, Float { c: String }, Bool, } /// What a C type means for a binding. #[derive(Clone, Debug, PartialEq)] enum Kind { Void, Scalar(Scalar), /// `const char *`. CStr, /// `void *`: a callback's environment. Env, /// A pointer to an opaque struct; `louise` is the Louise type's name. Opaque { c: String, louise: String, }, Callback(Box), } #[derive(Clone, Debug, PartialEq)] struct Callback { /// C parameter types (the environment is `None`). params: Vec>, ret: Option, /// The function pointer type, for comments. shown: String, } /// A callback's argument. #[derive(Clone, Debug, PartialEq)] enum Arg { Scalar(Scalar), CStr, } struct OpaqueType { louise: String, line: u32, finalizer: Option, } struct Generator<'a> { /// Struct names and typedef names of opaque structs, to their key in /// `opaque` (the struct's name). opaque_names: HashMap, opaque: BTreeMap, /// Structs with fields (struct names and aliases). defined: HashSet, typedefs: HashMap, fn_typedefs: HashMap, /// Functions used as finalizers. finalizers: HashSet, louise: String, c: String, /// Trampolines by C signature: their index and code. trampolines: BTreeMap, uses_resource: bool, skipped: Vec, } impl<'a> Generator<'a> { fn new(items: &'a [parse::Located]) -> Self { let mut g = Generator { opaque_names: HashMap::new(), opaque: BTreeMap::new(), defined: HashSet::new(), typedefs: HashMap::new(), fn_typedefs: HashMap::new(), finalizers: HashSet::new(), louise: String::new(), c: String::new(), trampolines: BTreeMap::new(), uses_resource: false, skipped: Vec::new(), }; // Types first, so declarations may use them in any order. for l in items { match &l.item { Item::StructDef { name, alias } => { g.defined.extend(name.iter().chain(alias).cloned()); } Item::Typedef { name, ty } => { g.typedefs.insert(name.clone(), ty); } Item::FnTypedef { name, sig } => { g.fn_typedefs.insert(name.clone(), sig); } _ => {} } } for l in items { if let Item::StructDecl { name, alias } = &l.item && !g.defined.contains(name) { g.opaque_names .insert(format!("struct {name}"), name.clone()); if let Some(a) = alias { g.opaque_names.insert(a.clone(), name.clone()); } g.opaque.entry(name.clone()).or_insert(OpaqueType { louise: type_name(name), line: l.line, finalizer: None, }); } } g.find_finalizers(items); g } /// Each opaque type's finalizer: the one `void f(T *)` named like one. fn find_finalizers(&mut self, items: &[parse::Located]) { let mut found: BTreeMap> = BTreeMap::new(); for l in items { let Item::Function { name, sig } = &l.item else { continue; }; if !FINALIZER_SUFFIXES.iter().any(|s| name.ends_with(s)) || sig.params.len() != 1 || self.kind(&sig.ret) != Ok(Kind::Void) { continue; } if let Ok(Kind::Opaque { louise, .. }) = self.kind(&sig.params[0].ty) && let Some(key) = self .opaque .iter() .find(|(_, o)| o.louise == louise) .map(|(k, _)| k) { found.entry(key.clone()).or_default().push(name.clone()); } } for (key, fns) in found { if let [f] = fns.as_slice() { self.finalizers.insert(f.clone()); if let Some(o) = self.opaque.get_mut(&key) { o.finalizer = Some(f.clone()); } } } } fn skip(&mut self, line: u32, what: &str, reason: impl Into) { self.skipped.push(Skipped { line, what: what.to_owned(), reason: reason.into(), }); } fn item(&mut self, line: u32, item: &Item) { match item { Item::Function { name, sig } => { if self.finalizers.contains(name) { let louise = self .opaque .values() .find(|o| o.finalizer.as_ref() == Some(name)) .map(|o| o.louise.clone()) .unwrap_or_default(); self.skip( line, name, format!("the finalizer of `{louise}`, not bound"), ); } else if let Err(reason) = self.function(name, sig) { self.skip(line, name, reason); } } Item::StructDef { name, alias } => { let shown = name .as_ref() .or(alias.as_ref()) .cloned() .unwrap_or_default(); self.skip(line, &format!("struct {shown}"), "a struct with fields"); } Item::Other(text) => self.skip(line, text, "not a supported declaration"), Item::StructDecl { .. } | Item::FnTypedef { .. } | Item::Typedef { .. } => {} } } /// What `ty` means for a binding, or why it is not supported. fn kind(&self, ty: &TypeSyntax) -> Result { let (words, is_const, pointers) = match ty { TypeSyntax::Plain { words, is_const, pointers, } => (words, *is_const, *pointers), TypeSyntax::FnPointer(sig) => return self.callback(sig, &shown_fn(sig)), TypeSyntax::Unsupported(text) => return Err(format!("unsupported type `{text}`")), }; let spelled = words.join(" "); let shown = format!( "{}{spelled}{}{}", if is_const { "const " } else { "" }, if pointers > 0 { " " } else { "" }, "*".repeat(pointers) ); if let [one] = words.as_slice() { if let Some(target) = self.typedefs.get(one) { // A typedef of a scalar keeps its own name in C. return match (self.kind(target)?, pointers) { (Kind::Scalar(Scalar::Int { .. }), 0) => { Ok(Kind::Scalar(Scalar::Int { c: spelled })) } (Kind::Scalar(Scalar::Float { .. }), 0) => { Ok(Kind::Scalar(Scalar::Float { c: spelled })) } (Kind::Scalar(Scalar::Bool), 0) => Ok(Kind::Scalar(Scalar::Bool)), _ => Err(format!("unsupported type `{shown}`")), }; } if let Some(sig) = self.fn_typedefs.get(one) { return match pointers { 0 => self.callback(sig, one), _ => Err(format!("a pointer to the function pointer `{one}`")), }; } } if let Some(key) = self.opaque_names.get(&spelled) { return match pointers { 1 => Ok(Kind::Opaque { c: format!("{}{spelled} *", if is_const { "const " } else { "" }), louise: self.opaque[key].louise.clone(), }), 0 => Err(format!("the struct `{spelled}` by value")), _ => Err(format!("unsupported type `{shown}`")), }; } let struct_name = words.get(1).filter(|_| words[0] == "struct"); if self.defined.contains(&spelled) || struct_name.is_some_and(|n| self.defined.contains(n)) { return Err(format!( "`{shown}`: only pointers to opaque structs are supported" )); } let scalar = if words.iter().all(|w| INT_WORDS.contains(&w.as_str())) || (words.len() == 1 && INT_TYPEDEFS.contains(&spelled.as_str())) { Some(Scalar::Int { c: spelled.clone() }) } else { match spelled.as_str() { "float" | "double" => Some(Scalar::Float { c: spelled.clone() }), "bool" | "_Bool" => Some(Scalar::Bool), _ => None, } }; match (scalar, spelled.as_str(), pointers) { (Some(s), _, 0) => Ok(Kind::Scalar(s)), (_, "void", 0) => Ok(Kind::Void), (_, "void", 1) => Ok(Kind::Env), (_, "char", 1) if is_const => Ok(Kind::CStr), (_, "char", 1) => { Err("`char *`, which C may write to (only `const char *` is supported)".into()) } _ if words[0] == "enum" => Err(format!("the enum `{spelled}`")), _ if words.iter().any(|w| !self.known_word(w)) => Err(format!( "unknown type `{spelled}` (macros are not expanded)" )), _ => Err(format!("unsupported type `{shown}`")), } } /// A word that can be part of a type in this header. fn known_word(&self, w: &str) -> bool { INT_WORDS.contains(&w) || INT_TYPEDEFS.contains(&w) || [ "void", "float", "double", "bool", "_Bool", "struct", "union", ] .contains(&w) || self.typedefs.contains_key(w) || self.fn_typedefs.contains_key(w) || self.opaque.contains_key(w) || self.opaque_names.contains_key(w) || self.defined.contains(w) } fn callback(&self, sig: &Signature, shown: &str) -> Result { let unsupported = |why: &str| Err(format!("the callback `{shown}` {why}")); if sig.variadic { return unsupported("is variadic"); } let mut params = Vec::new(); for p in &sig.params { params.push(match self.kind(&p.ty) { Ok(Kind::Scalar(s)) => Some(Arg::Scalar(s)), Ok(Kind::CStr) => Some(Arg::CStr), Ok(Kind::Env) => None, _ => return unsupported("takes a type bindings cannot pass it"), }); } if params.iter().filter(|p| p.is_none()).count() != 1 { return unsupported("needs exactly one `void *` parameter, its environment"); } let ret = match self.kind(&sig.ret) { Ok(Kind::Void) => None, Ok(Kind::Scalar(s)) => Some(s), _ => return unsupported("returns a type bindings cannot convert"), }; Ok(Kind::Callback(Box::new(Callback { params, ret, shown: shown.to_owned(), }))) } /// Bind one function, or say why not. fn function(&mut self, name: &str, sig: &Signature) -> Result<(), String> { if !is_til_name(name) { return Err("its name is not a Louise function name".into()); } if sig.variadic { return Err("a variadic function".into()); } let kinds = sig .params .iter() .map(|p| self.kind(&p.ty)) .collect::, _>>()?; if kinds.contains(&Kind::Void) { return Err("a `void` parameter".into()); } let ret = match self.kind(&sig.ret)? { Kind::Opaque { c, louise } => { if !CONSTRUCTOR_SUFFIXES.iter().any(|s| name.ends_with(s)) { return Err(format!( "returns a pointer it may still own: only functions named like constructors ({}) return a `Resource`", CONSTRUCTOR_SUFFIXES.join(", ") )); } let finalizer = self .opaque .values() .find(|o| o.louise == louise) .and_then(|o| o.finalizer.clone()); Result_::Opaque { c, louise, finalizer, } } Kind::Void => Result_::Void, Kind::Scalar(s) => Result_::Scalar(s), Kind::CStr => Result_::CStr, Kind::Env | Kind::Callback(_) => { return Err("returns a pointer bindings cannot convert".into()); } }; let callbacks = kinds .iter() .filter(|k| matches!(k, Kind::Callback(_))) .count(); let envs = kinds.iter().filter(|k| **k == Kind::Env).count(); match (callbacks, envs) { (0, 0) | (1, 1) => {} (0, _) => return Err("a `void *` parameter".into()), (1, _) => { return Err( "a callback needs exactly one `void *` parameter, its environment".into(), ); } _ => return Err("more than one callback".into()), } // Valid: emit it. if matches!(ret, Result_::Opaque { .. }) { self.uses_resource = true; } let mut f = Function::new(name, sig); let mut i = 0; while i < kinds.len() { let p = &sig.params[i]; match &kinds[i] { Kind::Scalar(s) => f.scalar_param(p, s), Kind::CStr => match (kinds.get(i + 1), sig.params.get(i + 1)) { (Some(Kind::Scalar(Scalar::Int { c })), Some(len)) if is_length(len) => { f.string_param(p, Some(c)); i += 1; } _ => f.string_param(p, None), }, Kind::Opaque { louise, .. } => { self.uses_resource = true; f.param(p, &format!("Resource<{louise}>"), "tl_resource_get({})"); } Kind::Env => f.c_args.push("&cb".into()), Kind::Callback(cb) => { let trampoline = self.trampoline(cb); f.callback_param(p, cb, &trampoline); } Kind::Void => unreachable!("rejected above"), } i += 1; } f.emit(&ret, &mut self.louise, &mut self.c); Ok(()) } /// The trampoline for callbacks of this C signature. fn trampoline(&mut self, cb: &Callback) -> String { let ret_c = cb.ret.as_ref().map_or("void".to_owned(), scalar_c); let params: Vec = cb .params .iter() .enumerate() .map(|(i, p)| match p { None => "void *env".to_owned(), Some(Arg::Scalar(s)) => format!("{} a{i}", scalar_c(s)), Some(Arg::CStr) => format!("const char *a{i}"), }) .collect(); let key = format!("{ret_c}({})", params.join(", ")); let next = self.trampolines.len(); let (index, _) = self.trampolines.entry(key).or_insert_with(|| { let name = format!("{PREFIX}trampoline_{next}"); let fail = if cb.ret.is_some() { "return 0;" } else { "return;" }; let mut c = String::new(); let _ = writeln!(c, "/* {} */", cb.shown); let _ = writeln!(c, "static {ret_c} {name}({}) {{", params.join(", ")); let _ = writeln!(c, " const tl_callback *cb = env;"); let _ = writeln!(c, " if (tl_callback_failed(cb)) {fail}"); let mut args = Vec::new(); for (i, p) in cb.params.iter().enumerate() { match p { None => {} Some(Arg::Scalar(Scalar::Int { .. })) => { let _ = writeln!( c, " if (!LOUISE_I64_OK(a{i})) {{ tl_panic_str(cb->ctx, \"a callback argument is out of Int's range\"); {fail} }}" ); args.push(format!("tl_int_from_i64(cb->ctx, (int64_t)a{i})")); } Some(Arg::Scalar(Scalar::Float { .. })) => { args.push(format!("tl_float_from(cb->ctx, (double)a{i})")); } Some(Arg::Scalar(Scalar::Bool)) => args.push(format!("tl_bool(a{i})")), Some(Arg::CStr) => { let _ = writeln!( c, " if (!a{i}) {{ tl_panic_str(cb->ctx, \"a callback argument is NULL\"); {fail} }}" ); args.push(format!("tl_string_cstr(cb->ctx, a{i})")); } } } let n = args.len(); if args.is_empty() { args.push("TL_UNIT".into()); } let _ = writeln!(c, " tl_value args[] = {{{}}};", args.join(", ")); let _ = writeln!(c, " tl_value r = tl_callback_call(cb, {n}, args);"); match &cb.ret { None => { let _ = writeln!(c, " tl_drop(cb->ctx, r);"); } Some(s) => { let _ = writeln!(c, " if (tl_callback_failed(cb)) {fail}"); match s { Scalar::Int { c: t } => { let _ = writeln!(c, " int64_t x;"); let _ = writeln!(c, " bool fits = tl_int_to_i64(r, &x) && LOUISE_FITS({t}, x);"); let _ = writeln!(c, " tl_drop(cb->ctx, r);"); let _ = writeln!( c, " if (!fits) {{ tl_panic_str(cb->ctx, \"a callback result is out of range for {t}\"); {fail} }}" ); let _ = writeln!(c, " return ({t})x;"); } Scalar::Float { c: t } => { let _ = writeln!(c, " double x = tl_float_get(r);"); let _ = writeln!(c, " tl_drop(cb->ctx, r);"); let _ = writeln!(c, " return ({t})x;"); } Scalar::Bool => { let _ = writeln!(c, " return r == TL_TRUE;"); } } } } c.push_str("}\n\n"); (next, c) }); format!("{PREFIX}trampoline_{index}") } fn finish(mut self, include: &str) -> Bindings { // Opaque types without a finalizer leak their values. let leaky: Vec<(u32, String)> = self .opaque .iter() .filter(|(_, o)| o.finalizer.is_none()) .map(|(k, o)| (o.line, k.clone())) .collect(); for (line, name) in leaky { let louise = self.opaque[&name].louise.clone(); self.skip( line, &format!("struct {name}"), format!("no finalizer found: `{louise}` resources are never freed"), ); } self.skipped.sort_by_key(|s| s.line); let mut louise = String::new(); let _ = writeln!( louise, "/// Bindings for `{include}`, generated by `louise bindgen` with their C shim:" ); let _ = writeln!(louise, "/// do not edit, regenerate."); if !self.skipped.is_empty() { let _ = writeln!(louise, "///\n/// Not bound, or worth knowing:"); for s in &self.skipped { let _ = writeln!(louise, "/// - line {}, `{}`: {}.", s.line, s.what, s.reason); } } louise.push('\n'); if self.uses_resource { louise.push_str("import std/ffi.{type Resource}\n\n"); } for (name, o) in &self.opaque { let _ = writeln!( louise, "/// `struct {name}`, opaque.\npub type {}\n", o.louise ); } louise.push_str(&self.louise); let louise = louise.trim_end().to_owned() + "\n"; // Generated code is formatted like everything else; if it somehow // does not parse, keep it as written rather than fail. let louise = louise_syntax::format::format(&louise).unwrap_or(louise); let mut c = String::new(); let _ = writeln!( c, "/* The C shim of the bindings for {include}, generated by `louise bindgen`:\n * do not edit, regenerate. */" ); c.push_str("#include \n#include \n\n#include \"louise_rt.h\"\n"); let _ = writeln!(c, "#include \"{include}\"\n"); c.push_str(CONVERSIONS); for o in self.opaque.values() { if let Some(f) = &o.finalizer { let _ = writeln!( c, "static void {PREFIX}finalize_{}(void *p) {{ {f}(p); }}\n", o.louise ); } } let mut trampolines: Vec<&(usize, String)> = self.trampolines.values().collect(); trampolines.sort_by_key(|(i, _)| *i); for (_, code) in trampolines { c.push_str(code); } c.push_str(&self.c); Bindings { louise, c: c.trim_end().to_owned() + "\n", skipped: self.skipped, } } } const CONVERSIONS: &str = r#"/* Int to the C integer type T and back: a value out of range panics. An * Int may be big (ADR 0014): it is read with tl_int_to_i64 and made with * tl_int_from_i64. */ #define LOUISE_FITS(T, x) ((int64_t)(T)(x) == (x) && ((T)(x) < 0) == ((x) < 0)) #define LOUISE_I64_OK(x) ((x) < 0 || (uint64_t)(x) <= (uint64_t)INT64_MAX) "#; /// A function's result. enum Result_ { Void, Scalar(Scalar), CStr, Opaque { c: String, louise: String, finalizer: Option, }, } /// One bound function, built parameter by parameter. struct Function<'s> { name: &'s str, sig: &'s Signature, /// Louise parameters: name and type. til_params: Vec<(String, String)>, /// Range checks before the call. checks: Vec, /// The C call's arguments, in order. c_args: Vec, /// The callback's Louise parameter (C name `p`). callback: Option, } impl<'s> Function<'s> { fn new(name: &'s str, sig: &'s Signature) -> Self { Function { name, sig, til_params: Vec::new(), checks: Vec::new(), c_args: Vec::new(), callback: None, } } /// The next Louise parameter, named after `p`; returns its C name. fn param(&mut self, p: &Param, ty: &str, arg: &str) -> String { let i = self.til_params.len(); let name = match &p.name { Some(n) if is_til_name(n) && !self.til_params.iter().any(|(m, _)| m == n) => n.clone(), _ => format!("a{i}"), }; self.til_params.push((name, ty.to_owned())); let c = format!("p{i}"); if !arg.is_empty() { self.c_args.push(arg.replace("{}", &c)); } c } fn til_name(&self, c: &str) -> &str { let i: usize = c[1..].parse().unwrap_or(0); &self.til_params[i].0 } fn scalar_param(&mut self, p: &Param, s: &Scalar) { match s { Scalar::Int { c: t } => { let c = self.param(p, "Int", &format!("({t})v{{}}")); let check = format!( "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}\");", self.name, self.til_name(&c) ); self.checks.push(check); } Scalar::Float { c: t } => { self.param(p, "Float", &format!("({t})tl_float_get({{}})")); } Scalar::Bool => { self.param(p, "Bool", "({} == TL_TRUE)"); } } } /// `const char *`, with its length parameter (of type `len`) if any. fn string_param(&mut self, p: &Param, len: Option<&String>) { let c = self.param(p, "String", "tl_string_ptr({})"); if let Some(t) = len { self.c_args.push(format!("({t})tl_string_len({c})")); let check = format!( "if (!LOUISE_FITS({t}, (int64_t)tl_string_len({c}))) return tl_panic_str(ctx, \"{}: `{}` is too long\");", self.name, self.til_name(&c) ); self.checks.push(check); } } fn callback_param(&mut self, p: &Param, cb: &Callback, trampoline: &str) { let params: Vec<&str> = cb .params .iter() .flatten() .map(|a| match a { Arg::Scalar(s) => til_scalar(s), Arg::CStr => "String", }) .collect(); let ret = cb.ret.as_ref().map_or("()", til_scalar); let ty = format!("fn({}) -> {ret} / ", params.join(", ")); let c = self.param(p, &ty, ""); self.c_args.push(trampoline.to_owned()); self.callback = Some(c); } fn emit(&self, ret: &Result_, louise: &mut String, out: &mut String) { let prototype = shown_fn_named(self.sig, self.name); let til_ret = match ret { Result_::Void => "()".to_owned(), Result_::Scalar(s) => til_scalar(s).to_owned(), Result_::CStr => "String".to_owned(), Result_::Opaque { louise, .. } => format!("Resource<{louise}>"), }; let params: Vec = self .til_params .iter() .map(|(n, t)| format!("{n}: {t}")) .collect(); let _ = writeln!(louise, "/// C: `{prototype}`"); let _ = writeln!(louise, "@extern c \"{PREFIX}{}\"", self.name); let _ = writeln!( louise, "pub fn {} ::{} -> {til_ret} / \n", self.name, params.iter().map(|p| format!(" {p}")).collect::(), ); let c_params: String = (0..self.til_params.len()) .map(|i| format!(", tl_value p{i}")) .collect(); let _ = writeln!(out, "/* {prototype} */"); let _ = writeln!( out, "tl_value {PREFIX}{}(tl_ctx *ctx{c_params}) {{", self.name ); // `ctx` is unused only by functions that cannot fail. let uses_ctx = !self.checks.is_empty() || self.callback.is_some() || !matches!(ret, Result_::Void | Result_::Scalar(Scalar::Bool)); if !uses_ctx { let _ = writeln!(out, " (void)ctx;"); } for check in &self.checks { let _ = writeln!(out, " {check}"); } if let Some(f) = &self.callback { let _ = writeln!( out, " tl_callback cb;\n tl_callback_begin(ctx, &cb, {f});" ); } let call = format!("{}({})", self.name, self.c_args.join(", ")); let declared = match ret { Result_::Void => format!("{call};"), Result_::Scalar(s) => format!("{} r = {call};", scalar_c(s)), Result_::CStr => format!("const char *r = {call};"), Result_::Opaque { c, .. } => format!("{c}r = {call};"), }; let _ = writeln!(out, " {declared}"); if self.callback.is_some() && matches!(ret, Result_::Void) { let _ = writeln!(out, " return tl_callback_end(&cb, TL_UNIT);\n}}\n"); return; } if self.callback.is_some() { // A callback panicked: the caller unwinds, the result is unused. let release = match ret { Result_::Opaque { finalizer: Some(f), .. } => format!("if (r) {f}(r); "), _ => String::new(), }; let _ = writeln!(out, " tl_callback_end(&cb, TL_UNIT);"); let _ = writeln!( out, " if (tl_callback_failed(&cb)) {{ {release}return TL_UNIT; }}" ); } let name = self.name; match ret { Result_::Void => { let _ = writeln!(out, " return TL_UNIT;"); } Result_::Scalar(Scalar::Int { .. }) => { let _ = writeln!( out, " 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);" ); } Result_::Scalar(Scalar::Float { .. }) => { let _ = writeln!(out, " return tl_float_from(ctx, (double)r);"); } Result_::Scalar(Scalar::Bool) => { let _ = writeln!(out, " return tl_bool(r);"); } Result_::CStr => { let _ = writeln!( out, " if (!r) return tl_panic_str(ctx, \"{name} returned NULL\");\n return tl_string_cstr(ctx, r);" ); } Result_::Opaque { louise, finalizer, .. } => { let fin = finalizer .as_ref() .map_or("NULL".to_owned(), |_| format!("{PREFIX}finalize_{louise}")); let _ = writeln!( out, " if (!r) return tl_panic_str(ctx, \"{name} returned NULL\");\n return tl_resource_new(ctx, (void *)r, {fin}, false);" ); } } out.push_str("}\n\n"); } } fn scalar_c(s: &Scalar) -> String { match s { Scalar::Int { c } | Scalar::Float { c } => c.clone(), Scalar::Bool => "bool".into(), } } fn til_scalar(s: &Scalar) -> &'static str { match s { Scalar::Int { .. } => "Int", Scalar::Float { .. } => "Float", Scalar::Bool => "Bool", } } /// Whether `p` names the length of the string before it. fn is_length(p: &Param) -> bool { p.name.as_deref().is_some_and(|n| { let n = n.to_ascii_lowercase(); n == "n" || n.ends_with("len") || n.ends_with("length") || n.ends_with("size") }) } /// A lowercase identifier that is not a keyword. fn is_til_name(name: &str) -> bool { name.chars() .next() .is_some_and(|c| c.is_ascii_lowercase() || c == '_') && name .chars() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') && louise_syntax::SyntaxKind::keyword(name).is_none() } /// `sk_vec` and `sk_vec_t` become `SkVec`. fn type_name(c: &str) -> String { c.trim_end_matches("_t") .split('_') .filter(|p| !p.is_empty()) .map(|p| { let mut cs = p.chars(); cs.next() .map(|f| f.to_ascii_uppercase().to_string() + cs.as_str()) .unwrap_or_default() }) .collect() } fn shown_type(ty: &TypeSyntax) -> String { match ty { TypeSyntax::Plain { words, is_const, pointers, } => format!( "{}{}{}{}", if *is_const { "const " } else { "" }, words.join(" "), if *pointers > 0 { " " } else { "" }, "*".repeat(*pointers) ), TypeSyntax::FnPointer(sig) => shown_fn(sig), TypeSyntax::Unsupported(text) => text.clone(), } } fn shown_params(sig: &Signature) -> String { let mut params: Vec = sig .params .iter() .map(|p| match (&p.ty, &p.name) { (TypeSyntax::FnPointer(sig), Some(n)) => { format!("{} (*{n})({})", shown_type(&sig.ret), shown_params(sig)) } (ty, Some(n)) => { let ty = shown_type(ty); let sep = if ty.ends_with('*') { "" } else { " " }; format!("{ty}{sep}{n}") } (ty, None) => shown_type(ty), }) .collect(); if sig.variadic { params.push("...".into()); } if params.is_empty() { "void".into() } else { params.join(", ") } } /// `int (*)(int64_t, void *)` fn shown_fn(sig: &Signature) -> String { format!("{} (*)({})", shown_type(&sig.ret), shown_params(sig)) } /// `size_t sk_vec_len(const sk_vec *v)` fn shown_fn_named(sig: &Signature, name: &str) -> String { let ret = shown_type(&sig.ret); let sep = if ret.ends_with('*') { "" } else { " " }; format!("{ret}{sep}{name}({})", shown_params(sig)) } #[cfg(test)] mod tests { use super::*; #[test] fn names() { assert_eq!(type_name("sk_vec"), "SkVec"); assert_eq!(type_name("sk_vec_t"), "SkVec"); assert!(is_til_name("sk_vec_new")); assert!(!is_til_name("SDL_Init")); assert!(!is_til_name("match")); } }