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
//! just-convert make easier to convert between structs.
//!
//! This crate provides JustConvert derive macro.
//!
//! Example of use:
//!
//! ```rust
//! # use just_convert::JustConvert;
//! #
//! // Allow convert A struct into B struct
//! #[derive(JustConvert)]
//! #[convert(into(B))]
//! struct A {
//!     // field can be renamed
//!     #[convert(rename = bid)]
//!     id: i64,
//!
//!     // field can execute any expression
//!     #[convert(map = ".to_string()")]
//!     num: i64,
//!
//!     // unwrap Option value for B::name
//!     #[convert(unwrap)]
//!     name: Option<String>,
//! }
//!
//! struct B {
//!     bid: i64,
//!     num: String,
//!     name: String,
//! }
//! ```
//!
//! See more [examples](https://github.com/vettich/just-convert-rs/tree/main/examples)

use std::collections::HashMap;

use parse::parse_params;
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput, Ident, Path};

mod build;
mod map;
mod parse;

#[proc_macro_derive(JustConvert, attributes(convert))]
pub fn just_convert_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    build_impl(input).into()
}

fn build_impl(input: DeriveInput) -> proc_macro2::TokenStream {
    let params = match parse_params(&input) {
        Ok(p) => p,
        Err(err) => return err.to_compile_error(),
    };

    params
        .build()
        .unwrap_or_else(syn::Error::into_compile_error)
}

#[derive(Debug)]
struct Params {
    name: Ident,
    from: Vec<PathParams>,
    into: Vec<PathParams>,
    fields: Fields,
}

#[derive(Debug)]
struct PathParams {
    path: Path,
    default: bool,
}

#[derive(Debug, Clone)]
struct FieldParams {
    map: FieldValue<proc_macro2::Literal>,
    rename: FieldValue<Ident>,
    wrap: FieldValue<bool>,
    unwrap: FieldValue<bool>,
    skip: FieldValue<bool>,
    a_type: AdditionalType,
}

impl FieldParams {
    fn new() -> Self {
        Self {
            map: FieldValue::new(),
            rename: FieldValue::new(),
            wrap: FieldValue::new(),
            unwrap: FieldValue::new(),
            skip: FieldValue::new(),
            a_type: AdditionalType::None,
        }
    }
}

#[derive(Debug, Default, Clone)]
struct FieldValue<T> {
    common: Option<T>,
    common_from: Option<T>,
    common_into: Option<T>,
    from: HashMap<Path, T>,
    into: HashMap<Path, T>,
}

impl<T> FieldValue<T> {
    fn new() -> Self {
        Self {
            common: None,
            common_from: None,
            common_into: None,
            from: [].into(),
            into: [].into(),
        }
    }

    fn set_from(&mut self, path: Option<Path>, value: T) {
        if let Some(path) = path {
            self.from.insert(path, value);
        } else {
            self.common_from = Some(value);
        }
    }

    fn set_into(&mut self, path: Option<Path>, value: T) {
        if let Some(path) = path {
            self.into.insert(path, value);
        } else {
            self.common_into = Some(value);
        }
    }
}

#[derive(Debug, Default, Clone, Copy)]
enum AdditionalType {
    #[default]
    None,
    /// Option<T>
    Option,
    /// Option<Vec<T>>
    OptionVec,
    /// Vec<T>
    Vec,
    /// Vec<Option<T>>
    VecOption,
}

impl AdditionalType {
    fn is_option(self) -> bool {
        matches!(self, Self::Option)
    }

    fn is_option_vec(self) -> bool {
        matches!(self, Self::OptionVec)
    }

    fn is_vec(self) -> bool {
        matches!(self, Self::Vec)
    }

    fn is_vec_option(self) -> bool {
        matches!(self, Self::VecOption)
    }
}

type Fields = HashMap<Ident, FieldParams>;