libperl-macrogen 0.1.5

Generate Rust FFI bindings from C macro functions in Perl headers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Rust宣言パーサー
//!
//! bindgenが生成したRustコードから宣言を抽出する。
//! syn crateを使用して正確にパースする。

use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::path::Path;

use syn::{Item, Type, FnArg, Pat, ReturnType, Fields, Visibility};
use quote::ToTokens;

use crate::unified_type::UnifiedType;

/// Rust定数
#[derive(Debug, Clone)]
pub struct RustConst {
    pub name: String,
    pub ty: String,
    pub uty: UnifiedType,
}

/// Rust関数パラメータ
#[derive(Debug, Clone)]
pub struct RustParam {
    pub name: String,
    pub ty: String,
    pub uty: UnifiedType,
}

/// Rust関数
#[derive(Debug, Clone)]
pub struct RustFn {
    pub name: String,
    pub params: Vec<RustParam>,
    pub ret_ty: Option<String>,
    pub uret_ty: Option<UnifiedType>,
}

/// Rust構造体フィールド
#[derive(Debug, Clone)]
pub struct RustField {
    pub name: String,
    pub ty: String,
    pub uty: UnifiedType,
}

/// Rust構造体
#[derive(Debug, Clone)]
pub struct RustStruct {
    pub name: String,
    pub fields: Vec<RustField>,
}

/// Rust型エイリアス
#[derive(Debug, Clone)]
pub struct RustTypeAlias {
    pub name: String,
    pub ty: String,
    pub uty: UnifiedType,
}

/// Rust宣言辞書
#[derive(Debug, Default)]
pub struct RustDeclDict {
    pub consts: HashMap<String, RustConst>,
    pub fns: HashMap<String, RustFn>,
    pub structs: HashMap<String, RustStruct>,
    pub types: HashMap<String, RustTypeAlias>,
    pub enums: HashSet<String>,
    /// 全 extern static 変数名の集合
    pub statics: HashSet<String>,
    /// 配列型の extern static 変数名の集合
    pub static_arrays: HashSet<String>,
    /// static 変数の型マップ (名前 → Rust 型文字列)
    /// 例: "PL_c9_utf8_dfa_tab" → "[U8; 0usize]"
    pub static_types: HashMap<String, String>,
    /// ビットフィールドのメソッド名集合(構造体名 → メソッド名セット)
    pub bitfield_methods: HashMap<String, HashSet<String>>,
    /// ビットフィールドアクセサ getter の戻り値型
    /// (構造体名, メソッド名) → 戻り値型文字列
    /// 例: ("op", "op_type") → "U16"
    pub bitfield_method_types: HashMap<(String, String), String>,
}

impl RustDeclDict {
    /// 新しい辞書を作成
    pub fn new() -> Self {
        Self::default()
    }

    /// ファイルからパース
    pub fn parse_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
        let content = fs::read_to_string(path)?;
        Ok(Self::parse(&content))
    }

    /// 全 struct / typedef / enum 名を StringInterner に intern する。
    ///
    /// bindgen が生成する `pmop__bindgen_ty_2` のような名前は通常 C ヘッダ側の
    /// パースでは登場しないため interner に未登録のまま。後段の型推論で
    /// `from_apidoc_string("pmop__bindgen_ty_2", interner)` のように
    /// `interner.lookup()` を経由する経路は immutable な interner しか見ないので、
    /// パース直後に明示的に intern しておく必要がある。
    pub fn intern_names(&self, interner: &mut crate::intern::StringInterner) {
        for name in self.structs.keys() {
            interner.intern(name);
        }
        for name in self.types.keys() {
            interner.intern(name);
        }
        for name in &self.enums {
            interner.intern(name);
        }
    }

    /// 文字列からパース
    pub fn parse(content: &str) -> Self {
        let mut dict = Self::new();

        // synでパース
        let file = match syn::parse_file(content) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("Warning: Failed to parse Rust file: {}", e);
                return dict;
            }
        };

        // 各アイテムを処理
        for item in file.items {
            dict.process_item(&item);
        }

        dict
    }

    /// アイテムを処理
    fn process_item(&mut self, item: &Item) {
        match item {
            Item::Const(item_const) => {
                if Self::is_pub(&item_const.vis) {
                    let name = item_const.ident.to_string();
                    let uty = UnifiedType::from_syn_type(&item_const.ty);
                    let ty = Self::type_to_string(&item_const.ty);
                    self.consts.insert(name.clone(), RustConst { name, ty, uty });
                }
            }
            Item::Type(item_type) => {
                if Self::is_pub(&item_type.vis) {
                    let name = item_type.ident.to_string();
                    let uty = UnifiedType::from_syn_type(&item_type.ty);
                    let ty = Self::type_to_string(&item_type.ty);
                    self.types.insert(name.clone(), RustTypeAlias { name, ty, uty });
                }
            }
            Item::Struct(item_struct) => {
                if Self::is_pub(&item_struct.vis) {
                    let name = item_struct.ident.to_string();
                    let fields = Self::extract_fields(&item_struct.fields);
                    self.structs.insert(name.clone(), RustStruct { name, fields });
                }
            }
            Item::Union(item_union) => {
                if Self::is_pub(&item_union.vis) {
                    let name = item_union.ident.to_string();
                    let fields = Self::extract_fields(&Fields::Named(item_union.fields.clone()));
                    self.structs.insert(name.clone(), RustStruct { name, fields });
                }
            }
            Item::Fn(item_fn) => {
                if Self::is_pub(&item_fn.vis) {
                    if let Some(rust_fn) = Self::extract_fn(&item_fn.sig) {
                        self.fns.insert(rust_fn.name.clone(), rust_fn);
                    }
                }
            }
            Item::ForeignMod(foreign_mod) => {
                // extern "C" { ... } ブロック内の関数と static 変数
                for foreign_item in &foreign_mod.items {
                    match foreign_item {
                        syn::ForeignItem::Fn(fn_item) => {
                            if Self::is_pub(&fn_item.vis) {
                                if let Some(rust_fn) = Self::extract_fn(&fn_item.sig) {
                                    self.fns.insert(rust_fn.name.clone(), rust_fn);
                                }
                            }
                        }
                        syn::ForeignItem::Static(static_item) => {
                            let name = static_item.ident.to_string();
                            let ty_str = Self::type_to_string(&static_item.ty);
                            self.statics.insert(name.clone());
                            if ty_str.starts_with("[") {
                                self.static_arrays.insert(name.clone());
                            }
                            self.static_types.insert(name, ty_str);
                        }
                        _ => {}
                    }
                }
            }
            Item::Enum(item_enum) => {
                if Self::is_pub(&item_enum.vis) {
                    self.enums.insert(item_enum.ident.to_string());
                }
            }
            Item::Impl(item_impl) => {
                // ビットフィールドのゲッターメソッドを収集
                let struct_name = Self::type_to_string(&item_impl.self_ty);
                for impl_item in &item_impl.items {
                    if let syn::ImplItem::Fn(method) = impl_item {
                        let body_str = method.block.to_token_stream().to_string();
                        if Self::has_self_receiver(&method.sig)
                            && body_str.contains("_bitfield_")
                            && method.sig.inputs.len() == 1  // getter: &self のみ
                        {
                            let method_name = method.sig.ident.to_string();
                            // 戻り値型を捕獲(型推論で利用)。戻り値なし getter は対象外。
                            if let syn::ReturnType::Type(_, ty) = &method.sig.output {
                                let ret_ty = Self::type_to_string(ty);
                                self.bitfield_method_types
                                    .insert((struct_name.clone(), method_name.clone()), ret_ty);
                            }
                            self.bitfield_methods
                                .entry(struct_name.clone())
                                .or_default()
                                .insert(method_name);
                        }
                    }
                }
            }
            _ => {}
        }
    }

    /// 可視性がpubかどうか
    fn is_pub(vis: &Visibility) -> bool {
        matches!(vis, Visibility::Public(_))
    }

    /// 関数シグネチャが &self レシーバを持つかどうか
    fn has_self_receiver(sig: &syn::Signature) -> bool {
        sig.inputs.first().is_some_and(|arg| matches!(arg, FnArg::Receiver(_)))
    }

    /// 型を文字列に変換
    fn type_to_string(ty: &Type) -> String {
        ty.to_token_stream().to_string()
    }

    /// 構造体フィールドを抽出
    fn extract_fields(fields: &Fields) -> Vec<RustField> {
        let mut result = Vec::new();

        match fields {
            Fields::Named(named) => {
                for field in &named.named {
                    if Self::is_pub(&field.vis) {
                        if let Some(ident) = &field.ident {
                            let uty = UnifiedType::from_syn_type(&field.ty);
                            let ty = Self::type_to_string(&field.ty);
                            result.push(RustField {
                                name: ident.to_string(),
                                ty,
                                uty,
                            });
                        }
                    }
                }
            }
            Fields::Unnamed(unnamed) => {
                for (i, field) in unnamed.unnamed.iter().enumerate() {
                    if Self::is_pub(&field.vis) {
                        let uty = UnifiedType::from_syn_type(&field.ty);
                        let ty = Self::type_to_string(&field.ty);
                        result.push(RustField {
                            name: format!("{}", i),
                            ty,
                            uty,
                        });
                    }
                }
            }
            Fields::Unit => {}
        }

        result
    }

    /// 関数シグネチャを抽出
    fn extract_fn(sig: &syn::Signature) -> Option<RustFn> {
        let name = sig.ident.to_string();

        let mut params = Vec::new();
        for arg in &sig.inputs {
            match arg {
                FnArg::Receiver(_) => {
                    // self, &self, &mut self はスキップ
                }
                FnArg::Typed(pat_type) => {
                    let param_name = match pat_type.pat.as_ref() {
                        Pat::Ident(pat_ident) => pat_ident.ident.to_string(),
                        _ => "_".to_string(),
                    };
                    let uty = UnifiedType::from_syn_type(&pat_type.ty);
                    let param_ty = Self::type_to_string(&pat_type.ty);
                    params.push(RustParam {
                        name: param_name,
                        ty: param_ty,
                        uty,
                    });
                }
            }
        }

        let (ret_ty, uret_ty) = match &sig.output {
            ReturnType::Default => (None, None),
            ReturnType::Type(_, ty) => (
                Some(Self::type_to_string(ty)),
                Some(UnifiedType::from_syn_type(ty)),
            ),
        };

        Some(RustFn {
            name,
            params,
            ret_ty,
            uret_ty,
        })
    }

    /// 統計情報を取得
    pub fn stats(&self) -> RustDeclStats {
        RustDeclStats {
            const_count: self.consts.len(),
            fn_count: self.fns.len(),
            struct_count: self.structs.len(),
            type_count: self.types.len(),
        }
    }

    /// THX依存関数の名前を取得
    ///
    /// 第一引数が *mut PerlInterpreter を含む関数を返す
    pub fn thx_functions(&self) -> std::collections::HashSet<String> {
        self.fns.iter()
            .filter(|(_, f)| {
                f.params.first()
                    .map(|p| p.ty.contains("PerlInterpreter"))
                    .unwrap_or(false)
            })
            .map(|(name, _)| name.clone())
            .collect()
    }

    /// 辞書をダンプ
    pub fn dump(&self) -> String {
        let mut result = String::new();

        result.push_str("=== Constants ===\n");
        let mut consts: Vec<_> = self.consts.values().collect();
        consts.sort_by_key(|c| &c.name);
        for c in consts {
            result.push_str(&format!("  {}: {}\n", c.name, c.ty));
        }

        result.push_str("\n=== Type Aliases ===\n");
        let mut types: Vec<_> = self.types.values().collect();
        types.sort_by_key(|t| &t.name);
        for t in types {
            result.push_str(&format!("  {} = {}\n", t.name, t.ty));
        }

        result.push_str("\n=== Functions ===\n");
        let mut fns: Vec<_> = self.fns.values().collect();
        fns.sort_by_key(|f| &f.name);
        for f in fns {
            let params: Vec<_> = f.params.iter().map(|p| format!("{}: {}", p.name, p.ty)).collect();
            let ret = f.ret_ty.as_deref().unwrap_or("()");
            result.push_str(&format!("  fn {}({}) -> {}\n", f.name, params.join(", "), ret));
        }

        result.push_str("\n=== Structs ===\n");
        let mut structs: Vec<_> = self.structs.values().collect();
        structs.sort_by_key(|s| &s.name);
        for s in structs {
            result.push_str(&format!("  struct {} {{\n", s.name));
            for f in &s.fields {
                result.push_str(&format!("    {}: {},\n", f.name, f.ty));
            }
            result.push_str("  }\n");
        }

        result
    }

    /// 名前で定数を検索
    pub fn lookup_const(&self, name: &str) -> Option<&RustConst> {
        self.consts.get(name)
    }

    /// 名前で関数を検索
    pub fn lookup_fn(&self, name: &str) -> Option<&RustFn> {
        self.fns.get(name)
    }

    /// 名前で構造体を検索
    pub fn lookup_struct(&self, name: &str) -> Option<&RustStruct> {
        self.structs.get(name)
    }

    /// 名前で型エイリアスを検索
    pub fn lookup_type(&self, name: &str) -> Option<&RustTypeAlias> {
        self.types.get(name)
    }
}

/// 統計情報
#[derive(Debug)]
pub struct RustDeclStats {
    pub const_count: usize,
    pub fn_count: usize,
    pub struct_count: usize,
    pub type_count: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_const() {
        let dict = RustDeclDict::parse("pub const FOO: u32 = 42;");
        assert_eq!(dict.consts.len(), 1);
        let c = dict.consts.get("FOO").unwrap();
        assert_eq!(c.name, "FOO");
        assert_eq!(c.ty, "u32");
    }

    #[test]
    fn test_parse_const_array() {
        let dict = RustDeclDict::parse("pub const MSG: &[u8; 10] = b\"(unknown)\\0\";");
        let c = dict.consts.get("MSG").unwrap();
        assert_eq!(c.name, "MSG");
        assert_eq!(c.ty, "& [u8 ; 10]");
    }

    #[test]
    fn test_parse_type_alias() {
        let dict = RustDeclDict::parse("pub type Size = ::std::os::raw::c_ulong;");
        let t = dict.types.get("Size").unwrap();
        assert_eq!(t.name, "Size");
        assert_eq!(t.ty, ":: std :: os :: raw :: c_ulong");
    }

    #[test]
    fn test_parse_fn() {
        let dict = RustDeclDict::parse(r#"
            extern "C" {
                pub fn foo(x: i32, y: *mut u8) -> bool;
            }
        "#);
        let f = dict.fns.get("foo").unwrap();
        assert_eq!(f.name, "foo");
        assert_eq!(f.params.len(), 2);
        assert_eq!(f.params[0].name, "x");
        assert_eq!(f.params[0].ty, "i32");
        assert_eq!(f.params[1].name, "y");
        assert_eq!(f.params[1].ty, "* mut u8");
        assert_eq!(f.ret_ty, Some("bool".to_string()));
    }

    #[test]
    fn test_parse_fn_no_return() {
        let dict = RustDeclDict::parse(r#"
            extern "C" {
                pub fn bar(x: i32);
            }
        "#);
        let f = dict.fns.get("bar").unwrap();
        assert_eq!(f.name, "bar");
        assert_eq!(f.ret_ty, None);
    }

    #[test]
    fn test_parse_struct() {
        let content = r#"
pub struct Point {
    pub x: i32,
    pub y: i32,
}
"#;
        let dict = RustDeclDict::parse(content);
        let s = dict.structs.get("Point").unwrap();
        assert_eq!(s.name, "Point");
        assert_eq!(s.fields.len(), 2);
        assert_eq!(s.fields[0].name, "x");
        assert_eq!(s.fields[0].ty, "i32");
    }

    #[test]
    fn test_parse_struct_with_option() {
        let content = r#"
pub struct Test {
    pub callback: ::std::option::Option<
        unsafe extern "C" fn(x: i32) -> i32,
    >,
}
"#;
        let dict = RustDeclDict::parse(content);
        let s = dict.structs.get("Test").unwrap();
        assert_eq!(s.name, "Test");
        assert_eq!(s.fields.len(), 1);
        assert_eq!(s.fields[0].name, "callback");
        // synのto_token_stream()は型を正しくパースする
        assert!(s.fields[0].ty.contains("Option"));
        assert!(s.fields[0].ty.contains("fn"));
        assert!(s.fields[0].ty.ends_with(">"), "Type should end with >");
    }

    #[test]
    fn test_parse_struct_with_generics() {
        let content = r#"
pub struct Wrapper<T> {
    pub value: T,
}
"#;
        let dict = RustDeclDict::parse(content);
        let s = dict.structs.get("Wrapper").unwrap();
        assert_eq!(s.name, "Wrapper");
    }
}