syster-base 0.3.2-alpha

Core library for SysML v2 and KerML parsing, AST, and semantic analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! Diagnostics — Semantic error reporting.
//!
//! This module provides diagnostic types for semantic analysis errors
//! and warnings. It integrates with the symbol index and resolver.

use std::sync::Arc;

use super::resolve::{ResolveResult, Resolver, SymbolIndex};
use super::symbols::{HirSymbol, SymbolKind};
use crate::base::FileId;

// ============================================================================
// DIAGNOSTIC TYPES
// ============================================================================

/// Severity level of a diagnostic.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Severity {
    Error,
    Warning,
    Info,
    Hint,
}

impl Severity {
    /// Convert to LSP severity number.
    pub fn to_lsp(&self) -> u32 {
        match self {
            Severity::Error => 1,
            Severity::Warning => 2,
            Severity::Info => 3,
            Severity::Hint => 4,
        }
    }
}

/// A diagnostic message with location.
#[derive(Clone, Debug)]
pub struct Diagnostic {
    /// The file containing this diagnostic.
    pub file: FileId,
    /// Start line (0-indexed).
    pub start_line: u32,
    /// Start column (0-indexed).
    pub start_col: u32,
    /// End line (0-indexed).
    pub end_line: u32,
    /// End column (0-indexed).
    pub end_col: u32,
    /// Severity level.
    pub severity: Severity,
    /// Error/warning code (e.g., "E0001").
    pub code: Option<Arc<str>>,
    /// The diagnostic message.
    pub message: Arc<str>,
    /// Optional related information.
    pub related: Vec<RelatedInfo>,
}

/// Related information for a diagnostic.
#[derive(Clone, Debug)]
pub struct RelatedInfo {
    /// The file containing this info.
    pub file: FileId,
    /// Line number.
    pub line: u32,
    /// Column number.
    pub col: u32,
    /// The message.
    pub message: Arc<str>,
}

impl Diagnostic {
    /// Create a new error diagnostic.
    pub fn error(file: FileId, line: u32, col: u32, message: impl Into<Arc<str>>) -> Self {
        Self {
            file,
            start_line: line,
            start_col: col,
            end_line: line,
            end_col: col,
            severity: Severity::Error,
            code: None,
            message: message.into(),
            related: Vec::new(),
        }
    }

    /// Create a new warning diagnostic.
    pub fn warning(file: FileId, line: u32, col: u32, message: impl Into<Arc<str>>) -> Self {
        Self {
            file,
            start_line: line,
            start_col: col,
            end_line: line,
            end_col: col,
            severity: Severity::Warning,
            code: None,
            message: message.into(),
            related: Vec::new(),
        }
    }

    /// Set the span (range) for this diagnostic.
    pub fn with_span(mut self, end_line: u32, end_col: u32) -> Self {
        self.end_line = end_line;
        self.end_col = end_col;
        self
    }

    /// Set the error code.
    pub fn with_code(mut self, code: impl Into<Arc<str>>) -> Self {
        self.code = Some(code.into());
        self
    }

    /// Add related information.
    pub fn with_related(mut self, info: RelatedInfo) -> Self {
        self.related.push(info);
        self
    }
}

// ============================================================================
// DIAGNOSTIC CODES
// ============================================================================

/// Standard diagnostic codes for semantic errors.
///
/// ## Error Code Ranges
///
/// - **E0001-E0099**: Semantic analysis errors (symbol resolution, type checking, validation)
/// - **W0001-W0099**: Warnings (unused, deprecated, conventions)
#[allow(dead_code)]
pub mod codes {
    // ========================================================================
    // SEMANTIC ERRORS (E0001-E0099)
    // ========================================================================

    /// Undefined reference (name not found).
    pub const UNDEFINED_REFERENCE: &str = "E0001";
    /// Ambiguous reference (multiple candidates).
    pub const AMBIGUOUS_REFERENCE: &str = "E0002";
    /// Type mismatch.
    pub const TYPE_MISMATCH: &str = "E0003";
    /// Duplicate definition.
    pub const DUPLICATE_DEFINITION: &str = "E0004";
    /// Missing required element.
    pub const MISSING_REQUIRED: &str = "E0005";
    /// Invalid specialization relationship.
    pub const INVALID_SPECIALIZATION: &str = "E0006";
    /// Circular dependency detected.
    pub const CIRCULAR_DEPENDENCY: &str = "E0007";
    /// Invalid type.
    pub const INVALID_TYPE: &str = "E0008";
    /// Invalid redefinition.
    pub const INVALID_REDEFINITION: &str = "E0009";
    /// Invalid subsetting relationship.
    pub const INVALID_SUBSETTING: &str = "E0010";
    /// Constraint violation.
    pub const CONSTRAINT_VIOLATION: &str = "E0011";
    /// Feature used in invalid context.
    pub const INVALID_FEATURE_CONTEXT: &str = "E0012";
    /// Cannot instantiate abstract element.
    pub const ABSTRACT_INSTANTIATION: &str = "E0013";
    /// Invalid import statement.
    pub const INVALID_IMPORT: &str = "E0014";

    // ========================================================================
    // WARNINGS (W0001-W0099)
    // ========================================================================

    /// Unused symbol.
    pub const UNUSED_SYMBOL: &str = "W0001";
    /// Deprecated usage.
    pub const DEPRECATED: &str = "W0002";
    /// Naming convention violation.
    pub const NAMING_CONVENTION: &str = "W0003";
}

// ============================================================================
// DIAGNOSTIC COLLECTOR
// ============================================================================

/// Collects diagnostics during semantic analysis.
#[derive(Clone, Debug, Default)]
pub struct DiagnosticCollector {
    diagnostics: Vec<Diagnostic>,
}

impl DiagnosticCollector {
    /// Create a new empty collector.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a diagnostic.
    pub fn add(&mut self, diagnostic: Diagnostic) {
        self.diagnostics.push(diagnostic);
    }

    /// Add an undefined reference error.
    pub fn undefined_reference(&mut self, file: FileId, symbol: &HirSymbol, name: &str) {
        self.add(
            Diagnostic::error(
                file,
                symbol.start_line,
                symbol.start_col,
                format!("undefined reference: '{}'", name),
            )
            .with_span(symbol.end_line, symbol.end_col)
            .with_code(codes::UNDEFINED_REFERENCE),
        );
    }

    /// Add an ambiguous reference error.
    pub fn ambiguous_reference(
        &mut self,
        file: FileId,
        symbol: &HirSymbol,
        name: &str,
        candidates: &[HirSymbol],
    ) {
        let candidate_names: Vec<_> = candidates
            .iter()
            .map(|c| c.qualified_name.as_ref())
            .collect();
        let mut diag = Diagnostic::error(
            file,
            symbol.start_line,
            symbol.start_col,
            format!(
                "ambiguous reference: '{}' could be: {}",
                name,
                candidate_names.join(", ")
            ),
        )
        .with_span(symbol.end_line, symbol.end_col)
        .with_code(codes::AMBIGUOUS_REFERENCE);

        // Add related info for each candidate
        for candidate in candidates {
            diag = diag.with_related(RelatedInfo {
                file: candidate.file,
                line: candidate.start_line,
                col: candidate.start_col,
                message: Arc::from(format!("candidate: {}", candidate.qualified_name)),
            });
        }

        self.add(diag);
    }

    /// Add a duplicate definition error.
    pub fn duplicate_definition(&mut self, file: FileId, symbol: &HirSymbol, existing: &HirSymbol) {
        self.add(
            Diagnostic::error(
                file,
                symbol.start_line,
                symbol.start_col,
                format!("duplicate definition: '{}' is already defined", symbol.name),
            )
            .with_span(symbol.end_line, symbol.end_col)
            .with_code(codes::DUPLICATE_DEFINITION)
            .with_related(RelatedInfo {
                file: existing.file,
                line: existing.start_line,
                col: existing.start_col,
                message: Arc::from(format!("previous definition of '{}'", existing.name)),
            }),
        );
    }

    /// Add a type mismatch error.
    pub fn type_mismatch(&mut self, file: FileId, symbol: &HirSymbol, expected: &str, found: &str) {
        self.add(
            Diagnostic::error(
                file,
                symbol.start_line,
                symbol.start_col,
                format!("type mismatch: expected '{}', found '{}'", expected, found),
            )
            .with_span(symbol.end_line, symbol.end_col)
            .with_code(codes::TYPE_MISMATCH),
        );
    }

    /// Add an unused symbol warning.
    pub fn unused_symbol(&mut self, symbol: &HirSymbol) {
        self.add(
            Diagnostic::warning(
                symbol.file,
                symbol.start_line,
                symbol.start_col,
                format!("unused {}: '{}'", symbol.kind.display(), symbol.name),
            )
            .with_span(symbol.end_line, symbol.end_col)
            .with_code(codes::UNUSED_SYMBOL),
        );
    }

    /// Get all diagnostics.
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Get diagnostics for a specific file.
    pub fn diagnostics_for_file(&self, file: FileId) -> Vec<&Diagnostic> {
        self.diagnostics.iter().filter(|d| d.file == file).collect()
    }

    /// Get the number of errors.
    pub fn error_count(&self) -> usize {
        self.diagnostics
            .iter()
            .filter(|d| d.severity == Severity::Error)
            .count()
    }

    /// Get the number of warnings.
    pub fn warning_count(&self) -> usize {
        self.diagnostics
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .count()
    }

    /// Check if there are any errors.
    pub fn has_errors(&self) -> bool {
        self.diagnostics
            .iter()
            .any(|d| d.severity == Severity::Error)
    }

    /// Take all diagnostics, leaving the collector empty.
    pub fn take(&mut self) -> Vec<Diagnostic> {
        std::mem::take(&mut self.diagnostics)
    }

    /// Clear all diagnostics.
    pub fn clear(&mut self) {
        self.diagnostics.clear();
    }
}

// ============================================================================
// SEMANTIC CHECKER
// ============================================================================

/// Performs semantic checks on symbols using the resolver.
pub struct SemanticChecker<'a> {
    index: &'a SymbolIndex,
    collector: DiagnosticCollector,
    /// Track which symbols are referenced (for unused detection).
    referenced: std::collections::HashSet<Arc<str>>,
}

impl<'a> SemanticChecker<'a> {
    /// Create a new semantic checker.
    pub fn new(index: &'a SymbolIndex) -> Self {
        Self {
            index,
            collector: DiagnosticCollector::new(),
            referenced: std::collections::HashSet::new(),
        }
    }

    /// Check all symbols in a file.
    pub fn check_file(&mut self, file: FileId) {
        let symbols = self.index.symbols_in_file(file);

        // Pass 1: Check references and collect what's referenced
        for symbol in &symbols {
            self.check_symbol(symbol);
        }

        // Pass 2: Check for duplicates within this file
        self.check_duplicates(file, &symbols);
    }

    /// Run all checks across the entire index (for workspace-wide diagnostics).
    pub fn check_all(&mut self) {
        // Collect all symbols first
        let all_symbols: Vec<_> = self.index.all_symbols().cloned().collect();

        // Check each symbol
        for symbol in &all_symbols {
            self.check_symbol(symbol);
        }

        // Check for unused definitions (only meaningful after checking all references)
        // Disabled by default as it can be noisy - uncomment to enable
        // self.check_unused(&all_symbols);
    }

    /// Check a single symbol.
    fn check_symbol(&mut self, symbol: &HirSymbol) {
        // NOTE: We don't check supertypes directly because they mix type references
        // (from `: TypeName`) with feature references (from `subsets featureName`).
        // Instead, we rely on type_refs which have proper RefKind discrimination.
        // The type_refs extraction already captures TypedBy relationships.

        // Check type_refs based on their RefKind
        self.check_type_refs(symbol);
    }

    /// Check type references in a symbol's body, filtering by RefKind.
    fn check_type_refs(&mut self, symbol: &HirSymbol) {
        use crate::hir::symbols::TypeRefKind;

        // Skip anonymous symbols (e.g., shorthand redefines like `:>> threadDia`)
        // Their type_refs are feature references that need inheritance context
        if symbol.qualified_name.contains("<:") {
            return;
        }

        for type_ref in &symbol.type_refs {
            match type_ref {
                TypeRefKind::Simple(tr) => {
                    // If already resolved, track as referenced
                    if let Some(ref resolved) = tr.resolved_target {
                        self.referenced.insert(resolved.clone());
                        continue;
                    }

                    // Check based on reference kind
                    if tr.kind.is_type_reference() {
                        // Type references resolve via scope walking
                        self.check_type_reference(symbol, &tr.target);
                    } else if tr.kind.is_feature_reference() {
                        // Feature references (Redefines, Subsets) resolve via inheritance
                        self.check_feature_reference(symbol, &tr.target);
                    }
                    // Expression and Other refs are not checked
                }
                TypeRefKind::Chain(chain) => {
                    // Track resolved parts
                    for part in &chain.parts {
                        if let Some(ref resolved) = part.resolved_target {
                            self.referenced.insert(resolved.clone());
                        }
                    }
                    // Chains are typically feature access paths, don't check as types
                }
            }
        }
    }

    /// Check a feature reference resolves via inheritance.
    ///
    /// For `attribute mass redefines Vehicle::mass`, we:
    /// 1. Parse the target - could be qualified (Vehicle::mass) or simple (mass)
    /// 2. For qualified: resolve the prefix, then find member in that scope
    /// 3. For simple: look in containing symbol's supertypes
    fn check_feature_reference(&mut self, symbol: &HirSymbol, target: &str) {
        // Strip index expressions like [1] from the target (e.g., "cylinders[1]" -> "cylinders")
        let target = if let Some(bracket_pos) = target.find('[') {
            &target[..bracket_pos]
        } else {
            target
        };

        // Handle qualified references like "Vehicle::mass"
        if let Some(idx) = target.rfind("::") {
            let prefix = &target[..idx];
            let member = &target[idx + 2..];

            // Resolve the prefix (e.g., "Vehicle")
            let scope = Self::extract_scope(&symbol.qualified_name);
            let resolver = Resolver::new(self.index).with_scope(scope);

            match resolver.resolve(prefix) {
                ResolveResult::Found(prefix_sym) => {
                    // Now look for the member in that symbol's scope
                    if let Some(found) = self
                        .index
                        .find_member_in_scope(&prefix_sym.qualified_name, member)
                    {
                        self.referenced.insert(found.qualified_name.clone());
                    } else if !Self::is_builtin_type(target) {
                        // Member not found in the specified scope
                        self.collector
                            .undefined_reference(symbol.file, symbol, target);
                    }
                }
                ResolveResult::NotFound => {
                    // Prefix itself couldn't be resolved
                    if !Self::is_builtin_type(prefix) {
                        self.collector
                            .undefined_reference(symbol.file, symbol, target);
                    }
                }
                ResolveResult::Ambiguous(_) => {
                    // Ambiguous prefix - could report but likely not the user's error
                }
            }
            return;
        }

        // Simple reference like "mass" - look in containing symbol's inheritance chain
        // The containing symbol should have supertypes that define this feature

        // First, check if it's defined in the current symbol itself (local redefinition)
        let member_qname = format!("{}::{}", symbol.qualified_name, target);
        if self.index.lookup_qualified(&member_qname).is_some() {
            self.referenced.insert(Arc::from(member_qname));
            return;
        }

        // Check if it's visible in the parent scope using visibility map resolution
        // (e.g., `:> vehicleAlternatives` where vehicleAlternatives is a sibling subject)
        let scope = Self::extract_scope(&symbol.qualified_name);
        let resolver = Resolver::new(self.index).with_scope(scope.clone());
        if let ResolveResult::Found(sibling_sym) = resolver.resolve(target) {
            self.referenced.insert(sibling_sym.qualified_name.clone());
            return;
        }

        // Look in the symbol's supertypes for the feature
        for supertype in &symbol.supertypes {
            // Resolve the supertype
            let resolver = Resolver::new(self.index).with_scope(scope.clone());

            if let ResolveResult::Found(super_sym) = resolver.resolve(supertype) {
                // Look for the member in the supertype (recursive search)
                if let Some(found) = self
                    .index
                    .find_member_in_scope(&super_sym.qualified_name, target)
                {
                    self.referenced.insert(found.qualified_name.clone());
                    return;
                }
            }
        }

        // Still not found - might be in a supertype's supertype, or genuinely undefined
        // Don't report error if it could be from stdlib or unloaded types
        if !Self::is_builtin_type(target) && !symbol.supertypes.is_empty() {
            // Only report if the symbol has supertypes (so we expected to find it)
            // But actually, this is often a false positive since we haven't loaded stdlib
            // For now, we'll be lenient and not report these
            // self.collector.undefined_reference(symbol.file, symbol, target);
        }
    }

    /// Check a type reference resolves correctly.
    fn check_type_reference(&mut self, symbol: &HirSymbol, name: &str) {
        let scope = Self::extract_scope(&symbol.qualified_name);
        let resolver = Resolver::new(self.index).with_scope(scope);

        match resolver.resolve(name) {
            ResolveResult::Found(resolved) => {
                // Track that this symbol is referenced
                self.referenced.insert(resolved.qualified_name.clone());
            }
            ResolveResult::Ambiguous(candidates) => {
                self.collector
                    .ambiguous_reference(symbol.file, symbol, name, &candidates);
            }
            ResolveResult::NotFound => {
                // Only report undefined if it's not a built-in/primitive type
                // Also skip expression paths that contain dots (like "foo.bar.baz")
                // These are member access expressions, not type references
                if !Self::is_builtin_type(name) && !name.contains('.') {
                    self.collector
                        .undefined_reference(symbol.file, symbol, name);
                }
            }
        }
    }

    /// Check for duplicate definitions within a file.
    fn check_duplicates(&mut self, file: FileId, symbols: &[&HirSymbol]) {
        use std::collections::HashMap;

        // Group by qualified name
        let mut by_qname: HashMap<&str, Vec<&HirSymbol>> = HashMap::new();
        for symbol in symbols {
            // Skip imports and aliases - they don't count as definitions
            if symbol.kind == SymbolKind::Import || symbol.kind == SymbolKind::Alias {
                continue;
            }
            // Skip anonymous elements - they have synthetic names like <anonymous-dependency>
            // and multiple anonymous elements with the same synthetic name are allowed
            if symbol.name.starts_with('<') && symbol.name.ends_with('>') {
                continue;
            }
            // Skip elements whose qualified name contains anonymous parent segments
            // (e.g., parameters inside anonymous transitions like `<:>>foo#1@L26>::s`)
            // Anonymous segments have format `<...#N@LNN>`
            if symbol.qualified_name.contains("<") && symbol.qualified_name.contains("#") {
                continue;
            }
            by_qname
                .entry(symbol.qualified_name.as_ref())
                .or_default()
                .push(symbol);
        }

        // Report duplicates
        for (_qname, defs) in by_qname {
            if defs.len() > 1 {
                // Report error on all but the first definition
                let first = defs[0];
                for dup in &defs[1..] {
                    self.collector.duplicate_definition(file, dup, first);
                }
            }
        }
    }

    /// Check for unused definitions (optional, can be noisy).
    #[allow(dead_code)]
    fn check_unused(&mut self, symbols: &[HirSymbol]) {
        for symbol in symbols {
            // Only check definitions, not usages
            if !symbol.kind.is_definition() {
                continue;
            }

            // Skip packages - they're organizational
            if symbol.kind == SymbolKind::Package {
                continue;
            }

            // Skip if referenced
            if self.referenced.contains(&symbol.qualified_name) {
                continue;
            }

            // Skip if it has supertypes (might be used via specialization)
            if !symbol.supertypes.is_empty() {
                continue;
            }

            self.collector.unused_symbol(symbol);
        }
    }

    /// Check if a type name is a built-in/primitive that doesn't need resolution.
    ///
    /// This includes:
    /// - KerML primitives (Boolean, Integer, etc.)
    /// - References to standard library packages (ISQ::*, SI::*, etc.)
    fn is_builtin_type(name: &str) -> bool {
        // Primitive types from KerML
        if matches!(
            name,
            "Boolean"
                | "String"
                | "Integer"
                | "Real"
                | "Natural"
                | "Positive"
                | "UnlimitedNatural"
                | "Complex"
                | "ScalarValues"
                | "Base"
                | "Anything"
        ) {
            return true;
        }

        // Standard library package prefixes
        // These are defined in the SysML Standard Library
        let stdlib_prefixes = [
            "ISQ::", // International System of Quantities
            "SI::",  // International System of Units
            "USCustomaryUnits::",
            "Quantities::",
            "MeasurementReferences::",
            "QuantityCalculations::",
            "TensorMeasurements::",
            "TrigFunctions::",
            "BaseFunctions::",
            "DataFunctions::",
            "ControlFunctions::",
            "NumericalFunctions::",
            "VectorFunctions::",
            "SequenceFunctions::",
            "CollectionFunctions::",
            "Performances::",
            "ScalarValues::",
            "RealFunctions::",
            "Time::",
            "Collections::",
            "Links::",
            "Occurrences::",
            "Objects::",
            "Items::",
            "Parts::",
            "Ports::",
            "Connections::",
            "Interfaces::",
            "Allocations::",
            "Actions::",
            "Calculations::",
            "Constraints::",
            "Requirements::",
            "Cases::",
            "AnalysisCases::",
            "Metadata::",
            "KerML::",
            "SysML::",
        ];

        for prefix in stdlib_prefixes {
            if name.starts_with(prefix) {
                return true;
            }
        }

        // Also handle simple names that are common stdlib types/packages
        // These might be imported with wildcard imports or referenced directly
        let stdlib_types = [
            // Packages (used as namespace references)
            "ISQ",
            "SI",
            "USCustomaryUnits",
            "Quantities",
            // Quantities
            "MassValue",
            "LengthValue",
            "TimeValue",
            "VelocityValue",
            "AccelerationValue",
            "ForceValue",
            "EnergyValue",
            "PowerValue",
            "PressureValue",
            "TemperatureValue",
            "ElectricCurrentValue",
            "TorqueValue",
            "AreaValue",
            "VolumeValue",
            "DensityValue",
            "AngleValue",
            "AngularVelocityValue",
            "AngularAccelerationValue",
            // Units
            "kg",
            "m",
            "s",
            "A",
            "K",
            "mol",
            "cd",
            "N",
            "J",
            "W",
            "Pa",
            // Common types
            "distancePerVolume",
            "length",
            "time",
            "mass",
            "power",
            // Functions and calculations
            "SampledFunction",
            "SamplePair",
            // Trade studies
            "TradeStudy",
            "evaluationFunction",
            // Modeling metadata
            "mop",
            "status",
        ];

        stdlib_types.contains(&name)
    }

    /// Extract scope from a qualified name.
    fn extract_scope(qualified_name: &str) -> String {
        if let Some(pos) = qualified_name.rfind("::") {
            qualified_name[..pos].to_string()
        } else {
            String::new()
        }
    }

    /// Get the collected diagnostics, deduplicated.
    pub fn finish(self) -> Vec<Diagnostic> {
        let mut seen = std::collections::HashSet::new();
        self.collector
            .diagnostics
            .into_iter()
            .filter(|d| {
                // Deduplicate by (file, line, col, message)
                let key = (d.file, d.start_line, d.start_col, d.message.clone());
                seen.insert(key)
            })
            .collect()
    }
}

/// Check a file and return diagnostics.
pub fn check_file(index: &SymbolIndex, file: FileId) -> Vec<Diagnostic> {
    let mut checker = SemanticChecker::new(index);
    checker.check_file(file);
    checker.finish()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hir::{SymbolKind, new_element_id};

    fn make_symbol(name: &str, qualified: &str, kind: SymbolKind, file: u32) -> HirSymbol {
        HirSymbol {
            name: Arc::from(name),
            short_name: None,
            qualified_name: Arc::from(qualified),
            element_id: new_element_id(),
            kind,
            file: FileId::new(file),
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 0,
            short_name_start_line: None,
            short_name_start_col: None,
            short_name_end_line: None,
            short_name_end_col: None,
            doc: None,
            supertypes: Vec::new(),
            relationships: Vec::new(),
            type_refs: Vec::new(),
            is_public: false,
            view_data: None,
            metadata_annotations: Vec::new(),
            is_abstract: false,
            is_variation: false,
            is_readonly: false,
            is_derived: false,
            is_parallel: false,
            is_individual: false,
            is_end: false,
            is_default: false,
            is_ordered: false,
            is_nonunique: false,
            is_portion: false,
            direction: None,
            multiplicity: None,
        }
    }

    #[test]
    fn test_diagnostic_error() {
        let diag = Diagnostic::error(FileId::new(0), 10, 5, "test error");
        assert_eq!(diag.severity, Severity::Error);
        assert_eq!(diag.start_line, 10);
        assert_eq!(diag.start_col, 5);
    }

    #[test]
    fn test_diagnostic_with_code() {
        let diag =
            Diagnostic::error(FileId::new(0), 0, 0, "test").with_code(codes::UNDEFINED_REFERENCE);
        assert_eq!(diag.code.as_deref(), Some("E0001"));
    }

    #[test]
    fn test_collector_counts() {
        let mut collector = DiagnosticCollector::new();
        collector.add(Diagnostic::error(FileId::new(0), 0, 0, "error 1"));
        collector.add(Diagnostic::error(FileId::new(0), 0, 0, "error 2"));
        collector.add(Diagnostic::warning(FileId::new(0), 0, 0, "warning 1"));

        assert_eq!(collector.error_count(), 2);
        assert_eq!(collector.warning_count(), 1);
        assert!(collector.has_errors());
    }

    #[test]
    fn test_collector_by_file() {
        let mut collector = DiagnosticCollector::new();
        collector.add(Diagnostic::error(FileId::new(0), 0, 0, "file 0"));
        collector.add(Diagnostic::error(FileId::new(1), 0, 0, "file 1"));
        collector.add(Diagnostic::error(FileId::new(0), 0, 0, "file 0 again"));

        let file0_diags = collector.diagnostics_for_file(FileId::new(0));
        assert_eq!(file0_diags.len(), 2);

        let file1_diags = collector.diagnostics_for_file(FileId::new(1));
        assert_eq!(file1_diags.len(), 1);
    }

    #[test]
    fn test_severity_to_lsp() {
        assert_eq!(Severity::Error.to_lsp(), 1);
        assert_eq!(Severity::Warning.to_lsp(), 2);
        assert_eq!(Severity::Info.to_lsp(), 3);
        assert_eq!(Severity::Hint.to_lsp(), 4);
    }

    #[test]
    fn test_semantic_checker_undefined_reference() {
        use crate::hir::symbols::{RefKind, TypeRef, TypeRefKind};

        let mut index = SymbolIndex::new();

        // Add a symbol that references a non-existent type via type_refs
        let mut symbol = make_symbol("wheel", "Vehicle::wheel", SymbolKind::PartUsage, 0);
        symbol.type_refs = vec![TypeRefKind::Simple(TypeRef::new(
            "NonExistent",
            RefKind::TypedBy,
            0,
            0,
            0,
            11,
        ))];

        index.add_file(FileId::new(0), vec![symbol]);

        let diagnostics = check_file(&index, FileId::new(0));

        assert_eq!(diagnostics.len(), 1);
        assert!(diagnostics[0].message.contains("undefined reference"));
    }

    #[test]
    fn test_semantic_checker_valid_reference() {
        let mut index = SymbolIndex::new();

        // Add the type definition
        let wheel_def = make_symbol("Wheel", "Wheel", SymbolKind::PartDefinition, 0);

        // Add a symbol that references the type
        let mut wheel_usage = make_symbol("wheel", "Vehicle::wheel", SymbolKind::PartUsage, 0);
        wheel_usage.supertypes = vec![Arc::from("Wheel")];

        index.add_file(FileId::new(0), vec![wheel_def, wheel_usage]);

        let diagnostics = check_file(&index, FileId::new(0));

        // Should have no errors - reference resolves
        assert_eq!(diagnostics.len(), 0);
    }
}