use std::fmt::Write as _;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SyntaxIssue {
pub message: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CrosswalkIssue {
pub rule_index: i64,
pub message: String,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum CrossmapError {
#[error("crosswalk syntax error: {}", syntax_message(.issues))]
Syntax {
issues: Vec<SyntaxIssue>,
},
#[error("crosswalk structure error: {}", structure_message(.issues))]
Structure {
issues: Vec<CrosswalkIssue>,
},
#[error("{}", rule_application_message(*.rule_index, .path, .detail))]
RuleApplication {
rule_index: i64,
path: String,
detail: String,
},
#[error("sample {sample_index} ({path}): {detail}")]
RoundTripMismatch {
sample_index: usize,
path: String,
detail: String,
},
#[error("{message}")]
WhenEvaluation {
message: String,
},
}
impl CrossmapError {
pub fn class_name(&self) -> &'static str {
match self {
Self::Syntax { .. } => "CrosswalkSyntaxError",
Self::Structure { .. } => "CrosswalkStructureError",
Self::RuleApplication { .. } => "RuleApplicationError",
Self::RoundTripMismatch { .. } => "RoundTripMismatchError",
Self::WhenEvaluation { .. } => "Error",
}
}
pub(crate) fn rule(
rule_index: usize,
path: impl Into<String>,
detail: impl Into<String>,
) -> Self {
Self::RuleApplication {
rule_index: i64::try_from(rule_index).unwrap_or(i64::MAX),
path: path.into(),
detail: detail.into(),
}
}
pub(crate) fn syntax(message: impl Into<String>) -> Self {
Self::Syntax {
issues: vec![SyntaxIssue {
message: message.into(),
}],
}
}
}
fn syntax_message(issues: &[SyntaxIssue]) -> String {
let parts: Vec<&str> = issues.iter().map(|issue| issue.message.as_str()).collect();
parts.join("; ")
}
fn structure_message(issues: &[CrosswalkIssue]) -> String {
let mut text = String::new();
for (position, issue) in issues.iter().enumerate() {
if position > 0 {
text.push_str("; ");
}
if issue.rule_index < 0 {
text.push_str(&issue.message);
} else {
let _ = write!(text, "rule {}: {}", issue.rule_index, issue.message);
}
}
text
}
fn rule_application_message(rule_index: i64, path: &str, detail: &str) -> String {
if rule_index < 0 {
format!("{path}: {detail}")
} else {
format!("rule {rule_index} ({path}): {detail}")
}
}