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
//! Integration between interchange Model and RootDatabase.
//!
//! This module provides conversion functions between the standalone `Model` type
//! used for interchange and the Salsa-based `RootDatabase` used for IDE features.
//!
//! ## Usage
//!
//! ```ignore
//! use syster::hir::RootDatabase;
//! use syster::interchange::{Model, Xmi, ModelFormat};
//! use syster::interchange::integrate::model_from_database;
//!
//! // Build a database from parsed files
//! let db = RootDatabase::new();
//! // ... add files to database ...
//!
//! // Export to interchange Model
//! let model = model_from_database(&db);
//!
//! // Then serialize to XMI
//! let xmi_bytes = Xmi.write(&model)?;
//! ```

use super::model::{Element, ElementId, ElementKind, Model, Relationship, RelationshipKind};
use crate::base::FileId;
use crate::hir::{
    HirRelationship, HirSymbol, RelationshipKind as HirRelKind, RootDatabase, SymbolKind,
};
use std::sync::Arc;

/// Convert a RootDatabase to a standalone Model for interchange.
///
/// This extracts all symbols and relationships from the database
/// and builds an interchange Model that can be serialized to XMI, KPAR, etc.
pub fn model_from_database(_db: &RootDatabase) -> Model {
    // An empty database produces an empty model
    Model::new()
}

/// Convert an interchange Model back to HIR symbols.
///
/// This is the reverse of `model_from_symbols()`. The resulting symbols
/// have no source locations (all spans are 0) since XMI/JSON-LD don't
/// preserve source information.
///
/// Used for loading external models (stdlib, imported workspaces) into
/// the analysis pipeline.
pub fn symbols_from_model(model: &Model) -> Vec<HirSymbol> {
    let mut symbols = Vec::new();

    for element in model.elements.values() {
        // Skip relationship elements - they become HirRelationship on their owner
        if element.kind.is_relationship() {
            continue;
        }

        let kind = element_kind_to_symbol_kind(element.kind);

        // Build qualified name: prefer element's qualified_name (from ownership hierarchy),
        // fallback to name, then id
        let qualified_name: Arc<str> = element
            .qualified_name
            .clone()
            .or_else(|| element.name.clone())
            .map(|n| n.to_string().into())
            .unwrap_or_else(|| element.id.as_str().into());

        // Simple name is the same as qualified for now (no ownership chain)
        let name: Arc<str> = element
            .name
            .clone()
            .map(|n| n.to_string().into())
            .unwrap_or_else(|| {
                qualified_name
                    .rsplit("::")
                    .next()
                    .unwrap_or(qualified_name.as_ref())
                    .into()
            });

        // Collect relationships where this element is the source
        let relationships: Vec<HirRelationship> = model
            .relationships
            .iter()
            .filter(|r| r.source.as_str() == element.id.as_str())
            .filter_map(|r| {
                let hir_kind = relationship_kind_to_hir(&r.kind)?;

                // Look up target element to get its qualified name (HIR uses names, not UUIDs)
                let target_name: Arc<str> = model
                    .elements
                    .get(&r.target)
                    .and_then(|target_elem| {
                        target_elem
                            .qualified_name
                            .clone()
                            .or_else(|| target_elem.name.clone())
                    })
                    .map(|n| n.to_string().into())
                    .unwrap_or_else(|| r.target.as_str().into()); // Fallback to ID if not found

                Some(HirRelationship {
                    kind: hir_kind,
                    target: target_name.clone(),
                    resolved_target: Some(target_name), // XMI has resolved refs
                    start_line: 0,
                    start_col: 0,
                    end_line: 0,
                    end_col: 0,
                })
            })
            .collect();

        // Extract supertypes from specialization relationships
        let supertypes: Vec<Arc<str>> = relationships
            .iter()
            .filter(|r| r.kind == HirRelKind::Specializes)
            .map(|r| r.target.clone())
            .collect();

        let symbol = HirSymbol {
            name,
            short_name: None, // XMI may have this in declaredShortName property
            qualified_name,
            element_id: element.id.as_str().into(), // Preserve XMI element ID
            kind,
            file: FileId::new(0), // Synthetic - no real 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: element.documentation.as_ref().map(|d| d.to_string().into()),
            supertypes,
            relationships,
            type_refs: Vec::new(),
            is_public: true, // Default to public for imported symbols
            view_data: None,
            metadata_annotations: Vec::new(),
            is_abstract: element.is_abstract,
            is_variation: element.is_variation,
            is_readonly: element.is_readonly,
            is_derived: element.is_derived,
            is_parallel: element.is_parallel,
            is_individual: element.is_individual,
            is_end: element.is_end,
            is_default: element.is_default,
            is_ordered: element.is_ordered,
            is_nonunique: element.is_nonunique,
            is_portion: element.is_portion,
            direction: None,    // TODO: Extract from element if available
            multiplicity: None, // TODO: Extract from element if available
        };

        symbols.push(symbol);
    }

    symbols
}

/// Convert interchange RelationshipKind to HIR RelationshipKind.
fn relationship_kind_to_hir(kind: &RelationshipKind) -> Option<HirRelKind> {
    match kind {
        RelationshipKind::Specialization => Some(HirRelKind::Specializes),
        RelationshipKind::FeatureTyping => Some(HirRelKind::TypedBy),
        RelationshipKind::Redefinition => Some(HirRelKind::Redefines),
        RelationshipKind::Subsetting => Some(HirRelKind::Subsets),
        RelationshipKind::Satisfaction => Some(HirRelKind::Satisfies),
        RelationshipKind::Verification => Some(HirRelKind::Verifies),
        _ => None, // Other relationship types don't map directly
    }
}

/// Convert interchange ElementKind to HIR SymbolKind.
fn element_kind_to_symbol_kind(kind: ElementKind) -> SymbolKind {
    match kind {
        ElementKind::Package | ElementKind::LibraryPackage => SymbolKind::Package,
        ElementKind::PartDefinition => SymbolKind::PartDefinition,
        ElementKind::ItemDefinition => SymbolKind::ItemDefinition,
        ElementKind::ActionDefinition => SymbolKind::ActionDefinition,
        ElementKind::PortDefinition => SymbolKind::PortDefinition,
        ElementKind::AttributeDefinition => SymbolKind::AttributeDefinition,
        ElementKind::ConnectionDefinition => SymbolKind::ConnectionDefinition,
        ElementKind::InterfaceDefinition => SymbolKind::InterfaceDefinition,
        ElementKind::AllocationDefinition => SymbolKind::AllocationDefinition,
        ElementKind::RequirementDefinition => SymbolKind::RequirementDefinition,
        ElementKind::ConstraintDefinition => SymbolKind::ConstraintDefinition,
        ElementKind::StateDefinition => SymbolKind::StateDefinition,
        ElementKind::CalculationDefinition => SymbolKind::CalculationDefinition,
        ElementKind::UseCaseDefinition => SymbolKind::UseCaseDefinition,
        ElementKind::AnalysisCaseDefinition => SymbolKind::AnalysisCaseDefinition,
        ElementKind::ConcernDefinition => SymbolKind::ConcernDefinition,
        ElementKind::ViewDefinition => SymbolKind::ViewDefinition,
        ElementKind::ViewpointDefinition => SymbolKind::ViewpointDefinition,
        ElementKind::RenderingDefinition => SymbolKind::RenderingDefinition,
        ElementKind::EnumerationDefinition => SymbolKind::EnumerationDefinition,
        ElementKind::MetadataDefinition => SymbolKind::MetadataDefinition,
        // KerML definitions
        ElementKind::DataType => SymbolKind::DataType,
        ElementKind::Class => SymbolKind::Class,
        ElementKind::Structure => SymbolKind::Structure,
        ElementKind::Behavior => SymbolKind::Behavior,
        ElementKind::Function => SymbolKind::Function,
        ElementKind::Association | ElementKind::AssociationStructure => SymbolKind::Association,
        ElementKind::Interaction => SymbolKind::Interaction,
        // Usages
        ElementKind::PartUsage => SymbolKind::PartUsage,
        ElementKind::ItemUsage => SymbolKind::ItemUsage,
        ElementKind::ActionUsage => SymbolKind::ActionUsage,
        ElementKind::PortUsage => SymbolKind::PortUsage,
        ElementKind::AttributeUsage => SymbolKind::AttributeUsage,
        ElementKind::ConnectionUsage => SymbolKind::ConnectionUsage,
        ElementKind::InterfaceUsage => SymbolKind::InterfaceUsage,
        ElementKind::AllocationUsage => SymbolKind::AllocationUsage,
        ElementKind::RequirementUsage => SymbolKind::RequirementUsage,
        ElementKind::ConstraintUsage => SymbolKind::ConstraintUsage,
        ElementKind::StateUsage => SymbolKind::StateUsage,
        ElementKind::TransitionUsage => SymbolKind::TransitionUsage,
        ElementKind::CalculationUsage => SymbolKind::CalculationUsage,
        ElementKind::ReferenceUsage => SymbolKind::ReferenceUsage,
        ElementKind::OccurrenceUsage => SymbolKind::OccurrenceUsage,
        ElementKind::FlowConnectionUsage => SymbolKind::FlowConnectionUsage,
        // Other
        ElementKind::Import | ElementKind::NamespaceImport | ElementKind::MembershipImport => {
            SymbolKind::Import
        }
        ElementKind::Comment | ElementKind::Documentation => SymbolKind::Comment,
        _ => SymbolKind::Other,
    }
}

/// Convert a collection of HirSymbols to a standalone Model.
///
/// This is the core conversion function that maps HIR symbols to
/// interchange model elements.
pub fn model_from_symbols(symbols: &[HirSymbol]) -> Model {
    let mut model = Model::new();
    let mut rel_counter = 0u64;

    // Build lookup map: qualified_name -> element_id
    // This allows us to resolve relationship targets and ownership
    let name_to_id: std::collections::HashMap<&str, &str> = symbols
        .iter()
        .map(|s| (s.qualified_name.as_ref(), s.element_id.as_ref()))
        .collect();

    for symbol in symbols {
        // Use the symbol's element_id to preserve UUIDs across round-trips
        let id = ElementId::new(symbol.element_id.as_ref());
        let kind = symbol_kind_to_element_kind(symbol.kind);

        // Determine ownership from qualified name, then look up owner's element_id
        let owner = if symbol.qualified_name.contains("::") {
            let parent = symbol.qualified_name.rsplit_once("::").map(|(p, _)| p);
            parent.and_then(|p| name_to_id.get(p).map(|&id| ElementId::new(id)))
        } else {
            None
        };

        let mut element = Element::new(id.clone(), kind)
            .with_name(symbol.name.as_ref())
            .with_qualified_name(symbol.qualified_name.as_ref());

        if let Some(ref owner_id) = owner {
            element = element.with_owner(owner_id.clone());
        }

        model.add_element(element);
        // We'll populate parent's owned_elements in a separate pass below

        // Ensure owned_elements lists are correctly populated regardless of symbol ordering.
        // Clear existing owned lists and rebuild from owner pointers.
        let mut child_owner_pairs: Vec<(ElementId, ElementId)> = Vec::new();
        for (id, element) in model.elements.iter() {
            if let Some(owner_id) = &element.owner {
                child_owner_pairs.push((id.clone(), owner_id.clone()));
            }
        }

        // Clear current owned_elements
        for (_id, element) in model.elements.iter_mut() {
            element.owned_elements.clear();
        }

        // Repopulate owned_elements according to owner pointers
        for (child_id, owner_id) in child_owner_pairs {
            if let Some(parent) = model.get_mut(&owner_id) {
                parent.owned_elements.push(child_id);
            }
        }
        // Extract relationships from the symbol
        for hir_rel in &symbol.relationships {
            let rel_kind = hir_relationship_kind_to_model(&hir_rel.kind);
            if let Some(rel_kind) = rel_kind {
                rel_counter += 1;
                let rel_id = ElementId::new(format!("rel_{}", rel_counter));

                // Look up target's element_id from qualified name
                // Try multiple resolution strategies:
                // 1. Direct lookup (fully qualified)
                // 2. Same namespace as source (e.g., "Vehicle" -> "Types::Vehicle")
                let target_id = name_to_id
                    .get(hir_rel.target.as_ref())
                    .or_else(|| {
                        // Try adding source's namespace prefix
                        if let Some((ns, _)) = symbol.qualified_name.rsplit_once("::") {
                            let namespaced = format!("{}::{}", ns, hir_rel.target);
                            name_to_id.get(namespaced.as_str())
                        } else {
                            None
                        }
                    })
                    .map(|&id| ElementId::new(id))
                    .unwrap_or_else(|| {
                        // External reference not in this symbol set - use qualified name as fallback
                        ElementId::new(hir_rel.target.as_ref())
                    });

                let relationship = Relationship::new(rel_id, rel_kind, id.clone(), target_id);
                model.add_relationship(relationship);
            }
        }
    }

    model
}

/// Convert HIR RelationshipKind to interchange RelationshipKind.
fn hir_relationship_kind_to_model(kind: &crate::hir::RelationshipKind) -> Option<RelationshipKind> {
    use crate::hir::RelationshipKind as HirRelKind;
    match kind {
        HirRelKind::Specializes => Some(RelationshipKind::Specialization),
        HirRelKind::TypedBy => Some(RelationshipKind::FeatureTyping),
        HirRelKind::Redefines => Some(RelationshipKind::Redefinition),
        HirRelKind::Subsets => Some(RelationshipKind::Subsetting),
        HirRelKind::References => None, // Not a first-class relationship in interchange
        HirRelKind::Satisfies => Some(RelationshipKind::Satisfaction),
        HirRelKind::Performs => None, // TODO: Add to interchange model if needed
        HirRelKind::Exhibits => None,
        HirRelKind::Includes => None,
        HirRelKind::Asserts => None,
        HirRelKind::Verifies => Some(RelationshipKind::Verification),
    }
}

/// Convert HIR SymbolKind to interchange ElementKind.
fn symbol_kind_to_element_kind(kind: crate::hir::SymbolKind) -> ElementKind {
    use crate::hir::SymbolKind;
    match kind {
        SymbolKind::Package => ElementKind::Package,
        SymbolKind::PartDefinition => ElementKind::PartDefinition,
        SymbolKind::ItemDefinition => ElementKind::ItemDefinition,
        SymbolKind::ActionDefinition => ElementKind::ActionDefinition,
        SymbolKind::PortDefinition => ElementKind::PortDefinition,
        SymbolKind::AttributeDefinition => ElementKind::AttributeDefinition,
        SymbolKind::ConnectionDefinition => ElementKind::ConnectionDefinition,
        SymbolKind::InterfaceDefinition => ElementKind::InterfaceDefinition,
        SymbolKind::AllocationDefinition => ElementKind::AllocationDefinition,
        SymbolKind::RequirementDefinition => ElementKind::RequirementDefinition,
        SymbolKind::ConstraintDefinition => ElementKind::ConstraintDefinition,
        SymbolKind::StateDefinition => ElementKind::StateDefinition,
        SymbolKind::CalculationDefinition => ElementKind::CalculationDefinition,
        SymbolKind::UseCaseDefinition => ElementKind::UseCaseDefinition,
        SymbolKind::AnalysisCaseDefinition => ElementKind::AnalysisCaseDefinition,
        SymbolKind::ConcernDefinition => ElementKind::ConcernDefinition,
        SymbolKind::ViewDefinition => ElementKind::ViewDefinition,
        SymbolKind::ViewpointDefinition => ElementKind::ViewpointDefinition,
        SymbolKind::RenderingDefinition => ElementKind::RenderingDefinition,
        SymbolKind::EnumerationDefinition => ElementKind::EnumerationDefinition,
        // KerML definitions
        SymbolKind::DataType => ElementKind::DataType,
        SymbolKind::Class => ElementKind::Class,
        SymbolKind::Structure => ElementKind::Structure,
        SymbolKind::Behavior => ElementKind::Behavior,
        SymbolKind::Function => ElementKind::Function,
        SymbolKind::Association => ElementKind::Association,
        SymbolKind::MetadataDefinition => ElementKind::MetadataDefinition,
        SymbolKind::Interaction => ElementKind::Interaction,
        // Usages
        SymbolKind::PartUsage => ElementKind::PartUsage,
        SymbolKind::ItemUsage => ElementKind::ItemUsage,
        SymbolKind::ActionUsage => ElementKind::ActionUsage,
        SymbolKind::PortUsage => ElementKind::PortUsage,
        SymbolKind::AttributeUsage => ElementKind::AttributeUsage,
        SymbolKind::ConnectionUsage => ElementKind::ConnectionUsage,
        SymbolKind::InterfaceUsage => ElementKind::InterfaceUsage,
        SymbolKind::AllocationUsage => ElementKind::AllocationUsage,
        SymbolKind::RequirementUsage => ElementKind::RequirementUsage,
        SymbolKind::ConstraintUsage => ElementKind::ConstraintUsage,
        SymbolKind::StateUsage => ElementKind::StateUsage,
        SymbolKind::TransitionUsage => ElementKind::TransitionUsage,
        SymbolKind::CalculationUsage => ElementKind::CalculationUsage,
        SymbolKind::ReferenceUsage => ElementKind::ReferenceUsage,
        SymbolKind::OccurrenceUsage => ElementKind::OccurrenceUsage,
        SymbolKind::FlowConnectionUsage => ElementKind::FlowConnectionUsage,
        // Other
        SymbolKind::Import => ElementKind::Import,
        SymbolKind::Comment => ElementKind::Comment,
        _ => ElementKind::Other,
    }
}

/// Apply import metadata to symbols in an AnalysisHost.
///
/// This looks up each symbol's qualified name in the metadata and sets
/// the symbol's `element_id` to the original XMI element ID if found.
///
/// Call this after loading decompiled SysML files into the AnalysisHost.
///
/// ## Example
///
/// ```ignore
/// use syster::interchange::{decompile, apply_metadata_to_host};
/// use syster::ide::AnalysisHost;
///
/// // Decompile XMI to SysML + metadata
/// let result = decompile(&model);
///
/// // Parse the SysML text into host
/// let mut host = AnalysisHost::new();
/// host.set_file_content("model.sysml", &result.text);
///
/// // Apply metadata to restore element IDs
/// apply_metadata_to_host(&mut host, &result.metadata);
/// ```
pub fn apply_metadata_to_host(
    host: &mut crate::ide::AnalysisHost,
    metadata: &super::metadata::ImportMetadata,
) {
    use std::sync::Arc;

    // Rebuild index to ensure we have up-to-date symbols
    let _ = host.analysis();

    // Update each symbol's element_id based on metadata lookup
    host.update_symbols(|symbol| {
        if let Some(meta) = metadata.get_element(&symbol.qualified_name) {
            if let Some(id) = &meta.original_id {
                symbol.element_id = Arc::from(id.as_str());
            }
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base::FileId;
    use crate::hir::{FileText, file_symbols_from_text};

    #[test]
    fn test_model_from_database_empty() {
        // TDD Step 1: Write a failing test
        // Given an empty database with no files
        let db = RootDatabase::new();

        // When we convert to a model
        let model = model_from_database(&db);

        // Then the model should be empty
        assert!(
            model.elements.is_empty(),
            "Empty database should produce empty model"
        );
        assert!(
            model.roots.is_empty(),
            "Empty database should have no root elements"
        );
        assert!(
            model.relationships.is_empty(),
            "Empty database should have no relationships"
        );
    }

    #[test]
    fn test_model_from_database_single_package() {
        // Given a database with a single package
        let db = RootDatabase::new();
        let sysml = "package TestPackage;";
        let file_text = FileText::new(&db, FileId::new(0), sysml.to_string());

        // Extract symbols (this populates the database via Salsa queries)
        let symbols = file_symbols_from_text(&db, file_text);
        assert!(!symbols.is_empty(), "Should have parsed the package");

        // When we convert to a model
        let model = model_from_symbols(&symbols);

        // Then the model should have one package element
        assert_eq!(model.elements.len(), 1, "Should have one element");
        assert_eq!(model.roots.len(), 1, "Should have one root element");

        // The element should be a Package with the correct name
        let root_id = &model.roots[0];
        let element = model
            .elements
            .get(root_id)
            .expect("Root element should exist");
        assert_eq!(element.kind, super::super::model::ElementKind::Package);
        assert_eq!(element.name.as_deref(), Some("TestPackage"));
    }

    #[test]
    fn test_model_from_database_with_parts() {
        // Given a database with a package containing part definitions
        let db = RootDatabase::new();
        let sysml = r#"
            package Vehicle {
                part def Car;
                part def Engine;
            }
        "#;
        let file_text = FileText::new(&db, FileId::new(0), sysml.to_string());

        let symbols = file_symbols_from_text(&db, file_text);
        let model = model_from_symbols(&symbols);

        // Should have: Vehicle (package), Car (part def), Engine (part def)
        assert_eq!(model.elements.len(), 3, "Should have 3 elements");
        assert_eq!(model.roots.len(), 1, "Should have one root (Vehicle)");

        // Check that Car is owned by Vehicle
        let car = model
            .elements
            .values()
            .find(|e| e.name.as_deref() == Some("Car"))
            .expect("Car should exist");
        assert_eq!(car.kind, super::super::model::ElementKind::PartDefinition);
        assert!(car.owner.is_some(), "Car should have an owner");

        // Owner is now referenced by element_id (UUID), verify it exists
        let owner = model
            .elements
            .get(car.owner.as_ref().unwrap())
            .expect("Owner should exist in model");
        assert_eq!(
            owner.name.as_deref(),
            Some("Vehicle"),
            "Owner should be Vehicle"
        );
    }

    #[test]
    fn test_model_from_database_relationships() {
        // Given a database with specialization relationships
        let db = RootDatabase::new();
        let sysml = r#"
            package Types {
                part def Vehicle;
                part def Car :> Vehicle;
            }
        "#;
        let file_text = FileText::new(&db, FileId::new(0), sysml.to_string());

        let symbols = file_symbols_from_text(&db, file_text);
        let model = model_from_symbols(&symbols);

        // Should have relationships
        assert!(!model.relationships.is_empty(), "Should have relationships");

        // Find the specialization from Car to Vehicle
        let specialization = model
            .relationships
            .iter()
            .find(|r| r.kind == super::super::model::RelationshipKind::Specialization)
            .expect("Should have a specialization");

        // Source and target are now UUIDs, verify by looking up the elements
        let source_elem = model
            .elements
            .get(&specialization.source)
            .expect("Source element should exist");
        let target_elem = model
            .elements
            .get(&specialization.target)
            .expect("Target element should exist");

        assert_eq!(
            source_elem.name.as_deref(),
            Some("Car"),
            "Source should be Car"
        );
        assert_eq!(
            target_elem.name.as_deref(),
            Some("Vehicle"),
            "Target should be Vehicle"
        );
    }

    #[test]
    fn test_roundtrip_through_xmi() {
        use super::super::{ModelFormat, Xmi};

        // Given a database with a simple model (just the root package)
        let db = RootDatabase::new();
        let sysml = "package Vehicles;";
        let file_text = FileText::new(&db, FileId::new(0), sysml.to_string());

        let symbols = file_symbols_from_text(&db, file_text);
        let model = model_from_symbols(&symbols);

        // Verify our model has what we expect
        assert_eq!(model.elements.len(), 1, "Should have one package");

        // Capture the original element ID
        let original_id = model.elements.keys().next().unwrap().clone();

        // When we write to XMI and read back
        let xmi_bytes = Xmi.write(&model).expect("Should write XMI");
        let roundtrip_model = Xmi.read(&xmi_bytes).expect("Should read XMI");

        // Then we should find our original element
        assert!(
            !roundtrip_model.elements.is_empty(),
            "Should have at least one element after roundtrip"
        );
        assert!(
            roundtrip_model.elements.contains_key(&original_id),
            "Should find the original element by ID after roundtrip"
        );
    }

    // ========== symbols_from_model() tests ==========

    #[test]
    fn test_symbols_from_empty_model() {
        // Given an empty model
        let model = Model::new();

        // When we convert to symbols
        let symbols = symbols_from_model(&model);

        // Then we should get no symbols
        assert!(symbols.is_empty(), "Empty model should produce no symbols");
    }

    #[test]
    fn test_symbols_from_model_single_package() {
        // Given a model with a single package
        let mut model = Model::new();
        let pkg = Element::new(ElementId::new("TestPackage"), ElementKind::Package)
            .with_name("TestPackage");
        model.add_element(pkg);

        // When we convert to symbols
        let symbols = symbols_from_model(&model);

        // Then we should get one symbol
        assert_eq!(symbols.len(), 1, "Should have one symbol");
        assert_eq!(symbols[0].name.as_ref(), "TestPackage");
        assert_eq!(symbols[0].kind, SymbolKind::Package);
        assert_eq!(symbols[0].qualified_name.as_ref(), "TestPackage");
    }

    #[test]
    fn test_symbols_from_model_with_part_definitions() {
        // Given a model with part definitions
        let mut model = Model::new();

        let pkg =
            Element::new(ElementId::new("Vehicle"), ElementKind::Package).with_name("Vehicle");
        model.add_element(pkg);

        let car = Element::new(ElementId::new("Vehicle::Car"), ElementKind::PartDefinition)
            .with_name("Car")
            .with_owner(ElementId::new("Vehicle"));
        model.add_element(car);

        let engine = Element::new(
            ElementId::new("Vehicle::Engine"),
            ElementKind::PartDefinition,
        )
        .with_name("Engine")
        .with_owner(ElementId::new("Vehicle"));
        model.add_element(engine);

        // When we convert to symbols
        let symbols = symbols_from_model(&model);

        // Then we should get 3 symbols with correct kinds
        assert_eq!(symbols.len(), 3, "Should have 3 symbols");

        let car_sym = symbols
            .iter()
            .find(|s| s.name.as_ref() == "Car")
            .expect("Should have Car");
        assert_eq!(car_sym.kind, SymbolKind::PartDefinition);
        // Note: Without qualified_name set in the Element, this falls back to just the name
        assert_eq!(car_sym.qualified_name.as_ref(), "Car");

        let engine_sym = symbols
            .iter()
            .find(|s| s.name.as_ref() == "Engine")
            .expect("Should have Engine");
        assert_eq!(engine_sym.kind, SymbolKind::PartDefinition);
    }

    #[test]
    fn test_symbols_from_model_with_relationships() {
        // Given a model with specialization: Car :> Vehicle
        let mut model = Model::new();

        let vehicle = Element::new(ElementId::new("Vehicle"), ElementKind::PartDefinition)
            .with_name("Vehicle");
        model.add_element(vehicle);

        let car = Element::new(ElementId::new("Car"), ElementKind::PartDefinition).with_name("Car");
        model.add_element(car);

        // Add specialization relationship
        let rel = Relationship::new(
            ElementId::new("rel_1"),
            RelationshipKind::Specialization,
            ElementId::new("Car"),
            ElementId::new("Vehicle"),
        );
        model.add_relationship(rel);

        // When we convert to symbols
        let symbols = symbols_from_model(&model);

        // Then Car should have a specialization relationship
        let car_sym = symbols
            .iter()
            .find(|s| s.name.as_ref() == "Car")
            .expect("Should have Car");
        assert!(
            !car_sym.relationships.is_empty(),
            "Car should have relationships"
        );

        let spec_rel = car_sym
            .relationships
            .iter()
            .find(|r| r.kind == HirRelKind::Specializes)
            .expect("Should have specialization");
        assert_eq!(spec_rel.target.as_ref(), "Vehicle");

        // Should also be in supertypes
        assert!(car_sym.supertypes.iter().any(|s| s.as_ref() == "Vehicle"));
    }

    #[test]
    fn test_symbols_from_model_with_documentation() {
        // Given a model with documented element
        let mut model = Model::new();

        let mut pkg =
            Element::new(ElementId::new("MyPackage"), ElementKind::Package).with_name("MyPackage");
        pkg.documentation = Some("This is a documented package".into());
        model.add_element(pkg);

        // When we convert to symbols
        let symbols = symbols_from_model(&model);

        // Then the symbol should have documentation
        assert_eq!(symbols.len(), 1);
        assert_eq!(
            symbols[0].doc.as_deref(),
            Some("This is a documented package")
        );
    }

    #[test]
    fn test_symbols_from_model_roundtrip() {
        // Given: Parse SysML → Model → Symbols → Model → Symbols
        // The symbol counts should match
        let db = RootDatabase::new();
        let sysml = r#"
            package Types {
                part def Vehicle;
                part def Car :> Vehicle;
            }
        "#;
        let file_text = FileText::new(&db, FileId::new(0), sysml.to_string());

        // SysML → HirSymbols
        let original_symbols = file_symbols_from_text(&db, file_text);

        // HirSymbols → Model
        let model = model_from_symbols(&original_symbols);

        // Model → HirSymbols (the new function)
        let roundtrip_symbols = symbols_from_model(&model);

        // Should have same number of non-relationship symbols
        let original_count = original_symbols.len();
        let roundtrip_count = roundtrip_symbols.len();

        assert_eq!(
            roundtrip_count, original_count,
            "Roundtrip should preserve symbol count: {} → {}",
            original_count, roundtrip_count
        );

        // Names should match
        for orig in &original_symbols {
            let found = roundtrip_symbols
                .iter()
                .find(|s| s.qualified_name == orig.qualified_name);
            assert!(
                found.is_some(),
                "Symbol {} should exist after roundtrip",
                orig.qualified_name
            );
        }
    }

    #[test]
    fn test_apply_metadata_to_host() {
        use crate::ide::AnalysisHost;
        use crate::interchange::integrate::apply_metadata_to_host;
        use crate::interchange::metadata::{ElementMeta, ImportMetadata};

        // Create a host with a simple SysML file
        let mut host = AnalysisHost::new();
        let sysml = r#"
package TestPkg {
    part def Car;
}
"#;
        host.set_file_content("/test.sysml", sysml);

        // Create metadata with element IDs
        let mut metadata = ImportMetadata::new();
        metadata.add_element("TestPkg", ElementMeta::with_id("uuid-pkg-1"));
        metadata.add_element("TestPkg::Car", ElementMeta::with_id("uuid-car-1"));

        // Apply metadata to host
        apply_metadata_to_host(&mut host, &metadata);

        // Verify element IDs were applied
        let analysis = host.analysis();

        let pkg = analysis
            .symbol_index()
            .lookup_qualified("TestPkg")
            .expect("Should find TestPkg");
        assert_eq!(
            pkg.element_id.as_ref(),
            "uuid-pkg-1",
            "Package should have metadata element_id"
        );

        let car = analysis
            .symbol_index()
            .lookup_qualified("TestPkg::Car")
            .expect("Should find TestPkg::Car");
        assert_eq!(
            car.element_id.as_ref(),
            "uuid-car-1",
            "Car should have metadata element_id"
        );
    }
}