gramatica
This crate provides a binary to compile grammars into Rust code and a library implementing Earley's parsing algorithm to parse the grammars specified.
Usage
This crate is gramatica. To use it you should install it in order to acquire the gramatica_compiler binary and also add gramatica to your dependencies in your project's Cargo.toml.
[]
= "0.1"
Then, if you have made a grammar file example.rsg execute gramatica_compiler example.rsg > example.rs. Afterwards you may use the generated file example.rs as a source Rust file.
Example: calculator
The classical example is to implement a calculator.
extern crate gramatica;
use Ordering;
use BufRead;
use ;
re_terminal!;
re_terminal!;
re_terminal!;
re_terminal!;
re_terminal!;
re_terminal!;
re_terminal!;
re_terminal!;
re_terminal!;
re_terminal!;//Otherwise skip spaces
nonterminal Input
nonterminal Line
nonterminal Expression
ordering!;
Advanced Lexer
To define terminal tokens not expressable with regular expressions you may use the following.
terminal LitChar
Since version 0.1.0 there is also a keyword_terminal! macro:
keyword_terminal!;
Parsing values as match clauses
Each rule is written as a match clause, whose ending expression is the value that the nonterminal token gets after being parsed. For example:
nonterminal Stmts
Reductions only execute if they are part of the final syntactic tree.
Precedence by annotations
To avoid ambiguities you have two options: to ensure the grammar does not contain them or to priorize rules by introducing annotations. In the example of the calculator we have seen two kinds:
#[priority(p_name)]to declare a rule with priorityp_name. Later there should be aordering!(p_0,p_1,p_2,...)macro-like to indicate thatp_0should reduce beforep_1.#[associativity(left/right)]to decide how to proceed when nesting the same rule.