use std::fmt;
use serde_json::{Map, Number, Value};
use crate::{Bounds, FieldRules, LengthUnit, ParamValue, Problem, Rules, ValueRules};
#[must_use = "a rule left out of the schema is only reported here"]
pub fn write_rules(rules: &Rules, schema: &mut Map<String, Value>) -> Vec<UnwrittenRule> {
let mut unwritten = Vec::new();
for field in rules.fields() {
write_field_rules(field, schema, &mut unwritten);
}
unwritten
}
#[derive(Debug, Clone, PartialEq)]
pub struct UnwrittenRule {
pointer: String,
problem: Problem,
reason: Reason,
}
impl UnwrittenRule {
#[must_use]
pub fn pointer(&self) -> &str {
&self.pointer
}
#[must_use]
pub fn problem(&self) -> &Problem {
&self.problem
}
#[must_use]
pub fn reason(&self) -> Reason {
self.reason
}
}
impl fmt::Display for UnwrittenRule {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"`{}` can't be written at `{}`: {}",
self.problem.code(),
self.pointer,
self.reason
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Reason {
NoSchema,
Reference,
OtherType,
NoKeyword,
}
impl fmt::Display for Reason {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let explanation = match self {
Self::NoSchema => "the schema has no subschema there",
Self::Reference => "the subschema there is a `$ref`, which isn't followed",
Self::OtherType => "the subschema there isn't of a type the rule constrains",
Self::NoKeyword => "no keyword says what the rule requires",
};
formatter.write_str(explanation)
}
}
struct Counted {
value_type: &'static str,
fewest: &'static str,
most: &'static str,
}
const CHARS: Counted = Counted {
value_type: "string",
fewest: "minLength",
most: "maxLength",
};
const ITEMS: Counted = Counted {
value_type: "array",
fewest: "minItems",
most: "maxItems",
};
const PROPERTIES: Counted = Counted {
value_type: "object",
fewest: "minProperties",
most: "maxProperties",
};
fn write_field_rules(field: &FieldRules, schema: &mut Map<String, Value>, unwritten: &mut Vec<UnwrittenRule>) {
if !write_where_declared(field, schema, "", unwritten) {
let pointer = property_pointer("", field.name());
leave_unwritten(field.rules(), &pointer, Reason::NoSchema, unwritten);
}
}
fn write_where_declared(
field: &FieldRules,
schema: &mut Map<String, Value>,
pointer: &str,
unwritten: &mut Vec<UnwrittenRule>,
) -> bool {
if let Some(property) = property_named(field.name(), schema) {
let property_pointer = property_pointer(pointer, field.name());
write_value_rules(field.rules(), property, &property_pointer, unwritten);
let is_broken_by_its_absence = field.rules().problems().contains(&Problem::Required) && !field.has_default();
if is_broken_by_its_absence {
list_as_required(field.name(), schema);
}
return true;
}
let Some(Value::Array(members)) = schema.get_mut("allOf") else {
return false;
};
members.iter_mut().enumerate().any(|(index, member)| {
let member_pointer = format!("{pointer}/allOf/{index}");
member
.as_object_mut()
.is_some_and(|member| write_where_declared(field, member, &member_pointer, unwritten))
})
}
fn property_named<'a>(name: &str, schema: &'a mut Map<String, Value>) -> Option<&'a mut Map<String, Value>> {
schema.get_mut("properties")?.get_mut(name)?.as_object_mut()
}
fn property_pointer(pointer: &str, name: &str) -> String {
let name = name.replace('~', "~0").replace('/', "~1");
format!("{pointer}/properties/{name}")
}
fn list_as_required(name: &str, schema: &mut Map<String, Value>) {
let required = schema.entry("required").or_insert_with(|| Value::Array(Vec::new()));
let Value::Array(required) = required else {
return;
};
if !required.iter().any(|listed| listed == name) {
required.push(name.into());
}
}
fn write_value_rules(
rules: &ValueRules,
schema: &mut Map<String, Value>,
pointer: &str,
unwritten: &mut Vec<UnwrittenRule>,
) {
for problem in rules.problems() {
if let Err(reason) = write_problem(problem, rules.is_optional(), schema) {
unwritten.push(UnwrittenRule {
pointer: pointer.to_owned(),
problem: problem.clone(),
reason,
});
}
}
let Some(element_rules) = rules.elements() else {
return;
};
let Some(elements) = keyword_of_the_elements(schema) else {
leave_unwritten(element_rules, pointer, why_unconstrained(schema), unwritten);
return;
};
let element_pointer = format!("{pointer}/{elements}");
match schema.get_mut(elements).and_then(Value::as_object_mut) {
Some(element_schema) => write_value_rules(element_rules, element_schema, &element_pointer, unwritten),
None => leave_unwritten(element_rules, &element_pointer, Reason::NoSchema, unwritten),
}
}
fn leave_unwritten(rules: &ValueRules, pointer: &str, reason: Reason, unwritten: &mut Vec<UnwrittenRule>) {
unwritten.extend(rules.problems().iter().map(|problem| UnwrittenRule {
pointer: pointer.to_owned(),
problem: problem.clone(),
reason,
}));
if let Some(element_rules) = rules.elements() {
leave_unwritten(element_rules, pointer, reason, unwritten);
}
}
fn keyword_of_the_elements(schema: &Map<String, Value>) -> Option<&'static str> {
if accepts("array", schema) {
return Some("items");
}
if accepts("object", schema) {
return Some("additionalProperties");
}
None
}
fn why_unconstrained(schema: &Map<String, Value>) -> Reason {
if schema.contains_key("$ref") {
return Reason::Reference;
}
Reason::OtherType
}
fn write_problem(problem: &Problem, is_value_optional: bool, schema: &mut Map<String, Value>) -> Result<(), Reason> {
match problem {
Problem::Required if is_value_optional => {
refuse_null(schema);
Ok(())
}
Problem::Required => write_counts(&[CHARS, ITEMS, PROPERTIES], Some(1), None, schema),
Problem::Length { bounds, unit } => write_length(bounds, *unit, schema),
Problem::Range { bounds } => write_range(bounds, schema),
Problem::Email => write_format("email", schema),
Problem::Url { .. } => write_format("iri", schema),
Problem::Ipv4 => write_format("ipv4", schema),
Problem::Ipv6 => write_format("ipv6", schema),
Problem::Pattern { pattern } => write_pattern((*pattern).to_owned(), schema),
Problem::Contains { text } => write_pattern(matching_exactly(text), schema),
Problem::Prefix { prefix } => write_pattern(format!("^{}", matching_exactly(prefix)), schema),
Problem::Suffix { suffix } => write_pattern(format!("{}$", matching_exactly(suffix)), schema),
_ => Err(Reason::NoKeyword),
}
}
fn accepts(value_type: &str, schema: &Map<String, Value>) -> bool {
match schema.get("type") {
Some(Value::String(only_type)) => only_type == value_type,
Some(Value::Array(types)) => types.iter().any(|accepted| accepted == value_type),
_ => false,
}
}
fn refuse_null(schema: &mut Map<String, Value>) {
if let Some(Value::Array(types)) = schema.get_mut("type") {
types.retain(|accepted| accepted != "null");
if let [only_type] = types.as_slice() {
let only_type = only_type.clone();
schema.insert("type".to_owned(), only_type);
}
}
for alternatives in ["oneOf", "anyOf"] {
if let Some(Value::Array(schemas)) = schema.get_mut(alternatives) {
schemas.retain(|alternative| !accepts_only_null(alternative));
}
replace_by_its_only_alternative(alternatives, schema);
}
}
fn replace_by_its_only_alternative(alternatives: &str, schema: &mut Map<String, Value>) {
let Some(Value::Array(schemas)) = schema.get(alternatives) else {
return;
};
let [Value::Object(only_alternative)] = schemas.as_slice() else {
return;
};
if only_alternative.keys().any(|keyword| schema.contains_key(keyword)) {
return;
}
let only_alternative = only_alternative.clone();
schema.remove(alternatives);
schema.extend(only_alternative);
}
fn accepts_only_null(schema: &Value) -> bool {
schema
.as_object()
.is_some_and(|schema| schema.len() == 1 && schema.get("type").is_some_and(|only_type| only_type == "null"))
}
fn write_length(bounds: &Bounds<usize>, unit: LengthUnit, schema: &mut Map<String, Value>) -> Result<(), Reason> {
let (shortest, longest) = bounds.ends();
let (shortest, longest) = (shortest.copied(), longest.copied());
match unit {
LengthUnit::Chars => write_counts(&[CHARS], shortest, longest, schema),
LengthUnit::Bytes => {
let fewest_chars = shortest.map(|bytes| bytes.div_ceil(char::MAX_LEN_UTF8));
write_counts(&[CHARS], fewest_chars, longest, schema)
}
LengthUnit::Graphemes => write_counts(&[CHARS], shortest, None, schema),
LengthUnit::Elements => write_counts(&[ITEMS, PROPERTIES], shortest, longest, schema),
}
}
fn write_counts(
counted: &[Counted],
fewest: Option<usize>,
most: Option<usize>,
schema: &mut Map<String, Value>,
) -> Result<(), Reason> {
if fewest.is_none() && most.is_none() {
return Err(Reason::NoKeyword);
}
let mut is_bounded = false;
for counted in counted {
if !accepts(counted.value_type, schema) {
continue;
}
if let Some(fewest) = fewest {
raise_to(Number::from(fewest), counted.fewest, schema);
}
if let Some(most) = most {
lower_to(Number::from(most), counted.most, schema);
}
is_bounded = true;
}
if !is_bounded {
return Err(why_unconstrained(schema));
}
Ok(())
}
fn write_range(bounds: &Bounds<ParamValue>, schema: &mut Map<String, Value>) -> Result<(), Reason> {
let (least, greatest) = bounds.ends();
let (least, greatest) = (least.and_then(as_number), greatest.and_then(as_number));
if least.is_none() && greatest.is_none() {
return Err(Reason::NoKeyword);
}
if !accepts("integer", schema) && !accepts("number", schema) {
return Err(why_unconstrained(schema));
}
if let Some(least) = least {
raise_to(least, "minimum", schema);
}
if let Some(greatest) = greatest {
lower_to(greatest, "maximum", schema);
}
Ok(())
}
fn as_number(bound: &ParamValue) -> Option<Number> {
match bound {
ParamValue::Integer(integer) => Number::from_i128(*integer),
ParamValue::Float(float) => Number::from_f64(*float),
ParamValue::Text(_) => None,
}
}
fn raise_to(minimum: Number, keyword: &str, schema: &mut Map<String, Value>) {
let is_high_enough_already =
matches!(schema.get(keyword), Some(Value::Number(current)) if !is_less(current, &minimum));
if !is_high_enough_already {
schema.insert(keyword.to_owned(), Value::Number(minimum));
}
}
fn lower_to(maximum: Number, keyword: &str, schema: &mut Map<String, Value>) {
let is_low_enough_already =
matches!(schema.get(keyword), Some(Value::Number(current)) if !is_less(&maximum, current));
if !is_low_enough_already {
schema.insert(keyword.to_owned(), Value::Number(maximum));
}
}
fn is_less(left: &Number, right: &Number) -> bool {
match (left.as_i128(), right.as_i128()) {
(Some(left), Some(right)) => left < right,
_ => left.as_f64() < right.as_f64(),
}
}
fn write_format(format: &str, schema: &mut Map<String, Value>) -> Result<(), Reason> {
if !accepts("string", schema) {
return Err(why_unconstrained(schema));
}
if !schema.contains_key("format") {
schema.insert("format".to_owned(), format.into());
}
Ok(())
}
fn write_pattern(pattern: String, schema: &mut Map<String, Value>) -> Result<(), Reason> {
if !accepts("string", schema) {
return Err(why_unconstrained(schema));
}
let Some(first_pattern) = schema.get("pattern") else {
schema.insert("pattern".to_owned(), pattern.into());
return Ok(());
};
if *first_pattern == pattern {
return Ok(());
}
let also_required = schema.entry("allOf").or_insert_with(|| Value::Array(Vec::new()));
let Value::Array(also_required) = also_required else {
return Err(Reason::NoSchema);
};
let requiring_the_pattern = Value::Object(Map::from_iter([("pattern".to_owned(), Value::String(pattern))]));
if !also_required.contains(&requiring_the_pattern) {
also_required.push(requiring_the_pattern);
}
Ok(())
}
fn matching_exactly(text: &str) -> String {
let mut expression = String::with_capacity(text.len());
for character in text.chars() {
if r"\^$.*+?()[]{}|".contains(character) {
expression.push('\\');
}
expression.push(character);
}
expression
}