macho-header-syntax 0.5.2

Process-free typed C, C++, and Objective-C header syntax
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
//! Bounded semantic validation for typed headers.

mod redeclaration;

use std::collections::{BTreeMap, BTreeSet};

use crate::{Decl, IdentifierPath, ObjectiveCForwardKind, TranslationUnit, Type};
use redeclaration::{Redeclaration, declaration_identity, redeclaration};

/// Stable semantic validation diagnostic code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HeaderValidationCode {
    /// Concrete syntax was invalid.
    SyntaxError,
    /// The same declaration was repeated.
    DuplicateDeclaration,
    /// Declarations with the same identity disagree.
    ConflictingRedeclaration,
    /// A tagged type has no declaration.
    UnresolvedType,
    /// A declaration owner has no declaration.
    UnresolvedOwner,
    /// The declared linkage is incompatible with the language.
    InvalidLinkage,
    /// The storage class is incompatible with the declaration.
    InvalidStorage,
    /// The calling convention is incompatible with the language.
    InvalidCallingConvention,
    /// A template could not be represented completely.
    IncompleteTemplateContext,
    /// An Objective-C selector's colon count differs from its parameter count.
    SelectorArityMismatch,
    /// An Objective-C reference resolves to the wrong entity kind.
    ObjectiveCKindMismatch,
    /// The declaration dependency graph contains a cycle.
    DependencyCycle,
}

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Severity {
    /// Informational finding.
    Info,
    /// Recoverable weakness.
    Warning,
    /// Semantic validation failure.
    Error,
}

/// One semantic validation diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeaderValidationDiagnostic {
    /// Stable diagnostic code.
    pub code: HeaderValidationCode,
    /// Severity.
    pub severity: Severity,
    /// Human-readable explanation.
    pub message: String,
    /// Top-level declaration index, when applicable.
    pub declaration_index: Option<u32>,
}

/// Complete syntax and semantic validation result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeaderValidationReport {
    /// Whether concrete syntax parsing succeeded.
    pub syntax_valid: bool,
    /// Whether all semantic checks succeeded.
    pub semantic_valid: bool,
    /// Ordered diagnostics.
    pub diagnostics: Vec<HeaderValidationDiagnostic>,
}

/// Hard resource bounds for recursive validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ValidationLimits {
    /// Maximum nested type depth.
    pub max_type_depth: usize,
    /// Maximum nested declaration depth.
    pub max_declaration_depth: usize,
    /// Maximum number of template arguments or members on one node.
    pub max_items_per_node: usize,
    /// Maximum total AST nodes.
    pub max_total_nodes: usize,
}

impl Default for ValidationLimits {
    fn default() -> Self {
        Self {
            max_type_depth: 64,
            max_declaration_depth: 64,
            max_items_per_node: 1_024,
            max_total_nodes: 1_000_000,
        }
    }
}

/// Typed validation limit failure.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ValidationError {
    /// Type nesting exceeded the configured bound.
    #[error("type recursion depth {actual} exceeds limit {limit}")]
    TypeDepth {
        /// Configured maximum.
        limit: usize,
        /// Observed depth.
        actual: usize,
    },
    /// Declaration nesting exceeded the configured bound.
    #[error("declaration nesting depth {actual} exceeds limit {limit}")]
    DeclarationDepth {
        /// Configured maximum.
        limit: usize,
        /// Observed depth.
        actual: usize,
    },
    /// One node contained too many children.
    #[error("{kind} item count {actual} exceeds limit {limit}")]
    ItemsPerNode {
        /// Child collection name.
        kind: &'static str,
        /// Configured maximum.
        limit: usize,
        /// Observed count.
        actual: usize,
    },
    /// The total syntax tree was too large.
    #[error("AST node count exceeds limit {limit}")]
    TotalNodes {
        /// Configured maximum.
        limit: usize,
    },
}

/// Validates a parsed translation unit under the normative resource bounds.
pub fn validate(
    unit: &TranslationUnit,
    limits: ValidationLimits,
) -> Result<HeaderValidationReport, ValidationError> {
    let mut budget = Budget { limits, nodes: 0 };
    for declaration in &unit.declarations {
        budget.declaration(declaration, 1)?;
    }

    let mut diagnostics = Vec::new();
    let mut declarations = BTreeMap::<String, (usize, &Decl)>::new();
    let mut declared_tags = BTreeSet::new();
    let mut objc_classes = BTreeSet::new();
    let mut objc_protocols = BTreeSet::new();

    // `id`, `Class`, and `SEL` are supplied by the Objective-C runtime rather
    // than by a recovered image. They are valid in a standalone projected
    // header without needing an SDK preamble.
    if unit.language == crate::Language::ObjectiveC {
        declared_tags.extend(["id".to_owned(), "Class".to_owned(), "SEL".to_owned()]);
    }

    for (index, declaration) in unit.declarations.iter().enumerate() {
        collect_declared_types(
            declaration,
            &mut declared_tags,
            &mut objc_classes,
            &mut objc_protocols,
        );
        if let Some(identity) = declaration_identity(unit.language, declaration) {
            if let Some((previous_index, previous)) = declarations.get(&identity) {
                match redeclaration(unit.language, previous, declaration) {
                    Redeclaration::Compatible { replace } => {
                        diagnostics.push(diagnostic_with_severity(
                            HeaderValidationCode::DuplicateDeclaration,
                            Severity::Info,
                            format!(
                                "declaration `{identity}` is compatible with index {previous_index}"
                            ),
                            index,
                        ));
                        if replace {
                            declarations.insert(identity, (index, declaration));
                        }
                    }
                    Redeclaration::Duplicate => diagnostics.push(diagnostic(
                        HeaderValidationCode::DuplicateDeclaration,
                        format!("declaration `{identity}` duplicates index {previous_index}"),
                        index,
                    )),
                    Redeclaration::Conflict => diagnostics.push(diagnostic(
                        HeaderValidationCode::ConflictingRedeclaration,
                        format!("declaration `{identity}` conflicts with index {previous_index}"),
                        index,
                    )),
                }
            } else {
                declarations.insert(identity, (index, declaration));
            }
        }
    }

    // Tree-sitter represents Objective-C class pointer spellings such as
    // `NSString *` as named types.  An `@class NSString;` declaration is the
    // corresponding declaration authority, so make that namespace available
    // to named-type validation after the complete declaration pass.
    declared_tags.extend(objc_classes.iter().cloned());

    for (index, declaration) in unit.declarations.iter().enumerate() {
        validate_decl(
            declaration,
            index,
            &declared_tags,
            &objc_classes,
            &objc_protocols,
            &mut diagnostics,
        );
    }
    validate_cycles(&unit.declarations, &mut diagnostics);
    diagnostics.sort_by_key(|diagnostic| {
        (
            diagnostic.declaration_index.unwrap_or(u32::MAX),
            diagnostic.code as u8,
            diagnostic.message.clone(),
        )
    });
    let semantic_valid = !diagnostics
        .iter()
        .any(|diagnostic| diagnostic.severity == Severity::Error);
    Ok(HeaderValidationReport {
        syntax_valid: true,
        semantic_valid,
        diagnostics,
    })
}

struct Budget {
    limits: ValidationLimits,
    nodes: usize,
}

impl Budget {
    fn node(&mut self) -> Result<(), ValidationError> {
        self.nodes += 1;
        if self.nodes > self.limits.max_total_nodes {
            Err(ValidationError::TotalNodes {
                limit: self.limits.max_total_nodes,
            })
        } else {
            Ok(())
        }
    }

    fn items(&self, kind: &'static str, actual: usize) -> Result<(), ValidationError> {
        if actual > self.limits.max_items_per_node {
            Err(ValidationError::ItemsPerNode {
                kind,
                limit: self.limits.max_items_per_node,
                actual,
            })
        } else {
            Ok(())
        }
    }

    fn declaration(&mut self, declaration: &Decl, depth: usize) -> Result<(), ValidationError> {
        if depth > self.limits.max_declaration_depth {
            return Err(ValidationError::DeclarationDepth {
                limit: self.limits.max_declaration_depth,
                actual: depth,
            });
        }
        self.node()?;
        match declaration {
            Decl::Function { signature, .. } => self.ty(signature, 1),
            Decl::Variable { ty, .. } | Decl::Alias { target: ty, .. } => self.ty(ty, 1),
            Decl::Record {
                bases,
                fields,
                members,
                ..
            } => {
                self.items("record members", bases.len() + fields.len() + members.len())?;
                for base in bases {
                    self.node()?;
                    self.ty(&base.ty, 1)?;
                }
                for field in fields {
                    self.node()?;
                    self.ty(&field.ty, 1)?;
                }
                for member in members {
                    self.declaration(member, depth + 1)?;
                }
                Ok(())
            }
            Decl::Forward { .. } => Ok(()),
            Decl::ObjectiveCInterface {
                ivars,
                methods,
                properties,
                ..
            } => {
                self.items(
                    "Objective-C members",
                    ivars.len() + methods.len() + properties.len(),
                )?;
                for ivar in ivars {
                    self.node()?;
                    self.ty(&ivar.ty, 1)?;
                }
                self.objc_members(methods, properties)
            }
            Decl::ObjectiveCCategory {
                methods,
                properties,
                ..
            }
            | Decl::ObjectiveCProtocol {
                methods,
                properties,
                ..
            } => {
                self.items("Objective-C members", methods.len() + properties.len())?;
                self.objc_members(methods, properties)
            }
            Decl::ObjectiveCForward { names, .. } => {
                self.items("Objective-C forward names", names.len())
            }
        }
    }

    fn objc_members(
        &mut self,
        methods: &[crate::ObjectiveCMethod],
        properties: &[crate::ObjectiveCProperty],
    ) -> Result<(), ValidationError> {
        for method in methods {
            self.node()?;
            self.ty(&method.return_type, 1)?;
            self.items("Objective-C method parameters", method.parameters.len())?;
            for parameter in &method.parameters {
                self.node()?;
                self.ty(&parameter.ty, 1)?;
            }
        }
        for property in properties {
            self.node()?;
            self.ty(&property.ty, 1)?;
        }
        Ok(())
    }

    fn ty(&mut self, ty: &Type, depth: usize) -> Result<(), ValidationError> {
        if depth > self.limits.max_type_depth {
            return Err(ValidationError::TypeDepth {
                limit: self.limits.max_type_depth,
                actual: depth,
            });
        }
        self.node()?;
        match ty {
            Type::Builtin(_) => Ok(()),
            Type::Named {
                template_arguments, ..
            } => {
                self.items("template arguments", template_arguments.len())?;
                for argument in template_arguments {
                    self.node()?;
                    if let crate::TemplateArgument::Type(ty) = argument {
                        self.ty(ty, depth + 1)?;
                    }
                }
                Ok(())
            }
            Type::Pointer { pointee, .. }
            | Type::Reference {
                target: pointee, ..
            }
            | Type::Array {
                element: pointee, ..
            }
            | Type::ObjectiveCBlock(pointee) => self.ty(pointee, depth + 1),
            Type::Function {
                return_type,
                parameters,
                ..
            } => {
                self.items("function parameters", parameters.len())?;
                self.ty(return_type, depth + 1)?;
                for parameter in parameters {
                    self.node()?;
                    self.ty(&parameter.ty, depth + 1)?;
                }
                Ok(())
            }
            Type::ObjectiveCObject { protocols, .. } => {
                self.items("Objective-C protocols", protocols.len())
            }
        }
    }
}

fn collect_declared_types(
    declaration: &Decl,
    tags: &mut BTreeSet<String>,
    classes: &mut BTreeSet<String>,
    protocols: &mut BTreeSet<String>,
) {
    match declaration {
        Decl::Record { path, members, .. } => {
            tags.insert(path_string(path));
            for member in members {
                collect_declared_types(member, tags, classes, protocols);
            }
        }
        Decl::Forward { path, .. } | Decl::Alias { path, .. } => {
            tags.insert(path_string(path));
        }
        Decl::ObjectiveCInterface { name, .. } => {
            classes.insert(name.to_string());
        }
        Decl::ObjectiveCProtocol { name, .. } => {
            protocols.insert(name.to_string());
        }
        Decl::ObjectiveCForward { kind, names } => {
            let destination = match kind {
                ObjectiveCForwardKind::Class => classes,
                ObjectiveCForwardKind::Protocol => protocols,
            };
            destination.extend(names.iter().map(ToString::to_string));
        }
        Decl::Function { .. } | Decl::Variable { .. } | Decl::ObjectiveCCategory { .. } => {}
    }
}

fn validate_decl(
    declaration: &Decl,
    index: usize,
    tags: &BTreeSet<String>,
    classes: &BTreeSet<String>,
    protocols: &BTreeSet<String>,
    diagnostics: &mut Vec<HeaderValidationDiagnostic>,
) {
    match declaration {
        Decl::Function { signature, .. } => {
            validate_type(signature, index, tags, protocols, diagnostics)
        }
        Decl::Variable { ty, .. } | Decl::Alias { target: ty, .. } => {
            validate_type(ty, index, tags, protocols, diagnostics)
        }
        Decl::Record {
            bases,
            fields,
            members,
            ..
        } => {
            for base in bases {
                validate_type(&base.ty, index, tags, protocols, diagnostics);
            }
            for field in fields {
                validate_type(&field.ty, index, tags, protocols, diagnostics);
            }
            for member in members {
                validate_decl(member, index, tags, classes, protocols, diagnostics);
            }
        }
        Decl::Forward { .. } | Decl::ObjectiveCForward { .. } => {}
        Decl::ObjectiveCInterface {
            superclass,
            protocols: adopted,
            ivars,
            methods,
            properties,
            ..
        } => {
            if let Some(superclass) = superclass
                .as_ref()
                .filter(|name| !classes.contains(name.as_str()))
            {
                diagnostics.push(diagnostic(
                    HeaderValidationCode::UnresolvedOwner,
                    format!("Objective-C superclass `{superclass}` is not declared"),
                    index,
                ));
            }
            for ivar in ivars {
                validate_type(&ivar.ty, index, tags, protocols, diagnostics);
            }
            validate_objc_members(
                adopted,
                methods,
                properties,
                index,
                tags,
                protocols,
                diagnostics,
            );
        }
        Decl::ObjectiveCCategory {
            extended_class,
            protocols: adopted,
            methods,
            properties,
            ..
        } => {
            if !classes.contains(extended_class.as_str()) {
                diagnostics.push(diagnostic(
                    HeaderValidationCode::UnresolvedOwner,
                    format!("Objective-C category owner `{extended_class}` is not declared"),
                    index,
                ));
            }
            validate_objc_members(
                adopted,
                methods,
                properties,
                index,
                tags,
                protocols,
                diagnostics,
            );
        }
        Decl::ObjectiveCProtocol {
            protocols: adopted,
            methods,
            properties,
            ..
        } => validate_objc_members(
            adopted,
            methods,
            properties,
            index,
            tags,
            protocols,
            diagnostics,
        ),
    }
}

fn validate_objc_members(
    adopted: &[crate::Identifier],
    methods: &[crate::ObjectiveCMethod],
    properties: &[crate::ObjectiveCProperty],
    index: usize,
    tags: &BTreeSet<String>,
    protocols: &BTreeSet<String>,
    diagnostics: &mut Vec<HeaderValidationDiagnostic>,
) {
    for protocol in adopted {
        if !protocols.contains(protocol.as_str()) {
            diagnostics.push(diagnostic(
                HeaderValidationCode::ObjectiveCKindMismatch,
                format!("Objective-C protocol `{protocol}` is not declared"),
                index,
            ));
        }
    }
    let mut identities = BTreeSet::new();
    for method in methods {
        let identity = format!("method:{:?}:{}", method.kind, method.selector);
        if !identities.insert(identity) {
            diagnostics.push(diagnostic(
                HeaderValidationCode::DuplicateDeclaration,
                format!("duplicate Objective-C method `{}`", method.selector),
                index,
            ));
        }
        let arity = method.selector.bytes().filter(|byte| *byte == b':').count();
        if arity != method.parameters.len() {
            diagnostics.push(diagnostic(
                HeaderValidationCode::SelectorArityMismatch,
                format!(
                    "selector `{}` has {arity} component(s) but {} parameter(s)",
                    method.selector,
                    method.parameters.len()
                ),
                index,
            ));
        }
        validate_type(&method.return_type, index, tags, protocols, diagnostics);
        for parameter in &method.parameters {
            validate_type(&parameter.ty, index, tags, protocols, diagnostics);
        }
    }
    for property in properties {
        if !identities.insert(format!("property:{}", property.name)) {
            diagnostics.push(diagnostic(
                HeaderValidationCode::DuplicateDeclaration,
                format!("duplicate Objective-C property `{}`", property.name),
                index,
            ));
        }
        validate_type(&property.ty, index, tags, protocols, diagnostics);
    }
}

fn validate_type(
    ty: &Type,
    index: usize,
    tags: &BTreeSet<String>,
    protocols: &BTreeSet<String>,
    diagnostics: &mut Vec<HeaderValidationDiagnostic>,
) {
    match ty {
        Type::Builtin(_) => {}
        Type::Named {
            tag,
            path,
            template_arguments,
        } => {
            let name = path_string(path);
            let resolved = if matches!(tag, crate::NamedTypeTag::Protocol) {
                protocols.contains(&name)
            } else {
                tags.contains(&name)
            };
            if !resolved {
                diagnostics.push(diagnostic(
                    HeaderValidationCode::UnresolvedType,
                    format!("named type `{name}` is not declared"),
                    index,
                ));
            }
            for argument in template_arguments {
                if let crate::TemplateArgument::Type(ty) = argument {
                    validate_type(ty, index, tags, protocols, diagnostics);
                }
            }
        }
        Type::Pointer { pointee, .. }
        | Type::Reference {
            target: pointee, ..
        }
        | Type::Array {
            element: pointee, ..
        }
        | Type::ObjectiveCBlock(pointee) => {
            validate_type(pointee, index, tags, protocols, diagnostics)
        }
        Type::Function {
            return_type,
            parameters,
            ..
        } => {
            validate_type(return_type, index, tags, protocols, diagnostics);
            for parameter in parameters {
                validate_type(&parameter.ty, index, tags, protocols, diagnostics);
            }
        }
        Type::ObjectiveCObject {
            name,
            protocols: used,
            ..
        } => {
            // Class names may originate in imported SDK headers and are opaque here.
            let _ = name;
            for protocol in used {
                if !protocols.contains(protocol.as_str()) {
                    diagnostics.push(diagnostic(
                        HeaderValidationCode::ObjectiveCKindMismatch,
                        format!("Objective-C protocol `{protocol}` is not declared"),
                        index,
                    ));
                }
            }
        }
    }
}

fn validate_cycles(declarations: &[Decl], diagnostics: &mut Vec<HeaderValidationDiagnostic>) {
    let graph = declarations
        .iter()
        .filter_map(|declaration| {
            let Decl::Record { path, bases, .. } = declaration else {
                return None;
            };
            let dependencies = bases
                .iter()
                .filter_map(|base| match &base.ty {
                    Type::Named { path, .. } => Some(path_string(path)),
                    _ => None,
                })
                .collect::<BTreeSet<_>>();
            Some((path_string(path), dependencies))
        })
        .collect::<BTreeMap<_, _>>();
    for (index, declaration) in declarations.iter().enumerate() {
        let Decl::Record { path, .. } = declaration else {
            continue;
        };
        let start = path_string(path);
        if reaches(&graph, &start, &start, &mut BTreeSet::new()) {
            diagnostics.push(diagnostic(
                HeaderValidationCode::DependencyCycle,
                format!("record dependency cycle includes `{start}`"),
                index,
            ));
        }
    }
}

fn reaches(
    graph: &BTreeMap<String, BTreeSet<String>>,
    current: &str,
    target: &str,
    seen: &mut BTreeSet<String>,
) -> bool {
    if !seen.insert(current.to_owned()) {
        return false;
    }
    graph.get(current).is_some_and(|dependencies| {
        dependencies
            .iter()
            .any(|dependency| dependency == target || reaches(graph, dependency, target, seen))
    })
}

fn diagnostic(
    code: HeaderValidationCode,
    message: String,
    index: usize,
) -> HeaderValidationDiagnostic {
    diagnostic_with_severity(code, Severity::Error, message, index)
}

fn diagnostic_with_severity(
    code: HeaderValidationCode,
    severity: Severity,
    message: String,
    index: usize,
) -> HeaderValidationDiagnostic {
    HeaderValidationDiagnostic {
        code,
        severity,
        message,
        declaration_index: u32::try_from(index).ok(),
    }
}

fn path_string(path: &IdentifierPath) -> String {
    path.components()
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join("::")
}

#[cfg(test)]
mod tests {
    use crate::{
        BuiltinType, CallingConvention, Decl, FunctionQualifiers, HeaderParser, Identifier,
        IdentifierPath, Language, Linkage, MethodKind, ObjectiveCMethod, Parameter, ParameterState,
        RecordKind, StorageClass, TranslationUnit, Type,
    };

    use super::*;

    #[test]
    fn duplicate_definitions_are_rejected() {
        let declaration = Decl::Record {
            kind: RecordKind::Struct,
            path: IdentifierPath::new(vec![Identifier::new("Value").unwrap()]).unwrap(),
            bases: Vec::new(),
            fields: Vec::new(),
            members: Vec::new(),
        };
        let report = validate(
            &TranslationUnit {
                language: Language::C,
                declarations: vec![declaration.clone(), declaration],
                declaration_spans: Vec::new(),
            },
            ValidationLimits::default(),
        )
        .unwrap();
        assert!(!report.semantic_valid);
        assert_eq!(
            report.diagnostics[0].code,
            HeaderValidationCode::DuplicateDeclaration
        );
    }

    #[test]
    fn compatible_function_redeclarations_are_accepted() {
        let function = |parameter_name: &str, return_type| Decl::Function {
            name: Identifier::new("transform").unwrap(),
            signature: Type::Function {
                return_type: Box::new(Type::Builtin(return_type)),
                parameters: vec![Parameter {
                    name: Identifier::new(parameter_name).unwrap(),
                    ty: Type::Builtin(BuiltinType::Int),
                }],
                parameter_state: ParameterState::Known,
                variadic: false,
                calling_convention: CallingConvention::C,
                qualifiers: FunctionQualifiers::default(),
            },
            storage: StorageClass::Extern,
            linkage: Linkage::C,
        };
        let report = validate(
            &TranslationUnit {
                language: Language::C,
                declarations: vec![
                    function("input", BuiltinType::Int),
                    function("value", BuiltinType::Int),
                ],
                declaration_spans: Vec::new(),
            },
            ValidationLimits::default(),
        )
        .unwrap();
        assert!(report.semantic_valid);
        assert_eq!(report.diagnostics[0].severity, Severity::Info);
    }

    #[test]
    fn conflicting_function_redeclarations_are_rejected() {
        let function = |return_type| Decl::Function {
            name: Identifier::new("transform").unwrap(),
            signature: Type::Function {
                return_type: Box::new(Type::Builtin(return_type)),
                parameters: Vec::new(),
                parameter_state: ParameterState::Known,
                variadic: false,
                calling_convention: CallingConvention::C,
                qualifiers: FunctionQualifiers::default(),
            },
            storage: StorageClass::Extern,
            linkage: Linkage::C,
        };
        let report = validate(
            &TranslationUnit {
                language: Language::C,
                declarations: vec![function(BuiltinType::Int), function(BuiltinType::Long)],
                declaration_spans: Vec::new(),
            },
            ValidationLimits::default(),
        )
        .unwrap();
        assert!(!report.semantic_valid);
        assert_eq!(
            report.diagnostics[0].code,
            HeaderValidationCode::ConflictingRedeclaration
        );
    }

    #[test]
    fn selector_arity_is_checked() {
        let report = validate(
            &TranslationUnit {
                language: Language::ObjectiveC,
                declarations: vec![Decl::ObjectiveCProtocol {
                    name: Identifier::new("Widget").unwrap(),
                    protocols: Vec::new(),
                    methods: vec![ObjectiveCMethod {
                        kind: MethodKind::Instance,
                        selector: "setValue:".to_owned(),
                        return_type: Type::Builtin(BuiltinType::Void),
                        parameters: Vec::new(),
                        required: Some(true),
                    }],
                    properties: Vec::new(),
                }],
                declaration_spans: Vec::new(),
            },
            ValidationLimits::default(),
        )
        .unwrap();
        assert_eq!(
            report.diagnostics[0].code,
            HeaderValidationCode::SelectorArityMismatch
        );
    }

    #[test]
    fn objc_class_forward_resolves_reparsed_named_pointer_types() {
        let unit = crate::TreeSitterHeaderParser
            .parse(
                Language::ObjectiveC,
                "@class NSString;\n@interface Widget\n@property NSString * name;\n@end\n",
            )
            .unwrap();
        let report = validate(&unit, ValidationLimits::default()).unwrap();
        assert!(report.semantic_valid, "{:?}", report.diagnostics);
    }

    #[test]
    fn type_depth_is_bounded() {
        let mut ty = Type::Builtin(BuiltinType::Int);
        for _ in 0..65 {
            ty = Type::Pointer {
                pointee: Box::new(ty),
                qualifiers: Default::default(),
            };
        }
        let error = validate(
            &TranslationUnit {
                language: Language::C,
                declarations: vec![Decl::Variable {
                    name: Identifier::new("value").unwrap(),
                    ty,
                    storage: StorageClass::None,
                    linkage: Linkage::C,
                }],
                declaration_spans: Vec::new(),
            },
            ValidationLimits::default(),
        )
        .unwrap_err();
        assert!(matches!(error, ValidationError::TypeDepth { .. }));
    }
}