//! The C header: the declarations of everything [`crate::glue`] defines. use std::collections::BTreeSet; use std::hash::Hasher; use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, Sig, Ty}; use crate::ir::{Function, Int, Literal, Receiver, Traits, Type}; /// The header for `abi`, as `.h`, and its contract: a hash of what it declares, /// which the library returns from `_contract`. pub(crate) fn header(abi: &Abi<'_>, packages: &str) -> (String, u64) { let mut h = Header { abi, out: String::new(), defined: BTreeSet::new(), }; h.write(); // Platform independent, so a header names the same contract wherever it is generated. let mut hasher = StableHasher::new(); hasher.write(h.out.as_bytes()); let contract = Hasher::finish(&hasher); let p = &abi.prefix; let upper = p.to_uppercase(); let guard = format!("{upper}_H"); let header = format!( "/* Generated by rust2-ffi: the C ABI of the pub API of {packages}. Do not edit. */\n\n\ #ifndef {guard}\n#define {guard}\n\n\ #include \n#include \n#include \n\n\ #ifdef __cplusplus\nextern \"C\" {{\n#endif\n\n\ /* A hash of everything below, which {p}_contract returns from a library built with\n * this header. Check it before any other call: a header and a library that declare\n * different APIs must not mix. */\n\ #define {upper}_CONTRACT ((uint64_t)0x{contract:016x}ULL)\n\ uint64_t {p}_contract(void);\n\n\ {body}\n\ #ifdef __cplusplus\n}}\n#endif\n\n\ #endif /* {guard} */\n", body = h.out, ); (header, contract) } struct Header<'a> { abi: &'a Abi<'a>, out: String, /// The value structs written so far, so each is written after what it holds. defined: BTreeSet, } impl Header<'_> { fn line(&mut self, line: impl AsRef) { self.out.push_str(line.as_ref()); self.out.push('\n'); } fn decl(&self, ty: &Ty, name: &str) -> String { decl(self.abi, ty, name) } fn prototype(&self, sig: &Sig) -> String { let params: Vec = sig.params.iter().map(|(n, ty)| self.decl(ty, n)).collect(); let params = match params.is_empty() { true => "void".to_string(), false => params.join(", "), }; format!("{};", self.decl(&sig.ret, &format!("{}({params})", sig.name))) } /// Everything the header declares but its contract. fn write(&mut self) { let abi = self.abi; let api = abi.api; let p = abi.prefix.clone(); let upper = p.to_uppercase(); let targets: String = (api.targets.iter().enumerate()) .map(|(i, t)| format!("\n * {i}: {t}")) .collect(); self.line(format!( "/* The index of the library's target among those this header serves:{targets} */\nuint32_t {p}_target(void);\n" )); let statuses: String = (crate::abi::STATUSES.iter().enumerate()) .map(|(n, (status, _))| format!("\t{upper}_STATUS_{} = {},\n", status.to_uppercase(), n + 1)) .collect(); self.line(format!( "/* Why a call failed a check of a handle, before it ran any Rust: a borrow or move\n * Rust's borrow checker would refuse. A function that can fail one takes a status\n * last, through which it writes the failure, returning a zeroed value to ignore;\n * passed null, it aborts with the message instead. */\ntypedef int32_t {p}_status;\nenum {{\n{statuses}}};\n\n/* What a status says broke. */\nconst char *{p}_status_message({p}_status status);\n" )); self.line(format!( "/* Bytes. Returned, an owned buffer to free once with {p}_buf_free, or pass back to\n * Rust by value, ptr and len narrowed to any range of its bytes. Passed by value, one\n * whose owner is set is Rust's from then on, taken without a copy, and one whose owner\n * is NULL is a view Rust reads during the call and never frees; in a value passed by\n * pointer, or an array's item, either is only read. A null ptr is None. */\ntypedef struct {p}_buf {{\n\tconst uint8_t *ptr;\n\tsize_t len;\n\tvoid *owner;\n}} {p}_buf;\n\nvoid {p}_buf_free({p}_buf buf);\n\n/* An owned copy of view's bytes: what a closure or reader C implements returns Rust,\n * which then owns it. */\n{p}_buf {p}_buf_copy({p}_buf view);\n\n/* A second owned buffer of an owned buffer's bytes, sharing them without a copy: what\n * a caller passes Rust while keeping buf. */\n{p}_buf {p}_buf_clone({p}_buf buf);\n" )); self.line(format!( "/* A u128: lo holds its low 64 bits and hi its high 64. */\ntypedef struct {p}_u128 {{\n\tuint64_t lo;\n\tuint64_t hi;\n}} {p}_u128;\n" )); self.line(format!( "typedef struct {p}_duration {{\n\tuint64_t secs;\n\tuint32_t nanos;\n}} {p}_duration;\n" )); self.line(format!( "/* An IPv4 address, in network order. */\ntypedef struct {p}_ipv4_addr {{\n\tuint8_t octets[4];\n}} {p}_ipv4_addr;\n\n/* An IPv6 address, in network order. */\ntypedef struct {p}_ipv6_addr {{\n\tuint8_t octets[16];\n}} {p}_ipv6_addr;\n\n/* An IP address: ip.v6 if v6, else ip.v4. */\ntypedef struct {p}_ip_addr {{\n\tbool v6;\n\tunion {{\n\t\t{p}_ipv4_addr v4;\n\t\t{p}_ipv6_addr v6;\n\t}} ip;\n}} {p}_ip_addr;\n\n/* An IPv4 socket address, its port in the host's order. */\ntypedef struct {p}_socket_addr_v4 {{\n\t{p}_ipv4_addr ip;\n\tuint16_t port;\n}} {p}_socket_addr_v4;\n\n/* An IPv6 socket address, its port in the host's order. */\ntypedef struct {p}_socket_addr_v6 {{\n\t{p}_ipv6_addr ip;\n\tuint16_t port;\n\tuint32_t flowinfo;\n\tuint32_t scope_id;\n}} {p}_socket_addr_v6;\n\n/* A socket address: addr.v6 if v6, else addr.v4. */\ntypedef struct {p}_socket_addr {{\n\tbool v6;\n\tunion {{\n\t\t{p}_socket_addr_v4 v4;\n\t\t{p}_socket_addr_v6 v6;\n\t}} addr;\n}} {p}_socket_addr;\n" )); self.line(format!( "/* Wakes a future's poller: wake may be called from any thread, any number of\n * times, until drop releases data. A poll passing the same wake and data again\n * reuses the waker. Either function may be null. One Rust returns is the caller's,\n * to drop once or pass back into Rust. */\ntypedef struct {p}_waker {{\n\tvoid (*wake)(void *data);\n\tvoid (*drop)(void *data);\n\tvoid *data;\n}} {p}_waker;\n" )); if api.unsent() { self.line(format!( "/* A value that is not Send, freed on another thread than the one that made it,\n * drops on that thread at its next call on such a value, or when it exits. A thread\n * running a loop that may call nothing for a while passes {p}_thread_wake a waker,\n * replacing any earlier one, which a free elsewhere wakes from its own thread as it\n * queues a drop: the waker then schedules {p}_thread_drain on the thread, which drops\n * each value queued for the thread it runs on. */\nvoid {p}_thread_wake({p}_waker wake);\nvoid {p}_thread_drain(void);\n" )); } self.line(format!( "/* A future C implements, of nothing: Rust polls it from any thread with a waker of\n * its own each time, which C wakes once the future can make progress and drops once,\n * until poll returns true, and calls free with data once it drops the future, done or\n * not. free may be null. */\ntypedef struct {p}_foreign_future {{\n\tbool (*poll)(void *data, {p}_waker waker);\n\tvoid (*free)(void *data);\n\tvoid *data;\n}} {p}_foreign_future;\n" )); self.line(format!( "/* A reader C implements, which Rust reads and seeks only during the call it is passed\n * to, one call at a time from any thread. read reads up to len bytes into buf,\n * writing how many to *n, none only at the end; seek moves offset from whence, SEEK_SET,\n * SEEK_CUR, or SEEK_END, writing the position from the start to *position; from SEEK_SET,\n * offset's bits are a uint64_t, which may pass INT64_MAX. Each\n * returns whether it succeeded, else writing its error's message to *err as a buffer\n * {p}_buf_copy made. */\ntypedef struct {p}_foreign_reader {{\n\tbool (*read)(void *data, uint8_t *buf, size_t len, size_t *n, {p}_buf *err);\n\tbool (*seek)(void *data, int whence, int64_t offset, uint64_t *position, {p}_buf *err);\n\tvoid *data;\n}} {p}_foreign_reader;\n" )); self.line(format!( "typedef enum {p}_poll {{\n\t{upper}_POLL_PENDING = 0,\n\t{upper}_POLL_READY = 1,\n\t{upper}_POLL_ERROR = 2,\n}} {p}_poll;\n" )); // Handles, each opaque. for i in 0..api.objects.len() { let name = abi.object(i); self.line(format!("typedef struct {name} {name};")); } self.line(""); // Plain enums. for (i, e) in api.enums.iter().enumerate().filter(|(_, e)| e.plain()) { let name = abi.enumeration(i); let upper = name.to_uppercase(); let variants: Vec = e .variants .iter() .map(|v| format!("\t{upper}_{} = {},", abi::snake(&v.name).to_uppercase(), v.discriminant)) .collect(); self.line(format!( "{}typedef enum {name} {{\n{}\n}} {name};\n", comment(&e.docs, ""), variants.join("\n") )); } if abi.ranges.values().any(|ty| matches!(ty, Type::Bound(_))) { let bound = abi.rt("bound"); let upper = bound.to_uppercase(); self.line(format!( "/* What a range's start or end bound does: nothing, include its value, or exclude it. */\ntypedef enum {bound} {{\n\t{upper}_UNBOUNDED = 0,\n\t{upper}_INCLUDED = 1,\n\t{upper}_EXCLUDED = 2,\n}} {bound};\n" )); } // Value structs, each after the values it holds. for name in abi.lists.keys() { self.value(&Ty::Struct(name.clone())); } for name in abi.ranges.keys() { self.value(&Ty::Struct(name.clone())); } for name in abi.arrays.keys() { self.value(&Ty::Struct(name.clone())); } for name in abi.options.keys() { self.value(&Ty::Struct(name.clone())); } for name in abi.tuples.keys() { self.value(&Ty::Struct(name.clone())); } for i in 0..api.records.len() { self.value(&Ty::Struct(abi.record(i))); } for (i, _) in api.enums.iter().enumerate().filter(|(_, e)| !e.plain()) { self.value(&Ty::Struct(abi.enumeration(i))); } for (i, callback) in api.callbacks.iter().enumerate() { let name = abi.callback(i); let mut table = vec!["\tvoid (*free)(void *data);".to_string()]; for method in &callback.methods { let params: Vec = std::iter::once("void *data".to_string()) .chain( method .params .iter() .map(|p| self.decl(&abi.ty(&p.ty), &abi::escape(&p.name))), ) .collect(); let decl = self.decl( &abi.ty(&method.ok), &format!("(*{})({})", method.name(), params.join(", ")), ); table.push(format!("\t{decl};")); } let docs = format!( "{}: implemented in C. Rust calls free once it drops the implementation, and\nmay call the others from any thread.\n\n{}", callback.path.join("::"), callback.docs ); self.line(format!( "{}typedef struct {name}_vtable {{\n{}\n}} {name}_vtable;\n\ntypedef struct {name} {{\n\tconst {name}_vtable *vtable;\n\tvoid *data;\n}} {name};\n", comment(docs.trim(), ""), table.join("\n") )); } for constant in &api.constants { let value = match constant.value { Literal::Bool(b) => b.to_string(), Literal::Int(int, v) => c_literal(int, v), }; self.line(format!( "{}#define {} {value}", comment(&constant.docs, ""), abi.constant(&constant.path) )); } if !api.constants.is_empty() { self.line(""); } for (i, record) in api.records.iter().enumerate() { let name = abi.record(i); self.line(format!("/* {} */", abi.api.rust(&record.path, &record.args)).trim_end()); self.value_functions( &name, Ty::Struct(name.clone()), record.traits, record.opaque.is_none(), abi.value_status(&Type::Record(i)), ); let owner = Ty::Struct(name.clone()); for method in &record.methods { self.function(method, Some(&owner)); } self.line(""); } for (i, e) in api.enums.iter().enumerate() { let name = abi.enumeration(i); let ty = abi.ty(&Type::Enum(i)); if e.methods.is_empty() && !has(e.traits) && e.plain() { continue; } self.line(format!("/* {} */", abi.api.rust(&e.path, &e.args))); self.value_functions( &name, ty.clone(), e.traits, !e.plain(), abi.value_status(&Type::Enum(i)), ); for method in &e.methods { self.function(method, Some(&ty)); } self.line(""); } for (i, object) in api.objects.iter().enumerate() { let name = abi.object(i); let docs = format!("{}\n\n{}", abi.api.rust(&object.path, &object.args), object.docs); self.line(comment(docs.trim(), "").trim_end()); self.line(format!("void {name}_free({name} *self);")); if abi.checked[i] { self.line( comment( "Drop the value now, as a move out would, leaving the handle to free: a later call fails as moved, and a second drop does nothing. Fails while a call or future borrows the value.", "", ) .trim_end(), ); self.line(format!("void {name}_drop({name} *self, {p}_status *status);")); } if object.shared { self.line(format!("bool {name}_borrowed(const {name} *self);")); } let t = object.traits; let status = match abi.traits_status(i) { true => format!(", {p}_status *status"), false => String::new(), }; if t.clone { self.line(format!("{name} *{name}_clone(const {name} *self{status});")); } if t.eq { self.line(format!("bool {name}_eq(const {name} *a, const {name} *b{status});")); } if t.hash { self.line(format!("uint64_t {name}_hash(const {name} *self{status});")); } if t.display { self.line(format!("{p}_buf {name}_to_string(const {name} *self{status});")); } if t.debug { self.line(format!("{p}_buf {name}_debug(const {name} *self{status});")); } if t.default { self.line(format!("{name} *{name}_default(void);")); if !object.send { self.line(format!("{name} *{name}_default_homed(void);")); } } let owner = Ty::Handle { name: name.clone(), constant: false, }; for method in &object.methods { self.function(method, Some(&owner)); } self.line(""); } for function in &api.functions { self.function(function, None); } } /// A value struct, after the structs its fields hold. fn value(&mut self, ty: &Ty) { let abi = self.abi; let Ty::Struct(name) = ty else { return; }; if !self.defined.insert(name.clone()) { return; } if let Some(ty) = abi.ranges.get(name) { let fields = match ty { Type::Range(int) => format!("\t{int} start;\n\t{int} end;", int = c_int(*int)), Type::Bound(int) => format!("\t{} kind;\n\t{} value;", abi.rt("bound"), c_int(*int)), Type::Bounds(int) => { let bound = abi.range(&Type::Bound(*int)); self.value(&Ty::Struct(bound.clone())); format!("\t{bound} start;\n\t{bound} end;") } other => unreachable!("{other:?} is no range"), }; self.line(format!("typedef struct {name} {{\n{fields}\n}} {name};\n")); return; } if let Some(n) = abi.arrays.get(name) { self.line(format!("typedef struct {name} {{\n\tuint8_t items[{n}];\n}} {name};\n")); return; } if let Some(elem) = abi.lists.get(name) { let elem = abi.ty(elem); self.value(&elem); let ptr = match elem { Ty::Handle { name, .. } => format!("{name} *const *ptr"), elem => self.decl(&Ty::In(Box::new(elem)), "ptr"), }; self.line(format!( "/* A Vec. Passed in, an array Rust reads during the call and never frees. Returned,\n * an array to free once with {name}_free, which frees its first len elements too:\n * set len to 0 first to keep them. A null ptr is None. */\ntypedef struct {name} {{\n\t{ptr};\n\tsize_t len;\n\tvoid *owner;\n}} {name};\n\nvoid {name}_free({name} vec);\n" )); return; } if let Some(inner) = abi.options.get(name) { let inner = abi.ty(inner); self.value(&inner); let value = self.decl(&inner, "value"); self.line(format!( "typedef struct {name} {{\n\tbool some;\n\t{value};\n}} {name};\n" )); return; } if let Some(elements) = abi.tuples.get(name) { let elements: Vec = elements.iter().map(|e| abi.ty(e)).collect(); let mut decls = Vec::new(); for (n, element) in elements.iter().enumerate() { self.value(element); decls.push(format!("\t{};", self.decl(element, &format!("_{n}")))); } self.line(format!("typedef struct {name} {{\n{}\n}} {name};\n", decls.join("\n"))); return; } if let Some(i) = (0..abi.api.records.len()).find(|&i| &abi.record(i) == name) { let record = &abi.api.records[i]; if let Some(opaque) = &record.opaque { self.line(format!( "{}typedef struct {name} {{\n\t/* Its bytes, which only Rust reads: copy it, but never make or change one. */\n\t{} opaque[{}];\n}} {name};\n", comment(&record.docs, ""), c_unit(opaque.unit()), opaque.units() )); return; } let fields: Vec = record.fields.iter().map(|f| abi.ty(&f.ty)).collect(); for field in &fields { self.value(field); } let decls: Vec = record .fields .iter() .zip(&fields) .map(|(f, ty)| format!("{}\t{};", comment(&f.docs, "\t"), self.decl(ty, &abi::escape(&f.name)))) .collect(); self.line(format!( "{}typedef struct {name} {{\n{}\n}} {name};\n", comment(&record.docs, ""), decls.join("\n") )); return; } let Some(i) = (0..abi.api.enums.len()).find(|&i| &abi.enumeration(i) == name) else { return; }; let e = &abi.api.enums[i]; let upper = name.to_uppercase(); let tags: Vec = e .variants .iter() .enumerate() .map(|(n, v)| format!("\t{upper}_{} = {n},", abi::snake(&v.name).to_uppercase())) .collect(); self.line(format!( "typedef enum {name}_tag {{\n{}\n}} {name}_tag;\n", tags.join("\n") )); let mut members = Vec::new(); for variant in e.variants.iter().filter(|v| !v.fields.is_empty()) { let payload = abi::payload(name, &variant.name); let fields: Vec = variant.fields.iter().map(|f| abi.ty(&f.ty)).collect(); for field in &fields { self.value(field); } let decls: Vec = variant .fields .iter() .zip(&fields) .map(|(f, ty)| format!("\t{};", self.decl(ty, &abi::escape(&f.name)))) .collect(); self.line(format!( "typedef struct {payload} {{\n{}\n}} {payload};\n", decls.join("\n") )); members.push(format!("\t\t{payload} {};", abi::escape(&abi::snake(&variant.name)))); } self.line(format!( "typedef struct {name} {{\n\t{name}_tag tag;\n\tunion {{\n{}\n\t}};\n}} {name};\n", members.join("\n") )); } /// The functions a value type's std traits export, and its `free` if it owns memory. fn value_functions(&mut self, name: &str, ty: Ty, traits: Traits, free: bool, status: bool) { let p = &self.abi.prefix; let status = match status { true => format!(", {p}_status *status"), false => String::new(), }; let this = self.decl(&Ty::In(Box::new(ty.clone())), "self"); let a = self.decl(&Ty::In(Box::new(ty.clone())), "a"); let b = self.decl(&Ty::In(Box::new(ty.clone())), "b"); if free { self.line(format!("void {name}_free({name} *self);")); } if traits.eq { self.line(format!("bool {name}_eq({a}, {b}{status});")); } if traits.hash { self.line(format!("uint64_t {name}_hash({this}{status});")); } if traits.display { self.line(format!("{p}_buf {name}_to_string({this}{status});")); } if traits.debug { self.line(format!("{p}_buf {name}_debug({this}{status});")); } if traits.default { self.line(format!("{} {name}_default(void);", self.decl(&ty, ""))); } } fn function(&mut self, function: &Function, owner: Option<&Ty>) { let export = self.abi.export(function, owner); let mut docs = function.docs.clone(); // What the call moves out of the caller's handles, which are then only freed. // A handle taken by value: one taken `&mut` is not `const` either, but stays. let receiver = function.receiver.map(|r| r == Receiver::Owned); let by_value = receiver .into_iter() .chain((function.params.iter()).map(|p| match &p.ty { Type::Option(inner) => !matches!(**inner, Type::Ref(..)), ty => !matches!(ty, Type::Ref(..)), })); let moved: Vec = export .call .params .iter() // A lent function's data follows it, and is no parameter of its own. .filter(|(_, ty)| *ty != Ty::Data) .zip(by_value) .filter(|((_, ty), by_value)| *by_value && matches!(ty, Ty::Handle { constant: false, .. })) .map(|((name, _), _)| format!("`{name}`")) .collect(); if !moved.is_empty() { docs.push_str(&format!( "\n\nMoves the value out of {}: free the handle after.", moved.join(" and ") )); } if matches!(export.call.params.first(), Some((_, Ty::InOut(_)))) { docs.push_str("\n\nRust writes what the call left in `self` back in place."); } for param in function.params.iter().filter(|p| p.ty.written()) { let name = abi::escape(¶m.name); docs.push_str(&format!( "\n\nRust writes what the call left in `{name}` through `{}`, on every path, errors included: the caller keeps what it passed, and frees what Rust wrote as a returned value.", Abi::written(function, &name) )); } for param in &function.params { let Type::Closure(closure) = ¶m.ty else { continue; }; let name = abi::escape(¶m.name); let at = (export.call.params.iter()) .position(|(n, _)| *n == name) .expect("a C parameter for each"); let data = &export.call.params[at + 1].0; match closure.kept { true => { let free = &export.call.params[at + 2].0; docs.push_str(&format!( "\n\nRust keeps `{name}`, calling it with `{data}` from any thread, then calls `{free}`\nwith `{data}` once it drops it; `{free}` may be null." )) } false => docs.push_str(&format!( "\n\nRust calls `{name}` with `{data}` only during the call, from any thread." )), } if closure.params.iter().any(|p| matches!(p.base(), Type::Object(_))) { docs.push_str(&format!( "\nA handle it lends lives only for that call of `{name}`: free none, nor move out of one." )); } if closure.ok == Type::String || closure.err.is_some() { docs.push_str(&format!( "\nA buffer it returns is Rust's, one {}_buf_copy made.", self.abi.prefix )); } } let api = self.abi.api; if !api.everywhere(function.on) { docs.push_str(&format!( "\n\nOnly on {}: elsewhere the library aborts if it is called.", api.named(function.on).join(", ") )); } self.out.push_str(&comment(docs.trim(), "")); if let Some(future) = &export.future { let handle = &future.handle; self.line(format!("typedef struct {handle} {handle};")); let homed = export.homed_call().into_iter().chain(export.homed_start()); for sig in [ export.call.clone(), future.start.clone(), future.poll.clone(), future.free.clone(), ] .into_iter() .chain(homed) { let prototype = self.prototype(&sig); self.line(prototype); } return; } for sig in std::iter::once(export.call.clone()).chain(export.homed_call()) { let prototype = self.prototype(&sig); self.line(prototype); } } } /// `ty` declaring `name`: a parameter, field, or, with an empty name, a type. pub(crate) fn decl(abi: &Abi<'_>, ty: &Ty, name: &str) -> String { let space = |t: &str| match name.is_empty() { true => t.to_string(), false => format!("{t} {name}"), }; match ty { Ty::Void => space("void"), Ty::Bool => space("bool"), Ty::Int(int) => space(c_int(*int)), Ty::F32 => space("float"), Ty::F64 => space("double"), Ty::Char => space("uint32_t"), Ty::Buf => space(&abi.rt("buf")), Ty::U128 => space(&abi.rt("u128")), Ty::Duration => space(&abi.rt("duration")), Ty::SocketAddr(family) => space(&abi.rt(crate::abi::addr(true, *family))), Ty::IpAddr(family) => space(&abi.rt(crate::abi::addr(false, *family))), Ty::Struct(n) | Ty::Enum(n) => space(n), Ty::Handle { name: n, constant } => match constant { true => format!("const {n} *{name}"), false => format!("{n} *{name}"), }, Ty::Future(n) => format!("{n} *{name}"), Ty::Waker => space(&abi.rt("waker")), Ty::ForeignFuture => space(&abi.rt("foreign_future")), Ty::ForeignReader => space(&abi.rt("foreign_reader")), Ty::Jni(_) => unreachable!("only Kotlin exports what takes a JNI value"), Ty::Poll => space(&abi.rt("poll")), Ty::Status => space(&abi.rt("status")), Ty::Out(inner) | Ty::InOut(inner) => decl(abi, inner, &format!("*{name}")), Ty::In(inner) => format!("const {}", decl(abi, inner, &format!("*{name}"))), Ty::Fn(params, ret) => { let params: Vec = std::iter::once("void *data".to_string()) .chain(params.iter().map(|p| decl(abi, p, ""))) .collect(); decl(abi, ret, &format!("(*{name})({})", params.join(", "))) } Ty::Data => format!("void *{name}"), } } /// A C comment holding `docs`, each line indented by `indent`, or nothing for none. fn comment(docs: &str, indent: &str) -> String { if docs.is_empty() { return String::new(); } // Neither may appear inside a C comment. let docs = docs.replace("*/", "* /").replace("/*", "/ *"); let lines: Vec<&str> = docs.lines().collect(); let mut out = String::new(); for (i, line) in lines.iter().enumerate() { let lead = match i { 0 => "/* ", _ => " * ", }; out.push_str(indent); out.push_str(lead.trim_end_matches(' ')); if !line.is_empty() { out.push(' '); out.push_str(line); } if i + 1 == lines.len() { out.push_str(" */"); } out.push('\n'); } out } fn has(traits: Traits) -> bool { traits.eq || traits.display || traits.debug || traits.default } /// The C type of each unit an opaque value's struct holds, of `bytes` bytes. pub(crate) fn c_unit(bytes: u64) -> &'static str { match bytes { 1 => "uint8_t", 2 => "uint16_t", 4 => "uint32_t", _ => "uint64_t", } } fn c_int(int: Int) -> &'static str { match int { Int::U8 => "uint8_t", Int::U16 => "uint16_t", Int::U32 => "uint32_t", Int::U64 => "uint64_t", Int::Usize => "size_t", Int::I8 => "int8_t", Int::I16 => "int16_t", Int::I32 => "int32_t", Int::I64 => "int64_t", Int::Isize => "ptrdiff_t", } } /// An integer constant, typed as its Rust type. fn c_literal(int: Int, v: i128) -> String { match int { Int::U64 | Int::Usize => format!("(({}){v}ULL)", c_int(int)), Int::I64 | Int::Isize if v == i64::MIN as i128 => format!("(({})(-9223372036854775807LL - 1))", c_int(int)), Int::I64 | Int::Isize => format!("(({}){v}LL)", c_int(int)), Int::U32 => format!("(({}){v}U)", c_int(int)), _ => format!("(({}){v})", c_int(int)), } }