derive_try_from_ref/
lib.rs

1use crate::{ir::IR, item::Item};
2use proc_macro::TokenStream;
3use proc_macro_error::proc_macro_error;
4use quote::ToTokens;
5
6mod attrs;
7mod ir;
8mod item;
9mod utils;
10
11/// This function is a procedural macro that derives the `TryFromRef` trait for a given input.
12/// The `TryFromRef` trait allows for converting a reference to a type into another type, with the possibility of failure.
13/// It is used with the `#[derive(TryFromRef)]` attribute.
14///
15/// By the default, the generated implementation of `TryFromRef` trait will convert all fields of the source type into the target type.
16/// However, this behavior can be changed by using the `#[default]` and `#[expr]` attributes.
17/// #[default] sets the value of the field to the default value of the field type.
18/// #[expr] sets the value of the field to the result of the given expression.
19///
20/// # Arguments
21///
22/// - `input`: A `TokenStream` representing the input for the procedural macro.
23///
24/// # Returns
25///
26/// The generated code as a `TokenStream`.
27///
28/// A `TokenStream` representing the generated code for the `TryFromRef` trait implementation.
29///
30/// # Example
31///
32/// ```
33/// use derive_try_from::TryFromRef;
34///
35/// struct Source {
36///    a: u32,
37///    b: u32,
38/// }
39///
40///
41/// #[derive(TryFromRef)]
42/// #[source(Source)]
43/// #[err(&'static str)]
44/// struct MyStruct {
45///     // fields
46/// }
47/// ```
48#[proc_macro_derive(TryFromRef, attributes(source, default, expr, err))]
49#[proc_macro_error]
50pub fn derive_try_from(input: TokenStream) -> TokenStream {
51    let input = syn::parse_macro_input!(input as syn::DeriveInput);
52
53    let ir = IR::new(input);
54    ir.validate();
55    Item::from(ir).into_token_stream().into()
56}