oa_gateway_uci/schema.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
//! In-memory model of a UCI schema. Enough for the OMS JSON rules; not a full
//! XSD processor.
//!
//! Build one by hand with the builder methods below, or compile the published
//! XSD into one with [`crate::xsd::compile`].
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap};
use regex::Regex;
use crate::primitive;
/// How many links of a named-simple-type chain [`Schema::primitive`] will follow
/// before giving up. The published schema nests three deep at most; the limit
/// exists so a cyclic hand-built schema cannot hang the caller.
const MAX_SIMPLE_DEPTH: usize = 16;
/// Enough of a UCI schema to convert and validate OMS JSON.
///
/// Not a full XSD infoset. Build one with the methods below, or compile
/// the published catalog with [`crate::xsd::compile`].
#[derive(Debug, Clone)]
pub struct Schema {
pub global_elements: HashMap<String, GlobalElement>,
pub complex_types: HashMap<String, ComplexType>,
/// Named simple types: what each one restricts, and how. The target is
/// usually an `xs:` primitive but may be another named simple type, so read
/// it through [`Schema::primitive`] rather than directly, and read the
/// constraints through [`Schema::effective_facets`].
pub simple_types: HashMap<String, SimpleType>,
}
/// A pattern facet: what the XSD wrote, and the matcher it translates to.
///
/// Constructing one never fails. A pattern this build cannot express is held
/// unchecked and reported by [`Schema::unchecked_patterns`], because refusing to
/// load a schema over one exotic pattern would stop a gateway that otherwise
/// converts every message in the catalog.
#[derive(Debug, Clone)]
pub struct Pattern {
source: String,
matcher: Option<Regex>,
}
impl Pattern {
/// Compiles `source` as an XSD pattern. An untranslatable pattern
/// is kept and reported by [`Schema::unchecked_patterns`] rather
/// than failing the load.
#[must_use]
pub fn new(source: impl Into<String>) -> Self {
let source = source.into();
let matcher = Regex::new(&translate(&source)).ok();
Self { source, matcher }
}
/// The pattern as the XSD wrote it.
#[must_use]
pub fn source(&self) -> &str {
&self.source
}
/// Whether this pattern can say no to anything.
#[must_use]
pub fn is_checked(&self) -> bool {
self.matcher.is_some()
}
/// Whether `value` satisfies the pattern. An unchecked pattern accepts
/// everything: it has no opinion to offer, and guessing one would invent
/// violations rather than find them.
#[must_use]
pub fn accepts(&self, value: &str) -> bool {
self.matcher
.as_ref()
.is_none_or(|matcher| matcher.is_match(value))
}
}
/// Rewrite an XSD pattern as an equivalent Rust regex.
///
/// Two differences matter. An XSD pattern has to match the value entire, so the
/// result is anchored. And XSD's regex grammar has no anchors at all, which
/// makes `^` and `$` ordinary characters there and metacharacters here, so they
/// are escaped. Everything the published catalog uses beyond that — classes,
/// bounded repetition, alternation, `\d` and its relatives — means the same in
/// both languages.
///
/// What is left untranslated is XSD's character-class subtraction, `[a-z-[aeiou]]`,
/// and its `\i` and `\c` shorthands for XML name characters. None appears in the
/// published catalog. One that did would fail to compile and be reported as
/// unchecked rather than quietly matching everything.
fn translate(xsd: &str) -> String {
let mut out = String::with_capacity(xsd.len() + 8);
out.push_str("\\A(?:");
let mut chars = xsd.chars();
let mut in_class = false;
while let Some(c) = chars.next() {
match c {
'\\' => {
out.push(c);
if let Some(escaped) = chars.next() {
out.push(escaped);
}
}
'[' if !in_class => {
in_class = true;
out.push(c);
}
']' if in_class => {
in_class = false;
out.push(c);
}
// Literal in XSD, an anchor here. Inside a class both languages
// agree, and escaping there is harmless.
'^' | '$' => {
if c == '^' && in_class && out.ends_with('[') {
out.push(c); // Class negation, which does mean the same.
} else {
out.push('\\');
out.push(c);
}
}
_ => out.push(c),
}
}
out.push_str(")\\z");
out
}
/// A named simple type: the type it restricts, and the facets it adds.
#[derive(Debug, Clone)]
pub struct SimpleType {
pub base: String,
pub facets: Facets,
}
/// Constraints a simple type places on a value, as written.
///
/// Read [`Schema::effective_facets`] instead of a single type's facets: a
/// restriction chain spreads them over several links.
#[derive(Debug, Clone, Default)]
pub struct Facets {
/// Permitted values. Empty means unconstrained rather than "nothing allowed".
pub enumeration: Vec<String>,
/// Patterns declared here, which XSD reads as alternatives: a value matching
/// any one of them satisfies this link.
pub patterns: Vec<Pattern>,
pub length: Option<usize>,
pub min_length: Option<usize>,
pub max_length: Option<usize>,
/// Numeric bounds, held as `f64`. Every bound in the published catalog is
/// small enough to be exact; a bound past 2^53 on an `xs:long` would not be,
/// and is worth revisiting if a program's message set carries one.
pub min_inclusive: Option<f64>,
pub max_inclusive: Option<f64>,
pub min_exclusive: Option<f64>,
pub max_exclusive: Option<f64>,
}
/// The facets in force for a type, gathered along its restriction chain.
///
/// A derived type's own enumeration is the operative one, since XSD requires it
/// to be a subset of its base's. Patterns are grouped by link, because XSD reads
/// several patterns in one restriction as alternatives while patterns in
/// different restrictions all have to hold — six types in the published catalog
/// declare up to eight alternatives at once, and treating those as a conjunction
/// would reject every value they were written to accept. For a length or a
/// bound, the tightest wins.
#[derive(Debug, Default)]
pub struct Effective<'a> {
pub enumeration: Option<&'a [String]>,
/// One entry per link in the chain that declares patterns. A value has to
/// satisfy every entry, and satisfies an entry by matching any pattern in it.
pub patterns: Vec<&'a [Pattern]>,
pub length: Option<usize>,
pub min_length: Option<usize>,
pub max_length: Option<usize>,
pub min_inclusive: Option<f64>,
pub max_inclusive: Option<f64>,
pub min_exclusive: Option<f64>,
pub max_exclusive: Option<f64>,
}
impl Effective<'_> {
/// Whether anything here can be violated.
#[must_use]
pub fn is_empty(&self) -> bool {
self.enumeration.is_none()
&& self.patterns.is_empty()
&& self.length.is_none()
&& self.min_length.is_none()
&& self.max_length.is_none()
&& self.min_inclusive.is_none()
&& self.max_inclusive.is_none()
&& self.min_exclusive.is_none()
&& self.max_exclusive.is_none()
}
}
/// A top-level element and the type it is declared as.
#[derive(Debug, Clone)]
pub struct GlobalElement {
pub type_name: String,
}
/// A named complex type: whether it is abstract, and how it is built.
#[derive(Debug, Clone)]
pub struct ComplexType {
pub name: String,
pub abstract_: bool,
pub content: ComplexContent,
}
#[derive(Debug, Clone)]
pub enum ComplexContent {
/// The compositors declared directly on the type. A type with no content
/// model has none.
Groups(Vec<Group>),
Extension {
base: String,
extra: Vec<Group>,
},
}
/// A run of element declarations under one compositor.
///
/// Kept apart from the flat list of declarations because the compositor is the
/// difference between siblings and alternatives, and only one of those can be
/// checked by counting.
#[derive(Debug, Clone)]
pub struct Group {
pub kind: GroupKind,
pub elements: Vec<Element>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GroupKind {
/// Members stand on their own, each governed by its own occurrence range.
Sequence,
/// Members are alternatives to one another.
Choice,
}
/// One element declaration: name, type, and occurrence range.
#[derive(Debug, Clone)]
pub struct Element {
pub name: String,
pub type_name: String,
pub min_occurs: u32,
pub max_occurs: MaxOccurs,
}
/// Upper bound of an element declaration. [`Self::is_array`] is what
/// conversion uses to decide a JSON array.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MaxOccurs {
Bounded(u32),
Unbounded,
}
impl MaxOccurs {
/// Whether JSON should carry this field as an array (`maxOccurs`
/// greater than one, or unbounded).
#[must_use]
pub fn is_array(self) -> bool {
match self {
Self::Unbounded => true,
Self::Bounded(n) => n > 1,
}
}
}
impl Schema {
/// An empty schema. Add types with the builder methods, or use
/// [`crate::xsd::compile`].
#[must_use]
pub fn new() -> Self {
Self {
global_elements: HashMap::new(),
complex_types: HashMap::new(),
simple_types: HashMap::new(),
}
}
/// Registers a global element named `name` of type `type_name`.
pub fn element(&mut self, name: impl Into<String>, type_name: impl Into<String>) -> &mut Self {
self.global_elements.insert(
name.into(),
GlobalElement {
type_name: type_name.into(),
},
);
self
}
/// Declare a named simple type that restricts `base` without narrowing it.
pub fn simple(&mut self, name: impl Into<String>, base: impl Into<String>) -> &mut Self {
self.simple_with(name, base, Facets::default())
}
/// Declare a named simple type that restricts `base` with `facets`.
pub fn simple_with(
&mut self,
name: impl Into<String>,
base: impl Into<String>,
facets: Facets,
) -> &mut Self {
self.simple_types.insert(
name.into(),
SimpleType {
base: base.into(),
facets,
},
);
self
}
/// Declares a concrete type whose content is one sequence of
/// `elements`.
pub fn complex(&mut self, name: impl Into<String>, elements: Vec<Element>) -> &mut Self {
self.complex_groups(name, vec![sequence(elements)])
}
/// Declare a type from explicit compositors, for a choice or a mix of both.
pub fn complex_groups(&mut self, name: impl Into<String>, groups: Vec<Group>) -> &mut Self {
let name = name.into();
self.complex_types.insert(
name.clone(),
ComplexType {
name,
abstract_: false,
content: ComplexContent::Groups(groups),
},
);
self
}
/// Declares an abstract type. Instantiating it without `$type` /
/// `xsi:type` is a validation error.
pub fn complex_abstract(
&mut self,
name: impl Into<String>,
elements: Vec<Element>,
) -> &mut Self {
let name = name.into();
self.complex_types.insert(
name.clone(),
ComplexType {
name,
abstract_: true,
content: ComplexContent::Groups(vec![sequence(elements)]),
},
);
self
}
/// Declares `name` as an extension of `base` with `extra` fields.
pub fn extend(
&mut self,
name: impl Into<String>,
base: impl Into<String>,
extra: Vec<Element>,
) -> &mut Self {
let name = name.into();
self.complex_types.insert(
name.clone(),
ComplexType {
name,
abstract_: false,
content: ComplexContent::Extension {
base: base.into(),
extra: vec![sequence(extra)],
},
},
);
self
}
/// Declared type of the global element `element`, if any.
#[must_use]
pub fn global_type(&self, element: &str) -> Option<&str> {
self.global_elements
.get(element)
.map(|g| g.type_name.as_str())
}
/// Every element declaration a type contributes, base types included.
///
/// Errors on a cyclic extension chain rather than following it. Nothing in
/// the published schema is cyclic, but a schema is an input like any other:
/// it can come from a program-specific Message Set, and a chain that closes
/// on itself would otherwise recurse until the stack ran out, at startup or
/// on the first message that touched the type.
///
/// # Errors
///
/// Returns [`crate::UciError::Xsd`] on a cycle, or
/// [`crate::UciError::UnknownType`] if `type_name` is not a complex
/// type.
pub fn flatten<'a>(&'a self, type_name: &str) -> Result<Vec<&'a Element>, super::UciError> {
Ok(self
.groups(type_name)?
.into_iter()
.flat_map(|g| g.elements.iter())
.collect())
}
/// The compositors a type is built from, base types first.
///
/// [`Self::flatten`] answers which elements may appear; this also answers
/// under what compositor, which is what tells a set of optional siblings
/// apart from a set of alternatives.
///
/// # Errors
///
/// Same as [`Self::flatten`].
pub fn groups<'a>(&'a self, type_name: &str) -> Result<Vec<&'a Group>, super::UciError> {
self.groups_chain(type_name, &mut Vec::new())
}
/// Walks an extension chain, pushing names onto `chain` so a cycle
/// can be named rather than followed.
fn groups_chain<'a>(
&'a self,
type_name: &str,
chain: &mut Vec<String>,
) -> Result<Vec<&'a Group>, super::UciError> {
if chain.iter().any(|seen| seen == type_name) {
chain.push(type_name.to_owned());
return Err(super::UciError::Xsd(format!(
"cyclic extension chain: {}",
chain.join(" -> ")
)));
}
let ct = self
.complex_types
.get(type_name)
.ok_or_else(|| super::UciError::UnknownType(type_name.to_owned()))?;
match &ct.content {
ComplexContent::Groups(groups) => Ok(groups.iter().collect()),
ComplexContent::Extension { base, extra } => {
chain.push(type_name.to_owned());
let mut out = self.groups_chain(base, chain)?;
chain.pop();
out.extend(extra.iter());
Ok(out)
}
}
}
/// Whether `type_name` is a named complex type in this schema.
#[must_use]
pub fn is_complex(&self, type_name: &str) -> bool {
self.complex_types.contains_key(type_name)
}
/// Whether `type_name` holds a scalar value rather than child elements.
///
/// Covers both `xs:` primitives and the schema's own named simple types —
/// the published catalog defines over nine hundred of the latter, so a
/// prefix test alone would misread them as complex.
#[must_use]
pub fn is_simple(&self, type_name: &str) -> bool {
type_name.starts_with("xs:") || self.simple_types.contains_key(type_name)
}
/// Reduce `type_name` to the `xs:` primitive it ultimately restricts.
///
/// Leaf coercion matches on primitive names to decide whether a value is a
/// JSON number, boolean, or string, so every named simple type has to be
/// resolved through its restriction chain first. Returns `type_name`
/// unchanged when it is already a primitive or is not a known simple type.
#[must_use]
pub fn primitive<'a>(&'a self, type_name: &'a str) -> &'a str {
let mut current = type_name;
for _ in 0..MAX_SIMPLE_DEPTH {
if current.starts_with("xs:") {
return current;
}
match self.simple_types.get(current) {
Some(simple) => current = simple.base.as_str(),
None => return current,
}
}
current
}
/// Every constraint a value of `type_name` has to satisfy.
///
/// Walks the restriction chain, so a type that narrows another inherits what
/// the other already required. An `xs:` primitive, or a type the schema does
/// not define, constrains nothing.
#[must_use]
pub fn effective_facets<'a>(&'a self, type_name: &str) -> Effective<'a> {
let mut out = Effective::default();
let mut current = type_name;
for _ in 0..MAX_SIMPLE_DEPTH {
let Some(simple) = self.simple_types.get(current) else {
break;
};
let facets = &simple.facets;
if out.enumeration.is_none() && !facets.enumeration.is_empty() {
out.enumeration = Some(&facets.enumeration);
}
if !facets.patterns.is_empty() {
out.patterns.push(&facets.patterns);
}
out.length = out.length.or(facets.length);
out.min_length = stricter(out.min_length, facets.min_length, Ordering::Greater);
out.max_length = stricter(out.max_length, facets.max_length, Ordering::Less);
out.min_inclusive = stricter_f64(out.min_inclusive, facets.min_inclusive, f64::max);
out.max_inclusive = stricter_f64(out.max_inclusive, facets.max_inclusive, f64::min);
out.min_exclusive = stricter_f64(out.min_exclusive, facets.min_exclusive, f64::max);
out.max_exclusive = stricter_f64(out.max_exclusive, facets.max_exclusive, f64::min);
current = simple.base.as_str();
}
out
}
/// Every primitive in use that this build has no check for.
///
/// `xs:string` is left out: there is nothing to check about a string beyond
/// the facets of the type declaring it. What appears here is a type whose
/// values pass unexamined — `xs:base64Binary`, `xs:anyURI`, `xs:QName` —
/// which is worth knowing when loading a schema this project has not seen.
#[must_use]
pub fn unchecked_primitives(&self) -> Vec<&str> {
let mut found: BTreeSet<&str> = BTreeSet::new();
for name in self.simple_types.keys() {
found.insert(self.primitive(name));
}
for name in self.complex_types.keys() {
// A type whose chain does not resolve is the compiler's complaint,
// not this one's.
if let Ok(groups) = self.groups(name) {
for element in groups.iter().flat_map(|group| &group.elements) {
found.insert(self.primitive(&element.type_name));
}
}
}
found
.into_iter()
.filter(|name| {
name.starts_with("xs:") && *name != "xs:string" && !primitive::is_checked(name)
})
.collect()
}
/// Every pattern this build cannot check, paired with the type declaring it.
///
/// Empty for the published catalog. A program whose own schema uses a corner
/// of XSD's regex language that does not translate would see it here, which
/// is the moment to know a constraint is going unread.
#[must_use]
pub fn unchecked_patterns(&self) -> Vec<(&str, &str)> {
let mut out: Vec<_> = self
.simple_types
.iter()
.flat_map(|(name, simple)| {
simple
.facets
.patterns
.iter()
.filter(|pattern| !pattern.is_checked())
.map(move |pattern| (name.as_str(), pattern.source()))
})
.collect();
out.sort_unstable();
out
}
}
/// Keep whichever bound is harder to satisfy.
fn stricter<T: Ord>(a: Option<T>, b: Option<T>, keep: Ordering) -> Option<T> {
match (a, b) {
(Some(a), Some(b)) => Some(if a.cmp(&b) == keep { a } else { b }),
(some, None) | (None, some) => some,
}
}
fn stricter_f64(a: Option<f64>, b: Option<f64>, keep: fn(f64, f64) -> f64) -> Option<f64> {
match (a, b) {
(Some(a), Some(b)) => Some(keep(a, b)),
(some, None) | (None, some) => some,
}
}
impl Default for Schema {
/// Same as [`Self::new`].
fn default() -> Self {
Self::new()
}
}
/// One compositor whose members stand on their own.
#[must_use]
pub fn sequence(elements: Vec<Element>) -> Group {
Group {
kind: GroupKind::Sequence,
elements,
}
}
/// One compositor whose members are alternatives.
#[must_use]
pub fn choice(elements: Vec<Element>) -> Group {
Group {
kind: GroupKind::Choice,
elements,
}
}
/// Required once (`minOccurs=1`, `maxOccurs=1`).
#[must_use]
pub fn el(name: &str, type_name: &str) -> Element {
Element {
name: name.into(),
type_name: type_name.into(),
min_occurs: 1,
max_occurs: MaxOccurs::Bounded(1),
}
}
/// Optional once (`minOccurs=0`, `maxOccurs=1`).
#[must_use]
pub fn el_opt(name: &str, type_name: &str) -> Element {
Element {
name: name.into(),
type_name: type_name.into(),
min_occurs: 0,
max_occurs: MaxOccurs::Bounded(1),
}
}
/// Zero or more (`minOccurs=0`, `maxOccurs` unbounded).
#[must_use]
pub fn el_many(name: &str, type_name: &str) -> Element {
Element {
name: name.into(),
type_name: type_name.into(),
min_occurs: 0,
max_occurs: MaxOccurs::Unbounded,
}
}