evenframe_derive 0.1.5

Derive macros for Evenframe - automatic database schema and CRUD generation
Documentation
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use crate::{
    PipelineKind, deserialization_impl::generate_custom_deserialize,
    imports::generate_struct_imports,
};
use evenframe_core::{
    derive::{
        attributes::{
            parse_annotation_attributes, parse_event_attributes, parse_format_attribute,
            parse_index_attributes, parse_macroforge_derive_attribute, parse_mock_data_attribute,
            parse_mockmake_attribute, parse_relation_attribute, parse_rust_derives,
        },
        validator_parser::parse_field_validators,
    },
    schemasync::{DefineConfig, EdgeConfig, PermissionsConfig},
    types::FieldType,
};
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::spanned::Spanned;
use syn::{Data, DeriveInput, Fields, LitStr};

pub fn generate_struct_impl(input: DeriveInput, pipeline: PipelineKind) -> TokenStream {
    let ident = input.ident.clone();

    // Get centralized imports for struct implementations
    let imports = generate_struct_imports();

    if let Data::Struct(ref data_struct) = input.data {
        // Ensure the struct has named fields.
        let fields_named = if let Fields::Named(ref fields_named) = data_struct.fields {
            fields_named
        } else {
            return syn::Error::new(
                ident.span(),
                format!("Evenframe derive macro only supports structs with named fields.\n\nExample of a valid struct:\n\nstruct {} {{\n    id: String,\n    name: String,\n}}", ident),
            )
            .to_compile_error();
        };

        // Parse struct-level attributes
        let permissions_config = match PermissionsConfig::parse(&input.attrs) {
            Ok(config) => config,
            Err(err) => {
                return syn::Error::new(
                        input.span(),
                        format!("Failed to parse permissions configuration: {}\n\nExample usage:\n#[permissions(\n    select = \"true\",\n    create = \"auth.role == 'admin'\",\n    update = \"$auth.id == id\",\n    delete = \"false\"\n)]\nstruct MyStruct {{ ... }}", err)
                    )
                    .to_compile_error();
            }
        };

        // Parse mock_data attribute
        let mock_data_config = match parse_mock_data_attribute(&input.attrs) {
            Ok(config) => config,
            Err(err) => return err.to_compile_error(),
        };

        // Parse table-level validators using the same parser as field validators
        let table_validators = match parse_field_validators(&input.attrs) {
            Ok(validators) => validators,
            Err(err) => {
                return syn::Error::new(
                    input.span(),
                    format!("Failed to parse table validators: {}\n\nExample usage:\n#[validators(StringValidator::MinLength(5))]\nstruct MyStruct {{ ... }}", err)
                )
                .to_compile_error();
            }
        };

        // Parse relation attribute
        let relation_config = match parse_relation_attribute(&input.attrs) {
            Ok(Some(mut config)) => {
                // Default edge_name to snake_case of struct name if not explicitly set
                if config.edge_name.is_empty() {
                    config.edge_name = {
                        // Manual PascalCase to snake_case conversion
                        let name = ident.to_string();
                        let mut snake = String::new();
                        for (i, ch) in name.chars().enumerate() {
                            if ch.is_uppercase() && i > 0 {
                                snake.push('_');
                            }
                            snake.push(ch.to_lowercase().next().unwrap());
                        }
                        snake
                    };
                }
                Some(config)
            }
            Ok(None) => None,
            Err(err) => return err.to_compile_error(),
        };

        // Parse table-level event attributes
        let events = match parse_event_attributes(&input.attrs) {
            Ok(events) => events,
            Err(err) => {
                return syn::Error::new(
                    input.span(),
                    format!(
                        "Failed to parse event attribute: {}\n\nExample usage:\n#[event(\"DEFINE EVENT my_event ON TABLE my_table WHEN $before != $after THEN ...\")]",
                        err
                    ),
                )
                .to_compile_error();
            }
        };

        // Parse macroforge_derive attribute
        let macroforge_derives = match parse_macroforge_derive_attribute(&input.attrs) {
            Ok(derives) => derives,
            Err(err) => return err.to_compile_error(),
        };

        // Parse annotation attributes
        let struct_annotations = match parse_annotation_attributes(&input.attrs) {
            Ok(annotations) => annotations,
            Err(err) => return err.to_compile_error(),
        };

        // Parse all Rust derives (#[derive(Serialize, Clone, ...)])
        let rust_derives = parse_rust_derives(&input.attrs);

        // Collect known field names so we can validate #[index(fields(...))]
        // references at parse time.
        let known_field_names: std::collections::BTreeSet<String> = fields_named
            .named
            .iter()
            .filter_map(|f| {
                f.ident
                    .as_ref()
                    .map(|i| i.to_string().trim_start_matches("r#").to_string())
            })
            .collect();

        // Parse struct-level #[index(fields(a, b), unique)] attributes.
        let indexes = match parse_index_attributes(&input.attrs, &known_field_names) {
            Ok(v) => v,
            Err(err) => return err.to_compile_error(),
        };

        // Check if an "id" field exists.
        // Structs with an "id" field are treated as persistable entities (database tables).
        // Structs without an "id" field are treated as application-level data structures.
        let has_id = fields_named.named.iter().any(|field| {
            // Check if field name is "id" - unwrap_or(false) handles unnamed fields gracefully
            field.ident.as_ref().map(|id| id == "id").unwrap_or(false)
        });

        // Single pass over all fields.
        let mut table_field_tokens = Vec::new();
        let mut json_assignments = Vec::new();

        for field in fields_named.named.iter() {
            let field_ident = match field.ident.as_ref() {
                Some(ident) => ident,
                None => {
                    return syn::Error::new(
                        field.span(),
                        "Internal error: Field identifier is missing. This should not happen with named fields."
                    )
                    .to_compile_error();
                }
            };
            let field_name = field_ident.to_string();
            // Remove the r# prefix from raw identifiers (e.g., r#type -> type)
            let field_name_trim = field_name.trim_start_matches("r#");

            // Build the field type token.
            let ty = &field.ty;
            let field_type = FieldType::parse_syn_ty(ty);

            // Parse any edge attribute.
            let edge_config = match EdgeConfig::parse(field) {
                Ok(details) => details,
                Err(err) => {
                    return syn::Error::new(
                        field.span(),
                        format!("Failed to parse edge configuration for field '{}': {}\n\nExample usage:\n#[edge(name = \"has_user\", direction = \"from\", to = \"User\")]\npub user: RecordLink<User>", field_name, err)
                    )
                    .to_compile_error();
                }
            };

            // Parse any define details.
            let define_config = match DefineConfig::parse(field) {
                Ok(details) => details,
                Err(err) => {
                    return syn::Error::new(
                        field.span(),
                        format!("Failed to parse define configuration for field '{}': {}\n\nExample usage:\n#[define(default = \"0\", readonly = true)]\npub count: u32", field_name, err)
                    )
                    .to_compile_error();
                }
            };

            // Parse any format attribute.
            let format = match parse_format_attribute(&field.attrs) {
                Ok(fmt) => fmt,
                Err(err) => {
                    return syn::Error::new(
                        field.span(),
                        format!(
                            "Failed to parse format attribute for field '{}': {}",
                            field_name, err
                        ),
                    )
                    .to_compile_error();
                }
            };

            // Parse field-level validators
            let field_validators = match parse_field_validators(&field.attrs) {
                Ok(v) => v,
                Err(err) => {
                    return syn::Error::new(
                        field.span(),
                        format!("Failed to parse validators for field '{}': {}\n\nExample usage:\n#[validate(min_length = 3, max_length = 50)]\npub name: String\n\n#[validate(email)]\npub email: String", field_name, err)
                    )
                    .to_compile_error();
                }
            };

            // Build the schema token for this field.
            let edge_config_tokens = if let Some(ref details) = edge_config {
                quote! {
                    Some(#details)
                }
            } else {
                quote! { None }
            };

            // Build the schema token for this field.
            let define_config_tokens = if let Some(ref define) = define_config {
                quote! {
                    Some(#define)
                }
            } else {
                quote! { None }
            };

            // Build the schema token for this field.
            let format_tokens = if let Some(ref fmt) = format {
                quote! { Some(#fmt) }
            } else {
                quote! { None }
            };

            // Parse field-level annotations
            let field_annotations = match parse_annotation_attributes(&field.attrs) {
                Ok(annotations) => annotations,
                Err(err) => return err.to_compile_error(),
            };

            // Parse unique attribute (marker attribute, no arguments)
            let is_unique = field
                .attrs
                .iter()
                .any(|attr| attr.path().is_ident("unique"));

            // Parse mockmake plugin attribute
            let mock_plugin = match parse_mockmake_attribute(&field.attrs) {
                Ok(p) => p,
                Err(err) => {
                    return syn::Error::new(
                        field.span(),
                        format!(
                            "Failed to parse mockmake attribute for field '{}': {}",
                            field_name, err
                        ),
                    )
                    .to_compile_error();
                }
            };

            // Build validators token for this field
            let validators_tokens = if field_validators.is_empty() {
                quote! { vec![] }
            } else {
                quote! { vec![#(#field_validators),*] }
            };

            let field_annotations_tokens = if field_annotations.is_empty() {
                quote! { vec![] }
            } else {
                quote! { vec![#(#field_annotations.to_string()),*] }
            };

            let mock_plugin_tokens = match &mock_plugin {
                Some(name) => quote! { Some(#name.to_string()) },
                None => quote! { None },
            };

            table_field_tokens.push(quote! {
                StructField {
                    field_name: #field_name_trim.to_string(),
                    field_type: #field_type,
                    edge_config: #edge_config_tokens,
                    define_config: #define_config_tokens,
                    format: #format_tokens,
                    validators: #validators_tokens,
                    always_regenerate: false,
                    doccom: None,
                    annotations: #field_annotations_tokens,
                    unique: #is_unique,
                    mock_plugin: #mock_plugin_tokens,
                    output_override: None,
                    raw_attributes: std::collections::BTreeMap::new(),
                }
            });

            // For the JSON payload, skip the "id" field and any field with an edge attribute.
            if field_name != "id" && edge_config.is_none() {
                json_assignments.push(quote! {
                    #field_name: payload.#field_ident,
                });
            }
        }

        // Build the JSON payload block.
        // let json_payload = quote! { { #(#json_assignments)* } };

        // Generate tokens for parsed attributes (shared between implementations)
        let struct_name = ident.to_string();

        let table_name = ident.to_string();

        let permissions_config_tokens = if let Some(ref config) = permissions_config {
            quote! { Some(#config) }
        } else {
            quote! { None }
        };

        let table_validators_tokens = if !table_validators.is_empty() {
            // The validators are already TokenStreams from parse_field_validators
            quote! { vec![#(#table_validators),*] }
        } else {
            quote! { vec![] }
        };

        let mock_data_tokens = if let Some(config) = mock_data_config {
            quote! { Some(#config) }
        } else {
            quote! { None }
        };

        let relation_tokens = if let Some(ref rel) = relation_config {
            quote! { Some(#rel) }
        } else {
            quote! { None }
        };

        let event_tokens = if events.is_empty() {
            quote! { Vec::new() }
        } else {
            let event_configs = events.iter().map(|statement| {
                let lit = LitStr::new(statement, Span::call_site());
                quote! {
                    ::evenframe::schemasync::EventConfig {
                        statement: String::from(#lit),
                    }
                }
            });

            quote! { vec![#(#event_configs),*] }
        };

        let macroforge_derives_tokens = if macroforge_derives.is_empty() {
            quote! { vec![] }
        } else {
            quote! { vec![#(#macroforge_derives.to_string()),*] }
        };

        let struct_annotations_tokens = if struct_annotations.is_empty() {
            quote! { vec![] }
        } else {
            quote! { vec![#(#struct_annotations.to_string()),*] }
        };

        let rust_derives_tokens = if rust_derives.is_empty() {
            quote! { vec![] }
        } else {
            quote! { vec![#(#rust_derives.to_string()),*] }
        };

        let pipeline_tokens = pipeline.to_tokens();

        let indexes_tokens = if indexes.is_empty() {
            quote! { vec![] }
        } else {
            let entries = indexes.iter().map(|idx| {
                let field_strs = idx.fields.iter().map(|s| quote! { #s.to_string() });
                let unique = idx.unique;
                quote! {
                    ::evenframe::schemasync::IndexConfig {
                        fields: vec![ #(#field_strs),* ],
                        unique: #unique,
                    }
                }
            });
            quote! { vec![ #(#entries),* ] }
        };

        let evenframe_persistable_struct_impl = {
            quote! {
                impl EvenframePersistableStruct for #ident {
                    fn static_table_config() -> TableConfig {
                        TableConfig {
                            table_name: #table_name.to_case(Case::Snake),
                            struct_config: ::evenframe::types::StructConfig {
                                struct_name: #struct_name.to_owned(),
                                fields: vec![ #(#table_field_tokens),* ],
                                validators: #table_validators_tokens,
                                doccom: None,
                                macroforge_derives: #macroforge_derives_tokens,
                                annotations: #struct_annotations_tokens,
                                pipeline: #pipeline_tokens,
                                rust_derives: #rust_derives_tokens,
                                output_override: None,
                                raw_attributes: std::collections::BTreeMap::new(),
                            },
                            relation: #relation_tokens,
                            permissions: #permissions_config_tokens,
                            mock_generation_config: #mock_data_tokens,
                            events: #event_tokens,
                            indexes: #indexes_tokens,
                        }
                    }
                }
            }
        };

        // No trait implementation needed for app structs - the derive macro itself is the marker

        // Check if any field has validators
        // We check this to determine if we need to generate custom deserialization
        let has_field_validators = fields_named.named.iter().any(|field| {
            match parse_field_validators(&field.attrs) {
                Ok(validators) => !validators.is_empty(),
                Err(_) => true, // If parsing fails, assume validators exist to be safe
            }
        });

        // Generate custom deserialization if there are field validators
        let deserialize_impl = if has_field_validators || !table_validators.is_empty() {
            generate_custom_deserialize(&input)
        } else {
            quote! {}
        };

        if has_id {
            // Generate registry submission for table structs
            let registry_var_name = syn::Ident::new(
                &format!("{}_REGISTRY_ENTRY", ident.to_string().to_uppercase()),
                ident.span(),
            );
            let registry_submission = quote! {
                #[::evenframe::linkme::distributed_slice(::evenframe::registry::TABLE_REGISTRY_ENTRIES)]
                static #registry_var_name: ::evenframe::registry::TableRegistryEntry = ::evenframe::registry::TableRegistryEntry {
                    type_name: #struct_name,
                    table_config_fn: || #ident::static_table_config(),
                    pipeline: #pipeline_tokens,
                };
            };

            quote! {
                const _: () = {
                    #imports

                    #evenframe_persistable_struct_impl

                    #registry_submission
                };

                #deserialize_impl
            }
        } else {
            // For app structs, we only generate deserialization if needed
            // The derive macro itself serves as the marker
            if has_field_validators {
                deserialize_impl
            } else {
                quote! {}
            }
        }
    } else {
        syn::Error::new(
            ident.span(),
            format!("The Evenframe derive macro can only be applied to structs.\n\nYou tried to apply it to: {}\n\nExample of correct usage:\n#[derive(Evenframe)]\nstruct MyStruct {{\n    id: String,\n    // ... other fields\n}}", ident)
        )
        .to_compile_error()
    }
}