Match Char Classes In A Tiny Tokenizer

A per-character match with literal, range, and wildcard arms turns a raw string into tokens: symbols emit immediately, word chars accumulate.

RustCli Tooling

Code

rustsnippet
58 lines
#[derive(Debug, PartialEq)]
enum Token {
    Number(u32),
    Ident(String),
    Plus,
    Dash,
}

fn parse_word(word: &str) -> Token {
    // All digits -> Number, otherwise -> Ident
    if word.chars().all(|c| c.is_ascii_digit()) {
        Token::Number(word.parse().expect("digits only"))
    } else {
        Token::Ident(String::from(word))
    }
}

fn tokenize(input: &str) -> Vec<Token> {
    let mut tokens = Vec::new();
    let mut word = String::new();

    for c in input.chars() {
        // Range and or-patterns: alphanumerics count as word characters
        let is_word = matches!(c, '0'..='9' | 'a'..='z' | 'A'..='Z');
        if !is_word && !word.is_empty() {
            tokens.push(parse_word(&word));
            word.clear();
        }
        match c {
            // Literal patterns: single-character symbols emit a token immediately
            '+' => tokens.push(Token::Plus),
            '-' => tokens.push(Token::Dash),
            '0'..='9' | 'a'..='z' | 'A'..='Z' => word.push(c),
            // Wildcard arm: everything else is just a separator
            _ => {}
        }
    }
    if !word.is_empty() {
        tokens.push(parse_word(&word));
    }
    tokens
}

fn main() {
    let tokens = tokenize("height-42+width");
    println!("{:?}", tokens);
    assert_eq!(
        tokens,
        vec![
            Token::Ident(String::from("height")),
            Token::Dash,
            Token::Number(42),
            Token::Plus,
            Token::Ident(String::from("width")),
        ]
    );
    println!("token count: {}", tokens.len());
}

How the snippet works

Match Char Classes In A Tiny Tokenizer is built around the functions parse_word, tokenize and main.

Repetition is confined to for c in input.chars() — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Using it

The primary signature is fn parse_word(word: &str) -> Token

The demo output is labeled (token count:); each label names the call that printed it.

The sequence tokenize lives in main; running the file triggers it.

Key statements

fn parse_word(word: &str) -> Token {
    // All digits -> Number, otherwise -> Ident
    if word.chars().all(|c| c.is_ascii_digit()) {
        Token::Number(word.parse().expect("digits only"))
    } else {
        Token::Ident(String::from(word))
    }
}

Interactive Tools for This Topic

FAQ

What does Match Char Classes In A Tiny Tokenizer print when run?
Invoke the file as-is — the `token count:` prefixes identify which step printed each line.