use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectorError {
pub kind: SelectorErrorKind,
pub message: String,
pub offset: usize,
pub expected: Vec<String>,
pub hint: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectorErrorKind {
Lex,
Parse,
Resolve,
Limit,
}
impl SelectorErrorKind {
pub const fn as_str(self) -> &'static str {
match self {
SelectorErrorKind::Lex => "lex",
SelectorErrorKind::Parse => "parse",
SelectorErrorKind::Resolve => "resolve",
SelectorErrorKind::Limit => "limit",
}
}
}
impl SelectorError {
pub fn new(kind: SelectorErrorKind, offset: usize, message: impl Into<String>) -> Self {
SelectorError {
kind,
message: message.into(),
offset,
expected: Vec::new(),
hint: None,
}
}
pub fn lex(offset: usize, message: impl Into<String>) -> Self {
Self::new(SelectorErrorKind::Lex, offset, message)
}
pub fn parse(offset: usize, message: impl Into<String>) -> Self {
Self::new(SelectorErrorKind::Parse, offset, message)
}
pub fn resolve(offset: usize, message: impl Into<String>) -> Self {
Self::new(SelectorErrorKind::Resolve, offset, message)
}
pub fn limit(offset: usize, message: impl Into<String>) -> Self {
Self::new(SelectorErrorKind::Limit, offset, message)
}
pub fn expecting<I, S>(mut self, items: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.expected.extend(items.into_iter().map(Into::into));
self.expected.sort();
self.expected.dedup();
self
}
pub fn hinting(mut self, hint: impl Into<String>) -> Self {
self.hint = Some(hint.into());
self
}
pub fn render(&self, input: &str) -> String {
let mut out = String::new();
out.push_str(&self.message);
if !self.expected.is_empty() {
out.push_str(" — 기대: ");
out.push_str(&self.expected.join(" | "));
}
out.push('\n');
out.push_str(input);
out.push('\n');
for (i, ch) in input.chars().enumerate() {
if i >= self.offset {
break;
}
out.push(if ch == '\t' { '\t' } else { ' ' });
}
out.push('^');
if let Some(hint) = &self.hint {
out.push('\n');
out.push_str("힌트: ");
out.push_str(hint);
}
out
}
pub fn to_json(&self) -> serde_json::Value {
let mut obj = serde_json::Map::new();
obj.insert("kind".into(), serde_json::json!(self.kind.as_str()));
obj.insert("message".into(), serde_json::json!(self.message));
obj.insert("offset".into(), serde_json::json!(self.offset));
if !self.expected.is_empty() {
obj.insert("expected".into(), serde_json::json!(self.expected));
}
if let Some(hint) = &self.hint {
obj.insert("hint".into(), serde_json::json!(hint));
}
serde_json::Value::Object(obj)
}
}
impl fmt::Display for SelectorError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "선택자 {}: {}", self.kind.as_str(), self.message)?;
if !self.expected.is_empty() {
write!(f, " (기대: {})", self.expected.join(" | "))?;
}
write!(f, " [문자 {}]", self.offset)
}
}
impl std::error::Error for SelectorError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expected_is_sorted_and_deduped() {
let err = SelectorError::parse(3, "예상 밖 토큰")
.expecting(["]", "[", "]"])
.expecting([":"]);
assert_eq!(err.expected, vec![":".to_string(), "[".into(), "]".into()]);
}
#[test]
fn caret_lands_on_char_boundary_not_byte() {
let err = SelectorError::parse(2, "여기");
let rendered = err.render("한글x");
let caret_line = rendered.lines().last().unwrap();
assert_eq!(caret_line, " ^");
}
#[test]
fn tabs_are_preserved_in_caret_line() {
let err = SelectorError::parse(2, "여기");
let rendered = err.render("\t\tx");
assert!(rendered.lines().last().unwrap().starts_with("\t\t"));
}
#[test]
fn json_keeps_zero_offset() {
let json = SelectorError::lex(0, "닫히지 않은 따옴표").to_json();
assert_eq!(json["offset"], serde_json::json!(0));
assert_eq!(json["kind"], serde_json::json!("lex"));
assert!(json.get("expected").is_none());
assert!(json.get("hint").is_none());
}
#[test]
fn display_has_no_caret_but_carries_offset() {
let err = SelectorError::resolve(7, "없는 축").expecting(["para", "table"]);
let text = err.to_string();
assert!(text.contains("[문자 7]"));
assert!(text.contains("para | table"));
assert!(!text.contains('^'));
}
}