use std::str::FromStr;
use indexmap::IndexMap;
use super::{seed, CardSchema, FieldSchema, FieldType, Quill, QuillConfig};
use crate::normalize::normalize_document;
use crate::quill::zero_value;
use crate::value::PathSegment;
use crate::{
Card, Diagnostic, Document, Payload, QuillValue, RenderError, SeedOverlay, Severity, Version,
};
impl Quill {
pub fn compile_data(&self, doc: &Document) -> Result<serde_json::Value, RenderError> {
self.config().compile_data(doc)
}
pub fn dry_run(&self, doc: &Document) -> Result<(), RenderError> {
self.config().dry_run(doc)
}
pub fn check_quill_reference(&self, doc: &Document) -> Result<(), RenderError> {
self.config().check_quill_reference(doc)
}
}
impl QuillConfig {
pub fn compile_data(&self, doc: &Document) -> Result<serde_json::Value, RenderError> {
let coerced = self.coerce_and_validate(doc)?;
let normalized = normalize_document(coerced)?;
let main_resolved = resolve_fields(&normalized.main().payload().to_index_map(), &self.main);
let cards_resolved: Vec<Card> = normalized
.cards()
.iter()
.map(|card| {
let fields = match self.card_kind(card.kind().unwrap_or("")) {
Some(schema) => resolve_fields(&card.payload().to_index_map(), schema),
None => card.payload().to_index_map(),
};
Card::from_parts(rebuild_payload_with_meta(card, fields), card.body().clone())
})
.collect();
let final_main = Card::from_parts(
rebuild_payload_with_meta(normalized.main(), main_resolved),
normalized.main().body().clone(),
);
let final_doc = Document::from_main_and_cards(final_main, cards_resolved);
Ok(final_doc.to_plate_json())
}
pub fn dry_run(&self, doc: &Document) -> Result<(), RenderError> {
self.check_quill_reference(doc)?;
self.coerce_and_validate(doc).map(|_| ())
}
fn coerce_and_validate(&self, doc: &Document) -> Result<Document, RenderError> {
let coerced_payload = self
.coerce_payload(&doc.main().payload().to_index_map())
.map_err(coercion_error)?;
let mut coerced_cards: Vec<Card> = Vec::with_capacity(doc.cards().len());
for card in doc.cards() {
let coerced_fields = self
.coerce_card(card.kind().unwrap_or(""), &card.payload().to_index_map())
.map_err(coercion_error)?;
coerced_cards.push(Card::from_parts(
rebuild_payload_with_meta(card, coerced_fields),
card.body().clone(),
));
}
let coerced_main = Card::from_parts(
rebuild_payload_with_meta(doc.main(), coerced_payload),
doc.main().body().clone(),
);
let coerced_doc = Document::from_main_and_cards(coerced_main, coerced_cards);
self.validate_document(&coerced_doc).map_err(|errors| {
RenderError::new(errors.iter().map(|e| e.to_diagnostic()).collect())
})?;
Ok(coerced_doc)
}
pub fn check_quill_reference(&self, doc: &Document) -> Result<(), RenderError> {
let doc_ref = doc.quill_reference();
if doc_ref.name.as_str() != self.name {
return Err(quill_mismatch(
format!(
"document declares $quill '{}' but was rendered with '{}'",
doc_ref, self.name
),
"quill::name_mismatch",
"render with the quill named by $quill, or update the $quill name",
));
}
let Ok(quill_version) = Version::from_str(&self.version) else {
return Ok(());
};
if !doc_ref.selector.matches(quill_version) {
return Err(quill_mismatch(
format!(
"document declares $quill '{}' but the loaded quill is version '{}'",
doc_ref, quill_version
),
"quill::version_mismatch",
"render with a quill whose version satisfies the selector, or update the $quill selector",
));
}
Ok(())
}
}
impl Quill {
pub fn validate(&self, doc: &Document) -> Vec<Diagnostic> {
let mut diags = match self.config().validate_document(doc) {
Ok(()) => Vec::new(),
Err(errors) => errors.iter().map(|e| e.to_diagnostic()).collect(),
};
diags.extend(validate_fills(doc));
diags.extend(self.validate_seed(doc));
diags
}
fn validate_seed(&self, doc: &Document) -> Vec<Diagnostic> {
let Some(seed_map) = doc.main().payload().seed() else {
return Vec::new();
};
let config = self.config();
let mut diags = Vec::new();
for (kind, overlay) in seed_map {
let Some(card_schema) = config.card_kind(kind) else {
diags.push(
Diagnostic::new(
Severity::Warning,
format!("`$seed` overlay targets unknown card kind `{kind}`"),
)
.with_code("validation::seed_unknown_kind".to_string())
.with_path(format!("$seed.{kind}"))
.with_hint(format!(
"Remove the `{kind}` overlay, or rename it to a declared card kind."
)),
);
continue;
};
let Some(obj) = overlay.as_object() else {
diags.push(
Diagnostic::new(
Severity::Warning,
format!("`$seed.{kind}` must be a mapping of field overrides"),
)
.with_code("validation::seed_overlay_shape".to_string())
.with_path(format!("$seed.{kind}")),
);
continue;
};
for (field, value) in obj {
if field == "$body" {
continue;
}
let field_path = format!("$seed.{kind}.{field}");
let Some(field_schema) = card_schema.fields.get(field) else {
diags.push(
Diagnostic::new(
Severity::Warning,
format!("`$seed.{kind}.{field}` is not a field of card kind `{kind}`"),
)
.with_code("validation::seed_unknown_field".to_string())
.with_path(field_path),
);
continue;
};
let qv = QuillValue::from_json(value.clone());
for violation in
super::validation::validate_schema_literal(field_schema, &qv, &field_path)
{
diags.push(seed_violation_diagnostic(&violation));
}
}
}
diags
}
pub fn seed_document(&self) -> Document {
seed::seed_document(self)
}
pub fn seed_main(&self) -> Card {
seed::seed_main(self)
}
pub fn seed_card(&self, card_kind: &str, overlay: Option<&SeedOverlay>) -> Option<Card> {
seed::seed_card_for_kind(self, card_kind, overlay)
}
}
fn quill_mismatch(message: String, code: &str, hint: &str) -> RenderError {
RenderError::from_diag(
Diagnostic::new(Severity::Error, message)
.with_code(code.to_string())
.with_hint(hint.to_string()),
)
}
fn seed_violation_diagnostic(v: &super::validation::ValidationError) -> Diagnostic {
let mut diag = Diagnostic::new(Severity::Warning, v.to_string())
.with_code(v.code().to_string())
.with_path(v.path().to_string());
if let Some(hint) = v.hint() {
diag = diag.with_hint(hint);
}
diag
}
fn coercion_error(e: impl std::fmt::Display) -> RenderError {
RenderError::from_diag(
Diagnostic::new(Severity::Error, e.to_string())
.with_code("validation::coercion_failed".to_string())
.with_hint("Ensure all fields can be coerced to their declared types".to_string()),
)
}
fn resolve_fields(
fields: &IndexMap<String, QuillValue>,
schema: &CardSchema,
) -> IndexMap<String, QuillValue> {
let mut result = fields.clone();
for (name, field) in &schema.fields {
let resolved = resolve_value(result.get(name), field);
result.insert(name.clone(), resolved);
}
result
}
fn resolve_value(value: Option<&QuillValue>, field: &FieldSchema) -> QuillValue {
let present = value.filter(|v| !v.as_json().is_null());
let Some(v) = present else {
if matches!(
field.r#type,
FieldType::RichText { .. } | FieldType::PlainText { .. }
) {
return field
.default_content
.clone()
.unwrap_or_else(|| zero_value(field));
}
return field.default.clone().unwrap_or_else(|| zero_value(field));
};
match (&field.r#type, &field.properties, &field.items) {
(FieldType::Object, Some(props), _) => {
let obj = v.as_json().as_object();
let mut out = serde_json::Map::new();
for (pname, pschema) in props {
let pv = obj
.and_then(|o| o.get(pname))
.map(|j| QuillValue::from_json(j.clone()));
out.insert(
pname.clone(),
resolve_value(pv.as_ref(), pschema).into_json(),
);
}
if let Some(o) = obj {
for (k, v) in o {
if !props.contains_key(k) {
out.insert(k.clone(), v.clone());
}
}
}
QuillValue::from_json(serde_json::Value::Object(out))
}
(FieldType::Array, _, Some(items)) => {
let arr = v.as_json().as_array().cloned().unwrap_or_default();
let out: Vec<serde_json::Value> = arr
.into_iter()
.map(|e| resolve_value(Some(&QuillValue::from_json(e)), items).into_json())
.collect();
QuillValue::from_json(serde_json::Value::Array(out))
}
_ => v.clone(),
}
}
fn rebuild_payload_with_meta(source: &Card, fields: IndexMap<String, QuillValue>) -> Payload {
let mut payload = Payload::from_index_map(fields);
if let Some(q) = source.quill() {
payload.set_quill(q.clone());
}
if let Some(k) = source.kind() {
payload.set_kind(k.to_string());
}
if let Some(id) = source.id() {
payload.set_id(id.to_string());
}
payload
}
fn validate_fills(doc: &Document) -> Vec<Diagnostic> {
let mut diags = Vec::new();
collect_fill_diags(doc.main(), "", &mut diags);
for (index, card) in doc.cards().iter().enumerate() {
let kind = card.kind().unwrap_or("");
let base = format!("cards.{kind}[{index}]");
collect_fill_diags(card, &base, &mut diags);
}
diags
}
fn collect_fill_diags(card: &Card, base: &str, out: &mut Vec<Diagnostic>) {
let payload = card.payload();
for (key, value) in payload {
let field_path = if base.is_empty() {
key.clone()
} else {
format!("{base}.{key}")
};
if payload.is_fill(key) {
out.push(fill_warning(&field_path));
}
for nested in value.nonroot_fill_paths() {
out.push(fill_warning(&render_fill_path(&field_path, &nested)));
}
}
}
fn render_fill_path(base: &str, segs: &[PathSegment]) -> String {
let mut s = base.to_string();
for seg in segs {
match seg {
PathSegment::Key(k) => {
s.push('.');
s.push_str(k);
}
PathSegment::Index(i) => s.push_str(&format!("[{i}]")),
}
}
s
}
fn fill_warning(path: &str) -> Diagnostic {
Diagnostic::new(
Severity::Warning,
format!("Field `{path}` is marked `!must_fill` — a placeholder awaiting a value."),
)
.with_code("validation::must_fill".to_string())
.with_path(path.to_string())
.with_hint(
"Replace the value and drop the `!must_fill` marker, or remove the marker if the \
current value is intended."
.to_string(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn field(yaml: &str) -> FieldSchema {
let value = QuillValue::from_yaml_str(yaml).unwrap();
FieldSchema::from_quill_value("field".to_string(), &value).unwrap()
}
#[test]
fn typed_dict_preserves_undeclared_keys() {
let schema = field(
r#"
type: object
properties:
street: { type: string }
zip: { type: integer }
"#,
);
let input = QuillValue::from_json(json!({ "street": "1 Infinite Loop", "note": "extra" }));
let resolved = resolve_value(Some(&input), &schema).into_json();
assert_eq!(
resolved,
json!({ "street": "1 Infinite Loop", "zip": 0, "note": "extra" })
);
}
#[test]
fn typed_table_row_preserves_undeclared_keys() {
let schema = field(
r#"
type: array
items:
type: object
properties:
name: { type: string }
"#,
);
let input = QuillValue::from_json(json!([{ "name": "ACME", "year": 2020 }]));
let resolved = resolve_value(Some(&input), &schema).into_json();
assert_eq!(resolved, json!([{ "name": "ACME", "year": 2020 }]));
}
}