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,
}
}
pub(crate) fn noml_error(error: noml::NomlError, format: &str) -> Error {
use noml::NomlError as E;
match error {
E::Parse {
message,
line,
column,
..
} => {
let what = if message.starts_with("Environment variable") {
"an env() variable is not set and has no default"
} else if message.starts_with("Duplicate key") {
"a key is defined twice"
} else if message.starts_with("Value is nested deeper") {
"values are nested too deeply"
} else if message.starts_with("Unknown function") {
"unknown function"
} else if message.starts_with("Unknown native type") {
"unknown native type"
} else if message.starts_with("Maximum include depth") {
"includes are nested too deeply"
} else if message.starts_with("include can only") {
"include is only allowed as the value of a key or an array element"
} else {
"syntax error"
};
Error::parse(format!("{format} {what}"), line, column)
}
E::Interpolation { .. } => Error::general(format!(
"{format}: a ${{...}} reference could not be resolved"
)),
E::CircularReference { .. } => {
Error::general(format!("{format}: a reference or include refers to itself"))
}
E::EnvVar { .. } => Error::general(format!(
"{format}: an env() variable is not set and has no default"
)),
E::Import { .. } | E::Io { .. } => {
Error::general(format!("{format}: an included file could not be read"))
}
_ => Error::general(format!("{format}: the document is not valid")),
}
}