Expand description
§typeward
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.
§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
BorrowInputtypes (&str,&[u8],ReadInput) or parse owned values from anyInputimplementation, including streaming inputs - Span support: track source locations with
SourceSpanfor error reporting - Optional serde support: enable the
serdefeature to serialize and deserialize parser outputs and error types - Zero global state: thread-safe parse context passed explicitly through parse calls
§Installation
[dependencies]
typeward = "0.6"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
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:
use typeward::prelude::*;§Borrowed vs Owned Parse Outputs
BorrowInputenables borrowed parse outputs like&str.- Plain
Inputsupports owned parse outputs likeString. - Built-in buffered inputs (
&str,&[u8],ReadInput) implement both traits. - Streaming inputs can implement
Inputonly, which naturally restricts parsing to owned output types. - Custom input types only need
input_len,display,take_char, andslice_to; overridepositionto get accurate spans.
§Building Parsers with Types
Parsers are expressed as types and composed together:
// 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
#[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:
#[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 anotherand_is!(A, B, C): compose a parser that checks all parsers on the same inputor!(A, B, C): try parsers in sequence, returning the first matchor_match!(val, arm => expr, ...): destructureOrresults into valuesToken![null]: resolve a token by its text
Define custom tokens with define_tokens!, which generates the token types and
a lookup macro for them:
use typeward::prelude::*;
typeward::define_tokens! {
macro Tok in (crate);
fn => FnKeyword,
'(' => LParen,
}
type FnParser = Ws<Kw<Tok![fn]>>;The built-in tokens use the exported Token! macro. Import it alongside the
prelude when referring to built-in tokens by text:
use typeward::{Token, prelude::*};
type NullValue = Token![null];§Example
See the examples/json.rs file for a complete JSON parser built with typeward.
§License
MIT, see LICENSE.md
§Module Overview
collections— Repetition/collection combinators likecollections::Many0andcollections::Repeatcombinators— Parser combinators likecombinators::Delimitederror— Parse error types anderror::ParseResultinput— Input abstraction trait (input::Input)literals— Parsers for literal tokens likeliterals::ACharparse— Theparse::Parsetrait and related typesprimitives—parse::Parseimplementations for built-in types and commonly used typestoken— Token trait (token::Token)
Modules§
- collections
- Collection types and utilities for parsing
- combinators
- Combinators for combining parsers and modifying their behavior.
- error
- Error types and utilities for parsing.
- input
- Input types and traits for parsing.
- literals
- Literal tokens and their definitions.
- parse
- Parsing utilities and traits.
- prelude
- Commonly used items for building parsers.
- primitives
- Parsers for primitive values and filtered text.
- token
- Token types and utilities for parsing.
Macros§
- Token
- Maps a token’s text to its token type, e.g.
Token![null]. - and
- Builds the nested
Andtype for a sequence of parser types. - and_is
- A macro to create an
AndIsparser with a value type and one or more validator types. - define_
tokens - Defines token types and a lookup macro, adding the parser integrations.
- new_and
- Builds a nested
Andvalue from parser outputs. - or
- A macro to create an
Orparser with two or more types. - or_
match - A macro to match on an
Orparser result with two or more patterns. - unpack_
and Deprecated - Unpacks a nested
Andvalue into a tuple.