use crate::ast::{Function, Node};
use crate::next::schema::value::{self, BuiltinProto, Ctor, Value, realm, scalar_to_js_string};
use crate::next::schema::{
self, BuiltinType, Config, Found, Matches, SchemaAttribute, TypeSpec, ValidationContext,
Variables, is_undefined_in, lookup,
};
use crate::next::transformer::find_schema;
use crate::types::{
JsObjectValue, Location, MarkdocError, NodeType, Result, Scalar, Span, ValidationError,
ValidationLevel,
};
use indexmap::IndexMap;
use serde_json::Value as Json;
#[derive(Debug, Clone)]
pub struct ValidateError {
pub node_type: NodeType,
pub lines: Vec<f64>,
pub location: Option<ValidateLocation>,
pub error: ValidationError,
pub span: Option<Span>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ValidateLocation {
Node(Location),
Error(Json),
}
impl ValidateLocation {
pub fn to_json(&self) -> Json {
match self {
ValidateLocation::Node(location) => location.to_json(),
ValidateLocation::Error(location) => location.clone(),
}
}
}
#[derive(Debug, Clone)]
pub enum Valid {
Bool(bool),
Errors(Vec<ValidationError>),
}
impl Valid {
fn truthy(&self) -> bool {
match self {
Valid::Bool(b) => *b,
Valid::Errors(_) => true,
}
}
}
fn error(id: &str, level: ValidationLevel, message: String) -> ValidationError {
ValidationError {
id: id.into(),
level,
message,
location: None,
raw: None,
span: None,
}
}
fn throw(message: impl Into<String>) -> MarkdocError {
MarkdocError::ValidationError(message.into())
}
pub fn is_ast(value: &Scalar) -> bool {
match value {
Scalar::Variable(_) | Scalar::Function(_) | Scalar::Tag(_) => true,
Scalar::Object(o) => o
.get("$$mdtype")
.is_some_and(|t| Value::from_scalar(t).to_boolean()),
Scalar::Js(js) => value::is_ast(js.value()),
_ => false,
}
}
fn is_function(value: &Scalar) -> bool {
match value {
Scalar::Function(_) => true,
Scalar::Js(js) => value::mdtype_is(js.value(), "Function"),
_ => false,
}
}
fn is_variable(value: &Scalar) -> bool {
match value {
Scalar::Variable(_) => true,
Scalar::Js(js) => value::mdtype_is(js.value(), "Variable"),
_ => false,
}
}
fn scalar_of(value: &Value) -> Scalar {
match value {
Value::Undefined => Scalar::Undefined,
Value::Null => Scalar::Null,
Value::Boolean(b) => Scalar::Boolean(*b),
Value::Number(n) => Scalar::Number(*n),
Value::String(s) => Scalar::String(s.to_string_lossy().into_owned()),
object => Scalar::Js(JsObjectValue::new(object.clone())),
}
}
fn function_name(value: &Scalar) -> Result<String> {
match value {
Scalar::Function(f) => Ok(f.name.clone()),
Scalar::Js(js) => {
let name = value::get(js.value(), "name").map_err(throw)?;
value::to_property_key(&name).map_err(throw)
}
_ => unreachable!("a call"),
}
}
enum Mapped {
Builtin(BuiltinType),
Prototype,
NotConstructor,
Undefined,
}
fn type_mapping(name: &str) -> Mapped {
if let Some(builtin) = BuiltinType::from_name(name) {
return Mapped::Builtin(builtin);
}
match name {
"constructor" => Mapped::Builtin(BuiltinType::Object),
"__proto__" => Mapped::Prototype,
_ if value::is_object_prototype_name(name) => Mapped::NotConstructor,
_ => Mapped::Undefined,
}
}
fn has_constructor(value: &Scalar, ctor: BuiltinType) -> bool {
if let Scalar::Js(js) = value {
return value::constructor_is(
js.value(),
match ctor {
BuiltinType::String => Ctor::String,
BuiltinType::Number => Ctor::Number,
BuiltinType::Boolean => Ctor::Boolean,
BuiltinType::Object => Ctor::Object,
BuiltinType::Array => Ctor::Array,
},
);
}
match value {
Scalar::String(_) => ctor == BuiltinType::String,
Scalar::Number(_) => ctor == BuiltinType::Number,
Scalar::Boolean(_) => ctor == BuiltinType::Boolean,
Scalar::Array(_) => ctor == BuiltinType::Array,
Scalar::Object(o) => !o.contains_key("constructor") && ctor == BuiltinType::Object,
Scalar::Undefined
| Scalar::Null
| Scalar::Variable(_)
| Scalar::Function(_)
| Scalar::Tag(_)
| Scalar::Js(_) => false,
}
}
pub fn validate_type(
t: &TypeSpec,
value: &Scalar,
cx: &ValidationContext<'_>,
key: &str,
) -> Result<Valid> {
if matches!(t, TypeSpec::Falsy) {
return Ok(Valid::Bool(true));
}
if is_function(value) && cx.config.validation.validate_functions {
let valid = match lookup(&cx.config.functions, &function_name(value)?) {
Found::Own(Some(schema)) => match &schema.returns {
None => true,
Some(returns) => returns.iter().any(|r| r.identical(t)),
},
_ => true,
};
return Ok(Valid::Bool(valid));
}
if is_ast(value) {
return Ok(Valid::Bool(true));
}
if let TypeSpec::Union(types) = t {
for t in types {
if validate_type(t, value, cx, key)?.truthy() {
return Ok(Valid::Bool(true));
}
}
return Ok(Valid::Bool(false));
}
let ctor = match t {
TypeSpec::Name(name) => match type_mapping(name) {
Mapped::Builtin(b) => Some(b),
Mapped::NotConstructor => {
return Err(throw("TypeError: type is not a constructor"));
}
Mapped::Prototype | Mapped::Undefined => None,
},
TypeSpec::Builtin(b) => Some(*b),
TypeSpec::Markdoc(m) => {
return Ok(Valid::Errors(
m.validate(value, cx.config, key).map_err(throw)?,
));
}
TypeSpec::Custom(custom) => {
if let Some(errors) = custom.validate(value, cx, key) {
return Ok(Valid::Errors(errors?));
}
None
}
TypeSpec::Realm(b) if b.is_callable() && !b.is_constructor() => {
return Err(throw("TypeError: type is not a constructor"));
}
TypeSpec::Realm(_) => None,
TypeSpec::Value(_) => None,
TypeSpec::Falsy | TypeSpec::Union(_) => unreachable!("handled above"),
};
Ok(Valid::Bool(
!matches!(value, Scalar::Undefined | Scalar::Null)
&& ctor.is_some_and(|c| has_constructor(value, c)),
))
}
pub fn type_to_string(t: &TypeSpec) -> String {
match t {
TypeSpec::Name(name) => name.clone(),
TypeSpec::Union(types) => types
.iter()
.map(type_to_string)
.collect::<Vec<_>>()
.join(" | "),
TypeSpec::Builtin(b) => b.name().into(),
TypeSpec::Markdoc(m) => m.name().into(),
TypeSpec::Custom(c) => c.name().into(),
TypeSpec::Realm(b) => match value::get_property(&Value::Builtin(*b), "name") {
Ok(name) => name
.to_js_string()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default(),
Err(_) => String::new(),
},
TypeSpec::Falsy => String::new(),
TypeSpec::Value(v) => value::get(v, "name")
.and_then(|n| n.to_js_string())
.map(value::JsString::into_string_lossy)
.unwrap_or_else(|e| e),
}
}
fn validate_function(f: &Scalar, cx: &ValidationContext<'_>) -> Result<Vec<ValidationError>> {
let name = function_name(f)?;
let schema = match lookup(&cx.config.functions, &name) {
Found::Own(Some(schema)) => schema,
Found::Own(None) | Found::Missing => {
return Ok(vec![error(
"function-undefined",
ValidationLevel::Critical,
format!(
"Undefined function: '{}'",
scalar_to_js_string(&name_value(f)?).map_err(throw)?
),
)]);
}
Found::Inherited => return Ok(Vec::new()),
};
let mut errors = Vec::new();
if let Some(validate) = &schema.validate {
errors.extend(validate(&as_function(f, &name), cx)?);
}
let parameters: Option<Value> = match f {
Scalar::Function(_) => None,
Scalar::Js(js) => Some(value::get(js.value(), "parameters").map_err(throw)?),
_ => unreachable!("a call"),
};
if let Some(schema_parameters) = &schema.parameters {
let entries: Vec<(String, Scalar)> = match (f, ¶meters) {
(Scalar::Function(plain), _) => plain
.parameters
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
(_, Some(p)) => value::own_entries_of(p)
.map_err(throw)?
.into_iter()
.map(|(k, v)| (k, scalar_of(&v)))
.collect(),
_ => unreachable!("a call"),
};
for (key, value) in &entries {
let param = match lookup(schema_parameters, key) {
Found::Own(param) if !param.kind.is_falsy() => param,
Found::Inherited => continue,
Found::Own(_) | Found::Missing => {
errors.push(error(
"parameter-undefined",
ValidationLevel::Error,
format!("Invalid parameter: '{key}'"),
));
continue;
}
};
if is_ast(value) && !is_function(value) {
continue;
}
if let Some(t) = ¶m.attr_type {
match validate_type(t, value, cx, key)? {
Valid::Bool(false) => errors.push(error(
"parameter-type-invalid",
ValidationLevel::Error,
format!(
"Parameter '{key}' of '{}' must be type of '{}'",
scalar_to_js_string(&name_value(f)?).map_err(throw)?,
type_to_string(t)
),
)),
Valid::Errors(e) => errors.extend(e),
Valid::Bool(true) => {}
}
}
}
}
for (key, param) in schema.parameters.iter().flatten() {
param.kind.read("required").map_err(throw)?;
let undefined = match (f, ¶meters) {
(Scalar::Function(plain), _) => {
is_undefined_in(&plain.parameters, key)
|| matches!(plain.parameters.get(key), Some(Scalar::Undefined))
}
(_, Some(p)) => value::is_undefined_at(p, key).map_err(throw)?,
_ => unreachable!("a call"),
};
if param.required && undefined {
errors.push(error(
"parameter-missing-required",
ValidationLevel::Error,
format!("Missing required parameter: '{key}'"),
));
}
}
Ok(errors)
}
fn name_value(f: &Scalar) -> Result<Scalar> {
Ok(match f {
Scalar::Function(plain) => Scalar::String(plain.name.clone()),
Scalar::Js(js) => scalar_of(&value::get(js.value(), "name").map_err(throw)?),
_ => unreachable!("a call"),
})
}
fn as_function(f: &Scalar, name: &str) -> Function {
match f {
Scalar::Function(plain) => plain.clone(),
Scalar::Js(js) => {
let parameters: IndexMap<String, Scalar> = value::get(js.value(), "parameters")
.ok()
.map(|p| {
value::own_entries(&p)
.into_iter()
.map(|(k, v)| (k, v.to_scalar().unwrap_or(Scalar::Null)))
.collect()
})
.unwrap_or_default();
Function::new(name.to_string(), parameters)
}
_ => unreachable!("a call"),
}
}
fn display_matches(matches: &[Value], n: usize) -> Result<String> {
if matches.len() <= n {
return Ok(value::json_stringify(&Value::array(matches.to_vec()), "")
.map_err(throw)?
.unwrap_or_default());
}
let items = matches[..n]
.iter()
.map(|item| {
Ok(value::json_stringify(item, "")
.map_err(throw)?
.unwrap_or_default())
})
.collect::<Result<Vec<String>>>()?;
Ok(format!(
"[{}, ... {} more]",
items.join(","),
matches.len() - n
))
}
fn includes(matches: &[Value], value: &Scalar) -> bool {
matches.iter().any(|m| match (m, value) {
(Value::Undefined, Scalar::Undefined) | (Value::Null, Scalar::Null) => true,
(Value::Boolean(a), Scalar::Boolean(b)) => a == b,
(Value::Number(a), Scalar::Number(b)) => a == b || (a.is_nan() && b.is_nan()),
(Value::String(a), Scalar::String(b)) => a == b,
_ => false,
})
}
fn call_matches(f: crate::next::realm::Builtin) -> Result<Matches> {
use crate::next::realm::Called;
let config = Value::empty_object();
match crate::next::realm::call(f, &Value::Undefined, &[config]).map_err(throw)? {
Called::Value(Value::Array(items)) => Ok(Matches::Array(
(0..items.len())
.map(|i| items.get(i).cloned().unwrap_or(Value::Undefined))
.collect(),
)),
_ => Ok(Matches::Other),
}
}
static INHERITED_ATTRIBUTE: std::sync::LazyLock<SchemaAttribute> =
std::sync::LazyLock::new(SchemaAttribute::default);
fn variables_truthy(config: &Config) -> bool {
match &config.variables {
Some(Variables::Value(v)) => v.to_boolean(),
Some(Variables::Fn(_)) => true,
None => false,
}
}
fn path_steps(variable: &Value) -> Result<(Value, Vec<Value>)> {
let path = value::get(variable, "path").map_err(throw)?;
let not_iterable = || throw("TypeError: value.path is not iterable");
let steps = match &path {
Value::String(s) => char::decode_utf16(s.code_units())
.map(|c| match c {
Ok(c) => Value::string(c.to_string()),
Err(lone) => {
Value::String(value::JsString::from_code_unit(lone.unpaired_surrogate()))
}
})
.collect(),
Value::Array(_) | Value::Object(_) if inherits_array(&path) => {
let (length, present) = value::array_like_elements(&path).map_err(throw)?;
let mut steps = Vec::with_capacity(present.len());
let mut present = present.into_iter().peekable();
for i in 0..length {
match present.peek() {
Some((j, _)) if *j == i => steps.push(present.next().expect("peeked").1),
_ => steps.push(Value::Undefined),
}
}
steps
}
_ => return Err(not_iterable()),
};
Ok((path, steps))
}
fn inherits_array(value: &Value) -> bool {
let mut at = value::prototype_of(value);
loop {
match at {
Some(value::Proto::Builtin(p)) => return p == BuiltinProto::ARRAY_PROTOTYPE,
Some(value::Proto::Value(v)) => at = value::prototype_of(&v),
_ => return false,
}
}
}
fn js_variable_missing(variable: &Value, config: &Config) -> Result<Option<String>> {
let (path, steps) = path_steps(variable)?;
let mut variables = match &config.variables {
Some(Variables::Value(v)) => v.clone(),
Some(Variables::Fn(_)) => {
match steps.first() {
Some(step) => {
let key = value::to_property_key(step).map_err(throw)?;
if matches!(key.as_str(), "length" | "name" | "prototype") {
return Err(throw(
"not modeled: a variable path into a variables function's own properties",
));
}
return missing_text(&path).map(Some);
}
None => return Ok(None),
}
}
None => Value::Undefined,
};
for step in &steps {
let key = value::to_property_key(step).map_err(throw)?;
if !value::has_own_property(&variables, &key).map_err(throw)? {
return missing_text(&path).map(Some);
}
variables = value::get(&variables, &key).map_err(throw)?;
}
Ok(None)
}
fn missing_text(path: &Value) -> Result<String> {
value::array_method(path, "join", value::Method::ArrayJoin, "value.path").map_err(throw)?;
Ok(value::array_join(path, &Value::string("."))
.map_err(throw)?
.into_string_lossy())
}
fn variable_missing(path: &[crate::ast::PathSegment], config: &Config) -> Result<bool> {
let mut variables = match &config.variables {
Some(Variables::Value(v)) => v.clone(),
Some(Variables::Fn(_)) => {
return match path.first().map(value::property_key).as_deref() {
Some("length" | "name" | "prototype") => Err(throw(
"not modeled: a variable path into a variables function's own properties",
)),
Some(_) => Ok(true),
None => Ok(false),
};
}
None => Value::Undefined,
};
for step in path {
let key = value::property_key(step);
if !value::has_own_property(&variables, &key).map_err(throw)? {
return Ok(true);
}
variables = value::get_property(&variables, &key).map_err(throw)?;
}
Ok(false)
}
pub fn validator(node: &Node, cx: &ValidationContext<'_>) -> Result<Vec<ValidationError>> {
let config = cx.config;
let schema = find_schema(node, config).get();
let mut errors: Vec<ValidationError> = node.errors.clone();
let tag = node.tag.as_deref();
let has_tag = tag.is_some_and(|t| !t.is_empty());
let Some(schema) = schema else {
errors.push(error(
if has_tag {
"tag-undefined"
} else {
"node-undefined"
},
ValidationLevel::Critical,
if has_tag {
format!("Undefined tag: '{}'", tag.unwrap_or_default())
} else {
format!("Undefined node: '{}'", node.node_type)
},
));
return Ok(errors);
};
let tag_text = tag.unwrap_or("undefined");
if let Some(inline) = &schema.inline
&& !matches!(inline, Value::Boolean(b) if *b == node.inline)
{
errors.push(error(
"tag-placement-invalid",
ValidationLevel::Critical,
format!(
"'{tag_text}' tag should be {}",
if inline.to_boolean() {
"inline"
} else {
"block"
}
),
));
}
if schema.self_closing && !node.children.is_empty() {
errors.push(error(
"tag-selfclosing-has-children",
ValidationLevel::Critical,
format!("'{tag_text}' tag should be self-closing"),
));
}
let attributes = schema::merged_attributes(Some(schema));
for key in node.slots.keys() {
let defined = match &schema.slots {
Some(slots) => match lookup(slots, key) {
Found::Own(slot) => !slot.kind.is_falsy(),
Found::Inherited => true,
Found::Missing => false,
},
None => false,
};
if !defined {
errors.push(error(
"slot-undefined",
ValidationLevel::Error,
format!("Invalid slot: '{key}'"),
));
}
}
for (key, value) in &node.attributes {
let attrib = match lookup(&attributes, key) {
Found::Own(a) if !a.kind.is_falsy() => a,
Found::Inherited => &*INHERITED_ATTRIBUTE,
Found::Own(_) | Found::Missing => {
errors.push(error(
"attribute-undefined",
ValidationLevel::Error,
format!("Invalid attribute: '{key}'"),
));
continue;
}
};
let level = attrib.error_level.clone().unwrap_or(ValidationLevel::Error);
if is_ast(value) {
if is_function(value) && config.validation.validate_functions {
errors.extend(validate_function(value, cx)?);
} else if is_variable(value) && variables_truthy(config) {
let missing = match value {
Scalar::Variable(v) => variable_missing(&v.path, config)?.then(|| {
let path: Vec<String> = v.path.iter().map(value::property_key).collect();
path.join(".")
}),
Scalar::Js(js) => js_variable_missing(js.value(), config)?,
_ => unreachable!("a variable"),
};
if let Some(path) = missing {
errors.push(error(
"variable-undefined",
ValidationLevel::Error,
format!("Undefined variable: '{path}'"),
));
}
} else {
continue;
}
}
if let Some(t) = &attrib.attr_type {
match validate_type(t, value, cx, key)? {
Valid::Bool(false) => errors.push(error(
"attribute-type-invalid",
level.clone(),
format!("Attribute '{key}' must be type of '{}'", type_to_string(t)),
)),
Valid::Errors(e) => errors.extend(e),
Valid::Bool(true) => {}
}
}
let matches = match &attrib.matches {
Some(Matches::Fn(f)) => Some(f(cx)),
Some(Matches::Call(f)) => Some(call_matches(*f)?),
other => other.clone(),
};
if let Some(Matches::Array(list)) = &matches
&& !includes(list, value)
{
errors.push(error(
"attribute-value-invalid",
level.clone(),
format!(
"Attribute '{key}' must match one of {}. Got '{}' instead.",
display_matches(list, 8)?,
scalar_to_js_string(value).map_err(throw)?
),
));
}
if let Some(Matches::RegExp(regexp)) = &matches
&& !regexp
.test(&scalar_to_js_string(value).map_err(throw)?)
.map_err(throw)?
{
errors.push(error(
"attribute-value-invalid",
level.clone(),
format!(
"Attribute '{key}' must match {}. Got '{}' instead.",
regexp.to_js_string(),
scalar_to_js_string(value).map_err(throw)?
),
));
}
if let Some(validate) = &attrib.validate {
errors.extend(validate(value, cx, key)?);
}
}
for (key, attr) in &attributes {
attr.kind.read("required").map_err(throw)?;
if attr.required && attribute_undefined(node, key)? {
errors.push(error(
"attribute-missing-required",
ValidationLevel::Error,
format!("Missing required attribute: '{key}'"),
));
}
}
if let Some(slots) = &schema.slots {
for (key, slot) in slots {
slot.kind.read("required").map_err(throw)?;
if slot.required && slot_undefined(node, key) {
errors.push(error(
"slot-missing-required",
ValidationLevel::Error,
format!("Missing required slot: '{key}'"),
));
}
}
}
for child in &node.children {
let child_type = child.node_type.as_str();
if child_type != "error"
&& let Some(allowed) = schema.allows_child(child_type)
&& !allowed.map_err(throw)?
{
let parent = match tag {
Some(t) if !t.is_empty() => t.to_string(),
_ => node.node_type.to_string(),
};
errors.push(error(
"child-invalid",
ValidationLevel::Warning,
format!("Can't nest '{child_type}' in '{parent}'"),
));
}
}
if let Some(validate) = &schema.validate {
errors.extend(validate(node, cx)?);
}
Ok(errors)
}
fn attribute_undefined(node: &Node, key: &str) -> Result<bool> {
if let Some(v) = node.attributes.get(key) {
return Ok(matches!(v, Scalar::Undefined));
}
Ok(match node.attributes_prototype.as_deref() {
None => !value::is_object_prototype_name(key),
Some(Scalar::Null) => true,
Some(proto) => value::is_undefined_at(&Value::from_scalar(proto), key).map_err(throw)?,
})
}
fn slot_undefined(node: &Node, key: &str) -> bool {
if node.slots.contains_key(key) {
return false;
}
match node.slots_prototype.as_deref() {
None => is_undefined_in(&node.slots, key),
Some(proto) => !node_property_defined(proto, key),
}
}
fn node_property_defined(node: &Node, key: &str) -> bool {
match key {
"$$mdtype" | "errors" | "lines" | "inline" | "attributes" | "children" | "type"
| "annotations" | "slots" => true,
"tag" => node.tag.is_some(),
"location" => node.location.is_some(),
_ => realm::has_inherited(BuiltinProto::NODE_PROTOTYPE, key),
}
}
pub const MAX_VALIDATE_DEPTH: usize = 4046;
pub(crate) const VALIDATE_COST: u64 = crate::depth::per_level(MAX_VALIDATE_DEPTH as u64);
pub(crate) const STACK_OVERFLOW: &str = "RangeError: Maximum call stack size exceeded";
pub fn walk_with_parents<'a, E>(
node: &'a Node,
mut visit: impl FnMut(&'a Node, &[&'a Node]) -> std::result::Result<(), E>,
) -> std::result::Result<(), E> {
let mut path: Vec<&'a Node> = Vec::new();
let mut next: Vec<usize> = Vec::new();
visit(node, &path)?;
path.push(node);
next.push(0);
while let (Some(¤t), Some(k)) = (path.last(), next.last_mut()) {
let child = match current.slots.get_index(*k) {
Some((_, slot)) => Some(slot),
None => current.children.get(*k - current.slots.len()),
};
match child {
Some(child) => {
*k += 1;
visit(child, &path)?;
path.push(child);
next.push(0);
}
None => {
path.pop();
next.pop();
}
}
}
Ok(())
}
pub(crate) fn deeper_than(node: &Node, limit: usize) -> bool {
struct Deep;
walk_with_parents(node, |_, parents| {
if parents.len() >= limit {
Err(Deep)
} else {
Ok(())
}
})
.is_err()
}
fn valid_location_lines(location: Option<&Json>) -> Option<[f64; 2]> {
let location = location?;
let line = |edge: &str| {
location
.get(edge)?
.as_object()?
.get("line")
.and_then(Json::as_f64)
};
let lines = [line("start")?, line("end")?];
match location.get("file") {
None | Some(Json::String(_)) => Some(lines),
Some(_) => None,
}
}
fn to_validate_error(node: &Node, error: ValidationError) -> Result<ValidateError> {
if error.raw.as_deref() == Some(&Json::Null) {
return Err(throw(
"TypeError: Cannot read properties of null (reading 'location')",
));
}
let span = error.span.clone().or_else(|| node.span.clone());
if let Some([start, end]) = valid_location_lines(error.location.as_ref()) {
let mut file = node
.location
.as_ref()
.and_then(|l| l.file.as_deref())
.map(|f| Json::String(f.to_string()));
let mut rest = Vec::new();
for (key, value) in error.location.iter().flat_map(|l| l.as_object()).flatten() {
if key == "file" {
file = Some(value.clone());
} else {
rest.push((key.clone(), value.clone()));
}
}
let location = js_object(
file.map(|f| ("file".to_string(), f))
.into_iter()
.chain(rest),
);
return Ok(ValidateError {
node_type: node.node_type.clone(),
lines: vec![start, end],
location: Some(ValidateLocation::Error(location)),
error,
span,
});
}
Ok(ValidateError {
node_type: node.node_type.clone(),
lines: node.lines.iter().map(|&l| l as f64).collect(),
location: node.location.clone().map(ValidateLocation::Node),
error,
span,
})
}
fn js_object(entries: impl Iterator<Item = (String, Json)>) -> Json {
let mut entries: Vec<(String, Json)> = entries.collect();
let rank = |key: &str| crate::types::array_index(key).map_or((1, 0), |n| (0, n));
entries.sort_by_key(|(key, _)| rank(key));
Json::Object(entries.into_iter().collect())
}
pub fn validate_tree(content: &Node, config: &Config) -> Result<Vec<ValidateError>> {
let limit = usize::try_from(crate::depth::left() / VALIDATE_COST).unwrap_or(usize::MAX);
if deeper_than(content, limit) {
return Err(throw(STACK_OVERFLOW));
}
let mut output = Vec::new();
walk_with_parents(content, |node, parents| {
let cx = ValidationContext { config, parents };
for error in validator(node, &cx)? {
output.push(to_validate_error(node, error)?);
}
Ok(())
})?;
Ok(output)
}
#[cfg(test)]
mod tests;