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
use std::sync::Arc;

use cairo_lang_defs::plugin::{
    DynGeneratedFileAuxData, MacroPlugin, PluginDiagnostic, PluginGeneratedFile, PluginResult,
};
use cairo_lang_semantic::plugin::{AsDynMacroPlugin, SemanticPlugin, TrivialPluginAuxData};
use cairo_lang_syntax::attribute::structured::{
    AttributeArg, AttributeArgVariant, AttributeStructurize,
};
use cairo_lang_syntax::node::ast::{
    AttributeList, ItemStruct, MemberList, OptionWrappedGenericParamList, VariantList,
};
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::helpers::QueryAttrs;
use cairo_lang_syntax::node::{ast, Terminal, TypedSyntaxNode};
use indoc::formatdoc;
use itertools::Itertools;
use smol_str::SmolStr;

#[derive(Debug, Default)]
#[non_exhaustive]
pub struct DerivePlugin;

impl MacroPlugin for DerivePlugin {
    fn generate_code(&self, db: &dyn SyntaxGroup, item_ast: ast::Item) -> PluginResult {
        match item_ast {
            ast::Item::Struct(struct_ast) => generate_derive_code_for_type(
                db,
                struct_ast.name(db),
                struct_ast.attributes(db),
                extract_struct_extra_info(db, &struct_ast),
            ),
            ast::Item::Enum(enum_ast) => generate_derive_code_for_type(
                db,
                enum_ast.name(db),
                enum_ast.attributes(db),
                ExtraInfo::Enum(variant_names(db, enum_ast.variants(db))),
            ),
            ast::Item::ExternType(extern_type_ast) => generate_derive_code_for_type(
                db,
                extern_type_ast.name(db),
                extern_type_ast.attributes(db),
                ExtraInfo::Extern,
            ),
            _ => PluginResult::default(),
        }
    }
}
impl AsDynMacroPlugin for DerivePlugin {
    fn as_dyn_macro_plugin<'a>(self: Arc<Self>) -> Arc<dyn MacroPlugin + 'a>
    where
        Self: 'a,
    {
        self
    }
}
impl SemanticPlugin for DerivePlugin {}

enum ExtraInfo {
    Enum(Vec<SmolStr>),
    Struct { members: Vec<SmolStr>, type_generics: Vec<SmolStr>, other_generics: Vec<String> },
    Extern,
}

fn member_names(db: &dyn SyntaxGroup, members: MemberList) -> Vec<SmolStr> {
    members.elements(db).into_iter().map(|member| member.name(db).text(db)).collect()
}

fn variant_names(db: &dyn SyntaxGroup, variants: VariantList) -> Vec<SmolStr> {
    variants.elements(db).into_iter().map(|variant| variant.name(db).text(db)).collect()
}

fn extract_struct_extra_info(db: &dyn SyntaxGroup, struct_ast: &ItemStruct) -> ExtraInfo {
    let members = member_names(db, struct_ast.members(db));
    let mut type_generics = vec![];
    let mut other_generics = vec![];
    match struct_ast.generic_params(db) {
        OptionWrappedGenericParamList::WrappedGenericParamList(gens) => gens
            .generic_params(db)
            .elements(db)
            .into_iter()
            .map(|member| match member {
                ast::GenericParam::Type(t) => {
                    type_generics.push(t.name(db).text(db));
                }
                ast::GenericParam::Impl(i) => {
                    other_generics.push(i.as_syntax_node().get_text_without_trivia(db))
                }
                ast::GenericParam::Const(c) => {
                    other_generics.push(c.as_syntax_node().get_text_without_trivia(db))
                }
            })
            .collect(),
        OptionWrappedGenericParamList::Empty(_) => vec![],
    };
    ExtraInfo::Struct { members, type_generics, other_generics }
}

fn format_generics_with_trait(
    type_generics: &[SmolStr],
    other_generics: &[String],
    f: impl Fn(&SmolStr) -> String,
) -> String {
    format!(
        "<{}{}{}>",
        type_generics.iter().map(|s| format!("{}, ", s)).collect::<String>(),
        other_generics.iter().map(|s| format!("{}, ", s)).collect::<String>(),
        type_generics.iter().map(f).join(", "),
    )
}

fn format_generics(type_generics: &[SmolStr], other_generics: &[String]) -> String {
    format!(
        "<{}{}>",
        type_generics.iter().map(|s| format!("{}, ", s)).collect::<String>(),
        other_generics.iter().map(|s| format!("{}, ", s)).collect::<String>(),
    )
}

/// Adds an implementation for all requested derives for the type.
fn generate_derive_code_for_type(
    db: &dyn SyntaxGroup,
    ident: ast::TerminalIdentifier,
    attributes: AttributeList,
    extra_info: ExtraInfo,
) -> PluginResult {
    let mut diagnostics = vec![];
    let mut impls = vec![];
    for attr in attributes.query_attr(db, "derive") {
        let attr = attr.structurize(db);

        if attr.args.is_empty() {
            diagnostics.push(PluginDiagnostic {
                stable_ptr: attr.args_stable_ptr.untyped(),
                message: "Expected args.".into(),
            });
            continue;
        }

        for arg in attr.args {
            let AttributeArg {
                variant:
                    AttributeArgVariant::Unnamed {
                        value: ast::Expr::Path(path), value_stable_ptr, ..
                    },
                ..
            } = arg
            else {
                diagnostics.push(PluginDiagnostic {
                    stable_ptr: arg.arg_stable_ptr.untyped(),
                    message: "Expected path.".into(),
                });
                continue;
            };

            let [ast::PathSegment::Simple(segment)] = &path.elements(db)[..] else {
                continue;
            };

            let name = ident.text(db);
            let derived = segment.ident(db).text(db);
            match derived.as_str() {
                "Copy" | "Drop" => impls.push(get_empty_impl(&name, &derived, &extra_info)),
                "Clone" if !matches!(extra_info, ExtraInfo::Extern) => {
                    impls.push(get_clone_impl(&name, &extra_info))
                }
                "Destruct" if !matches!(extra_info, ExtraInfo::Extern) => {
                    impls.push(get_destruct_impl(&name, &extra_info))
                }
                "PanicDestruct" if !matches!(extra_info, ExtraInfo::Extern) => {
                    impls.push(get_panic_destruct_impl(&name, &extra_info))
                }
                "PartialEq" if !matches!(extra_info, ExtraInfo::Extern) => {
                    impls.push(get_partial_eq_impl(&name, &extra_info))
                }
                "Serde" if !matches!(extra_info, ExtraInfo::Extern) => {
                    impls.push(get_serde_impl(&name, &extra_info))
                }
                "Clone" | "Destruct" | "PartialEq" | "Serde" => {
                    diagnostics.push(PluginDiagnostic {
                        stable_ptr: value_stable_ptr.untyped(),
                        message: "Unsupported trait for derive for extern types.".into(),
                    })
                }
                _ => {
                    // TODO(spapini): How to allow downstream derives while also
                    //  alerting the user when the derive doesn't exist?
                }
            }
        }
    }
    PluginResult {
        code: if impls.is_empty() {
            None
        } else {
            Some(PluginGeneratedFile {
                name: "impls".into(),
                content: impls.join(""),
                aux_data: DynGeneratedFileAuxData(Arc::new(TrivialPluginAuxData {})),
            })
        },
        diagnostics,
        remove_original_item: false,
    }
}

fn get_clone_impl(name: &str, extra_info: &ExtraInfo) -> String {
    match extra_info {
        ExtraInfo::Enum(variants) => {
            formatdoc! {"
                    impl {name}Clone of Clone::<{name}> {{
                        fn clone(self: @{name}) -> {name} {{
                            match self {{
                                {}
                            }}
                        }}
                    }}
                ", variants.iter().map(|variant| {
                format!("{name}::{variant}(x) => {name}::{variant}(x.clone()),")
            }).join("\n            ")}
        }
        ExtraInfo::Struct { members, type_generics, other_generics } => {
            formatdoc! {"
                    impl {name}Clone{generics_impl} of Clone::<{name}{generics}> {{
                        fn clone(self: @{name}{generics}) -> {name}{generics} {{
                            {name} {{
                                {}
                            }}
                        }}
                    }}
                ", members.iter().map(|member| {
                    format!("{member}: self.{member}.clone(),")
                }).join("\n            "),
                generics = format_generics(type_generics, other_generics),
                generics_impl = format_generics_with_trait(type_generics, other_generics,
                    |t| format!("impl {t}Clone: Clone<{t}>, impl {t}Destruct: Destruct<{t}>"))
            }
        }
        ExtraInfo::Extern => unreachable!(),
    }
}

fn get_destruct_impl(name: &str, extra_info: &ExtraInfo) -> String {
    match extra_info {
        ExtraInfo::Enum(variants) => {
            formatdoc! {"
                    impl {name}Destruct of Destruct::<{name}> {{
                        fn destruct(self: {name}) nopanic {{
                            match self {{
                                {}
                            }}
                        }}
                    }}
                ", variants.iter().map(|variant| {
                format!("{name}::{variant}(x) => traits::Destruct::destruct(x),")
            }).join("\n            ")}
        }
        ExtraInfo::Struct { members, type_generics, other_generics } => {
            formatdoc! {"
                    impl {name}Destruct{generics_impl} of Destruct::<{name}{generics}> {{
                        fn destruct(self: {name}{generics}) nopanic {{
                            {}
                        }}
                    }}
                ", members.iter().map(|member| {
                    format!("traits::Destruct::destruct(self.{member});")
                }).join("\n        "),
                generics = format_generics(type_generics, other_generics),
                generics_impl = format_generics_with_trait(type_generics, other_generics,
                    |t| format!("impl {t}Destruct: Destruct<{t}>"))
            }
        }
        ExtraInfo::Extern => unreachable!(),
    }
}

fn get_panic_destruct_impl(name: &str, extra_info: &ExtraInfo) -> String {
    match extra_info {
        ExtraInfo::Enum(variants) => {
            formatdoc! {"
                    impl {name}PanicDestruct of PanicDestruct::<{name}> {{
                        fn panic_destruct(self: {name}, ref panic: Panic) nopanic {{
                            match self {{
                                {}
                            }}
                        }}
                    }}
                ", variants.iter().map(|variant| {
                format!(
                    "{name}::{variant}(x) => traits::PanicDestruct::panic_destruct(x, ref panic),",
                )
            }).join("\n            ")}
        }
        ExtraInfo::Struct { members, type_generics, other_generics } => {
            formatdoc! {"
                    impl {name}PanicDestruct{generics_impl} of PanicDestruct::<{name}{generics}> {{
                        fn panic_destruct(self: {name}{generics}, ref panic: Panic) nopanic {{
                            {}
                        }}
                    }}
                ", members.iter().map(|member| {
                    format!("traits::PanicDestruct::panic_destruct(self.{member}, ref panic);")
                }).join("\n        "),
                generics = format_generics(type_generics, other_generics),
                generics_impl = format_generics_with_trait(type_generics, other_generics,
                    |t| format!("impl {t}PanicDestruct: PanicDestruct<{t}>"))
            }
        }
        ExtraInfo::Extern => unreachable!(),
    }
}

fn get_partial_eq_impl(name: &str, extra_info: &ExtraInfo) -> String {
    match extra_info {
        ExtraInfo::Enum(variants) => {
            formatdoc! {"
                    impl {name}PartialEq of PartialEq::<{name}> {{
                        fn eq(lhs: @{name}, rhs: @{name}) -> bool {{
                            match lhs {{
                                {}
                            }}
                        }}
                        #[inline(always)]
                        fn ne(lhs: @{name}, rhs: @{name}) -> bool {{
                            !(lhs == rhs)
                        }}
                    }}
                ", variants.iter().map(|lhs_variant| {
                format!(
                    "{name}::{lhs_variant}(x) => match rhs {{\n                {}\n            }},",
                    variants.iter().map(|rhs_variant|{
                        if lhs_variant == rhs_variant {
                            format!("{name}::{rhs_variant}(y) => x == y,")
                        } else {
                            format!("{name}::{rhs_variant}(y) => false,")
                        }
                    }).join("\n                "),
                )
            }).join("\n            ")}
        }
        ExtraInfo::Struct { members, type_generics, other_generics } => {
            let generics = format_generics(type_generics, other_generics);
            let generics_impl = format_generics_with_trait(type_generics, other_generics, |t| {
                format!("impl {t}PartialEq: PartialEq<{t}>, impl {t}Destruct: Destruct<{t}>")
            });
            if members.is_empty() {
                formatdoc! {"
                    impl {name}PartialEq{generics_impl} of PartialEq::<{name}{generics}> {{
                        fn eq(lhs: @{name}{generics}, rhs: @{name}{generics}) -> bool {{ true }}
                        fn ne(lhs: @{name}{generics}, rhs: @{name}{generics}) -> bool {{ false }}
                    }}
                "}
            } else {
                formatdoc! {"
                    impl {name}PartialEq{generics_impl} of PartialEq::<{name}{generics}> {{
                        #[inline(always)]
                        fn eq(lhs: @{name}{generics}, rhs: @{name}{generics}) -> bool {{
                            {}
                        }}
                        #[inline(always)]
                        fn ne(lhs: @{name}{generics}, rhs: @{name}{generics}) -> bool {{
                            !(lhs == rhs)
                        }}
                    }}
                ", members.iter().map(|member| format!("lhs.{member} == rhs.{member}")).join(" && ")
                }
            }
        }
        ExtraInfo::Extern => unreachable!(),
    }
}

fn get_serde_impl(name: &str, extra_info: &ExtraInfo) -> String {
    match extra_info {
        ExtraInfo::Enum(variants) => {
            formatdoc! {"
                    impl {name}Serde of serde::Serde::<{name}> {{
                        fn serialize(self: @{name}, ref output: array::Array<felt252>) {{
                            match self {{
                                {}
                            }}
                        }}
                        fn deserialize(ref serialized: array::Span<felt252>) -> Option<{name}> {{
                            let idx: felt252 = serde::Serde::deserialize(ref serialized)?;
                            Option::Some(
                                {}
                                else {{ return Option::None; }}
                            )
                        }}
                    }}
                ",
                variants.iter().enumerate().map(|(idx, variant)| {
                    format!(
                        "{name}::{variant}(x) => {{ serde::Serde::serialize(@{idx}, ref output); \
                        serde::Serde::serialize(x, ref output); }},",
                    )
                }).join("\n            "),
                variants.iter().enumerate().map(|(idx, variant)| {
                    format!(
                        "if idx == {idx} {{ {name}::{variant}(serde::Serde::deserialize(ref serialized)?) }}",
                    )
                }).join("\n            else "),
            }
        }
        ExtraInfo::Struct { members, type_generics, other_generics } => {
            formatdoc! {"
                    impl {name}Serde{generics_impl} of serde::Serde::<{name}{generics}> {{
                        fn serialize(self: @{name}{generics}, ref output: array::Array<felt252>) {{
                            {}
                        }}
                        fn deserialize(ref serialized: array::Span<felt252>) -> Option<{name}{generics}> {{
                            Option::Some({name} {{
                                {}
                            }})
                        }}
                    }}
                ",
                members.iter().map(|member| format!("serde::Serde::serialize(self.{member}, ref output)")).join(";\n        "),
                members.iter().map(|member| format!("{member}: serde::Serde::deserialize(ref serialized)?,")).join("\n            "),
                generics = format_generics(type_generics, other_generics),
                generics_impl = format_generics_with_trait(type_generics, other_generics,
                    |t| format!("impl {t}Serde: serde::Serde<{t}>, impl {t}Destruct: Destruct<{t}>"))
            }
        }
        ExtraInfo::Extern => unreachable!(),
    }
}

fn get_empty_impl(name: &str, derived_trait: &str, extra_info: &ExtraInfo) -> String {
    match extra_info {
        ExtraInfo::Struct { type_generics, other_generics, .. } => format!(
            "impl {name}{derived_trait}{generics_impl} of {derived_trait}::<{name}{generics}>;\n",
            generics = format_generics(type_generics, other_generics),
            generics_impl = format_generics_with_trait(type_generics, other_generics, |t| format!(
                "impl {t}{derived_trait}: {derived_trait}<{t}>"
            ))
        ),
        _ => format!("impl {name}{derived_trait} of {derived_trait}::<{name}>;\n"),
    }
}