use test_lang::Snapshot;
#[derive(Debug)]
struct Token {
kind: Kind,
text: String,
}
#[derive(Debug)]
enum Kind {
Ident,
Int,
Eq,
Plus,
}
impl std::fmt::Display for Token {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}({})", self.kind, self.text)
}
}
fn lex(source: &str) -> Vec<Token> {
source
.split_whitespace()
.map(|lexeme| {
let kind = match lexeme {
"=" => Kind::Eq,
"+" => Kind::Plus,
_ if lexeme.chars().all(|c| c.is_ascii_digit()) => Kind::Int,
_ => Kind::Ident,
};
Token {
kind,
text: lexeme.to_string(),
}
})
.collect()
}
fn main() {
let tokens = lex("total = a + 42");
let snapshot = Snapshot::per_line(&tokens);
println!("captured token stream:\n{snapshot}\n");
let expected = "\
Ident(total)
Eq(=)
Ident(a)
Plus(+)
Int(42)";
match snapshot.check(expected) {
Ok(()) => println!("snapshot matches expected token stream"),
Err(mismatch) => {
println!("{mismatch}");
std::process::exit(1);
}
}
}