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 and printing for template expansions.
diagnostic
Diagnostic accumulation and emission. Diagnostic accumulation and emission.
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.
meta
Attribute argument parsing types. Attribute argument parsing types.
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.
debug
Expands a zyn template with diagnostic output for debugging.
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 structure representing a diagnostic message and associated children messages.
Diagnostics
An accumulator for compiler diagnostics (errors, warnings, notes, help messages).
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
An enum representing a diagnostic level.

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.
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.
SpanDiagnosticExt
Extension trait for proc_macro2::Span emulating the proc-macro diagnostic API on stable and nightly.
ToDiagnostics
Conversion trait for types that can be turned into Diagnostics.
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.
levenshtein
Computes the Levenshtein edit distance between two strings.

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 Input.
derive
Defines a derive macro entry point that auto-parses DeriveInput into Input.
element
Defines a reusable template component that generates a struct implementing Render.
pipe
Defines a custom pipe transform that generates a struct implementing Pipe.

Derive Macros§

Attribute
Derives the Attribute trait for typed attribute parsing from #[attr(...)] syntax.