use super::error::SelectorError;
use super::token::{Tok, Token};
#[derive(Debug, Clone)]
pub struct Lexed {
pub tokens: Vec<Token>,
pub char_len: usize,
}
pub fn lex(input: &str) -> Result<Lexed, SelectorError> {
let chars: Vec<char> = input.chars().collect();
let mut tokens = Vec::new();
let mut i = 0usize;
while i < chars.len() {
let start = i;
let c = chars[i];
if c.is_whitespace() {
while i < chars.len() && chars[i].is_whitespace() {
i += 1;
}
tokens.push(Token::new(Tok::Ws, start));
continue;
}
if c == '"' || c == '\'' {
let (value, next) = lex_string(&chars, i, c)?;
tokens.push(Token::new(Tok::Str(value), start));
i = next;
continue;
}
if c.is_ascii_digit()
|| (c == '-' && matches!(chars.get(i + 1), Some(d) if d.is_ascii_digit()))
{
let (value, next) = lex_int(&chars, i)?;
tokens.push(Token::new(Tok::Int(value), start));
i = next;
continue;
}
if is_ident_start(c) {
let mut end = i + 1;
while end < chars.len() && is_ident_continue(chars[end]) {
end += 1;
}
let text: String = chars[i..end].iter().collect();
tokens.push(Token::new(Tok::Ident(text), start));
i = end;
continue;
}
let two = if i + 1 < chars.len() {
Some((c, chars[i + 1]))
} else {
None
};
let (tok, width) = match two {
Some(('>', '=')) => (Tok::Ge, 2),
Some(('<', '=')) => (Tok::Le, 2),
Some(('!', '=')) => (Tok::Ne, 2),
Some(('^', '=')) => (Tok::Prefix, 2),
Some(('$', '=')) => (Tok::Suffix, 2),
Some(('*', '=')) => (Tok::Substr, 2),
Some(('~', '=')) => (Tok::Glob, 2),
Some(('.', '.')) => (Tok::DotDot, 2),
_ => match c {
'*' => (Tok::Star, 1),
'[' => (Tok::LBracket, 1),
']' => (Tok::RBracket, 1),
'(' => (Tok::LParen, 1),
')' => (Tok::RParen, 1),
':' => (Tok::Colon, 1),
',' => (Tok::Comma, 1),
'>' => (Tok::Gt, 1),
'<' => (Tok::Lt, 1),
'=' => (Tok::Eq, 1),
'+' => (Tok::Plus, 1),
'~' => (Tok::Tilde, 1),
'!' => {
return Err(SelectorError::lex(start, "`!` 뒤에는 `=` 만 올 수 있다")
.expecting(["!="])
.hinting("부정은 `:not(...)` 으로 쓴다"));
}
'.' => {
return Err(SelectorError::lex(start, "`.` 하나는 뜻이 없다")
.expecting([".."])
.hinting("범위는 `:nth(1..3)`, 자손은 공백으로 쓴다"));
}
'#' => {
return Err(SelectorError::lex(start, "`#` 문법은 없다")
.hinting("이름 지목은 `[name=\"…\"]` 으로 쓴다"));
}
other => {
return Err(SelectorError::lex(
start,
format!("선택자에 쓸 수 없는 문자 `{other}`"),
));
}
},
};
tokens.push(Token::new(tok, start));
i += width;
}
Ok(Lexed {
tokens,
char_len: chars.len(),
})
}
fn is_ident_start(c: char) -> bool {
c.is_alphabetic() || c == '_'
}
fn is_ident_continue(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '-'
}
fn lex_int(chars: &[char], start: usize) -> Result<(i64, usize), SelectorError> {
let mut i = start;
if chars[i] == '-' {
i += 1;
}
let digits_from = i;
while i < chars.len() && chars[i].is_ascii_digit() {
i += 1;
}
debug_assert!(i > digits_from, "호출부가 첫 숫자를 확인하고 부른다");
let text: String = chars[start..i].iter().collect();
let value = text
.parse::<i64>()
.map_err(|_| SelectorError::lex(start, format!("정수 범위를 벗어난 값 `{text}`")))?;
Ok((value, i))
}
fn lex_string(chars: &[char], start: usize, quote: char) -> Result<(String, usize), SelectorError> {
let mut out = String::new();
let mut i = start + 1;
while i < chars.len() {
let c = chars[i];
if c == quote {
return Ok((out, i + 1));
}
if c != '\\' {
out.push(c);
i += 1;
continue;
}
let esc = chars.get(i + 1).copied().ok_or_else(|| {
SelectorError::lex(i, "역슬래시로 끝나는 문자열")
.hinting("역슬래시 자체는 `\\\\` 로 적는다")
})?;
match esc {
'\\' => out.push('\\'),
'"' => out.push('"'),
'\'' => out.push('\''),
'n' => out.push('\n'),
't' => out.push('\t'),
'r' => out.push('\r'),
'0' => out.push('\0'),
'u' => {
let (ch, next) = lex_unicode_escape(chars, i)?;
out.push(ch);
i = next;
continue;
}
other => {
return Err(
SelectorError::lex(i, format!("알 수 없는 이스케이프 `\\{other}`"))
.expecting(["\\\\", "\\\"", "\\'", "\\n", "\\t", "\\r", "\\0", "\\uXXXX"]),
);
}
}
i += 2;
}
Err(
SelectorError::lex(start, format!("닫히지 않은 문자열 (`{quote}` 로 시작)"))
.hinting("문자열 안의 따옴표는 역슬래시로 감싼다"),
)
}
fn lex_unicode_escape(chars: &[char], at: usize) -> Result<(char, usize), SelectorError> {
let first = read_hex4(chars, at)?;
let mut next = at + 6;
if (0xD800..0xDC00).contains(&first) {
let has_pair = chars.get(next) == Some(&'\\') && chars.get(next + 1) == Some(&'u');
if !has_pair {
return Err(SelectorError::lex(at, "짝 없는 상위 서로게이트")
.hinting("BMP 밖 문자는 `\\uD83D\\uDE00` 처럼 두 개를 이어 적는다"));
}
let second = read_hex4(chars, next)?;
if !(0xDC00..0xE000).contains(&second) {
return Err(SelectorError::lex(next, "하위 서로게이트가 아니다"));
}
let combined = 0x1_0000 + ((first - 0xD800) << 10) + (second - 0xDC00);
next += 6;
let ch = char::from_u32(combined)
.ok_or_else(|| SelectorError::lex(at, "유효하지 않은 코드포인트"))?;
return Ok((ch, next));
}
if (0xDC00..0xE000).contains(&first) {
return Err(SelectorError::lex(at, "짝 없는 하위 서로게이트"));
}
let ch =
char::from_u32(first).ok_or_else(|| SelectorError::lex(at, "유효하지 않은 코드포인트"))?;
Ok((ch, next))
}
fn read_hex4(chars: &[char], at: usize) -> Result<u32, SelectorError> {
let mut value = 0u32;
for k in 0..4 {
let c = chars.get(at + 2 + k).copied().ok_or_else(|| {
SelectorError::lex(at, "`\\u` 뒤 16진수 네 자리가 모자라다").expecting(["\\uXXXX"])
})?;
let digit = c.to_digit(16).ok_or_else(|| {
SelectorError::lex(at + 2 + k, format!("16진수가 아닌 문자 `{c}`"))
.expecting(["0-9", "a-f", "A-F"])
})?;
value = value * 16 + digit;
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(input: &str) -> Vec<Tok> {
lex(input)
.unwrap()
.tokens
.into_iter()
.map(|t| t.tok)
.collect()
}
#[test]
fn whitespace_survives_as_a_single_token() {
assert_eq!(
kinds("a b"),
vec![Tok::Ident("a".into()), Tok::Ws, Tok::Ident("b".into())]
);
}
#[test]
fn longest_match_wins_on_operator_prefixes() {
assert_eq!(kinds(">="), vec![Tok::Ge]);
assert_eq!(kinds(">"), vec![Tok::Gt]);
assert_eq!(kinds("*="), vec![Tok::Substr]);
assert_eq!(kinds("*"), vec![Tok::Star]);
assert_eq!(kinds("~="), vec![Tok::Glob]);
assert_eq!(kinds("~"), vec![Tok::Tilde]);
assert_eq!(kinds(".."), vec![Tok::DotDot]);
}
#[test]
fn korean_identifiers_and_strings_keep_char_offsets() {
let out = lex("표[제목=\"합계\"]").unwrap();
assert_eq!(out.tokens[0].offset, 0);
assert_eq!(out.tokens[1].offset, 1);
assert_eq!(out.tokens[1].tok, Tok::LBracket);
}
#[test]
fn negative_int_is_one_token() {
assert_eq!(kinds("-1"), vec![Tok::Int(-1)]);
assert_eq!(kinds(">-1"), vec![Tok::Gt, Tok::Int(-1)]);
}
#[test]
fn hyphen_binds_into_identifiers() {
assert_eq!(kinds("page-break"), vec![Tok::Ident("page-break".into())]);
}
#[test]
fn string_escapes_are_unescaped_once() {
assert_eq!(kinds(r#""a\"b""#), vec![Tok::Str("a\"b".into())]);
assert_eq!(kinds(r#""tab\there""#), vec![Tok::Str("tab\there".into())]);
assert_eq!(kinds(r#""A""#), vec![Tok::Str("A".into())]);
}
#[test]
fn surrogate_pairs_combine() {
assert_eq!(kinds(r#""😀""#), vec![Tok::Str("😀".into())]);
}
#[test]
fn lone_surrogate_is_rejected_with_a_hint() {
let err = lex(r#""\uD83D""#).unwrap_err();
assert!(err.message.contains("서로게이트"));
assert!(err.hint.is_some());
}
#[test]
fn unterminated_string_points_at_the_opening_quote() {
let err = lex("para[style=\"열림").unwrap_err();
assert_eq!(err.offset, 11);
}
#[test]
fn unknown_escape_lists_the_allowed_set() {
let err = lex(r#""\q""#).unwrap_err();
assert!(err.expected.iter().any(|e| e == "\\uXXXX"));
}
#[test]
fn hash_and_dot_redirect_to_real_syntax() {
let hash = lex("#T1").unwrap_err();
assert!(hash.hint.unwrap().contains("[name="));
let dot = lex("a.b").unwrap_err();
assert!(dot.hint.unwrap().contains(":nth"));
}
#[test]
fn bang_alone_points_at_not() {
let err = lex("a!b").unwrap_err();
assert!(err.hint.unwrap().contains(":not"));
}
#[test]
fn int_overflow_is_a_korean_diagnostic() {
let err = lex("99999999999999999999").unwrap_err();
assert!(err.message.contains("정수 범위"));
}
#[test]
fn char_len_is_reported_for_eof_offsets() {
assert_eq!(lex("문단표").unwrap().char_len, 3);
}
}