use crate::error::{Error, Result};
use noml::parser::ast::{AstNode, AstValue};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Policy {
Toml,
#[cfg_attr(not(feature = "noml"), allow(dead_code))]
StrictNoml,
}
impl Policy {
fn format(self) -> &'static str {
match self {
Policy::Toml => "TOML",
Policy::StrictNoml => "strict NOML",
}
}
}
pub(crate) fn check(document: &noml::Document, policy: Policy) -> Result<()> {
let mut pending: Vec<&AstNode> = vec![&document.root];
while let Some(node) = pending.pop() {
if let Some(what) = refused(&node.value, policy) {
return Err(Error::parse(
format!("{what} is not allowed in {}", policy.format()),
node.span.start_line,
node.span.start_column,
));
}
match &node.value {
AstValue::Array { elements, .. } => pending.extend(elements.iter().rev()),
AstValue::Table { entries, .. } => {
pending.extend(entries.iter().rev().map(|entry| &entry.value));
}
AstValue::FunctionCall { args, .. } | AstValue::Native { args, .. } => {
pending.extend(args.iter().rev());
}
_ => {}
}
}
Ok(())
}
fn refused(value: &AstValue, policy: Policy) -> Option<&'static str> {
match value {
AstValue::Include { .. } => Some("include"),
AstValue::FunctionCall { name, .. } if name == "env" => Some("env()"),
AstValue::FunctionCall { .. } => Some("a function call"),
AstValue::Native { .. } if policy == Policy::Toml => Some("a native type (@type)"),
AstValue::Interpolation { .. } if policy == Policy::Toml => {
Some("an interpolation (${...})")
}
_ => None,
}
}