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.
Architecture
The workspace comprises four specialized crates:
- fack: Unified facade providing the complete error handling API
- fack-core: Trait definitions with
no_stdcompatibility, 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.
no_alloc Runtime: While code generation uses alloc for internal data structures, the generated error implementations require no heap allocation during normal operation.
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.
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
[]
= "0.1.0"
use *;
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.
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.
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)
These shorthands can be used together with any additional format arguments, which may be arbitrary expressions. For example:
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:
All format arguments are evaluated in the context of the error type, with fields automatically destructured for access.
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.
Any error type that implements std::error::Error or dereferences to dyn std::error::Error will work as a source.
The source field can be referenced by name for named fields:
Or by index for tuple struct fields:
;
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:
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:
// PublicError is public, but opaque and easy to keep compatible.
// Private and free to change across minor versions of the crate.
Transparent errors behave identically to their wrapped type for both display and error chaining purposes. The specified field must implement std::error::Error.
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.
The variant or struct using #[error(from)] must contain exactly one field. The field may be named or unnamed:
This generates:
Named field example:
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)].
Inline Control: #[error(inline(...))]
Controls the inlining behavior of generated trait implementations. This attribute allows fine-tuning performance characteristics of error handling code.
Syntax: #[error(inline(strategy))]
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.
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:
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:
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.
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.
Syntax: #[error(import(::path))]
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:
This generates code using ::std instead of the default ::core:
Explicit core usage: While ::core is the default, you can make it explicit:
Custom preludes: When integrating with custom preludes or re-exports:
The import root affects all generated trait implementations and macro invocations. This attribute is particularly useful when:
- Explicitly targeting
stdin std-only crates - Making
coreusage 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:
Errors with Source
Chaining errors while providing custom context:
Transparent Wrappers
New-type wrappers that preserve the inner error's display and source:
;
Convertible Wrappers
New-types with automatic conversion and custom display:
;
// 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.
Basic Enum
Enum with Sources
Each variant can specify its own source field:
Enum with Transparent Variants
Mix transparent and custom variants:
Enum with From Conversions
Enable automatic conversion for specific variants:
// Enables automatic conversion:
// let err: ParseError = "abc".parse::<i32>().unwrap_err().into();
Enum-Level Attributes
Type-level attributes apply to all variants:
Field Reference Syntax
Fields can be referenced by name or position:
Named fields: Use the field's identifier
Tuple fields: Use zero-based numeric indices
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:
use ;
// Parse error definition
let target = input?;
// Generate implementation
let expanded = target?;
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
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
Unsupported: Union types (unions cannot implement Error)
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 for further information.