Skip to main content

Crate swiftlet

Crate swiftlet 

Source
Expand description

Swiftlet is a high-performance text-parsing library for Rust, inspired by Python’s Lark.

§Example

use swiftlet::preclude::*;


fn calculate(ast: &Ast) -> i32 {
    match ast {
        Ast::Token(token) => {
            token.word().parse::<i32>().unwrap()
        }
        Ast::Tree(tree, children) => {
            match tree.as_str() {
                "start" | "expr" => calculate(&children[0]),
                "add" => calculate(&children[0]) + calculate(&children[2]),
                "sub" => calculate(&children[0]) - calculate(&children[2]),
                _ => {
                    panic!("unexpected tree: {}", tree);
                }
            }
        }
    }
}

fn main() {
    let grammar = r#"
        start: expr
        expr: expr "+" INT -> add
            | expr "-" INT -> sub
            | INT
        %import (WS, INT)
        %ignore WS
        "#;

    let swiftlet = Swiftlet::from_str(grammar).expect("failed to load grammar");
    let parser = swiftlet.parser(ParserConfig::default());
    let text = "10 - 2 + 5 - 2";

    match parser.parse(text) {
        Ok(tree) => {
            print!("AST: "); tree.print();
            println!("Total: {}", calculate(&tree));
        }
        Err(e) => println!("Error: {}", e),
    }
}

Modules§

ast
error
grammar
lexer
load_grammar
parser
parser_frontends
preclude

Macros§

non_terms
Wraps a string in Arc<Symbol::NonTerminal>.
terminal_def
Creates an Arc<TerminalDef> from either a literal string or a regex pattern.
terms
Wraps a string in Ac<Symbol::Terminal>.

Structs§

Parser
Parser instance built from a validated Swiftlet grammar plus configuration.
ParserConfig
Configures parser construction and runtime behavior.
ParserEngine
Builds and executes the concrete parser selected by ParserConfig.
Swiftlet
Reusable loaded grammar that can build multiple parser instances.

Enums§

Ambiguity
Controls how the Earley parser handles ambiguous grammars.