Crate dynparser

source ·
Expand description

For an introduction and context view, read…

README.md

A very basic example…

   extern crate dynparser;
   use dynparser::{parse, rules_from_peg};

   fn main() {
       let rules = rules_from_peg(
           r#"

   main            =   letter letter_or_num+

   letter          =   [a-zA-Z]

   letter_or_num   =   letter
                   /   number

   number          =   [0-9]

           "#,
       ).unwrap();

       assert!(parse("a2AA456bzJ88", &rules).is_ok());
   }

The classical calculator example

extern crate dynparser;
use dynparser::{parse, rules_from_peg};


fn main() {
    let rules = rules_from_peg(
        r#"

    main            =   _  expr  _

    expr            =   add_t       (_  add_op  _   add_t)*
                    /   portion_expr

    add_t           =   fact_t      (_  fact_op _   fact_t)*

    fact_t          =   portion_expr

    portion_expr    =   '(' expr ')'
                    /   item

    item            =   num

    num             =   [0-9]+ ('.' [0-9]+)?
    add_op          =   '+'  /  '-'
    fact_op         =   '*'  /  '/'

    _               =   ' '*

        "#,
    ).map_err(|e| {
        println!("{}", e);
        panic!("FAIL");
    })
        .unwrap();

    let result = parse(" 1 +  2*  3 +(5/5 - (8-7))", &rules);
    match result {
        Ok(ast) => println!(
            "{:#?}",
            ast.compact()
                .prune(&vec!["_"])
                .passthrow_except(&vec!["main", "add_t", "fact_t"])
        ),
        Err(e) => println!("Error: {:?}", e),
    };
}

Please, read README.md for more context information

extern crate dynparser;
use dynparser::{parse, rules_from_peg};
fn main() {
    let rules = rules_from_peg(
        r#"

    main    =   '('  main   ( ')'  /  error("unbalanced parenthesis") )
            /   'hello'

        "#,
    ).unwrap();

    match parse("((hello)", &rules) {
        Ok(_) => panic!("It should fail"),
        Err(e) => assert!(e.descr == "unbalanced parenthesis"),
    }
}

Re-exports

pub use peg::rules_from_peg;

Modules

Data information to build the AST And some functions to work with AST
Tools to execute parser of a expression
Module with functions to generate rules from PEG grammar

Macros

Concat expressions (and)
Atom::Dot (any character)
Generate a match expression with optional characters and a list of bounds
Generate an error
Create a literal
negate expression
Choose expressions (or)
This will create a subexpression referring to a “rule name”
repeat expression. You have to define minimum repetitions and optionally maximum repetitions (if missing, infinite)
Create a map of rules

Functions

Parse a string with a set of rules
Same as parser, but with debug info