use thiserror::Error;
use std::fmt;
pub type Result<T> = std::result::Result<T, HyperQLError>;
#[derive(Error, Debug)]
pub enum HyperQLError {
#[error("Parse error at line {line}, column {column}: {message}")]
ParseError {
message: String,
line: usize,
column: usize,
source_text: Option<String>,
error_code: Option<String>,
suggestions: Vec<String>,
examples: Vec<String>,
position: Option<usize>,
},
#[error("Semantic error: {message}")]
SemanticError {
message: String,
context: Vec<String>,
},
#[error("Validation error: {message}{}", field.as_ref().map(|f| format!(" in field '{}'", f)).unwrap_or_default())]
ValidationError {
message: String,
field: Option<String>,
},
#[error("Type error: expected {expected}, found {found} in {context}")]
TypeError {
expected: String,
found: String,
context: String,
},
#[error("Undefined {ref_type}: '{name}'")]
UndefinedReference {
name: String,
ref_type: String,
available: Vec<String>,
suggestions: Vec<String>,
context: Option<String>,
error_code: Option<String>,
},
#[error("Execution error: {message}")]
ExecutionError {
message: String,
operation: String,
entity_context: Option<String>,
},
#[error("Geometric error: {operation} failed - {reason}")]
GeometricError {
operation: String,
reason: String,
positions: Vec<String>,
},
#[error("Cascade error: {message} in measure {measure_name}")]
CascadeError {
message: String,
measure_name: String,
propagation_path: Vec<String>,
},
#[error("Database error: {message}")]
DatabaseError {
message: String,
operation: String,
#[source]
source: Option<Box<dyn std::error::Error + Send + Sync>>,
},
#[error("Resource error: {resource} {constraint}")]
ResourceError {
resource: String,
constraint: String,
current_usage: Option<String>,
},
#[error("Internal error: {message} - this indicates a bug")]
InternalError {
message: String,
component: String,
debug_info: String,
},
#[error("Builder error: {}", errors.join("; "))]
BuilderError {
errors: Vec<String>,
},
}
#[derive(Debug, Clone)]
pub struct ErrorContext {
pub query_text: String,
pub position: Option<usize>,
pub line: Option<usize>,
pub column: Option<usize>,
pub problematic_text: Option<String>,
pub suggestions: Vec<String>,
pub examples: Vec<String>,
pub error_code: Option<String>,
}
impl ErrorContext {
pub fn new(query_text: String, position: Option<usize>) -> Self {
let (line, column) = if let Some(pos) = position {
Self::calculate_line_column(&query_text, pos)
} else {
(None, None)
};
Self {
query_text,
position,
line,
column,
problematic_text: None,
suggestions: Vec::new(),
examples: Vec::new(),
error_code: None,
}
}
fn calculate_line_column(text: &str, position: usize) -> (Option<usize>, Option<usize>) {
let mut line = 1;
let mut column = 1;
let mut current_pos = 0;
for ch in text.chars() {
if current_pos >= position {
break;
}
if ch == '\n' {
line += 1;
column = 1;
} else {
column += 1;
}
current_pos += ch.len_utf8();
}
(Some(line), Some(column))
}
pub fn with_problematic_text(mut self) -> Self {
if let Some(pos) = self.position {
let start = pos.saturating_sub(30);
let end = (pos + 30).min(self.query_text.len());
if let Some(text) = self.query_text.get(start..end) {
self.problematic_text = Some(text.to_string());
}
}
self
}
pub fn add_suggestion(mut self, suggestion: impl Into<String>) -> Self {
self.suggestions.push(suggestion.into());
self
}
pub fn add_example(mut self, example: impl Into<String>) -> Self {
self.examples.push(example.into());
self
}
pub fn with_error_code(mut self, code: impl Into<String>) -> Self {
self.error_code = Some(code.into());
self
}
pub fn get_line_at(&self, line_num: usize) -> Option<String> {
self.query_text
.lines()
.nth(line_num - 1)
.map(|s| s.to_string())
}
pub fn get_token_length_at_position(&self) -> Option<usize> {
if let Some(pos) = self.position {
let remaining = &self.query_text[pos..];
let token_end = remaining
.chars()
.position(|c| c.is_whitespace() || "()[]{},.;:".contains(c))
.unwrap_or(remaining.chars().count());
let prefix = &self.query_text[..pos];
let token_start_offset = prefix
.chars()
.rev()
.position(|c| c.is_whitespace() || "()[]{},.;:".contains(c))
.unwrap_or(prefix.chars().count());
Some(token_start_offset + token_end)
} else {
None
}
}
}
pub trait WithContext<T> {
fn with_context(self, query: &str, position: Option<usize>) -> Result<T>;
}
impl<T, E> WithContext<T> for std::result::Result<T, E>
where
E: fmt::Debug,
{
fn with_context(self, query: &str, position: Option<usize>) -> Result<T> {
match self {
Ok(value) => Ok(value),
Err(err) => {
let error_msg = format!("{:?}", err);
let mut context = ErrorContext::new(query.to_string(), position)
.with_problematic_text()
.with_error_code("E001");
if error_msg.to_lowercase().contains("expected") {
context = context.add_suggestion("Check syntax documentation for correct format");
}
Err(HyperQLError::ParseError {
message: error_msg,
line: context.line.unwrap_or(1),
column: context.column.unwrap_or(1),
source_text: Some(query.to_string()),
error_code: context.error_code.clone(),
suggestions: context.suggestions.clone(),
examples: context.examples.clone(),
position: context.position,
})
}
}
}
}
impl HyperQLError {
pub fn parse_error_with_context(
message: impl Into<String>,
query: &str,
position: Option<usize>,
) -> Self {
let context = ErrorContext::new(query.to_string(), position);
HyperQLError::ParseError {
message: message.into(),
line: context.line.unwrap_or(1),
column: context.column.unwrap_or(1),
source_text: Some(query.to_string()),
error_code: None,
suggestions: Vec::new(),
examples: Vec::new(),
position: context.position,
}
}
pub fn undefined_reference_with_suggestions(
name: impl Into<String>,
ref_type: impl Into<String>,
available: Vec<String>,
context: Option<String>,
) -> Self {
let name = name.into();
let suggestions = crate::error_context::SuggestionGenerator::find_similar_names(
&name,
&available,
);
HyperQLError::UndefinedReference {
name,
ref_type: ref_type.into(),
available,
suggestions,
context,
error_code: Some("E0102".to_string()),
}
}
pub fn simple_parse_error(
message: impl Into<String>,
query: &str,
line: usize,
column: usize,
) -> Self {
HyperQLError::ParseError {
message: message.into(),
line,
column,
source_text: Some(query.to_string()),
error_code: None,
suggestions: Vec::new(),
examples: Vec::new(),
position: None,
}
}
}