# typeward
[](https://crates.io/crates/typeward)
[](LICENSE.md)
[](https://doc.rust-lang.org/edition-guide/rust-2024/)
A parser combinator library that builds parsers by composing smaller parsers **within the type system**.
This crate is an alternative to `nom` for creating structs that can be parsed by composing type-level parsers. Define tokens as types, implement `Parse` for your structs, and combine them using generic combinators like [`combinators::Delimited`](crate::combinators::Delimited).
## Features
- **Type-level parser composition**: parsers are types, composed via generics rather than runtime closures
- **Derive macro**: `#[derive(Parse)]` generates parser implementations for structs, enums, and unions
- **Borrowed + streaming-friendly input model**: parse borrowed values from `BorrowInput` types (`&str`, `&[u8]`, `ReadInput`) or parse owned values from any `Input` implementation, including streaming inputs
- **Span support**: track source locations with `SourceSpan` for error reporting
- **Optional serde support**: enable the `serde` feature to serialize and deserialize parser outputs and error types
- **Zero global state**: thread-safe parse context passed explicitly through parse calls
## Installation
```toml
[dependencies]
typeward = "0.5"
```
The `macros` feature (enabled by default) provides the `#[derive(Parse)]` macro. Disable it with `default-features = false` if you only need the combinator library.
## Quick Start
```rust,ignore
use typeward::prelude::*;
// Parse a complete input string
let value = parse_complete::<f64>("3.14 remainder")?;
```
Import the prelude to get access to core traits, combinators, primitives, and the derive macro:
```rust,ignore
use typeward::prelude::*;
```
### Borrowed vs Owned Parse Outputs
- `BorrowInput` enables borrowed parse outputs like `&str`.
- Plain `Input` supports owned parse outputs like `String`.
- Built-in buffered inputs (`&str`, `&[u8]`, `ReadInput`) implement both traits.
- Streaming inputs can implement `Input` only, which naturally restricts parsing to owned output types.
## Building Parsers with Types
Parsers are expressed as types and composed together:
```rust,ignore
// A quoted string: "..."
type QuotedString = DelimitedExact<DoubleQuote, DoubleQuote, TakeTillToken<DoubleQuote>>;
// A comma-separated list inside brackets: [a, b, c]
type List = Delimited<LBracket, RBracket, Separated0<String, Ws<Comma>>>;
// Try multiple alternatives
type Value = or!(Ws<KwNull>, Ws<bool>, Ws<f64>, QuotedString, List);
// Also implemented for `Option` and `Result`:
type OptionalValue = Option<Value>;
type FallibleValue = Result<Value, ParseError>;
```
### Implementing `Parse` for Custom Types
```rust,ignore
#[derive(Debug, Clone)]
struct Point {
x: f64,
y: f64,
}
impl<'a> Parse<'a> for Point {
fn parse_with_context(
input: &'a str,
context: &mut ParseOffsetContext,
) -> ParseResult<(Self, &'a str)> {
let (x, rest) = Ws::<f64>::parse_with_context(input, context)?;
let (_, rest) = Ws::<Comma>::parse_with_context(rest, context)?;
let (y, rest) = Ws::<f64>::parse_with_context(rest, context)?;
Ok((Point { x, y }, rest))
}
}
```
### Using the Derive Macro
Enable the `macros` feature and derive `Parse` automatically:
```rust,ignore
#[derive(Parse)]
struct Point {
#[parse(ws)]
x: f64,
#[parse(ws)]
y: f64,
}
#[derive(Parse)]
enum Shape {
Circle { radius: f64 },
Rect { width: f64, height: f64 },
}
#[derive(Parse)]
struct Wrapper<T>(T);
```
Field-level attributes like `#[parse(ws)]` and `#[parse(from(ParserType, mapper))]` customize how each field is parsed. Attributes that accept a value support both `name(value)` and `name = value` forms, such as `#[parse(map = |value| value + 1)]` or `#[parse(from = Ws::<String>)]`. Optional fields can use `#[parse(default)]` to fall back to `Default::default()`, or `#[parse(default = expr)]` to supply a custom fallback.
When `#[parse(from(ParserType))]` has no explicit mapper, the parser output is recursively unpacked into the field type with [`parse::Unpack`]. Transparent wrappers such as `Ws`, `DelimitedExact`, `DelimNested`, `Separated`, and `And` are removed automatically, so a field can be declared as `Vec<T>` even when its parser produces `Ws<BracketedList<...>>`. Unpacking also recurses through `Vec`, `Option`, tuples, and collection wrappers, while `Span` and `Nested` keep their wrapper. See the [`parse::Unpack`] documentation for the full rules. The underlying trait is also published as the standalone [`unpackable`] crate. Omit `from` when the field type is already the parser type, and pass an explicit mapper when you need a custom conversion.
Recursive parser shapes are rejected by default; add `#[parse(recursive)]` on the container to opt in when your grammar is structured to consume input at each recursive step.
## Core Modules
| Module | Description |
|---|---|
| [`primitives`] | `Parse` implementations for built-in types (`bool`, `f64`, `i64`, `String`, etc.) |
| [`combinators`] | Parser combinators: `And`, `Or`, `Delimited`, `Separated`, `Ws`, `Span`, `Peek`, `Not` |
| [`collections`] | Repetition combinators: `Many0`, `Many1`, `Repeat` |
| [`input`] | Input abstraction via `Input` + `BorrowInput` for owned vs borrowed parse outputs |
| [`error`] | Error types: `ParseError`, `ParseResult`, `SourceSpan` |
| [`parse`] | Core `Parse` trait and entry points like `parse_complete` |
## Macros
The crate provides helper macros for composing parsers ergonomically:
- `and!(A, B, C)`: compose a tuple parser from multiple types one after another
- `and_is!(A, B, C)`: compose a parser that checks all parsers on the same input
- `or!(A, B, C)`: try parsers in sequence, returning the first match
- `or_match!(val, arm => expr, ...)`: destructure `Or` results into values
## Example
See the [`examples/json.rs`](examples/json.rs) file for a complete JSON parser built with typeward.
## License
MIT, see [LICENSE.md](LICENSE.md)