use std::collections::HashMap;
use std::fmt;
use crate::path::Path;
use crate::tree::{Node, Value};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SchemaId(u32);
impl SchemaId {
const fn index(self) -> usize {
self.0 as usize
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct Types(u8);
impl Types {
pub const NULL: Self = Self(1);
pub const BOOLEAN: Self = Self(2);
pub const INTEGER: Self = Self(4);
pub const NUMBER: Self = Self(8);
pub const STRING: Self = Self(16);
pub const ARRAY: Self = Self(32);
pub const OBJECT: Self = Self(64);
const NAMES: [(Self, &'static str); 7] = [
(Self::OBJECT, "object"),
(Self::ARRAY, "array"),
(Self::STRING, "string"),
(Self::NUMBER, "number"),
(Self::INTEGER, "integer"),
(Self::BOOLEAN, "boolean"),
(Self::NULL, "null"),
];
fn from_name(name: &str) -> Option<Self> {
Self::NAMES
.iter()
.find(|(_, known)| *known == name)
.map(|(types, _)| *types)
}
#[must_use]
pub const fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
#[must_use]
pub const fn intersects(self, other: Self) -> bool {
self.0 & other.0 != 0
}
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[must_use]
pub fn of(node: &Node) -> Self {
match &node.value {
Value::Null => Self::NULL,
Value::Bool(_) => Self::BOOLEAN,
Value::Number(number) => {
if number.as_i128().is_some() {
Self::NUMBER.union(Self::INTEGER)
} else {
Self::NUMBER
}
}
Value::Text(_) => Self::STRING,
Value::List(_) => Self::ARRAY,
Value::Map(_) => Self::OBJECT,
}
}
#[must_use]
pub fn admits(self, node: &Node) -> bool {
match &node.value {
Value::Number(_) => self.contains(Self::NUMBER) || self.contains(Self::INTEGER),
_ => self.contains(Self::of(node)),
}
}
#[must_use]
pub fn names(self) -> Vec<&'static str> {
Self::NAMES
.iter()
.filter(|(types, _)| self.contains(*types))
.map(|(_, name)| *name)
.collect()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
Float,
Double,
Int8,
Int16,
Int32,
Int64,
Uint8,
Uint16,
Uint32,
Uint64,
UriReference,
}
impl Format {
fn from_name(name: &str) -> Option<Self> {
Some(match name {
"float" => Self::Float,
"double" => Self::Double,
"int8" => Self::Int8,
"int16" => Self::Int16,
"int32" => Self::Int32,
"int64" => Self::Int64,
"uint8" => Self::Uint8,
"uint16" => Self::Uint16,
"uint32" => Self::Uint32,
"uint64" => Self::Uint64,
"uri-reference" => Self::UriReference,
_ => return None,
})
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Float => "float",
Self::Double => "double",
Self::Int8 => "int8",
Self::Int16 => "int16",
Self::Int32 => "int32",
Self::Int64 => "int64",
Self::Uint8 => "uint8",
Self::Uint16 => "uint16",
Self::Uint32 => "uint32",
Self::Uint64 => "uint64",
Self::UriReference => "uri-reference",
}
}
#[must_use]
pub const fn integer_range(self) -> Option<(i128, i128)> {
Some(match self {
Self::Int8 => (i8::MIN as i128, i8::MAX as i128),
Self::Int16 => (i16::MIN as i128, i16::MAX as i128),
Self::Int32 => (i32::MIN as i128, i32::MAX as i128),
Self::Int64 => (i64::MIN as i128, i64::MAX as i128),
Self::Uint8 => (0, u8::MAX as i128),
Self::Uint16 => (0, u16::MAX as i128),
Self::Uint32 => (0, u32::MAX as i128),
Self::Uint64 => (0, u64::MAX as i128),
_ => return None,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Additional {
Allowed,
Denied,
Schema(SchemaId),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Definition {
pub topic: String,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Default)]
pub struct SchemaNode {
pub definition: Option<Definition>,
pub never: bool,
pub types: Option<Types>,
pub constant: Option<Node>,
pub choices: Option<Vec<Node>>,
pub properties: Vec<(String, SchemaId)>,
pub required: Vec<String>,
pub additional: Option<Additional>,
pub items: Option<Additional>,
pub prefix_items: Vec<SchemaId>,
pub min_items: Option<usize>,
pub max_items: Option<usize>,
pub max_properties: Option<usize>,
pub minimum: Option<f64>,
pub maximum: Option<f64>,
pub min_length: Option<usize>,
pub max_length: Option<usize>,
pub format: Option<Format>,
pub forms: Vec<SchemaId>,
pub tag: Option<String>,
pub partial_tag: Option<String>,
pub reference: Option<SchemaId>,
pub pattern: Option<String>,
pub not: Option<SchemaId>,
pub default: Option<Node>,
pub extensions: Vec<(String, Node)>,
}
impl SchemaNode {
#[must_use]
pub fn property(&self, name: &str) -> Option<SchemaId> {
self.properties
.iter()
.find(|(known, _)| known == name)
.map(|(_, id)| *id)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SchemaError {
pub path: Path,
pub message: String,
}
impl fmt::Display for SchemaError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}: {}", self.path, self.message)
}
}
impl std::error::Error for SchemaError {}
#[derive(Clone, Debug)]
pub struct Schema {
nodes: Vec<SchemaNode>,
root: SchemaId,
definitions: HashMap<String, SchemaId>,
}
#[derive(Clone, Copy, Debug)]
pub struct Import<'a> {
pub tree: &'a Node,
pub topic: &'a str,
}
struct Document<'a> {
tree: &'a Node,
topic: &'a str,
id: Option<&'a str>,
}
struct Compiler<'a> {
documents: Vec<Document<'a>>,
nodes: Vec<SchemaNode>,
definitions: HashMap<(usize, String), SchemaId>,
pending: Vec<(usize, String, SchemaId)>,
}
impl Schema {
pub fn compile(tree: &Node, topic: &str) -> Result<Self, SchemaError> {
Self::compile_with(tree, topic, &[])
}
pub fn compile_with(
tree: &Node,
topic: &str,
imports: &[Import<'_>],
) -> Result<Self, SchemaError> {
let documents = std::iter::once((tree, topic))
.chain(imports.iter().map(|import| (import.tree, import.topic)))
.map(|(tree, topic)| Document {
tree,
topic,
id: tree.get("$id").and_then(Node::as_str),
})
.collect();
let mut compiler = Compiler {
documents,
nodes: Vec::new(),
definitions: HashMap::new(),
pending: Vec::new(),
};
let path = Path::root("schema");
if let Some(definitions) = tree.get("$defs") {
let entries = definitions.as_map().ok_or_else(|| SchemaError {
path: path.key("$defs"),
message: "`$defs` is not an object".into(),
})?;
for entry in entries {
compiler.definition(0, &entry.key);
}
}
let root = compiler.reserve();
compiler.compile_into(0, tree, &path, root, true)?;
while let Some((document, name, id)) = compiler.pending.pop() {
let path = Path::root("schema").key("$defs").key(name.clone());
let body = compiler.documents[document]
.tree
.get("$defs")
.and_then(|definitions| definitions.get(&name))
.ok_or_else(|| SchemaError {
path: path.clone(),
message: format!("no definition {name}"),
})?;
compiler.compile_into(document, body, &path, id, false)?;
compiler.nodes[id.index()].definition = Some(Definition {
topic: compiler.documents[document].topic.to_owned(),
name: name.clone(),
});
}
let definitions = compiler
.definitions
.iter()
.filter(|((document, _), _)| *document == 0)
.map(|((_, name), id)| (name.clone(), *id))
.collect();
let schema = Self {
nodes: compiler.nodes,
root,
definitions,
};
Ok(schema.find_tags())
}
#[must_use]
pub const fn root(&self) -> SchemaId {
self.root
}
#[must_use]
pub fn node(&self, id: SchemaId) -> &SchemaNode {
&self.nodes[id.index()]
}
#[must_use]
pub fn definition(&self, name: &str) -> Option<SchemaId> {
self.definitions.get(name).copied()
}
#[must_use]
pub fn resolve(&self, mut id: SchemaId) -> SchemaId {
for _ in 0..64 {
let node = self.node(id);
match node.reference {
Some(target) if node.is_bare_reference() => id = target,
_ => break,
}
}
id
}
#[must_use]
pub fn non_null_forms(&self, id: SchemaId) -> Vec<SchemaId> {
let id = self.resolve(id);
let node = self.node(id);
if node.forms.is_empty() {
return vec![id];
}
node.forms
.iter()
.map(|form| self.resolve(*form))
.filter(|form| self.node(*form).types != Some(Types::NULL))
.collect()
}
#[must_use]
pub fn objects(&self, id: SchemaId) -> Vec<SchemaId> {
self.non_null_forms(id)
.into_iter()
.filter(|form| {
let node = self.node(*form);
!node.properties.is_empty()
|| node
.types
.is_some_and(|types| types.contains(Types::OBJECT))
})
.collect()
}
#[must_use]
pub fn definition_of(&self, id: SchemaId) -> Option<&Definition> {
let mut id = id;
for _ in 0..64 {
let node = self.node(id);
if let Some(definition) = &node.definition {
return Some(definition);
}
match node.reference {
Some(target) if node.is_bare_reference() => id = target,
_ => return None,
}
}
None
}
#[must_use]
pub fn types(&self, id: SchemaId) -> Types {
self.types_at(id, 0)
}
fn types_at(&self, id: SchemaId, depth: usize) -> Types {
let node = self.node(id);
if depth > 16 || node.never {
return Types::default();
}
if let Some(target) = node.reference {
return self.types_at(target, depth + 1);
}
if let Some(types) = node.types {
return types;
}
if let Some(constant) = &node.constant {
return Types::of(constant);
}
if let Some(choices) = &node.choices {
return choices.iter().fold(Types::default(), |types, choice| {
types.union(Types::of(choice))
});
}
if !node.forms.is_empty() {
return node.forms.iter().fold(Types::default(), |types, form| {
types.union(self.types_at(*form, depth + 1))
});
}
if !node.properties.is_empty() {
return Types::OBJECT;
}
Types(0x7F)
}
#[must_use]
pub fn constants(&self, id: SchemaId) -> Option<Vec<&Node>> {
let id = self.resolve(id);
let node = self.node(id);
if let Some(constant) = &node.constant {
return Some(vec![constant]);
}
if let Some(choices) = &node.choices {
return Some(choices.iter().collect());
}
if node.forms.is_empty() {
return None;
}
let mut all = Vec::new();
for form in &node.forms {
all.extend(self.constants(*form)?);
}
Some(all)
}
#[must_use]
pub fn constant_match(&self, id: SchemaId, node: &Node) -> Option<bool> {
let id = self.resolve(id);
let rule = self.node(id);
if let Some(constant) = &rule.constant {
return Some(constant.same_value(node));
}
if let Some(choices) = &rule.choices {
return Some(choices.iter().any(|choice| choice.same_value(node)));
}
if rule.forms.is_empty() {
return None;
}
let mut found = false;
for form in &rule.forms {
found |= self.constant_match(*form, node)?;
}
Some(found)
}
#[must_use]
pub fn tag_value(&self, form: SchemaId, tag: &str) -> Option<&Node> {
let property = self.node(self.resolve(form)).property(tag)?;
let property = self.node(self.resolve(property));
property.constant.as_ref().or_else(|| {
property
.choices
.as_ref()
.filter(|choices| choices.len() == 1)?
.first()
})
}
fn find_tags(mut self) -> Self {
let tags: Vec<Option<String>> = (0..self.nodes.len())
.map(|index| self.tag_of(&self.nodes[index]))
.collect();
let partial: Vec<Option<String>> = (0..self.nodes.len())
.map(|index| {
if tags[index].is_some() {
None
} else {
self.partial_tag_of(&self.nodes[index])
}
})
.collect();
for ((node, tag), partial) in self.nodes.iter_mut().zip(tags).zip(partial) {
node.tag = tag;
node.partial_tag = partial;
}
self
}
fn partial_tag_of(&self, node: &SchemaNode) -> Option<String> {
if node.forms.len() < 2 {
return None;
}
let forms: Vec<SchemaId> = node.forms.iter().map(|form| self.resolve(*form)).collect();
let mut names: Vec<&str> = forms
.iter()
.flat_map(|form| {
self.node(*form)
.properties
.iter()
.map(|(name, _)| name.as_str())
})
.collect();
names.sort_unstable();
names.dedup();
names.sort_by_key(|name| {
["type", "op", "kind", "mode", "shape"]
.iter()
.position(|preferred| preferred == name)
.unwrap_or(usize::MAX)
});
names
.into_iter()
.find(|name| {
let mut seen: Vec<&Node> = Vec::new();
for form in &forms {
if self.node(*form).property(name).is_none() {
continue;
}
match self.tag_value(*form, name) {
Some(value) if !seen.iter().any(|known| known.same_value(value)) => {
seen.push(value);
}
Some(_) => return false,
None => {}
}
}
seen.len() >= 2
})
.map(str::to_owned)
}
fn tag_of(&self, node: &SchemaNode) -> Option<String> {
if node.forms.len() < 2 {
return None;
}
let forms: Vec<SchemaId> = node.forms.iter().map(|form| self.resolve(*form)).collect();
let first = self.node(forms[0]);
let mut candidates: Vec<&str> = first
.properties
.iter()
.map(|(name, _)| name.as_str())
.filter(|name| {
let mut seen: Vec<&Node> = Vec::new();
forms.iter().all(|form| match self.tag_value(*form, name) {
Some(value) if !seen.iter().any(|known| known.same_value(value)) => {
seen.push(value);
true
}
_ => false,
})
})
.collect();
candidates.sort_by_key(|name| {
["type", "op", "kind", "mode", "shape"]
.iter()
.position(|preferred| preferred == name)
.unwrap_or(usize::MAX)
});
candidates.first().map(|name| (*name).to_owned())
}
}
impl SchemaNode {
#[must_use]
pub fn is_bare_reference(&self) -> bool {
self.reference.is_some()
&& !self.never
&& self.types.is_none()
&& self.constant.is_none()
&& self.choices.is_none()
&& self.properties.is_empty()
&& self.required.is_empty()
&& self.additional.is_none()
&& self.items.is_none()
&& self.prefix_items.is_empty()
&& self.min_items.is_none()
&& self.max_items.is_none()
&& self.max_properties.is_none()
&& self.minimum.is_none()
&& self.maximum.is_none()
&& self.min_length.is_none()
&& self.max_length.is_none()
&& self.format.is_none()
&& self.forms.is_empty()
}
}
fn bound(node: &mut SchemaNode, key: &str, value: &Node, at: &Path) -> Result<(), SchemaError> {
match key {
"minItems" => node.min_items = Some(count(value, at)?),
"maxItems" => node.max_items = Some(count(value, at)?),
"maxProperties" => node.max_properties = Some(count(value, at)?),
"minLength" => node.min_length = Some(count(value, at)?),
"maxLength" => node.max_length = Some(count(value, at)?),
"minimum" => node.minimum = Some(number(value, at)?),
_ => node.maximum = Some(number(value, at)?),
}
Ok(())
}
fn types(value: &Node, at: &Path) -> Result<Types, SchemaError> {
let names: Vec<&Node> = match &value.value {
Value::Text(_) => vec![value],
Value::List(items) => items.iter().collect(),
_ => return Err(error(at, "expected a type name or a list of them")),
};
let mut types = Types::default();
for name in names {
let known = name
.as_str()
.and_then(Types::from_name)
.ok_or_else(|| error(at, "unknown type name"))?;
types = types.union(known);
}
Ok(types)
}
fn error(path: &Path, message: impl Into<String>) -> SchemaError {
SchemaError {
path: path.clone(),
message: message.into(),
}
}
fn count(node: &Node, path: &Path) -> Result<usize, SchemaError> {
node.as_number()
.and_then(crate::tree::Number::as_i128)
.and_then(|value| usize::try_from(value).ok())
.ok_or_else(|| error(path, "expected a non-negative integer"))
}
fn number(node: &Node, path: &Path) -> Result<f64, SchemaError> {
node.as_number()
.map(crate::tree::Number::as_f64)
.filter(|value| value.is_finite())
.ok_or_else(|| error(path, "expected a number"))
}
impl Compiler<'_> {
fn reserve(&mut self) -> SchemaId {
let id = SchemaId(u32::try_from(self.nodes.len()).unwrap_or(u32::MAX));
self.nodes.push(SchemaNode::default());
id
}
fn definition(&mut self, document: usize, name: &str) -> SchemaId {
if let Some(id) = self.definitions.get(&(document, name.to_owned())) {
return *id;
}
let id = self.reserve();
self.definitions.insert((document, name.to_owned()), id);
self.pending.push((document, name.to_owned(), id));
id
}
fn reference(
&mut self,
document: usize,
target: &str,
path: &Path,
) -> Result<SchemaId, SchemaError> {
let (base, fragment) = target.split_once('#').unwrap_or((target, ""));
let document = if base.is_empty() {
document
} else {
self.documents
.iter()
.position(|known| known.id == Some(base))
.ok_or_else(|| error(path, format!("`$ref` names {base}, which is not given")))?
};
let name = fragment
.strip_prefix("/$defs/")
.filter(|name| !name.contains('/'))
.ok_or_else(|| {
error(
path,
format!("`$ref` {target} is not of the form #/$defs/Name"),
)
})?;
let exists = self.documents[document]
.tree
.get("$defs")
.and_then(|definitions| definitions.get(name))
.is_some();
if !exists {
return Err(error(
path,
format!("`$ref` names {target}, which is not defined"),
));
}
Ok(self.definition(document, name))
}
fn compile(
&mut self,
document: usize,
tree: &Node,
path: &Path,
) -> Result<SchemaId, SchemaError> {
let id = self.reserve();
self.compile_into(document, tree, path, id, false)?;
Ok(id)
}
fn compile_list(
&mut self,
document: usize,
tree: &Node,
path: &Path,
) -> Result<Vec<SchemaId>, SchemaError> {
let items = tree
.as_list()
.ok_or_else(|| error(path, "expected an array of schemas"))?;
items
.iter()
.enumerate()
.map(|(index, item)| self.compile(document, item, &path.index(index)))
.collect()
}
fn compile_into(
&mut self,
document: usize,
tree: &Node,
path: &Path,
id: SchemaId,
root: bool,
) -> Result<(), SchemaError> {
let mut node = SchemaNode::default();
match &tree.value {
Value::Bool(true) => {}
Value::Bool(false) => node.never = true,
Value::Map(entries) => {
for entry in entries {
let at = path.key(entry.key.clone());
self.keyword(document, &mut node, &entry.key, &entry.value, &at, root)?;
}
}
_ => return Err(error(path, "a schema is an object or a boolean")),
}
let definition = self.nodes[id.index()].definition.take();
node.definition = definition;
self.nodes[id.index()] = node;
Ok(())
}
fn keyword(
&mut self,
document: usize,
node: &mut SchemaNode,
key: &str,
value: &Node,
at: &Path,
root: bool,
) -> Result<(), SchemaError> {
match key {
"$ref" => {
let target = value
.as_str()
.ok_or_else(|| error(at, "expected a string"))?;
node.reference = Some(self.reference(document, target, at)?);
}
"$defs" if root => {}
"type" => node.types = Some(types(value, at)?),
"properties" => {
let entries = value
.as_map()
.ok_or_else(|| error(at, "expected an object"))?;
for entry in entries {
let schema =
self.compile(document, &entry.value, &at.key(entry.key.clone()))?;
node.properties.push((entry.key.clone(), schema));
}
}
"required" => {
let names = value
.as_list()
.ok_or_else(|| error(at, "expected an array"))?;
for name in names {
let name = name.as_str().ok_or_else(|| error(at, "expected strings"))?;
node.required.push(name.to_owned());
}
}
"additionalProperties" | "items" => {
let rule = match value.value {
Value::Bool(true) => Additional::Allowed,
Value::Bool(false) => Additional::Denied,
_ => Additional::Schema(self.compile(document, value, at)?),
};
if key == "items" {
node.items = Some(rule);
} else {
node.additional = Some(rule);
}
}
"prefixItems" => node.prefix_items = self.compile_list(document, value, at)?,
"oneOf" | "anyOf" => {
if !node.forms.is_empty() {
return Err(error(at, "both `oneOf` and `anyOf`"));
}
node.forms = self.compile_list(document, value, at)?;
}
"enum" => {
let choices = value
.as_list()
.ok_or_else(|| error(at, "expected an array"))?;
node.choices = Some(
choices
.iter()
.map(|choice| choice.clone().without_spans())
.collect(),
);
}
"const" => node.constant = Some(value.clone().without_spans()),
"default" => node.default = Some(value.clone().without_spans()),
"minItems" | "maxItems" | "maxProperties" | "minLength" | "maxLength" | "minimum"
| "maximum" => bound(node, key, value, at)?,
"format" => {
let name = value
.as_str()
.ok_or_else(|| error(at, "expected a string"))?;
node.format = Some(
Format::from_name(name)
.ok_or_else(|| error(at, format!("unsupported format {name}")))?,
);
}
"pattern" => {
node.pattern = Some(
value
.as_str()
.ok_or_else(|| error(at, "expected a string"))?
.to_owned(),
);
}
"not" => node.not = Some(self.compile(document, value, at)?),
"description" | "title" | "$id" | "$schema" => {}
_ if key.starts_with("x-") => node
.extensions
.push((key.to_owned(), value.clone().without_spans())),
_ => return Err(error(at, format!("unsupported schema keyword {key}"))),
}
Ok(())
}
}