use std::path::PathBuf;
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Position {
pub line: usize,
pub column: usize,
pub offset: usize,
}
impl Position {
pub fn new(line: usize, column: usize, offset: usize) -> Self {
Self {
line,
column,
offset,
}
}
pub fn start() -> Self {
Self::new(1, 1, 0)
}
pub fn advance(&mut self, ch: char) {
if ch == '\n' {
self.line += 1;
self.column = 1;
} else {
self.column += 1;
}
self.offset += ch.len_utf8();
}
pub fn advance_str(&mut self, s: &str) {
for ch in s.chars() {
self.advance(ch);
}
}
}
impl std::fmt::Display for Position {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", self.line, self.column)
}
}
#[derive(Error, Debug)]
pub enum LatexError {
#[error("Parse error: {message}{line_info}{column_info}{context_info}",
line_info = line.map(|l| format!(" at line {}", l)).unwrap_or_default(),
column_info = column.map(|c| format!(", column {}", c)).unwrap_or_default(),
context_info = context.as_ref().map(|ctx| format!("\nContext: {}", ctx)).unwrap_or_default()
)]
ParseError {
message: String,
line: Option<usize>,
column: Option<usize>,
context: Option<String>,
},
#[error("PDF generation error: {message}{context_info}",
context_info = context.as_ref().map(|ctx| format!("\nContext: {}", ctx)).unwrap_or_default()
)]
PdfError {
message: String,
context: Option<String>,
},
#[error("I/O error for file '{path}': {source}")]
IoError {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("Font error for '{font_name}': {message}")]
FontError { font_name: String, message: String },
#[error("Math error in '{expression}': {message}")]
MathError { expression: String, message: String },
#[error("Configuration error: {message}")]
ConfigError { message: String },
#[error("Unsupported feature: {feature}{suggestion_info}",
suggestion_info = suggestion.as_ref().map(|s| format!("\nSuggestion: {}", s)).unwrap_or_default()
)]
UnsupportedFeature {
feature: String,
suggestion: Option<String>,
},
#[error("Invalid file path")]
InvalidPath,
}
pub type Result<T> = std::result::Result<T, LatexError>;
impl From<String> for LatexError {
fn from(message: String) -> Self {
LatexError::PdfError {
message,
context: None,
}
}
}
impl From<&str> for LatexError {
fn from(message: &str) -> Self {
LatexError::PdfError {
message: message.to_string(),
context: None,
}
}
}
impl From<std::io::Error> for LatexError {
fn from(error: std::io::Error) -> Self {
LatexError::IoError {
path: PathBuf::from("<unknown>"),
source: error,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_position_start() {
let p = Position::start();
assert_eq!(p.line, 1);
assert_eq!(p.column, 1);
assert_eq!(p.offset, 0);
assert_eq!(p.to_string(), "1:1");
}
#[test]
fn test_position_advance() {
let mut p = Position::start();
p.advance('a');
assert_eq!(p.line, 1);
assert_eq!(p.column, 2);
assert_eq!(p.offset, 1);
p.advance('\n');
assert_eq!(p.line, 2);
assert_eq!(p.column, 1);
assert_eq!(p.offset, 2);
}
#[test]
fn test_position_advance_str() {
let mut p = Position::start();
p.advance_str("hi\nworld");
assert_eq!(p.line, 2);
assert_eq!(p.column, 6);
assert_eq!(p.offset, 8);
}
#[test]
fn test_parse_error_display() {
let err = LatexError::ParseError {
message: "Unexpected token".to_string(),
line: Some(42),
column: Some(10),
context: Some("\\begin{document}".to_string()),
};
let display = format!("{}", err);
assert!(display.contains("Parse error"));
assert!(display.contains("line 42"));
assert!(display.contains("column 10"));
}
#[test]
fn test_unsupported_feature() {
let err = LatexError::UnsupportedFeature {
feature: "\\usepackage{tikz}".to_string(),
suggestion: Some("Use external LaTeX for TikZ diagrams".to_string()),
};
let display = format!("{}", err);
assert!(display.contains("Unsupported feature"));
assert!(display.contains("Suggestion"));
}
#[test]
fn test_unsupported_feature_no_suggestion() {
let err = LatexError::UnsupportedFeature {
feature: "custom macro".to_string(),
suggestion: None,
};
let display = format!("{}", err);
assert!(display.contains("Unsupported feature"));
assert!(!display.contains("Suggestion"));
}
#[test]
fn test_string_to_error_conversion() {
let err: LatexError = "something went wrong".into();
match err {
LatexError::PdfError { message, .. } => assert_eq!(message, "something went wrong"),
_ => panic!("expected PdfError"),
}
}
#[test]
fn test_io_error_conversion() {
let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
let err: LatexError = io_err.into();
match err {
LatexError::IoError { .. } => {}
_ => panic!("expected IoError"),
}
}
#[test]
fn test_invalid_path_display() {
let err = LatexError::InvalidPath;
assert_eq!(format!("{}", err), "Invalid file path");
}
#[test]
fn test_parse_error_without_context() {
let err = LatexError::ParseError {
message: "Unexpected EOF".to_string(),
line: None,
column: None,
context: None,
};
let display = format!("{}", err);
assert!(display.contains("Parse error"));
assert!(!display.contains("line"));
}
}