use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
pub tok: Tok,
pub offset: usize,
}
impl Token {
pub fn new(tok: Tok, offset: usize) -> Self {
Token { tok, offset }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Tok {
Ident(String),
Str(String),
Int(i64),
Star,
LBracket,
RBracket,
LParen,
RParen,
Colon,
Comma,
DotDot,
Gt,
Lt,
Ge,
Le,
Eq,
Ne,
Prefix,
Suffix,
Substr,
Glob,
Plus,
Tilde,
Ws,
}
impl Tok {
pub fn describe(&self) -> String {
match self {
Tok::Ident(s) => format!("식별자 `{s}`"),
Tok::Str(s) => format!("문자열 \"{s}\""),
Tok::Int(n) => format!("정수 {n}"),
other => format!("`{}`", other.symbol()),
}
}
pub fn symbol(&self) -> &'static str {
match self {
Tok::Ident(_) => "식별자",
Tok::Str(_) => "문자열",
Tok::Int(_) => "정수",
Tok::Star => "*",
Tok::LBracket => "[",
Tok::RBracket => "]",
Tok::LParen => "(",
Tok::RParen => ")",
Tok::Colon => ":",
Tok::Comma => ",",
Tok::DotDot => "..",
Tok::Gt => ">",
Tok::Lt => "<",
Tok::Ge => ">=",
Tok::Le => "<=",
Tok::Eq => "=",
Tok::Ne => "!=",
Tok::Prefix => "^=",
Tok::Suffix => "$=",
Tok::Substr => "*=",
Tok::Glob => "~=",
Tok::Plus => "+",
Tok::Tilde => "~",
Tok::Ws => "공백",
}
}
pub fn is_compare_op(&self) -> bool {
matches!(
self,
Tok::Eq
| Tok::Ne
| Tok::Gt
| Tok::Lt
| Tok::Ge
| Tok::Le
| Tok::Prefix
| Tok::Suffix
| Tok::Substr
| Tok::Glob
)
}
}
impl fmt::Display for Tok {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.describe())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compare_ops_exclude_bare_star_and_tilde() {
assert!(Tok::Substr.is_compare_op());
assert!(Tok::Glob.is_compare_op());
assert!(!Tok::Star.is_compare_op());
assert!(!Tok::Tilde.is_compare_op());
}
#[test]
fn describe_shows_the_value_not_just_the_kind() {
assert_eq!(Tok::Ident("para".into()).describe(), "식별자 `para`");
assert_eq!(Tok::Int(-1).describe(), "정수 -1");
assert_eq!(Tok::Ge.describe(), "`>=`");
}
}