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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! マクロ型推論の高レベル API
//!
//! build.rs や外部ツールから型推論を実行するための API を提供する。

use std::collections::{HashMap, HashSet};
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};

use crate::apidoc::{ApidocCollector, ApidocDict, ApidocResolveError};
use crate::ast::{DerivedDecl, ExternalDecl, TypeSpec};
use crate::c_fn_decl::{CFnDecl, CFnDeclDict, CParam};
use crate::enum_dict::EnumDict;
use crate::error::EnrichedCompileError;
use crate::fields_dict::FieldsDict;
use crate::inline_fn::InlineFnDict;
use crate::intern::InternedStr;
use crate::macro_infer::{ExplicitExpandSymbols, MacroInferContext, NoExpandSymbols};
use crate::parser::Parser;
use crate::perl_config::PerlConfigError;
use crate::preprocessor::{MacroCallWatcher, MacroDefCallback, Preprocessor};
use crate::rust_decl::RustDeclDict;

/// typedef 辞書の型エイリアス
pub type TypedefDict = HashSet<InternedStr>;

/// 型推論エラー
#[derive(Debug)]
pub enum InferError {
    /// Perl 設定取得エラー
    PerlConfig(PerlConfigError),
    /// apidoc 解決エラー
    ApidocResolve(ApidocResolveError),
    /// プリプロセッサ/パースエラー(ファイルパスと該当行で強化済み)
    Compile(EnrichedCompileError),
    /// ファイル I/O エラー
    Io(std::io::Error),
}

impl std::fmt::Display for InferError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InferError::PerlConfig(e) => write!(f, "Perl config error: {}", e),
            InferError::ApidocResolve(e) => write!(f, "Apidoc resolve error: {}", e),
            InferError::Compile(e) => write!(f, "Compile error: {}", e),
            InferError::Io(e) => write!(f, "I/O error: {}", e),
        }
    }
}

impl std::error::Error for InferError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            InferError::PerlConfig(e) => Some(e),
            InferError::ApidocResolve(e) => Some(e),
            InferError::Compile(e) => Some(e),
            InferError::Io(e) => Some(e),
        }
    }
}

impl From<PerlConfigError> for InferError {
    fn from(e: PerlConfigError) -> Self {
        InferError::PerlConfig(e)
    }
}

impl From<ApidocResolveError> for InferError {
    fn from(e: ApidocResolveError) -> Self {
        InferError::ApidocResolve(e)
    }
}

impl From<EnrichedCompileError> for InferError {
    fn from(e: EnrichedCompileError) -> Self {
        InferError::Compile(e)
    }
}

impl From<std::io::Error> for InferError {
    fn from(e: std::io::Error) -> Self {
        InferError::Io(e)
    }
}

/// 型推論の設定
#[derive(Debug, Clone)]
pub struct InferConfig {
    /// 入力ファイル(wrapper.h など)
    pub input_file: PathBuf,
    /// apidoc ファイルのパス(省略時は自動検索)
    pub apidoc_path: Option<PathBuf>,
    /// Rust バインディングファイルのパス
    pub bindings_path: Option<PathBuf>,
    /// apidoc ディレクトリの検索パス(省略時は自動検索)
    pub apidoc_dir: Option<PathBuf>,
    /// デバッグ出力
    pub debug: bool,
}

impl InferConfig {
    /// 入力ファイルのみを指定した最小構成
    pub fn new(input_file: PathBuf) -> Self {
        Self {
            input_file,
            apidoc_path: None,
            bindings_path: None,
            apidoc_dir: None,
            debug: false,
        }
    }

    /// apidoc パスを設定
    pub fn with_apidoc(mut self, path: PathBuf) -> Self {
        self.apidoc_path = Some(path);
        self
    }

    /// bindings パスを設定
    pub fn with_bindings(mut self, path: PathBuf) -> Self {
        self.bindings_path = Some(path);
        self
    }

    /// apidoc ディレクトリを設定
    pub fn with_apidoc_dir(mut self, path: PathBuf) -> Self {
        self.apidoc_dir = Some(path);
        self
    }

    /// デバッグモードを設定
    pub fn with_debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }
}

/// デバッグ出力オプション
///
/// パイプラインの特定の段階でデータ構造をダンプして早期終了するためのオプション。
#[derive(Debug, Clone, Default)]
pub struct DebugOptions {
    /// apidoc マージ後にダンプして終了
    /// Some(filter) でフィルタ指定(正規表現)、Some("") で全件出力
    pub dump_apidoc_after_merge: Option<String>,
    /// 型推論デバッグ対象のマクロ名リスト
    pub debug_type_inference: Vec<String>,
}

impl DebugOptions {
    pub fn new() -> Self {
        Self::default()
    }

    /// apidoc マージ後にダンプして終了するオプションを設定
    pub fn dump_apidoc(mut self, filter: impl Into<String>) -> Self {
        self.dump_apidoc_after_merge = Some(filter.into());
        self
    }
}

/// 共通フィールドマクロ (`_XPV_HEAD` / `_XPVCV_COMMON` 等) の本体を
/// `#define` の時点で捕獲する `MacroDefCallback`。
///
/// これらのマクロは perl のヘッダ(perl.h, sv.h)で `#undef` されてから
/// 利用が終わるため、最終的な MacroTable には残らない。`on_macro_defined`
/// で本体を保存しておくことで Phase 2 後にもアクセスできる。
struct CommonMacroBodyCollector {
    targets: HashSet<InternedStr>,
    bodies: HashMap<InternedStr, Vec<crate::token::Token>>,
}

impl CommonMacroBodyCollector {
    fn new(targets: HashSet<InternedStr>) -> Self {
        Self { targets, bodies: HashMap::new() }
    }
}

impl MacroDefCallback for CommonMacroBodyCollector {
    fn on_macro_defined(&mut self, def: &crate::macro_def::MacroDef) {
        if self.targets.contains(&def.name) {
            self.bodies.insert(def.name, def.body.clone());
        }
    }
    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any> { self }
}

/// 統計情報
#[derive(Debug, Clone, Default)]
pub struct InferStats {
    /// コメントから収集した apidoc 数
    pub apidoc_from_comments: usize,
    /// THX 依存マクロ数
    pub thx_dependent_count: usize,
    /// 収集された C 関数宣言数
    pub c_fn_decl_count: usize,
    /// THX 依存の C 関数数
    pub c_fn_thx_count: usize,
}

/// 型推論の結果
pub struct InferResult {
    /// マクロ推論コンテキスト(全マクロの解析結果)
    pub infer_ctx: MacroInferContext,
    /// フィールド辞書
    pub fields_dict: FieldsDict,
    /// Enum 辞書
    pub enum_dict: EnumDict,
    /// インライン関数辞書
    pub inline_fn_dict: InlineFnDict,
    /// Apidoc 辞書
    pub apidoc: ApidocDict,
    /// Rust 宣言辞書
    pub rust_decl_dict: Option<RustDeclDict>,
    /// C 関数宣言辞書
    pub c_fn_decl_dict: CFnDeclDict,
    /// typedef 辞書
    pub typedefs: TypedefDict,
    /// global static const 配列宣言辞書(bodies_by_type 等)
    pub global_const_dict: crate::global_const_dict::GlobalConstDict,
    /// apidoc patches(perl C ヘッダ既知バグの訂正データ)
    pub apidoc_patches: crate::apidoc_patches::ApidocPatchSet,
    /// 対象 perl の build mode(threaded / non-threaded)
    pub perl_build_mode: crate::perl_config::PerlBuildMode,
    /// PERLVAR 観測辞書 (Phase 1 で収集、Phase 3 で `PL_xxx!()` 出力に使う)。
    /// Pipeline で `with_perlvar_collection(false)` した場合は空。
    pub perlvar_dict: crate::perlvar_dict::PerlvarDict,
    /// プリプロセッサ(マクロテーブル、StringInterner、FileRegistry へのアクセス用)
    pub preprocessor: Preprocessor,
    /// 統計情報
    pub stats: InferStats,
}

/// 既存の Preprocessor を使ってマクロ型推論を実行
///
/// Preprocessor が既に初期化されている場合に使用。
/// 主に Pipeline の内部実装から呼び出される。
///
/// **Note**: 新しいコードでは `Pipeline` API の使用を推奨します。
/// この関数は Pipeline の内部実装で使用されており、直接呼び出す必要は
/// 通常ありません。
///
/// `debug_opts` が指定され、デバッグダンプで早期終了した場合は `Ok(None)` を返す。
pub fn run_inference_with_preprocessor(
    mut pp: Preprocessor,
    apidoc_path: Option<&Path>,
    bindings_path: Option<&Path>,
    debug_opts: Option<&DebugOptions>,
    skip_codegen_lists: &[PathBuf],
    perl_build_mode_override: Option<crate::perl_config::PerlBuildMode>,
) -> Result<Option<InferResult>, InferError> {
    // Perl build mode を確定(明示指定があれば優先、なければ auto-detect)
    let perl_build_mode = match perl_build_mode_override {
        Some(m) => m,
        None => crate::perl_config::PerlBuildMode::detect_from_perl_config()
            .unwrap_or(crate::perl_config::PerlBuildMode::Threaded),
    };
    eprintln!("[perl-mode] {:?}", perl_build_mode);
    // RustDeclDict をロード(パーサー作成前に行い、展開抑制を設定)
    let rust_decl_dict = if let Some(path) = bindings_path {
        Some(RustDeclDict::parse_file(path)?)
    } else {
        None
    };

    // bindings.rs の定数名を展開抑制に登録
    if let Some(ref dict) = rust_decl_dict {
        for name in dict.consts.keys() {
            let interned = pp.interner_mut().intern(name);
            pp.add_skip_expand_macro(interned);
        }
        // bindgen 生成の anonymous union 型名 (`pmop__bindgen_ty_2` 等) を
        // intern しておくことで、後段の型推論で
        // `from_apidoc_string` 経由の `TypedefName` 解決が可能になる。
        dict.intern_names(pp.interner_mut());
    }

    // 明示展開マクロを Preprocessor に登録(wrapped_macros の引数展開用)
    // SvANY, SvFLAGS など、preserve_function_macros モードでも展開するマクロ
    {
        let explicit_expand = ExplicitExpandSymbols::new(pp.interner_mut());
        pp.add_explicit_expand_macros(explicit_expand.iter());
    }

    // フィールド辞書を作成(パースしながら収集)
    let mut fields_dict = FieldsDict::new();
    let mut global_const_dict = crate::global_const_dict::GlobalConstDict::new();

    // Enum 辞書を作成(パースしながら収集)
    let mut enum_dict = EnumDict::new();

    // ApidocCollector を Preprocessor に設定
    pp.set_comment_callback(Box::new(ApidocCollector::new()));

    // _SV_HEAD マクロ呼び出しを監視
    let sv_head_id = pp.interner_mut().intern("_SV_HEAD");
    pp.set_macro_called_callback(sv_head_id, Box::new(MacroCallWatcher::new()));

    // 共通フィールド宣言マクロ(perl5 専用ハードコード)。
    // `_SV_HEAD` と同様、struct 通過時に Watcher を見て使用関係を fields_dict
    // に記録する。新規追加はこのリストに 1 行足すだけで良い。
    //
    // また、これらのマクロは perl.h / sv.h で `#undef` されるため、最終的な
    // MacroTable には残らない。本体(フィールド宣言列)は
    // `CommonMacroBodyCollector` が `#define` 時点で捕獲する。
    const COMMON_FIELD_MACROS: &[&str] = &["_XPV_HEAD", "_XPVCV_COMMON"];
    let common_field_macro_ids: Vec<InternedStr> = COMMON_FIELD_MACROS
        .iter()
        .map(|name| {
            let id = pp.interner_mut().intern(name);
            pp.set_macro_called_callback(id, Box::new(MacroCallWatcher::new()));
            id
        })
        .collect();
    pp.set_macro_def_callback(Box::new(CommonMacroBodyCollector::new(
        common_field_macro_ids.iter().copied().collect(),
    )));

    // pTHX_ と pTHX マクロ呼び出しを監視(関数宣言の THX 依存検出用)
    //
    // 非 threaded perl では `pTHX_` / `pTHX` は空マクロに展開される。
    // しかし `set_macro_called_callback` はマクロが呼び出された事実を
    // 記録するため、展開結果が空でも is_thx=true が立ってしまう。
    // それをそのまま codegen に渡すと「存在しない my_perl 引数」を
    // 注入する破綻を起こすので、threaded mode のときだけ callback を
    // 登録する(non-threaded では誰も THX 依存にならない)。
    let pthx_id = pp.interner_mut().intern("pTHX_");
    let pthx_no_comma_id = pp.interner_mut().intern("pTHX");
    if perl_build_mode.is_threaded() {
        pp.set_macro_called_callback(pthx_id, Box::new(MacroCallWatcher::new()));
        pp.set_macro_called_callback(pthx_no_comma_id, Box::new(MacroCallWatcher::new()));
    }

    // C 関数宣言辞書を作成
    let mut c_fn_decl_dict = CFnDeclDict::new();

    // パーサー作成
    let mut parser = match Parser::new(&mut pp) {
        Ok(p) => p,
        Err(e) => return Err(InferError::Compile(e.with_files(pp.files()))),
    };

    // inline 関数辞書を作成
    let mut inline_fn_dict = InlineFnDict::new();

    // parse_each_with_pp でフィールド辞書と inline 関数を収集
    // 同時に _SV_HEAD マクロ呼び出しを検出して SV ファミリーを動的に構築
    // また、関数宣言を収集して THX 依存性を検出
    let parse_result = parser.parse_each_with_pp(|decl, loc, path, pp| {
        let interner = pp.interner();
        fields_dict.collect_from_external_decl(decl, decl.is_target(), interner);

        // global static const declarations を捕捉
        // 例: `static const struct body_details bodies_by_type[] = {...}`
        global_const_dict.try_collect(decl, decl.is_target(), interner);

        // enum 情報を収集
        enum_dict.collect_from_external_decl(decl, decl.is_target(), interner);

        // inline 関数を収集
        if decl.is_target() {
            if let ExternalDecl::FunctionDef(func_def) = decl {
                inline_fn_dict.collect_from_function_def(func_def, interner);
            }
        }

        // 関数宣言を収集(THX 依存性検出用)
        if let ExternalDecl::Declaration(declaration) = decl {
            // pTHX_ または pTHX が呼ばれたかチェック
            let is_thx = check_macro_called(pp, pthx_id) || check_macro_called(pp, pthx_no_comma_id);

            // 関数宣言を収集
            collect_function_declarations(
                declaration,
                &mut c_fn_decl_dict,
                is_thx,
                loc,
                path,
                interner,
            );

            // フラグをリセット(次の宣言のために)
            reset_macro_called(pp, pthx_id);
            reset_macro_called(pp, pthx_no_comma_id);
        }

        // 構造体定義の場合、_SV_HEAD と共通フィールドマクロのフラグをチェック
        if decl.is_target() {
            if let Some(struct_names) = extract_struct_names(decl) {
                // _SV_HEAD が呼ばれていたら SV ファミリーに追加
                if let Some(cb) = pp.get_macro_called_callback(sv_head_id) {
                    if let Some(watcher) = cb.as_any().downcast_ref::<MacroCallWatcher>() {
                        if watcher.take_called() {
                            // _SV_HEAD(typeName) の引数を取得
                            let type_name = watcher.last_args()
                                .and_then(|args| args.first().cloned())
                                .unwrap_or_default();

                            for name in &struct_names {
                                // typeName → 構造体名マッピングも同時に登録
                                fields_dict.add_sv_family_member_with_type(*name, &type_name);
                            }
                        }
                    }
                }

                // 共通フィールドマクロ (_XPV_HEAD, _XPVCV_COMMON 等) の使用を記録
                for &macro_id in &common_field_macro_ids {
                    if let Some(cb) = pp.get_macro_called_callback(macro_id) {
                        if let Some(watcher) = cb.as_any().downcast_ref::<MacroCallWatcher>() {
                            if watcher.take_called() {
                                for name in &struct_names {
                                    fields_dict.add_struct_uses_common_macro(*name, macro_id);
                                }
                            }
                        }
                    }
                }
            }
        }
        ControlFlow::Continue(())
    });
    if let Err(e) = parse_result {
        // parser を drop して pp の借用を解放してから enrich する
        drop(parser);
        return Err(InferError::Compile(e.with_files(pp.files())));
    }

    // パーサーから typedef 辞書を取得
    let typedefs = parser.typedefs().clone();

    // コールバックを取り出してダウンキャスト
    let callback = pp.take_comment_callback().expect("callback should exist");
    let apidoc_collector = callback
        .into_any()
        .downcast::<ApidocCollector>()
        .expect("callback type mismatch");

    // token 型マクロを intern して InternedStr のベクターに変換
    // (apidoc から検出されたトークン合成マクロ、例: XopENTRYCUSTOM)
    let token_type_macros: Vec<InternedStr> = apidoc_collector
        .token_type_macros()
        .iter()
        .map(|name| pp.interner_mut().intern(name))
        .collect();

    // 一致型キャッシュを構築(全フィールドについて型の一貫性を事前計算)
    fields_dict.build_consistent_type_cache(pp.interner());

    // 共通フィールドマクロの canonical field set を構築(B-2)。
    // B-1 で観測対象として登録した各マクロの本体を struct member 列として
    // パースし、フィールド名と関数ポインタ判定を `FieldsDict.common_macros`
    // と `field_to_defining_macro` に格納する。
    {
        let collector = pp
            .take_macro_def_callback()
            .and_then(|cb| cb.into_any().downcast::<CommonMacroBodyCollector>().ok());
        let mut macro_bodies: Vec<(InternedStr, Vec<crate::token::Token>)> = collector
            .map(|c| c.bodies.into_iter().collect())
            .unwrap_or_default();
        // perl 共通マクロ本体内に現れる `pTHX_` / `pTHX` トークンは関数ポインタ
        // シグネチャ内のスレッド対応マクロ。本体パース時は意味的に空に展開
        // されるべきなのでトークンレベルで除去する。
        let pthx_id = pp.interner_mut().intern("pTHX_");
        let pthx_no_comma_id = pp.interner_mut().intern("pTHX");
        for (_id, body) in macro_bodies.iter_mut() {
            body.retain(|t| !matches!(&t.kind,
                crate::token::TokenKind::Ident(id)
                    if *id == pthx_id || *id == pthx_no_comma_id));
        }
        let interner = pp.interner();
        let files = pp.files().clone();
        let typedefs_ref = typedefs.clone();
        fields_dict.build_common_macro_fields(&macro_bodies, |body| {
            crate::parser::parse_struct_members_from_tokens_ref(
                body, interner, &files, &typedefs_ref,
            ).map_err(crate::error::CompileError::from)
        });
    }

    // 共通フィールドマクロ宣言フィールド名 → bindings.rs 由来の Rust 型
    // のマッピングを構築。`CvXSUB` の戻り値型のような無名 union メンバ
    // への型解決に使う。
    if let Some(ref dict) = rust_decl_dict {
        fields_dict.build_common_field_rust_types(dict, pp.interner_mut());
    }

    // 共通フィールドマクロ → 一意な SV ファミリー typedef の事前マッピング
    // を構築。`CvHASGV(cv)` のように `_XPVCV_COMMON` 由来フィールドへの
    // アクセス経路から `cv: *const CV` を逆推論するために使う。
    fields_dict.build_common_macro_sv_family(pp.interner());

    // sv_u フィールド型は parse_each で動的に収集済み
    // (SV ファミリー構造体の sv_u union から自動検出)

    // Apidoc をロード(ファイルから + コメントから)
    let mut apidoc = if let Some(path) = apidoc_path {
        ApidocDict::load_auto(path)?
    } else {
        ApidocDict::new()
    };
    let apidoc_from_comments = apidoc_collector.len();
    apidoc_collector.merge_into(&mut apidoc);

    // apidoc patches を適用(merge 後 / type macro 展開前)
    // perl の C ヘッダや apidoc に含まれる既知の誤りを訂正する。
    // 2 段マージ:
    //   1. <apidoc dir>/common.patches.json     ← 全バージョン共通
    //   2. <apidoc dir>/v$major.$minor.patches.json ← 当該バージョン固有
    // 両方とも存在しなければ no-op。
    let mut apidoc_patches = if let Some(path) = apidoc_path {
        crate::apidoc_patches::ApidocPatchSet::load_for_apidoc_path(path)?
    } else {
        crate::apidoc_patches::ApidocPatchSet::empty()
    };
    // テキスト形式の skip-list ファイルをマージ(同名は patches 側を優先)
    for list_path in skip_codegen_lists {
        let added = apidoc_patches.merge_skip_list(list_path)?;
        eprintln!(
            "[apidoc-patches] merged {} skip entry(ies) from {}",
            added, list_path.display()
        );
    }
    if !apidoc_patches.is_empty() {
        let applied = apidoc_patches.apply_to_apidoc(&mut apidoc);
        if !apidoc_patches.source_paths.is_empty() {
            let paths_str = apidoc_patches.source_paths.iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join(", ");
            eprintln!(
                "[apidoc-patches] loaded {} patch(es) from [{}] ({} return-type override applied, {} skip-codegen registered)",
                apidoc_patches.count(),
                paths_str,
                applied.len(),
                apidoc_patches.skip_codegen.len(),
            );
        }
    }

    // apidoc 内の型マクロを展開 (Off_t → off_t, Size_t → size_t など)
    apidoc.expand_type_macros(pp.macros(), pp.interner());

    // デバッグ: apidoc マージ後にダンプして早期終了
    if let Some(opts) = debug_opts {
        if let Some(filter) = &opts.dump_apidoc_after_merge {
            apidoc.dump_filtered(filter);
            return Ok(None);
        }
    }

    // MacroInferContext を作成して解析
    let mut infer_ctx = MacroInferContext::new();

    // デバッグ対象マクロを設定
    if let Some(opts) = debug_opts {
        if !opts.debug_type_inference.is_empty() {
            infer_ctx.set_debug_macros(opts.debug_type_inference.iter().cloned());
        }
    }

    // THX シンボルを事前に intern
    let sym_athx = pp.interner_mut().intern("aTHX");
    let sym_tthx = pp.interner_mut().intern("tTHX");
    let sym_my_perl = pp.interner_mut().intern("my_perl");
    let thx_symbols = (sym_athx, sym_tthx, sym_my_perl);

    // 展開を抑制するマクロシンボルを作成(assert など特殊処理用)
    let no_expand = NoExpandSymbols::new(pp.interner_mut());

    // 明示的に展開するマクロを Preprocessor に登録
    // (SvANY, SvFLAGS など + apidoc から検出した token 型マクロ)
    {
        let explicit_expand = ExplicitExpandSymbols::new(pp.interner_mut());
        pp.add_explicit_expand_macros(explicit_expand.iter());
    }
    pp.add_explicit_expand_macros(token_type_macros.iter().copied());

    infer_ctx.analyze_all_macros(
        &mut pp,
        Some(&apidoc),
        Some(&apidoc_patches),
        Some(&fields_dict),
        rust_decl_dict.as_ref(),
        Some(&mut inline_fn_dict),
        Some(&c_fn_decl_dict),
        &typedefs,
        thx_symbols,
        no_expand,
        perl_build_mode,
    );

    // THX 依存マクロ数をカウント
    let thx_dependent_count = infer_ctx.macros.values()
        .filter(|info| info.is_target && info.is_thx_dependent)
        .count();

    // C 関数宣言の統計
    let c_fn_decl_count = c_fn_decl_dict.len();
    let c_fn_thx_count = c_fn_decl_dict.thx_count();

    let stats = InferStats {
        apidoc_from_comments,
        thx_dependent_count,
        c_fn_decl_count,
        c_fn_thx_count,
    };

    // Phase 2 最終パス: パラメータ/戻り値型の確定(const/mut, bool)
    infer_ctx.resolve_param_and_return_types(
        pp.interner_mut(),
        rust_decl_dict.as_ref(),
        &inline_fn_dict,
    );

    Ok(Some(InferResult {
        infer_ctx,
        fields_dict,
        enum_dict,
        inline_fn_dict,
        apidoc,
        rust_decl_dict,
        c_fn_decl_dict,
        typedefs,
        global_const_dict,
        apidoc_patches,
        perl_build_mode,
        // Default: empty. Pipeline overwrites this with the collected dict
        // before returning the result.
        perlvar_dict: crate::perlvar_dict::PerlvarDict::new(),
        preprocessor: pp,
        stats,
    }))
}

/// 宣言から構造体名を抽出
fn extract_struct_names(decl: &ExternalDecl) -> Option<Vec<InternedStr>> {
    let declaration = match decl {
        ExternalDecl::Declaration(d) => d,
        _ => return None,
    };

    let mut names = Vec::new();

    for type_spec in &declaration.specs.type_specs {
        match type_spec {
            TypeSpec::Struct(spec) | TypeSpec::Union(spec) => {
                // メンバーリストを持つ定義のみ(前方宣言は除外)
                if spec.members.is_some() {
                    if let Some(name) = spec.name {
                        names.push(name);
                    }
                }
            }
            _ => {}
        }
    }

    if names.is_empty() {
        None
    } else {
        Some(names)
    }
}

/// MacroCallWatcher の呼び出しフラグをチェック
fn check_macro_called(pp: &Preprocessor, macro_id: InternedStr) -> bool {
    pp.get_macro_called_callback(macro_id)
        .and_then(|cb| cb.as_any().downcast_ref::<MacroCallWatcher>())
        .is_some_and(|w| w.was_called())
}

/// MacroCallWatcher のフラグをリセット
fn reset_macro_called(pp: &Preprocessor, macro_id: InternedStr) {
    // take_called() は Cell を使っているので &self で動作する
    if let Some(cb) = pp.get_macro_called_callback(macro_id) {
        if let Some(w) = cb.as_any().downcast_ref::<MacroCallWatcher>() {
            w.take_called(); // フラグを消費してリセット
        }
    }
}

/// 宣言から関数宣言を収集
fn collect_function_declarations(
    declaration: &crate::ast::Declaration,
    dict: &mut CFnDeclDict,
    is_thx: bool,
    loc: &crate::source::SourceLocation,
    path: &std::path::Path,
    interner: &crate::intern::StringInterner,
) {
    // 各宣言子を処理
    for init_decl in &declaration.declarators {
        let declarator = &init_decl.declarator;

        // 関数宣言かどうかをチェック(DerivedDecl::Function があるか)
        let param_list = declarator.derived.iter().find_map(|d| {
            if let DerivedDecl::Function(params) = d {
                Some(params)
            } else {
                None
            }
        });

        if let Some(param_list) = param_list {
            if let Some(name) = declarator.name {
                // パラメータを抽出
                let params: Vec<CParam> = param_list.params.iter().map(|param| {
                    let param_name = param.declarator.as_ref().and_then(|d| d.name);
                    let ty = type_specs_to_string(&param.specs, interner);
                    CParam { name: param_name, ty }
                }).collect();

                // 戻り値の型を抽出
                let ret_ty = type_specs_to_string(&declaration.specs, interner);

                let c_fn_decl = CFnDecl {
                    name,
                    params,
                    ret_ty,
                    is_thx,
                    is_target: declaration.is_target,
                    location: Some(format!("{}:{}", path.display(), loc.line)),
                };
                dict.insert(c_fn_decl);
            }
        }
    }
}

/// DeclSpecs から型の文字列表現を生成(シンプルな実装)
fn type_specs_to_string(specs: &crate::ast::DeclSpecs, interner: &crate::intern::StringInterner) -> String {
    use crate::ast::TypeSpec;

    let mut parts = Vec::new();

    for type_spec in &specs.type_specs {
        match type_spec {
            TypeSpec::Void => parts.push("void".to_string()),
            TypeSpec::Char => parts.push("char".to_string()),
            TypeSpec::Short => parts.push("short".to_string()),
            TypeSpec::Int => parts.push("int".to_string()),
            TypeSpec::Long => parts.push("long".to_string()),
            TypeSpec::Float => parts.push("float".to_string()),
            TypeSpec::Double => parts.push("double".to_string()),
            TypeSpec::Signed => parts.push("signed".to_string()),
            TypeSpec::Unsigned => parts.push("unsigned".to_string()),
            TypeSpec::Bool => parts.push("bool".to_string()),
            TypeSpec::Complex => parts.push("_Complex".to_string()),
            TypeSpec::TypedefName(name) => parts.push(interner.get(*name).to_string()),
            TypeSpec::Struct(spec) => {
                if let Some(name) = spec.name {
                    parts.push(format!("struct {}", interner.get(name)));
                } else {
                    parts.push("struct".to_string());
                }
            }
            TypeSpec::Union(spec) => {
                if let Some(name) = spec.name {
                    parts.push(format!("union {}", interner.get(name)));
                } else {
                    parts.push("union".to_string());
                }
            }
            TypeSpec::Enum(spec) => {
                if let Some(name) = spec.name {
                    parts.push(format!("enum {}", interner.get(name)));
                } else {
                    parts.push("enum".to_string());
                }
            }
            TypeSpec::TypeofExpr(_) => parts.push("typeof(...)".to_string()),
            TypeSpec::Int128 => parts.push("__int128".to_string()),
            TypeSpec::Float16 => parts.push("_Float16".to_string()),
            TypeSpec::Float32 => parts.push("_Float32".to_string()),
            TypeSpec::Float64 => parts.push("_Float64".to_string()),
            TypeSpec::Float128 => parts.push("_Float128".to_string()),
            TypeSpec::Float32x => parts.push("_Float32x".to_string()),
            TypeSpec::Float64x => parts.push("_Float64x".to_string()),
        }
    }

    if parts.is_empty() {
        "int".to_string() // デフォルトは int
    } else {
        parts.join(" ")
    }
}