Yoshi Derive - Advanced Error Handling Macros

Enterprise-grade procedural macros for the Yoshi error handling framework with mathematical precision and performance optimization.
๐ฏ Overview
yoshi-derive provides sophisticated derive macros and attribute processors that generate optimized error handling code with compile-time validation, performance hints, and intelligent error mapping strategies. Built on Rust 1.87's enhanced macro system with precise capturing in traits and stabilized intrinsics for optimal code generation.
Key Features
- ๐ฅ Advanced AST Analysis - O(n) complexity with intelligent memoization
- โก Compile-time Validation - Zero runtime cost with enhanced error reporting
- ๐ Performance-optimized Code Generation - SIMD-friendly patterns and cache optimization
- ๐ก๏ธ Type-safe Error Mapping - Precise capturing and phantom type validation
- ๐ง Smart Contextual Analysis - Dependency graph resolution for optimal error chains
- ๐ Enterprise-grade Documentation - Comprehensive rustdoc coverage
Mathematical Properties
- Time Complexity: O(V + A + F) where V=variants, A=attributes, F=fields
- Space Complexity: O(V) for variant analysis + O(A) for attribute cache
- Code Generation: O(1) amortized per variant through template-based expansion
- Expected Performance: <100ms compilation overhead for typical error enums (<50 variants)
๐ Quick Start
Add to your Cargo.toml:
[]
= "0.1.0"
= "0.1.0"
Basic Usage
use YoshiError;
use PathBuf;
๐ Comprehensive Attribute Reference
Container Attributes (#[yoshi(...)] on enums)
| Attribute | Type | Description | Example |
|---|---|---|---|
error_code_prefix |
String |
Global prefix for error codes | #[yoshi(error_code_prefix = "HTTP")] |
default_severity |
u8 |
Default severity level (0-255) | #[yoshi(default_severity = 75)] |
performance_monitoring |
bool |
Enable performance tracking | #[yoshi(performance_monitoring = true)] |
tracing_integration |
bool |
Enable tracing support | #[yoshi(tracing_integration = true)] |
Variant Attributes (#[yoshi(...)] on enum variants)
| Attribute | Type | Description | Example |
|---|---|---|---|
display |
String |
Custom display format string | #[yoshi(display = "Error: {message}")] |
kind |
String |
Map to YoshiKind variant | #[yoshi(kind = "Network")] |
error_code |
u32 |
Unique error code | #[yoshi(error_code = 1001)] |
severity |
u8 |
Severity level (0-255) | #[yoshi(severity = 80)] |
transient |
bool |
Mark as retryable error | #[yoshi(transient = true)] |
context |
String |
Default context message | #[yoshi(context = "Operation failed")] |
suggestion |
String |
Recovery suggestion | #[yoshi(suggestion = "Check network")] |
Field Attributes (#[yoshi(...)] on struct fields)
| Attribute | Type | Description | Example |
|---|---|---|---|
source |
Flag | Mark as error source | #[yoshi(source)] |
context |
String |
Add to context metadata | #[yoshi(context = "file_path")] |
shell |
Flag | Add as typed shell | #[yoshi(shell)] |
skip |
Flag | Skip in Display formatting | #[yoshi(skip)] |
suggestion |
String |
Field-level suggestion | #[yoshi(suggestion = "Check file")] |
๐๏ธ Advanced Usage Examples
Complete Error Enum with All Features
use YoshiError;
use Error;
use ;
Generated Code Overview
The derive macro automatically generates:
๐ง Intelligent Auto-Inference System
The derive macro includes sophisticated pattern recognition for automatic attribute inference:
Kind Inference by Variant Name
- Names containing
timeout,expiredโkind = "Timeout" - Names containing
network,connection,httpโkind = "Network" - Names containing
not_found,missingโkind = "NotFound" - Names containing
internal,bug,panicโkind = "Internal" - Names containing
resource,limit,quotaโkind = "ResourceExhausted"
Field Type Analysis
std::io::Errorโsource = trueBox<dyn std::error::Error>โsource = truereqwest::Errorโsource = true- Field names containing
path,fileโcontext = "file_path" - Field names containing
url,uriโcontext = "endpoint" - Field names containing
user,idโcontext = "identifier"
Display Format Inference
- Single field variants get
display = "{variant_name}: {field}" - Multi-field variants get contextual formatting based on field names
๐จ YoshiKind Mapping System
The derive macro intelligently maps error variants to appropriate YoshiKind categories:
| Variant Kind | Generated YoshiKind | Typical Use Case |
|---|---|---|
"Io" |
YoshiKind::Io |
File system, I/O operations |
"Network" |
YoshiKind::Network |
HTTP, TCP, networking errors |
"Config" |
YoshiKind::Config |
Configuration parsing, validation |
"Validation" |
YoshiKind::Validation |
Input validation, format checking |
"Internal" |
YoshiKind::Internal |
Logic errors, invariant violations |
"NotFound" |
YoshiKind::NotFound |
Resource lookup failures |
"Timeout" |
YoshiKind::Timeout |
Operation timeouts |
"ResourceExhausted" |
YoshiKind::ResourceExhausted |
Memory, connection limits |
โก Performance Characteristics
Compilation Performance
- Typical Enums (<50 variants): <100ms overhead
- Large Enums (50-200 variants): <500ms overhead
- Worst Case (>200 variants): May approach 1-2s but with optimizations
Runtime Performance
- Error Creation: O(1) - Zero runtime cost from macros
- Display Formatting: Depends on generated format strings
- Context Attachment: O(1) per context item
- Shell Access: O(1) hash map lookup
Memory Efficiency
- Generated code uses static string literals where possible
- Minimal heap allocations during error creation
- Efficient struct layouts for variant data
๐ Compile-time Validation
The derive macro performs extensive validation to catch errors early:
Structural Validation
- โ
Only one
#[yoshi(source)]field per variant - โ Valid identifier patterns for context keys
- โ Severity levels within valid ranges (0-255)
- โ Error codes are unique within enum
- โ Display format placeholders match field names
Performance Analysis
- ๐ Warnings for overly complex display formats
- ๐ Hints for optimal field ordering
- ๐ Suggestions for shell vs context usage
- ๐ Detection of redundant attributes
Security Considerations
- ๐ Input sanitization for all user-provided strings
- ๐ Validation of format string patterns
- ๐ Prevention of code injection through attributes
๐งช Testing and Quality Assurance
Macro Testing Examples
๐ Integration with Yoshi
With yoshi-std
use YoshiError;
use ;
With Tracing Integration
// Automatically generates tracing events
let error = ProcessingFailed ;
let yoshi_error: Yoshi = error.into;
yoshi_error.make_event;
๐ ๏ธ Development and Contributing
Building from Source
Running Tests
# Unit tests
# Integration tests
# Doc tests
# Benchmark tests
Performance Profiling
# Profile compilation performance
# Run comprehensive benchmarks
# Generate detailed performance reports
# Profile macro expansion
๐ Performance Benchmarking and Analysis
Benchmark Results Summary
Latest Performance Analysis: January 27, 2025 Environment: Windows x64, Rust 1.84.0 Reference: Complete Benchmark Report
โ Excellent Performance Areas
| Metric | Performance | Status |
|---|---|---|
| Basic Error Creation | 49-162ns | โ Excellent |
| Cross-Crate Integration | 1.4-22ยตs | โ Excellent |
| Memory Efficiency | ~8ยตs/100 errors | โ Excellent |
| Simple Error Formatting | 347ns-1.2ยตs | โ Excellent |
โ ๏ธ Performance Concerns
| Issue | Current Performance | Target | Action Required |
|---|---|---|---|
| Error Chain Formatting | 9.7ms (10-chain) | <100ยตs | ๐ด Critical Fix Needed |
| Display Formatting | +4% regression | 0% regression | ๐ก Investigation Required |
| Database Scenarios | +8% slower | โค5% tolerance | ๐ก Optimization Needed |
Performance Targets vs Actual
โ
Error Creation: Target: <1ยตs | Actual: 49-162ns | ๐ฏ EXCEEDED
โ
Memory Usage: Target: <1KB | Actual: 128-384B | ๐ฏ EXCEEDED
โ
Integration: Target: <50ยตs | Actual: 1.4-22ยตs | ๐ฏ EXCEEDED
โ Chain Formatting: Target: <100ยตs | Actual: 9.7ms | ๐จ 97x OVER
โ
Simple Formatting: Target: <10ยตs | Actual: 347ns-1.2ยตs | ๐ฏ EXCEEDED
Macro Compilation Performance Details
The yoshi-derive macro is designed for zero-runtime overhead with compile-time generation:
- Macro Expansion: < 5ms for typical error enums
- Code Generation: O(n) scaling with number of variants
- Compilation Impact: Minimal - comparable to hand-written implementations
- Binary Size: Near-zero overhead - only generates necessary code
Runtime Performance Analysis
Error Creation (Sub-microsecond)
// Benchmark: 49-162ns per operation
let error = NetworkTimeout ; // ~162ns
Memory Allocation Patterns
Basic Error: 128 bytes (1 allocation)
With Context: 256 bytes (2 allocations)
With Shell: 384 bytes (3 allocations)
Error Chain: 128n bytes (n+1 allocations)
Cross-Crate Integration
// Benchmark: 1.4-22ยตs depending on complexity
let yoshi_error: Yoshi = my_error.into; // ~5.2ยตs
Critical Performance Issue: Error Chain Formatting
Current Behavior: O(nยฒ) scaling for error chain formatting
1 chain: 13.2ยตs (acceptable)
2 chains: 89.4ยตs (acceptable)
5 chains: 1.2ms (concerning)
10 chains: 9.7ms (unacceptable)
Root Cause: Recursive string allocation and inefficient chain traversal
Proposed Solution:
// Replace recursive approach with iterative O(n) algorithm
Performance Monitoring
The derive macro can optionally generate performance monitoring code:
// Automatically tracks creation time, memory usage, and frequency
let error = NetworkError ;
error.track_creation; // Records performance metrics
Optimization Recommendations
Immediate Actions
- Fix error chain formatting scaling - Replace O(nยฒ) with O(n) algorithm
- Investigate display formatting regression - Profile recent changes
- Optimize database scenario performance - Reduce 8% overhead
Future Optimizations
- Implement lazy formatting - Defer expensive string operations
- Add performance budgets - CI-based performance regression testing
- Optimize memory allocation - Use
SmallVecand object pooling - SIMD string processing - Leverage CPU-specific optimizations
๐ Additional Resources
- Main Yoshi Documentation - Complete framework overview
- API Documentation - Detailed API reference
- Examples Repository - Real-world usage examples
- Performance Guide - Optimization strategies
- Migration Guide - Upgrading from other error crates
๐ข Enterprise Information
Powered by ArcMoon Studios - Where precision meets innovation.
- Business Inquiries: LordXyn@proton.me
- Technical Support: GitHub Issues
- License: Business Source License 1.1 (BSL-1.1)
- Commercial License: Available for production use
License Terms
- โ Non-production use: Free for development, testing, and evaluation
- โ Open source projects: Free under BSL-1.1 terms
- ๐ผ Commercial/Production use: Requires paid license
- ๐ Change Date: 2025-05-25 (converts to GPL v3)
๐ Roadmap
- v0.2.0: Enhanced macro diagnostics and IDE integration
- v0.3.0: Custom derive macro for error context types
- v0.4.0: Integration with cargo expand for debugging
- v1.0.0: Stable API with full Rust 1.87+ feature support
GitHub: ArcMoon Studios | Copyright: (c) 2025 ArcMoon Studios | Author: Lord Xyn
Mathematical precision. Enterprise excellence. Zero compromises.