use crate::dsl::error::{Diagnostics, PrintError};
use crate::dsl::{parse, print};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FormatError {
Parse(Diagnostics),
Print(PrintError),
}
impl std::fmt::Display for FormatError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FormatError::Parse(found) => write!(f, "{found}"),
FormatError::Print(err) => write!(f, "the source cannot be written back: {err}"),
}
}
}
impl std::error::Error for FormatError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
FormatError::Parse(found) => Some(found),
FormatError::Print(err) => Some(err),
}
}
}
pub fn format(file: &str, text: &str) -> Result<String, FormatError> {
let parsed = parse(file, text).map_err(FormatError::Parse)?;
print(&parsed.policy, parsed.language).map_err(FormatError::Print)
}
pub fn is_formatted(file: &str, text: &str) -> Result<bool, FormatError> {
Ok(format(file, text)? == text)
}