zyn 0.5.4

A proc macro framework with templates, composable elements, and built-in diagnostics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! ![zyn](https://raw.githubusercontent.com/aacebo/zyn/refs/heads/main/assets/banner.svg)
//!
//! A proc macro framework with templates, composable elements, and built-in diagnostics.
//!
//! ```sh
//! cargo add zyn
//! ```
//!
//! # Table of Contents
//!
//! - [Templates](#templates)
//! - [Elements](#elements)
//! - [Pipes](#pipes)
//! - [Attributes](#attributes)
//!   - [Auto-suggest](#auto-suggest)
//! - [Testing](#testing)
//!   - [Assertions](#assertions)
//!   - [Debugging](#debugging)
//! - [Features](#features)
//!   - [ext](#ext)
//!   - [pretty](#pretty)
//!   - [diagnostics](#diagnostics)
//!
//! ---
//!
//! # Templates
//!
//! The [`zyn!`] macro is the core of zyn. Write token output as if it were source code,
//! with `{{ }}` interpolation and `@` control flow directives.
//!
//! **Interpolation** — any [`quote::ToTokens`] value:
//!
//! ```ignore
//! let name = zyn::format_ident!("hello_world");
//! zyn::zyn!(fn {{ name }}() {})
//! // → fn hello_world() {}
//! ```
//!
//! **Pipes** — transform values inline:
//!
//! ```ignore
//! zyn::zyn!(fn {{ name | pascal }}() {})
//! // name = "hello_world" → fn HelloWorld() {}
//! ```
//!
//! **Control flow:**
//!
//! ```ignore
//! zyn::zyn!(
//!     @if (is_pub) { pub }
//!     @for (field in fields.named.iter()) {
//!         fn {{ field.ident }}(&self) -> &{{ field.ty }} {
//!             &self.{{ field.ident }}
//!         }
//!     }
//! )
//! ```
//!
//! **Full template syntax:**
//!
//! | Syntax | Purpose |
//! |--------|---------|
//! | `{{ expr }}` | Interpolate any [`quote::ToTokens`] value |
//! | `{{ expr \| pipe }}` | Transform value through a [pipe](#pipes) before inserting |
//! | `@if (cond) { ... }` | Conditional token emission |
//! | `@else { ... }` | Else branch |
//! | `@else if (cond) { ... }` | Else-if branch |
//! | `@for (x in iter) { ... }` | Loop over an iterator |
//! | `@for (N) { ... }` | Repeat N times |
//! | `@match (expr) { pat => { ... } }` | Pattern-based emission |
//! | `@element_name(prop = val)` | Invoke a [`#[element]`](macro@element) component |
//!
//! See [`zyn!`] for the full syntax reference.
//!
//! > Templates are fully type-checked at compile time — errors appear inline, just like regular Rust code.
//!
//! ![Compile-time type safety](https://raw.githubusercontent.com/aacebo/zyn/refs/heads/main/assets/screenshots/screenshot-1.png)
//!
//! ---
//!
//! # Elements
//!
//! Elements are reusable template components defined with [`#[zyn::element]`](macro@element).
//! They encapsulate a fragment of token output and accept typed props.
//!
//! **Define an element:**
//!
//! ```ignore
//! #[zyn::element]
//! fn getter(name: zyn::syn::Ident, ty: zyn::syn::Type) -> zyn::TokenStream {
//!     zyn::zyn! {
//!         pub fn {{ name | snake | ident:"get_{}" }}(&self) -> &{{ ty }} {
//!             &self.{{ name }}
//!         }
//!     }
//! }
//! ```
//!
//! **Invoke it inside any template with `@`:**
//!
//! ```ignore
//! zyn::zyn! {
//!     impl {{ ident }} {
//!         @for (field in fields.named.iter()) {
//!             @getter(name = field.ident.clone().unwrap(), ty = field.ty.clone())
//!         }
//!     }
//! }
//! ```
//!
//! Elements can also receive **extractors** — values resolved automatically from proc macro
//! input — by marking a param with `#[zyn(input)]`:
//!
//! ```ignore
//! #[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 }
//! // }
//! ```
//!
//! See [`element`](macro@element) and [`derive`](macro@derive) for the full reference.
//!
//! ---
//!
//! # Pipes
//!
//! Pipes transform interpolated values: `{{ expr | pipe }}`. They chain left to right:
//!
//! ```ignore
//! zyn::zyn!(fn {{ name | snake | ident:"get_{}" }}() {})
//! // name = "HelloWorld" → fn get_hello_world() {}
//! ```
//!
//! **Built-in pipes:**
//!
//! | Pipe | Input example | Output |
//! |------|--------------|--------|
//! | `snake` | `HelloWorld` | `hello_world` |
//! | `pascal` | `hello_world` | `HelloWorld` |
//! | `camel` | `hello_world` | `helloWorld` |
//! | `screaming` | `HelloWorld` | `HELLO_WORLD` |
//! | `kebab` | `HelloWorld` | `"hello-world"` |
//! | `upper` | `hello` | `HELLO` |
//! | `lower` | `HELLO` | `hello` |
//! | `str` | `hello` | `"hello"` |
//! | `trim` | `__foo__` | `foo` |
//! | `plural` | `user` | `users` |
//! | `singular` | `users` | `user` |
//! | `ident:"pattern_{}"` | `hello` | `pattern_hello` (ident) |
//! | `fmt:"pattern_{}"` | `hello` | `"pattern_hello"` (string) |
//!
//! All built-in pipes are in the [`pipes`] module and re-exported by [`prelude`].
//!
//! **Custom pipes** via [`#[zyn::pipe]`](macro@pipe):
//!
//! ```ignore
//! #[zyn::pipe]
//! fn shout(input: String) -> zyn::syn::Ident {
//!     zyn::syn::Ident::new(&format!("{}_BANG", input.to_uppercase()), zyn::Span::call_site())
//! }
//!
//! zyn::zyn!(fn {{ name | shout }}() {})
//! // name = "hello" → fn HELLO_BANG() {}
//! ```
//!
//! See [`pipe`](macro@pipe) and the [`Pipe`] trait for the full reference.
//!
//! ---
//!
//! # Attributes
//!
//! zyn provides two tools for attribute handling: a derive macro for typed parsing and a
//! proc macro attribute for writing attribute macros.
//!
//! **Typed attribute structs** via [`#[derive(Attribute)]`](derive@Attribute):
//!
//! ```ignore
//! #[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")]
//! ```
//!
//! The derive generates `from_args`, `FromArg`, and `FromInput` implementations, as well as
//! a human-readable `about()` string for error messages.
//!
//! **Auto-suggest** — when a user misspells an argument name, zyn automatically suggests
//! the closest known field. No extra setup required:
//!
//! ```text
//! error: unknown argument `skiip`
//!   --> src/main.rs:5:12
//!    |
//! 5  | #[builder(skiip)]
//!    |           ^^^^^
//!    |
//!    = help: did you mean `skip`?
//! ```
//!
//! Suggestions are offered when the edit distance is ≤ 3 characters. Distant or completely
//! unknown keys produce only the "unknown argument" error without a suggestion.
//!
//! **Attribute proc macros** via [`#[zyn::attribute]`](macro@attribute):
//!
//! ```ignore
//! #[zyn::attribute]
//! fn my_attr(#[zyn(input)] item: zyn::syn::ItemFn, args: zyn::Args) -> zyn::TokenStream {
//!     // args: parsed key=value arguments from the attribute invocation
//!     zyn::zyn!({ { item } })
//! }
//! ```
//!
//! See [`Attribute`](derive@Attribute) and [`attribute`](macro@attribute) for the full reference.
//!
//! ---
//!
//! # Testing
//!
//! ## Assertions
//!
//! `zyn!` returns [`Output`] — test both tokens and diagnostics directly:
//!
//! ```ignore
//! #[test]
//! fn generates_function() {
//!     let input: zyn::Input = zyn::parse!("struct Foo;" => zyn::syn::DeriveInput).unwrap().into();
//!     let output = zyn::zyn!(fn hello() {});
//!     let expected = zyn::quote::quote!(fn hello() {});
//!     zyn::assert_tokens!(output, expected);
//! }
//! ```
//!
//! Diagnostic assertions check error messages from `error!`, `warn!`, `bail!`:
//!
//! ```ignore
//! #[zyn::element]
//! fn validated(name: zyn::syn::Ident) -> zyn::TokenStream {
//!     if name == "forbidden" {
//!         bail!("reserved identifier `{}`", name);
//!     }
//!     zyn::zyn!(fn {{ name }}() {})
//! }
//!
//! #[test]
//! fn rejects_forbidden_name() {
//!     let input: zyn::Input = zyn::parse!("struct Foo;" => zyn::syn::DeriveInput).unwrap().into();
//!     let output = zyn::zyn!(@validated(name = zyn::format_ident!("forbidden")));
//!     zyn::assert_diagnostic_error!(output, "reserved identifier");
//!     zyn::assert_tokens_empty!(output);
//! }
//!
//! #[test]
//! fn accepts_valid_name() {
//!     let input: zyn::Input = zyn::parse!("struct Foo;" => zyn::syn::DeriveInput).unwrap().into();
//!     let output = zyn::zyn!(@validated(name = zyn::format_ident!("hello")));
//!     zyn::assert_tokens_contain!(output, "fn hello");
//! }
//! ```
//!
//! | Macro | Purpose |
//! |-------|---------|
//! | `assert_tokens!` | Compare two token streams |
//! | `assert_tokens_empty!` | Assert no tokens produced |
//! | `assert_tokens_contain!` | Check for substring in output |
//! | `assert_diagnostic_error!` | Assert error diagnostic with message |
//! | `assert_diagnostic_warning!` | Assert warning diagnostic |
//! | `assert_diagnostic_note!` | Assert note diagnostic |
//! | `assert_diagnostic_help!` | Assert help diagnostic |
//! | `assert_compile_error!` | Alias for `assert_diagnostic_error!` |
//!
//! With the `pretty` feature:
//!
//! | Macro | Purpose |
//! |-------|---------|
//! | `assert_tokens_pretty!` | Compare using `prettyplease`-formatted output |
//! | `assert_tokens_contain_pretty!` | Substring check on pretty-printed output |
//!
//! ## Debugging
//!
//! Add `debug` (or `debug(pretty)`) to any zyn attribute macro and set `ZYN_DEBUG` to
//! inspect generated code at compile time:
//!
//! ```ignore
//! #[zyn::element(debug)]
//! fn greeting(name: zyn::syn::Ident) -> zyn::TokenStream {
//!     zyn::zyn!(fn {{ name }}() {})
//! }
//! ```
//!
//! ```sh
//! ZYN_DEBUG="*" cargo build
//! ```
//!
//! ```text
//! note: zyn::element ─── Greeting
//!
//!       struct Greeting { pub name : zyn :: syn :: Ident , } impl :: zyn :: Render
//!       for Greeting { fn render (& self , input : & :: zyn :: Input) -> :: zyn ::
//!       proc_macro2 :: TokenStream { ... } }
//! ```
//!
//! With the `pretty` feature, use `debug(pretty)` for formatted output:
//!
//! ```ignore
//! #[zyn::element(debug(pretty))]
//! fn greeting(name: zyn::syn::Ident) -> zyn::TokenStream {
//!     zyn::zyn!(fn {{ name }}() {})
//! }
//! ```
//!
//! ```text
//! note: zyn::element ─── Greeting
//!
//!       struct Greeting {
//!           pub name: zyn::syn::Ident,
//!       }
//!       impl ::zyn::Render for Greeting {
//!           fn render(&self, input: &::zyn::Input) -> ::zyn::Output { ... }
//!       }
//! ```
//!
//! All macros support `debug`: `#[zyn::element]`, `#[zyn::pipe]`, `#[zyn::derive]`,
//! `#[zyn::attribute]`.
//!
//! `ZYN_DEBUG` accepts comma-separated `*`-wildcard patterns matched against the generated
//! PascalCase type name:
//!
//! ```sh
//! ZYN_DEBUG="Greeting" cargo build     # exact match
//! ZYN_DEBUG="Greet*" cargo build       # prefix wildcard
//! ZYN_DEBUG="*Element" cargo build     # suffix wildcard
//! ZYN_DEBUG="Greeting,Shout" cargo build  # multiple patterns
//! ```
//!
//! See the [`test`] module for the full assertion macro reference and the [`debug`] module
//! for programmatic access via `DebugExt`.
//!
//! ---
//!
//! # Features
//!
//! | Feature | Default | Description |
//! |---------|:-------:|-------------|
//! | `derive` | ✓ | All proc macro attributes: [`element`](macro@element), [`pipe`](macro@pipe), [`derive`](macro@derive), [`attribute`](macro@attribute), and [`Attribute`](derive@Attribute) |
//! | `ext` | | Extension traits for common `syn` AST types (`AttrExt`, `FieldExt`, `TypeExt`, etc.) — see [`ext`] |
//! | `pretty` | | Pretty-printed token output in debug mode — see [`debug`] |
//! | `diagnostics` | | Error accumulation — collect multiple errors before aborting — see [`mark`] |
//!
//! ## ext
//!
//! The [`ext`] module adds ergonomic extension traits for navigating `syn` AST types.
//!
//! ```toml
//! zyn = { features = ["ext"] }
//! ```
//!
//! ```ignore
//! use zyn::ext::{AttrExt, TypeExt};
//!
//! // check and read attribute arguments
//! if attr.is("serde") {
//!     let rename: Option<_> = attr.get("rename"); // → Some(Meta::NameValue)
//!     let skip: bool = attr.exists("skip");
//! }
//!
//! // inspect field types
//! if field.is_option() {
//!     let inner = field.inner_type().unwrap();
//! }
//! ```
//!
//! See the [`ext`] module for all available traits.
//!
//! ## pretty
//!
//! The `pretty` feature enables pretty-printed output in [`debug`] mode, formatting
//! generated token streams as readable Rust source code via `prettyplease`.
//!
//! ```toml
//! zyn = { features = ["pretty"] }
//! ```
//!
//! Enable debug output per-element with the `debug` or `debug(pretty)` argument,
//! then set `ZYN_DEBUG="*"` at build time:
//!
//! ```ignore
//! #[zyn::element(debug(pretty))]
//! fn my_element(name: zyn::syn::Ident) -> zyn::TokenStream {
//!     zyn::zyn!(struct {{ name }} {})
//! }
//! ```
//!
//! ```sh
//! ZYN_DEBUG="*" cargo build
//! ```
//!
//! ```text
//! note: zyn::element ─── my_element
//!
//!     struct MyElement {
//!         pub name: zyn::syn::Ident,
//!     }
//!     impl ::zyn::Render for MyElement {
//!         fn render(&self, input: &::zyn::Input) -> ::zyn::Output {
//!             ...
//!         }
//!     }
//! ```
//!
//! > An element annotated with `debug` — the argument is inert until `ZYN_DEBUG` is set.
//!
//! ![Element with debug arg](https://raw.githubusercontent.com/aacebo/zyn/refs/heads/main/assets/screenshots/screenshot-2.png)
//!
//! > Raw debug output shown as an inline compiler diagnostic in the editor.
//!
//! ![Raw debug output — inline diagnostic](https://raw.githubusercontent.com/aacebo/zyn/refs/heads/main/assets/screenshots/screenshot-3.png)
//!
//! > The same raw output surfaced in the Problems panel for easy navigation.
//!
//! ![Raw debug output — Problems panel](https://raw.githubusercontent.com/aacebo/zyn/refs/heads/main/assets/screenshots/screenshot-4.png)
//!
//! > Pretty-printed debug output — formatted with `prettyplease` for readable, indented Rust code.
//!
//! ![Pretty debug output](https://raw.githubusercontent.com/aacebo/zyn/refs/heads/main/assets/screenshots/screenshot-5.png)
//!
//! See the [`debug`] module for programmatic access via `DebugExt`.
//!
//! ## diagnostics
//!
//! The `diagnostics` feature enables error accumulation — collecting multiple compiler
//! errors before aborting, so users see all problems at once instead of one at a time.
//!
//! ```toml
//! zyn = { features = ["diagnostics"] }
//! ```
//!
//! Inside any `#[zyn::element]`, `#[zyn::derive]`, or `#[zyn::attribute]` body, use the
//! built-in diagnostic macros directly — no setup required:
//!
//! ```ignore
//! #[zyn::element]
//! fn my_element(name: zyn::syn::Ident) -> zyn::TokenStream {
//!     if name == "forbidden" {
//!         bail!("reserved identifier `{}`", name);
//!     }
//!
//!     if name.to_string().starts_with('_') {
//!         warn!("identifiers starting with `_` are conventionally unused");
//!     }
//!
//!     zyn::zyn!(fn {{ name }}() {})
//! }
//! ```
//!
//! | Macro | Level | Behaviour |
//! |-------|-------|-----------|
//! | `error!(msg)` | error | accumulates, does not stop execution |
//! | `warn!(msg)` | warning | accumulates, does not stop execution |
//! | `note!(msg)` | note | accumulates, does not stop execution |
//! | `help!(msg)` | help | accumulates, does not stop execution |
//! | `bail!(msg)` | error | accumulates and immediately returns |
//!
//! All accumulated diagnostics are emitted together at the end of the element or macro body,
//! so users see every error at once instead of fixing them one by one.
//!
//! ```text
//! error: reserved identifier `forbidden`
//!  --> src/main.rs:3:1
//!
//! error: reserved identifier `forbidden`
//!  --> src/main.rs:7:1
//! ```
//!
//! See the [`mark`] module for the lower-level diagnostic builder API.

pub use zyn_core::*;

#[cfg(feature = "derive")]
pub use zyn_derive::*;

pub mod test;

/// The zyn prelude. Re-exports all built-in pipes, core traits, and proc macros.
pub mod prelude {
    pub use crate::pipes::*;
    pub use crate::{Diagnostic, Output, Pipe, Render};

    #[cfg(feature = "derive")]
    pub use zyn_derive::*;

    #[cfg(feature = "ext")]
    pub use zyn_core::ext::*;
}