cppshift 0.1.1

CPP parser and transpiler
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
use std::collections::HashMap;

use proc_macro2::TokenStream;
use quote::ToTokens as _;
use serde::Deserialize;
use serde::de::{self, MapAccess, Visitor};

use crate::SourceCodeSpan as _;
use crate::ast::ItemTypedef;
use crate::ast::expr::{Expr, ExprLit, LitKind};
use crate::ast::item::{ItemConst, ItemStatic, Path};
use crate::ast::ty::{FundamentalKind, TemplateArg, Type};
use crate::transpile::{Transpile, TranspileContext, Transpiler};

use super::error::TranspileError;

impl From<FundamentalKind> for syn::Type {
    fn from(kind: FundamentalKind) -> Self {
        use FundamentalKind::*;
        let s = match kind {
            Void => "()",
            Bool => "bool",
            Char | Char8 | Char16 | Char32 | Wchar => "char",
            UnsignedChar => "u8",
            UnsignedShort => "u16",
            UnsignedInt => "u32",
            Short => "i16",
            Int => "i32",
            Long | LongLong => "i64",
            Float => "f32",
            Double | LongDouble => "f64",
            SignedChar => "i8",
            UnsignedLong | UnsignedLongLong => "u64",
        };
        syn::parse_str(s).unwrap()
    }
}

/// Configurable mapper from C++ AST types to `syn::Type`.
///
/// Built via [`TypeMapper::builder()`] or [`TypeMapper::new()`] (defaults only).
///
/// ```
/// use cppshift::transpile::TypeMapper;
/// use cppshift::ast::ty::{Type, TypeFundamental, FundamentalKind};
/// use cppshift::SourceSpan;
///
/// let mapper = TypeMapper::new();
/// let src = "int";
/// let ty = Type::Fundamental(TypeFundamental {
///     span: SourceSpan::new(src, 0, 3),
///     kind: FundamentalKind::Int,
/// });
/// let rust_ty = mapper.map_type(&ty).expect("fundamental types always map");
/// assert_eq!(quote::quote!(#rust_ty).to_string(), "i32");
/// ```
#[derive(Debug, Clone)]
pub struct TypeMapper {
    paths: HashMap<String, syn::Type>,
}

/// Builder for [`TypeMapper`].
pub struct TypeMapperBuilder {
    paths: HashMap<String, syn::Type>,
}

impl TypeMapper {
    /// Create a builder for configuring type mappings.
    pub fn builder() -> TypeMapperBuilder {
        TypeMapperBuilder {
            paths: HashMap::new(),
        }
    }

    /// Create a mapper with default fundamental type mappings only.
    pub fn new() -> Self {
        Self::builder().build()
    }

    /// Map a C++ AST type to a `syn::Type`.
    ///
    /// # Errors
    ///
    /// Returns [`TranspileError`] if the type cannot be mapped (e.g. unknown path,
    /// `auto`, `decltype`, unsized array).
    pub fn map_type(&self, ty: &Type<'_>) -> Result<syn::Type, TranspileError> {
        match ty {
            Type::Fundamental(f) => Ok(syn::Type::from(f.kind)),
            Type::Path(p) => self.resolve_path(&p.path),
            Type::Ptr(p) => {
                let inner = self.map_type(&p.pointee)?;
                if p.cv.const_token {
                    Ok(syn::parse_quote!(*const #inner))
                } else {
                    Ok(syn::parse_quote!(*mut #inner))
                }
            }
            Type::Reference(r) => {
                let inner = self.map_type(&r.referent)?;
                if r.cv.const_token {
                    Ok(syn::parse_quote!(&#inner))
                } else {
                    Ok(syn::parse_quote!(&mut #inner))
                }
            }
            Type::RvalueReference(r) => self.map_type(&r.referent),
            Type::Array(a) => {
                let inner = self.map_type(&a.element)?;
                match &a.size {
                    Some(Expr::Lit(lit)) if lit.kind == LitKind::Integer => {
                        let n: usize =
                            lit.span.src().parse().map_err(|_| {
                                unsupported_from_type("invalid array size literal", ty)
                            })?;
                        let lit_n =
                            syn::LitInt::new(&n.to_string(), proc_macro2::Span::call_site());
                        Ok(syn::parse_quote!([#inner; #lit_n]))
                    }
                    _ => Err(unsupported_from_type("unsized or dynamic array", ty)),
                }
            }
            Type::FnPtr(f) => {
                let ret = self.map_type(&f.return_type)?;
                let params: Result<Vec<syn::Type>, _> =
                    f.params.iter().map(|p| self.map_type(p)).collect();
                let params = params?;
                Ok(syn::parse_quote!(fn(#(#params),*) -> #ret))
            }
            Type::Qualified(q) => self.map_type(&q.ty),
            Type::TemplateInst(t) => {
                let base_ty = self.resolve_path(&t.path)?;
                let mapped_args: Result<Vec<syn::Type>, _> = t
                    .args
                    .iter()
                    .map(|arg| match arg {
                        TemplateArg::Type(ty) => self.map_type(ty),
                        TemplateArg::Expr(_) => {
                            Err(unsupported_from_type("expression template argument", ty))
                        }
                    })
                    .collect();
                let mapped_args = mapped_args?;

                let mut result = base_ty;
                if let syn::Type::Path(ref mut type_path) = result
                    && let Some(last_seg) = type_path.path.segments.last_mut()
                {
                    last_seg.arguments =
                        syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
                            colon2_token: None,
                            lt_token: syn::token::Lt::default(),
                            args: mapped_args
                                .into_iter()
                                .map(syn::GenericArgument::Type)
                                .collect(),
                            gt_token: syn::token::Gt::default(),
                        });
                }
                Ok(result)
            }
            Type::Auto(_) => Err(unsupported_from_type(
                "auto type cannot be mapped to Rust",
                ty,
            )),
            Type::Decltype(_) => Err(unsupported_from_type(
                "decltype cannot be mapped to Rust",
                ty,
            )),
        }
    }

    fn resolve_path(&self, path: &Path<'_>) -> Result<syn::Type, TranspileError> {
        let key = path.to_string();
        if let Some(ty) = self.paths.get(&key) {
            Ok(ty.clone())
        } else {
            syn::Type::try_from(path.clone()).map_err(|_| unmapped_path_error(&key, path))
        }
    }
}

impl Default for TypeMapper {
    fn default() -> Self {
        Self::new()
    }
}

impl<'de> Deserialize<'de> for TypeMapper {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct TypeMapperVisitor;

        impl<'de> Visitor<'de> for TypeMapperVisitor {
            type Value = TypeMapper;

            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("a map of C++ type paths to Rust type strings")
            }

            fn visit_map<M>(self, mut access: M) -> Result<TypeMapper, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut builder = TypeMapper::builder();
                while let Some((cpp_path, rust_type)) = access.next_entry::<String, String>()? {
                    builder = builder
                        .map_path(&cpp_path, &rust_type)
                        .map_err(de::Error::custom)?;
                }
                Ok(builder.build())
            }
        }

        deserializer.deserialize_map(TypeMapperVisitor)
    }
}

impl TypeMapperBuilder {
    /// Register a C++ path → Rust type mapping.
    ///
    /// The `rust_type` string is parsed via `syn::parse_str`.
    ///
    /// # Errors
    ///
    /// Returns [`TranspileError::InvalidRustType`] if `rust_type` is not valid Rust syntax.
    pub fn map_path(mut self, cpp_path: &str, rust_type: &str) -> Result<Self, TranspileError> {
        let ty: syn::Type =
            syn::parse_str(rust_type).map_err(|e| TranspileError::InvalidRustType {
                rust_type: rust_type.to_owned(),
                reason: e.to_string(),
            })?;
        self.paths.insert(cpp_path.to_owned(), ty);
        Ok(self)
    }

    /// Register a C++ path → Rust type mapping with a pre-built `syn::Type`.
    pub fn map_path_to_type(mut self, cpp_path: &str, ty: syn::Type) -> Self {
        self.paths.insert(cpp_path.to_owned(), ty);
        self
    }

    /// Build the [`TypeMapper`].
    pub fn build(self) -> TypeMapper {
        TypeMapper { paths: self.paths }
    }
}

/// Build an [`TranspileError::UnmappedPath`] from a path string and AST path.
fn unmapped_path_error(path_str: &str, path: &Path<'_>) -> TranspileError {
    let span = path.segments.first().map(|s| s.ident.span);
    match span {
        Some(span) => TranspileError::UnmappedPath {
            path: path_str.to_owned(),
            src: span.full_source().to_owned(),
            err_span: span.into(),
        },
        None => TranspileError::UnmappedPath {
            path: path_str.to_owned(),
            src: String::new(),
            err_span: miette::SourceSpan::new(0.into(), 0),
        },
    }
}

/// Build an [`TranspileError::UnsupportedType`] by extracting the best span from a [`Type`].
fn unsupported_from_type(message: &str, ty: &Type<'_>) -> TranspileError {
    match ty.span() {
        Some(span) => TranspileError::UnsupportedType {
            message: message.to_owned(),
            src: span.full_source().to_owned(),
            err_span: span.into(),
        },
        None => TranspileError::UnsupportedType {
            message: format!("{}: {:?}", message, ty),
            src: String::new(),
            err_span: miette::SourceSpan::new(0.into(), 0),
        },
    }
}

impl<'de> Transpile for Type<'de> {
    fn transpile(
        &self,
        transpiler: &Transpiler,
        _ctx: &mut TranspileContext,
        tokens: &mut TokenStream,
    ) -> Result<(), TranspileError> {
        transpiler.ty_mapper.map_type(self)?.to_tokens(tokens);
        Ok(())
    }
}

impl<'de> Transpile for ItemTypedef<'de> {
    fn transpile(
        &self,
        transpiler: &Transpiler,
        _ctx: &mut TranspileContext,
        tokens: &mut TokenStream,
    ) -> Result<(), TranspileError> {
        let name = self.ident;
        // char array typedefs → &str
        if let Type::Array(arr) = &self.ty
            && is_char_element_type(&arr.element)
        {
            tokens.extend(quote::quote! {
                #[doc = concat!(" Auto-transpiled type for ", stringify!(#name))]
                pub type #name = &str;
            });
        } else if let Type::Path(p) = &self.ty {
            let rust_ty = transpiler.ty_mapper.resolve_path(&p.path)?;
            tokens.extend(quote::quote! {
                #[doc = concat!(" Auto-transpiled type for ", stringify!(#name))]
                pub type #name = #rust_ty;
            });
        } else {
            let rust_ty = transpiler.ty_mapper.map_type(&self.ty)?;
            tokens.extend(quote::quote! {
                #[doc = concat!(" Auto-transpiled type for ", stringify!(#name))]
                pub type #name = #rust_ty;
            });
        }

        Ok(())
    }
}

/// Returns `true` if `ty` is a byte-sized char type (char, char8_t, unsigned char, signed char),
/// stripping CV-qualifiers.
fn is_char_element_type(ty: &Type<'_>) -> bool {
    use FundamentalKind::*;
    match ty {
        Type::Fundamental(f) => matches!(f.kind, Char | Char8 | Char16 | Char32 | Wchar),
        Type::Qualified(q) => is_char_element_type(&q.ty),
        _ => false,
    }
}

/// Try to transpile an unsized char array initialised with a string literal.
///
/// C++: `const char foo[] = "ALPN";` / `static char foo[] = "ALPN";`
/// Rust: `pub static foo: &str = "ALPN";`
///
/// `keyword` is the Rust storage keyword to emit (`const` or `static`).
/// Returns `None` if the pattern doesn't match and normal mapping should proceed.
fn try_transpile_char_array_from_str_lit<'de>(
    name: crate::ast::item::Ident<'de>,
    element: &Type<'de>,
    expr: &Expr<'de>,
    transpiler: &Transpiler,
    ctx: &mut TranspileContext,
    keyword: &str,
    tokens: &mut TokenStream,
) -> Option<Result<(), TranspileError>> {
    if !is_char_element_type(element) {
        return None;
    }
    let Expr::Lit(ExprLit {
        kind: LitKind::String,
        ..
    }) = expr
    else {
        return None;
    };

    let mut expr_tokens = TokenStream::new();
    if let Err(e) = expr.transpile(transpiler, ctx, &mut expr_tokens) {
        return Some(Err(e));
    }

    let keyword_tok: proc_macro2::TokenStream = keyword.parse().unwrap();
    tokens.extend(quote::quote! {
        pub #keyword_tok #name: &str = #expr_tokens;
    });
    Some(Ok(()))
}

impl<'de> Transpile for ItemConst<'de> {
    fn transpile(
        &self,
        transpiler: &Transpiler,
        ctx: &mut TranspileContext,
        tokens: &mut TokenStream,
    ) -> Result<(), TranspileError> {
        let name = self.ident;

        // Special case: `const char foo[] = "ALPN";` → `pub const foo: [u8; 5] = *b"ALPN\0";`
        if let Type::Array(arr) = &self.ty
            && arr.size.is_none()
            && let Some(result) = try_transpile_char_array_from_str_lit(
                name,
                &arr.element,
                &self.expr,
                transpiler,
                ctx,
                "const",
                tokens,
            )
        {
            return result;
        }

        let mut expr_tokens = TokenStream::new();
        self.expr.transpile(transpiler, ctx, &mut expr_tokens)?;

        match &self.expr {
            // C++ string constants with string literal init → `&str`
            Expr::Lit(ExprLit {
                kind: LitKind::String,
                ..
            }) => {
                tokens.extend(quote::quote! {
                    #[doc = " Auto-transpiled &str const"]
                    pub const #name: &str = #expr_tokens;
                });
            }
            Expr::Lit(ExprLit { kind, .. }) => {
                let rust_ty = transpiler.ty_mapper.map_type(&self.ty)?;
                if kind.match_type(&self.ty) {
                    tokens.extend(quote::quote! {
                        #[doc = concat!(" Auto-transpiled const literal ", stringify!(#rust_ty))]
                        pub const #name: #rust_ty = #expr_tokens;
                    });
                } else {
                    tokens.extend(quote::quote! {
                        #[doc = concat!(" Auto-transpiled const literal ", stringify!(#rust_ty))]
                        pub const #name: #rust_ty = #expr_tokens as #rust_ty;
                    });
                }
            }
            _ => {
                let rust_ty = transpiler.ty_mapper.map_type(&self.ty)?;
                tokens.extend(quote::quote! {
                    #[doc = concat!(" Auto-transpiled const ", stringify!(#rust_ty))]
                    pub const #name: #rust_ty = #expr_tokens;
                });
            }
        }

        Ok(())
    }
}

impl<'de> Transpile for ItemStatic<'de> {
    fn transpile(
        &self,
        transpiler: &Transpiler,
        ctx: &mut TranspileContext,
        tokens: &mut TokenStream,
    ) -> Result<(), TranspileError> {
        let name = self.ident;
        let expr = self
            .expr
            .as_ref()
            .ok_or_else(|| TranspileError::UnsupportedExpr {
                message: "Rust statics require an initializer".to_owned(),
                src: name.span.full_source().to_owned(),
                err_span: name.span.into(),
            })?;

        // Special case: `static char foo[] = "ALPN";` → `pub static foo: [u8; 5] = *b"ALPN\0";`
        if let Type::Array(arr) = &self.ty
            && arr.size.is_none()
            && let Some(result) = try_transpile_char_array_from_str_lit(
                name,
                &arr.element,
                expr,
                transpiler,
                ctx,
                "static",
                tokens,
            )
        {
            return result;
        }

        let mut expr_tokens = TokenStream::new();
        expr.transpile(transpiler, ctx, &mut expr_tokens)?;

        match expr {
            // C++ string statics with string literal init → `&str`
            Expr::Lit(ExprLit {
                kind: LitKind::String,
                ..
            }) => {
                tokens.extend(quote::quote! {
                    #[doc = " Auto-transpiled &str static"]
                    pub static #name: &str = #expr_tokens;
                });
            }
            Expr::Lit(ExprLit { kind, .. }) => {
                let rust_ty = transpiler.ty_mapper.map_type(&self.ty)?;
                if kind.match_type(&self.ty) {
                    tokens.extend(quote::quote! {
                        #[doc = concat!(" Auto-transpiled static literal ", stringify!(#rust_ty))]
                        pub static #name: #rust_ty = #expr_tokens;
                    });
                } else {
                    tokens.extend(quote::quote! {
                        #[doc = concat!(" Auto-transpiled static literal ", stringify!(#rust_ty))]
                        pub static #name: #rust_ty = #expr_tokens as #rust_ty;
                    });
                }
            }
            _ => {
                let rust_ty = transpiler.ty_mapper.map_type(&self.ty)?;
                tokens.extend(quote::quote! {
                    #[doc = concat!(" Auto-transpiled static ", stringify!(#rust_ty))]
                    pub static #name: #rust_ty = #expr_tokens;
                });
            }
        }

        Ok(())
    }
}

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

    use crate::SourceSpan;
    use crate::ast::expr::ExprLit;
    use crate::ast::item::{Ident, PathSegment};
    use crate::ast::punct::Punctuated;
    use crate::ast::{parse_file, ty::*};

    fn ty_str(ty: &syn::Type) -> String {
        quote!(#ty).to_string()
    }

    fn make_fundamental(src: &str, kind: FundamentalKind) -> Type<'_> {
        Type::Fundamental(TypeFundamental {
            span: SourceSpan::new(src, 0, src.len()),
            kind,
        })
    }

    fn make_path<'a>(src: &'a str, segments: &[&'a str]) -> Type<'a> {
        Type::Path(TypePath {
            path: make_raw_path(src, segments),
        })
    }

    fn make_raw_path<'a>(src: &'a str, segments: &[&'a str]) -> Path<'a> {
        Path {
            leading_colon: false,
            segments: segments
                .iter()
                .map(|s| {
                    let offset = s.as_ptr() as usize - src.as_ptr() as usize;
                    PathSegment {
                        ident: Ident {
                            sym: s,
                            span: SourceSpan::new(src, offset, s.len()),
                        },
                    }
                })
                .collect(),
        }
    }

    #[test]
    fn typedef_transpiles() -> Result<(), TranspileError> {
        let transpiler = Transpiler {
            ty_mapper: TypeMapper::builder()
                .map_path("std::string", "BytesMut")?
                .build(),
            ..Default::default()
        };

        let typedef_header = r#"
            typedef Custom::int16 MyInt16;
            typedef std::string MyString;
            typedef char type24[3];
        "#;

        let typedef_file = parse_file(typedef_header).unwrap();
        let mut typedef_iter = typedef_file.items.iter();

        match typedef_iter.next() {
            Some(crate::ast::Item::Typedef(t)) => {
                assert_eq!(
                    "# [doc = concat ! (\" Auto-transpiled type for \" , stringify ! (MyInt16))] pub type MyInt16 = Custom :: int16 ;",
                    t.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string()
                );
            }
            t => panic!("unexpected typedef {t:?}"),
        };

        match typedef_iter.next() {
            Some(crate::ast::Item::Typedef(t)) => {
                assert_eq!(
                    "# [doc = concat ! (\" Auto-transpiled type for \" , stringify ! (MyString))] pub type MyString = BytesMut ;",
                    t.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string()
                );
            }
            t => panic!("unexpected typedef {t:?}"),
        };

        match typedef_iter.next() {
            Some(crate::ast::Item::Typedef(t)) => {
                assert_eq!(
                    "# [doc = concat ! (\" Auto-transpiled type for \" , stringify ! (type24))] pub type type24 = & str ;",
                    t.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string()
                );
            }
            t => panic!("unexpected typedef {t:?}"),
        };

        Ok(())
    }

    // ---- Fundamental types (table-driven) ----

    #[test]
    fn fundamental_defaults() -> Result<(), TranspileError> {
        use FundamentalKind::*;
        let mapper = TypeMapper::new();
        let cases: &[(FundamentalKind, &str, &str)] = &[
            (Void, "void", "()"),
            (Bool, "bool", "bool"),
            (Char, "char", "char"),
            (Char8, "char8_t", "char"),
            (Char16, "char16_t", "char"),
            (Char32, "char32_t", "char"),
            (Wchar, "wchar_t", "char"),
            (Short, "short", "i16"),
            (Int, "int", "i32"),
            (Long, "long", "i64"),
            (LongLong, "long long", "i64"),
            (Float, "float", "f32"),
            (Double, "double", "f64"),
            (LongDouble, "long double", "f64"),
            (SignedChar, "signed char", "i8"),
            (UnsignedChar, "unsigned char", "u8"),
            (UnsignedShort, "unsigned short", "u16"),
            (UnsignedInt, "unsigned int", "u32"),
            (UnsignedLong, "unsigned long", "u64"),
            (UnsignedLongLong, "unsigned long long", "u64"),
        ];
        for &(kind, src, expected) in cases {
            let ty = make_fundamental(src, kind);
            let result = mapper.map_type(&ty)?;
            assert_eq!(ty_str(&result), expected, "failed for {kind:?}");
        }
        Ok(())
    }

    // ---- Path mappings ----

    #[test]
    fn path_mapping_custom() -> Result<(), TranspileError> {
        let mapper = TypeMapper::builder()
            .map_path("Custom::int32", "i32")?
            .map_path("std::string", "String")?
            .build();

        let src = "Custom::int32";
        let ty = make_path(src, &[&src[..6], &src[8..]]);
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "i32");

        let src2 = "std::string";
        let ty2 = make_path(src2, &[&src2[..3], &src2[5..]]);
        assert_eq!(ty_str(&mapper.map_type(&ty2)?), "String");
        Ok(())
    }

    #[test]
    fn path_unknown_passes_through() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src = "Unknown";
        let ty = make_path(src, &[src]);
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "Unknown");
        Ok(())
    }

    // ---- Composite types ----

    #[test]
    fn const_ptr() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src = "int";
        let inner = make_fundamental(src, FundamentalKind::Int);
        let ty = Type::Ptr(TypePtr {
            cv: CvQualifiers {
                const_token: true,
                volatile_token: false,
            },
            pointee: Box::new(inner),
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "* const i32");
        Ok(())
    }

    #[test]
    fn mut_ptr() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src = "int";
        let inner = make_fundamental(src, FundamentalKind::Int);
        let ty = Type::Ptr(TypePtr {
            cv: CvQualifiers::default(),
            pointee: Box::new(inner),
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "* mut i32");
        Ok(())
    }

    #[test]
    fn reference_mut() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src = "int";
        let inner = make_fundamental(src, FundamentalKind::Int);
        let ty = Type::Reference(TypeReference {
            cv: CvQualifiers::default(),
            referent: Box::new(inner),
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "& mut i32");
        Ok(())
    }

    #[test]
    fn reference_const() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src = "int";
        let inner = make_fundamental(src, FundamentalKind::Int);
        let ty = Type::Reference(TypeReference {
            cv: CvQualifiers {
                const_token: true,
                volatile_token: false,
            },
            referent: Box::new(inner),
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "& i32");
        Ok(())
    }

    #[test]
    fn rvalue_reference() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src = "int";
        let inner = make_fundamental(src, FundamentalKind::Int);
        let ty = Type::RvalueReference(TypeRvalueReference {
            referent: Box::new(inner),
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "i32");
        Ok(())
    }

    #[test]
    fn array_with_size() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src_elem = "int";
        let src_size = "10";
        let inner = make_fundamental(src_elem, FundamentalKind::Int);
        let ty = Type::Array(TypeArray {
            element: Box::new(inner),
            size: Some(Expr::Lit(ExprLit {
                span: SourceSpan::new(src_size, 0, 2),
                kind: LitKind::Integer,
            })),
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "[i32 ; 10]");
        Ok(())
    }

    #[test]
    fn array_without_size() {
        let mapper = TypeMapper::new();
        let src = "int";
        let inner = make_fundamental(src, FundamentalKind::Int);
        let ty = Type::Array(TypeArray {
            element: Box::new(inner),
            size: None,
        });
        assert!(mapper.map_type(&ty).is_err());
    }

    // ---- CV-qualified ----

    #[test]
    fn cv_qualified_strips() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src = "int";
        let inner = make_fundamental(src, FundamentalKind::Int);
        let ty = Type::Qualified(TypeQualified {
            cv: CvQualifiers {
                const_token: true,
                volatile_token: false,
            },
            ty: Box::new(inner),
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "i32");
        Ok(())
    }

    // ---- Template instantiation ----

    #[test]
    fn template_inst_with_mapped_args() -> Result<(), TranspileError> {
        let mapper = TypeMapper::builder()
            .map_path("std::vector", "Vec")?
            .build();

        let path_src = "std::vector";
        let inner_src = "int";
        let inner = make_fundamental(inner_src, FundamentalKind::Int);
        let ty = Type::TemplateInst(TypeTemplateInst {
            path: make_raw_path(path_src, &[&path_src[..3], &path_src[5..]]),
            args: vec![TemplateArg::Type(inner)],
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "Vec < i32 >");
        Ok(())
    }

    #[test]
    fn template_inst_unknown_path_passes_through() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let path_src = "std::deque";
        let inner_src = "int";
        let inner = make_fundamental(inner_src, FundamentalKind::Int);
        let ty = Type::TemplateInst(TypeTemplateInst {
            path: make_raw_path(path_src, &[&path_src[..3], &path_src[5..]]),
            args: vec![TemplateArg::Type(inner)],
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "std :: deque < i32 >");
        Ok(())
    }

    #[test]
    fn template_inst_unmapped_arg_passes_through() -> Result<(), TranspileError> {
        let mapper = TypeMapper::builder()
            .map_path("std::vector", "Vec")?
            .build();

        let path_src = "std::vector";
        let inner_src = "Unknown";
        let inner = make_path(inner_src, &[inner_src]);
        let ty = Type::TemplateInst(TypeTemplateInst {
            path: make_raw_path(path_src, &[&path_src[..3], &path_src[5..]]),
            args: vec![TemplateArg::Type(inner)],
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "Vec < Unknown >");
        Ok(())
    }

    // ---- auto / decltype ----

    #[test]
    fn auto_returns_err() {
        let mapper = TypeMapper::new();
        let src = "auto";
        let ty = Type::Auto(TypeAuto {
            span: SourceSpan::new(src, 0, 4),
        });
        assert!(mapper.map_type(&ty).is_err());
    }

    #[test]
    fn decltype_returns_err() {
        let mapper = TypeMapper::new();
        let src = "x";
        let ty = Type::Decltype(TypeDecltype {
            expr: Expr::Ident(crate::ast::expr::ExprIdent {
                ident: Ident {
                    sym: src,
                    span: SourceSpan::new(src, 0, 1),
                },
            }),
        });
        assert!(mapper.map_type(&ty).is_err());
    }

    // ---- Inner type unknown in composite ----

    #[test]
    fn ptr_unknown_inner_passes_through() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let src = "Unknown";
        let inner = make_path(src, &[src]);
        let ty = Type::Ptr(TypePtr {
            cv: CvQualifiers::default(),
            pointee: Box::new(inner),
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "* mut Unknown");
        Ok(())
    }

    // ---- Function pointer ----

    #[test]
    fn fn_ptr() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let ret_src = "int";
        let p1_src = "double";
        let p2_src = "float";

        let ret = make_fundamental(ret_src, FundamentalKind::Int);
        let p1 = make_fundamental(p1_src, FundamentalKind::Double);
        let p2 = make_fundamental(p2_src, FundamentalKind::Float);

        let mut params = Punctuated::new();
        params.push_value(p1);
        params.push_value(p2);

        let ty = Type::FnPtr(TypeFnPtr {
            return_type: Box::new(ret),
            params,
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "fn (f64 , f32) -> i32");
        Ok(())
    }

    #[test]
    fn fn_ptr_unmapped_param_passes_through() -> Result<(), TranspileError> {
        let mapper = TypeMapper::new();
        let ret_src = "int";
        let p_src = "Unknown";

        let ret = make_fundamental(ret_src, FundamentalKind::Int);
        let p = make_path(p_src, &[p_src]);

        let mut params = Punctuated::new();
        params.push_value(p);

        let ty = Type::FnPtr(TypeFnPtr {
            return_type: Box::new(ret),
            params,
        });
        assert_eq!(ty_str(&mapper.map_type(&ty)?), "fn (Unknown) -> i32");
        Ok(())
    }

    // ---- Builder error ----

    #[test]
    fn builder_invalid_rust_type() {
        let result = TypeMapper::builder().map_path("foo", "not a {{ valid type");
        assert!(result.is_err());
    }

    // ---- Error diagnostics ----

    #[test]
    fn error_is_diagnostic() {
        let mapper = TypeMapper::new();
        let src = "auto";
        let ty = Type::Auto(TypeAuto {
            span: SourceSpan::new(src, 0, 4),
        });
        let err = mapper.map_type(&ty).unwrap_err();
        // TranspileError implements miette::Diagnostic
        let diagnostic: &dyn miette::Diagnostic = &err;
        assert!(diagnostic.source_code().is_some());
        assert!(diagnostic.labels().is_some());
    }

    // ---- ItemConst / ItemStatic transpilation ----

    #[test]
    fn const_int_transpiles() -> Result<(), TranspileError> {
        let transpiler = Transpiler::default();
        let src = "const int MAX = 100;\nconst int MyClass::MIN = 10;";
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Const(c) => {
                assert_eq!(
                    c.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string(),
                    "# [doc = concat ! (\" Auto-transpiled const literal \" , stringify ! (i32))] pub const MAX : i32 = 100 ;"
                );
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }
        match &file.items[1] {
            crate::ast::Item::Const(c) => {
                let class_path = c.class_path.as_ref().expect("expected class_path");
                assert_eq!(class_path.segments[0].ident.sym, "MyClass");
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }
        Ok(())
    }

    #[test]
    fn constexpr_transpiles() -> Result<(), TranspileError> {
        let transpiler = Transpiler::default();
        let src = "constexpr double PI = 3.14;";
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Const(c) => {
                assert_eq!(
                    c.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string(),
                    "# [doc = concat ! (\" Auto-transpiled const literal \" , stringify ! (f64))] pub const PI : f64 = 3.14 ;"
                );
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }
        Ok(())
    }

    #[test]
    fn const_bool_transpiles() -> Result<(), TranspileError> {
        let transpiler = Transpiler::default();
        let src = "const bool FLAG = true;";
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Const(c) => {
                assert_eq!(
                    c.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string(),
                    "# [doc = concat ! (\" Auto-transpiled const \" , stringify ! (bool))] pub const FLAG : bool = true ;"
                );
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }
        Ok(())
    }

    #[test]
    fn const_char_literal_casts() -> Result<(), TranspileError> {
        let transpiler = Transpiler::default();
        let src = "
            constexpr char CONST_CHAR_VALUE = 'W';
            constexpr CustomType CONST_CUSTOM_VALUE = 'W';";
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Const(c) => {
                assert_eq!(
                    c.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string(),
                    "# [doc = concat ! (\" Auto-transpiled const literal \" , stringify ! (char))] pub const CONST_CHAR_VALUE : char = 'W' ;"
                );
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }
        match &file.items[1] {
            crate::ast::Item::Const(c) => {
                assert_eq!(
                    c.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string(),
                    "# [doc = concat ! (\" Auto-transpiled const literal \" , stringify ! (CustomType))] pub const CONST_CUSTOM_VALUE : CustomType = 'W' as CustomType ;"
                );
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }
        Ok(())
    }

    #[test]
    fn const_string_uses_str_ref() -> Result<(), TranspileError> {
        let transpiler = Transpiler::default();
        let src = r#"constexpr string WRONG_RETURN_CODE = "404";"#;
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Const(c) => {
                assert_eq!(
                    c.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string(),
                    r#"# [doc = " Auto-transpiled &str const"] pub const WRONG_RETURN_CODE : & str = "404" ;"#
                );
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }
        Ok(())
    }

    #[test]
    fn static_int_transpiles() -> Result<(), TranspileError> {
        let transpiler = Transpiler::default();
        let src = "static int count = 0;\nstatic int MyClass::instance = 42;";
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Static(s) => {
                assert_eq!(
                    s.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                        .to_string(),
                    "# [doc = concat ! (\" Auto-transpiled static literal \" , stringify ! (i32))] pub static count : i32 = 0 ;"
                );
                assert!(s.class_path.is_none());
            }
            item => panic!("expected ItemStatic, got {item:?}"),
        }
        match &file.items[1] {
            crate::ast::Item::Static(s) => {
                let class_path = s.class_path.as_ref().expect("expected class_path");
                assert_eq!(class_path.segments[0].ident.sym, "MyClass");
                assert_eq!(s.ident.sym, "instance");
            }
            item => panic!("expected ItemStatic, got {item:?}"),
        }
        Ok(())
    }

    #[test]
    fn char_array_from_string_literal() -> Result<(), TranspileError> {
        // `const char` is parsed as Const with a const-qualified element type.
        // The transpiler should infer the size (4 chars + null terminator = 5).
        let transpiler = Transpiler::default();
        let src = r#"const char listOfChars[] = "ALPN";"#;
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Const(c) => {
                let out = c
                    .transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                    .to_string();
                assert_eq!(out, r#"pub const listOfChars : & str = "ALPN" ;"#);
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }

        Ok(())
    }

    #[test]
    fn char_array_with_escape_sequence() -> Result<(), TranspileError> {
        // `\n` counts as one character: size = 3 + 1 = 4.
        let transpiler = Transpiler::default();
        let src = r#"const char nl[] = "a\nb";"#;
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Const(c) => {
                let out = c
                    .transpile_token_stream(&transpiler, &mut TranspileContext::default())?
                    .to_string();
                assert_eq!(out, r#"pub const nl : & str = "a\nb" ;"#);
            }
            item => panic!("expected ItemConst, got {item:?}"),
        }

        Ok(())
    }

    #[test]
    fn static_no_init_errors() {
        let transpiler = Transpiler::default();
        let src = "static int count;";
        let file = parse_file(src).unwrap();
        match &file.items[0] {
            crate::ast::Item::Static(s) => {
                assert!(
                    s.transpile_token_stream(&transpiler, &mut TranspileContext::default())
                        .is_err()
                );
            }
            item => panic!("expected ItemStatic, got {item:?}"),
        }
    }
}