enum_code/
lib.rs

1//! ## Introduction
2//!
3//! `enum-code` is a `derive macro` for `enum` types. This library generates code that associates error codes with error types. It can be used in conjunction with the `thiserror` crate. Developers can quickly retrieve error codes by calling the `get_code` method.
4//!
5//! ## Usage
6//!
7//! #### 1. Add the `Code` attribute to the `enum` type:
8//!
9//! ```
10//! #[derive(enum_code::Code)]
11//! enum TestError {
12//!     #[code(1)]
13//!     Tuple(String),
14//!     #[code(2)]
15//!     Struct { message: String },
16//!     #[code(3)]
17//!     Simple,
18//! }
19//! ```
20//!
21//! #### 2. Code Generation
22//!
23//! For the `TestError` enum above, an associated `impl TestError` struct is generated, which includes a `get_code` method that returns the corresponding error code based on the variant value.
24//!
25//! ```
26//! impl TestError {
27//!     pub const fn get_code(&self) -> u32 {
28//!         match self {
29//!             TestError::Tuple(..) => 1u32,
30//!             TestError::Struct { .. } => 2u32,
31//!             TestError::Simple => 3u32,
32//!         }
33//!     }
34//! }
35//! ```
36//!
37//! #### 3. Retrieving Error Codes
38//!
39//! Error codes can be retrieved by calling `get_code`:
40//!
41//! ```
42//! let err = TestError::Tuple("error message".to_owned());
43//! let code = err.get_code();
44//! println!("error code: {}", code); // should print 「error code: 1」
45//! ```
46
47use crate::code::parse_code_stream;
48
49mod code;
50
51#[proc_macro_derive(Code, attributes(code))]
52pub fn code(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
53    parse_code_stream(input)
54}