#proc-macro #tokenization #automata #macro-derive #parser #generate #utilities

derive-finite-automaton

Procedural macro for generating finite automaton

5 releases

0.2.0 Mar 1, 2024
0.1.3 Sep 20, 2023
0.1.2 Sep 20, 2023
0.1.1 Sep 19, 2023
0.1.0 Dec 6, 2021

#158 in Parser tooling

Download history 7/week @ 2024-07-22 90/week @ 2024-07-29 41/week @ 2024-08-05 15/week @ 2024-08-12 11/week @ 2024-08-19 43/week @ 2024-08-26 54/week @ 2024-09-02 13/week @ 2024-09-09 3/week @ 2024-09-16 23/week @ 2024-09-23 8/week @ 2024-09-30 90/week @ 2024-10-07 14/week @ 2024-10-14 4/week @ 2024-10-21 7/week @ 2024-10-28 32/week @ 2024-11-04

131 downloads per month
Used in 4 crates (via ezno-parser)

MIT license

7KB
81 lines

derive finite automaton

crates.io badge docs.rs badge

A procedural macro for building a finite automaton. Main use is for lexing multiple character wide tokens see derive-finite-automaton/examples/main.rs.

Run example:

cd derive-finite-automaton
cargo run --example main

View example macro expansion (requires cargo-expand):

cd derive-finite-automaton
cargo expand --example main

Example

use derive_finite_automaton::{FiniteAutomata, FiniteAutomataConstructor};

#[derive(FiniteAutomataConstructor, Debug, PartialEq)]
#[automaton_mappings(
    "{" => Tokens::OpenBrace,
    "}" => Tokens::CloseBrace,
    "=" => Tokens::Assign,
    "=>" => Tokens::ArrowFunction,
    "==" => Tokens::Equal,
    "===" => Tokens::StrictEqual,
    "." => Tokens::Dot,
    "..." => Tokens::Spread,
)]
pub enum Tokens {
    OpenBrace,
    CloseBrace,
    ArrowFunction,
    Equal,
    StrictEqual,
    Assign,
    Dot,
    Spread,
}

You can add conditional mappings with the following

use derive_finite_automaton::FiniteAutomataConstructor;

#[derive(Debug, FiniteAutomataConstructor)]
#[automaton_mappings(
    "{" => Tokens::OpenBrace,
    "}" => Tokens::CloseBrace,
    "=>" => Tokens::ArrowFunction,
    "==" => Tokens::Equal,
    "===" => Tokens::StrictEqual,
    "=" => Tokens::Assign,
    // Some mapping
    "." => Tokens::Dot,
)]
#[cfg_attr(feature = "special", automaton_mappings(
    ".?." => Tokens::Magic,
))]
pub enum Tokens {
    OpenBrace,
    CloseBrace,
    ArrowFunction,
    Equal,
    StrictEqual,
    Assign,
    Dot,
    #[cfg(feature = "special")]
    Magic,
}

Dependencies

~265–720KB
~17K SLoC