Remap Tokens During Parsing

The Rhai Engine first parses a script into a stream of tokens.

Tokens have the type Token which is only exported under internals.

The function Engine::on_parse_token, available only under internals, allows registration of a mapper function that converts (remaps) a Token into another.

Function Signature

The function signature passed to Engine::on_parse_token takes the following form:

Fn(token: Token, pos: Position, state: &TokenizeState) -> Token

where pos is the location of the token and [state]TokenizeState holds the current state of the tokenizer.

Raising errors

It is possible to raise a parsing error by returning Token::LexError as the mapped token.

Example


#![allow(unused)]
fn main() {
use rhai::{Engine, FLOAT, Token};

let mut engine = Engine::new();

// Register a token mapper function.
engine.on_parse_token(|token, pos, state| {
    match token {
        // Change 'begin' .. 'end' to '{' .. '}'
        Token::Identifier(s) if &s == "begin" => Token::LeftBrace,
        Token::Identifier(s) if &s == "end" => Token::RightBrace,

        // Change all integer literals to floating-point
        Token::IntegerConstant(n) => Token::FloatConstant((n as FLOAT).into()),
        
        // Pass through all other tokens unchanged
        _ => token
    }
});
}