Skip to main content

model_core/
model.rs

1use crate::entity::{EntityId, EntityKind, LanguageId};
2use crate::metamodel::{KindId, KindInfo, Metamodel, TraitMask};
3use crate::relation::{Provenance, RelationId, RelationKind, SiteFlags};
4use crate::source::Range;
5use crate::strings::{StrId, StrTable};
6use crate::value::Props;
7
8/// Absent `u32` reference (parent, file).
9pub(crate) const NONE: u32 = u32::MAX;
10pub(crate) const NO_LANGUAGE: u16 = u16::MAX;
11
12static NO_PROPS: Props = Props::new();
13
14/// 52 bytes per entity; strings live in the model's [`StrTable`].
15#[derive(Debug, Clone, Copy)]
16pub(crate) struct EntityRow {
17    pub(crate) key: StrId,
18    pub(crate) name: StrId,
19    pub(crate) file: u32,
20    pub(crate) parent: u32,
21    pub(crate) range: Range,
22    pub(crate) name_range: Range,
23    /// Fine kind; the archetype is looked up in the [`Metamodel`].
24    pub(crate) kind: KindId,
25    pub(crate) language: u16,
26    pub(crate) flags: u8,
27}
28
29impl EntityRow {
30    pub(crate) const EXTERNAL: u8 = 1;
31    pub(crate) const HAS_NAME_RANGE: u8 = 2;
32
33    pub(crate) fn set_flag(&mut self, flag: u8, on: bool) {
34        if on {
35            self.flags |= flag;
36        } else {
37            self.flags &= !flag;
38        }
39    }
40}
41
42/// 12 bytes per distinct `(from, kind, to, provenance)`; the field order is
43/// the sort order of [`Model::relations`].
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
45pub(crate) struct RelRow {
46    pub(crate) from: EntityId,
47    pub(crate) kind: u16,
48    pub(crate) to: EntityId,
49    pub(crate) provenance: Provenance,
50}
51
52/// Frozen, compact model.
53///
54/// Layout, chosen to keep every occurrence affordable:
55/// - strings (keys, names, files) interned once in a single buffer;
56/// - fixed-size entity rows, sparse props;
57/// - relations deduplicated and sorted by source, so the outgoing relations
58///   of an entity are one slice (CSR); incoming ones are an index array;
59/// - occurrence sites stored as 16-byte ranges plus a 1-byte flags column
60///   (17 bytes/site), grouped by relation (CSR); their file is the file of
61///   the relation's source entity.
62#[derive(Clone)]
63pub struct Model {
64    strings: StrTable,
65    languages: Vec<LanguageId>,
66    metamodel: Metamodel,
67    kinds: Vec<RelationKind>,
68    entities: Vec<EntityRow>,
69    /// Sorted by id.
70    props: Vec<(EntityId, Props)>,
71    /// Entity ids sorted by key.
72    by_key: Vec<EntityId>,
73    /// `children[child_offsets[e]..child_offsets[e + 1]]`.
74    child_offsets: Vec<u32>,
75    children: Vec<EntityId>,
76    relations: Vec<RelRow>,
77    /// `relations[out_offsets[e]..out_offsets[e + 1]]` leave entity `e`.
78    out_offsets: Vec<u32>,
79    /// `incoming[in_offsets[e]..in_offsets[e + 1]]` are relation indices.
80    in_offsets: Vec<u32>,
81    incoming: Vec<u32>,
82    /// `sites[site_offsets[r]..site_offsets[r + 1]]` of relation `r`.
83    site_offsets: Vec<u32>,
84    sites: Vec<Range>,
85    /// [`SiteFlags`] of `sites`, same indices.
86    site_flags: Vec<SiteFlags>,
87}
88
89/// Prefix sums of `keys` counted into `n` buckets: `offsets[k]..offsets[k+1]`.
90fn offsets(n: usize, keys: impl Iterator<Item = usize>) -> Vec<u32> {
91    let mut off = vec![0u32; n + 1];
92    for k in keys {
93        off[k + 1] += 1;
94    }
95    for i in 0..n {
96        off[i + 1] += off[i];
97    }
98    off
99}
100
101fn slice<'a, T>(data: &'a [T], offsets: &[u32], i: usize) -> &'a [T] {
102    match (offsets.get(i), offsets.get(i + 1)) {
103        (Some(&a), Some(&b)) => &data[a as usize..b as usize],
104        _ => &[],
105    }
106}
107
108/// Approximate heap usage, to watch the cost of keeping every occurrence.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub struct MemoryStats {
111    pub entities: usize,
112    pub relations: usize,
113    pub sites: usize,
114    pub strings: usize,
115    /// Excluding props.
116    pub heap_bytes: usize,
117}
118
119impl Model {
120    #[allow(clippy::too_many_arguments)]
121    pub(crate) fn from_rows(
122        strings: StrTable,
123        languages: Vec<LanguageId>,
124        metamodel: Metamodel,
125        kinds: Vec<RelationKind>,
126        entities: Vec<EntityRow>,
127        props: Vec<(EntityId, Props)>,
128        relations: Vec<RelRow>,
129        sites: Vec<(u32, Range, u8)>,
130    ) -> Model {
131        let n = entities.len();
132
133        let mut order: Vec<u32> = (0..relations.len() as u32).collect();
134        order.sort_unstable_by_key(|&i| relations[i as usize]);
135        let mut new_of = vec![0u32; order.len()];
136        for (new, &old) in order.iter().enumerate() {
137            new_of[old as usize] = new as u32;
138        }
139        let relations: Vec<RelRow> = order.iter().map(|&i| relations[i as usize]).collect();
140
141        let mut sites = sites;
142        for s in &mut sites {
143            s.0 = new_of[s.0 as usize];
144        }
145        sites.sort_unstable();
146        // One site per (relation, range): flags are merged.
147        sites.dedup_by(|b, a| {
148            let same = a.0 == b.0 && a.1 == b.1;
149            if same {
150                a.2 |= b.2;
151            }
152            same
153        });
154        let site_offsets = offsets(relations.len(), sites.iter().map(|s| s.0 as usize));
155        let mut site_flags: Vec<SiteFlags> = sites.iter().map(|s| SiteFlags(s.2)).collect();
156        let mut sites: Vec<Range> = sites.into_iter().map(|s| s.1).collect();
157        // The in-place collect keeps the builder's growth slack.
158        sites.shrink_to_fit();
159        site_flags.shrink_to_fit();
160
161        let out_offsets = offsets(n, relations.iter().map(|r| r.from.index()));
162        let mut incoming: Vec<u32> = (0..relations.len() as u32).collect();
163        incoming.sort_by_key(|&i| relations[i as usize].to);
164        let in_offsets = offsets(n, relations.iter().map(|r| r.to.index()));
165
166        let mut children: Vec<(u32, EntityId)> = entities
167            .iter()
168            .enumerate()
169            .filter(|(_, e)| (e.parent as usize) < n)
170            .map(|(i, e)| (e.parent, EntityId(i as u32)))
171            .collect();
172        children.sort_unstable();
173        let child_offsets = offsets(n, children.iter().map(|c| c.0 as usize));
174        let mut children: Vec<EntityId> = children.into_iter().map(|c| c.1).collect();
175        children.shrink_to_fit();
176
177        let mut by_key: Vec<EntityId> = (0..n as u32).map(EntityId).collect();
178        by_key.sort_unstable_by(|a, b| {
179            strings
180                .get(entities[a.index()].key)
181                .cmp(strings.get(entities[b.index()].key))
182        });
183        let mut entities = entities;
184        entities.shrink_to_fit();
185        let mut languages = languages;
186        languages.shrink_to_fit();
187
188        Model {
189            strings,
190            languages,
191            metamodel,
192            kinds,
193            entities,
194            props,
195            by_key,
196            child_offsets,
197            children,
198            relations,
199            out_offsets,
200            in_offsets,
201            incoming,
202            site_offsets,
203            sites,
204            site_flags,
205        }
206    }
207
208    pub fn entity_count(&self) -> usize {
209        self.entities.len()
210    }
211
212    pub fn relation_count(&self) -> usize {
213        self.relations.len()
214    }
215
216    pub fn site_count(&self) -> usize {
217        self.sites.len()
218    }
219
220    pub fn entity(&self, id: EntityId) -> Option<EntityRef<'_>> {
221        (id.index() < self.entities.len()).then_some(EntityRef { model: self, id })
222    }
223
224    pub fn by_key(&self, key: &str) -> Option<EntityRef<'_>> {
225        let i = self
226            .by_key
227            .binary_search_by(|id| self.strings.get(self.entities[id.index()].key).cmp(key))
228            .ok()?;
229        self.entity(self.by_key[i])
230    }
231
232    pub fn entities(&self) -> impl ExactSizeIterator<Item = EntityRef<'_>> {
233        (0..self.entities.len() as u32).map(|i| EntityRef {
234            model: self,
235            id: EntityId(i),
236        })
237    }
238
239    /// Entities of an archetype, whatever their fine kind.
240    pub fn of_kind(&self, kind: EntityKind) -> impl Iterator<Item = EntityRef<'_>> {
241        self.entities().filter(move |e| e.kind() == kind)
242    }
243
244    /// Entities of exactly this fine kind.
245    pub fn of_kind_id(&self, kind: KindId) -> impl Iterator<Item = EntityRef<'_>> {
246        self.entities().filter(move |e| e.kind_id() == kind)
247    }
248
249    /// Entities whose kind carries every trait of `traits`. Bit meanings are
250    /// defined by the metamodel's author (see the `model-traits` crate).
251    pub fn of_trait(&self, traits: TraitMask) -> impl Iterator<Item = EntityRef<'_>> {
252        self.entities().filter(move |e| e.has_trait(traits))
253    }
254
255    /// Kinds of this model: archetype, traits and FM3 class of each.
256    pub fn metamodel(&self) -> &Metamodel {
257        &self.metamodel
258    }
259
260    pub fn roots(&self) -> impl Iterator<Item = EntityRef<'_>> {
261        self.entities().filter(|e| e.parent().is_none())
262    }
263
264    pub fn relation(&self, id: RelationId) -> Option<RelationRef<'_>> {
265        (id.index() < self.relations.len()).then_some(RelationRef { model: self, id })
266    }
267
268    pub fn relations(&self) -> impl ExactSizeIterator<Item = RelationRef<'_>> {
269        (0..self.relations.len() as u32).map(|i| RelationRef {
270            model: self,
271            id: RelationId(i),
272        })
273    }
274
275    /// Languages present, in first-seen order.
276    pub fn languages(&self) -> &[LanguageId] {
277        &self.languages
278    }
279
280    pub fn memory(&self) -> MemoryStats {
281        fn v<T>(x: &Vec<T>) -> usize {
282            x.capacity() * size_of::<T>()
283        }
284        MemoryStats {
285            entities: self.entities.len(),
286            relations: self.relations.len(),
287            sites: self.sites.len(),
288            strings: self.strings.len(),
289            heap_bytes: self.strings.heap_bytes()
290                + v(&self.entities)
291                + v(&self.props)
292                + v(&self.by_key)
293                + v(&self.child_offsets)
294                + v(&self.children)
295                + v(&self.relations)
296                + v(&self.out_offsets)
297                + v(&self.in_offsets)
298                + v(&self.incoming)
299                + v(&self.site_offsets)
300                + v(&self.sites)
301                + v(&self.site_flags),
302        }
303    }
304
305    fn kind_id(&self, kind: &RelationKind) -> Option<u16> {
306        self.kinds.iter().position(|k| k == kind).map(|k| k as u16)
307    }
308}
309
310impl std::fmt::Debug for Model {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        f.debug_struct("Model")
313            .field("entities", &self.entities.len())
314            .field("relations", &self.relations.len())
315            .field("sites", &self.sites.len())
316            .finish()
317    }
318}
319
320/// An entity of a [`Model`]; cheap to copy.
321#[derive(Clone, Copy)]
322pub struct EntityRef<'m> {
323    model: &'m Model,
324    id: EntityId,
325}
326
327impl<'m> EntityRef<'m> {
328    fn row(self) -> &'m EntityRow {
329        &self.model.entities[self.id.index()]
330    }
331
332    pub fn id(self) -> EntityId {
333        self.id
334    }
335
336    /// Unique and stable across runs; see [`crate::SymbolKey`].
337    pub fn key(self) -> &'m str {
338        self.model.strings.get(self.row().key)
339    }
340
341    /// Archetype of the entity's fine kind.
342    pub fn kind(self) -> EntityKind {
343        self.model.metamodel.archetype(self.row().kind)
344    }
345
346    /// Fine kind (`record`, `enum_constant`...); same as the archetype's
347    /// default kind when the frontend does not refine it.
348    pub fn kind_id(self) -> KindId {
349        self.row().kind
350    }
351
352    pub fn kind_info(self) -> Option<&'m KindInfo> {
353        self.model.metamodel.get(self.row().kind)
354    }
355
356    /// Whether the entity's kind carries every trait of `traits`.
357    pub fn has_trait(self, traits: TraitMask) -> bool {
358        self.kind_info().is_some_and(|k| k.traits.contains(traits))
359    }
360
361    /// Name of the fine kind.
362    pub fn kind_name(self) -> &'m str {
363        self.kind_info().map_or("", |k| k.name.as_str())
364    }
365
366    /// Simple name.
367    pub fn name(self) -> &'m str {
368        self.model.strings.get(self.row().name)
369    }
370
371    pub fn language(self) -> Option<&'m LanguageId> {
372        self.model.languages.get(self.row().language as usize)
373    }
374
375    /// Referenced but not defined in the analysed sources (library, JDK...).
376    pub fn external(self) -> bool {
377        self.row().flags & EntityRow::EXTERNAL != 0
378    }
379
380    /// Path relative to the analysed root, '/' separators.
381    pub fn file(self) -> Option<&'m str> {
382        let f = self.row().file;
383        (f != NONE).then(|| self.model.strings.get(StrId(f)))
384    }
385
386    /// Full extent, when the entity has a source.
387    pub fn range(self) -> Option<Range> {
388        (self.row().file != NONE).then_some(self.row().range)
389    }
390
391    /// Identifier only; used to match SCIP definition occurrences.
392    pub fn name_range(self) -> Option<Range> {
393        let r = self.row();
394        (r.file != NONE && r.flags & EntityRow::HAS_NAME_RANGE != 0).then_some(r.name_range)
395    }
396
397    pub fn props(self) -> &'m Props {
398        let props = &self.model.props;
399        props
400            .binary_search_by_key(&self.id, |(id, _)| *id)
401            .map_or(&NO_PROPS, |i| &props[i].1)
402    }
403
404    pub fn parent(self) -> Option<EntityRef<'m>> {
405        self.model.entity(EntityId(self.row().parent))
406    }
407
408    /// Enclosing entities, innermost first. Bounded to survive cycles.
409    pub fn ancestors(self) -> impl Iterator<Item = EntityRef<'m>> {
410        let mut cur = self.parent();
411        let mut left = self.model.entities.len();
412        std::iter::from_fn(move || {
413            left = left.checked_sub(1)?;
414            let e = cur?;
415            cur = e.parent();
416            Some(e)
417        })
418    }
419
420    pub fn children(self) -> impl ExactSizeIterator<Item = EntityRef<'m>> {
421        let m = self.model;
422        slice(&m.children, &m.child_offsets, self.id.index())
423            .iter()
424            .map(move |&id| EntityRef { model: m, id })
425    }
426
427    /// Sorted by kind, then target.
428    pub fn outgoing(self) -> impl ExactSizeIterator<Item = RelationRef<'m>> {
429        let m = self.model;
430        let (a, b) = match (
431            m.out_offsets.get(self.id.index()),
432            m.out_offsets.get(self.id.index() + 1),
433        ) {
434            (Some(&a), Some(&b)) => (a, b),
435            _ => (0, 0),
436        };
437        (a..b).map(move |i| RelationRef {
438            model: m,
439            id: RelationId(i),
440        })
441    }
442
443    pub fn incoming(self) -> impl ExactSizeIterator<Item = RelationRef<'m>> {
444        let m = self.model;
445        slice(&m.incoming, &m.in_offsets, self.id.index())
446            .iter()
447            .map(move |&i| RelationRef {
448                model: m,
449                id: RelationId(i),
450            })
451    }
452
453    /// Targets of the outgoing relations of `kind`, any provenance.
454    pub fn targets(self, kind: &RelationKind) -> impl Iterator<Item = EntityRef<'m>> {
455        let k = self.model.kind_id(kind);
456        self.outgoing()
457            .filter(move |r| Some(r.row().kind) == k)
458            .map(|r| r.to())
459    }
460}
461
462impl PartialEq for EntityRef<'_> {
463    fn eq(&self, other: &Self) -> bool {
464        std::ptr::eq(self.model, other.model) && self.id == other.id
465    }
466}
467
468impl std::fmt::Debug for EntityRef<'_> {
469    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
470        write!(f, "{:?} {}", self.kind(), self.key())
471    }
472}
473
474/// A relation of a [`Model`] with all its occurrence sites; cheap to copy.
475#[derive(Clone, Copy)]
476pub struct RelationRef<'m> {
477    model: &'m Model,
478    id: RelationId,
479}
480
481impl<'m> RelationRef<'m> {
482    fn row(self) -> &'m RelRow {
483        &self.model.relations[self.id.index()]
484    }
485
486    pub fn id(self) -> RelationId {
487        self.id
488    }
489
490    pub fn kind(self) -> &'m RelationKind {
491        &self.model.kinds[self.row().kind as usize]
492    }
493
494    pub fn from(self) -> EntityRef<'m> {
495        EntityRef {
496            model: self.model,
497            id: self.row().from,
498        }
499    }
500
501    pub fn to(self) -> EntityRef<'m> {
502        EntityRef {
503            model: self.model,
504            id: self.row().to,
505        }
506    }
507
508    pub fn provenance(self) -> Provenance {
509        self.row().provenance
510    }
511
512    /// Occurrence sites, sorted, in the file of [`Self::from`].
513    pub fn sites(self) -> &'m [Range] {
514        slice(&self.model.sites, &self.model.site_offsets, self.id.index())
515    }
516
517    /// Flags of each site of [`Self::sites`], same order.
518    pub fn site_flags(self) -> &'m [SiteFlags] {
519        slice(
520            &self.model.site_flags,
521            &self.model.site_offsets,
522            self.id.index(),
523        )
524    }
525}
526
527impl PartialEq for RelationRef<'_> {
528    fn eq(&self, other: &Self) -> bool {
529        std::ptr::eq(self.model, other.model) && self.id == other.id
530    }
531}
532
533impl std::fmt::Debug for RelationRef<'_> {
534    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
535        write!(
536            f,
537            "{} -{:?}-> {} ({:?}, {} sites)",
538            self.from().key(),
539            self.kind(),
540            self.to().key(),
541            self.provenance(),
542            self.sites().len()
543        )
544    }
545}
546
547#[cfg(test)]
548pub(crate) mod tests {
549    use super::*;
550    use crate::{ModelBuilder, TraitMask};
551
552    fn r(line: u32) -> Range {
553        Range::new(line, 4, line, 10)
554    }
555
556    pub(crate) fn sample() -> Model {
557        let java = LanguageId::new("java");
558        let mut b = ModelBuilder::new();
559        let pkg = b.entity("model java . . com/acme/", EntityKind::Namespace, "acme");
560        let a = b.entity("model java . . com/acme/A#", EntityKind::Class, "A");
561        let run = b.entity(
562            "model java . . com/acme/A#run().",
563            EntityKind::Method,
564            "run",
565        );
566        let list = b.entity(
567            "semanticdb maven jdk 17 java/util/List#",
568            EntityKind::Interface,
569            "List",
570        );
571        for e in [pkg, a, run] {
572            b.set_language(e, &java);
573        }
574        b.set_parent(a, Some(pkg));
575        b.set_parent(run, Some(a));
576        b.set_source(
577            a,
578            "src/A.java",
579            Range::new(2, 0, 20, 1),
580            Some(Range::new(2, 13, 2, 14)),
581        );
582        b.set_source(run, "src/A.java", Range::new(3, 2, 9, 3), None);
583        b.set_external(list, true);
584        b.set_prop(a, "java.annotations", vec!["Service"]);
585        b.occurrence(&RelationKind::References, run, list, Provenance::Scip, r(5));
586        b.occurrence(&RelationKind::References, run, list, Provenance::Scip, r(4));
587        b.occurrence(&RelationKind::References, run, list, Provenance::Scip, r(5));
588        b.occurrence(&RelationKind::Calls, run, run, Provenance::TreeSitter, r(7));
589        b.relate(
590            &RelationKind::Other("http".into()),
591            run,
592            a,
593            Provenance::Derived,
594        );
595        b.build()
596    }
597
598    #[test]
599    fn rows_stay_compact() {
600        assert_eq!(size_of::<EntityRow>(), 52);
601        assert_eq!(size_of::<KindId>(), 1);
602        assert_eq!(size_of::<RelRow>(), 12);
603        assert_eq!(size_of::<Range>(), 16);
604    }
605
606    #[test]
607    fn rekey_moves_the_key_and_drops_the_old_string() {
608        let mut b = ModelBuilder::new();
609        let a = b.entity("model java . . A#", EntityKind::Class, "A");
610        let c = b.entity("semanticdb maven m 1 C#", EntityKind::Class, "C");
611        assert_eq!(b.rekey(a, "semanticdb maven m 1 A#"), Ok(()));
612        assert_eq!(b.rekey(a, "semanticdb maven m 1 A#"), Ok(()));
613        assert_eq!(b.rekey(a, "semanticdb maven m 1 C#"), Err(c));
614        assert_eq!(b.get("model java . . A#"), None);
615        assert_eq!(b.get("semanticdb maven m 1 A#"), Some(a));
616        let m = b.build();
617        assert_eq!(
618            m.by_key("semanticdb maven m 1 A#").map(|e| e.name()),
619            Some("A")
620        );
621        assert_eq!(m.memory().strings, 4, "A, C, and their SCIP keys");
622    }
623
624    #[test]
625    fn builder_is_get_or_create_by_key() {
626        let mut b = ModelBuilder::new();
627        let x = b.entity("k", EntityKind::Class, "X");
628        let y = b.entity("k", EntityKind::Method, "Y");
629        assert_eq!(x, y);
630        assert_eq!(b.entity_count(), 1);
631        assert_eq!(b.kind(x), EntityKind::Class);
632        assert_eq!(b.get("k"), Some(x));
633        assert_eq!(b.get("nope"), None);
634    }
635
636    #[test]
637    fn entity_accessors() {
638        let m = sample();
639        let a = m.by_key("model java . . com/acme/A#").unwrap();
640        assert_eq!(a.name(), "A");
641        assert_eq!(a.file(), Some("src/A.java"));
642        assert_eq!(a.name_range(), Some(Range::new(2, 13, 2, 14)));
643        assert_eq!(a.language().map(|l| l.as_str()), Some("java"));
644        assert!(a.props().contains_key("java.annotations"));
645        let run = m.by_key("model java . . com/acme/A#run().").unwrap();
646        assert_eq!(run.name_range(), None);
647        assert!(run.props().is_empty());
648        let list = m.by_key("semanticdb maven jdk 17 java/util/List#").unwrap();
649        assert!(list.external());
650        assert_eq!(list.file(), None);
651        assert_eq!(list.language(), None);
652        assert!(m.by_key("model java . . com/").is_none());
653    }
654
655    #[test]
656    fn navigates_containment() {
657        let m = sample();
658        let run = m.by_key("model java . . com/acme/A#run().").unwrap();
659        let up: Vec<_> = run.ancestors().map(|e| e.name()).collect();
660        assert_eq!(up, ["A", "acme"]);
661        assert_eq!(m.roots().count(), 2);
662        let a = run.parent().unwrap();
663        assert_eq!(a.children().collect::<Vec<_>>(), [run]);
664    }
665
666    #[test]
667    fn keeps_every_distinct_site_on_one_relation() {
668        let m = sample();
669        assert_eq!(m.relation_count(), 3);
670        assert_eq!(m.site_count(), 3, "duplicate site dropped");
671        let run = m.by_key("model java . . com/acme/A#run().").unwrap();
672        let refs: Vec<_> = run
673            .outgoing()
674            .filter(|r| r.kind() == &RelationKind::References)
675            .collect();
676        assert_eq!(refs.len(), 1);
677        assert_eq!(refs[0].sites(), [r(4), r(5)]);
678        assert_eq!(refs[0].from().file(), Some("src/A.java"));
679        let targets: Vec<_> = run
680            .targets(&RelationKind::References)
681            .map(|e| e.name())
682            .collect();
683        assert_eq!(targets, ["List"]);
684        assert_eq!(run.targets(&RelationKind::Inherits).count(), 0);
685        let calls = run
686            .outgoing()
687            .find(|r| r.kind() == &RelationKind::Calls)
688            .unwrap();
689        assert_eq!(calls.provenance(), Provenance::TreeSitter);
690        let a = run.parent().unwrap();
691        let into_a: Vec<_> = a.incoming().map(|r| r.kind().clone()).collect();
692        assert_eq!(into_a, [RelationKind::Other("http".into())]);
693        assert_eq!(run.incoming().count(), 1);
694    }
695
696    #[test]
697    fn same_pair_different_provenance_are_distinct() {
698        let mut b = ModelBuilder::new();
699        let x = b.entity("x", EntityKind::Function, "x");
700        let y = b.entity("y", EntityKind::Function, "y");
701        b.relate(&RelationKind::Calls, x, y, Provenance::TreeSitter);
702        b.relate(&RelationKind::Calls, x, y, Provenance::Scip);
703        b.relate(&RelationKind::Calls, x, y, Provenance::Scip);
704        assert_eq!(b.build().relation_count(), 2);
705    }
706
707    #[test]
708    fn fine_kinds_refine_the_archetype() {
709        let mut b = ModelBuilder::new();
710        let rec = b.define_kind(
711            "record",
712            EntityKind::Class,
713            TraitMask(0b10),
714            Some("Famix-Java-Entities.Record"),
715        );
716        assert_eq!(
717            b.define_kind("record", EntityKind::Enum, TraitMask::EMPTY, None),
718            rec
719        );
720        let r = b.entity_of_kind("r", rec, "R");
721        let c = b.entity("c", EntityKind::Class, "C");
722        assert_eq!(b.kind(r), EntityKind::Class);
723        assert_eq!(b.kind_id(r), rec);
724        assert_eq!(b.kind_id(c), KindId::of(EntityKind::Class));
725        let m = b.build();
726        let r = m.by_key("r").unwrap();
727        assert_eq!(
728            (r.kind(), r.kind_id(), r.kind_name()),
729            (EntityKind::Class, rec, "record")
730        );
731        let info = r.kind_info().unwrap();
732        assert_eq!(info.fm3.as_deref(), Some("Famix-Java-Entities.Record"));
733        assert!(info.traits.contains(TraitMask(0b10)));
734        assert_eq!(m.of_kind(EntityKind::Class).count(), 2);
735        assert_eq!(m.of_kind_id(rec).count(), 1);
736        assert!(r.has_trait(TraitMask(0b10)) && !r.has_trait(TraitMask(0b100)));
737        assert!(r.has_trait(TraitMask::EMPTY));
738        assert_eq!(m.of_trait(TraitMask(0b10)).count(), 1);
739        assert_eq!(m.of_trait(TraitMask::EMPTY).count(), 2);
740        assert_eq!(m.metamodel().find("record"), Some(rec));
741    }
742
743    #[test]
744    fn full_metamodel_falls_back_to_the_archetype() {
745        let mut mm = Metamodel::default();
746        let mut last = KindId::of(EntityKind::Class);
747        for i in 0..300 {
748            last = mm.define(&format!("k{i}"), EntityKind::Enum, TraitMask::EMPTY, None);
749        }
750        assert_eq!(mm.len(), 256);
751        assert_eq!(last, KindId::of(EntityKind::Enum));
752    }
753
754    #[test]
755    fn reports_memory() {
756        let s = sample().memory();
757        assert_eq!((s.entities, s.relations, s.sites), (4, 3, 3));
758        assert!(s.heap_bytes >= 4 * 52 + 3 * 12 + 3 * 16);
759    }
760}