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::*;
use std::sync::Arc;


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!("Invalid tree: {}", tree);
                }
            }
        }
    }
}

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

    let conf = Arc::new(ParserConfig::default());
    let swiftlet = Swiftlet::from_str(grammar).expect("failed to load grammar");
    let parser = swiftlet.parser(conf);
    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
terminal_def
terms

Structs§

Parser
Parser instance built from a validated Swiftlet grammar plus parser options.
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
Ambiguity Enum used to decide how to handle ambiguity in the parse. Relevant to Earley algorithm