syn-grammar
syn-grammar is a parser generator for Rust that allows you to define EBNF-like grammars directly inside your code (or in external files) and compiles them into syn parsers.
It is designed to make writing procedural macros and Domain Specific Languages (DSLs) in Rust significantly easier by handling the parsing boilerplate for you.
Features
- EBNF Syntax: Define rules using sequences, alternatives (
|), optionals (?), repetitions (*,+), and groups(...). - Type-Safe Actions: Attach Rust code blocks (
-> { ... }) to rules to transform parsed tokens into your own AST orsynstructures. - Syn Integration: Built-in support for parsing Rust identifiers (
ident), integers (int_lit), and strings (string_lit). - Left Recursion: Automatically handles direct left recursion (e.g.,
expr = expr "+" term), making expression parsing intuitive. - Backtracking: Supports speculative parsing for ambiguous grammars.
- External Files: Keep your Rust code clean by moving grammars to
.gfiles withinclude_grammar!.
Installation
Add this to your Cargo.toml:
[]
= "0.1"
= { = "2.0", = ["full", "extra-traits"] }
= "1.0"
= "1.0"
Quick Start
Inline Grammar
You can define a grammar directly inside a macro:
use grammar;
use Parser; // Required for .parse_str()
grammar!
External Grammar File
src/grammar.g
grammar MyGrammar {
rule main -> String = "hello" "world" -> { "Success".to_string() }
}
src/lib.rs
use include_grammar;
include_grammar!;
Syntax Reference
| Syntax | Description | Example |
|---|---|---|
"lit" |
Literal match | "fn" |
ident |
Rust Identifier | my_var |
int_lit |
Integer Literal | 42 |
string_lit |
String Literal | "hello" |
name:rule |
Rule call with binding | e:expr |
( A B ) |
Grouping | ("a" "b") |
A | B |
Alternatives | "true" | "false" |
A? |
Optional | ","? |
A* |
Zero or more | item* |
A+ |
One or more | digit+ |
paren(A) |
Parentheses (...) |
paren(expr) |
bracketed[A] |
Brackets [...] |
bracketed[expr] |
braced{A} |
Braces {...} |
braced{expr} |
A => B |
Cut Operator (Commit) | "let" => "mut" |
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.