Skip to main content

Crate typeward

Crate typeward 

Source
Expand description

§typeward

Crates.io License: MIT Rust Edition 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.

§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

[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

  • 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.
  • Custom input types only need input_len, display, take_char, and slice_to; override position to 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

ModuleDescription
primitivesParse implementations for built-in types (bool, f64, i64, String, etc.)
combinatorsParser combinators: And, Or, Delimited, Separated, Ws, Span, Peek, Not
collectionsRepetition combinators: Many0, Many1, Repeat
inputInput abstraction via Input + BorrowInput for owned vs borrowed parse outputs
errorError types: ParseError, ParseResult, SourceSpan
parseCore 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
  • Token![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

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 And type for a sequence of parser types.
and_is
A macro to create an AndIs parser 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 And value from parser outputs.
or
A macro to create an Or parser with two or more types.
or_match
A macro to match on an Or parser result with two or more patterns.
unpack_andDeprecated
Unpacks a nested And value into a tuple.

Derive Macros§

Parse