alef 0.58.3

Opinionated polyglot binding generator for Rust libraries
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
use crate::core::ir::{PrimitiveType, TypeRef};
use std::cell::RefCell;

/// Which `Result` type alias the module currently being extracted resolves `Result` to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResultAliasScope {
    /// `Result` names a crate-local alias declared in this module path (`""` = crate root).
    Crate(String),
    /// `Result` names a foreign crate's alias (e.g. `anyhow::Result`), so no crate-local
    /// error type applies.
    Foreign,
}

thread_local! {
    /// Thread-local storage for Result type alias error hints.
    ///
    /// Maps the module path a `Result` alias is *declared* in (`""` = crate root) to the error
    /// type it carries (e.g. `"SampleCrateError"`). Keying by declaring module — rather than by
    /// the alias name — is what keeps a module-private `Result` (a format-specific `error.rs`,
    /// say) from overwriting the crate's canonical alias. ~keep
    static RESULT_ERROR_HINTS: RefCell<ahash::AHashMap<String, String>> = RefCell::new(ahash::AHashMap::new());

    /// The `Result` alias in scope for the module whose items are being extracted right now.
    /// `None` means the module neither declares nor imports one, so lookup falls back to the
    /// crate's canonical alias.
    static RESULT_ALIAS_SCOPE: RefCell<Option<ResultAliasScope>> = const { RefCell::new(None) };
}

/// Drop every Result error hint collected so far.
///
/// Hints accumulate across a crate's modules, so they must be dropped when extraction moves on to
/// the next crate — otherwise a crate with no `Result` alias of its own inherits the previous
/// crate's error type. ~keep
pub fn reset_result_error_hints() {
    RESULT_ERROR_HINTS.with(|h| {
        h.borrow_mut().clear();
    });
    RESULT_ALIAS_SCOPE.with(|s| {
        *s.borrow_mut() = None;
    });
}

/// Record the error type of a `Result` alias declared in `module_path`.
///
/// Extraction walks one file at a time, but a crate's `Result` alias is declared in one module
/// (`error.rs`) and used from others (`convert_api.rs`). Replacing the map per file would drop the
/// alias before the functions that return it are resolved, so hints must accumulate. ~keep
pub fn record_result_error_hint(module_path: &str, error_type: String) {
    RESULT_ERROR_HINTS.with(|h| {
        h.borrow_mut().insert(module_path.to_string(), error_type);
    });
}

/// Install `scope` as the `Result` alias in scope, returning the value it replaced.
pub fn set_result_alias_scope(scope: Option<ResultAliasScope>) -> Option<ResultAliasScope> {
    RESULT_ALIAS_SCOPE.with(|s| s.replace(scope))
}

/// Number of path segments in a module path (`""` — the crate root — has none).
fn module_depth(module_path: &str) -> usize {
    if module_path.is_empty() {
        0
    } else {
        module_path.split("::").count()
    }
}

/// The crate's canonical `Result` alias error type: the one declared nearest the crate root.
///
/// A crate that exports `Result` declares it at (or one module below) the root and re-exports it
/// from `lib.rs`; aliases buried deeper are private to a subsystem and are never the type the
/// crate's public API returns. Ties break lexicographically so codegen stays deterministic. ~keep
fn canonical_result_error_hint() -> Option<String> {
    RESULT_ERROR_HINTS.with(|hints| {
        hints
            .borrow()
            .iter()
            .min_by(|(left, _), (right, _)| {
                module_depth(left.as_str())
                    .cmp(&module_depth(right.as_str()))
                    .then_with(|| left.cmp(right))
            })
            .map(|(_, error_type)| error_type.clone())
    })
}

/// Get the error type hint for the `Result` alias in scope for the current module.
fn get_result_error_hint() -> Option<String> {
    let scope = RESULT_ALIAS_SCOPE.with(|s| s.borrow().clone());
    match scope {
        Some(ResultAliasScope::Foreign) => None,
        // The declaring module may not have been walked yet (module order is source order), so an
        // unresolved crate-local alias still falls back to the canonical one. ~keep
        Some(ResultAliasScope::Crate(module_path)) => RESULT_ERROR_HINTS
            .with(|h| h.borrow().get(&module_path).cloned())
            .or_else(canonical_result_error_hint),
        None => canonical_result_error_hint(),
    }
}

/// Restores the enclosing `Result` alias scope when extraction leaves a module.
pub struct ResultAliasScopeGuard(Option<ResultAliasScope>);

impl ResultAliasScopeGuard {
    /// Enter `scope`, remembering the scope it replaced.
    pub fn enter(scope: Option<ResultAliasScope>) -> Self {
        Self(set_result_alias_scope(scope))
    }
}

impl Drop for ResultAliasScopeGuard {
    fn drop(&mut self) {
        set_result_alias_scope(self.0.take());
    }
}

/// Isolates the `Result` alias hints collected so far for the duration of a foreign-crate walk.
///
/// Re-exported items from a workspace sibling are extracted inline, and that sibling's own
/// `Result` alias must neither be resolved against the host crate's hints nor leak back into
/// them once the walk finishes. ~keep
pub struct IsolatedResultHintsGuard {
    hints: ahash::AHashMap<String, String>,
    scope: Option<ResultAliasScope>,
}

impl IsolatedResultHintsGuard {
    /// Swap in an empty hint set, remembering the current one.
    pub fn enter() -> Self {
        let hints = RESULT_ERROR_HINTS.with(|h| std::mem::take(&mut *h.borrow_mut()));
        let scope = set_result_alias_scope(None);
        Self { hints, scope }
    }
}

impl Drop for IsolatedResultHintsGuard {
    fn drop(&mut self) {
        RESULT_ERROR_HINTS.with(|h| {
            *h.borrow_mut() = std::mem::take(&mut self.hints);
        });
        set_result_alias_scope(self.scope.take());
    }
}

/// Convert a `syn::Type` into our IR `TypeRef`.
pub fn resolve_type(ty: &syn::Type) -> TypeRef {
    match ty {
        syn::Type::Path(type_path) => resolve_path_type(type_path),
        syn::Type::Reference(type_ref) => resolve_reference_type(type_ref),
        syn::Type::Tuple(tuple) => {
            if tuple.elems.is_empty() {
                TypeRef::Unit
            } else {
                let parts: Vec<String> = tuple.elems.iter().map(type_to_string).collect();
                TypeRef::Named(format!("({})", parts.join(", ")))
            }
        }
        syn::Type::Slice(slice) => resolve_slice_type(&slice.elem),
        syn::Type::TraitObject(trait_obj) => {
            if let Some(syn::TypeParamBound::Trait(trait_bound)) = trait_obj.bounds.first()
                && let Some(seg) = trait_bound.path.segments.last()
            {
                return TypeRef::Named(seg.ident.to_string());
            }
            TypeRef::Named("DynObject".to_string())
        }
        syn::Type::ImplTrait(impl_trait) => {
            if let Some(syn::TypeParamBound::Trait(trait_bound)) = impl_trait.bounds.first()
                && let Some(seg) = trait_bound.path.segments.last()
            {
                let trait_name = seg.ident.to_string();
                if (trait_name == "Into" || trait_name == "AsRef")
                    && let Some(inner_ty) = extract_single_generic_arg(seg)
                {
                    return inner_ty;
                }
                return TypeRef::Named(trait_name);
            }
            TypeRef::Named("ImplTrait".to_string())
        }
        _ => TypeRef::Named(type_to_string(ty)),
    }
}

/// Convert a syn::Type to its string representation.
///
/// Strips cosmetic whitespace that `quote` adds around punctuation, while preserving
/// the space between a lifetime (e.g. `'static`) and the type token that follows it.
/// Without that preservation, `&'static str` would be rendered as `&'staticstr`.
pub fn type_to_string(ty: &syn::Type) -> String {
    use quote::ToTokens;
    let raw = ty.to_token_stream().to_string();
    normalize_type_string(&raw)
}

/// Remove cosmetic spaces added by `quote` around punctuation, but keep the space
/// that separates a lifetime token from the type or bracket that follows it.
///
/// Examples:
/// - `& 'static str`      → `&'static str`
/// - `& 'static [ & 'static str ]` → `&'static [&'static str]`
/// - `Vec < String >`     → `Vec<String>`
fn normalize_type_string(s: &str) -> String {
    let bytes = s.as_bytes();
    let n = bytes.len();
    let mut out = String::with_capacity(n);
    let is_punct = |b: u8| matches!(b, b'<' | b'>' | b'[' | b']' | b'(' | b')' | b',' | b'*' | b'&' | b':');

    let mut i = 0;
    while i < n {
        let c = bytes[i];
        if c == b' ' {
            let prev_is_punct = out.as_bytes().last().copied().map(is_punct).unwrap_or(false);
            let mut j = i + 1;
            while j < n && bytes[j] == b' ' {
                j += 1;
            }
            let next_is_punct = j < n && is_punct(bytes[j]);
            let prev_ends_lifetime = ends_with_lifetime(&out);
            if (prev_is_punct || next_is_punct) && !prev_ends_lifetime {
            } else {
                out.push(' ');
            }
        } else if c.is_ascii() {
            out.push(c as char);
        } else {
            let mut j = i + 1;
            while j < n && (bytes[j] & 0b1100_0000) == 0b1000_0000 {
                j += 1;
            }
            if let Ok(slice) = std::str::from_utf8(&bytes[i..j]) {
                out.push_str(slice);
            }
            i = j;
            continue;
        }
        i += 1;
    }
    out
}

/// Returns `true` if `s` ends with a lifetime token such as `'static` or `'a`.
fn ends_with_lifetime(s: &str) -> bool {
    let bytes = s.as_bytes();
    let mut i = bytes.len();
    while i > 0 && (bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_') {
        i -= 1;
    }
    i > 0 && bytes[i - 1] == b'\''
}

/// Resolve a path-based type like `String`, `Vec<T>`, `Option<T>`, etc.
fn resolve_path_type(type_path: &syn::TypePath) -> TypeRef {
    let segment = match type_path.path.segments.last() {
        Some(seg) => seg,
        None => return TypeRef::Named(String::new()),
    };

    let ident = segment.ident.to_string();

    if type_path.path.segments.len() >= 2 {
        let full_path: String = type_path
            .path
            .segments
            .iter()
            .map(|s| s.ident.to_string())
            .collect::<Vec<_>>()
            .join("::");
        if full_path == "serde_json::Value" {
            return TypeRef::Json;
        }
    }

    match ident.as_str() {
        "bool" => TypeRef::Primitive(PrimitiveType::Bool),
        "u8" => TypeRef::Primitive(PrimitiveType::U8),
        "u16" => TypeRef::Primitive(PrimitiveType::U16),
        "u32" => TypeRef::Primitive(PrimitiveType::U32),
        "u64" => TypeRef::Primitive(PrimitiveType::U64),
        "i8" => TypeRef::Primitive(PrimitiveType::I8),
        "i16" => TypeRef::Primitive(PrimitiveType::I16),
        "i32" => TypeRef::Primitive(PrimitiveType::I32),
        "i64" => TypeRef::Primitive(PrimitiveType::I64),
        "f32" => TypeRef::Primitive(PrimitiveType::F32),
        "f64" => TypeRef::Primitive(PrimitiveType::F64),
        "usize" => TypeRef::Primitive(PrimitiveType::Usize),
        "isize" => TypeRef::Primitive(PrimitiveType::Isize),

        "String" | "str" => TypeRef::String,
        "char" => TypeRef::Char,

        "PathBuf" | "Path" => TypeRef::Path,

        "Bytes" => TypeRef::Bytes,

        "JsonValue" | "Value" => TypeRef::Named(ident),

        "Vec" => {
            let inner = extract_single_generic_arg(segment);
            match inner {
                Some(inner_ty) => {
                    if matches!(inner_ty, TypeRef::Primitive(PrimitiveType::U8)) {
                        TypeRef::Bytes
                    } else {
                        TypeRef::Vec(Box::new(inner_ty))
                    }
                }
                None => TypeRef::Vec(Box::new(TypeRef::Named("unknown".into()))),
            }
        }

        "Option" => {
            let inner = extract_single_generic_arg(segment).unwrap_or(TypeRef::Named("unknown".into()));
            TypeRef::Optional(Box::new(inner))
        }

        "HashMap" | "BTreeMap" | "AHashMap" | "IndexMap" | "FxHashMap" => {
            let (k, v) = extract_two_generic_args(segment);
            TypeRef::Map(Box::new(k), Box::new(v))
        }

        "HashSet" | "BTreeSet" | "AHashSet" | "IndexSet" | "FxHashSet" => {
            let inner = extract_single_generic_arg(segment).unwrap_or(TypeRef::Named("unknown".into()));
            TypeRef::Vec(Box::new(inner))
        }

        "Result" => extract_single_generic_arg(segment).unwrap_or(TypeRef::Named("unknown".into())),

        "Box" | "Arc" | "Rc" | "Mutex" | "RwLock" => {
            extract_single_generic_arg(segment).unwrap_or(TypeRef::Named("unknown".into()))
        }

        "Duration" => TypeRef::Duration,
        "SecretString" => TypeRef::String,
        "Cow" => extract_single_generic_arg(segment).unwrap_or(TypeRef::String),

        other => TypeRef::Named(other.to_string()),
    }
}

/// Resolve a reference type like `&str`, `&Path`, `&[u8]`.
fn resolve_reference_type(type_ref: &syn::TypeReference) -> TypeRef {
    let inner = &*type_ref.elem;
    match inner {
        syn::Type::Path(p) => {
            if let Some(seg) = p.path.segments.last() {
                match seg.ident.to_string().as_str() {
                    "str" => TypeRef::String,
                    "Path" => TypeRef::Path,
                    _ => resolve_type(inner),
                }
            } else {
                resolve_type(inner)
            }
        }
        syn::Type::Slice(slice) => resolve_slice_type(&slice.elem),
        _ => resolve_type(inner),
    }
}

/// Resolve a slice type `[T]` — `[u8]` becomes Bytes, otherwise Vec<T>.
fn resolve_slice_type(elem: &syn::Type) -> TypeRef {
    let inner = resolve_type(elem);
    if matches!(inner, TypeRef::Primitive(PrimitiveType::U8)) {
        TypeRef::Bytes
    } else {
        TypeRef::Vec(Box::new(inner))
    }
}

/// Extract the first generic type argument from a path segment, e.g., `Vec<T>` → T.
/// Extract the raw syn::Type of the first generic argument (unresolved).
pub fn extract_single_generic_arg_syn(segment: &syn::PathSegment) -> Option<Box<syn::Type>> {
    if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
        for arg in &args.args {
            if let syn::GenericArgument::Type(ty) = arg {
                return Some(Box::new(ty.clone()));
            }
        }
    }
    None
}

fn extract_single_generic_arg(segment: &syn::PathSegment) -> Option<TypeRef> {
    if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
        for arg in &args.args {
            if let syn::GenericArgument::Type(ty) = arg {
                return Some(resolve_type(ty));
            }
        }
    }
    None
}

/// Extract two generic type arguments from a path segment, e.g., `HashMap<K, V>`.
fn extract_two_generic_args(segment: &syn::PathSegment) -> (TypeRef, TypeRef) {
    let mut types = Vec::new();
    if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
        for arg in &args.args {
            if let syn::GenericArgument::Type(ty) = arg {
                types.push(resolve_type(ty));
            }
        }
    }
    let k = types.first().cloned().unwrap_or(TypeRef::Named("unknown".into()));
    let v = types.get(1).cloned().unwrap_or(TypeRef::Named("unknown".into()));
    (k, v)
}

/// Check if a `syn::Type` represents `Option<T>`, and if so return the inner type.
pub fn is_option_type(ty: &syn::Type) -> Option<TypeRef> {
    if let syn::Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && segment.ident == "Option"
    {
        return extract_single_generic_arg(segment);
    }
    None
}

/// Extract the error type from a `pub type Result<T> = std::result::Result<T, E>` alias definition.
/// Returns the string representation of the error type E.
pub fn extract_result_error_type_from_alias(ty: &syn::Type) -> Option<String> {
    if let syn::Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && segment.ident == "Result"
        && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
    {
        let type_args: Vec<_> = args
            .args
            .iter()
            .filter_map(|a| {
                if let syn::GenericArgument::Type(ty) = a {
                    Some(ty)
                } else {
                    None
                }
            })
            .collect();
        if type_args.len() == 2 {
            return Some(type_to_string(type_args[1]));
        }
    }
    None
}

/// Extract the error type string from a `Result<T, E>` return type.
pub fn extract_result_error_type(ty: &syn::Type) -> Option<String> {
    if let syn::Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && segment.ident == "Result"
        && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
    {
        let type_args: Vec<_> = args
            .args
            .iter()
            .filter_map(|a| {
                if let syn::GenericArgument::Type(ty) = a {
                    Some(ty)
                } else {
                    None
                }
            })
            .collect();
        if type_args.len() >= 2 {
            return Some(type_to_string(type_args[1]));
        }
        if !type_args.is_empty() {
            if let Some(hint) = get_result_error_hint() {
                return Some(hint);
            }
            return Some("anyhow::Error".to_string());
        }
    }
    None
}

/// Check if a return type is `Result<T, E>` and return the inner T type.
pub fn unwrap_result_type(ty: &syn::Type) -> Option<&syn::Type> {
    if let syn::Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && segment.ident == "Result"
        && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
    {
        for arg in &args.args {
            if let syn::GenericArgument::Type(inner_ty) = arg {
                return Some(inner_ty);
            }
        }
    }
    None
}

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

    fn parse_type(s: &str) -> syn::Type {
        syn::parse_str(s).unwrap()
    }

    #[test]
    fn test_primitives() {
        assert_eq!(
            resolve_type(&parse_type("bool")),
            TypeRef::Primitive(PrimitiveType::Bool)
        );
        assert_eq!(resolve_type(&parse_type("u32")), TypeRef::Primitive(PrimitiveType::U32));
        assert_eq!(resolve_type(&parse_type("f64")), TypeRef::Primitive(PrimitiveType::F64));
        assert_eq!(
            resolve_type(&parse_type("usize")),
            TypeRef::Primitive(PrimitiveType::Usize)
        );
    }

    #[test]
    fn test_string_types() {
        assert_eq!(resolve_type(&parse_type("String")), TypeRef::String);
        assert_eq!(resolve_type(&parse_type("&str")), TypeRef::String);
    }

    #[test]
    fn test_bytes_types() {
        assert_eq!(resolve_type(&parse_type("Vec<u8>")), TypeRef::Bytes);
        assert_eq!(resolve_type(&parse_type("&[u8]")), TypeRef::Bytes);
        assert_eq!(resolve_type(&parse_type("Bytes")), TypeRef::Bytes);
    }

    #[test]
    fn test_vec() {
        assert_eq!(
            resolve_type(&parse_type("Vec<String>")),
            TypeRef::Vec(Box::new(TypeRef::String))
        );
    }

    #[test]
    fn test_option() {
        assert_eq!(
            resolve_type(&parse_type("Option<u64>")),
            TypeRef::Optional(Box::new(TypeRef::Primitive(PrimitiveType::U64)))
        );
    }

    #[test]
    fn test_nested_option_preserved() {
        assert_eq!(
            resolve_type(&parse_type("Option<Option<u64>>")),
            TypeRef::Optional(Box::new(TypeRef::Optional(Box::new(TypeRef::Primitive(
                PrimitiveType::U64
            )))))
        );
    }

    #[test]
    fn test_map() {
        assert_eq!(
            resolve_type(&parse_type("HashMap<String, u32>")),
            TypeRef::Map(
                Box::new(TypeRef::String),
                Box::new(TypeRef::Primitive(PrimitiveType::U32))
            )
        );
    }

    #[test]
    fn test_ahashmap_resolves_as_map() {
        assert_eq!(
            resolve_type(&parse_type("AHashMap<String, MyType>")),
            TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::Named("MyType".into())))
        );
    }

    #[test]
    fn test_indexmap_resolves_as_map() {
        assert_eq!(
            resolve_type(&parse_type("IndexMap<String, u64>")),
            TypeRef::Map(
                Box::new(TypeRef::String),
                Box::new(TypeRef::Primitive(PrimitiveType::U64))
            )
        );
    }

    #[test]
    fn test_fxhashmap_resolves_as_map() {
        assert_eq!(
            resolve_type(&parse_type("FxHashMap<String, bool>")),
            TypeRef::Map(
                Box::new(TypeRef::String),
                Box::new(TypeRef::Primitive(PrimitiveType::Bool))
            )
        );
    }

    #[test]
    fn test_hashset_resolves_as_vec() {
        assert_eq!(
            resolve_type(&parse_type("HashSet<String>")),
            TypeRef::Vec(Box::new(TypeRef::String))
        );
    }

    #[test]
    fn test_btreeset_resolves_as_vec() {
        assert_eq!(
            resolve_type(&parse_type("BTreeSet<u32>")),
            TypeRef::Vec(Box::new(TypeRef::Primitive(PrimitiveType::U32)))
        );
    }

    #[test]
    fn test_ahashset_resolves_as_vec() {
        assert_eq!(
            resolve_type(&parse_type("AHashSet<String>")),
            TypeRef::Vec(Box::new(TypeRef::String))
        );
    }

    #[test]
    fn test_indexset_resolves_as_vec() {
        assert_eq!(
            resolve_type(&parse_type("IndexSet<MyType>")),
            TypeRef::Vec(Box::new(TypeRef::Named("MyType".into())))
        );
    }

    #[test]
    fn test_fxhashset_resolves_as_vec() {
        assert_eq!(
            resolve_type(&parse_type("FxHashSet<u64>")),
            TypeRef::Vec(Box::new(TypeRef::Primitive(PrimitiveType::U64)))
        );
    }

    #[test]
    fn test_path_types() {
        assert_eq!(resolve_type(&parse_type("PathBuf")), TypeRef::Path);
        assert_eq!(resolve_type(&parse_type("&Path")), TypeRef::Path);
        assert_eq!(resolve_type(&parse_type("Path")), TypeRef::Path);
        assert_eq!(resolve_type(&parse_type("impl AsRef<Path>")), TypeRef::Path);
        assert_eq!(resolve_type(&parse_type("impl AsRef<PathBuf>")), TypeRef::Path);
    }

    #[test]
    fn test_unit() {
        assert_eq!(resolve_type(&parse_type("()")), TypeRef::Unit);
    }

    #[test]
    fn test_json() {
        assert_eq!(resolve_type(&parse_type("serde_json::Value")), TypeRef::Json);
        assert_eq!(
            resolve_type(&parse_type("JsonValue")),
            TypeRef::Named("JsonValue".to_string())
        );
        assert_eq!(resolve_type(&parse_type("Value")), TypeRef::Named("Value".to_string()));
        assert_eq!(
            resolve_type(&parse_type("HashMap<String, Value>")),
            TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::Named("Value".to_string())))
        );
    }

    #[test]
    fn test_box_arc_unwrap() {
        assert_eq!(resolve_type(&parse_type("Box<String>")), TypeRef::String);
        assert_eq!(
            resolve_type(&parse_type("Arc<u32>")),
            TypeRef::Primitive(PrimitiveType::U32)
        );
    }

    #[test]
    fn test_result_unwrap() {
        assert_eq!(resolve_type(&parse_type("Result<String, Error>")), TypeRef::String);
    }

    #[test]
    fn test_named() {
        assert_eq!(
            resolve_type(&parse_type("MyCustomType")),
            TypeRef::Named("MyCustomType".into())
        );
    }

    #[test]
    fn test_trait_object() {
        assert_eq!(
            resolve_type(&parse_type("dyn MyTrait")),
            TypeRef::Named("MyTrait".into())
        );
    }

    #[test]
    fn test_box_dyn_trait() {
        assert_eq!(
            resolve_type(&parse_type("Box<dyn MyTrait>")),
            TypeRef::Named("MyTrait".into())
        );
    }

    #[test]
    fn test_duration() {
        assert_eq!(resolve_type(&parse_type("Duration")), TypeRef::Duration);
    }

    #[test]
    fn test_secret_string() {
        assert_eq!(resolve_type(&parse_type("SecretString")), TypeRef::String);
    }

    #[test]
    fn test_impl_trait() {
        assert_eq!(resolve_type(&parse_type("impl Into<String>")), TypeRef::String);
    }

    #[test]
    fn test_extract_result_error() {
        let ty = parse_type("Result<String, MyError>");
        assert_eq!(extract_result_error_type(&ty), Some("MyError".into()));
    }

    #[test]
    fn test_extract_result_error_from_alias_definition() {
        let ty = parse_type("std::result::Result<T, SampleCrateError>");
        assert_eq!(
            extract_result_error_type_from_alias(&ty),
            Some("SampleCrateError".into())
        );
    }

    #[test]
    fn test_extract_result_error_with_hint() {
        reset_result_error_hints();
        record_result_error_hint("error", "SampleCrateError".to_string());

        let ty = parse_type("Result<ExtractionResult>");
        assert_eq!(extract_result_error_type(&ty), Some("SampleCrateError".into()));
    }

    #[test]
    fn test_extract_result_error_fallback_without_hint() {
        reset_result_error_hints();

        let ty = parse_type("Result<ExtractionResult>");
        assert_eq!(extract_result_error_type(&ty), Some("anyhow::Error".into()));
    }

    #[test]
    fn test_canonical_hint_wins_over_a_deeper_module_private_alias() {
        reset_result_error_hints();
        // Declaration order must not matter: the deeper alias is recorded last on purpose.
        record_result_error_hint("error", "SampleCrateError".to_string());
        record_result_error_hint("extraction::binary::error", "BinaryFormatError".to_string());

        let ty = parse_type("Result<ExtractionResult>");
        assert_eq!(
            extract_result_error_type(&ty),
            Some("SampleCrateError".into()),
            "a module-private alias must never displace the crate's canonical Result alias"
        );
    }

    #[test]
    fn test_module_private_alias_applies_inside_its_own_module() {
        reset_result_error_hints();
        record_result_error_hint("error", "SampleCrateError".to_string());
        record_result_error_hint("extraction::binary::error", "BinaryFormatError".to_string());
        let _scope =
            ResultAliasScopeGuard::enter(Some(ResultAliasScope::Crate("extraction::binary::error".to_string())));

        let ty = parse_type("Result<ExtractionResult>");
        assert_eq!(extract_result_error_type(&ty), Some("BinaryFormatError".into()));
    }

    #[test]
    fn test_foreign_result_alias_falls_back_to_anyhow() {
        reset_result_error_hints();
        record_result_error_hint("error", "SampleCrateError".to_string());
        let _scope = ResultAliasScopeGuard::enter(Some(ResultAliasScope::Foreign));

        let ty = parse_type("Result<ExtractionResult>");
        assert_eq!(
            extract_result_error_type(&ty),
            Some("anyhow::Error".into()),
            "a module using anyhow::Result must not claim the crate's own error type"
        );
    }

    #[test]
    fn test_alias_scope_guard_restores_the_enclosing_scope() {
        reset_result_error_hints();
        record_result_error_hint("error", "SampleCrateError".to_string());
        record_result_error_hint("extraction::binary::error", "BinaryFormatError".to_string());

        let outer = ResultAliasScopeGuard::enter(Some(ResultAliasScope::Crate(String::new())));
        {
            let _inner =
                ResultAliasScopeGuard::enter(Some(ResultAliasScope::Crate("extraction::binary::error".to_string())));
            let ty = parse_type("Result<ExtractionResult>");
            assert_eq!(extract_result_error_type(&ty), Some("BinaryFormatError".into()));
        }
        let ty = parse_type("Result<ExtractionResult>");
        assert_eq!(extract_result_error_type(&ty), Some("SampleCrateError".into()));
        drop(outer);
    }

    #[test]
    fn test_normalize_type_string_static_str() {
        assert_eq!(normalize_type_string("& 'static str"), "&'static str");
    }

    #[test]
    fn test_normalize_type_string_static_slice_of_static_str() {
        assert_eq!(
            normalize_type_string("& 'static [& 'static str]"),
            "&'static [&'static str]"
        );
    }

    #[test]
    fn test_normalize_type_string_generic_no_spaces() {
        assert_eq!(normalize_type_string("Vec < String >"), "Vec<String>");
    }

    #[test]
    fn test_type_to_string_static_str() {
        let ty = parse_type("&'static str");
        assert_eq!(type_to_string(&ty), "&'static str");
    }

    #[test]
    fn test_type_to_string_static_slice_of_static_str() {
        let ty = parse_type("&'static [&'static str]");
        assert_eq!(type_to_string(&ty), "&'static [&'static str]");
    }

    #[test]
    fn test_arc_mutex_inner_resolved_through_unwrap() {
        assert_eq!(resolve_type(&parse_type("Arc<Mutex<String>>")), TypeRef::String);
    }

    #[test]
    fn test_arc_rwlock_inner_resolved_through_unwrap() {
        assert_eq!(resolve_type(&parse_type("Arc<RwLock<Vec<u8>>>")), TypeRef::Bytes);
    }

    #[test]
    fn test_arc_hashmap_string_string_inner_resolved() {
        assert_eq!(
            resolve_type(&parse_type("Arc<HashMap<String, String>>")),
            TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::String))
        );
    }
}