Skip to main content

Crate zyn

Crate zyn 

Source
Expand description

A template engine and framework for Rust procedural macros.

zyn replaces the typical syn + quote + heck + proc-macro-error stack with a single dependency. It provides a zyn! template macro with interpolation, control flow, and pipes — plus reusable elements, typed attribute parsing, and proc macro entry points.

§Quick start

cargo add zyn

A derive macro that generates getters:

#[zyn::derive]
fn my_getters(
    #[zyn(input)] ident: zyn::Extract<zyn::syn::Ident>,
    #[zyn(input)] fields: zyn::Fields<zyn::syn::FieldsNamed>,
) -> zyn::TokenStream {
    zyn::zyn! {
        impl {{ ident }} {
            @for (field in fields.named.iter()) {
                pub fn {{ field.ident | snake | ident:"get_{}" }}(&self) -> &{{ field.ty }} {
                    &self.{{ field.ident }}
                }
            }
        }
    }
}

Applied to struct User { first_name: String, age: u32 } generates:

impl User {
    pub fn get_first_name(&self) -> &String { &self.first_name }
    pub fn get_age(&self) -> &u32 { &self.age }
}

§Template syntax

SyntaxPurpose
{{ expr }}Interpolate any quote::ToTokens value
{{ expr | pipe }}Transform value through a pipe before inserting
@if (cond) { ... }Conditional token emission
@for (x in iter) { ... }Loop over an iterator
@for (N) { ... }Repeat N times
@match (expr) { pat => { ... }}Pattern-based code generation
@element_name(prop = val)Invoke a #[zyn::element] component

See zyn! for the full syntax reference with examples.

§Pipes

13 built-in pipes: snake, pascal, camel, screaming, kebab, upper, lower, str, trim, plural, singular, ident, fmt. They chain:

zyn::zyn! { fn {{ name | snake | ident:"get_{}" }}() {} }
// name = "HelloWorld" → fn get_hello_world() {}

Custom pipes via pipe.

§Elements

#[zyn::element]
fn getter(name: syn::Ident, ty: syn::Type) -> zyn::TokenStream {
    zyn::zyn! {
        pub fn {{ name | snake | ident:"get_{}" }}(&self) -> &{{ ty }} {
            &self.{{ name }}
        }
    }
}

// invoked as:
zyn::zyn! { @getter(name = field.ident.clone().unwrap(), ty = field.ty.clone()) }

§Typed attribute parsing

#[derive(zyn::Attribute)]
#[zyn("builder")]
struct BuilderConfig {
    #[zyn(default)]
    skip: bool,
    #[zyn(default = "build".to_string())]
    method: String,
}
// users write: #[builder(skip)] or #[builder(method = "create")]

Modules§

ast
Template AST node types. Template AST node types.
case
Case conversion utilities. Case conversion functions and macros.
debug
Debug formatting and printing for template expansions. Debug formatting utilities for macro expansions.
ext
Extension traits for common syn AST types. Extension traits for common syn AST types.
extract
Extractors for resolving values from proc macro input. Extractors for resolving typed values from proc macro input.
ident
Internal identifier generation for template expansion. Internal identifier generation for template expansion.
mark
Types and implementations for marking spans. Diagnostic construction utilities.
meta
Attribute argument parsing types. Attribute argument parsing types.
path
Dot-separated path type for navigating nested syn metadata. Dot-separated path type for navigating nested syn metadata.
pipes
Built-in pipe types for template value transforms. Built-in pipe transforms for template value interpolation.
prelude
The zyn prelude. Re-exports all built-in pipes, core traits, and proc macros.
proc_macro2
githubcrates-iodocs-rs
quote
githubcrates-iodocs-rs
syn
githubcrates-iodocs-rs
template
Template parsing and expansion. Template parsing and expansion.
types
Proc macro input types. Proc macro input types.

Macros§

camel
Converts a string or ident to camelCase.
format_ident
Formatting macro for constructing Idents.
kebab
Converts a string or ident to kebab-case.
parse
Parses tokens or string literals into a type. Wraps syn::parse_str and syn::parse2.
parse_input
Parses a proc_macro::TokenStream in a proc macro entry point. Wraps syn::parse_macro_input!.
pascal
Converts a string or ident to PascalCase.
screaming
Converts a string or ident to SCREAMING_SNAKE_CASE.
snake
Converts a string or ident to snake_case.
zyn
Expands a zyn template into a [proc_macro2::TokenStream].

Structs§

Args
A parsed list of attribute arguments.
Attr
Element extractor that resolves a #[derive(Attribute)] struct from the input’s attributes.
Data
Element extractor that pulls the syn::Data from a derive input.
Diagnostic
A compiler diagnostic (error, warning, note, or help message).
DiagnosticBuilder
Builder for constructing Diagnostic instances.
Extract
Generic extractor wrapper — delegates to T::from_input.
Fields
Element extractor that pulls struct fields from the input.
Span
A region of source code, along with macro expansion information.
Template
A parsed template AST. Created by parsing template syntax via syn::parse2::<Template>(tokens).
TokenStream
An abstract stream of tokens, or more concretely a sequence of token trees.
Variants
Element extractor that pulls enum variants from the input.

Enums§

Arg
A single parsed attribute argument.
Input
The proc macro input context. Wraps either a DeriveInput or an Item.
Level
Diagnostic severity level, ordered from least to most severe.

Traits§

Expand
Internal trait for AST node expansion. Not part of the public API.
FromArg
Converts a single Arg into a typed value.
FromData
Converts syn::Data into a specific data representation.
FromFields
Converts syn::Fields into a specific fields representation.
FromInput
Extracts a value from the macro input context.
MultiSpan
A type that can be converted into a list of Spans.
Pipe
Implemented by #[zyn::pipe] types. Transforms a value in a pipe chain.
Render
Implemented by #[zyn::element] types. Renders the element with the given Input context.
ToTokens
Types that can be interpolated inside a quote! invocation.

Functions§

closest_match
Returns the closest matching string from haystack if the edit distance is at most 3. Used for “did you mean?” suggestions in error messages.
error
Creates an error diagnostic builder with the given message.
help
Creates a help diagnostic builder with the given message.
levenshtein
Computes the Levenshtein edit distance between two strings.
new
Creates an empty diagnostic builder.
note
Creates a note diagnostic builder with the given message.
warning
Creates a warning diagnostic builder with the given message.

Type Aliases§

Result
A specialized Result type for zyn diagnostics.

Attribute Macros§

attribute
Defines an attribute macro entry point that auto-parses the annotated item into typed inputs.
derive
Defines a derive macro entry point that auto-parses DeriveInput into typed inputs.
element
Defines a reusable template component generating a struct that implements Render.
pipe
Defines a custom pipe transform used inside {{ expr | pipe }} interpolations.

Derive Macros§

Attribute
Derives typed attribute parsing from #[attr(...)] key-value syntax.