sigmd 0.1.0

Windows API signature metadata
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
//! Safe wrapper around `clang-sys`.
//!
//! Tries its best to mirror the `clang` crate's API shape:
//! [`Index`] -> [`Parser<'i>`] -> [`TranslationUnit<'i>`] -> [`Entity<'tu>`] /
//! [`Type<'tu>`]. Method names match.
//!
//! Intentional divergences:
//!
//! - [`EntityKind`] and [`TypeKind`] are curated enums covering only the
//!   kinds the wrapper consumes, with an [`Other(i32)`] catch-all for
//!   everything else. libclang has renumbered cursor kinds across versions
//!   (`CXCursor_TranslationUnit` moved from 300 to 350 in clang 15), so
//!   matching against `clang_sys` constants keeps the conversion correct
//!   as long as the bindings are regenerated.
//!
//! - There is no `Clang` singleton type. With `clang-sys`'s `runtime`
//!   feature libclang loads per-thread on demand. [`Index::new`] calls
//!   `clang_sys::load()` if the library is not yet loaded on the
//!   current thread.
//!
//! - The `clang` crate exposes a single `Parser::arguments(&[S])` that
//!   replaces the whole argument list. We expose [`Parser::arg`] /
//!   [`Parser::args`], which append to it.
//!
//! [`Other(i32)`]: EntityKind::Other

use std::{
    ffi::{CStr, CString},
    os::raw::c_char,
    path::PathBuf,
};

/// Errors from the `clang` wrapper.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    /// Failure to load or initialize libclang on this thread.
    #[error("failed to load libclang: {0}")]
    LibClang(String),

    /// `clang_createIndex` returned null.
    #[error("clang_createIndex returned null")]
    NullIndex,

    /// `clang_parseTranslationUnit2` failed.
    #[error("clang failed to parse `{}`: error code {code}", path.display())]
    Parse {
        /// Source file that failed to parse.
        path: PathBuf,

        /// libclang error code (`CXError_*`).
        code: i32,
    },
}

/// Lifetime-erased libclang index. One per worker thread.
///
/// libclang permits a `CXIndex` to be used by a single thread at a time,
/// which is what `Send` encodes. `Sync` is forbidden because the libclang
/// API itself is not.
///
/// `clang-sys`'s `runtime` feature loads libclang into thread-local
/// storage. Any thread that handles an `Index` (calls a method, drops
/// it) must have libclang loaded on its TLS first, otherwise the FFI
/// dispatch panics.
pub struct Index {
    handle: clang_sys::CXIndex,
}

// SAFETY: libclang's CXIndex is safe to use from a single thread at a
// time. Send transfers ownership across threads but does not allow
// concurrent access. The receiving thread must have libclang loaded on
// its TLS - see the [`Index`] rustdoc.
unsafe impl Send for Index {}

impl Index {
    /// Creates a new libclang index on the current thread.
    ///
    /// Loads the libclang shared library on this thread if it is not already
    /// loaded.
    pub fn new() -> Result<Self, Error> {
        if !clang_sys::is_loaded() {
            clang_sys::load().map_err(Error::LibClang)?;
        }

        // SAFETY: `clang_createIndex` is safe to call with any int args, and
        // libclang is loaded on this thread by the call above.
        let handle = unsafe { clang_sys::clang_createIndex(0, 0) };
        if handle.is_null() {
            return Err(Error::NullIndex);
        }

        Ok(Self { handle })
    }

    /// Returns a parser for the supplied source file.
    pub fn parser(&self, file: impl Into<PathBuf>) -> Parser<'_> {
        Parser {
            index: self,
            file: file.into(),
            arguments: Vec::new(),
        }
    }
}

impl Drop for Index {
    fn drop(&mut self) {
        // SAFETY: `handle` is non-null (checked at construction). We are
        // the unique owner.
        unsafe { clang_sys::clang_disposeIndex(self.handle) };
    }
}

/// Builder for `clang_parseTranslationUnit2` invocations.
pub struct Parser<'i> {
    index: &'i Index,
    file: PathBuf,
    arguments: Vec<String>,
}

impl<'i> Parser<'i> {
    /// Appends a single command-line argument.
    pub fn arg(&mut self, arg: impl Into<String>) -> &mut Self {
        self.arguments.push(arg.into());
        self
    }

    /// Appends a sequence of command-line arguments.
    pub fn args(&mut self, args: impl IntoIterator<Item = impl Into<String>>) -> &mut Self {
        for arg in args {
            self.arg(arg);
        }

        self
    }

    /// Parses the configured translation unit.
    pub fn parse(&self) -> Result<TranslationUnit<'i>, Error> {
        let path = CString::new(self.file.to_string_lossy().as_bytes())
            .map_err(|err| Error::LibClang(format!("path contains NUL: {err}")))?;

        let cstrings = self
            .arguments
            .iter()
            .map(|a| CString::new(a.as_bytes()))
            .collect::<Result<Vec<_>, _>>()
            .map_err(|err| Error::LibClang(format!("argument contains NUL: {err}")))?;

        let argv = cstrings
            .iter()
            .map(|c| c.as_ptr())
            .collect::<Vec<*const c_char>>();

        let mut handle = std::ptr::null_mut();
        // SAFETY: arguments are owned for the duration of the call.
        // `index.handle` is non-null.
        let code = unsafe {
            clang_sys::clang_parseTranslationUnit2(
                self.index.handle,
                path.as_ptr(),
                argv.as_ptr(),
                argv.len() as i32,
                std::ptr::null_mut(),
                0,
                clang_sys::CXTranslationUnit_None,
                &mut handle,
            )
        };

        if code != clang_sys::CXError_Success || handle.is_null() {
            return Err(Error::Parse {
                path: self.file.clone(),
                code,
            });
        }

        Ok(TranslationUnit {
            handle,
            _marker: std::marker::PhantomData,
        })
    }
}

/// Owned translation unit. Lifetime tied to its `Index`.
pub struct TranslationUnit<'i> {
    handle: clang_sys::CXTranslationUnit,
    _marker: std::marker::PhantomData<&'i Index>,
}

impl<'i> TranslationUnit<'i> {
    /// Returns the root entity of this translation unit.
    pub fn get_entity(&'i self) -> Entity<'i> {
        // SAFETY: clang_getTranslationUnitCursor returns a valid cursor tied
        // to this TU's lifetime.
        let raw = unsafe { clang_sys::clang_getTranslationUnitCursor(self.handle) };
        Entity { raw, tu: self }
    }
}

impl<'i> Drop for TranslationUnit<'i> {
    fn drop(&mut self) {
        // SAFETY: handle is owned and non-null.
        unsafe { clang_sys::clang_disposeTranslationUnit(self.handle) };
    }
}

/// Categorization of an `Entity`.
///
/// Discriminants are bound to `clang_sys::CXCursor_*` constants so the wrapper
/// stays in sync with whichever libclang the bindings target. Only the kinds
/// this wrapper consumes are listed. Anything else folds into `Other` via
/// `from_raw`.
/// `UnexposedDecl` is reserved for libclang's `CXCursor_UnexposedDecl`
/// specifically, which means "a declaration whose kind libclang chose not to
/// expose" - that is distinct from "a kind this wrapper does not model"
/// (`Other`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntityKind {
    /// A declaration whose specific kind libclang chose not to expose
    /// via the C API.
    ///
    /// Corresponds to `CXCursor_UnexposedDecl`.
    UnexposedDecl,

    /// A C or C++ struct.
    ///
    /// Corresponds to `CXCursor_StructDecl`.
    StructDecl,

    /// A C or C++ union.
    ///
    /// Corresponds to `CXCursor_UnionDecl`.
    UnionDecl,

    /// A C++ class.
    ///
    /// Corresponds to `CXCursor_ClassDecl`.
    ClassDecl,

    /// A function.
    ///
    /// Corresponds to `CXCursor_FunctionDecl`.
    FunctionDecl,

    /// A function or method parameter.
    ///
    /// Corresponds to `CXCursor_ParmDecl`.
    ParmDecl,

    /// A typedef.
    ///
    /// Corresponds to `CXCursor_TypedefDecl`.
    TypedefDecl,

    /// A C++ method.
    ///
    /// Corresponds to `CXCursor_CXXMethod`.
    Method,

    /// A C++ namespace.
    ///
    /// Corresponds to `CXCursor_Namespace`.
    Namespace,

    /// A linkage specification (`extern "C"`).
    ///
    /// Corresponds to `CXCursor_LinkageSpec`.
    LinkageSpec,

    /// A C++ type alias declaration (`using X = Y;`).
    ///
    /// Corresponds to `CXCursor_TypeAliasDecl`.
    TypeAliasDecl,

    /// A C++ base class specifier.
    ///
    /// Corresponds to `CXCursor_CXXBaseSpecifier`.
    BaseSpecifier,

    /// The translation unit root cursor.
    ///
    /// Corresponds to `CXCursor_TranslationUnit`.
    TranslationUnit,

    /// An `__attribute__((annotate(...)))` attribute.
    ///
    /// Corresponds to `CXCursor_AnnotateAttr`.
    AnnotateAttr,

    /// A cursor kind not modeled by this wrapper.
    Other(i32),
}

impl EntityKind {
    /// Builds an `EntityKind` from a raw `CXCursorKind`.
    fn from_raw(raw: clang_sys::CXCursorKind) -> Self {
        match raw {
            clang_sys::CXCursor_UnexposedDecl => Self::UnexposedDecl,
            clang_sys::CXCursor_StructDecl => Self::StructDecl,
            clang_sys::CXCursor_UnionDecl => Self::UnionDecl,
            clang_sys::CXCursor_ClassDecl => Self::ClassDecl,
            clang_sys::CXCursor_FunctionDecl => Self::FunctionDecl,
            clang_sys::CXCursor_ParmDecl => Self::ParmDecl,
            clang_sys::CXCursor_TypedefDecl => Self::TypedefDecl,
            clang_sys::CXCursor_CXXMethod => Self::Method,
            clang_sys::CXCursor_Namespace => Self::Namespace,
            clang_sys::CXCursor_LinkageSpec => Self::LinkageSpec,
            clang_sys::CXCursor_TypeAliasDecl => Self::TypeAliasDecl,
            clang_sys::CXCursor_CXXBaseSpecifier => Self::BaseSpecifier,
            clang_sys::CXCursor_TranslationUnit => Self::TranslationUnit,
            clang_sys::CXCursor_AnnotateAttr => Self::AnnotateAttr,
            _ => Self::Other(raw),
        }
    }
}

/// Categorization of a `Type`.
///
/// Discriminants are bound to `clang_sys::CXType_*` constants. Only the kinds
/// this wrapper consumes are listed. Anything else folds into `Other` via
/// `from_raw`.
/// `Unexposed` is reserved for libclang's `CXType_Unexposed` specifically,
/// which means "a type whose specific kind libclang chose not to expose" -
/// distinct from "a kind this wrapper does not model" (`Other`). `Invalid`
/// is not a variant: it is filtered to `Option::None` at the API boundary by
/// `get_pointee_type` and `get_result_type`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TypeKind {
    /// libclang's `CXType_Unexposed`. A type whose specific kind libclang
    /// chose not to expose via the C API.
    ///
    /// Corresponds to `CXType_Unexposed`.
    Unexposed,

    /// `void`.
    ///
    /// Corresponds to `CXType_Void`.
    Void,

    /// `bool` or `_Bool`.
    ///
    /// Corresponds to `CXType_Bool`.
    Bool,

    /// `char` when unsigned by default.
    ///
    /// Corresponds to `CXType_Char_U`.
    CharU,

    /// `unsigned char`.
    ///
    /// Corresponds to `CXType_UChar`.
    UChar,

    /// `unsigned short`.
    ///
    /// Corresponds to `CXType_UShort`.
    UShort,

    /// `unsigned int`.
    ///
    /// Corresponds to `CXType_UInt`.
    UInt,

    /// `unsigned long`.
    ///
    /// Corresponds to `CXType_ULong`.
    ULong,

    /// `unsigned long long`.
    ///
    /// Corresponds to `CXType_ULongLong`.
    ULongLong,

    /// `char` when signed by default.
    ///
    /// Corresponds to `CXType_Char_S`.
    CharS,

    /// `signed char`.
    ///
    /// Corresponds to `CXType_SChar`.
    SChar,

    /// `wchar_t`.
    ///
    /// Corresponds to `CXType_WChar`.
    WChar,

    /// `short`.
    ///
    /// Corresponds to `CXType_Short`.
    Short,

    /// `int`.
    ///
    /// Corresponds to `CXType_Int`.
    Int,

    /// `long`.
    ///
    /// Corresponds to `CXType_Long`.
    Long,

    /// `long long`.
    ///
    /// Corresponds to `CXType_LongLong`.
    LongLong,

    /// `float`.
    ///
    /// Corresponds to `CXType_Float`.
    Float,

    /// `double`.
    ///
    /// Corresponds to `CXType_Double`.
    Double,

    /// A pointer.
    ///
    /// Corresponds to `CXType_Pointer`.
    Pointer,

    /// A C++ lvalue reference (`T&`).
    ///
    /// Corresponds to `CXType_LValueReference`.
    LValueReference,

    /// A C++ rvalue reference (`T&&`).
    ///
    /// Corresponds to `CXType_RValueReference`.
    RValueReference,

    /// An enum.
    ///
    /// Corresponds to `CXType_Enum`.
    Enum,

    /// A type kind not modeled by this wrapper.
    Other(i32),
}

impl TypeKind {
    /// Builds a `TypeKind` from a raw `CXTypeKind`. Unknown values fold into
    /// `Self::Other`. Callers must filter `CXType_Invalid` themselves
    /// before calling this.
    fn from_raw(raw: clang_sys::CXTypeKind) -> Self {
        match raw {
            clang_sys::CXType_Unexposed => Self::Unexposed,
            clang_sys::CXType_Void => Self::Void,
            clang_sys::CXType_Bool => Self::Bool,
            clang_sys::CXType_Char_U => Self::CharU,
            clang_sys::CXType_UChar => Self::UChar,
            clang_sys::CXType_UShort => Self::UShort,
            clang_sys::CXType_UInt => Self::UInt,
            clang_sys::CXType_ULong => Self::ULong,
            clang_sys::CXType_ULongLong => Self::ULongLong,
            clang_sys::CXType_Char_S => Self::CharS,
            clang_sys::CXType_SChar => Self::SChar,
            clang_sys::CXType_WChar => Self::WChar,
            clang_sys::CXType_Short => Self::Short,
            clang_sys::CXType_Int => Self::Int,
            clang_sys::CXType_Long => Self::Long,
            clang_sys::CXType_LongLong => Self::LongLong,
            clang_sys::CXType_Float => Self::Float,
            clang_sys::CXType_Double => Self::Double,
            clang_sys::CXType_Pointer => Self::Pointer,
            clang_sys::CXType_LValueReference => Self::LValueReference,
            clang_sys::CXType_RValueReference => Self::RValueReference,
            clang_sys::CXType_Enum => Self::Enum,
            _ => Self::Other(raw),
        }
    }
}

/// Converts a `CXString` to an owned String, disposing it. Returns `None` for
/// null or empty.
///
/// # Safety
///
/// `s` must be a `CXString` returned by libclang on the calling thread that
/// has not yet been disposed. The function disposes it in every branch. The
/// caller must not retain or dispose another reference to the same value.
unsafe fn cx_string_to_owned(s: clang_sys::CXString) -> Option<String> {
    let raw = unsafe { clang_sys::clang_getCString(s) };
    if raw.is_null() {
        unsafe { clang_sys::clang_disposeString(s) };
        return None;
    }

    let owned = unsafe { CStr::from_ptr(raw) }
        .to_string_lossy()
        .into_owned();

    unsafe { clang_sys::clang_disposeString(s) };

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

/// Lightweight handle to a libclang cursor. `CXCursor` is POD-by-value, so
/// `Entity` is `Copy`. Lifetime is tied to the parent `TranslationUnit`.
#[derive(Clone, Copy)]
pub struct Entity<'tu> {
    raw: clang_sys::CXCursor,
    tu: &'tu TranslationUnit<'tu>,
}

impl<'tu> Entity<'tu> {
    /// Returns the categorization of this entity.
    pub fn get_kind(&self) -> EntityKind {
        // SAFETY: cursor is valid for its TU lifetime.
        let raw = unsafe { clang_sys::clang_getCursorKind(self.raw) };
        EntityKind::from_raw(raw)
    }

    /// Returns the name (spelling) of this entity, if any.
    pub fn get_name(&self) -> Option<String> {
        // SAFETY: cursor valid. CXString must be disposed.
        unsafe {
            let s = clang_sys::clang_getCursorSpelling(self.raw);
            cx_string_to_owned(s)
        }
    }

    /// Returns the type of this entity, if any.
    pub fn get_type(&self) -> Option<Type<'tu>> {
        // SAFETY: cursor valid.
        let raw = unsafe { clang_sys::clang_getCursorType(self.raw) };
        match raw.kind {
            clang_sys::CXType_Invalid => None,
            _ => Some(Type { raw, tu: self.tu }),
        }
    }

    /// Returns the result type of this entity, if applicable.
    pub fn get_result_type(&self) -> Option<Type<'tu>> {
        // SAFETY: cursor valid. Result type is `CXType_Invalid` for
        // non-function cursors.
        let raw = unsafe { clang_sys::clang_getCursorResultType(self.raw) };
        match raw.kind {
            clang_sys::CXType_Invalid => None,
            _ => Some(Type { raw, tu: self.tu }),
        }
    }

    /// Returns whether this declaration was marked invalid by clang.
    pub fn is_invalid_declaration(&self) -> bool {
        // SAFETY: cursor valid.
        unsafe { clang_sys::clang_isInvalidDeclaration(self.raw) != 0 }
    }

    /// Returns the children of this entity, in source order.
    pub fn get_children(&self) -> Vec<Self> {
        extern "C" fn collect(
            cursor: clang_sys::CXCursor,
            _parent: clang_sys::CXCursor,
            data: clang_sys::CXClientData,
        ) -> clang_sys::CXChildVisitResult {
            // SAFETY: data is `&mut Vec<CXCursor>` (cast at call site below).
            let acc = unsafe { &mut *(data as *mut Vec<clang_sys::CXCursor>) };
            acc.push(cursor);
            clang_sys::CXChildVisit_Continue
        }

        let mut acc = Vec::<clang_sys::CXCursor>::new();
        // SAFETY: clang_visitChildren is safe. `collect` upholds invariants.
        unsafe {
            clang_sys::clang_visitChildren(
                self.raw,
                collect,
                &mut acc as *mut _ as clang_sys::CXClientData,
            );
        }

        acc.into_iter()
            .map(|raw| Self { raw, tu: self.tu })
            .collect()
    }
}

/// Lightweight handle to a libclang `CXType`. `CXType` is POD-by-value.
#[derive(Clone, Copy)]
pub struct Type<'tu> {
    raw: clang_sys::CXType,
    tu: &'tu TranslationUnit<'tu>,
}

impl<'tu> Type<'tu> {
    /// Returns the categorization of this type.
    pub fn get_kind(&self) -> TypeKind {
        TypeKind::from_raw(self.raw.kind)
    }

    /// Returns the human-readable spelling of this type. Empty string is
    /// possible but rare. `Type` is never constructed for `CXType_Invalid`.
    pub fn get_display_name(&self) -> String {
        // SAFETY: type valid. CXString must be disposed.
        unsafe { cx_string_to_owned(clang_sys::clang_getTypeSpelling(self.raw)) }
            .unwrap_or_default()
    }

    /// Returns the byte size of this type, or `None` if libclang cannot size
    /// it (incomplete, dependent, variable-size, or invalid-field-name).
    pub fn get_sizeof(&self) -> Option<u64> {
        // SAFETY: type valid.
        let size = unsafe { clang_sys::clang_Type_getSizeOf(self.raw) };
        match size {
            size if size > 0 => Some(size as u64),
            _ => None,
        }
    }

    /// Returns the canonical (typedef-stripped) form of this type.
    pub fn get_canonical_type(&self) -> Self {
        // SAFETY: type valid.
        let raw = unsafe { clang_sys::clang_getCanonicalType(self.raw) };
        Self { raw, tu: self.tu }
    }

    /// Returns the pointee type, if this type is a pointer or reference.
    pub fn get_pointee_type(&self) -> Option<Self> {
        // SAFETY: type valid.
        let raw = unsafe { clang_sys::clang_getPointeeType(self.raw) };
        match raw.kind {
            clang_sys::CXType_Invalid => None,
            _ => Some(Self { raw, tu: self.tu }),
        }
    }
}

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

    #[test]
    fn index_creates_and_drops() {
        // Skips silently when libclang is not available on the system.
        match Index::new() {
            Ok(index) => drop(index),
            Err(err) => eprintln!("skipping: libclang not available: {err}"),
        }
    }

    #[test]
    fn entity_kind_round_trip_known() {
        assert_eq!(
            EntityKind::from_raw(clang_sys::CXCursor_FunctionDecl),
            EntityKind::FunctionDecl,
        );
        assert_eq!(
            EntityKind::from_raw(clang_sys::CXCursor_CXXMethod),
            EntityKind::Method,
        );
        assert_eq!(
            EntityKind::from_raw(clang_sys::CXCursor_TranslationUnit),
            EntityKind::TranslationUnit,
        );
        assert_eq!(
            EntityKind::from_raw(clang_sys::CXCursor_AnnotateAttr),
            EntityKind::AnnotateAttr,
        );
    }

    #[test]
    fn entity_kind_unknown_folds_to_other() {
        // Cursor kinds the wrapper does not model fold into `Other`, distinct
        // from `UnexposedDecl` (which is reserved for `CXCursor_UnexposedDecl`).
        // Important for `parse.rs::visit`: recursing on `UnexposedDecl` must
        // not descend into template bodies.
        assert_eq!(
            EntityKind::from_raw(clang_sys::CXCursor_BinaryOperator),
            EntityKind::Other(clang_sys::CXCursor_BinaryOperator),
        );
        assert_eq!(
            EntityKind::from_raw(clang_sys::CXCursor_FunctionTemplate),
            EntityKind::Other(clang_sys::CXCursor_FunctionTemplate),
        );
        assert_eq!(
            EntityKind::from_raw(clang_sys::CXCursor_ClassTemplate),
            EntityKind::Other(clang_sys::CXCursor_ClassTemplate),
        );
    }

    #[test]
    fn entity_kind_unexposed_decl_maps_to_unexposed_decl() {
        assert_eq!(
            EntityKind::from_raw(clang_sys::CXCursor_UnexposedDecl),
            EntityKind::UnexposedDecl,
        );
    }

    #[test]
    fn type_kind_round_trip_known() {
        assert_eq!(TypeKind::from_raw(clang_sys::CXType_Void), TypeKind::Void);
        assert_eq!(TypeKind::from_raw(clang_sys::CXType_Bool), TypeKind::Bool);
        assert_eq!(
            TypeKind::from_raw(clang_sys::CXType_Pointer),
            TypeKind::Pointer
        );
        assert_eq!(
            TypeKind::from_raw(clang_sys::CXType_LValueReference),
            TypeKind::LValueReference,
        );
        assert_eq!(TypeKind::from_raw(clang_sys::CXType_Enum), TypeKind::Enum);
    }

    #[test]
    fn type_kind_unknown_folds_to_other() {
        // Type kinds the wrapper does not model fold into `Other`, distinct
        // from `Unexposed` (which is reserved for `CXType_Unexposed`).
        assert_eq!(
            TypeKind::from_raw(clang_sys::CXType_Vector),
            TypeKind::Other(clang_sys::CXType_Vector),
        );
    }

    #[test]
    fn type_kind_unexposed_maps_to_unexposed() {
        assert_eq!(
            TypeKind::from_raw(clang_sys::CXType_Unexposed),
            TypeKind::Unexposed,
        );
    }

    #[test]
    fn parses_a_function_declaration() {
        let index = match Index::new() {
            Ok(index) => index,
            Err(err) => {
                eprintln!("skipping: libclang not available: {err}");
                return;
            }
        };

        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("input.cpp");
        std::fs::write(&path, b"int my_function(int x);\n").expect("write");

        let mut parser = index.parser(&path);
        parser.args(["-x", "c++"]);
        let tu = parser.parse().expect("parse");

        let root = tu.get_entity();
        assert_eq!(root.get_kind(), EntityKind::TranslationUnit);

        let children = root.get_children();
        let function = children
            .iter()
            .find(|entity| entity.get_kind() == EntityKind::FunctionDecl)
            .expect("FunctionDecl");
        assert_eq!(function.get_name().as_deref(), Some("my_function"));

        let params = function
            .get_children()
            .into_iter()
            .filter(|entity| entity.get_kind() == EntityKind::ParmDecl)
            .count();
        assert_eq!(params, 1);
    }

    #[test]
    fn type_accessors_walk_a_pointer() {
        let index = match Index::new() {
            Ok(index) => index,
            Err(err) => {
                eprintln!("skipping: libclang not available: {err}");
                return;
            }
        };

        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("input.cpp");
        std::fs::write(&path, b"int* takes_pointer(const int* x);\n").expect("write");

        let mut parser = index.parser(&path);
        parser.args(["-x", "c++"]);
        let tu = parser.parse().expect("parse");

        let function = tu
            .get_entity()
            .get_children()
            .into_iter()
            .find(|c| c.get_kind() == EntityKind::FunctionDecl)
            .expect("FunctionDecl");

        let return_ty = function.get_result_type().expect("result type");
        assert_eq!(return_ty.get_kind(), TypeKind::Pointer);
        let pointee = return_ty.get_pointee_type().expect("pointee");
        assert_eq!(pointee.get_canonical_type().get_kind(), TypeKind::Int);

        let parm = function
            .get_children()
            .into_iter()
            .find(|c| c.get_kind() == EntityKind::ParmDecl)
            .expect("ParmDecl");
        let parm_ty = parm.get_type().expect("parm type");
        assert_eq!(parm_ty.get_kind(), TypeKind::Pointer);
        // Display name retains const qualifier on the pointee.
        assert!(parm_ty.get_display_name().contains("const int"));
    }
}