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
#![doc = include_str!("../README.md")]

mod derive;
mod fields;
mod generic_helpers;
mod lists_and_arguments;
mod model;

use std::error::Error;

use either_n::Either2;
use proc_macro2::{Ident, Span, TokenStream};
use syn::{Attribute, ConstParam, Expr, FnArg, GenericParam, Path, Stmt, Type, TypeParam};

pub use proc_macro2;
pub use quote::{format_ident, quote, ToTokens};
pub use syn;

pub use derive::*;
pub use fields::*;
pub use lists_and_arguments::*;
pub use model::Item;

/// Returns true if same variant and same name, ignores bounds
pub(crate) fn generic_parameters_have_same_name(
    generic_parameter1: &GenericParam,
    generic_parameter2: &GenericParam,
) -> bool {
    match (generic_parameter1, generic_parameter2) {
        (GenericParam::Type(gtp1), GenericParam::Type(gtp2)) => gtp1.ident == gtp2.ident,
        (GenericParam::Lifetime(glp1), GenericParam::Lifetime(glp2)) => {
            glp1.lifetime.ident == glp2.lifetime.ident
        }
        (GenericParam::Const(gcp1), GenericParam::Const(gcp2)) => gcp1.ident == gcp2.ident,
        _ => false,
    }
}

/// Removes the bounds and uses the parameter as a reference
pub(crate) fn generic_param_to_generic_argument_token_stream(
    trait_generic_parameter: &GenericParam,
) -> TokenStream {
    match trait_generic_parameter {
        GenericParam::Const(ConstParam { ident, .. })
        | GenericParam::Type(TypeParam { ident, .. }) => ident.to_token_stream(),
        GenericParam::Lifetime(lifetime) => lifetime.to_token_stream(),
    }
}

pub fn dyn_error_to_compile_error_tokens(err: Box<dyn Error>) -> TokenStream {
    let error_as_string = syn::LitStr::new(&err.to_string(), Span::call_site());
    quote!(compile_error!(#error_as_string);)
}

/// A declaration for a Rust [trait](https://doc.rust-lang.org/rust-by-example/trait.html)
pub struct Trait {
    pub name: Path,
    pub generic_parameters: Option<Vec<GenericParam>>,
    pub items: Vec<TraitItem>,
}

/// Statements returned from the handler
type HandlerResult = Result<Vec<Stmt>, Box<dyn Error>>;

/// A item under a trait
pub enum TraitItem {
    Method {
        name: Ident,
        generic_parameters: Option<Vec<GenericParam>>,
        self_type: TypeOfSelf,
        other_parameters: Vec<FnArg>,
        return_type: Option<Type>,
        handler: Box<dyn for<'a> Fn(Item<'a>) -> HandlerResult>,
    },
    AssociatedFunction {
        name: Ident,
        generic_parameters: Option<Vec<GenericParam>>,
        parameters: Vec<FnArg>,
        return_type: Option<Type>,
        handler: Box<dyn for<'a> Fn(&'a mut Structure) -> HandlerResult>,
    },
}

/// What ownership the method requires
#[derive(Clone, Copy)]
pub enum TypeOfSelf {
    /// `&self`
    Reference,
    /// `&mut self`
    MutableReference,
    /// `self`
    Owned,
}

impl TypeOfSelf {
    fn as_parameter_tokens(&self) -> TokenStream {
        match self {
            TypeOfSelf::Reference => quote!(&self),
            TypeOfSelf::MutableReference => quote!(&mut self),
            TypeOfSelf::Owned => quote!(self),
        }
    }

    fn as_matcher_tokens(&self) -> TokenStream {
        match self {
            TypeOfSelf::Reference => quote!(ref),
            TypeOfSelf::MutableReference => quote!(ref mut),
            TypeOfSelf::Owned => TokenStream::default(),
        }
    }
}

impl TraitItem {
    /// Create a new method (something that takes `self`, `&self` or `&mut self`)
    pub fn new_method(
        name: Ident,
        generic_parameters: Option<Vec<GenericParam>>,
        self_type: TypeOfSelf,
        other_parameters: Vec<FnArg>,
        return_type: Option<Type>,
        handler: impl for<'a> Fn(Item<'a>) -> HandlerResult + 'static,
    ) -> Self {
        Self::Method {
            name,
            generic_parameters,
            self_type,
            other_parameters,
            return_type,
            handler: Box::new(handler),
        }
    }

    /// Create a new associated function (doesn't take any reference of self)
    pub fn new_associated_function(
        name: Ident,
        generic_parameters: Option<Vec<GenericParam>>,
        parameters: Vec<FnArg>,
        return_type: Option<Type>,
        handler: impl for<'a> Fn(&'a mut Structure) -> HandlerResult + 'static,
    ) -> Self {
        Self::AssociatedFunction {
            name,
            generic_parameters,
            parameters,
            return_type,
            handler: Box::new(handler),
        }
    }
}

/// An [Enum](https://doc.rust-lang.org/rust-by-example/custom_types/enum.html)
pub struct EnumStructure {
    name: Ident,
    attrs: Vec<Attribute>,
    variants: Vec<EnumVariant>,
}

impl EnumStructure {
    pub fn get_variants(&self) -> &[EnumVariant] {
        &self.variants
    }

    pub fn get_variants_mut(&mut self) -> &mut [EnumVariant] {
        self.variants.as_mut_slice()
    }
}

impl HasAttributes for EnumStructure {
    fn get_attributes(&self) -> &[Attribute] {
        &self.attrs
    }
}

/// A member of an [EnumStructure]
pub struct EnumVariant {
    full_path: Path,
    pub idx: usize,
    fields: Fields,
}

/// A [Struct](https://doc.rust-lang.org/rust-by-example/custom_types/structs.html)
pub struct StructStructure {
    name: Ident,
    fields: Fields,
}

/// A Rust structure which can be *created* (either a struct or enum variant)
pub trait Constructable {
    /// Get the path required to construct the expression
    fn get_constructor_path(&self) -> Path;

    /// Builds a constructor expression by evaluating a expression generator for each field
    fn build_constructor(
        &self,
        generator: impl Fn(NamedOrUnnamedField) -> Result<Expr, Box<dyn Error>>,
    ) -> Result<Expr, Box<dyn std::error::Error>>;

    fn get_fields(&self) -> &Fields;
    fn get_fields_mut(&mut self) -> &mut Fields;
}

impl Constructable for StructStructure {
    fn build_constructor(
        &self,
        generator: impl Fn(NamedOrUnnamedField) -> Result<Expr, Box<dyn Error>>,
    ) -> Result<Expr, Box<dyn std::error::Error>> {
        self.fields
            .to_constructor(generator, self.name.clone().into())
    }

    fn get_fields(&self) -> &Fields {
        &self.fields
    }

    fn get_fields_mut(&mut self) -> &mut Fields {
        &mut self.fields
    }

    fn get_constructor_path(&self) -> Path {
        self.name.clone().into()
    }
}

impl Constructable for EnumVariant {
    fn build_constructor(
        &self,
        generator: impl Fn(NamedOrUnnamedField) -> Result<Expr, Box<dyn Error>>,
    ) -> Result<Expr, Box<dyn std::error::Error>> {
        self.fields
            .to_constructor(generator, self.full_path.clone())
    }

    fn get_fields(&self) -> &Fields {
        &self.fields
    }

    fn get_fields_mut(&mut self) -> &mut Fields {
        &mut self.fields
    }

    fn get_constructor_path(&self) -> Path {
        self.full_path.clone()
    }
}

pub trait HasAttributes {
    fn get_attributes(&self) -> &[Attribute];
}

/// Either a [StructStructure] or [EnumStructure]
pub enum Structure {
    Struct(StructStructure),
    Enum(EnumStructure),
}

/// Either a [StructStructure] or [EnumVariant] (with it's parents attributes)
pub enum ConstructableStructure<'a> {
    Struct(&'a mut StructStructure),
    EnumVariant(&'a mut EnumVariant, &'a [Attribute]),
}

impl Structure {
    /// Iterator over all the fields
    fn all_fields(&self) -> impl Iterator<Item = NamedOrUnnamedField<'_>> {
        match self {
            Structure::Struct(r#struct) => Either2::One(r#struct.get_fields().fields_iterator()),
            Structure::Enum(r#enum) => Either2::Two(
                r#enum
                    .variants
                    .iter()
                    .flat_map(|variant| variant.get_fields().fields_iterator()),
            ),
        }
    }

    /// The top attributes
    pub fn get_attributes(&self) -> &[Attribute] {
        match self {
            // attributes have been moved to fields here
            Structure::Struct(r#struct) => r#struct.fields.get_field_attributes(),
            Structure::Enum(r#enum) => r#enum.attrs.as_slice(),
        }
    }

    /// The declaration name
    pub fn get_name(&self) -> &Ident {
        match self {
            Structure::Struct(r#struct) => &r#struct.name,
            Structure::Enum(r#enum) => &r#enum.name,
        }
    }
}

impl Constructable for ConstructableStructure<'_> {
    fn build_constructor(
        &self,
        generator: impl Fn(NamedOrUnnamedField) -> Result<Expr, Box<dyn Error>>,
    ) -> Result<Expr, Box<dyn std::error::Error>> {
        match self {
            ConstructableStructure::Struct(r#struct) => r#struct.build_constructor(generator),
            ConstructableStructure::EnumVariant(enum_variant, _) => {
                enum_variant.build_constructor(generator)
            }
        }
    }

    fn get_fields(&self) -> &Fields {
        match self {
            ConstructableStructure::Struct(r#struct) => r#struct.get_fields(),
            ConstructableStructure::EnumVariant(enum_variant, _) => enum_variant.get_fields(),
        }
    }

    fn get_fields_mut(&mut self) -> &mut Fields {
        match self {
            ConstructableStructure::Struct(r#struct) => r#struct.get_fields_mut(),
            ConstructableStructure::EnumVariant(enum_variant, _) => enum_variant.get_fields_mut(),
        }
    }

    fn get_constructor_path(&self) -> Path {
        match self {
            ConstructableStructure::Struct(r#struct) => r#struct.get_constructor_path(),
            ConstructableStructure::EnumVariant(enum_variant, _) => {
                enum_variant.get_constructor_path()
            }
        }
    }
}

impl<'a> ConstructableStructure<'a> {
    pub fn as_enum_variant(&'a self) -> Option<&'a EnumVariant> {
        if let Self::EnumVariant(variant, _) = self {
            Some(&**variant)
        } else {
            None
        }
    }

    pub fn all_attributes<'b: 'a>(&'b self) -> impl Iterator<Item = &'b Attribute> + '_ {
        match self {
            ConstructableStructure::Struct(r#struct) => {
                Either2::One(r#struct.get_fields().get_field_attributes().iter())
            }
            ConstructableStructure::EnumVariant(r#enum, parent_attrs) => Either2::Two(
                parent_attrs
                    .iter()
                    .chain(r#enum.get_fields().get_field_attributes().iter()),
            ),
        }
    }
}

/// Prints a path out as its source representation
pub fn path_to_string(path: Path) -> String {
    let mut buf = String::new();
    if path.leading_colon.is_some() {
        buf.push_str("::");
    }
    for (idx, segment) in path.segments.iter().enumerate() {
        buf.push_str(&segment.ident.to_string());
        if !segment.arguments.is_empty() {
            todo!()
        }
        if idx != path.segments.len() - 1 {
            buf.push_str("::");
        }
    }
    buf
}