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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
use core::{fmt, mem::transmute};

/// The macro to define [`ResultCode`].
macro_rules! define_result_code {
    (
        $( #[$meta:meta] )*
        pub enum ResultCode {
            $(
                $( #[$vmeta:meta] )*
                $vname:ident = $vd:expr
            ),* $(,)*
        }
    ) => {
        $( #[$meta] )*
        pub enum ResultCode {
            $(
                $( #[$vmeta] )*
                $vname = $vd
            ),*
        }

        impl ResultCode {
            /// Get the short name of the result code.
            ///
            /// # Examples
            ///
            /// ```
            /// use r3_core::kernel::ResultCode;
            /// assert_eq!(ResultCode::BadObjectState.as_str(), "BadObjectState");
            /// ```
            pub fn as_str(self) -> &'static str {
                match self {
                    $(
                        Self::$vname => stringify!($vname),
                    )*
                }
            }

            fn fmt(self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }

        impl fmt::Debug for ResultCode {
            #[inline]
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                (*self).fmt(f)
            }
        }
    };
}

define_result_code! {
    /// All result codes (including the one indicating success) that a kernel
    /// function can return.
    ///
    /// <div class="admonition-follows"></div>
    ///
    /// > **Relation to Other Specifications:** The error variants were loosely
    /// > inspired from μITRON4.0 for no particular reasons.
    ///
    /// <div class="admonition-follows"></div>
    ///
    /// > **Rationale:**
    /// > Giving them explicit and stable discriminants makes it possible to
    /// > produce them directly in foreign code.
    /// >
    /// > The discriminants are assigned in a way that maximizes the execution
    /// > efficiency based on the following assumptions:
    /// >
    /// > - Some variants, such as [`BadContext`][] and [`NoAccess`][], are more
    /// >   likely to be handled by `unwrap`-ing than other variants. Therefore,
    /// >   sorting their `u8` interpretations in the increasing order of the
    /// >   likelihood of being handled by `unwrap`-ing increases the likelihood
    /// >   of the evaluation of an `unwrap` condition being compiled down to a
    /// >   single integer comparison.
    /// >
    /// > - The discriminants are tightly arranged so that the membership test
    /// >   with a compile-time result code set can be implemented by a bitfield
    /// >   look-up table on a general-purpose register.
    /// >
    /// > - Most of the error types including subsets of `ResultCode` include
    /// >   [`BadContext`][], hence by assigning `-1` to it, `Result<(),
    /// >   $ErrorType>::Ok` will get `0` as its discriminant, which improves
    /// >   the execution efficiency because comparison to zero can be done
    /// >   efficiently on most instruction set architectures.
    /// >   <!-- [ref:zero_discriminant_optimization] -->
    ///
    /// [`BadContext`]: Self::BadContext
    /// [`NoAccess`]: Self::NoAccess
    ///
    /// # Stability
    ///
    /// This type is covered by [the application-side API stability
    /// guarantee][1]. The explicit discriminants are only covered by the
    /// kernel-side API stability guarantee. Adding new variants or changing the
    /// representation size is not considered a breaking change.
    ///
    /// [1]: crate#stability
    #[doc = include_str!("../common.md")]
    #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
    #[repr(i8)]
    #[non_exhaustive]
    pub enum ResultCode {
        /// The operation was successful. No additional information is available.
        Success = 0,
        /// The operation is not supported.
        NotSupported = -2,
        /// A parameter is invalid in a way that is no covered by any other error
        /// codes.
        BadParam = -5,
        /// The current operation was rejected by an optional protection
        /// mechanism, e.g., because the specified object identifier ([`Id`]) is
        /// invalid, or the caller lacks the necessary privileges to complete
        /// the operation.
        ///
        /// This error usually indicates an [object safety][1] or memory
        /// safety violation. A kernel implementation is not required to report
        /// this as it's not practical in general cases. It's strongly
        /// recommended that *application code not rely on this error code being
        /// returned and, should it be returned, escalate it to a panic or abort
        /// immediately* unless the code is written for a specific kernel
        /// implementation that makes a special provision.
        ///
        /// <div class="admonition-follows"></div>
        ///
        /// > **Rationale:** In the original design, R3 was limited to a
        /// > specific kernel implementation, and this kernel implementation
        /// > always validated input object identifiers as it was trivial to do
        /// > so. Now that R3 is being redesigned as a pure interface for
        /// > unknown kernels, requiring this property might pose a considerable
        /// > burden on kernel implementations. In addition, the provided object
        /// > handle types enforces object safety, and creating them from raw
        /// > object IDs is impossible in safe code. It's for this reason that
        /// > detecting this error is now optional.
        /// >
        /// > One of the avenues being explored is to support RTOS kernels with
        /// > a security-oriented protection mechanism. From a security point of
        /// > view, it's preferable not to disclose the state of other
        /// > protection domains (e.g., if the object IDs were memory addresses,
        /// > exposing them would undermine the security benefits of address
        /// > space layout randomization), hence the intentional lack of error
        /// > code distinction between invalid IDs and inaccessible IDs.
        /// >
        /// > Since it's most likely escalated to a panic or abort, it was also
        /// > considered to remove this error code altogether. However, since
        /// > error codes are not extensible, this would unnecessarily
        /// > complicate the rare cases where it can be reasonably handled in
        /// > other ways.
        ///
        /// [`Id`]: super::Id
        /// [1]: crate#object-safety
        NoAccess = -3,
        /// The current context disallows the operation.
        BadContext = -1,
        /// The caller does not own the resource.
        NotOwner = -4,
        /// Resource deadlock would occur.
        WouldDeadlock = -8,
        /// A target object is in a state that disallows the operation.
        BadObjectState = -9,
        /// An operation or an object couldn't be enqueued because there are too
        /// many of such things that already have been enqueued.
        QueueOverflow = -11,
        /// The owner of a mutex exited while holding the mutex lock.
        Abandoned = -6,
        /// The wait operation was interrupted by [`Task::interrupt`].
        ///
        /// [`Task::interrupt`]: crate::kernel::task::TaskMethods::interrupt
        Interrupted = -7,
        /// The operation timed out.
        Timeout = -10,
    }
}

impl ResultCode {
    /// Get a flag indicating whether the code represents a failure.
    ///
    /// Failure codes have negative values.
    #[inline]
    pub fn is_err(self) -> bool {
        (self as i8) < 0
    }

    /// Get a flag indicating whether the code represents a success.
    ///
    /// Success codes have non-negative values.
    #[inline]
    pub fn is_ok(self) -> bool {
        !self.is_err()
    }
}

macro_rules! define_error {
    (
        mod $mod_name:ident {}
        $( #[$meta:meta] )*
        $vis:vis enum $name:ident $(: $($subty:ident),* $(,)*)? {
            $(
                $( #[$vmeta:meta] )*
                $vname:ident
            ),* $(,)*
        }
    ) => {
        $( #[$meta] )*
        ///
        /// See [`ResultCode`] for all result codes and generic descriptions.
        #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
        #[repr(i8)]
        $vis enum $name {
            $(
                $( #[$vmeta] )*
                // Use the same discriminants as `ResultCode` for cost-free
                // conversion
                $vname = ResultCode::$vname as i8
            ),*
        }

        impl fmt::Debug for $name {
            #[inline]
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                ResultCode::from(*self).fmt(f)
            }
        }

        impl From<Result<(), $name>> for ResultCode {
            #[inline]
            fn from(x: Result<(), $name>) -> Self {
                match x {
                    Ok(()) => Self::Success,
                    Err(e) => Self::from(e),
                }
            }
        }

        impl From<$name> for ResultCode {
            #[inline]
            fn from(x: $name) -> Self {
                // Safety: `ResultCode` and `$name` has the same representation
                //         type, and the representation of `ResultCode` is a
                //         superset of `x`.
                unsafe { transmute(x) }
            }
        }

        #[cfg(test)]
        mod $mod_name {
            use super::*;

            #[test]
            fn to_result_code() {
                $(
                    assert_eq!(
                        ResultCode::$vname,
                        ResultCode::from($name::$vname),
                    );
                )*
            }

            #[test]
            fn result_to_result_code() {
                $(
                    assert_eq!(
                        ResultCode::$vname,
                        ResultCode::from(Err($name::$vname)),
                    );
                )*
                assert_eq!(
                    ResultCode::Success,
                    ResultCode::from(Result::<(), $name>::Ok(())),
                );
            }

            #[test]
            fn is_failure() {
                // All error values represent failure
                $(
                    assert!(ResultCode::from(Err($name::$vname)).is_err());
                )*
            }
        }

        $($(
            $subty!(impl From<_> for $name);
        )*)?

        #[allow(unused_macros)]
        macro_rules! $name {
            (impl From<_> for $dest_ty:ty) => {
                impl From<$name> for $dest_ty {
                    #[inline]
                    fn from(x: $name) -> Self {
                        match x {
                            $(
                                $name::$vname => Self::$vname,
                            )*
                        }
                    }
                }
            };
        }
    };
}

define_error! {
    mod activate_task_error {}
    /// Error type for [`Task::activate`].
    ///
    /// [`Task::activate`]: super::task::TaskMethods::activate
    pub enum ActivateTaskError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        /// The task is already active (not in the Dormant state).
        ///
        /// This error code originates from `E_QOVR` defined in the μITRON 4.0
        /// specification. In this specification, the `act_tsk` (activate task)
        /// system service works by enqueueing an activation request. `E_QOVR`
        /// is used to report a condition in which an enqueue count limit has
        /// been reached. Our kernel doesn't support enqueueing activation
        /// request (at the moment), so any attempts to activate an
        /// already-active task will fail.
        QueueOverflow,
    }
}

define_error! {
    mod get_current_task_error {}
    /// Error type for [`LocalTask::current`].
    ///
    /// [`LocalTask::current`]: super::task::LocalTask::current
    pub enum GetCurrentTaskError {
        /// CPU Lock is active, or the current context is not a task context.
        BadContext,
    }
}

define_error! {
    mod interrupt_task_error {}
    /// Error type for [`Task::interrupt`].
    ///
    /// [`Task::interrupt`]: super::task::TaskMethods::interrupt
    pub enum InterruptTaskError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        /// The task is not in the Waiting state.
        BadObjectState,
    }
}

define_error! {
    mod set_task_priority_error {}
    /// Error type for [`Task::set_priority`].
    ///
    /// [`Task::set_priority`]: super::task::TaskMethods::set_priority
    pub enum SetTaskPriorityError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        /// The priority is out of range, or the task owns a mutex created with
        /// with the protocol attribute having the value [`Ceiling`] and the
        /// task's new priority is higher than the mutex's priority ceiling.
        ///
        /// [`Ceiling`]: crate::kernel::MutexProtocol::Ceiling
        BadParam,
        /// The task is in the Dormant state.
        BadObjectState,
    }
}

define_error! {
    mod get_task_priority_error {}
    /// Error type for [`Task::priority`].
    ///
    /// [`Task::priority`]: super::task::TaskMethods::priority
    pub enum GetTaskPriorityError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        /// The task is in the Dormant state.
        BadObjectState,
    }
}

define_error! {
    mod exit_task_error {}
    /// Error type for [`Kernel::exit_task`].
    ///
    /// [`Kernel::exit_task`]: super::Kernel::exit_task
    pub enum ExitTaskError {
        /// The current context is not a task context.
        BadContext,
    }
}

define_error! {
    mod cpu_lock_error {}
    /// Error type for [`Kernel::acquire_cpu_lock`] and
    /// [`Kernel::release_cpu_lock`].
    ///
    /// [`Kernel::acquire_cpu_lock`]: super::Kernel::acquire_cpu_lock
    /// [`Kernel::release_cpu_lock`]: super::Kernel::release_cpu_lock
    pub enum CpuLockError {
        /// CPU Lock is already active or inactive.
        BadContext,
    }
}

define_error! {
    mod boost_priority_error {}
    /// Error type for [`Kernel::boost_priority`] and
    /// [`Kernel::unboost_priority`].
    ///
    /// [`Kernel::boost_priority`]: super::Kernel::boost_priority
    /// [`Kernel::unboost_priority`]: super::Kernel::unboost_priority
    pub enum BoostPriorityError {
        /// Priority Boost is already active or inactive, the current
        /// context is not a task context, or CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod time_error {}
    /// Error type for [`Kernel::time`] and
    /// [`Kernel::set_time`].
    ///
    /// [`Kernel::time`]: super::Kernel::time
    /// [`Kernel::set_time`]: super::Kernel::set_time
    pub enum TimeError {
        /// The current context is not a task context, or CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod adjust_time_error {}
    /// Error type for [`Kernel::adjust_time`].
    ///
    /// [`Kernel::adjust_time`]: super::Kernel::adjust_time
    pub enum AdjustTimeError {
        /// CPU Lock is active.
        BadContext,
        /// The requested adjustment is not possible under the current system
        /// state.
        BadObjectState,
    }
}

define_error! {
    mod wait_error {}
    /// Error type for wait operations such as [`EventGroup::wait`].
    ///
    /// [`EventGroup::wait`]: super::event_group::EventGroupMethods::wait
    pub enum WaitError {
        Interrupted,
    }
}

define_error! {
    mod wait_timeout_error {}
    /// Error type for wait operations with timeout such as
    /// [`EventGroup::wait_timeout`].
    ///
    /// [`EventGroup::wait_timeout`]: super::event_group::EventGroupMethods::wait_timeout
    pub enum WaitTimeoutError: WaitError {
        Interrupted,
        Timeout,
    }
}

define_error! {
    mod park_error {}
    /// Error type for [`Kernel::park`].
    ///
    /// [`Kernel::park`]: super::Kernel::park
    pub enum ParkError: WaitError {
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
    }
}

define_error! {
    mod park_timeout_error {}
    /// Error type for [`Kernel::park_timeout`].
    ///
    /// [`Kernel::park_timeout`]: super::Kernel::park_timeout
    pub enum ParkTimeoutError: WaitTimeoutError {
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
        Timeout,
        /// The timeout duration is negative.
        BadParam,
    }
}

define_error! {
    mod unpark_error {}
    /// Error type for [`Task::unpark`].
    ///
    /// [`Task::unpark`]: super::task::TaskMethods::unpark
    pub enum UnparkError {
        /// CPU Lock is active.
        BadContext,
        /// Invalid object access.
        NoAccess,
        /// The task is in the Dormant state.
        BadObjectState,
    }
}

define_error! {
    mod unpark_exact_error {}
    /// Error type for [`Task::unpark_exact`].
    ///
    /// [`Task::unpark_exact`]: super::task::TaskMethods::unpark_exact
    pub enum UnparkExactError {
        /// CPU Lock is active.
        BadContext,
        /// Invalid object access.
        NoAccess,
        /// The task already has a token.
        QueueOverflow,
        /// The task is in the Dormant state.
        BadObjectState,
    }
}

define_error! {
    mod sleep_error {}
    /// Error type for [`Kernel::sleep`].
    ///
    /// [`Kernel::sleep`]: super::Kernel::sleep
    pub enum SleepError {
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
        /// The duration is negative.
        BadParam,
    }
}
define_error! {
    mod update_event_group_error {}
    /// Error type for [`EventGroup::set`] and [`EventGroup::clear`].
    ///
    /// [`EventGroup::set`]: super::event_group::EventGroupMethods::set
    /// [`EventGroup::clear`]: super::event_group::EventGroupMethods::clear
    pub enum UpdateEventGroupError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod get_event_group_error {}
    /// Error type for [`EventGroup::get`].
    ///
    /// [`EventGroup::get`]: super::event_group::EventGroupMethods::get
    pub enum GetEventGroupError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod poll_event_group_error {}
    /// Error type for [`EventGroup::poll`].
    ///
    /// [`EventGroup::poll`]: super::event_group::EventGroupMethods::poll
    pub enum PollEventGroupError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        Timeout,
    }
}

define_error! {
    mod wait_event_group_error {}
    /// Error type for [`EventGroup::wait`].
    ///
    /// [`EventGroup::wait`]: super::event_group::EventGroupMethods::wait
    pub enum WaitEventGroupError: WaitError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
    }
}

define_error! {
    mod wait_event_group_timeout_error {}
    /// Error type for [`EventGroup::wait_timeout`].
    ///
    /// [`EventGroup::wait_timeout`]: super::event_group::EventGroupMethods::wait_timeout
    pub enum WaitEventGroupTimeoutError: WaitTimeoutError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
        Timeout,
        /// The timeout duration is negative.
        BadParam,
    }
}

define_error! {
    mod get_semaphore_error {}
    /// Error type for [`Semaphore::get`].
    ///
    /// [`Semaphore::get`]: super::semaphore::SemaphoreMethods::get
    pub enum GetSemaphoreError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod drain_semaphore_error {}
    /// Error type for [`Semaphore::drain`].
    ///
    /// [`Semaphore::drain`]: super::semaphore::SemaphoreMethods::drain
    pub enum DrainSemaphoreError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod signal_semaphore_error {}
    /// Error type for [`Semaphore::signal`].
    ///
    /// [`Semaphore::signal`]: super::semaphore::SemaphoreMethods::signal
    pub enum SignalSemaphoreError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        /// The semaphore value is already at the maximum value.
        QueueOverflow,
    }
}

define_error! {
    mod poll_semaphore_error {}
    /// Error type for [`Semaphore::poll_one`].
    ///
    /// [`Semaphore::poll_one`]: super::semaphore::SemaphoreMethods::poll_one
    pub enum PollSemaphoreError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        Timeout,
    }
}

define_error! {
    mod wait_semaphore_error {}
    /// Error type for [`Semaphore::wait_one`].
    ///
    /// [`Semaphore::wait_one`]: super::semaphore::SemaphoreMethods::wait_one
    pub enum WaitSemaphoreError: WaitError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
    }
}

define_error! {
    mod wait_semaphore_timeout_error {}
    /// Error type for [`Semaphore::wait_one_timeout`].
    ///
    /// [`Semaphore::wait_one_timeout`]: super::semaphore::SemaphoreMethods::wait_one_timeout
    pub enum WaitSemaphoreTimeoutError: WaitTimeoutError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
        Timeout,
        /// The timeout duration is negative.
        BadParam,
    }
}

define_error! {
    mod query_mutex_error {}
    /// Error type for [`Mutex::is_locked`].
    ///
    /// [`Mutex::is_locked`]: super::mutex::MutexMethods::is_locked
    pub enum QueryMutexError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod unlock_mutex_error {}
    /// Error type for [`Mutex::unlock`].
    ///
    /// [`Mutex::unlock`]: super::mutex::MutexMethods::unlock
    pub enum UnlockMutexError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        /// The current task does not currently own the mutex.
        NotOwner,
        /// The correct mutex unlocking order is violated.
        BadObjectState,
    }
}

define_error! {
    mod try_lock_mutex_error {}
    /// Error type for [`Mutex::try_lock`].
    ///
    /// [`Mutex::try_lock`]: super::mutex::MutexMethods::try_lock
    pub enum TryLockMutexError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active, or the current context is not a [task context].
        ///
        /// [task context]: crate#contexts
        BadContext,
        Timeout,
        /// The current task already owns the mutex.
        WouldDeadlock,
        /// The mutex was created with the protocol attribute having the value
        /// [`Ceiling`] and the current task's priority is higher than the
        /// mutex's priority ceiling.
        ///
        /// [`Ceiling`]: crate::kernel::MutexProtocol::Ceiling
        BadParam,
        /// The previous owning task exited while holding the mutex lock. *The
        /// current task shall hold the mutex lock*, but is up to make the
        /// state consistent.
        Abandoned,
    }
}

define_error! {
    mod lock_mutex_error {}
    /// Error type for [`Mutex::lock`].
    ///
    /// [`Mutex::lock`]: super::mutex::MutexMethods::lock
    pub enum LockMutexError: WaitError
    {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
        /// The current task already owns the mutex.
        WouldDeadlock,
        /// The mutex was created with the protocol attribute having the value
        /// [`Ceiling`] and the current task's priority is higher than the
        /// mutex's priority ceiling.
        ///
        /// [`Ceiling`]: crate::kernel::MutexProtocol::Ceiling
        BadParam,
        /// The previous owning task exited while holding the mutex lock. *The
        /// current task shall hold the mutex lock*, but is up to make the
        /// state consistent.
        Abandoned,
    }
}

define_error! {
    mod lock_mutex_timeout_error {}
    /// Error type for [`Mutex::lock_timeout`].
    ///
    /// [`Mutex::lock_timeout`]: super::mutex::MutexMethods::lock_timeout
    pub enum LockMutexTimeoutError: WaitTimeoutError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active, or the current context is not [waitable].
        ///
        /// [waitable]: crate#contexts
        BadContext,
        Interrupted,
        Timeout,
        /// The current task already owns the mutex.
        WouldDeadlock,
        /// The timeout duration is negative, or the mutex was created with the
        /// protocol attribute having the value [`Ceiling`] and the current
        /// task's priority is higher than the mutex's priority ceiling.
        ///
        /// [`Ceiling`]: crate::kernel::MutexProtocol::Ceiling
        BadParam,
        /// The previous owning task exited while holding the mutex lock. *The
        /// current task shall hold the mutex lock*, but is up to make the
        /// state consistent.
        Abandoned,
    }
}

define_error! {
    mod mark_consistent_mutex_error {}
    /// Error type for [`Mutex::mark_consistent`].
    ///
    /// [`Mutex::mark_consistent`]: super::mutex::MutexMethods::mark_consistent
    pub enum MarkConsistentMutexError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        /// The mutex does not protect an inconsistent state.
        BadObjectState,
    }
}

define_error! {
    mod set_interrupt_line_priority_error {}
    /// Error type for [`InterruptLine::set_priority`] and
    /// [`InterruptLine::set_priority_unchecked`].
    ///
    /// [`InterruptLine::set_priority`]: super::InterruptLine::set_priority
    /// [`InterruptLine::set_priority_unchecked`]: super::InterruptLine::set_priority_unchecked
    pub enum SetInterruptLinePriorityError {
        /// The operation is not supported by the kernel.
        NotSupported,
        /// CPU Lock is active, or the current context is not [a task context].
        ///
        /// [a task context]: crate#contexts
        BadContext,
        /// The specified interrupt number or the specified priority value is
        /// out of range.
        BadParam,
    }
}

define_error! {
    mod enable_interrupt_line_error {}
    /// Error type for [`InterruptLine::enable`] and [`InterruptLine::disable`].
    ///
    /// [`InterruptLine::enable`]: super::InterruptLine::enable
    /// [`InterruptLine::disable`]: super::InterruptLine::disable
    pub enum EnableInterruptLineError {
        /// The operation is not supported by the kernel.
        NotSupported,
        /// Enabling or disabling the specified interrupt line is not supported.
        BadParam,
    }
}

define_error! {
    mod pend_interrupt_line_error {}
    /// Error type for [`InterruptLine::pend`].
    ///
    /// [`InterruptLine::pend`]: super::InterruptLine::pend
    pub enum PendInterruptLineError {
        /// Setting a pending flag is not supported by the kernel.
        NotSupported,
        /// Setting the pending flag of the specified interrupt line is not
        /// supported.
        BadParam,
        /// The interrupt line is not configured to allow this operation. For
        /// example, this operation is invalid for an level-triggered interrupt
        /// line.
        ///
        /// A kernel is not required to detect this condition.
        BadObjectState,
    }
}

define_error! {
    mod clear_interrupt_line_error {}
    /// Error type for [`InterruptLine::clear`].
    ///
    /// [`InterruptLine::clear`]: super::InterruptLine::clear
    pub enum ClearInterruptLineError {
        /// Clearing a pending flag is not supported by the kernel.
        NotSupported,
        /// Clearing the pending flag of the specified interrupt line is not
        /// supported.
        BadParam,
        /// The interrupt line is not configured to allow this operation. For
        /// example, this operation is invalid for an level-triggered interrupt
        /// line.
        ///
        /// A kernel is not required to detect this condition.
        BadObjectState,
    }
}

define_error! {
    mod query_interrupt_line_error {}
    /// Error type for [`InterruptLine::is_pending`].
    ///
    /// [`InterruptLine::is_pending`]: super::InterruptLine::is_pending
    pub enum QueryInterruptLineError {
        /// Reading a pending flag is not supported by the kernel.
        NotSupported,
        /// Reading the pending flag of the specified interrupt line is not
        /// supported.
        BadParam,
    }
}

define_error! {
    mod start_timer_error {}
    /// Error type for [`Timer::start`].
    ///
    /// [`Timer::start`]: super::timer::TimerMethods::start
    pub enum StartTimerError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod stop_timer_error {}
    /// Error type for [`Timer::stop`].
    ///
    /// [`Timer::stop`]: super::timer::TimerMethods::stop
    pub enum StopTimerError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
    }
}

define_error! {
    mod set_timer_delay_error {}
    /// Error type for [`Timer::set_delay`].
    ///
    /// [`Timer::set_delay`]: super::timer::TimerMethods::set_delay
    pub enum SetTimerDelayError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        /// The duration is negative.
        BadParam,
    }
}

define_error! {
    mod set_timer_period_error {}
    /// Error type for [`Timer::set_period`].
    ///
    /// [`Timer::set_period`]: super::timer::TimerMethods::set_period
    pub enum SetTimerPeriodError {
        /// Invalid object access.
        NoAccess,
        /// CPU Lock is active.
        BadContext,
        /// The duration is negative.
        BadParam,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn success_is_success() {
        assert!(ResultCode::Success.is_ok());
    }

    /// Checks that the compiler assigns `0` as `Ok`'s discriminant. While this
    /// isn't important for correctness nor guaranteed by the compiler, it's a
    /// useful property for performance. `[tag:zero_discriminant_optimization]`
    #[test]
    fn zero_discriminant_optimization() {
        type LockResult = Result<(), LockMutexError>;
        assert_eq!(core::mem::size_of::<LockResult>(), 1);
        assert_eq!(
            // Safety: It contains no uninitialized bytes
            unsafe { core::mem::transmute::<_, u8>(LockResult::Ok(())) },
            0
        );
    }
}