hyperstack-macros 0.6.9

Proc-macros for defining HyperStack streams
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Shared handler code generation for hyperstack-macros.
//!
//! This module provides unified handler generation that can be used by both:
//! - `#[hyperstack]` - generates handlers during macro expansion
//! - `#[ast_spec]` - generates handlers from serialized AST
//!
//! The key abstraction is `build_handler_code` which takes a `SerializableHandlerSpec`
//! and generates the corresponding Rust code for creating a `TypedHandlerSpec`.

use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};

use crate::ast::{
    ComparisonOp, ConditionExpr, FieldPath, IdlSerializationSnapshot, KeyResolutionStrategy,
    LogicalOp, MappingSource, ParsedCondition, PopulationStrategy, SerializableFieldMapping,
    SerializableHandlerSpec, SourceSpec, Transformation,
};

/// Build handler code from a serializable handler spec.
///
/// This is the main entry point for generating handler code. It takes a
/// `SerializableHandlerSpec` (which can come from either macro expansion or
/// deserialized AST) and generates the corresponding `TypedHandlerSpec` construction code.
///
/// # Arguments
///
/// * `handler` - The handler specification to generate code for
/// * `state_name` - The name of the state struct (e.g., "BondingCurveState")
///
/// # Returns
///
/// A `TokenStream` containing the code to construct a `TypedHandlerSpec`.
pub fn build_handler_code(
    handler: &SerializableHandlerSpec,
    state_name: &syn::Ident,
) -> TokenStream {
    // Generate source spec code
    let source_code = build_source_spec_code(&handler.source);

    // Generate key resolution code
    let key_resolution_code = build_key_resolution_code(&handler.key_resolution);

    // Generate field mapping code
    let mappings_code: Vec<TokenStream> = handler
        .mappings
        .iter()
        .map(build_field_mapping_code)
        .collect();

    let emit = handler.emit;

    quote_spanned! { state_name.span()=>
        hyperstack::runtime::hyperstack_interpreter::ast::TypedHandlerSpec::<#state_name>::new(
            #source_code,
            #key_resolution_code,
            vec![
                #(#mappings_code),*
            ],
            #emit,
        )
    }
}

/// Build a handler function definition.
///
/// This generates a complete function that returns a `TypedHandlerSpec`.
///
/// # Arguments
///
/// * `handler` - The handler specification
/// * `handler_name` - The name for the generated function
/// * `state_name` - The name of the state struct
pub fn build_handler_fn(
    handler: &SerializableHandlerSpec,
    handler_name: &syn::Ident,
    state_name: &syn::Ident,
) -> TokenStream {
    let handler_code = build_handler_code(handler, state_name);

    quote_spanned! { handler_name.span()=>
        fn #handler_name() -> hyperstack::runtime::hyperstack_interpreter::ast::TypedHandlerSpec<#state_name> {
            #handler_code
        }
    }
}

/// Generate code for SourceSpec.
fn build_source_spec_code(source: &SourceSpec) -> TokenStream {
    match source {
        SourceSpec::Source {
            program_id,
            discriminator,
            type_name,
            serialization,
            is_account,
        } => {
            let program_id_code = match program_id {
                Some(id) => quote! { Some(#id.to_string()) },
                None => quote! { None },
            };

            let discriminator_code = match discriminator {
                Some(disc) => {
                    let bytes = disc.iter();
                    quote! { Some(vec![#(#bytes),*]) }
                }
                None => quote! { None },
            };

            let serialization_code = match serialization {
                Some(IdlSerializationSnapshot::Borsh) => quote! {
                    Some(hyperstack::runtime::hyperstack_interpreter::ast::IdlSerializationSnapshot::Borsh)
                },
                Some(IdlSerializationSnapshot::Bytemuck) => quote! {
                    Some(hyperstack::runtime::hyperstack_interpreter::ast::IdlSerializationSnapshot::Bytemuck)
                },
                Some(IdlSerializationSnapshot::BytemuckUnsafe) => quote! {
                    Some(hyperstack::runtime::hyperstack_interpreter::ast::IdlSerializationSnapshot::BytemuckUnsafe)
                },
                None => quote! { None },
            };

            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::SourceSpec::Source {
                    program_id: #program_id_code,
                    discriminator: #discriminator_code,
                    type_name: #type_name.to_string(),
                    serialization: #serialization_code,
                    is_account: #is_account,
                }
            }
        }
    }
}

/// Generate code for KeyResolutionStrategy.
fn build_key_resolution_code(strategy: &KeyResolutionStrategy) -> TokenStream {
    match strategy {
        KeyResolutionStrategy::Embedded { primary_field } => {
            let field_path_code = build_field_path_code(primary_field);
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::KeyResolutionStrategy::Embedded {
                    primary_field: #field_path_code,
                }
            }
        }
        KeyResolutionStrategy::Lookup { primary_field } => {
            let field_path_code = build_field_path_code(primary_field);
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::KeyResolutionStrategy::Lookup {
                    primary_field: #field_path_code,
                }
            }
        }
        KeyResolutionStrategy::Computed {
            primary_field,
            compute_partition,
        } => {
            let field_path_code = build_field_path_code(primary_field);
            let compute_code = build_compute_function_code(compute_partition);
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::KeyResolutionStrategy::Computed {
                    primary_field: #field_path_code,
                    compute_partition: #compute_code,
                }
            }
        }
        KeyResolutionStrategy::TemporalLookup {
            lookup_field,
            timestamp_field,
            index_name,
        } => {
            let lookup_code = build_field_path_code(lookup_field);
            let timestamp_code = build_field_path_code(timestamp_field);
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::KeyResolutionStrategy::TemporalLookup {
                    lookup_field: #lookup_code,
                    timestamp_field: #timestamp_code,
                    index_name: #index_name.to_string(),
                }
            }
        }
    }
}

/// Generate code for FieldPath.
fn build_field_path_code(path: &FieldPath) -> TokenStream {
    let segments: Vec<&str> = path.segments.iter().map(|s| s.as_str()).collect();
    quote! {
        hyperstack::runtime::hyperstack_interpreter::ast::FieldPath::new(&[#(#segments),*])
    }
}

/// Generate code for ComputeFunction.
fn build_compute_function_code(func: &crate::ast::ComputeFunction) -> TokenStream {
    match func {
        crate::ast::ComputeFunction::Sum => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComputeFunction::Sum }
        }
        crate::ast::ComputeFunction::Concat => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComputeFunction::Concat }
        }
        crate::ast::ComputeFunction::Format(fmt) => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComputeFunction::Format(#fmt.to_string()) }
        }
        crate::ast::ComputeFunction::Custom(name) => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComputeFunction::Custom(#name.to_string()) }
        }
    }
}

/// Generate code for a single field mapping.
fn build_field_mapping_code(mapping: &SerializableFieldMapping) -> TokenStream {
    let target_path = &mapping.target_path;
    let source_code = build_mapping_source_code(&mapping.source);
    let population_code = build_population_strategy_code(&mapping.population);

    let mut mapping_code = quote! {
        hyperstack::runtime::hyperstack_interpreter::ast::TypedFieldMapping::new(
            #target_path.to_string(),
            #source_code,
            #population_code,
        )
    };

    if let Some(transform) = &mapping.transform {
        let transform_code = build_transformation_code(transform);
        mapping_code = quote! {
            #mapping_code.with_transform(#transform_code)
        };
    }

    if let Some(condition) = &mapping.condition {
        let condition_code = build_condition_expr_code(condition);
        mapping_code = quote! {
            #mapping_code.with_condition(#condition_code)
        };
    }

    if let Some(when) = &mapping.when {
        mapping_code = quote! {
            #mapping_code.with_when(#when.to_string())
        };
    }

    if let Some(stop) = &mapping.stop {
        mapping_code = quote! {
            #mapping_code.with_stop(#stop.to_string())
        };
    }

    if !mapping.emit {
        mapping_code = quote! {
            #mapping_code.with_emit(false)
        };
    }

    mapping_code
}

fn build_condition_expr_code(condition: &ConditionExpr) -> TokenStream {
    let expression = &condition.expression;
    let parsed_code = match &condition.parsed {
        Some(parsed) => {
            let parsed_code = build_parsed_condition_code(parsed);
            quote! { Some(#parsed_code) }
        }
        None => quote! { None },
    };

    quote! {
        hyperstack::runtime::hyperstack_interpreter::ast::ConditionExpr {
            expression: #expression.to_string(),
            parsed: #parsed_code,
        }
    }
}

fn build_parsed_condition_code(condition: &ParsedCondition) -> TokenStream {
    match condition {
        ParsedCondition::Comparison { field, op, value } => {
            let field_code = build_field_path_code(field);
            let op_code = build_comparison_op_code(op);
            let value_str = serde_json::to_string(value).unwrap_or_else(|_| "null".to_string());
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::ParsedCondition::Comparison {
                    field: #field_code,
                    op: #op_code,
                    value: hyperstack::runtime::serde_json::from_str(#value_str)
                        .unwrap_or(hyperstack::runtime::serde_json::Value::Null),
                }
            }
        }
        ParsedCondition::Logical { op, conditions } => {
            let op_code = build_logical_op_code(op);
            let nested: Vec<TokenStream> =
                conditions.iter().map(build_parsed_condition_code).collect();
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::ParsedCondition::Logical {
                    op: #op_code,
                    conditions: vec![#(#nested),*],
                }
            }
        }
    }
}

fn build_comparison_op_code(op: &ComparisonOp) -> TokenStream {
    match op {
        ComparisonOp::Equal => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComparisonOp::Equal }
        }
        ComparisonOp::NotEqual => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComparisonOp::NotEqual }
        }
        ComparisonOp::GreaterThan => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComparisonOp::GreaterThan }
        }
        ComparisonOp::GreaterThanOrEqual => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComparisonOp::GreaterThanOrEqual }
        }
        ComparisonOp::LessThan => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComparisonOp::LessThan }
        }
        ComparisonOp::LessThanOrEqual => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::ComparisonOp::LessThanOrEqual }
        }
    }
}

fn build_logical_op_code(op: &LogicalOp) -> TokenStream {
    match op {
        LogicalOp::And => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::LogicalOp::And }
        }
        LogicalOp::Or => quote! { hyperstack::runtime::hyperstack_interpreter::ast::LogicalOp::Or },
    }
}

/// Generate code for MappingSource.
fn build_mapping_source_code(source: &MappingSource) -> TokenStream {
    match source {
        MappingSource::FromSource {
            path,
            default,
            transform,
        } => {
            let path_code = build_field_path_code(path);
            let default_code = match default {
                Some(val) => {
                    let val_str = serde_json::to_string(val).unwrap_or_else(|_| "null".to_string());
                    quote! { Some(hyperstack::runtime::serde_json::from_str(#val_str).unwrap_or(hyperstack::runtime::serde_json::Value::Null)) }
                }
                None => quote! { None },
            };
            let transform_code = match transform {
                Some(t) => {
                    let t_code = build_transformation_code(t);
                    quote! { Some(#t_code) }
                }
                None => quote! { None },
            };
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::FromSource {
                    path: #path_code,
                    default: #default_code,
                    transform: #transform_code,
                }
            }
        }
        MappingSource::Constant(val) => {
            let val_str = serde_json::to_string(val).unwrap_or_else(|_| "null".to_string());
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::Constant(
                    hyperstack::runtime::serde_json::from_str(#val_str).unwrap_or(hyperstack::runtime::serde_json::Value::Null)
                )
            }
        }
        MappingSource::Computed { inputs, function } => {
            let inputs_code: Vec<TokenStream> = inputs.iter().map(build_field_path_code).collect();
            let func_code = build_compute_function_code(function);
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::Computed {
                    inputs: vec![#(#inputs_code),*],
                    function: #func_code,
                }
            }
        }
        MappingSource::FromState { path } => {
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::FromState {
                    path: #path.to_string(),
                }
            }
        }
        MappingSource::AsEvent { fields } => {
            let fields_code: Vec<TokenStream> = fields
                .iter()
                .map(|f| {
                    let source_code = build_mapping_source_code(f);
                    quote! { Box::new(#source_code) }
                })
                .collect();
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::AsEvent {
                    fields: vec![#(#fields_code),*],
                }
            }
        }
        MappingSource::WholeSource => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::WholeSource }
        }
        MappingSource::AsCapture { field_transforms } => {
            let transform_insertions: Vec<TokenStream> = field_transforms
                .iter()
                .map(|(field, transform)| {
                    let transform_code = build_transformation_code(transform);
                    quote! {
                        field_transforms.insert(#field.to_string(), #transform_code);
                    }
                })
                .collect();

            if transform_insertions.is_empty() {
                quote! {
                    hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::AsCapture {
                        field_transforms: std::collections::BTreeMap::new(),
                    }
                }
            } else {
                quote! {
                    {
                        let mut field_transforms = std::collections::BTreeMap::new();
                        #(#transform_insertions)*
                        hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::AsCapture {
                            field_transforms,
                        }
                    }
                }
            }
        }
        MappingSource::FromContext { field } => {
            quote! {
                hyperstack::runtime::hyperstack_interpreter::ast::MappingSource::FromContext {
                    field: #field.to_string(),
                }
            }
        }
    }
}

/// Generate code for PopulationStrategy.
fn build_population_strategy_code(strategy: &PopulationStrategy) -> TokenStream {
    match strategy {
        PopulationStrategy::SetOnce => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::SetOnce }
        }
        PopulationStrategy::LastWrite => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::LastWrite }
        }
        PopulationStrategy::Append => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::Append }
        }
        PopulationStrategy::Merge => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::Merge }
        }
        PopulationStrategy::Max => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::Max }
        }
        PopulationStrategy::Sum => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::Sum }
        }
        PopulationStrategy::Count => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::Count }
        }
        PopulationStrategy::Min => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::Min }
        }
        PopulationStrategy::UniqueCount => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::PopulationStrategy::UniqueCount }
        }
    }
}

/// Generate code for Transformation.
fn build_transformation_code(transform: &Transformation) -> TokenStream {
    match transform {
        Transformation::HexEncode => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::Transformation::HexEncode }
        }
        Transformation::HexDecode => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::Transformation::HexDecode }
        }
        Transformation::Base58Encode => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::Transformation::Base58Encode }
        }
        Transformation::Base58Decode => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::Transformation::Base58Decode }
        }
        Transformation::ToString => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::Transformation::ToString }
        }
        Transformation::ToNumber => {
            quote! { hyperstack::runtime::hyperstack_interpreter::ast::Transformation::ToNumber }
        }
    }
}

/// Generate handlers from a list of handler specs.
///
/// This is a higher-level helper that generates all handler functions and their calls.
///
/// # Arguments
///
/// * `handlers` - List of handler specifications
/// * `entity_name` - The entity name (used for function naming)
/// * `state_name` - The state struct name
///
/// # Returns
///
/// A tuple of (handler_functions, handler_calls) where:
/// - handler_functions are the fn definitions
/// - handler_calls are the invocation expressions
pub fn generate_handlers_from_specs(
    handlers: &[SerializableHandlerSpec],
    entity_name: &str,
    state_name: &syn::Ident,
) -> (Vec<TokenStream>, Vec<TokenStream>) {
    let mut handler_fns = Vec::new();
    let mut handler_calls = Vec::new();

    for (i, handler) in handlers.iter().enumerate() {
        // Extract type name for handler naming
        let type_name = match &handler.source {
            SourceSpec::Source { type_name, .. } => type_name.clone(),
        };

        // Generate handler name from type
        let handler_suffix = crate::utils::to_snake_case(&type_name);
        let handler_name = format_ident!(
            "create_{}_{}_handler_{}",
            crate::utils::to_snake_case(entity_name),
            handler_suffix,
            i
        );

        let handler_fn = build_handler_fn(handler, &handler_name, state_name);
        handler_fns.push(handler_fn);
        handler_calls.push(quote! { #handler_name() });
    }

    (handler_fns, handler_calls)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_field_path_code() {
        let path = FieldPath::new(&["accounts", "mint"]);
        let code = build_field_path_code(&path);
        let code_str = code.to_string();
        assert!(code_str.contains("FieldPath"));
        assert!(code_str.contains("accounts"));
        assert!(code_str.contains("mint"));
    }

    #[test]
    fn test_build_population_strategy_code() {
        let strategy = PopulationStrategy::Sum;
        let code = build_population_strategy_code(&strategy);
        let code_str = code.to_string();
        assert!(code_str.contains("Sum"));
    }
}