use thiserror::Error;
pub type Result<T> = std::result::Result<T, SynalogError>;
#[derive(Error, Debug)]
pub enum SynalogError {
#[error(transparent)]
Parse(#[from] ParseError),
#[error(transparent)]
Compile(#[from] CompileError),
#[error(transparent)]
Verify(#[from] VerifyError),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
}
#[derive(Error, Debug, Clone)]
pub enum ParseError {
#[error("Syntax error: {message}")]
Syntax {
message: String,
#[source]
location: Option<SourceLocation>,
},
}
#[derive(Debug, Clone)]
pub struct SourceLocation {
pub before: String,
pub highlighted: String,
pub after: String,
pub line: Option<usize>,
pub column: Option<usize>,
}
impl std::fmt::Display for SourceLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let (Some(line), Some(col)) = (self.line, self.column) {
write!(f, "at line {}, column {}", line, col)
} else {
write!(f, "at '{}'", self.highlighted)
}
}
}
impl std::error::Error for SourceLocation {}
#[derive(Error, Debug, Clone)]
pub enum CompileError {
#[error("Compile error: {message}")]
Generic { message: String, rule: String },
}
#[derive(Error, Debug, Clone)]
pub enum VerifyError {
#[error("Unbound variable '{var}' in head of rule: {rule}")]
UnboundHeadVar { var: String, rule: String },
#[error("Unsafe negation: variable '{var}' only appears negated in: {rule}")]
UnsafeNegation { var: String, rule: String },
#[error("Unsafe aggregation: variable '{var}' not bound outside aggregate in: {rule}")]
UnsafeAggregation { var: String, rule: String },
#[error("Negative recursion cycle: {}", predicates.join(" -> "))]
NegativeCycle { predicates: Vec<String> },
#[error("Recursive predicate '{predicate}' has no base case")]
NoBaseCase { predicate: String, rule: String },
#[error("Trivial infinite loop: '{predicate}' calls itself with same arguments")]
TrivialLoop { predicate: String, rule: String },
#[error("Recursive predicate '{predicate}' missing @Recursive annotation")]
UnboundedRecursion { predicate: String, rule: String },
#[error("Arity mismatch for '{predicate}': expected {expected}, got {actual}")]
ArityMismatch {
predicate: String,
expected: usize,
actual: usize,
},
#[error("Unknown column '{column}' for predicate '{predicate}'")]
UnknownColumn { predicate: String, column: String },
#[error("Reserved predicate name '{predicate}': it is a built-in library predicate and cannot be redefined")]
ReservedPredicateName { predicate: String },
#[error("Unsafe SqlExpr in rule '{predicate}': raw SQL bypasses verification and portability")]
UnsafeSqlExpr { predicate: String },
#[error("Positional arguments in '{predicate}': Synalog requires named arguments; use `field_name: value` instead of positional arguments")]
PositionalArguments { predicate: String },
#[error("Undefined predicate '{predicate}'{}", match suggestion {
Some(s) => format!(" — did you mean '{}'?", s),
None => String::new(),
})]
UndefinedPredicate {
predicate: String,
suggestion: Option<String>,
rule: String,
},
}
#[derive(Debug, Default)]
pub struct VerifyResult {
pub errors: Vec<VerifyError>,
pub warnings: Vec<String>,
}
impl VerifyResult {
pub fn ok() -> Self {
Self::default()
}
pub fn is_valid(&self) -> bool {
self.errors.is_empty()
}
pub fn add_error(&mut self, error: VerifyError) {
self.errors.push(error);
}
pub fn add_warning(&mut self, warning: impl Into<String>) {
self.warnings.push(warning.into());
}
pub fn merge(&mut self, other: VerifyResult) {
self.errors.extend(other.errors);
self.warnings.extend(other.warnings);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_error_display() {
let err = ParseError::Syntax {
message: "unexpected token '}'".to_string(),
location: None,
};
assert!(err.to_string().contains("unexpected token"));
}
#[test]
fn test_compile_error_display() {
let err = CompileError::Generic {
message: "boom".to_string(),
rule: "Test(x) :- Foo(x)".to_string(),
};
assert!(err.to_string().contains("boom"));
}
#[test]
fn test_verify_error_display() {
let err = VerifyError::UnboundHeadVar {
var: "y".to_string(),
rule: "Test(x, y) :- Source(x)".to_string(),
};
assert!(err.to_string().contains("Unbound variable 'y'"));
}
#[test]
fn test_negative_cycle_display() {
let err = VerifyError::NegativeCycle {
predicates: vec!["A".to_string(), "B".to_string(), "C".to_string()],
};
assert!(err.to_string().contains("A -> B -> C"));
}
#[test]
fn test_verify_result() {
let mut result = VerifyResult::ok();
assert!(result.is_valid());
result.add_error(VerifyError::UnboundHeadVar {
var: "x".to_string(),
rule: "Test(x) :- Source()".to_string(),
});
assert!(!result.is_valid());
}
}