1use std::collections::{HashMap, HashSet};
2use std::hash::{BuildHasherDefault, Hasher};
3
4#[derive(Default, Clone, Copy)]
18pub struct FastHasher {
19 hash: u64,
20}
21
22const SEED: u64 = 0xf135_7aea_2e62_a9c5;
23
24impl FastHasher {
25 #[inline]
26 fn add(&mut self, word: u64) {
27 self.hash = self.hash.wrapping_add(word).wrapping_mul(SEED);
28 }
29}
30
31impl Hasher for FastHasher {
32 #[inline]
33 fn write(&mut self, bytes: &[u8]) {
34 let mut chunks = bytes.chunks_exact(8);
35 for c in &mut chunks {
36 self.add(u64::from_le_bytes(c.try_into().expect("chunk of 8")));
37 }
38 let rest = chunks.remainder();
39 if !rest.is_empty() {
40 let mut buf = [0u8; 8];
41 buf[..rest.len()].copy_from_slice(rest);
42 self.add(u64::from_le_bytes(buf));
43 }
44 }
45 #[inline]
46 fn write_u8(&mut self, i: u8) {
47 self.add(i as u64);
48 }
49 #[inline]
50 fn write_u32(&mut self, i: u32) {
51 self.add(i as u64);
52 }
53 #[inline]
54 fn write_u64(&mut self, i: u64) {
55 self.add(i);
56 }
57 #[inline]
58 fn write_usize(&mut self, i: usize) {
59 self.add(i as u64);
60 }
61 #[inline]
62 fn finish(&self) -> u64 {
63 self.hash.rotate_left(26)
64 }
65}
66
67pub type FastBuildHasher = BuildHasherDefault<FastHasher>;
68pub type FastMap<K, V> = HashMap<K, V, FastBuildHasher>;
69pub type FastSet<T> = HashSet<T, FastBuildHasher>;
70pub type FieldMap = FastMap<&'static str, FieldValue>;
74
75pub fn intern(key: &str) -> &'static str {
80 use std::cell::RefCell;
81 use std::sync::{Mutex, OnceLock};
82 thread_local! {
83 static LOCAL: RefCell<FastSet<&'static str>> = RefCell::new(FastSet::default());
84 }
85 static GLOBAL: OnceLock<Mutex<FastSet<&'static str>>> = OnceLock::new();
86 if let Some(k) = LOCAL.with(|l| l.borrow().get(key).copied()) {
87 return k;
88 }
89 let k = {
90 let mut global = GLOBAL.get_or_init(Default::default).lock().unwrap();
91 match global.get(key) {
92 Some(k) => *k,
93 None => {
94 let k: &'static str = Box::leak(key.to_owned().into_boxed_str());
95 global.insert(k);
96 k
97 }
98 }
99 };
100 LOCAL.with(|l| l.borrow_mut().insert(k));
101 k
102}
103
104pub fn foreign_class(ns: &str, local: &str) -> &'static ClassDef {
109 use std::sync::{Mutex, OnceLock};
110 static CLASSES: OnceLock<Mutex<FastMap<String, &'static ClassDef>>> = OnceLock::new();
111 let iri = format!("{ns}{local}");
112 let mut classes = CLASSES.get_or_init(Default::default).lock().unwrap();
113 if let Some(c) = classes.get(&iri) {
114 return c;
115 }
116 let qualified: &'static str = Box::leak(iri.clone().into_boxed_str());
117 let class: &'static ClassDef = Box::leak(Box::new(ClassDef {
118 ns: intern(ns),
119 local: &qualified[ns.len()..],
120 qualified,
121 super_class: None,
122 concrete: true,
123 attrs: &[],
124 origins: &[],
125 comment: "",
126 }));
127 classes.insert(iri, class);
128 class
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum FieldValue {
133 Text(String),
134 TextList(Vec<String>),
137 Resource(String),
138 ResourceList(Vec<String>),
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
143pub enum Value<'a> {
144 Text(&'a str),
145 Resource(&'a str),
146}
147
148impl Value<'_> {
149 pub fn owned(&self) -> FieldValue {
151 match *self {
152 Value::Text(t) => FieldValue::Text(t.to_string()),
153 Value::Resource(r) => FieldValue::Resource(r.to_string()),
154 }
155 }
156}
157
158impl PartialEq<FieldValue> for Value<'_> {
159 fn eq(&self, other: &FieldValue) -> bool {
160 match (self, other) {
161 (Value::Text(a), FieldValue::Text(b)) => *a == b,
162 (Value::Resource(a), FieldValue::Resource(b)) => *a == b,
163 _ => false,
164 }
165 }
166}
167
168impl FieldValue {
169 pub fn values(&self) -> impl Iterator<Item = Value<'_>> {
171 let (texts, refs): (&[String], &[String]) = match self {
172 FieldValue::Text(t) => (std::slice::from_ref(t), &[]),
173 FieldValue::TextList(l) => (l.as_slice(), &[]),
174 FieldValue::Resource(r) => (&[], std::slice::from_ref(r)),
175 FieldValue::ResourceList(l) => (&[], l.as_slice()),
176 };
177 texts.iter().map(|t| Value::Text(t)).chain(refs.iter().map(|r| Value::Resource(r)))
178 }
179}
180
181#[derive(Debug, Clone)]
191pub struct Element {
192 class: &'static ClassDef,
193 mrid: String,
194 fields: FieldMap,
195 duplicate_fields: FastSet<&'static str>,
198 langs: Option<Box<Langs>>,
202 also: Option<Box<Types>>,
208 described: bool,
212}
213
214type Langs = Vec<(&'static str, Box<str>)>;
216
217type Types = Vec<&'static ClassDef>;
219
220impl Element {
221 pub fn new(class: &'static ClassDef, mrid: String) -> Self {
222 Self { class, mrid, fields: FieldMap::default(), duplicate_fields: FastSet::default(), langs: None, also: None, described: false }
223 }
224
225 pub fn with_fields(class: &'static ClassDef, mrid: String, fields: FieldMap) -> Self {
226 Self { class, mrid, fields, duplicate_fields: FastSet::default(), langs: None, also: None, described: false }
227 }
228
229 pub fn class(&self) -> &'static ClassDef {
230 self.class
231 }
232
233 pub fn types(&self) -> impl Iterator<Item = &'static ClassDef> + '_ {
236 std::iter::once(self.class).chain(self.also.iter().flat_map(|v| v.iter().copied()))
237 }
238
239 pub(crate) fn add_type(&mut self, other: &'static ClassDef, reg: &TypeRegistry) -> bool {
244 if self.types().any(|c| c.qualified == other.qualified) {
245 return false;
246 }
247 let promote = reg.chain(other).iter().any(|c| c.qualified == self.class.qualified);
248 let kept = if promote { std::mem::replace(&mut self.class, other) } else { other };
249 self.also.get_or_insert_with(Default::default).push(kept);
250 promote
251 }
252
253 pub fn defined(&self) -> bool {
256 !self.described
257 }
258
259 pub fn mark_described(&mut self) {
261 self.described = true;
262 }
263
264 pub fn mrid(&self) -> &str {
265 &self.mrid
266 }
267
268 pub fn type_name(&self) -> &'static str {
271 self.class.qualified
272 }
273
274 pub fn local_name(&self) -> &'static str {
276 self.class.local
277 }
278
279 pub fn type_ns(&self) -> &'static str {
281 self.class.ns
282 }
283
284 pub fn fields(&self) -> &FieldMap {
285 &self.fields
286 }
287
288 pub fn duplicate_fields(&self) -> &FastSet<&'static str> {
289 &self.duplicate_fields
290 }
291
292 pub fn langs(&self, key: &str) -> impl Iterator<Item = &str> {
296 self.langs.iter().flat_map(|l| l.iter()).filter(move |(k, _)| *k == key).map(|(_, l)| &**l)
297 }
298
299 pub fn add_lang(&mut self, key: &'static str, lang: &str) {
301 self.langs.get_or_insert_with(Default::default).push((key, lang.into()));
302 }
303
304 pub fn retype(&mut self, key: &str, reference: bool) {
307 if let Some(value) = self.fields.get_mut(key) {
308 *value = match (std::mem::replace(value, FieldValue::Text(String::new())), reference) {
309 (FieldValue::Text(s), true) => FieldValue::Resource(s),
310 (FieldValue::TextList(v), true) => FieldValue::ResourceList(v),
311 (FieldValue::Resource(s), false) => FieldValue::Text(s),
312 (FieldValue::ResourceList(v), false) => FieldValue::TextList(v),
313 (other, _) => other,
314 };
315 }
316 }
317
318 pub fn get(&self, attr: &str) -> Option<&FieldValue> {
319 self.fields.get(attr)
320 }
321
322 pub fn get_str(&self, attr: &str) -> Option<&str> {
323 match self.fields.get(attr) {
324 Some(FieldValue::Text(s)) => Some(s.as_str()),
325 Some(FieldValue::TextList(v)) => v.first().map(String::as_str),
326 _ => None,
327 }
328 }
329
330 pub fn get_f64(&self, attr: &str) -> Option<f64> {
331 self.get_str(attr)?.parse().ok()
332 }
333
334 pub fn get_bool(&self, attr: &str) -> Option<bool> {
335 match self.get_str(attr)? {
336 "true" | "1" => Some(true),
337 "false" | "0" => Some(false),
338 _ => None,
339 }
340 }
341
342 pub fn get_refs(&self, attr: &str) -> &[String] {
348 match self.fields.get(attr) {
349 Some(FieldValue::Resource(s)) => std::slice::from_ref(s),
350 Some(FieldValue::ResourceList(v)) => v.as_slice(),
351 _ => &[],
352 }
353 }
354
355 pub fn get_ref(&self, attr: &str) -> Option<&str> {
357 self.get_refs(attr).first().map(String::as_str)
358 }
359
360 pub fn add_field(&mut self, key: &'static str, val: FieldValue) {
363 match &val {
364 FieldValue::Resource(new_ref) => match self.fields.get_mut(key) {
365 Some(FieldValue::ResourceList(list)) => {
366 list.push(new_ref.clone());
367 self.duplicate_fields.insert(key);
368 return;
369 }
370 Some(existing @ FieldValue::Resource(_)) => {
371 let FieldValue::Resource(old) = std::mem::replace(existing, FieldValue::ResourceList(Vec::new())) else {
372 unreachable!()
373 };
374 *existing = FieldValue::ResourceList(vec![old, new_ref.clone()]);
375 self.duplicate_fields.insert(key);
376 return;
377 }
378 _ => {}
379 },
380 FieldValue::Text(new_text) => match self.fields.get_mut(key) {
381 Some(FieldValue::TextList(list)) => {
382 list.push(new_text.clone());
383 self.duplicate_fields.insert(key);
384 return;
385 }
386 Some(existing @ FieldValue::Text(_)) => {
387 let FieldValue::Text(old) = std::mem::replace(existing, FieldValue::TextList(Vec::new())) else {
388 unreachable!()
389 };
390 *existing = FieldValue::TextList(vec![old, new_text.clone()]);
391 self.duplicate_fields.insert(key);
392 return;
393 }
394 _ => {}
395 },
396 _ => {
397 if self.fields.contains_key(key) {
398 self.duplicate_fields.insert(key);
399 }
400 }
401 }
402 self.fields.insert(key, val);
403 }
404
405 pub fn has_value(&self, key: &str, value: &FieldValue) -> bool {
408 self.fields.get(key).is_some_and(|held| held.values().any(|v| v == *value))
409 }
410
411 pub fn remove_value(&mut self, key: &str, value: &FieldValue) -> bool {
416 let Some(held) = self.fields.get_mut(key) else { return false };
417 let left: Vec<FieldValue> = held.values().filter(|v| *v != *value).map(|v| v.owned()).collect();
418 if left.len() == held.values().count() {
419 return false;
420 }
421 let (k, _) = self.fields.remove_entry(key).expect("just held");
422 if let Some(langs) = self.langs.as_mut() {
423 langs.retain(|(l, _)| *l != k);
424 }
425 match left.len() {
426 0 => {
427 self.duplicate_fields.remove(k);
428 }
429 1 => {
430 self.duplicate_fields.remove(k);
431 self.fields.insert(k, left.into_iter().next().expect("one"));
432 }
433 _ => {
434 for v in left {
435 self.add_field(k, v);
436 }
437 }
438 }
439 true
440 }
441
442 pub(crate) fn set_types(&mut self, types: &[&'static ClassDef]) {
445 let Some((&first, rest)) = types.split_first() else { return };
446 self.class = first;
447 self.also = (!rest.is_empty()).then(|| Box::new(rest.to_vec()));
448 }
449
450 pub fn merge_from(&mut self, other: &Element) {
453 self.described &= other.described;
454 for (k, v) in &other.fields {
455 match v {
456 FieldValue::ResourceList(new_list) => match self.fields.get_mut(k) {
457 Some(FieldValue::ResourceList(existing)) => existing.extend(new_list.iter().cloned()),
458 _ => {
459 self.fields.insert(*k, v.clone());
460 }
461 },
462 _ => {
463 self.fields.insert(*k, v.clone());
464 if let Some(l) = self.langs.as_mut() {
466 l.retain(|(key, _)| key != k);
467 }
468 for lang in other.langs(k) {
469 self.add_lang(k, lang);
470 }
471 }
472 }
473 }
474 }
475
476 pub fn to_json_value(&self) -> serde_json::Value {
480 let mut map = serde_json::Map::with_capacity(self.fields.len() + 2);
481 map.insert("id".to_string(), serde_json::Value::String(self.mrid.clone()));
482 for (k, v) in &self.fields {
483 map.insert(k.to_string(), field_to_json(v));
484 }
485 if let Some(langs) = &self.langs {
486 let mut tags = serde_json::Map::new();
487 for (key, lang) in langs.iter() {
488 if let serde_json::Value::Array(list) =
489 tags.entry(key.to_string()).or_insert_with(|| serde_json::Value::Array(Vec::new()))
490 {
491 list.push(serde_json::Value::String(lang.to_string()));
492 }
493 }
494 map.insert(LANG_KEY.to_string(), serde_json::Value::Object(tags));
495 }
496 serde_json::Value::Object(map)
497 }
498
499 pub fn from_json(
503 class: &'static ClassDef,
504 reg: &TypeRegistry,
505 value: &serde_json::Value,
506 ) -> Result<Self, String> {
507 let obj = value.as_object().ok_or("element is not a JSON object")?;
508 let mrid = obj.get("id").and_then(|v| v.as_str()).ok_or("element has no \"id\"")?.to_string();
509 let mut fields = FieldMap::default();
510 for (k, v) in obj {
511 if k == "id" || k == "_type" || k == LANG_KEY {
512 continue;
513 }
514 let is_ref = reg.attr(class, k).is_some_and(|a| a.kind != AttrKind::Literal);
515 let value = match v {
516 serde_json::Value::String(s) if is_ref => FieldValue::Resource(s.clone()),
517 serde_json::Value::String(s) => FieldValue::Text(s.clone()),
518 serde_json::Value::Array(items) => {
519 let items: Vec<String> = items
520 .iter()
521 .map(|i| i.as_str().map(str::to_string).ok_or(format!("{k}: list item is not a string")))
522 .collect::<Result<_, _>>()?;
523 if is_ref { FieldValue::ResourceList(items) } else { FieldValue::TextList(items) }
524 }
525 other => return Err(format!("{k}: expected a string or an array, got {other}")),
526 };
527 fields.insert(reg.field_key(class, k), value);
528 }
529 let mut element = Self::with_fields(class, mrid, fields);
530 if let Some(tags) = obj.get(LANG_KEY).and_then(|t| t.as_object()) {
531 for (k, list) in tags {
532 let key = reg.field_key(class, k);
533 for lang in list.as_array().into_iter().flatten().filter_map(|l| l.as_str()) {
534 element.add_lang(key, lang);
535 }
536 }
537 }
538 Ok(element)
539 }
540}
541
542pub const LANG_KEY: &str = "_lang";
544
545fn field_to_json(v: &FieldValue) -> serde_json::Value {
546 match v {
547 FieldValue::Text(s) | FieldValue::Resource(s) => serde_json::Value::String(s.clone()),
548 FieldValue::TextList(v) | FieldValue::ResourceList(v) => {
549 serde_json::Value::Array(v.iter().cloned().map(serde_json::Value::String).collect())
550 }
551 }
552}
553
554#[derive(Debug, Clone, Copy, PartialEq, Eq)]
558pub enum AttrKind {
559 Literal,
561 Association,
563 Enum,
565}
566
567#[derive(Debug)]
569pub struct AttrDef {
570 pub id: &'static str,
572 pub ns: &'static str,
574 pub kind: AttrKind,
575 pub range: &'static str,
578 pub is_list: bool,
579 pub used: bool,
583 pub xsd: &'static str,
586 pub value_ns: &'static str,
589 pub origins: &'static [&'static str],
591 pub comment: &'static str,
594}
595
596#[derive(Debug)]
600pub struct Schema {
601 pub classes: &'static [ClassDef],
602 pub profiles: &'static [(&'static str, &'static str)],
605 pub namespaces: &'static [(&'static str, &'static str)],
607 pub enums: &'static [EnumDef],
609}
610
611impl Schema {
612 pub fn enumeration(&self, name: &str) -> Option<&'static EnumDef> {
614 let enums: &'static [EnumDef] = self.enums;
615 enums.binary_search_by_key(&name, |e| e.local).ok().map(|i| &enums[i])
616 }
617
618 pub fn enum_value(&self, id: &str) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
621 let e = self.enumeration(id.split_once('.')?.0)?;
622 Some((e, e.values.iter().find(|v| v.id == id)?))
623 }
624}
625
626#[derive(Debug)]
628pub struct EnumDef {
629 pub ns: &'static str,
630 pub local: &'static str,
631 pub comment: &'static str,
633 pub values: &'static [EnumValueDef],
635}
636
637#[derive(Debug)]
639pub struct EnumValueDef {
640 pub id: &'static str,
642 pub comment: &'static str,
644}
645
646#[derive(Debug)]
648pub struct ClassDef {
649 pub ns: &'static str,
650 pub local: &'static str,
651 pub qualified: &'static str,
653 pub super_class: Option<usize>,
655 pub concrete: bool,
656 pub attrs: &'static [AttrDef],
660 pub origins: &'static [&'static str],
661 pub comment: &'static str,
664}
665
666impl ClassDef {
667 pub fn attr(&self, id: &str) -> Option<&'static AttrDef> {
669 self.attrs.iter().find(|a| a.id == id)
670 }
671}
672
673#[derive(Default)]
681pub struct TypeRegistry {
682 by_ns: FastMap<&'static str, FastMap<&'static str, &'static ClassDef>>,
683 bare: FastMap<&'static str, &'static ClassDef>,
684 by_type_name: FastMap<&'static str, &'static ClassDef>,
685 declared: FastMap<&'static str, FastMap<&'static str, &'static AttrDef>>,
688 chain: FastMap<&'static str, Vec<&'static ClassDef>>,
690 families: Vec<FamilyTable>,
692}
693
694struct FamilyTable {
697 id: &'static str,
698 prefix: &'static str,
699 schema: &'static Schema,
700 attrs: FastMap<&'static str, &'static AttrDef>,
703}
704
705impl TypeRegistry {
706 pub fn new() -> Self {
707 Self::default()
708 }
709
710 pub fn add_family(&mut self, id: &'static str, schema: &'static Schema, bare_fallback: bool) {
714 let classes = schema.classes;
715 let prefix = classes
716 .first()
717 .and_then(|c| c.qualified.strip_suffix(c.local))
718 .unwrap_or("");
719 let mut by_id = FastMap::default();
720 for class in classes {
721 for a in class.attrs {
722 by_id.entry(a.id).or_insert(a);
723 }
724 }
725 self.families.push(FamilyTable { id, prefix, schema, attrs: by_id });
726 for class in classes {
727 self.by_ns.entry(class.ns).or_default().insert(class.local, class);
728 self.by_type_name.insert(class.qualified, class);
729 if bare_fallback {
730 self.bare.insert(class.local, class);
731 }
732 let mut attrs = FastMap::default();
733 let mut chain = Vec::new();
734 let mut next = Some(class);
735 while let Some(c) = next {
736 for a in c.attrs {
737 attrs.entry(a.id).or_insert(a);
738 }
739 chain.push(c);
740 next = c.super_class.map(|i| &classes[i]);
741 }
742 chain.reverse();
743 self.declared.insert(class.qualified, attrs);
744 self.chain.insert(class.qualified, chain);
745 }
746 }
747
748 pub fn ns_table(&self, ns: &str) -> Option<&FastMap<&'static str, &'static ClassDef>> {
750 self.by_ns.get(ns)
751 }
752
753 pub fn bare(&self) -> &FastMap<&'static str, &'static ClassDef> {
754 &self.bare
755 }
756
757 pub fn by_type_name(&self, name: &str) -> Option<&'static ClassDef> {
758 self.by_type_name.get(name).copied()
759 }
760
761 pub fn attr(&self, class: &ClassDef, id: &str) -> Option<&'static AttrDef> {
763 self.declared.get(class.qualified)?.get(id).copied()
764 }
765
766 pub fn declared(&self, class: &ClassDef) -> Option<&FastMap<&'static str, &'static AttrDef>> {
769 self.declared.get(class.qualified)
770 }
771
772 pub fn field_key(&self, class: &ClassDef, id: &str) -> &'static str {
774 self.attr(class, id).map_or_else(|| intern(id), |a| a.id)
775 }
776
777 pub fn chain(&self, class: &ClassDef) -> &[&'static ClassDef] {
779 self.chain.get(class.qualified).map_or(&[], Vec::as_slice)
780 }
781
782 pub fn concrete_descendants(&self, qualified: &str) -> Vec<&'static str> {
785 let mut out: Vec<&'static str> = self
786 .chain
787 .iter()
788 .filter(|(_, chain)| chain.iter().any(|c| c.qualified == qualified))
789 .filter_map(|(q, _)| self.by_type_name.get(q).filter(|c| c.concrete).map(|c| c.qualified))
790 .collect();
791 out.sort_unstable();
792 out
793 }
794
795 pub fn attrs(&self, class: &ClassDef) -> impl Iterator<Item = &'static AttrDef> + '_ {
797 self.declared.get(class.qualified).into_iter().flat_map(|m| m.values().copied())
798 }
799
800 pub fn schema(&self, family: &str) -> Option<&'static Schema> {
802 self.family(family).map(|f| f.schema)
803 }
804
805 fn family(&self, id: &str) -> Option<&FamilyTable> {
806 self.families.iter().find(|f| f.id == id)
807 }
808
809 pub fn enum_value(&self, class: &ClassDef, id: &str) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
812 self.schema(self.family_of(class.qualified)?)?.enum_value(id)
813 }
814
815 pub fn family_of(&self, type_name: &str) -> Option<&'static str> {
817 self.families
819 .iter()
820 .filter(|f| type_name.starts_with(f.prefix))
821 .max_by_key(|f| f.prefix.len())
822 .map(|f| f.id)
823 }
824
825 pub fn family_attr(&self, family: &str, id: &str) -> Option<&'static AttrDef> {
828 self.family(family)?.attrs.get(id).copied()
829 }
830
831 pub fn attr_of(&self, class: &ClassDef, key: &str) -> Option<&'static AttrDef> {
834 self.attr(class, key)
835 .or_else(|| self.family_attr(self.family_of(class.qualified)?, key))
836 }
837}