1use crate::entity::{EntityId, EntityKind, LanguageId};
2use crate::relation::{Provenance, RelationId, RelationKind};
3use crate::source::Range;
4use crate::strings::{StrId, StrTable};
5use crate::value::Props;
6
7pub(crate) const NONE: u32 = u32::MAX;
9pub(crate) const NO_LANGUAGE: u16 = u16::MAX;
10
11static NO_PROPS: Props = Props::new();
12
13#[derive(Debug, Clone, Copy)]
15pub(crate) struct EntityRow {
16 pub(crate) key: StrId,
17 pub(crate) name: StrId,
18 pub(crate) file: u32,
19 pub(crate) parent: u32,
20 pub(crate) range: Range,
21 pub(crate) name_range: Range,
22 pub(crate) kind: EntityKind,
23 pub(crate) language: u16,
24 pub(crate) flags: u8,
25}
26
27impl EntityRow {
28 pub(crate) const EXTERNAL: u8 = 1;
29 pub(crate) const HAS_NAME_RANGE: u8 = 2;
30
31 pub(crate) fn set_flag(&mut self, flag: u8, on: bool) {
32 if on {
33 self.flags |= flag;
34 } else {
35 self.flags &= !flag;
36 }
37 }
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
43pub(crate) struct RelRow {
44 pub(crate) from: EntityId,
45 pub(crate) kind: u16,
46 pub(crate) to: EntityId,
47 pub(crate) provenance: Provenance,
48}
49
50#[derive(Clone)]
60pub struct Model {
61 strings: StrTable,
62 languages: Vec<LanguageId>,
63 kinds: Vec<RelationKind>,
64 entities: Vec<EntityRow>,
65 props: Vec<(EntityId, Props)>,
67 by_key: Vec<EntityId>,
69 child_offsets: Vec<u32>,
71 children: Vec<EntityId>,
72 relations: Vec<RelRow>,
73 out_offsets: Vec<u32>,
75 in_offsets: Vec<u32>,
77 incoming: Vec<u32>,
78 site_offsets: Vec<u32>,
80 sites: Vec<Range>,
81}
82
83fn offsets(n: usize, keys: impl Iterator<Item = usize>) -> Vec<u32> {
85 let mut off = vec![0u32; n + 1];
86 for k in keys {
87 off[k + 1] += 1;
88 }
89 for i in 0..n {
90 off[i + 1] += off[i];
91 }
92 off
93}
94
95fn slice<'a, T>(data: &'a [T], offsets: &[u32], i: usize) -> &'a [T] {
96 match (offsets.get(i), offsets.get(i + 1)) {
97 (Some(&a), Some(&b)) => &data[a as usize..b as usize],
98 _ => &[],
99 }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub struct MemoryStats {
105 pub entities: usize,
106 pub relations: usize,
107 pub sites: usize,
108 pub strings: usize,
109 pub heap_bytes: usize,
111}
112
113impl Model {
114 pub(crate) fn from_rows(
115 strings: StrTable,
116 languages: Vec<LanguageId>,
117 kinds: Vec<RelationKind>,
118 entities: Vec<EntityRow>,
119 props: Vec<(EntityId, Props)>,
120 relations: Vec<RelRow>,
121 sites: Vec<(u32, Range)>,
122 ) -> Model {
123 let n = entities.len();
124
125 let mut order: Vec<u32> = (0..relations.len() as u32).collect();
126 order.sort_unstable_by_key(|&i| relations[i as usize]);
127 let mut new_of = vec![0u32; order.len()];
128 for (new, &old) in order.iter().enumerate() {
129 new_of[old as usize] = new as u32;
130 }
131 let relations: Vec<RelRow> = order.iter().map(|&i| relations[i as usize]).collect();
132
133 let mut sites = sites;
134 for s in &mut sites {
135 s.0 = new_of[s.0 as usize];
136 }
137 sites.sort_unstable();
138 sites.dedup();
139 let site_offsets = offsets(relations.len(), sites.iter().map(|s| s.0 as usize));
140 let mut sites: Vec<Range> = sites.into_iter().map(|s| s.1).collect();
141 sites.shrink_to_fit();
143
144 let out_offsets = offsets(n, relations.iter().map(|r| r.from.index()));
145 let mut incoming: Vec<u32> = (0..relations.len() as u32).collect();
146 incoming.sort_by_key(|&i| relations[i as usize].to);
147 let in_offsets = offsets(n, relations.iter().map(|r| r.to.index()));
148
149 let mut children: Vec<(u32, EntityId)> = entities
150 .iter()
151 .enumerate()
152 .filter(|(_, e)| (e.parent as usize) < n)
153 .map(|(i, e)| (e.parent, EntityId(i as u32)))
154 .collect();
155 children.sort_unstable();
156 let child_offsets = offsets(n, children.iter().map(|c| c.0 as usize));
157 let mut children: Vec<EntityId> = children.into_iter().map(|c| c.1).collect();
158 children.shrink_to_fit();
159
160 let mut by_key: Vec<EntityId> = (0..n as u32).map(EntityId).collect();
161 by_key.sort_unstable_by(|a, b| {
162 strings
163 .get(entities[a.index()].key)
164 .cmp(strings.get(entities[b.index()].key))
165 });
166 let mut entities = entities;
167 entities.shrink_to_fit();
168 let mut languages = languages;
169 languages.shrink_to_fit();
170
171 Model {
172 strings,
173 languages,
174 kinds,
175 entities,
176 props,
177 by_key,
178 child_offsets,
179 children,
180 relations,
181 out_offsets,
182 in_offsets,
183 incoming,
184 site_offsets,
185 sites,
186 }
187 }
188
189 pub fn entity_count(&self) -> usize {
190 self.entities.len()
191 }
192
193 pub fn relation_count(&self) -> usize {
194 self.relations.len()
195 }
196
197 pub fn site_count(&self) -> usize {
198 self.sites.len()
199 }
200
201 pub fn entity(&self, id: EntityId) -> Option<EntityRef<'_>> {
202 (id.index() < self.entities.len()).then_some(EntityRef { model: self, id })
203 }
204
205 pub fn by_key(&self, key: &str) -> Option<EntityRef<'_>> {
206 let i = self
207 .by_key
208 .binary_search_by(|id| self.strings.get(self.entities[id.index()].key).cmp(key))
209 .ok()?;
210 self.entity(self.by_key[i])
211 }
212
213 pub fn entities(&self) -> impl ExactSizeIterator<Item = EntityRef<'_>> {
214 (0..self.entities.len() as u32).map(|i| EntityRef {
215 model: self,
216 id: EntityId(i),
217 })
218 }
219
220 pub fn of_kind(&self, kind: EntityKind) -> impl Iterator<Item = EntityRef<'_>> {
221 self.entities().filter(move |e| e.kind() == kind)
222 }
223
224 pub fn roots(&self) -> impl Iterator<Item = EntityRef<'_>> {
225 self.entities().filter(|e| e.parent().is_none())
226 }
227
228 pub fn relation(&self, id: RelationId) -> Option<RelationRef<'_>> {
229 (id.index() < self.relations.len()).then_some(RelationRef { model: self, id })
230 }
231
232 pub fn relations(&self) -> impl ExactSizeIterator<Item = RelationRef<'_>> {
233 (0..self.relations.len() as u32).map(|i| RelationRef {
234 model: self,
235 id: RelationId(i),
236 })
237 }
238
239 pub fn languages(&self) -> &[LanguageId] {
241 &self.languages
242 }
243
244 pub fn memory(&self) -> MemoryStats {
245 fn v<T>(x: &Vec<T>) -> usize {
246 x.capacity() * size_of::<T>()
247 }
248 MemoryStats {
249 entities: self.entities.len(),
250 relations: self.relations.len(),
251 sites: self.sites.len(),
252 strings: self.strings.len(),
253 heap_bytes: self.strings.heap_bytes()
254 + v(&self.entities)
255 + v(&self.props)
256 + v(&self.by_key)
257 + v(&self.child_offsets)
258 + v(&self.children)
259 + v(&self.relations)
260 + v(&self.out_offsets)
261 + v(&self.in_offsets)
262 + v(&self.incoming)
263 + v(&self.site_offsets)
264 + v(&self.sites),
265 }
266 }
267
268 fn kind_id(&self, kind: &RelationKind) -> Option<u16> {
269 self.kinds.iter().position(|k| k == kind).map(|k| k as u16)
270 }
271}
272
273impl std::fmt::Debug for Model {
274 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275 f.debug_struct("Model")
276 .field("entities", &self.entities.len())
277 .field("relations", &self.relations.len())
278 .field("sites", &self.sites.len())
279 .finish()
280 }
281}
282
283#[derive(Clone, Copy)]
285pub struct EntityRef<'m> {
286 model: &'m Model,
287 id: EntityId,
288}
289
290impl<'m> EntityRef<'m> {
291 fn row(self) -> &'m EntityRow {
292 &self.model.entities[self.id.index()]
293 }
294
295 pub fn id(self) -> EntityId {
296 self.id
297 }
298
299 pub fn key(self) -> &'m str {
301 self.model.strings.get(self.row().key)
302 }
303
304 pub fn kind(self) -> EntityKind {
305 self.row().kind
306 }
307
308 pub fn name(self) -> &'m str {
310 self.model.strings.get(self.row().name)
311 }
312
313 pub fn language(self) -> Option<&'m LanguageId> {
314 self.model.languages.get(self.row().language as usize)
315 }
316
317 pub fn external(self) -> bool {
319 self.row().flags & EntityRow::EXTERNAL != 0
320 }
321
322 pub fn file(self) -> Option<&'m str> {
324 let f = self.row().file;
325 (f != NONE).then(|| self.model.strings.get(StrId(f)))
326 }
327
328 pub fn range(self) -> Option<Range> {
330 (self.row().file != NONE).then_some(self.row().range)
331 }
332
333 pub fn name_range(self) -> Option<Range> {
335 let r = self.row();
336 (r.file != NONE && r.flags & EntityRow::HAS_NAME_RANGE != 0).then_some(r.name_range)
337 }
338
339 pub fn props(self) -> &'m Props {
340 let props = &self.model.props;
341 props
342 .binary_search_by_key(&self.id, |(id, _)| *id)
343 .map_or(&NO_PROPS, |i| &props[i].1)
344 }
345
346 pub fn parent(self) -> Option<EntityRef<'m>> {
347 self.model.entity(EntityId(self.row().parent))
348 }
349
350 pub fn ancestors(self) -> impl Iterator<Item = EntityRef<'m>> {
352 let mut cur = self.parent();
353 let mut left = self.model.entities.len();
354 std::iter::from_fn(move || {
355 left = left.checked_sub(1)?;
356 let e = cur?;
357 cur = e.parent();
358 Some(e)
359 })
360 }
361
362 pub fn children(self) -> impl ExactSizeIterator<Item = EntityRef<'m>> {
363 let m = self.model;
364 slice(&m.children, &m.child_offsets, self.id.index())
365 .iter()
366 .map(move |&id| EntityRef { model: m, id })
367 }
368
369 pub fn outgoing(self) -> impl ExactSizeIterator<Item = RelationRef<'m>> {
371 let m = self.model;
372 let (a, b) = match (
373 m.out_offsets.get(self.id.index()),
374 m.out_offsets.get(self.id.index() + 1),
375 ) {
376 (Some(&a), Some(&b)) => (a, b),
377 _ => (0, 0),
378 };
379 (a..b).map(move |i| RelationRef {
380 model: m,
381 id: RelationId(i),
382 })
383 }
384
385 pub fn incoming(self) -> impl ExactSizeIterator<Item = RelationRef<'m>> {
386 let m = self.model;
387 slice(&m.incoming, &m.in_offsets, self.id.index())
388 .iter()
389 .map(move |&i| RelationRef {
390 model: m,
391 id: RelationId(i),
392 })
393 }
394
395 pub fn targets(self, kind: &RelationKind) -> impl Iterator<Item = EntityRef<'m>> {
397 let k = self.model.kind_id(kind);
398 self.outgoing()
399 .filter(move |r| Some(r.row().kind) == k)
400 .map(|r| r.to())
401 }
402}
403
404impl PartialEq for EntityRef<'_> {
405 fn eq(&self, other: &Self) -> bool {
406 std::ptr::eq(self.model, other.model) && self.id == other.id
407 }
408}
409
410impl std::fmt::Debug for EntityRef<'_> {
411 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412 write!(f, "{:?} {}", self.kind(), self.key())
413 }
414}
415
416#[derive(Clone, Copy)]
418pub struct RelationRef<'m> {
419 model: &'m Model,
420 id: RelationId,
421}
422
423impl<'m> RelationRef<'m> {
424 fn row(self) -> &'m RelRow {
425 &self.model.relations[self.id.index()]
426 }
427
428 pub fn id(self) -> RelationId {
429 self.id
430 }
431
432 pub fn kind(self) -> &'m RelationKind {
433 &self.model.kinds[self.row().kind as usize]
434 }
435
436 pub fn from(self) -> EntityRef<'m> {
437 EntityRef {
438 model: self.model,
439 id: self.row().from,
440 }
441 }
442
443 pub fn to(self) -> EntityRef<'m> {
444 EntityRef {
445 model: self.model,
446 id: self.row().to,
447 }
448 }
449
450 pub fn provenance(self) -> Provenance {
451 self.row().provenance
452 }
453
454 pub fn sites(self) -> &'m [Range] {
456 slice(&self.model.sites, &self.model.site_offsets, self.id.index())
457 }
458}
459
460impl PartialEq for RelationRef<'_> {
461 fn eq(&self, other: &Self) -> bool {
462 std::ptr::eq(self.model, other.model) && self.id == other.id
463 }
464}
465
466impl std::fmt::Debug for RelationRef<'_> {
467 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
468 write!(
469 f,
470 "{} -{:?}-> {} ({:?}, {} sites)",
471 self.from().key(),
472 self.kind(),
473 self.to().key(),
474 self.provenance(),
475 self.sites().len()
476 )
477 }
478}
479
480#[cfg(test)]
481pub(crate) mod tests {
482 use super::*;
483 use crate::ModelBuilder;
484
485 fn r(line: u32) -> Range {
486 Range::new(line, 4, line, 10)
487 }
488
489 pub(crate) fn sample() -> Model {
490 let java = LanguageId::new("java");
491 let mut b = ModelBuilder::new();
492 let pkg = b.entity("model java . . com/acme/", EntityKind::Namespace, "acme");
493 let a = b.entity("model java . . com/acme/A#", EntityKind::Class, "A");
494 let run = b.entity(
495 "model java . . com/acme/A#run().",
496 EntityKind::Method,
497 "run",
498 );
499 let list = b.entity(
500 "semanticdb maven jdk 17 java/util/List#",
501 EntityKind::Interface,
502 "List",
503 );
504 for e in [pkg, a, run] {
505 b.set_language(e, &java);
506 }
507 b.set_parent(a, Some(pkg));
508 b.set_parent(run, Some(a));
509 b.set_source(
510 a,
511 "src/A.java",
512 Range::new(2, 0, 20, 1),
513 Some(Range::new(2, 13, 2, 14)),
514 );
515 b.set_source(run, "src/A.java", Range::new(3, 2, 9, 3), None);
516 b.set_external(list, true);
517 b.set_prop(a, "java.annotations", vec!["Service"]);
518 b.occurrence(&RelationKind::References, run, list, Provenance::Scip, r(5));
519 b.occurrence(&RelationKind::References, run, list, Provenance::Scip, r(4));
520 b.occurrence(&RelationKind::References, run, list, Provenance::Scip, r(5));
521 b.occurrence(&RelationKind::Calls, run, run, Provenance::TreeSitter, r(7));
522 b.relate(
523 &RelationKind::Other("http".into()),
524 run,
525 a,
526 Provenance::Derived,
527 );
528 b.build()
529 }
530
531 #[test]
532 fn rows_stay_compact() {
533 assert_eq!(size_of::<EntityRow>(), 52);
534 assert_eq!(size_of::<RelRow>(), 12);
535 assert_eq!(size_of::<Range>(), 16);
536 }
537
538 #[test]
539 fn rekey_moves_the_key_and_drops_the_old_string() {
540 let mut b = ModelBuilder::new();
541 let a = b.entity("model java . . A#", EntityKind::Class, "A");
542 let c = b.entity("semanticdb maven m 1 C#", EntityKind::Class, "C");
543 assert_eq!(b.rekey(a, "semanticdb maven m 1 A#"), Ok(()));
544 assert_eq!(b.rekey(a, "semanticdb maven m 1 A#"), Ok(()));
545 assert_eq!(b.rekey(a, "semanticdb maven m 1 C#"), Err(c));
546 assert_eq!(b.get("model java . . A#"), None);
547 assert_eq!(b.get("semanticdb maven m 1 A#"), Some(a));
548 let m = b.build();
549 assert_eq!(
550 m.by_key("semanticdb maven m 1 A#").map(|e| e.name()),
551 Some("A")
552 );
553 assert_eq!(m.memory().strings, 4, "A, C, and their SCIP keys");
554 }
555
556 #[test]
557 fn builder_is_get_or_create_by_key() {
558 let mut b = ModelBuilder::new();
559 let x = b.entity("k", EntityKind::Class, "X");
560 let y = b.entity("k", EntityKind::Method, "Y");
561 assert_eq!(x, y);
562 assert_eq!(b.entity_count(), 1);
563 assert_eq!(b.kind(x), EntityKind::Class);
564 assert_eq!(b.get("k"), Some(x));
565 assert_eq!(b.get("nope"), None);
566 }
567
568 #[test]
569 fn entity_accessors() {
570 let m = sample();
571 let a = m.by_key("model java . . com/acme/A#").unwrap();
572 assert_eq!(a.name(), "A");
573 assert_eq!(a.file(), Some("src/A.java"));
574 assert_eq!(a.name_range(), Some(Range::new(2, 13, 2, 14)));
575 assert_eq!(a.language().map(|l| l.as_str()), Some("java"));
576 assert!(a.props().contains_key("java.annotations"));
577 let run = m.by_key("model java . . com/acme/A#run().").unwrap();
578 assert_eq!(run.name_range(), None);
579 assert!(run.props().is_empty());
580 let list = m.by_key("semanticdb maven jdk 17 java/util/List#").unwrap();
581 assert!(list.external());
582 assert_eq!(list.file(), None);
583 assert_eq!(list.language(), None);
584 assert!(m.by_key("model java . . com/").is_none());
585 }
586
587 #[test]
588 fn navigates_containment() {
589 let m = sample();
590 let run = m.by_key("model java . . com/acme/A#run().").unwrap();
591 let up: Vec<_> = run.ancestors().map(|e| e.name()).collect();
592 assert_eq!(up, ["A", "acme"]);
593 assert_eq!(m.roots().count(), 2);
594 let a = run.parent().unwrap();
595 assert_eq!(a.children().collect::<Vec<_>>(), [run]);
596 }
597
598 #[test]
599 fn keeps_every_distinct_site_on_one_relation() {
600 let m = sample();
601 assert_eq!(m.relation_count(), 3);
602 assert_eq!(m.site_count(), 3, "duplicate site dropped");
603 let run = m.by_key("model java . . com/acme/A#run().").unwrap();
604 let refs: Vec<_> = run
605 .outgoing()
606 .filter(|r| r.kind() == &RelationKind::References)
607 .collect();
608 assert_eq!(refs.len(), 1);
609 assert_eq!(refs[0].sites(), [r(4), r(5)]);
610 assert_eq!(refs[0].from().file(), Some("src/A.java"));
611 let targets: Vec<_> = run
612 .targets(&RelationKind::References)
613 .map(|e| e.name())
614 .collect();
615 assert_eq!(targets, ["List"]);
616 assert_eq!(run.targets(&RelationKind::Inherits).count(), 0);
617 let calls = run
618 .outgoing()
619 .find(|r| r.kind() == &RelationKind::Calls)
620 .unwrap();
621 assert_eq!(calls.provenance(), Provenance::TreeSitter);
622 let a = run.parent().unwrap();
623 let into_a: Vec<_> = a.incoming().map(|r| r.kind().clone()).collect();
624 assert_eq!(into_a, [RelationKind::Other("http".into())]);
625 assert_eq!(run.incoming().count(), 1);
626 }
627
628 #[test]
629 fn same_pair_different_provenance_are_distinct() {
630 let mut b = ModelBuilder::new();
631 let x = b.entity("x", EntityKind::Function, "x");
632 let y = b.entity("y", EntityKind::Function, "y");
633 b.relate(&RelationKind::Calls, x, y, Provenance::TreeSitter);
634 b.relate(&RelationKind::Calls, x, y, Provenance::Scip);
635 b.relate(&RelationKind::Calls, x, y, Provenance::Scip);
636 assert_eq!(b.build().relation_count(), 2);
637 }
638
639 #[test]
640 fn reports_memory() {
641 let s = sample().memory();
642 assert_eq!((s.entities, s.relations, s.sites), (4, 3, 3));
643 assert!(s.heap_bytes >= 4 * 52 + 3 * 12 + 3 * 16);
644 }
645}