Lex Multi-Char Tokens With Iterator::peekable

Scan a character stream using Iterator::peekable to group multi-digit integers, identifiers, and two-character operators like == and !=.

RustCli Tooling

Code

rustsnippet
54 lines
#[derive(Debug, PartialEq)]
enum Tok {
    Ident(String),
    Number(u64),
    Eq,
    EqEq,
    Neq,
    Bang,
}

fn lex(input: &str) -> Vec<Tok> {
    let mut chars = input.chars().peekable();
    let mut out = Vec::new();
    while let Some(c) = chars.next() {
        if c.is_whitespace() {
            continue;
        }
        if c.is_ascii_digit() {
            let mut digits = String::from(c);
            while let Some(&next) = chars.peek() {
                if !next.is_ascii_digit() {
                    break;
                }
                digits.push(chars.next().unwrap());
            }
            out.push(Tok::Number(digits.parse().unwrap()));
        } else if c.is_ascii_alphabetic() || c == '_' {
            let mut ident = String::from(c);
            while let Some(&next) = chars.peek() {
                if !(next.is_ascii_alphanumeric() || next == '_') {
                    break;
                }
                ident.push(chars.next().unwrap());
            }
            out.push(Tok::Ident(ident));
        } else if c == '=' && chars.peek() == Some(&'=') {
            chars.next();
            out.push(Tok::EqEq);
        } else if c == '=' {
            out.push(Tok::Eq);
        } else if c == '!' && chars.peek() == Some(&'=') {
            chars.next();
            out.push(Tok::Neq);
        } else if c == '!' {
            out.push(Tok::Bang);
        }
    }
    out
}

fn main() {
    let tokens = lex("status == 200 retries != 0 flag = !ready");
    println!("tokens ({}): {tokens:?}", tokens.len());
}

Execution path — Lex Multi-Char Tokens With Iterator::peekable

Lex Multi-Char Tokens With Iterator::peekable is built around the functions lex and main.

Repetition is confined to while let Some(c) = chars.next() — the rest of the file is straight-line.

What to watch for

  • Any import statements resolve cleanly to stock standard-library packages.

Using it

Signature: fn lex(input: &str) -> Vec<Tok>

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

Launch the file; main takes over and steps through lex.

Key statements

while let Some(&next) = chars.peek() {
    if !next.is_ascii_digit() {
        break;
    }
    digits.push(chars.next().unwrap());
}
while let Some(&next) = chars.peek() {
    if !(next.is_ascii_alphanumeric() || next == '_') {
        break;
    }
    ident.push(chars.next().unwrap());
}
out.push(Tok::Number(digits.parse().unwrap()));

Interactive Tools for This Topic

FAQ

What does Lex Multi-Char Tokens With Iterator::peekable print when run?
Execute the whole file; each printed line is prefixed with a label like `tokens (`.