fack-codegen 0.1.1

Standalone code generation engine for fack error handling
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# fack

A declarative error handling library for Rust that eliminates boilerplate through intelligent macro-driven code generation.

## Overview

`fack` provides a `#[derive(Error)]` macro that generates complete `Error` and `Display` implementations from declarative attributes. The library is architected for maximum compatibility: `no_std` by default, zero runtime allocations, and composable code generation primitives.

<br>

## Architecture

The workspace comprises four specialized crates:

<br>

- **fack**: Unified facade providing the complete error handling API
- **fack-core**: Trait definitions with `no_std` compatibility, zero dependencies
- **fack-macro**: Procedural macro entry point for `#[derive(Error)]`
- **fack-codegen**: Standalone code generation engine, usable outside proc-macro contexts

### Design Principles

**no_std First**: All crates operate without the standard library. Generated code uses `::core` by default, with opt-in `::std` support.

<br>

**no_alloc Runtime**: While code generation uses `alloc` for internal data structures, the generated error implementations require no heap allocation during normal operation.

<br>

**Composable Code Generation**: `fack-codegen` is deliberately not a proc-macro crate, enabling direct integration into custom build systems, code generators, or other procedural macros.

<br>

**Span Preservation**: The macro preserves source spans from the original code, ensuring error messages, IDE hints, and language server features point to the correct locations in your source files. This provides an unparalleled LSP experience with accurate go-to-definition, hover information, and diagnostics.

---

## Usage

```toml
[dependencies]
fack = "0.1.0"
```

```rust,no_run
use fack::prelude::*;

#[derive(Error, Debug)]
#[error("configuration error: {message}")]
struct ConfigError {
    message: String,
}
```

---

## Attribute Reference

The `#[error(...)]` attribute controls all aspects of error behavior. Multiple attributes can be applied to a single type or variant, each serving a distinct purpose.

<br>

### Format String: `#[error("...")]`

A `Display` implementation is generated for your error if you provide `#[error("...")]` messages on the struct or each variant of your enum.

<br>

The messages support a shorthand for interpolating fields from the error:

- `#[error("{var}")]``write!("{}", self.var)`
- `#[error("{0}")]``write!("{}", self.0)`
- `#[error("{var:?}")]``write!("{:?}", self.var)`
- `#[error("{0:?}")]``write!("{:?}", self.0)`

<br>

These shorthands can be used together with any additional format arguments, which may be arbitrary expressions. For example:

```rust,no_run
#[derive(Error, Debug)]
pub enum Error {
    #[error("invalid rdo_lookahead_frames {0} (expected < {max})", max = i32::MAX)]
    InvalidLookahead(u32),
}
```

<br>

If one of the additional expression arguments needs to refer to a field of the struct or enum, then refer to named fields as `.var` and tuple fields as `.0`:

```rust,no_run
#[derive(Error, Debug)]
pub enum Error {
    #[error("first letter must be lowercase but was {:?}", first_char(.0))]
    WrongCase(String),

    #[error("invalid index {idx}, expected at least {} and at most {}", .limits.lo, .limits.hi)]
    OutOfBounds { idx: usize, limits: Limits },
}
```

<br>

All format arguments are evaluated in the context of the error type, with fields automatically destructured for access.

<br>

### Source Declaration: `#[error(source(field))]`

The Error trait's `source()` method is implemented to return whichever field has a `#[error(source(...))]` attribute, if any. This is for identifying the underlying lower-level error that caused your error.

<br>

Any error type that implements `std::error::Error` or dereferences to `dyn std::error::Error` will work as a source.

<br>

```rust,no_run
#[derive(Error, Debug)]
pub struct MyError {
    msg: String,
    #[error(source(cause))]
    cause: std::io::Error,
}
```

<br>

The source field can be referenced by name for named fields:

```rust,no_run
#[derive(Error, Debug)]
#[error("network request failed")]
#[error(source(io_error))]
struct NetworkError {
    io_error: std::io::Error,
    url: String,
}
```

<br>

Or by index for tuple struct fields:

```rust,no_run
#[derive(Error, Debug)]
#[error("wrapped error")]
#[error(source(0))]
struct Wrapper(std::io::Error, String);
```

The `source()` method returns `Option<&(dyn std::error::Error + 'static)>`, enabling error chain traversal for debugging and logging purposes.

### Transparent Forwarding: `#[error(transparent(field))]`

Errors may use `#[error(transparent(field))]` to forward the source and Display methods straight through to an underlying error without adding an additional message. This would be appropriate for enums that need an "anything else" variant:

<br>

```rust,no_run
#[derive(Error, Debug)]
pub enum MyError {
    #[error("something went wrong")]
    SomethingBad,

    #[error(transparent(0))]
    Other(anyhow::Error),  // source and Display delegate to anyhow::Error
}
```

<br>

Another use case is hiding implementation details of an error representation behind an opaque error type, so that the representation is able to evolve without breaking the crate's public API:

```rust,no_run
// PublicError is public, but opaque and easy to keep compatible.
#[derive(Error, Debug)]
#[error(transparent(inner))]
pub struct PublicError {
    inner: ErrorRepr,
}

impl PublicError {
    // Accessors for anything we do want to expose publicly.
}

// Private and free to change across minor versions of the crate.
#[derive(Error, Debug)]
enum ErrorRepr {
    // ...
}
```

<br>

Transparent errors behave identically to their wrapped type for both display and error chaining purposes. The specified field must implement `std::error::Error`.

<br>

### Automatic Conversion: `#[error(from)]`

A `From` implementation is generated for each variant or struct that contains an `#[error(from)]` attribute. This enables automatic error conversion using the `?` operator.

<br>

The variant or struct using `#[error(from)]` must contain exactly one field. The field may be named or unnamed:

<br>

```rust,no_run
#[derive(Error, Debug)]
pub enum MyError {
    #[error("io error")]
    #[error(from)]
    Io(std::io::Error),

    #[error("parse error")]
    #[error(from)]
    Parse(std::num::ParseIntError),
}
```

<br>

This generates:

```rust,no_run
impl From<std::io::Error> for MyError {
    fn from(source: std::io::Error) -> Self {
        MyError::Io(source)
    }
}

impl From<std::num::ParseIntError> for MyError {
    fn from(source: std::num::ParseIntError) -> Self {
        MyError::Parse(source)
    }
}
```

<br>

Named field example:

```rust,no_run
#[derive(Error, Debug)]
#[error("io operation failed")]
#[error(from)]
struct IoError {
    inner: std::io::Error,
}
```

<br>

The `#[error(from)]` attribute always implies that the same field is also the error source, so you don't need to specify `#[error(source(...))]` separately when using `#[error(from)]`.

<br>

### Inline Control: `#[error(inline(...))]`

Controls the inlining behavior of generated trait implementations. This attribute allows fine-tuning performance characteristics of error handling code.

<br>

**Syntax**: `#[error(inline(strategy))]`

<br>

**Available strategies**:

- **`neutral`** (default): Emits `#[inline]`, which hints to the compiler that inlining may be beneficial but leaves the final decision to the optimizer. This is appropriate for most error types.

<br>

- **`always`**: Emits `#[inline(always)]`, which strongly suggests to the compiler that the function should always be inlined. Use this for performance-critical error paths where you want to eliminate function call overhead:

<br>

  ```rust,no_run
  #[derive(Error, Debug)]
  #[error(inline(always))]
  #[error("fast path error: {code}")]
  struct FastError {
      code: u32,
  }
  ```

<br>

- **`never`**: Emits `#[inline(never)]`, which prevents the compiler from inlining the function. Use this to reduce code size when errors are rarely constructed or when you want consistent stack traces:

<br>

  ```rust,no_run
  #[derive(Error, Debug)]
  #[error(inline(never))]
  #[error("rare error condition")]
  struct RareError {
      details: String,
  }
  ```

<br>

The inline strategy applies to all generated methods: `fmt` for Display, `source` for Error, and `from` if `#[error(from)]` is used. When applied at the enum level, it affects all variants.

<br>

### Import Root: `#[error(import(path))]`

By default, all generated code uses `::core` for maximum compatibility with `no_std` environments. The `#[error(import(path))]` attribute overrides this default, allowing you to specify an alternative import root.

<br>

**Syntax**: `#[error(import(::path))]`

<br>

**Common use cases**:

**Using `std` instead of `core`**: When your crate requires the standard library and you want to explicitly use `std::error::Error` and `std::fmt`:

<br>

```rust,no_run
#[derive(Error, Debug)]
#[error(import(::std))]
#[error("standard error")]
struct StdError {
    message: String,
}
```

<br>

This generates code using `::std` instead of the default `::core`:

<br>
```rust,no_run
impl ::std::error::Error for StdError { /* ... */ }
impl ::std::fmt::Display for StdError { /* ... */ }
```

<br>

**Explicit `core` usage**: While `::core` is the default, you can make it explicit:

<br>

```rust,no_run
#[derive(Error, Debug)]
#[error(import(::core))]
#[error("explicit core error")]
struct CoreError {
    msg: String,
}
```

<br>

**Custom preludes**: When integrating with custom preludes or re-exports:

<br>

```rust,no_run
#[derive(Error, Debug)]
#[error(import(crate::prelude))]
#[error("custom prelude error")]
struct CustomError {
    msg: String,
}
```

<br>

The import root affects all generated trait implementations and macro invocations. This attribute is particularly useful when:
- Explicitly targeting `std` in std-only crates
- Making `core` usage explicit for documentation purposes
- Working with custom error trait definitions
- Integrating with frameworks that provide their own error handling primitives

---

## Struct Patterns

### Standalone Errors

Simple errors with custom messages and optional source fields:

<br>

```rust,no_run
#[derive(Error, Debug)]
#[error("operation failed: {reason}")]
struct OperationError {
    reason: String,
}
```

<br>

### Errors with Source

Chaining errors while providing custom context:

<br>

```rust,no_run
#[derive(Error, Debug)]
#[error("database query failed: {}", query)]
#[error(source(cause))]
struct QueryError {
    query: String,
    cause: sqlx::Error,
}
```

<br>

### Transparent Wrappers

New-type wrappers that preserve the inner error's display and source:

<br>

```rust,no_run
#[derive(Error, Debug)]
#[error(transparent(0))]
struct DatabaseError(sqlx::Error);
```

<br>

### Convertible Wrappers

New-types with automatic conversion and custom display:

<br>

```rust,no_run
#[derive(Error, Debug)]
#[error("integer parsing failed")]
#[error(from)]
struct IntError(std::num::ParseIntError);

// Enables: let err: IntError = "abc".parse::<i32>().unwrap_err().into();
```

---

## Enum Patterns

Enums support per-variant attribute configuration, enabling complex error hierarchies with minimal code.

<br>

### Basic Enum

<br>

```rust,no_run
#[derive(Error, Debug)]
enum FileError {
    #[error("file not found: {}", path)]
        NotFound { path: String },

        #[error("permission denied: {}", path)]
        PermissionDenied { path: String },

    #[error("file is a directory")]
    IsDirectory,
}
```

<br>

### Enum with Sources

Each variant can specify its own source field:

<br>

```rust,no_run
#[derive(Error, Debug)]
enum ApplicationError {
    #[error("database error")]
    #[error(source(0))]
    Database(sqlx::Error),

    #[error("network error")]
    #[error(source(io))]
    Network { io: std::io::Error },

    #[error("configuration error: {0}")]
    Config(String),
}
```

<br>

### Enum with Transparent Variants

Mix transparent and custom variants:

<br>

```rust,no_run
#[derive(Error, Debug)]
enum ServerError {
    #[error(transparent(0))]
    Io(std::io::Error),

    #[error(transparent(inner))]
    Database { inner: sqlx::Error },

    #[error("invalid request: {}", message)]
    BadRequest { message: String },
}
```

<br>

### Enum with From Conversions

Enable automatic conversion for specific variants:

<br>

```rust,no_run
#[derive(Error, Debug)]
enum ParseError {
    #[error("integer parse failed")]
    #[error(from)]
    Int(std::num::ParseIntError),

    #[error("float parse failed")]
    #[error(from)]
    Float(std::num::ParseFloatError),

    #[error("syntax error: {0}")]
    Syntax(String),
}

// Enables automatic conversion:
// let err: ParseError = "abc".parse::<i32>().unwrap_err().into();
```

<br>

### Enum-Level Attributes

Type-level attributes apply to all variants:

<br>

```rust,no_run
#[derive(Error, Debug)]
#[error(inline(always))]
#[error(import(::std))]
enum OptimizedError {
    #[error("first variant")]
    First,

    #[error("second variant")]
    Second,
}
```

## Field Reference Syntax

Fields can be referenced by name or position:

<br>

**Named fields**: Use the field's identifier

<br>
```rust,no_run
#[error(source(field_name))]
#[error(transparent(field_name))]
```

<br>

**Tuple fields**: Use zero-based numeric indices

<br>
```rust,no_run
#[error(source(0))]
#[error(transparent(1))]
```

---

## Composability with fack-codegen

The `fack-codegen` crate provides the code generation engine as a standalone library, distinct from the proc-macro interface. This enables integration into custom tooling:

<br>

```rust,no_run
use fack_codegen::{Target, expand::Expand};

// Parse error definition
let target = Target::input(&derive_input)?;

// Generate implementation
let expanded = Expand::target(target)?;
```

<br>

**Use cases**:
- Custom derive macros that extend error functionality
- Build-time code generation without proc-macros
- IDE tooling and code analysis
- Error schema validation and documentation generation

<br>

The separation between `fack-macro` (proc-macro interface) and `fack-codegen` (pure logic) ensures the generation logic remains accessible in contexts where proc-macros cannot be used.

---

## Type Support

**Supported**: Structs (named, tuple, unit) and enums with any variant style

<br>

**Unsupported**: Union types (unions cannot implement `Error`)

<br>

## Generated Code Guarantees

All implementations include:
- `#[automatically_derived]` attribute for tool recognition and linter warning supression
- Proper destructuring of fields in pattern matches
- Correct forwarding of lifetimes and generic parameters
- No unsafe code
- No heap allocations in generated methods (all `no_std`-compatible!)

## License

Copyright (C) 2025 W. Frakchi

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

See [the full license agreement](LICENSE.md) for further information.