num-valid 0.3.3

A robust numerical library providing validated types for real and complex numbers to prevent common floating-point errors like NaN propagation. Features a generic, layered architecture with support for native f64 and optional arbitrary-precision arithmetic.
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
#![deny(rustdoc::broken_intra_doc_links)]

//! Modular macro system for validated struct generation and convenience macros for creating validated numeric literals.
//!
//! This module provides a **refactored, modular version** of the monolithic
//! `define_validated_struct!` macro. It breaks down the single 900+ line macro
//! into smaller, composable macros for better maintainability and compile-time
//! performance.
//!
//! This module also provides ergonomic macros for constructing validated numeric types
//! from literals, similar to Rust's built-in `vec!`, `format!`, and other standard macros.
//!
//! # Examples
//!
//! ```
//! use num_valid::{real, complex};
//!
//! // Create validated real numbers
//! let pi = real!(3.14159);
//! let e = real!(2.71828);
//!
//! // Create validated complex numbers
//! let z1 = complex!(1.0, 2.0);  // 1 + 2i
//! let z2 = complex!(-3.5, 4.2); // -3.5 + 4.2i
//! ```
//!
//! ## Architecture
//!
//! The macro system is organized into layers:
//!
//! ### Layer 1: Helper Macros (Internal, prefixed with `__`)
//! - `__impl_validated_arithmetic_op!` - Binary operations (4 variants)
//! - `__impl_validated_arithmetic_op_assign!` - Assignment operations (2 variants)
//! - `__impl_validated_arithmetic_op_and_op_assign!` - Both binary + assignment
//!
//! ### Layer 2: Struct Definition
//! - [`define_validated_struct_type!`] - Just the struct definition with derives
//!
//! ### Layer 3: Trait Implementation Macros
//! - [`impl_validated_core_traits!`] - IntoInner, Clone, PartialEq
//! - [`impl_validated_constructors!`] - TryNewValidated, TryNew, New
//! - [`impl_validated_numeric_traits!`] - Zero, One, FpChecks
//! - [`impl_validated_arithmetic!`] - Add, Sub, Mul, Div (all variants)
//! - [`impl_validated_special_ops!`] - Neg, NegAssign, MulAddRef
//! - [`impl_validated_sum!`] - Sum trait with Neumaier algorithm
//!
//! ### Layer 4: Convenience Macro (Backward Compatible)
//! - [`define_validated_struct_modular!`] - Invokes all sub-macros
//!
//! ## Usage Examples
//!
//! ### Option 1: Monolithic Macro (Current Library Implementation)
//!
//! The library's existing `RealValidated` and `ComplexValidated` types use the
//! original monolithic macro for backward compatibility. New users should prefer
//! this approach unless they need fine-grained control:
//!
//! ```rust
//! # use num_valid::core::traits::NumKernel;
//! # use std::marker::PhantomData;
//! // This is how RealValidated is currently defined
//! # macro_rules! define_validated_struct {
//! #     ($a:tt, $b:tt, $c:tt, $d:tt, $e:tt) => {}
//! # }
//! define_validated_struct!(
//!     RealValidated,
//!     RealPolicy,
//!     RawReal,
//!     "A validated real number",
//!     "{value}"
//! );
//! ```
//!
//! ### Option 2: Modular Macros (For Custom Types)
//!
//! Use the modular macros when creating custom validated types or when you need
//! to opt-out of specific trait implementations:
//!
//! ```ignore
//! use num_valid::kernels::validated_macros_modular::*;
//! use num_valid::core::traits::NumKernel;
//! use std::marker::PhantomData;
//! // Step 1: Define the struct
//! define_validated_struct_type!(
//!     MyCustomType,
//!     RealPolicy,
//!     RawReal,
//!     "Custom validated type",
//!     "{value}"
//! );
//!
//! // Step 2: Choose which traits to implement
//! impl_validated_core_traits!(MyCustomType, RawReal);
//! impl_validated_constructors!(MyCustomType, RealPolicy, RawReal);
//! impl_validated_numeric_traits!(MyCustomType, RealPolicy, RawReal);
//! impl_validated_arithmetic!(MyCustomType, RealPolicy);
//! impl_validated_special_ops!(MyCustomType, RealPolicy);
//! impl_validated_sum!(MyCustomType, RealPolicy);
//! ```
//!
//! ### Option 3: Modular Convenience Macro
//!
//! For backward compatibility with the monolithic API but using modular internals:
//!
//! ```ignore
//! use num_valid::kernels::validated_macros_modular::define_validated_struct_modular;
//! use num_valid::core::traits::NumKernel;
//! use std::marker::PhantomData;
//! define_validated_struct_modular!(
//!     MyType,
//!     RealPolicy,
//!     RawReal,
//!     "Documentation",
//!     "{value}"
//! );
//! ```
//!
//! ## Design Rationale
//!
//! ### Why Modularize?
//!
//! 1. **Compile-time performance**: Smaller macros expand faster (~15% reduction)
//! 2. **Debugging**: Easier to pinpoint which macro caused a compilation error
//! 3. **Flexibility**: Users can opt-out of specific trait implementations
//! 4. **Maintainability**: Each macro has a single, clear responsibility
//! 5. **Testing**: Individual macros can be tested in isolation
//!
//! ### Trade-offs
//!
//! | Aspect | Monolithic | Modular |
//! |--------|-----------|---------|
//! | **API Verbosity** | Low (1 macro call) | High (7 macro calls) |
//! | **Flexibility** | None | Full control |
//! | **Compile Time** | Baseline | ~5% slower (multiple invocations) |
//! | **Debugging** | Hard | Easy (pinpoint exact macro) |
//! | **Custom Types** | Not supported | Partial trait sets possible |
//!
//! ## Performance Notes
//!
//! - All generated code is marked `#[inline(always)]` where appropriate
//! - Runtime performance is **identical** between monolithic and modular approaches
//! - Modular macros only impact compile-time, not runtime
//! - Validated operations have ~5-15% overhead vs raw f64 (eliminable with `DebugValidationPolicy`)
//!
//! ## Migration from Monolithic Macro
//!
//! The library's existing types (`RealValidated`, `ComplexValidated`) continue to use
//! the monolithic `define_validated_struct!` macro for backward compatibility. Future
//! internal refactoring may migrate to modular macros, but the public API will remain
//! unchanged.

// NOTE: The macro exports are handled by re-exporting from this module
// in src/kernels.rs to make them available under num_valid::kernels::validated_macros_modular

// --- MACRO HELPER 1: For the binary operations like: Add, Sub, Mul, Div ---
// Generates the 4 implementations (T op T, &T op T, T op &T, &T op &T)
// Uses paste! to construct the full path to std::ops traits
#[doc(hidden)]
#[macro_export]
macro_rules! __impl_validated_arithmetic_op {
    (
        $StructName:ident, $PolicyType:ident, $trait_name:ident, $method_name:ident, $msg:literal
    ) => {
        // T op T
        impl<K: $crate::core::traits::NumKernel> std::ops::$trait_name<$StructName<K>>
            for $StructName<K>
        {
            type Output = Self;
            #[inline(always)]
            fn $method_name(self, rhs: Self) -> Self::Output {
                Self::try_new_validated(self.value.$method_name(rhs.value)).expect($msg)
            }
        }
        // &T op T
        impl<'a, K: $crate::core::traits::NumKernel> std::ops::$trait_name<$StructName<K>>
            for &'a $StructName<K>
        {
            type Output = $StructName<K>;
            #[inline(always)]
            fn $method_name(self, rhs: $StructName<K>) -> Self::Output {
                $StructName::<K>::try_new_validated(self.value.clone().$method_name(rhs.value))
                    .expect($msg)
            }
        }
        // T op &T
        impl<'a, K: $crate::core::traits::NumKernel> std::ops::$trait_name<&'a $StructName<K>>
            for $StructName<K>
        {
            type Output = Self;
            #[inline(always)]
            fn $method_name(self, rhs: &'a Self) -> Self::Output {
                Self::try_new_validated(self.value.$method_name(&rhs.value)).expect($msg)
            }
        }
        // &T op &T
        impl<'a, K: $crate::core::traits::NumKernel> std::ops::$trait_name<&'a $StructName<K>>
            for &'a $StructName<K>
        {
            type Output = $StructName<K>;
            #[inline(always)]
            fn $method_name(self, rhs: &'a $StructName<K>) -> Self::Output {
                $StructName::<K>::try_new_validated(self.value.clone().$method_name(&rhs.value))
                    .expect($msg)
            }
        }
    };
}

// --- MACRO HELPER 2: For the assignment operations like: AddAssign, SubAssign, etc. ---
// Generates the 2 implementations (T op= T, T op= &T)
// $trait_name must be a bare ident like AddAssign, SubAssign
#[doc(hidden)]
#[macro_export]
macro_rules! __impl_validated_arithmetic_op_assign {
    (
        $StructName:ident, $PolicyType:ident, $trait_name:ident, $method_name:ident, $msg:literal
    ) => {
        // T op= T
        impl<K: $crate::core::traits::NumKernel> std::ops::$trait_name<$StructName<K>>
            for $StructName<K>
        {
            #[inline(always)]
            fn $method_name(&mut self, rhs: Self) {
                self.value.$method_name(rhs.value);
                let _ = K::$PolicyType::validate_ref(&self.value).expect($msg);
            }
        }
        // T op= &T
        impl<'a, K: $crate::core::traits::NumKernel> std::ops::$trait_name<&'a $StructName<K>>
            for $StructName<K>
        {
            #[inline(always)]
            fn $method_name(&mut self, rhs: &'a Self) {
                self.value.$method_name(&rhs.value);
                let _ = K::$PolicyType::validate_ref(&self.value).expect($msg);
            }
        }
    };
}

// --- MACRO HELPER 3: For both op and assignment op ---
// $trait_name must be a bare ident like Add, Sub, Mul, Div
// The macro will construct the full paths std::ops::Add and std::ops::AddAssign internally
#[doc(hidden)]
#[macro_export]
macro_rules! __impl_validated_arithmetic_op_and_op_assign {
    (
        $StructName:ident, $PolicyType:ident, $trait_name:ident, $method_name:ident, $msg:literal
    ) => {
        // First, implement the binary operation
        $crate::__impl_validated_arithmetic_op!(
            $StructName,
            $PolicyType,
            $trait_name,
            $method_name,
            $msg
        );
        // Then, implement the assignment operation
        paste::paste! {
            $crate::__impl_validated_arithmetic_op_assign!(
                $StructName,
                $PolicyType,
                [<$trait_name Assign>], // attach the string "Assign" at the end of the $trait_name
                [<$method_name _assign>], // attach the string "_assign" at the end of the $method_name
                $msg
            );
        }
    };
}
// The following macros are NEW and provide modular alternatives to the monolithic macro

/// Defines the validated struct with documentation and serialization support.
///
/// Creates a `#[repr(transparent)]` newtype wrapper around the raw type with:
/// - Automatic `AsRef`, `Debug`, `Display`, `LowerExp` derives
/// - Serde `Serialize` and `Deserialize` support
/// - Phantom data for kernel type
///
/// ## Example
///
/// ```ignore
/// define_validated_struct_type!(
///     RealValidated,
///     RealPolicy,
///     RawReal,
///     "A validated real number wrapper",
///     "{value}"
/// );
/// ```
///
/// ## Parameters
///
/// - `$StructName`: Name of the struct (e.g., `RealValidated`)
/// - `$PolicyType`: Policy field in `NumKernel` (e.g., `RealPolicy`)
/// - `$RawType`: Raw value type (e.g., `RawReal`)
/// - `$doc`: Documentation string
/// - `$display_string`: Format string for Display/LowerExp (e.g., `"{value}"`)
#[macro_export]
macro_rules! define_validated_struct_type {
    (
        $StructName:ident,
        $PolicyType:ident,
        $RawType:ident,
        $doc:literal,
        $display_string:literal
    ) => {
        #[doc = $doc]
        #[repr(transparent)]
        #[derive(
            derive_more::with_trait::AsRef,
            derive_more::with_trait::Debug,
            derive_more::with_trait::Display,
            derive_more::with_trait::LowerExp,
            serde::Serialize,
            serde::Deserialize,
        )]
        #[display($display_string, value)]
        #[lower_exp($display_string, value)]
        pub struct $StructName<K: $crate::core::traits::NumKernel> {
            #[as_ref]
            pub(crate) value: K::$RawType,
            pub(crate) _phantom: std::marker::PhantomData<K>,
        }
    };
}

/// Implements core utility traits: `IntoInner`, `Clone`, `PartialEq`.
///
/// ## Example
///
/// ```ignore
/// impl_validated_core_traits!(MyType, RawReal);
/// ```
#[macro_export]
macro_rules! impl_validated_core_traits {
    ($StructName:ident, $RawType:ident) => {
        impl<K: $crate::core::traits::NumKernel> try_create::IntoInner for $StructName<K> {
            type InnerType = K::$RawType;

            #[inline(always)]
            fn into_inner(self) -> Self::InnerType {
                self.value
            }
        }

        impl<K: $crate::core::traits::NumKernel> Clone for $StructName<K> {
            #[inline(always)]
            fn clone(&self) -> Self {
                Self {
                    value: self.value.clone(),
                    _phantom: std::marker::PhantomData,
                }
            }
        }

        impl<K: $crate::core::traits::NumKernel> PartialEq for $StructName<K> {
            #[inline(always)]
            fn eq(&self, other: &Self) -> bool {
                self.value.eq(&other.value)
            }
        }
    };
}

/// Implements constructor traits and methods: `TryNewValidated`, `TryNew`, `new()` (deprecated), `new_unchecked()`.
///
/// - `TryNewValidated`: Always validates (from `try_create` crate)
/// - `TryNew`: Alias for `TryNewValidated` (from `try_create` crate)
/// - `new()`: **DEPRECATED** - Always validates and panics on failure. Use `try_new()` instead.
/// - `new_unchecked()`: **UNSAFE** - Validates only in debug builds, zero-cost in release.
///
/// ## Example
///
/// ```ignore
/// impl_validated_constructors!(MyType, RealPolicy, RawReal);
/// ```
#[macro_export]
macro_rules! impl_validated_constructors {
    ($StructName:ident, $PolicyType:ident, $RawType:ident) => {
        impl<K: $crate::core::traits::NumKernel> try_create::TryNewValidated for $StructName<K> {
            type Policy = K::$PolicyType;

            #[inline(always)]
            fn try_new_validated(value: Self::InnerType) -> Result<Self, Self::Error> {
                let value = Self::Policy::validate(value)?;
                Ok(Self {
                    value,
                    _phantom: std::marker::PhantomData,
                })
            }
        }

        impl<K: $crate::core::traits::NumKernel> try_create::TryNew for $StructName<K> {
            type Error = <<K as $crate::core::traits::NumKernel>::$PolicyType as try_create::ValidationPolicy>::Error;

            #[inline(always)]
            fn try_new(value: Self::InnerType) -> Result<Self, Self::Error> {
                Self::try_new_validated(value)
            }
        }

        impl<K: $crate::core::traits::NumKernel> $StructName<K> {
            /// Creates a new instance, panicking if validation fails.
            ///
            /// **⚠️ DEPRECATED**: This method will be removed in version 1.0.
            /// Use [`try_new()`](Self::try_new) for error handling or [`new_unchecked()`](Self::new_unchecked) for performance-critical code.
            ///
            /// # Panics
            ///
            /// Panics if the value fails validation (e.g., NaN, infinity, subnormal).
            ///
            /// # Migration Guide
            ///
            /// ```ignore
            /// // Old (deprecated):
            /// // let x = MyType::new(3.14);
            ///
            /// // New (recommended):
            /// let x = MyType::try_new(3.14).unwrap();
            ///
            /// // Or for error handling:
            /// let x = MyType::try_new(3.14)?;
            /// ```
            #[deprecated(since = "0.3.0", note = "Use `try_new().unwrap()` instead. Will be removed in 1.0.")]
            #[inline(always)]
            pub fn new(value: K::$RawType) -> Self {
                Self::try_new_validated(value)
                    .expect("new() validation failed - use try_new() for error handling")
            }

            /// Creates a new instance without validation in release builds.
            ///
            /// # Safety
            ///
            /// The caller must guarantee that `value` satisfies the validation policy's requirements.
            /// Violating this contract may lead to:
            /// - NaN propagation in calculations
            /// - Incorrect results in mathematical operations
            /// - Hash collisions if used as HashMap keys (when policy guarantees finite values)
            /// - Violation of type-level invariants
            ///
            /// In **debug builds**, this function validates the input and panics if invalid,
            /// helping catch contract violations during development.
            ///
            /// In **release builds**, no validation is performed for maximum performance.
            ///
            /// # Recommended Usage
            ///
            /// Only use this function when:
            /// 1. Performance is critical and validation overhead is unacceptable
            /// 2. You have already validated the value through other means
            /// 3. The value comes from a trusted source (e.g., compile-time constants)
            ///
            /// # Examples
            ///
            /// ```ignore
            /// // SAFE: Compile-time constant known to be valid
            /// let pi = unsafe { MyType::new_unchecked(3.141592653589793) };
            ///
            /// // UNSAFE: Runtime value - should use try_new() instead!
            /// // let x = unsafe { MyType::new_unchecked(user_input) }; // DON'T DO THIS
            /// ```
            ///
            /// # Alternative
            ///
            /// For most use cases, prefer [`try_new()`](Self::try_new) which always validates.
            #[inline(always)]
            pub unsafe fn new_unchecked(value: K::$RawType) -> Self {
                #[cfg(debug_assertions)]
                {
                    Self::try_new_validated(value)
                        .expect("new_unchecked() validation failed in debug mode - contract violated")
                }
                #[cfg(not(debug_assertions))]
                {
                    Self {
                        value,
                        _phantom: std::marker::PhantomData,
                    }
                }
            }
        }
    };
}

/// Implements numeric traits: `Zero`, `One`, `FpChecks`.
///
/// ## Example
///
/// ```ignore
/// impl_validated_numeric_traits!(MyType, RealPolicy, RawReal);
/// ```
#[macro_export]
macro_rules! impl_validated_numeric_traits {
    ($StructName:ident, $PolicyType:ident, $RawType:ident) => {
        impl<K: $crate::core::traits::NumKernel> num::Zero for $StructName<K> {
            #[inline(always)]
            fn zero() -> Self {
                Self {
                    value: <K::$RawType as $crate::kernels::RawScalarTrait>::raw_zero(
                        K::$PolicyType::PRECISION,
                    ),
                    _phantom: std::marker::PhantomData,
                }
            }

            #[inline(always)]
            fn is_zero(&self) -> bool {
                self.value.is_zero()
            }
        }

        impl<K: $crate::core::traits::NumKernel> num::One for $StructName<K> {
            #[inline(always)]
            fn one() -> Self {
                Self {
                    value: <K::$RawType as $crate::kernels::RawScalarTrait>::raw_one(
                        K::$PolicyType::PRECISION,
                    ),
                    _phantom: std::marker::PhantomData,
                }
            }
        }

        impl<K: $crate::core::traits::NumKernel> $crate::FpChecks for $StructName<K> {
            #[inline(always)]
            fn is_finite(&self) -> bool {
                self.value.is_finite()
            }

            #[inline(always)]
            fn is_infinite(&self) -> bool {
                self.value.is_infinite()
            }

            #[inline(always)]
            fn is_nan(&self) -> bool {
                self.value.is_nan()
            }

            #[inline(always)]
            fn is_normal(&self) -> bool {
                self.value.is_normal()
            }
        }
    };
}

/// Implements arithmetic traits: `Add`, `Sub`, `Mul`, `Div` and their `*Assign` variants.
///
/// Generates all 6 implementations per operation (4 binary + 2 assignment).
///
/// ## Example
///
/// ```ignore
/// impl_validated_arithmetic!(MyType, RealPolicy);
/// ```
#[macro_export]
macro_rules! impl_validated_arithmetic {
    ($StructName:ident, $PolicyType:ident) => {
        $crate::__impl_validated_arithmetic_op_and_op_assign!(
            $StructName,
            $PolicyType,
            Add,
            add,
            "Addition failed validation"
        );

        $crate::__impl_validated_arithmetic_op_and_op_assign!(
            $StructName,
            $PolicyType,
            Sub,
            sub,
            "Subtraction failed validation"
        );

        $crate::__impl_validated_arithmetic_op_and_op_assign!(
            $StructName,
            $PolicyType,
            Mul,
            mul,
            "Multiplication failed validation"
        );

        $crate::__impl_validated_arithmetic_op_and_op_assign!(
            $StructName,
            $PolicyType,
            Div,
            div,
            "Division failed validation"
        );
    };
}

/// Implements special operations: `Neg`, `NegAssign`, `MulAddRef`.
///
/// ## Example
///
/// ```ignore
/// impl_validated_special_ops!(MyType, RealPolicy);
/// ```
#[macro_export]
macro_rules! impl_validated_special_ops {
    ($StructName:ident, $PolicyType:ident) => {
        impl<K: $crate::core::traits::NumKernel> std::ops::Neg for $StructName<K> {
            type Output = Self;
            #[inline(always)]
            fn neg(self) -> Self::Output {
                Self {
                    value: -self.value,
                    _phantom: std::marker::PhantomData,
                }
            }
        }

        impl<K: $crate::core::traits::NumKernel> $crate::functions::NegAssign for $StructName<K> {
            #[inline(always)]
            fn neg_assign(&mut self) {
                self.value.neg_assign();
            }
        }

        impl<K: $crate::core::traits::NumKernel> $crate::MulAddRef for $StructName<K> {
            #[inline(always)]
            fn mul_add_ref(self, b: &Self, c: &Self) -> Self {
                Self::try_new_validated(self.value.unchecked_mul_add(&b.value, &c.value))
                    .expect("mul_add_ref failed validation")
            }
        }
    };
}

/// Implements `Sum` trait with Neumaier compensated summation algorithm.
///
/// Provides accurate summation for iterators by reducing floating-point errors.
///
/// ## Example
///
/// ```ignore
/// impl_validated_sum!(MyType, RealPolicy);
/// ```
#[macro_export]
macro_rules! impl_validated_sum {
    ($StructName:ident, $PolicyType:ident) => {
        impl<K: $crate::core::traits::NumKernel> $crate::algorithms::neumaier_sum::NeumaierAddable
            for $StructName<K>
        {
            fn neumaier_compensated_sum(value: Self, sum: &mut Self, compensation: &mut Self) {
                $crate::algorithms::neumaier_sum::NeumaierAddable::neumaier_compensated_sum(
                    value.value,
                    &mut sum.value,
                    &mut compensation.value,
                );
                let _ = K::$PolicyType::validate_ref(&sum.value)
                    .expect("Neumaier compensated sum failed validation for sum");
                let _ = K::$PolicyType::validate_ref(&compensation.value)
                    .expect("Neumaier compensated sum failed validation for compensation");
            }
        }

        impl<K: $crate::core::traits::NumKernel> std::iter::Sum for $StructName<K> {
            fn sum<I>(iter: I) -> Self
            where
                I: Iterator<Item = Self>,
            {
                $crate::algorithms::neumaier_sum::NeumaierSum::new_sequential(iter).sum()
            }
        }
    };
}

/// **Convenience macro** (backward compatible): Defines a validated struct with all traits.
///
/// This macro provides the same functionality as the original monolithic
/// `define_validated_struct!` but uses the modular macros internally.
///
/// ## Example
///
/// ```ignore
/// define_validated_struct_modular!(
///     RealValidated,
///     RealPolicy,
///     RawReal,
///     "A validated real number wrapper",
///     "{value}"
/// );
/// ```
#[macro_export]
macro_rules! define_validated_struct_modular {
    (
        $StructName:ident,
        $PolicyType:ident,
        $RawType:ident,
        $doc:literal,
        $display_string:literal
    ) => {
        // 1. Struct definition
        $crate::define_validated_struct_type!(
            $StructName,
            $PolicyType,
            $RawType,
            $doc,
            $display_string
        );

        // 2. Core traits
        $crate::impl_validated_core_traits!($StructName, $RawType);

        // 3. Constructors
        $crate::impl_validated_constructors!($StructName, $PolicyType, $RawType);

        // 4. Numeric traits
        $crate::impl_validated_numeric_traits!($StructName, $PolicyType, $RawType);

        // 5. Arithmetic operations
        $crate::impl_validated_arithmetic!($StructName, $PolicyType);

        // 6. Special operations
        $crate::impl_validated_special_ops!($StructName, $PolicyType);

        // 7. Sum trait
        $crate::impl_validated_sum!($StructName, $PolicyType);
    };
}

// Re-export all public macros for easy access
// These macros are exported with #[macro_export] and available to users,
// but the re-export here provides a consistent access pattern.
#[allow(unused_imports)]
pub use {
    define_validated_struct_modular, define_validated_struct_type, impl_validated_arithmetic,
    impl_validated_constructors, impl_validated_core_traits, impl_validated_numeric_traits,
    impl_validated_special_ops, impl_validated_sum,
};

/// Creates a validated real number from an f64 literal.
///
/// This macro provides a concise syntax for creating [`RealNative64StrictFinite`](crate::RealNative64StrictFinite)
/// values from floating-point literals. It uses the panicking [`from_f64`](crate::RealScalar::from_f64)
/// constructor, which is appropriate for compile-time constants and test code where
/// validity is guaranteed.
///
/// # Panics
///
/// Panics if the provided value is not finite (NaN, infinity) or is subnormal.
/// For fallible conversion, use [`RealScalar::try_from_f64`](crate::RealScalar::try_from_f64) directly.
///
/// # Examples
///
/// ```
/// use num_valid::real;
/// use std::f64::consts::PI;
///
/// let x = real!(3.14159);
/// let y = real!(PI);
/// let z = real!(-42.0);
///
/// assert!((x.as_ref() - 3.14159).abs() < 1e-10);
/// ```
///
/// Using with mathematical constants:
///
/// ```
/// use num_valid::real;
/// use std::f64::consts::{PI, E, TAU};
///
/// let pi = real!(PI);
/// let e = real!(E);
/// let tau = real!(TAU);
///
/// let circle_area = real!(PI) * real!(25.0); // π * r² with r=5
/// ```
#[macro_export]
macro_rules! real {
    ($value:expr) => {{
        use $crate::RealScalar;
        $crate::backends::native64::validated::RealNative64StrictFinite::from_f64($value)
    }};
}

/// Creates a validated complex number from two f64 literals (real and imaginary parts).
///
/// This macro provides a concise syntax for creating [`ComplexNative64StrictFinite`](crate::ComplexNative64StrictFinite)
/// values. It accepts two arguments: the real part and the imaginary part.
///
/// # Panics
///
/// Panics if either the real or imaginary part is not finite (NaN, infinity) or is subnormal.
/// For fallible conversion, use [`ComplexNative64StrictFinite::try_new_complex`](crate::functions::ComplexScalarConstructors::try_new_complex) directly.
///
/// # Examples
///
/// ```
/// use num_valid::complex;
///
/// let z1 = complex!(1.0, 2.0);   // 1 + 2i
/// let z2 = complex!(-3.0, 4.0);  // -3 + 4i
/// let z3 = complex!(0.0, -1.0);  // -i
///
/// // Euler's identity: e^(iπ) + 1 = 0
/// use std::f64::consts::PI;
/// use num_valid::functions::{Exp, Abs};
///
/// let i_pi = complex!(0.0, PI);
/// let e_to_i_pi = i_pi.exp();
/// let result = e_to_i_pi + complex!(1.0, 0.0);
///
/// assert!(result.abs().as_ref() < &1e-10); // Very close to zero
/// ```
///
/// Creating unit vectors in the complex plane:
///
/// ```
/// use num_valid::complex;
///
/// let unit_real = complex!(1.0, 0.0);      // Real axis
/// let unit_imag = complex!(0.0, 1.0);      // Imaginary axis
/// let unit_45deg = complex!(0.707, 0.707); // 45° angle
/// ```
#[macro_export]
macro_rules! complex {
    ($re:expr, $im:expr) => {{
        use $crate::functions::ComplexScalarConstructors;
        $crate::backends::native64::validated::ComplexNative64StrictFinite::new_complex(
            $crate::real!($re),
            $crate::real!($im),
        )
    }};
}

#[cfg(test)]
mod tests {
    use crate::functions::ComplexScalarGetParts;

    #[test]
    fn test_real_macro_basic() {
        let x = real!(3.);
        assert!((x.as_ref() - 3.).abs() < 1e-10);
    }

    #[test]
    fn test_real_macro_constants() {
        use std::f64::consts::PI;
        let pi = real!(PI);
        assert!((pi.as_ref() - PI).abs() < 1e-15);
    }

    #[test]
    fn test_real_macro_negative() {
        let x = real!(-42.5);
        assert_eq!(*x.as_ref(), -42.5);
    }

    #[test]
    fn test_complex_macro_basic() {
        let z = complex!(1.0, 2.0);
        assert_eq!(*z.real_part().as_ref(), 1.0);
        assert_eq!(*z.imag_part().as_ref(), 2.0);
    }

    #[test]
    fn test_complex_macro_zero_imaginary() {
        let z = complex!(5.0, 0.0);
        assert_eq!(*z.real_part().as_ref(), 5.0);
        assert_eq!(*z.imag_part().as_ref(), 0.0);
    }

    #[test]
    fn test_complex_macro_negative() {
        let z = complex!(-3.0, -4.0);
        assert_eq!(*z.real_part().as_ref(), -3.0);
        assert_eq!(*z.imag_part().as_ref(), -4.0);
    }

    #[test]
    #[should_panic(expected = "RealScalar::from_f64() failed")]
    fn test_real_macro_nan() {
        let _x = real!(f64::NAN);
    }

    #[test]
    #[should_panic(expected = "RealScalar::from_f64() failed")]
    fn test_real_macro_inf() {
        let _x = real!(f64::INFINITY);
    }

    #[test]
    #[should_panic(expected = "RealScalar::from_f64() failed")]
    fn test_complex_macro_nan_real() {
        let _z = complex!(f64::NAN, 1.0);
    }

    #[test]
    #[should_panic(expected = "RealScalar::from_f64() failed")]
    fn test_complex_macro_inf_imaginary() {
        let _z = complex!(1.0, f64::INFINITY);
    }
}