1use anyhow::{Context, Result};
2use syn::{File, ForeignItem, ForeignItemFn, Item, ItemEnum, ItemStruct, ItemType};
3use tracing::{debug, info};
4
5#[derive(Debug, Clone)]
7pub struct FfiInfo {
8 pub functions: Vec<FfiFunction>,
9 pub types: Vec<FfiType>,
10 pub enums: Vec<FfiEnum>,
11 pub constants: Vec<FfiConstant>,
12 pub opaque_types: Vec<String>,
13}
14
15#[derive(Debug, Clone)]
16pub struct FfiFunction {
17 pub name: String,
18 pub params: Vec<FfiParam>,
19 pub return_type: String,
20 pub docs: Option<String>,
21}
22
23#[derive(Debug, Clone)]
24pub struct FfiParam {
25 pub name: String,
26 pub ty: String,
27 pub is_pointer: bool,
28 pub is_mut: bool,
29}
30
31#[derive(Debug, Clone)]
32pub struct FfiType {
33 pub name: String,
34 pub is_opaque: bool,
35 pub docs: Option<String>,
36 pub fields: Vec<FfiField>,
37}
38
39#[derive(Debug, Clone)]
40pub struct FfiField {
41 pub name: String,
42 pub ty: String,
43}
44
45#[derive(Debug, Clone)]
46pub struct FfiEnum {
47 pub name: String,
48 pub variants: Vec<FfiEnumVariant>,
49 pub docs: Option<String>,
50}
51
52#[derive(Debug, Clone)]
53pub struct FfiEnumVariant {
54 pub name: String,
55 pub value: Option<i64>,
56}
57
58#[derive(Debug, Clone)]
59pub struct FfiConstant {
60 pub name: String,
61 pub value: String,
62 pub ty: String,
63}
64
65impl Default for FfiInfo {
66 fn default() -> Self {
67 Self::new()
68 }
69}
70
71impl FfiInfo {
72 pub fn new() -> Self {
73 Self {
74 functions: Vec::new(),
75 types: Vec::new(),
76 enums: Vec::new(),
77 constants: Vec::new(),
78 opaque_types: Vec::new(),
79 }
80 }
81}
82
83pub fn parse_ffi_bindings(bindings_code: &str) -> Result<FfiInfo> {
85 info!("Parsing FFI bindings");
86
87 let syntax_tree: File =
88 syn::parse_str(bindings_code).context("Failed to parse generated bindings as Rust code")?;
89
90 let mut ffi_info = FfiInfo::new();
91
92 for item in syntax_tree.items {
93 match item {
94 Item::ForeignMod(foreign_mod) => {
95 debug!(
96 "Found foreign module with {} items",
97 foreign_mod.items.len()
98 );
99 for foreign_item in foreign_mod.items {
100 if let ForeignItem::Fn(func) = foreign_item
101 && let Some(ffi_func) = parse_foreign_function(func)
102 {
103 ffi_info.functions.push(ffi_func);
104 }
105 }
106 }
107 Item::Struct(item_struct) => {
108 if let Some(ffi_type) = parse_struct(item_struct) {
109 ffi_info.types.push(ffi_type);
110 }
111 }
112 Item::Enum(item_enum) => {
113 if let Some(ffi_enum) = parse_enum(item_enum) {
114 ffi_info.enums.push(ffi_enum);
115 }
116 }
117 Item::Type(item_type) => {
118 if is_opaque_type(&item_type) {
120 ffi_info.opaque_types.push(item_type.ident.to_string());
121 }
122 }
123 Item::Const(item_const) => {
124 ffi_info.constants.push(FfiConstant {
125 name: item_const.ident.to_string(),
126 value: quote::quote!(#item_const).to_string(),
127 ty: quote::quote!(#item_const.ty).to_string(),
128 });
129 }
130 _ => {}
131 }
132 }
133
134 info!(
135 "Parsed {} functions, {} types, {} enums, {} constants",
136 ffi_info.functions.len(),
137 ffi_info.types.len(),
138 ffi_info.enums.len(),
139 ffi_info.constants.len()
140 );
141
142 Ok(ffi_info)
143}
144
145fn parse_foreign_function(func: ForeignItemFn) -> Option<FfiFunction> {
146 let name = func.sig.ident.to_string();
147
148 let params: Vec<FfiParam> = func
149 .sig
150 .inputs
151 .iter()
152 .filter_map(|arg| {
153 if let syn::FnArg::Typed(pat_type) = arg
154 && let syn::Pat::Ident(pat_ident) = &*pat_type.pat
155 {
156 let param_name = pat_ident.ident.to_string();
157 let type_str = quote::quote!(#pat_type.ty).to_string();
158
159 let (is_pointer, is_mut) = analyze_pointer_type(&pat_type.ty);
160
161 return Some(FfiParam {
162 name: param_name,
163 ty: type_str,
164 is_pointer,
165 is_mut,
166 });
167 }
168 None
169 })
170 .collect();
171
172 let return_type = match &func.sig.output {
173 syn::ReturnType::Default => "()".to_string(),
174 syn::ReturnType::Type(_, ty) => quote::quote!(#ty).to_string(),
175 };
176
177 let docs = extract_docs(&func.attrs);
178
179 Some(FfiFunction {
180 name,
181 params,
182 return_type,
183 docs,
184 })
185}
186
187fn parse_struct(item_struct: ItemStruct) -> Option<FfiType> {
188 let name = item_struct.ident.to_string();
189 let docs = extract_docs(&item_struct.attrs);
190
191 let fields: Vec<FfiField> = match item_struct.fields {
192 syn::Fields::Named(fields_named) => fields_named
193 .named
194 .iter()
195 .map(|field| FfiField {
196 name: field.ident.as_ref().unwrap().to_string(),
197 ty: quote::quote!(#field.ty).to_string(),
198 })
199 .collect(),
200 syn::Fields::Unnamed(_) => Vec::new(),
201 syn::Fields::Unit => Vec::new(),
202 };
203
204 let is_opaque = fields.is_empty();
205
206 Some(FfiType {
207 name,
208 is_opaque,
209 docs,
210 fields,
211 })
212}
213
214fn parse_enum(item_enum: ItemEnum) -> Option<FfiEnum> {
215 let name = item_enum.ident.to_string();
216 let docs = extract_docs(&item_enum.attrs);
217
218 let variants: Vec<FfiEnumVariant> = item_enum
219 .variants
220 .iter()
221 .map(|variant| {
222 let variant_name = variant.ident.to_string();
223 let value = match &variant.discriminant {
224 Some((_, expr)) => {
225 if let syn::Expr::Lit(expr_lit) = expr {
227 if let syn::Lit::Int(lit_int) = &expr_lit.lit {
228 lit_int.base10_parse::<i64>().ok()
229 } else {
230 None
231 }
232 } else {
233 None
234 }
235 }
236 None => None,
237 };
238
239 FfiEnumVariant {
240 name: variant_name,
241 value,
242 }
243 })
244 .collect();
245
246 Some(FfiEnum {
247 name,
248 variants,
249 docs,
250 })
251}
252
253fn is_opaque_type(item_type: &ItemType) -> bool {
254 if let syn::Type::Path(type_path) = &*item_type.ty
256 && let Some(segment) = type_path.path.segments.first()
257 {
258 let ident = segment.ident.to_string();
260 return ident == "c_void" || ident.ends_with("_impl") || ident.ends_with("_internal");
261 }
262 false
263}
264
265fn analyze_pointer_type(ty: &syn::Type) -> (bool, bool) {
266 match ty {
267 syn::Type::Ptr(type_ptr) => {
268 let is_mut = type_ptr.mutability.is_some();
269 (true, is_mut)
270 }
271 _ => (false, false),
272 }
273}
274
275fn extract_docs(attrs: &[syn::Attribute]) -> Option<String> {
276 let mut docs = Vec::new();
277
278 for attr in attrs {
279 if attr.path().is_ident("doc")
280 && let syn::Meta::NameValue(meta_name_value) = &attr.meta
281 && let syn::Expr::Lit(expr_lit) = &meta_name_value.value
282 && let syn::Lit::Str(lit_str) = &expr_lit.lit
283 {
284 docs.push(lit_str.value().trim().to_string());
285 }
286 }
287
288 if docs.is_empty() {
289 None
290 } else {
291 Some(docs.join("\n"))
292 }
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 #[test]
300 fn test_parse_simple_function() {
301 let code = r#"
302 extern "C" {
303 pub fn foo(x: i32) -> i32;
304 }
305 "#;
306
307 let result = parse_ffi_bindings(code);
308 assert!(result.is_ok());
309 let ffi_info = result.unwrap();
310 assert_eq!(ffi_info.functions.len(), 1);
311 assert_eq!(ffi_info.functions[0].name, "foo");
312 }
313}