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
178 .iter()
179 .map(|t| Value::Text(t))
180 .chain(refs.iter().map(|r| Value::Resource(r)))
181 }
182}
183
184#[derive(Debug, Clone)]
194pub struct Element {
195 class: &'static ClassDef,
196 mrid: String,
197 fields: FieldMap,
198 duplicate_fields: FastSet<&'static str>,
201 langs: Option<Box<Langs>>,
205 also: Option<Box<Types>>,
211 described: bool,
215}
216
217type Langs = Vec<(&'static str, Box<str>)>;
219
220type Types = Vec<&'static ClassDef>;
222
223impl Element {
224 pub fn new(class: &'static ClassDef, mrid: String) -> Self {
225 Self {
226 class,
227 mrid,
228 fields: FieldMap::default(),
229 duplicate_fields: FastSet::default(),
230 langs: None,
231 also: None,
232 described: false,
233 }
234 }
235
236 pub fn with_fields(class: &'static ClassDef, mrid: String, fields: FieldMap) -> Self {
237 Self {
238 class,
239 mrid,
240 fields,
241 duplicate_fields: FastSet::default(),
242 langs: None,
243 also: None,
244 described: false,
245 }
246 }
247
248 pub fn class(&self) -> &'static ClassDef {
249 self.class
250 }
251
252 pub fn types(&self) -> impl Iterator<Item = &'static ClassDef> + '_ {
255 std::iter::once(self.class).chain(self.also.iter().flat_map(|v| v.iter().copied()))
256 }
257
258 pub(crate) fn add_type(&mut self, other: &'static ClassDef, reg: &TypeRegistry) -> bool {
263 if self.types().any(|c| c.qualified == other.qualified) {
264 return false;
265 }
266 let promote = reg
267 .chain(other)
268 .iter()
269 .any(|c| c.qualified == self.class.qualified);
270 let kept = if promote {
271 std::mem::replace(&mut self.class, other)
272 } else {
273 other
274 };
275 self.also.get_or_insert_with(Default::default).push(kept);
276 promote
277 }
278
279 pub fn defined(&self) -> bool {
282 !self.described
283 }
284
285 pub fn mark_described(&mut self) {
287 self.described = true;
288 }
289
290 pub fn mrid(&self) -> &str {
291 &self.mrid
292 }
293
294 pub fn type_name(&self) -> &'static str {
297 self.class.qualified
298 }
299
300 pub fn local_name(&self) -> &'static str {
302 self.class.local
303 }
304
305 pub fn type_ns(&self) -> &'static str {
307 self.class.ns
308 }
309
310 pub fn fields(&self) -> &FieldMap {
311 &self.fields
312 }
313
314 pub fn duplicate_fields(&self) -> &FastSet<&'static str> {
315 &self.duplicate_fields
316 }
317
318 pub fn langs(&self, key: &str) -> impl Iterator<Item = &str> {
322 self.langs
323 .iter()
324 .flat_map(|l| l.iter())
325 .filter(move |(k, _)| *k == key)
326 .map(|(_, l)| &**l)
327 }
328
329 pub fn add_lang(&mut self, key: &'static str, lang: &str) {
331 self.langs
332 .get_or_insert_with(Default::default)
333 .push((key, lang.into()));
334 }
335
336 pub fn retype(&mut self, key: &str, reference: bool) {
339 if let Some(value) = self.fields.get_mut(key) {
340 *value = match (
341 std::mem::replace(value, FieldValue::Text(String::new())),
342 reference,
343 ) {
344 (FieldValue::Text(s), true) => FieldValue::Resource(s),
345 (FieldValue::TextList(v), true) => FieldValue::ResourceList(v),
346 (FieldValue::Resource(s), false) => FieldValue::Text(s),
347 (FieldValue::ResourceList(v), false) => FieldValue::TextList(v),
348 (other, _) => other,
349 };
350 }
351 }
352
353 pub fn get(&self, attr: &str) -> Option<&FieldValue> {
354 self.fields.get(attr)
355 }
356
357 pub fn get_str(&self, attr: &str) -> Option<&str> {
358 match self.fields.get(attr) {
359 Some(FieldValue::Text(s)) => Some(s.as_str()),
360 Some(FieldValue::TextList(v)) => v.first().map(String::as_str),
361 _ => None,
362 }
363 }
364
365 pub fn get_f64(&self, attr: &str) -> Option<f64> {
366 self.get_str(attr)?.parse().ok()
367 }
368
369 pub fn get_bool(&self, attr: &str) -> Option<bool> {
370 match self.get_str(attr)? {
371 "true" | "1" => Some(true),
372 "false" | "0" => Some(false),
373 _ => None,
374 }
375 }
376
377 pub fn get_refs(&self, attr: &str) -> &[String] {
383 match self.fields.get(attr) {
384 Some(FieldValue::Resource(s)) => std::slice::from_ref(s),
385 Some(FieldValue::ResourceList(v)) => v.as_slice(),
386 _ => &[],
387 }
388 }
389
390 pub fn get_ref(&self, attr: &str) -> Option<&str> {
392 self.get_refs(attr).first().map(String::as_str)
393 }
394
395 pub fn add_field(&mut self, key: &'static str, val: FieldValue) {
398 match &val {
399 FieldValue::Resource(new_ref) => match self.fields.get_mut(key) {
400 Some(FieldValue::ResourceList(list)) => {
401 list.push(new_ref.clone());
402 self.duplicate_fields.insert(key);
403 return;
404 }
405 Some(existing @ FieldValue::Resource(_)) => {
406 let FieldValue::Resource(old) =
407 std::mem::replace(existing, FieldValue::ResourceList(Vec::new()))
408 else {
409 unreachable!()
410 };
411 *existing = FieldValue::ResourceList(vec![old, new_ref.clone()]);
412 self.duplicate_fields.insert(key);
413 return;
414 }
415 _ => {}
416 },
417 FieldValue::Text(new_text) => match self.fields.get_mut(key) {
418 Some(FieldValue::TextList(list)) => {
419 list.push(new_text.clone());
420 self.duplicate_fields.insert(key);
421 return;
422 }
423 Some(existing @ FieldValue::Text(_)) => {
424 let FieldValue::Text(old) =
425 std::mem::replace(existing, FieldValue::TextList(Vec::new()))
426 else {
427 unreachable!()
428 };
429 *existing = FieldValue::TextList(vec![old, new_text.clone()]);
430 self.duplicate_fields.insert(key);
431 return;
432 }
433 _ => {}
434 },
435 _ => {
436 if self.fields.contains_key(key) {
437 self.duplicate_fields.insert(key);
438 }
439 }
440 }
441 self.fields.insert(key, val);
442 }
443
444 pub fn has_value(&self, key: &str, value: &FieldValue) -> bool {
447 self.fields
448 .get(key)
449 .is_some_and(|held| held.values().any(|v| v == *value))
450 }
451
452 pub fn remove_value(&mut self, key: &str, value: &FieldValue) -> bool {
457 let Some(held) = self.fields.get_mut(key) else {
458 return false;
459 };
460 let left: Vec<FieldValue> = held
461 .values()
462 .filter(|v| *v != *value)
463 .map(|v| v.owned())
464 .collect();
465 if left.len() == held.values().count() {
466 return false;
467 }
468 let (k, _) = self.fields.remove_entry(key).expect("just held");
469 if let Some(langs) = self.langs.as_mut() {
470 langs.retain(|(l, _)| *l != k);
471 }
472 match left.len() {
473 0 => {
474 self.duplicate_fields.remove(k);
475 }
476 1 => {
477 self.duplicate_fields.remove(k);
478 self.fields.insert(k, left.into_iter().next().expect("one"));
479 }
480 _ => {
481 for v in left {
482 self.add_field(k, v);
483 }
484 }
485 }
486 true
487 }
488
489 pub(crate) fn set_types(&mut self, types: &[&'static ClassDef]) {
492 let Some((&first, rest)) = types.split_first() else {
493 return;
494 };
495 self.class = first;
496 self.also = (!rest.is_empty()).then(|| Box::new(rest.to_vec()));
497 }
498
499 pub fn merge_from(&mut self, other: &Element) {
502 self.described &= other.described;
503 for (k, v) in &other.fields {
504 match v {
505 FieldValue::ResourceList(new_list) => match self.fields.get_mut(k) {
506 Some(FieldValue::ResourceList(existing)) => {
507 existing.extend(new_list.iter().cloned())
508 }
509 _ => {
510 self.fields.insert(*k, v.clone());
511 }
512 },
513 _ => {
514 self.fields.insert(*k, v.clone());
515 if let Some(l) = self.langs.as_mut() {
517 l.retain(|(key, _)| key != k);
518 }
519 for lang in other.langs(k) {
520 self.add_lang(k, lang);
521 }
522 }
523 }
524 }
525 }
526
527 pub fn to_json_value(&self) -> serde_json::Value {
531 let mut map = serde_json::Map::with_capacity(self.fields.len() + 2);
532 map.insert(
533 "id".to_string(),
534 serde_json::Value::String(self.mrid.clone()),
535 );
536 for (k, v) in &self.fields {
537 map.insert(k.to_string(), field_to_json(v));
538 }
539 if let Some(langs) = &self.langs {
540 let mut tags = serde_json::Map::new();
541 for (key, lang) in langs.iter() {
542 if let serde_json::Value::Array(list) = tags
543 .entry(key.to_string())
544 .or_insert_with(|| serde_json::Value::Array(Vec::new()))
545 {
546 list.push(serde_json::Value::String(lang.to_string()));
547 }
548 }
549 map.insert(LANG_KEY.to_string(), serde_json::Value::Object(tags));
550 }
551 serde_json::Value::Object(map)
552 }
553
554 pub fn from_json(
558 class: &'static ClassDef,
559 reg: &TypeRegistry,
560 value: &serde_json::Value,
561 ) -> Result<Self, String> {
562 let obj = value.as_object().ok_or("element is not a JSON object")?;
563 let mrid = obj
564 .get("id")
565 .and_then(|v| v.as_str())
566 .ok_or("element has no \"id\"")?
567 .to_string();
568 let mut fields = FieldMap::default();
569 for (k, v) in obj {
570 if k == "id" || k == "_type" || k == LANG_KEY {
571 continue;
572 }
573 let is_ref = reg
574 .attr(class, k)
575 .is_some_and(|a| a.kind != AttrKind::Literal);
576 let value = match v {
577 serde_json::Value::String(s) if is_ref => FieldValue::Resource(s.clone()),
578 serde_json::Value::String(s) => FieldValue::Text(s.clone()),
579 serde_json::Value::Array(items) => {
580 let items: Vec<String> = items
581 .iter()
582 .map(|i| {
583 i.as_str()
584 .map(str::to_string)
585 .ok_or(format!("{k}: list item is not a string"))
586 })
587 .collect::<Result<_, _>>()?;
588 if is_ref {
589 FieldValue::ResourceList(items)
590 } else {
591 FieldValue::TextList(items)
592 }
593 }
594 other => return Err(format!("{k}: expected a string or an array, got {other}")),
595 };
596 fields.insert(reg.field_key(class, k), value);
597 }
598 let mut element = Self::with_fields(class, mrid, fields);
599 if let Some(tags) = obj.get(LANG_KEY).and_then(|t| t.as_object()) {
600 for (k, list) in tags {
601 let key = reg.field_key(class, k);
602 for lang in list
603 .as_array()
604 .into_iter()
605 .flatten()
606 .filter_map(|l| l.as_str())
607 {
608 element.add_lang(key, lang);
609 }
610 }
611 }
612 Ok(element)
613 }
614}
615
616pub const LANG_KEY: &str = "_lang";
618
619fn field_to_json(v: &FieldValue) -> serde_json::Value {
620 match v {
621 FieldValue::Text(s) | FieldValue::Resource(s) => serde_json::Value::String(s.clone()),
622 FieldValue::TextList(v) | FieldValue::ResourceList(v) => {
623 serde_json::Value::Array(v.iter().cloned().map(serde_json::Value::String).collect())
624 }
625 }
626}
627
628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
632pub enum AttrKind {
633 Literal,
635 Association,
637 Enum,
639}
640
641#[derive(Debug)]
643pub struct AttrDef {
644 pub id: &'static str,
646 pub ns: &'static str,
648 pub kind: AttrKind,
649 pub range: &'static str,
652 pub is_list: bool,
653 pub used: bool,
657 pub xsd: &'static str,
660 pub value_ns: &'static str,
663 pub origins: &'static [&'static str],
665 pub comment: &'static str,
668}
669
670#[derive(Debug)]
674pub struct Schema {
675 pub classes: &'static [ClassDef],
676 pub profiles: &'static [(&'static str, &'static str)],
679 pub namespaces: &'static [(&'static str, &'static str)],
681 pub enums: &'static [EnumDef],
683}
684
685impl Schema {
686 pub fn enumeration(&self, name: &str) -> Option<&'static EnumDef> {
688 let enums: &'static [EnumDef] = self.enums;
689 enums
690 .binary_search_by_key(&name, |e| e.local)
691 .ok()
692 .map(|i| &enums[i])
693 }
694
695 pub fn enum_value(&self, id: &str) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
698 let e = self.enumeration(id.split_once('.')?.0)?;
699 Some((e, e.values.iter().find(|v| v.id == id)?))
700 }
701}
702
703#[derive(Debug)]
705pub struct EnumDef {
706 pub ns: &'static str,
707 pub local: &'static str,
708 pub comment: &'static str,
710 pub values: &'static [EnumValueDef],
712}
713
714#[derive(Debug)]
716pub struct EnumValueDef {
717 pub id: &'static str,
719 pub comment: &'static str,
721}
722
723#[derive(Debug)]
725pub struct ClassDef {
726 pub ns: &'static str,
727 pub local: &'static str,
728 pub qualified: &'static str,
730 pub super_class: Option<usize>,
732 pub concrete: bool,
733 pub attrs: &'static [AttrDef],
737 pub origins: &'static [&'static str],
738 pub comment: &'static str,
741}
742
743impl ClassDef {
744 pub fn attr(&self, id: &str) -> Option<&'static AttrDef> {
746 self.attrs.iter().find(|a| a.id == id)
747 }
748}
749
750#[derive(Default)]
758pub struct TypeRegistry {
759 by_ns: FastMap<&'static str, FastMap<&'static str, &'static ClassDef>>,
760 bare: FastMap<&'static str, &'static ClassDef>,
761 by_type_name: FastMap<&'static str, &'static ClassDef>,
762 declared: FastMap<&'static str, FastMap<&'static str, &'static AttrDef>>,
765 chain: FastMap<&'static str, Vec<&'static ClassDef>>,
767 families: Vec<FamilyTable>,
769}
770
771struct FamilyTable {
774 id: &'static str,
775 prefix: &'static str,
776 schema: &'static Schema,
777 attrs: FastMap<&'static str, &'static AttrDef>,
780}
781
782impl TypeRegistry {
783 pub fn new() -> Self {
784 Self::default()
785 }
786
787 pub fn add_family(&mut self, id: &'static str, schema: &'static Schema, bare_fallback: bool) {
791 let classes = schema.classes;
792 let prefix = classes
793 .first()
794 .and_then(|c| c.qualified.strip_suffix(c.local))
795 .unwrap_or("");
796 let mut by_id = FastMap::default();
797 for class in classes {
798 for a in class.attrs {
799 by_id.entry(a.id).or_insert(a);
800 }
801 }
802 self.families.push(FamilyTable {
803 id,
804 prefix,
805 schema,
806 attrs: by_id,
807 });
808 for class in classes {
809 self.by_ns
810 .entry(class.ns)
811 .or_default()
812 .insert(class.local, class);
813 self.by_type_name.insert(class.qualified, class);
814 if bare_fallback {
815 self.bare.insert(class.local, class);
816 }
817 let mut attrs = FastMap::default();
818 let mut chain = Vec::new();
819 let mut next = Some(class);
820 while let Some(c) = next {
821 for a in c.attrs {
822 attrs.entry(a.id).or_insert(a);
823 }
824 chain.push(c);
825 next = c.super_class.map(|i| &classes[i]);
826 }
827 chain.reverse();
828 self.declared.insert(class.qualified, attrs);
829 self.chain.insert(class.qualified, chain);
830 }
831 }
832
833 pub fn ns_table(&self, ns: &str) -> Option<&FastMap<&'static str, &'static ClassDef>> {
835 self.by_ns.get(ns)
836 }
837
838 pub fn bare(&self) -> &FastMap<&'static str, &'static ClassDef> {
839 &self.bare
840 }
841
842 pub fn by_type_name(&self, name: &str) -> Option<&'static ClassDef> {
843 self.by_type_name.get(name).copied()
844 }
845
846 pub fn attr(&self, class: &ClassDef, id: &str) -> Option<&'static AttrDef> {
848 self.declared.get(class.qualified)?.get(id).copied()
849 }
850
851 pub fn declared(&self, class: &ClassDef) -> Option<&FastMap<&'static str, &'static AttrDef>> {
854 self.declared.get(class.qualified)
855 }
856
857 pub fn field_key(&self, class: &ClassDef, id: &str) -> &'static str {
859 self.attr(class, id).map_or_else(|| intern(id), |a| a.id)
860 }
861
862 pub fn chain(&self, class: &ClassDef) -> &[&'static ClassDef] {
864 self.chain.get(class.qualified).map_or(&[], Vec::as_slice)
865 }
866
867 pub fn concrete_descendants(&self, qualified: &str) -> Vec<&'static str> {
870 let mut out: Vec<&'static str> = self
871 .chain
872 .iter()
873 .filter(|(_, chain)| chain.iter().any(|c| c.qualified == qualified))
874 .filter_map(|(q, _)| {
875 self.by_type_name
876 .get(q)
877 .filter(|c| c.concrete)
878 .map(|c| c.qualified)
879 })
880 .collect();
881 out.sort_unstable();
882 out
883 }
884
885 pub fn attrs(&self, class: &ClassDef) -> impl Iterator<Item = &'static AttrDef> + '_ {
887 self.declared
888 .get(class.qualified)
889 .into_iter()
890 .flat_map(|m| m.values().copied())
891 }
892
893 pub fn schema(&self, family: &str) -> Option<&'static Schema> {
895 self.family(family).map(|f| f.schema)
896 }
897
898 fn family(&self, id: &str) -> Option<&FamilyTable> {
899 self.families.iter().find(|f| f.id == id)
900 }
901
902 pub fn enum_value(
905 &self,
906 class: &ClassDef,
907 id: &str,
908 ) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
909 self.schema(self.family_of(class.qualified)?)?
910 .enum_value(id)
911 }
912
913 pub fn family_of(&self, type_name: &str) -> Option<&'static str> {
915 self.families
917 .iter()
918 .filter(|f| type_name.starts_with(f.prefix))
919 .max_by_key(|f| f.prefix.len())
920 .map(|f| f.id)
921 }
922
923 pub fn family_attr(&self, family: &str, id: &str) -> Option<&'static AttrDef> {
926 self.family(family)?.attrs.get(id).copied()
927 }
928
929 pub fn attr_of(&self, class: &ClassDef, key: &str) -> Option<&'static AttrDef> {
932 self.attr(class, key)
933 .or_else(|| self.family_attr(self.family_of(class.qualified)?, key))
934 }
935}