Cirru Parser
This crate provides a parser for the Cirru text syntax, an indentation-based syntax that can be used as a replacement for S-Expressions. It's designed to be simple, clean, and easy to read.
For example, this Cirru code:
defn fib (x)
if (<= x 2) 1
+
fib $ dec x
fib $ - x 2
is parsed into a tree structure that represents the nested expressions:
[ ["defn" "fib" [ "x" ]
[ "if" [ "<=" "x" "2" ] "1"
[ "+" [ "fib" ["dec" "x"] ] [ "fib" ["-" "x" "2"] ] ]
]
] ]
Usage
Add this to your Cargo.toml
:
[]
= "0.1.33"
Parsing
To parse a string of Cirru code, use the parse
function. It returns a Result<Vec<Cirru>, String>
, where Cirru
is an enum representing either a leaf (string) or a list of Cirru
expressions.
use ;
Formatting
This crate also provides a format
function to convert a Cirru
tree back into a string. You can control the output format with CirruWriterOptions
.
use ;
let code = "a (b c)";
let tree = parse.unwrap;
let options = CirruWriterOptions ;
let formatted_code = format.unwrap;
assert_eq!;
Escaping
When creating Cirru code programmatically, you might need to escape strings to ensure they are treated as single leaves, especially if they contain spaces or special characters.
use escape_cirru_leaf;
let escaped = escape_cirru_leaf;
assert_eq!;
Features
This crate provides the following features:
Default features:
- serde: The
Cirru
type implementsSerialize
andDeserialize
traits by default, allowing integration with any serde-compatible serialization format (bincode, MessagePack, etc.).
Optional features:
- serde-json: Provides JSON conversion utilities (
from_json_str
,to_json_str
, etc.) for converting between Cirru structures and JSON.
To use JSON conversion features, add them to your Cargo.toml
:
[]
= { = "0.1.33", = ["serde-json"] }
Examples
use Cirru;
// Basic usage (always available)
let data = leaf;
// Serde serialization (always available)
use serde_json;
let json = to_string.unwrap;
// JSON conversion (requires "serde-json" feature)
Development
Contributions are welcome! Here's how to get started:
- Run tests:
cargo test
- Run benchmarks:
cargo bench
- Check for issues:
cargo clippy
License
This project is licensed under the MIT License.