use crate::OutputFormat;
pub const MAX_INPUT_SIZE: usize = 10 * 1024 * 1024;
pub const MAX_YAML_SIZE: usize = 1024 * 1024;
pub const MAX_NESTING_DEPTH: usize = 100;
pub use crate::document::limits::MAX_YAML_DEPTH;
pub const MAX_CARD_COUNT: usize = 1000;
pub const MAX_FIELD_COUNT: usize = 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Error,
Warning,
Note,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Location {
pub file: String,
pub line: u32,
pub column: u32,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Diagnostic {
pub severity: Severity,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub code: Option<String>,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub location: Option<Location>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub hint: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub source_chain: Vec<String>,
}
impl Diagnostic {
pub fn new(severity: Severity, message: String) -> Self {
Self {
severity,
code: None,
message,
location: None,
hint: None,
source_chain: Vec::new(),
}
}
pub fn with_code(mut self, code: String) -> Self {
self.code = Some(code);
self
}
pub fn with_location(mut self, location: Location) -> Self {
self.location = Some(location);
self
}
pub fn with_hint(mut self, hint: String) -> Self {
self.hint = Some(hint);
self
}
pub fn with_source(mut self, source: &(dyn std::error::Error + 'static)) -> Self {
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(source);
while let Some(err) = current {
self.source_chain.push(err.to_string());
current = err.source();
}
self
}
pub fn fmt_pretty(&self) -> String {
let mut result = format!(
"[{}] {}",
match self.severity {
Severity::Error => "ERROR",
Severity::Warning => "WARN",
Severity::Note => "NOTE",
},
self.message
);
if let Some(ref code) = self.code {
result.push_str(&format!(" ({})", code));
}
if let Some(ref loc) = self.location {
result.push_str(&format!("\n --> {}:{}:{}", loc.file, loc.line, loc.column));
}
if let Some(ref hint) = self.hint {
result.push_str(&format!("\n hint: {}", hint));
}
result
}
pub fn fmt_pretty_with_source(&self) -> String {
let mut result = self.fmt_pretty();
for (i, cause) in self.source_chain.iter().enumerate() {
result.push_str(&format!("\n cause {}: {}", i + 1, cause));
}
result
}
}
impl std::fmt::Display for Diagnostic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
#[derive(thiserror::Error, Debug)]
pub enum ParseError {
#[error("Input too large: {size} bytes (max: {max} bytes)")]
InputTooLarge {
size: usize,
max: usize,
},
#[error("Invalid YAML structure: {0}")]
InvalidStructure(String),
#[error("{0}")]
EmptyInput(String),
#[error("{0}")]
MissingQuillField(String),
#[error("YAML error at line {line}: {message}")]
YamlErrorWithLocation {
message: String,
line: usize,
block_index: usize,
},
#[error("{0}")]
Other(String),
}
impl ParseError {
pub fn to_diagnostic(&self) -> Diagnostic {
match self {
ParseError::InputTooLarge { size, max } => Diagnostic::new(
Severity::Error,
format!("Input too large: {} bytes (max: {} bytes)", size, max),
)
.with_code("parse::input_too_large".to_string()),
ParseError::InvalidStructure(msg) => Diagnostic::new(Severity::Error, msg.clone())
.with_code("parse::invalid_structure".to_string()),
ParseError::EmptyInput(msg) => Diagnostic::new(Severity::Error, msg.clone())
.with_code("parse::empty_input".to_string()),
ParseError::MissingQuillField(msg) => Diagnostic::new(Severity::Error, msg.clone())
.with_code("parse::missing_quill_field".to_string()),
ParseError::YamlErrorWithLocation {
message,
line,
block_index,
} => Diagnostic::new(
Severity::Error,
format!(
"YAML error at line {} (block {}): {}",
line, block_index, message
),
)
.with_code("parse::yaml_error_with_location".to_string()),
ParseError::Other(msg) => Diagnostic::new(Severity::Error, msg.clone()),
}
}
}
impl From<Box<dyn std::error::Error + Send + Sync>> for ParseError {
fn from(err: Box<dyn std::error::Error + Send + Sync>) -> Self {
ParseError::Other(err.to_string())
}
}
impl From<String> for ParseError {
fn from(msg: String) -> Self {
ParseError::Other(msg)
}
}
impl From<&str> for ParseError {
fn from(msg: &str) -> Self {
ParseError::Other(msg.to_string())
}
}
#[derive(thiserror::Error, Debug)]
pub enum RenderError {
#[error("{diag}")]
EngineCreation {
diag: Box<Diagnostic>,
},
#[error("{diag}")]
InvalidFrontmatter {
diag: Box<Diagnostic>,
},
#[error("Backend compilation failed with {} error(s)", diags.len())]
CompilationFailed {
diags: Vec<Diagnostic>,
},
#[error("{diag}")]
FormatNotSupported {
diag: Box<Diagnostic>,
},
#[error("{diag}")]
UnsupportedBackend {
diag: Box<Diagnostic>,
},
#[error("{diag}")]
ValidationFailed {
diag: Box<Diagnostic>,
},
#[error("Quill configuration failed with {} error(s)", diags.len())]
QuillConfig {
diags: Vec<Diagnostic>,
},
}
impl RenderError {
pub fn diagnostics(&self) -> Vec<&Diagnostic> {
match self {
RenderError::CompilationFailed { diags } | RenderError::QuillConfig { diags } => {
diags.iter().collect()
}
RenderError::EngineCreation { diag }
| RenderError::InvalidFrontmatter { diag }
| RenderError::FormatNotSupported { diag }
| RenderError::UnsupportedBackend { diag }
| RenderError::ValidationFailed { diag } => vec![diag.as_ref()],
}
}
}
impl From<ParseError> for RenderError {
fn from(err: ParseError) -> Self {
RenderError::InvalidFrontmatter {
diag: Box::new(
Diagnostic::new(Severity::Error, err.to_string())
.with_code("parse::error".to_string()),
),
}
}
}
#[derive(Debug)]
pub struct RenderResult {
pub artifacts: Vec<crate::Artifact>,
pub warnings: Vec<Diagnostic>,
pub output_format: OutputFormat,
}
impl RenderResult {
pub fn new(artifacts: Vec<crate::Artifact>, output_format: OutputFormat) -> Self {
Self {
artifacts,
warnings: Vec::new(),
output_format,
}
}
pub fn with_warning(mut self, warning: Diagnostic) -> Self {
self.warnings.push(warning);
self
}
}
pub fn print_errors(err: &RenderError) {
for d in err.diagnostics() {
eprintln!("{}", d.fmt_pretty());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_diagnostic_with_source_chain() {
let root_err = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
let diag =
Diagnostic::new(Severity::Error, "Rendering failed".to_string()).with_source(&root_err);
assert_eq!(diag.source_chain.len(), 1);
assert!(diag.source_chain[0].contains("File not found"));
}
#[test]
fn test_diagnostic_serialization() {
let diag = Diagnostic::new(Severity::Error, "Test error".to_string())
.with_code("E001".to_string())
.with_location(Location {
file: "test.typ".to_string(),
line: 10,
column: 5,
});
let json = serde_json::to_string(&diag).unwrap();
assert!(json.contains("Test error"));
assert!(json.contains("E001"));
assert!(json.contains("\"severity\":\"error\""));
assert!(json.contains("\"column\":5"));
}
#[test]
fn test_render_error_diagnostics_extraction() {
let diag1 = Diagnostic::new(Severity::Error, "Error 1".to_string());
let diag2 = Diagnostic::new(Severity::Error, "Error 2".to_string());
let err = RenderError::CompilationFailed {
diags: vec![diag1, diag2],
};
let diags = err.diagnostics();
assert_eq!(diags.len(), 2);
}
#[test]
fn test_diagnostic_fmt_pretty() {
let diag = Diagnostic::new(Severity::Warning, "Deprecated field used".to_string())
.with_code("W001".to_string())
.with_location(Location {
file: "input.md".to_string(),
line: 5,
column: 10,
})
.with_hint("Use the new field name instead".to_string());
let output = diag.fmt_pretty();
assert!(output.contains("[WARN]"));
assert!(output.contains("Deprecated field used"));
assert!(output.contains("W001"));
assert!(output.contains("input.md:5:10"));
assert!(output.contains("hint:"));
}
#[test]
fn test_diagnostic_fmt_pretty_with_source() {
let root_err = std::io::Error::other("Underlying error");
let diag = Diagnostic::new(Severity::Error, "Top-level error".to_string())
.with_code("E002".to_string())
.with_source(&root_err);
let output = diag.fmt_pretty_with_source();
assert!(output.contains("[ERROR]"));
assert!(output.contains("Top-level error"));
assert!(output.contains("cause 1:"));
assert!(output.contains("Underlying error"));
}
#[test]
fn test_render_result_with_warnings() {
let artifacts = vec![];
let warning = Diagnostic::new(Severity::Warning, "Test warning".to_string());
let result = RenderResult::new(artifacts, OutputFormat::Pdf).with_warning(warning);
assert_eq!(result.warnings.len(), 1);
assert_eq!(result.warnings[0].message, "Test warning");
}
}