syster-base 0.4.0-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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
//! Integration between interchange Model and AnalysisHost/RootDatabase.
//!
//! This module bridges the two parallel model systems:
//!
//! - **AnalysisHost** (Salsa path): parses text → `SymbolIndex` → IDE queries
//! - **ModelHost** (interchange path): standalone `Model` → semantic edits → `render_dirty`
//!
//! ## Functions
//!
//! | Function | Direction | Purpose |
//! |----------|-----------|---------|
//! | `model_from_symbols()` | HIR → Model | Export symbols to interchange Model |
//! | `symbols_from_model()` | Model → HIR | Import Model elements as HirSymbols |
//! | `model_from_database()` | RootDatabase → Model | Export Salsa DB to Model |
//! | `apply_metadata_to_host()` | Metadata → AnalysisHost | Restore element IDs after decompile |
//!
//! For bridging ChangeTracker edits into Salsa queries, use
//! [`AnalysisHost::apply_model_edit()`](crate::ide::AnalysisHost::apply_model_edit).

use super::model::{Element, ElementId, ElementKind, Model, PropertyValue, Visibility};
use crate::base::FileId;
use crate::hir::{
    HirRelationship, HirSymbol, RelationshipKind as HirRelKind, RootDatabase, SymbolKind,
};
use crate::parser::{Direction, Multiplicity};
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: SymbolKind = element.kind.into();

        // 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
            .rel_elements_from(&element.id)
            .filter_map(|re| {
                let hir_kind = element_kind_to_hir(re.kind)?;

                // Look up target element to get its qualified name (HIR uses names, not UUIDs)
                let target_name: Arc<str> = re
                    .target()
                    .and_then(|tid| model.elements.get(tid))
                    .and_then(|target_elem| {
                        target_elem
                            .qualified_name
                            .clone()
                            .or_else(|| target_elem.name.clone())
                    })
                    .map(|n| n.to_string().into())
                    .unwrap_or_else(|| {
                        re.target()
                            .map(|tid| tid.as_str().into())
                            .unwrap_or_else(|| "".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: element.properties.get("direction").and_then(|v| match v {
                PropertyValue::String(s) => match s.as_ref() {
                    "in" => Some(Direction::In),
                    "out" => Some(Direction::Out),
                    "inout" => Some(Direction::InOut),
                    _ => None,
                },
                _ => None,
            }),
            multiplicity: extract_multiplicity(element, model),
            value: None,
        };

        symbols.push(symbol);
    }

    symbols
}

/// Extract multiplicity from an element's owned `MultiplicityRange` child.
///
/// SysML XMI stores multiplicity as a nested child element:
/// ```xml
/// <ownedMember xsi:type="MultiplicityRange" ...>
///   <ownedMember xsi:type="LiteralInteger" value="0"/>   <!-- lower -->
///   <ownedMember xsi:type="LiteralInteger" value="*"/>   <!-- upper -->
/// </ownedMember>
/// ```
fn extract_multiplicity(element: &Element, model: &Model) -> Option<Multiplicity> {
    // Find the first owned MultiplicityRange child
    for child_id in &element.owned_elements {
        if let Some(child) = model.elements.get(child_id) {
            if child.kind == ElementKind::MultiplicityRange {
                return multiplicity_from_range(child, model);
            }
            // Sometimes the MultiplicityRange is nested one level deeper
            // (e.g., inside an OwningMembership)
            for grandchild_id in &child.owned_elements {
                if let Some(grandchild) = model.elements.get(grandchild_id) {
                    if grandchild.kind == ElementKind::MultiplicityRange {
                        return multiplicity_from_range(grandchild, model);
                    }
                }
            }
        }
    }
    None
}

/// Build a `Multiplicity` from a `MultiplicityRange` element's literal children.
fn multiplicity_from_range(range: &Element, model: &Model) -> Option<Multiplicity> {
    let mut lower: Option<u64> = None;
    let mut upper: Option<u64> = None;

    for (i, child_id) in range.owned_elements.iter().enumerate() {
        if let Some(child) = model.elements.get(child_id) {
            match child.kind {
                ElementKind::LiteralInteger => {
                    if let Some(PropertyValue::Integer(v)) = child.properties.get("value") {
                        let val = (*v).max(0) as u64;
                        if i == 0 {
                            lower = Some(val);
                        } else {
                            upper = Some(val);
                        }
                    }
                }
                ElementKind::LiteralInfinity => {
                    // Infinity is represented as upper = None (None means "*")
                    if i == 0 {
                        lower = None;
                    }
                    // upper stays None → means unbounded
                }
                _ => {}
            }
        }
    }

    // Only return if we found at least one bound
    if lower.is_some() || upper.is_some() {
        Some(Multiplicity { lower, upper })
    } else {
        None
    }
}

/// Convert an element-based relationship kind to HIR relationship kind.
fn element_kind_to_hir(kind: ElementKind) -> Option<HirRelKind> {
    match kind {
        ElementKind::Specialization => Some(HirRelKind::Specializes),
        ElementKind::FeatureTyping => Some(HirRelKind::TypedBy),
        ElementKind::Redefinition => Some(HirRelKind::Redefines),
        ElementKind::Subsetting => Some(HirRelKind::Subsets),
        ElementKind::Satisfaction => Some(HirRelKind::Satisfies),
        ElementKind::Verification => Some(HirRelKind::Verifies),
        ElementKind::ActionUsage => Some(HirRelKind::Performs), // Performs maps to ActionUsage
        _ => None,
    }
}

/// Convert interchange `ElementKind` to HIR `SymbolKind`.
///
/// This is a lossy, many-to-one mapping: several `ElementKind` variants
/// (e.g. `LibraryPackage`, `AssociationStructure`, import/comment variants)
/// collapse into a single `SymbolKind`.
impl From<ElementKind> for SymbolKind {
    fn from(kind: ElementKind) -> Self {
        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: ElementKind = symbol.kind.into();

        // Handle Import symbols specially: create NamespaceImport/MembershipImport
        // relationship elements instead of bare Import elements.
        if symbol.kind == SymbolKind::Import {
            // Parse the import name to determine kind and target namespace.
            // Import symbol name is like "ScalarValues::*" or "Pkg::Elem".
            let import_name = symbol.name.as_ref();
            let is_wildcard = import_name.ends_with("::*");
            let namespace = if is_wildcard {
                import_name.trim_end_matches("::*")
            } else {
                import_name
            };

            // Determine the owner package from the qualified name.
            // Import qn format: "Vehicle::import:ScalarValues::*"
            // The owner is the first segment before "::import:".
            let owner_id = symbol.qualified_name.find("::import:").and_then(|idx| {
                let parent_qn = &symbol.qualified_name[..idx];
                name_to_id.get(parent_qn).map(|&eid| ElementId::new(eid))
            });

            let import_kind = if is_wildcard {
                ElementKind::NamespaceImport
            } else {
                ElementKind::MembershipImport
            };

            // Create the import as a relationship element with the namespace as target.
            // The target ID is the namespace name (external reference).
            let target_id = ElementId::new(namespace);
            let source_id = owner_id.clone().unwrap_or_else(|| id.clone());

            let rel_id = model.add_rel(
                id.clone(),
                import_kind,
                source_id,
                target_id,
                owner_id.clone(),
            );

            // Store importedNamespace attribute for XMI roundtrip and decompiler fallback
            let attr_name = if is_wildcard {
                "importedNamespace"
            } else {
                "importedMembership"
            };
            if let Some(rel_element) = model.get_mut(&rel_id) {
                rel_element.properties.insert(
                    Arc::from(attr_name),
                    PropertyValue::String(Arc::from(namespace)),
                );
                // Copy import visibility
                rel_element.visibility = if symbol.is_public {
                    Visibility::Public
                } else {
                    Visibility::Private
                };
            }

            // Add to parent's owned_elements
            if let Some(ref oid) = owner_id {
                if let Some(parent) = model.get_mut(oid) {
                    if !parent.owned_elements.contains(&id) {
                        parent.owned_elements.push(id.clone());
                    }
                }
            }

            continue;
        }

        // 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());
        }

        // Copy boolean flags from HIR symbol
        element.is_abstract = symbol.is_abstract;
        element.is_variation = symbol.is_variation;
        element.is_readonly = symbol.is_readonly;
        element.is_derived = symbol.is_derived;
        element.is_parallel = symbol.is_parallel;
        element.is_individual = symbol.is_individual;
        element.is_end = symbol.is_end;
        element.is_default = symbol.is_default;
        element.is_ordered = symbol.is_ordered;
        element.is_nonunique = symbol.is_nonunique;
        element.is_portion = symbol.is_portion;

        // Copy short name
        element.short_name = symbol.short_name.clone();

        // Copy documentation
        element.documentation = symbol.doc.clone();

        // Copy direction as a property (for decompiler to read)
        if let Some(ref dir) = symbol.direction {
            let dir_str = match dir {
                Direction::In => "in",
                Direction::Out => "out",
                Direction::InOut => "inout",
            };
            element.properties.insert(
                Arc::from("direction"),
                PropertyValue::String(Arc::from(dir_str)),
            );
        }

        // Copy multiplicity as properties
        if let Some(ref mult) = symbol.multiplicity {
            if let Some(lower) = mult.lower {
                element.properties.insert(
                    Arc::from("multiplicityLower"),
                    PropertyValue::String(Arc::from(lower.to_string())),
                );
            }
            if let Some(upper) = mult.upper {
                element.properties.insert(
                    Arc::from("multiplicityUpper"),
                    PropertyValue::String(Arc::from(upper.to_string())),
                );
            }
        }

        // Don't set visibility from is_public on regular elements.
        // SysML default is public — only imports use the is_public flag
        // to distinguish `private import` from `import`.

        // Store alias target from supertypes (for decompiler)
        if symbol.kind == SymbolKind::Alias {
            if let Some(target) = symbol.supertypes.first() {
                element.properties.insert(
                    Arc::from("aliasTarget"),
                    PropertyValue::String(Arc::from(target.as_ref())),
                );
            }
        }

        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 element_kind = hir_relationship_kind_to_element_kind(&hir_rel.kind);
            if let Some(ek) = element_kind {
                rel_counter += 1;
                let rel_id = ElementId::new(format!("rel_{}", rel_counter));

                // Look up target's element_id from qualified name.
                // Resolution order:
                // 0. Use resolved_target from the resolver (best source)
                // 1. Direct lookup by name (fully qualified)
                // 2. Walk up ancestor namespaces (e.g., for "Label" from
                //    "Sensor::Thermometer::name", try "Sensor::Thermometer::Label"
                //    then "Sensor::Label")
                // 3. Scan all symbols for a matching simple name suffix
                //    (handles cross-type references like `redefines size`
                //    where `size` lives in a supertype)
                let target_name = hir_rel
                    .resolved_target
                    .as_deref()
                    .unwrap_or(hir_rel.target.as_ref());

                let target_id = name_to_id
                    .get(target_name)
                    .or_else(|| {
                        // Also try the unresolved name if resolved didn't match
                        name_to_id.get(hir_rel.target.as_ref())
                    })
                    .or_else(|| {
                        let mut ns = symbol.qualified_name.as_ref();
                        while let Some((parent, _)) = ns.rsplit_once("::") {
                            let candidate = format!("{}::{}", parent, hir_rel.target);
                            if let Some(found) = name_to_id.get(candidate.as_str()) {
                                return Some(found);
                            }
                            ns = parent;
                        }
                        None
                    })
                    .or_else(|| {
                        // Scan for any element whose qualified name ends with
                        // ::target.  Needed for cross-type references (e.g.
                        // `redefines size` where size is in a supertype).
                        let suffix = format!("::{}", hir_rel.target);
                        let mut matches: Vec<&&str> = name_to_id
                            .keys()
                            .filter(|qn| qn.ends_with(suffix.as_str()))
                            .collect();
                        if matches.len() == 1 {
                            // Unambiguous match
                            name_to_id.get(*matches[0])
                        } else if matches.len() > 1 {
                            // Multiple matches — try to pick one that shares
                            // the longest common prefix with our symbol's qn
                            matches.sort_by_key(|qn| {
                                let common = symbol
                                    .qualified_name
                                    .as_ref()
                                    .chars()
                                    .zip(qn.chars())
                                    .take_while(|(a, b)| a == b)
                                    .count();
                                std::cmp::Reverse(common)
                            });
                            name_to_id.get(*matches[0])
                        } else {
                            None
                        }
                    })
                    .map(|&id| ElementId::new(id));

                // If resolution failed, create a stub element for the external
                // reference so the decompiler can still render its name.
                let target_id = target_id.unwrap_or_else(|| {
                    let ext_id = ElementId::new(format!("_ext_{}", hir_rel.target));
                    if !model.elements.contains_key(&ext_id) {
                        let mut stub = Element::new(ext_id.clone(), ElementKind::Other)
                            .with_name(hir_rel.target.as_ref());
                        // Mark as external so it is never decompiled to output
                        stub.properties
                            .insert(Arc::from("_external"), PropertyValue::Boolean(true));
                        model.add_element(stub);
                    }
                    ext_id
                });

                // Use add_rel to create the relationship element directly
                model.add_rel(
                    rel_id.clone(),
                    ek,
                    id.clone(),
                    target_id.clone(),
                    Some(id.clone()),
                );

                // Store the resolved target name on the relationship for XMI
                let target_attr = match ek {
                    ElementKind::FeatureTyping => "type",
                    ElementKind::Specialization => "general",
                    ElementKind::Redefinition => "redefinedFeature",
                    ElementKind::Subsetting => "subsettedFeature",
                    _ => "target",
                };
                if let Some(rel_element) = model.get_mut(&rel_id) {
                    rel_element.properties.insert(
                        Arc::from(target_attr),
                        PropertyValue::String(Arc::from(target_id.as_str())),
                    );
                }
                if let Some(parent) = model.get_mut(&id) {
                    parent.owned_elements.push(rel_id);
                }
            }
        }

        // Create FeatureValue + Literal child elements for symbols with values
        if let Some(ref value) = symbol.value {
            use crate::parser::ValueExpression;

            let fv_id = ElementId::new(format!("{}-fv", symbol.element_id));
            let lit_id = ElementId::new(format!("{}-fv-lit", symbol.element_id));

            let (lit_kind, lit_prop_value) = match value {
                ValueExpression::LiteralInteger(v) => {
                    (ElementKind::LiteralInteger, PropertyValue::Integer(*v))
                }
                ValueExpression::LiteralReal(v) => {
                    (ElementKind::LiteralReal, PropertyValue::Real(*v))
                }
                ValueExpression::LiteralString(s) => (
                    ElementKind::LiteralString,
                    PropertyValue::String(Arc::from(s.as_str())),
                ),
                ValueExpression::LiteralBoolean(b) => {
                    (ElementKind::LiteralBoolean, PropertyValue::Boolean(*b))
                }
                ValueExpression::Null => (
                    ElementKind::NullExpression,
                    PropertyValue::String(Arc::from("null")),
                ),
                ValueExpression::Expression(text) => (
                    ElementKind::FeatureReferenceExpression,
                    PropertyValue::String(Arc::from(text.as_str())),
                ),
            };

            // Create the literal element
            let mut lit_element = Element::new(lit_id.clone(), lit_kind).with_owner(fv_id.clone());
            lit_element
                .properties
                .insert(Arc::from("value"), lit_prop_value);
            model.add_element(lit_element);

            // Create the FeatureValue relationship element
            let mut fv_element =
                Element::new(fv_id.clone(), ElementKind::FeatureValue).with_owner(id.clone());
            fv_element.owned_elements.push(lit_id);
            model.add_element(fv_element);

            // Add FeatureValue as owned child of the usage element
            if let Some(parent) = model.get_mut(&id) {
                parent.owned_elements.push(fv_id);
            }
        }
    }

    // Phase 6: wrap non-relationship children in OwningMembership/FeatureMembership
    model.wrap_children_in_memberships();

    model
}

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

/// Convert HIR `SymbolKind` to interchange `ElementKind`.
///
/// Inverse of `From<ElementKind> for SymbolKind` (modulo lossy many-to-one
/// arms: e.g. `SymbolKind::Package` maps to `ElementKind::Package`, not
/// `LibraryPackage`).
impl From<SymbolKind> for ElementKind {
    fn from(kind: SymbolKind) -> Self {
        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,
            SymbolKind::Alias => ElementKind::Alias,
            _ => 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());
            }
        }
    });
}

/// Result of applying ChangeTracker edits to an AnalysisHost.
#[derive(Debug)]
pub struct ApplyEditsResult {
    /// The new SysML text after edits (rendered via `render_dirty`).
    pub rendered_text: String,
    /// Parse errors from re-parsing the rendered text.
    pub parse_errors: Vec<crate::syntax::parser::ParseError>,
}

#[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_eq!(
            model.relationship_count(),
            0,
            "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)
        // Plus 2 membership wrappers (OwningMembership for Car and Engine)
        assert_eq!(model.roots.len(), 1, "Should have one root (Vehicle)");

        // Check content elements via owned_members (looks through memberships)
        let root_id = &model.roots[0];
        let members = model.owned_members(root_id);
        assert_eq!(members.len(), 2, "Vehicle should own 2 content members");

        // Check that Car exists and is a PartDefinition
        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");

        // Car's direct owner should be a membership, whose owner is Vehicle
        let direct_owner = model
            .elements
            .get(car.owner.as_ref().unwrap())
            .expect("Direct owner should exist");
        assert!(
            direct_owner.kind.is_membership(),
            "Car's direct owner should be a membership"
        );
        let logical_owner = model
            .elements
            .get(direct_owner.owner.as_ref().unwrap())
            .expect("Logical owner should exist");
        assert_eq!(
            logical_owner.name.as_deref(),
            Some("Vehicle"),
            "Logical 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.relationship_count() > 0, "Should have relationships");

        // Find the specialization from Car to Vehicle
        let specialization = model
            .iter_relationship_elements()
            .find(|e| e.kind == super::super::model::ElementKind::Specialization)
            .expect("Should have a specialization");

        // Source and target are in RelationshipData
        let rel_data = specialization.relationship.as_ref().unwrap();
        let source_elem = model
            .elements
            .get(&rel_data.source[0])
            .expect("Source element should exist");
        let target_elem = model
            .elements
            .get(&rel_data.target[0])
            .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
        model.add_rel(
            ElementId::new("rel_1"),
            ElementKind::Specialization,
            ElementId::new("Car"),
            ElementId::new("Vehicle"),
            None,
        );

        // 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"
        );
    }
}