1use std::collections::HashSet;
24
25use anyhow::{bail, Result};
26
27use crate::link::Link;
28use crate::link_storage::ChangeObserver;
29use crate::named_type_links::NamedTypeLinks;
30
31pub const ROOT_TYPE_NAME: &str = "Type";
33
34pub const EXTENDS_NAME: &str = "Extends";
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub struct TypeMarkers {
42 pub root: u32,
43 pub extends: Option<u32>,
44}
45
46impl TypeMarkers {
47 pub fn ensure<L: NamedTypeLinks + ?Sized>(links: &mut L) -> Result<Self> {
50 Ok(Self {
51 root: ensure_point(links, ROOT_TYPE_NAME)?,
52 extends: Some(ensure_point(links, EXTENDS_NAME)?),
53 })
54 }
55}
56
57pub fn ensure_point<L: NamedTypeLinks + ?Sized>(links: &mut L, name: &str) -> Result<u32> {
61 if let Some(known) = links.get_by_name(name)? {
62 if known != 0 && links.exists(known) {
63 return Ok(known);
64 }
65 }
66 let id = links.try_create(0, 0)?;
67 links.update(id, id, id)?;
68 links.set_name(id, name)?;
69 Ok(id)
70}
71
72pub trait Types: NamedTypeLinks {
80 fn root(&self) -> u32;
82
83 fn extends(&self) -> Option<u32>;
85
86 fn type_of(&mut self, link: u32) -> Option<u32> {
88 stored(self, link).map(|link| link.source)
89 }
90
91 fn is_type(&mut self, link: u32) -> bool {
93 stored(self, link).is_some_and(|stored| stored.target == link)
94 }
95
96 fn parents_of(&mut self, type_id: u32) -> Vec<u32> {
99 let mut parents = Vec::new();
100 let Some(link) = stored(self, type_id) else {
101 return parents;
102 };
103 if link.source != type_id && link.source != 0 {
104 parents.push(link.source);
105 }
106 add_extended_types(self, type_id, &mut parents);
107 parents
108 }
109
110 fn ancestors_of(&mut self, type_id: u32) -> Vec<u32> {
112 let mut ancestors = vec![type_id];
113 let mut seen = HashSet::from([type_id]);
114 let mut i = 0;
115 while i < ancestors.len() {
116 for parent in self.parents_of(ancestors[i]) {
117 if seen.insert(parent) {
118 ancestors.push(parent);
119 }
120 }
121 i += 1;
122 }
123 ancestors
124 }
125
126 fn is_extension(&mut self, link: u32) -> bool {
128 match self.extends() {
129 Some(extends) if link != 0 => self.search(extends, link).is_some(),
130 _ => false,
131 }
132 }
133
134 fn is_of(&mut self, link: u32, type_id: u32) -> bool {
138 match stored(self, link) {
139 Some(link) => self.is_of_link(&link, type_id),
140 None => false,
141 }
142 }
143
144 fn is_of_link(&mut self, link: &Link, type_id: u32) -> bool {
147 let mut starts = Vec::new();
151 match self.extends() {
152 Some(extends) if self.is_extension(link.index) => starts.push(extends),
153 _ => {
154 starts.push(link.source);
155 if link.index != 0 && self.exists(link.index) {
156 add_extended_types(self, link.index, &mut starts);
157 }
158 }
159 }
160 let mut stack: Vec<u32> = starts.into_iter().rev().collect();
161 let mut seen = HashSet::new();
162 while let Some(at) = stack.pop() {
163 if at == type_id {
164 return true;
165 }
166 if at == 0 || !seen.insert(at) {
167 continue;
168 }
169 stack.extend(self.parents_of(at));
170 }
171 false
172 }
173
174 fn is_a(&mut self, link: u32, type_id: u32) -> bool {
176 stored(self, link).is_some() && (link == type_id || self.is_of(link, type_id))
177 }
178
179 fn is_a_link(&mut self, link: &Link, type_id: u32) -> bool {
182 link.index == type_id || self.is_of_link(link, type_id)
183 }
184
185 fn define(&mut self, parent: u32, more: &[u32]) -> Result<u32> {
187 if !more.is_empty() && self.extends().is_none() {
188 bail!("Multiple parents need an Extends marker.");
189 }
190 ensure_exists(self, parent)?;
191 for &other in more {
192 ensure_exists(self, other)?;
193 }
194 let id = self.try_create(0, 0)?;
195 self.update(id, parent, id)?;
196 for &other in more {
197 self.extend(id, other)?;
198 }
199 Ok(id)
200 }
201
202 fn define_root(&mut self) -> Result<u32> {
204 let root = self.root();
205 self.define(root, &[])
206 }
207
208 fn extend(&mut self, type_id: u32, parent: u32) -> Result<u32> {
214 let Some(extends) = self.extends() else {
215 bail!("Multiple parents need an Extends marker.");
216 };
217 ensure_exists(self, type_id)?;
218 let parent_link = ensure_exists(self, parent)?;
219 if parent_link.source == type_id && parent_link.target == parent {
220 bail!(
223 "Type {parent} is a direct sub-type of {type_id}: the pair ({type_id} {parent}) would be its definition."
224 );
225 }
226 let pair = self.try_get_or_create(type_id, parent)?;
227 self.try_get_or_create(extends, pair)?;
228 Ok(pair)
229 }
230
231 fn instance(&mut self, type_id: u32) -> Result<u32> {
233 ensure_exists(self, type_id)?;
234 let id = self.try_create(0, 0)?;
235 self.update(id, type_id, id)?;
236 Ok(id)
237 }
238
239 fn instance_with_target(&mut self, type_id: u32, target: u32) -> Result<u32> {
241 ensure_exists(self, type_id)?;
242 ensure_exists(self, target)?;
243 self.try_get_or_create(type_id, target)
244 }
245}
246
247fn stored<L: NamedTypeLinks + ?Sized>(links: &mut L, link: u32) -> Option<Link> {
248 if link == 0 {
249 return None;
250 }
251 links.get_link(link)
252}
253
254fn ensure_exists<L: NamedTypeLinks + ?Sized>(links: &mut L, link: u32) -> Result<Link> {
255 match stored(links, link) {
256 Some(stored) => Ok(stored),
257 None => bail!("Link {link} does not exist."),
258 }
259}
260
261fn add_extended_types<T: Types + ?Sized>(types: &mut T, type_id: u32, parents: &mut Vec<u32>) {
264 if types.extends().is_none() || type_id == 0 {
265 return;
266 }
267 for pair in types.query_links(None, Some(type_id), None) {
268 if pair.index != type_id && pair.target != 0 && types.is_extension(pair.index) {
269 parents.push(pair.target);
270 }
271 }
272}
273
274pub struct TypesDecorator<L: NamedTypeLinks> {
278 links: L,
279 markers: TypeMarkers,
280}
281
282impl<L: NamedTypeLinks> TypesDecorator<L> {
283 pub fn new(links: L, root: u32, extends: Option<u32>) -> Self {
286 Self::with_markers(links, TypeMarkers { root, extends })
287 }
288
289 pub fn with_markers(links: L, markers: TypeMarkers) -> Self {
290 Self { links, markers }
291 }
292
293 pub fn with_named_markers(mut links: L) -> Result<Self> {
296 let markers = TypeMarkers::ensure(&mut links)?;
297 Ok(Self::with_markers(links, markers))
298 }
299
300 pub fn markers(&self) -> TypeMarkers {
301 self.markers
302 }
303
304 pub fn links(&self) -> &L {
305 &self.links
306 }
307
308 pub fn links_mut(&mut self) -> &mut L {
309 &mut self.links
310 }
311
312 pub fn into_inner(self) -> L {
313 self.links
314 }
315}
316
317impl<L: NamedTypeLinks> Types for TypesDecorator<L> {
318 fn root(&self) -> u32 {
319 self.markers.root
320 }
321
322 fn extends(&self) -> Option<u32> {
323 self.markers.extends
324 }
325}
326
327impl<L: NamedTypeLinks> NamedTypeLinks for TypesDecorator<L> {
328 fn create(&mut self, source: u32, target: u32) -> u32 {
329 self.links.create(source, target)
330 }
331
332 fn ensure_created(&mut self, id: u32) -> u32 {
333 self.links.ensure_created(id)
334 }
335
336 fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
337 self.links.try_ensure_created(id)
338 }
339
340 fn get_link(&mut self, id: u32) -> Option<Link> {
341 self.links.get_link(id)
342 }
343
344 fn exists(&mut self, id: u32) -> bool {
345 self.links.exists(id)
346 }
347
348 fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
349 self.links.try_create(source, target)
350 }
351
352 fn try_get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
353 self.links.try_get_or_create(source, target)
354 }
355
356 fn reference_exists(&mut self, id: u32) -> bool {
357 self.links.reference_exists(id)
358 }
359
360 fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
361 self.links.next_created_addresses(count)
362 }
363
364 fn update_observed(
365 &mut self,
366 id: u32,
367 source: u32,
368 target: u32,
369 observer: ChangeObserver<'_>,
370 ) -> Result<Link> {
371 self.links.update_observed(id, source, target, observer)
372 }
373
374 fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
375 self.links.delete_observed(id, observer)
376 }
377
378 fn all_links(&mut self) -> Vec<Link> {
379 self.links.all_links()
380 }
381
382 fn query_links(
383 &mut self,
384 index: Option<u32>,
385 source: Option<u32>,
386 target: Option<u32>,
387 ) -> Vec<Link> {
388 self.links.query_links(index, source, target)
389 }
390
391 fn search(&mut self, source: u32, target: u32) -> Option<u32> {
392 self.links.search(source, target)
393 }
394
395 fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
396 self.links.get_or_create(source, target)
397 }
398
399 fn get_name(&mut self, id: u32) -> Result<Option<String>> {
400 self.links.get_name(id)
401 }
402
403 fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
404 self.links.set_name(id, name)
405 }
406
407 fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
408 self.links.get_by_name(name)
409 }
410
411 fn remove_name(&mut self, id: u32) -> Result<()> {
412 self.links.remove_name(id)
413 }
414
415 fn save(&mut self) -> Result<()> {
416 self.links.save()
417 }
418
419 fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
420 self.links.get_or_create_named(name)
421 }
422}