dampen-core 0.3.2

Core parser, IR, and traits for Dampen UI framework
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Binding expression inlining for code generation
//!
//! This module provides functions to generate pure Rust code from binding expressions,
//! eliminating runtime interpretation overhead in production builds.

use crate::CodegenError;
use crate::expr::ast::{
    BinaryOp, BinaryOpExpr, ConditionalExpr, Expr, FieldAccessExpr, LiteralExpr, MethodCallExpr,
    SharedFieldAccessExpr, UnaryOp, UnaryOpExpr,
};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};

/// Generate Rust code for a binding expression
///
/// This function converts binding expressions from the AST into TokenStream
/// for direct field access without runtime evaluation.
///
/// # Arguments
/// * `expr` - The expression to generate code for
///
/// # Returns
/// Generated code as a TokenStream that produces a String when interpolated
pub fn generate_expr(expr: &Expr) -> TokenStream {
    match expr {
        Expr::FieldAccess(field_access) => generate_field_access(field_access),
        Expr::SharedFieldAccess(shared_access) => generate_shared_field_access(shared_access),
        Expr::MethodCall(method_call) => generate_method_call(method_call),
        Expr::BinaryOp(binary_op) => generate_binary_op(binary_op),
        Expr::UnaryOp(unary_op) => generate_unary_op(unary_op),
        Expr::Conditional(conditional) => generate_conditional(conditional),
        Expr::Literal(literal) => generate_literal(literal),
    }
}

/// Generate Rust code for a boolean expression
///
/// This function is like generate_expr but produces native boolean values
/// instead of converting to String. Use for conditions like `enabled="{count > 0}"`.
///
/// # Arguments
/// * `expr` - The expression to generate code for
///
/// # Returns
/// Generated code as a TokenStream that produces a bool
pub fn generate_bool_expr(expr: &Expr) -> TokenStream {
    match expr {
        Expr::FieldAccess(field_access) => generate_field_access_raw(field_access),
        Expr::SharedFieldAccess(shared_access) => generate_shared_field_access_raw(shared_access),
        Expr::MethodCall(method_call) => generate_method_call_raw(method_call),
        Expr::BinaryOp(binary_op) => generate_binary_op_raw(binary_op),
        Expr::UnaryOp(unary_op) => generate_unary_op_raw(unary_op),
        Expr::Conditional(conditional) => generate_conditional_raw(conditional),
        Expr::Literal(literal) => generate_literal_raw(literal),
    }
}

/// Validate that an expression can be inlined
///
/// Returns Err if the expression contains unsupported constructs for codegen
pub fn validate_expression_inlinable(expr: &Expr) -> Result<(), CodegenError> {
    match expr {
        Expr::FieldAccess(_) => Ok(()),
        Expr::SharedFieldAccess(_) => Ok(()), // Shared field access is inlinable
        Expr::MethodCall(method_expr) => {
            validate_expression_inlinable(&method_expr.receiver)?;
            for arg in &method_expr.args {
                validate_expression_inlinable(arg)?;
            }
            Ok(())
        }
        Expr::BinaryOp(binary_expr) => {
            validate_expression_inlinable(&binary_expr.left)?;
            validate_expression_inlinable(&binary_expr.right)?;
            Ok(())
        }
        Expr::UnaryOp(unary_expr) => {
            validate_expression_inlinable(&unary_expr.operand)?;
            Ok(())
        }
        Expr::Conditional(cond_expr) => {
            validate_expression_inlinable(&cond_expr.condition)?;
            validate_expression_inlinable(&cond_expr.then_branch)?;
            validate_expression_inlinable(&cond_expr.else_branch)?;
            Ok(())
        }
        Expr::Literal(_) => Ok(()),
    }
}

/// Generate code for a field access expression
///
/// # Arguments
/// * `expr` - Field access with path components
///
/// # Returns
/// TokenStream generating `model.field.to_string()`
fn generate_field_access(expr: &FieldAccessExpr) -> TokenStream {
    if expr.path.is_empty() {
        return quote! { String::new() };
    }

    let field_access: Vec<_> = expr.path.iter().map(|s| format_ident!("{}", s)).collect();

    quote! { model.#(#field_access).*.to_string() }
}

/// Generate code for a shared field access expression
///
/// # Arguments
/// * `expr` - Shared field access with path components (after "shared.")
///
/// # Returns
/// TokenStream generating `shared.field.to_string()` where `shared` refers to
/// the shared context's read guard
fn generate_shared_field_access(expr: &SharedFieldAccessExpr) -> TokenStream {
    if expr.path.is_empty() {
        return quote! { String::new() };
    }

    // Generate access to the shared context
    // The generated code assumes a `shared` variable is in scope (the read guard)
    let field_access: Vec<_> = expr.path.iter().map(|s| format_ident!("{}", s)).collect();

    quote! { shared.#(#field_access).*.to_string() }
}

/// Generate code for a method call expression
///
/// # Arguments
/// * `expr` - Method call with receiver and arguments
///
/// # Returns
/// TokenStream generating `model.receiver.method(args).to_string()`
fn generate_method_call(expr: &MethodCallExpr) -> TokenStream {
    let receiver_tokens = generate_expr(&expr.receiver);
    let method_ident = format_ident!("{}", expr.method);

    if expr.args.is_empty() {
        quote! { #receiver_tokens.#method_ident().to_string() }
    } else {
        let arg_tokens: Vec<TokenStream> = expr.args.iter().map(generate_expr).collect();
        quote! { #receiver_tokens.#method_ident(#(#arg_tokens),*).to_string() }
    }
}

/// Generate code for a binary operation expression
///
/// # Arguments
/// * `expr` - Binary operation with left, op, right
///
/// # Returns
/// TokenStream generating `(left op right).to_string()`
fn generate_binary_op(expr: &BinaryOpExpr) -> TokenStream {
    let left = generate_expr(&expr.left);
    let right = generate_expr(&expr.right);
    let op = match expr.op {
        BinaryOp::Eq => quote! { == },
        BinaryOp::Ne => quote! { != },
        BinaryOp::Lt => quote! { < },
        BinaryOp::Le => quote! { <= },
        BinaryOp::Gt => quote! { > },
        BinaryOp::Ge => quote! { >= },
        BinaryOp::And => quote! { && },
        BinaryOp::Or => quote! { || },
        BinaryOp::Add => quote! { + },
        BinaryOp::Sub => quote! { - },
        BinaryOp::Mul => quote! { * },
        BinaryOp::Div => quote! { / },
    };

    quote! { (#left #op #right).to_string() }
}

/// Generate code for a unary operation expression
///
/// # Arguments
/// * `expr` - Unary operation with operator and operand
///
/// # Returns
/// TokenStream generating `(!operand).to_string()` or `(-operand).to_string()`
fn generate_unary_op(expr: &UnaryOpExpr) -> TokenStream {
    let operand = generate_expr(&expr.operand);
    let op = match expr.op {
        UnaryOp::Not => quote! { ! },
        UnaryOp::Neg => quote! { - },
    };

    quote! { (#op #operand).to_string() }
}

/// Generate code for a conditional expression
///
/// # Arguments
/// * `expr` - Conditional with condition, then_branch, else_branch
///
/// # Returns
/// TokenStream generating `if condition { then } else { else }.to_string()`
fn generate_conditional(expr: &ConditionalExpr) -> TokenStream {
    let condition = generate_expr(&expr.condition);
    let then_branch = generate_expr(&expr.then_branch);
    let else_branch = generate_expr(&expr.else_branch);

    quote! {
        {
            let __cond = #condition;
            let __then = #then_branch;
            let __else = #else_branch;
            if __cond.trim() == "true" || __cond.parse::<bool>().unwrap_or(false) {
                __then
            } else {
                __else
            }
        }
    }
}

/// Generate code for a literal expression
///
/// # Arguments
/// * `expr` - Literal value
///
/// # Returns
/// TokenStream generating the literal value as a string
fn generate_literal(expr: &LiteralExpr) -> TokenStream {
    match expr {
        LiteralExpr::String(s) => {
            let lit = proc_macro2::Literal::string(s);
            quote! { #lit.to_string() }
        }
        LiteralExpr::Integer(n) => {
            let lit = proc_macro2::Literal::i64_unsuffixed(*n);
            quote! { #lit.to_string() }
        }
        LiteralExpr::Float(f) => {
            let lit = proc_macro2::Literal::f64_unsuffixed(*f);
            quote! { #lit.to_string() }
        }
        LiteralExpr::Bool(b) => {
            let val = if *b { "true" } else { "false" };
            let lit = proc_macro2::Literal::string(val);
            quote! { #lit.to_string() }
        }
    }
}

/// Generate Rust code for interpolated strings
///
/// Converts interpolated strings like "Count: {count}" into format! macro calls.
///
/// # Arguments
/// * `parts` - Alternating literal strings and binding expressions
///
/// # Returns
/// TokenStream generating format! macro invocation
///
/// # Examples
/// ```ignore
/// // "Count: {count}"
/// generate_interpolated(...) -> quote! { format!("Count: {}", count) }
/// ```
pub fn generate_interpolated(parts: &[String]) -> TokenStream {
    if parts.is_empty() {
        return quote! { String::new() };
    }

    let mut format_args = Vec::new();
    let mut arg_exprs = Vec::new();

    for part in parts {
        if part.starts_with('{') && part.ends_with('}') {
            let binding_name = &part[1..part.len() - 1];
            let field_parts: Vec<_> = binding_name
                .split('.')
                .map(|s| format_ident!("{}", s))
                .collect();
            format_args.push("{}");
            arg_exprs.push(quote! { #(#field_parts).*.to_string() });
        } else {
            format_args.push(part);
        }
    }

    let format_string = format_args.join("");
    let lit = proc_macro2::Literal::string(&format_string);

    quote! { format!(#lit, #(#arg_exprs),*) }
}

// ============================================================================
// Raw value generation (without .to_string() conversion)
// Used for boolean expressions in conditions like enabled="{count > 0}"
// ============================================================================

/// Generate field access without .to_string() conversion
fn generate_field_access_raw(expr: &FieldAccessExpr) -> TokenStream {
    generate_field_access_raw_with_locals(expr, &std::collections::HashSet::new())
}

/// Generate field access with local variable context
fn generate_field_access_raw_with_locals(
    expr: &FieldAccessExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    if expr.path.is_empty() {
        return quote! { false };
    }

    // Check if the first element is a local variable
    if let Some(first) = expr.path.first()
        && local_vars.contains(first)
    {
        // Use the local variable directly without model. prefix
        let field_access: Vec<_> = expr.path.iter().map(|s| format_ident!("{}", s)).collect();
        return quote! { #(#field_access).* };
    }

    let field_access: Vec<_> = expr.path.iter().map(|s| format_ident!("{}", s)).collect();
    quote! { model.#(#field_access).* }
}

/// Generate bool expression with local variable context
pub fn generate_bool_expr_with_locals(
    expr: &Expr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    match expr {
        Expr::FieldAccess(field_access) => {
            generate_field_access_raw_with_locals(field_access, local_vars)
        }
        Expr::SharedFieldAccess(shared_access) => generate_shared_field_access_raw(shared_access),
        Expr::MethodCall(method_call) => {
            generate_method_call_raw_with_locals(method_call, local_vars)
        }
        Expr::BinaryOp(binary_op) => generate_binary_op_raw_with_locals(binary_op, local_vars),
        Expr::UnaryOp(unary_op) => generate_unary_op_raw_with_locals(unary_op, local_vars),
        Expr::Conditional(conditional) => {
            generate_conditional_raw_with_locals(conditional, local_vars)
        }
        Expr::Literal(literal) => generate_literal_raw(literal),
    }
}

/// Generate expr with local variable context (returns String)
pub fn generate_expr_with_locals(
    expr: &Expr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    match expr {
        Expr::FieldAccess(field_access) => {
            generate_field_access_with_locals(field_access, local_vars)
        }
        Expr::SharedFieldAccess(shared_access) => generate_shared_field_access(shared_access),
        Expr::MethodCall(method_call) => generate_method_call_with_locals(method_call, local_vars),
        Expr::BinaryOp(binary_op) => generate_binary_op_with_locals(binary_op, local_vars),
        Expr::UnaryOp(unary_op) => generate_unary_op_with_locals(unary_op, local_vars),
        Expr::Conditional(conditional) => generate_conditional_with_locals(conditional, local_vars),
        Expr::Literal(literal) => generate_literal(literal),
    }
}

/// Generate field access with local variable context (returns String)
fn generate_field_access_with_locals(
    expr: &FieldAccessExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    if expr.path.is_empty() {
        return quote! { String::new() };
    }

    // Check if the first element is a local variable
    if let Some(first) = expr.path.first()
        && local_vars.contains(first)
    {
        // Use the local variable directly without model. prefix
        let field_access: Vec<_> = expr.path.iter().map(|s| format_ident!("{}", s)).collect();
        return quote! { #(#field_access).*.to_string() };
    }

    let field_access: Vec<_> = expr.path.iter().map(|s| format_ident!("{}", s)).collect();
    quote! { model.#(#field_access).*.to_string() }
}

fn generate_method_call_with_locals(
    expr: &MethodCallExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    let receiver_tokens = generate_expr_with_locals(&expr.receiver, local_vars);
    let method_ident = format_ident!("{}", expr.method);
    let arg_tokens: Vec<_> = expr
        .args
        .iter()
        .map(|a| generate_expr_with_locals(a, local_vars))
        .collect();

    if arg_tokens.is_empty() {
        quote! { #receiver_tokens.#method_ident().to_string() }
    } else {
        quote! { #receiver_tokens.#method_ident(#(#arg_tokens),*).to_string() }
    }
}

fn generate_binary_op_with_locals(
    expr: &BinaryOpExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    let left = generate_expr_with_locals(&expr.left, local_vars);
    let right = generate_expr_with_locals(&expr.right, local_vars);
    let op = match expr.op {
        BinaryOp::Eq => quote! { == },
        BinaryOp::Ne => quote! { != },
        BinaryOp::Lt => quote! { < },
        BinaryOp::Le => quote! { <= },
        BinaryOp::Gt => quote! { > },
        BinaryOp::Ge => quote! { >= },
        BinaryOp::And => quote! { && },
        BinaryOp::Or => quote! { || },
        BinaryOp::Add => quote! { + },
        BinaryOp::Sub => quote! { - },
        BinaryOp::Mul => quote! { * },
        BinaryOp::Div => quote! { / },
    };

    quote! { (#left #op #right).to_string() }
}

fn generate_unary_op_with_locals(
    expr: &UnaryOpExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    let operand = generate_expr_with_locals(&expr.operand, local_vars);
    let op = match expr.op {
        UnaryOp::Not => quote! { ! },
        UnaryOp::Neg => quote! { - },
    };

    quote! { (#op #operand).to_string() }
}

fn generate_conditional_with_locals(
    expr: &ConditionalExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    let condition = generate_expr_with_locals(&expr.condition, local_vars);
    let then_branch = generate_expr_with_locals(&expr.then_branch, local_vars);
    let else_branch = generate_expr_with_locals(&expr.else_branch, local_vars);

    quote! {
        {
            let __cond = #condition;
            let __then = #then_branch;
            let __else = #else_branch;
            if __cond.trim() == "true" || __cond.parse::<bool>().unwrap_or(false) {
                __then
            } else {
                __else
            }
        }
    }
}

fn generate_method_call_raw_with_locals(
    expr: &MethodCallExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    let receiver_tokens = generate_bool_expr_with_locals(&expr.receiver, local_vars);
    let method_ident = format_ident!("{}", &expr.method);
    let arg_tokens: Vec<_> = expr
        .args
        .iter()
        .map(|a| generate_bool_expr_with_locals(a, local_vars))
        .collect();

    quote! { #receiver_tokens.#method_ident(#(#arg_tokens),*) }
}

fn generate_binary_op_raw_with_locals(
    expr: &BinaryOpExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    let left = generate_bool_expr_with_locals(&expr.left, local_vars);
    let right = generate_bool_expr_with_locals(&expr.right, local_vars);
    let op = match expr.op {
        BinaryOp::Eq => quote! { == },
        BinaryOp::Ne => quote! { != },
        BinaryOp::Lt => quote! { < },
        BinaryOp::Le => quote! { <= },
        BinaryOp::Gt => quote! { > },
        BinaryOp::Ge => quote! { >= },
        BinaryOp::And => quote! { && },
        BinaryOp::Or => quote! { || },
        BinaryOp::Add => quote! { + },
        BinaryOp::Sub => quote! { - },
        BinaryOp::Mul => quote! { * },
        BinaryOp::Div => quote! { / },
    };

    quote! { #left #op #right }
}

fn generate_unary_op_raw_with_locals(
    expr: &UnaryOpExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    let operand = generate_bool_expr_with_locals(&expr.operand, local_vars);
    let op = match expr.op {
        UnaryOp::Not => quote! { ! },
        UnaryOp::Neg => quote! { - },
    };

    quote! { #op #operand }
}

fn generate_conditional_raw_with_locals(
    expr: &ConditionalExpr,
    local_vars: &std::collections::HashSet<String>,
) -> TokenStream {
    let condition = generate_bool_expr_with_locals(&expr.condition, local_vars);
    let then_branch = generate_bool_expr_with_locals(&expr.then_branch, local_vars);
    let else_branch = generate_bool_expr_with_locals(&expr.else_branch, local_vars);

    quote! {
        if #condition {
            #then_branch
        } else {
            #else_branch
        }
    }
}

/// Generate shared field access without .to_string() conversion
fn generate_shared_field_access_raw(expr: &SharedFieldAccessExpr) -> TokenStream {
    if expr.path.is_empty() {
        return quote! { false };
    }

    let field_access: Vec<_> = expr.path.iter().map(|s| format_ident!("{}", s)).collect();
    quote! { shared.#(#field_access).* }
}

/// Generate method call without .to_string() conversion
fn generate_method_call_raw(expr: &MethodCallExpr) -> TokenStream {
    let receiver_tokens = generate_bool_expr(&expr.receiver);
    let method_ident = format_ident!("{}", &expr.method);
    let arg_tokens: Vec<_> = expr.args.iter().map(generate_bool_expr).collect();

    quote! { #receiver_tokens.#method_ident(#(#arg_tokens),*) }
}

/// Generate binary operation without .to_string() conversion
fn generate_binary_op_raw(expr: &BinaryOpExpr) -> TokenStream {
    let left = generate_bool_expr(&expr.left);
    let right = generate_bool_expr(&expr.right);
    let op = match expr.op {
        BinaryOp::Eq => quote! { == },
        BinaryOp::Ne => quote! { != },
        BinaryOp::Lt => quote! { < },
        BinaryOp::Le => quote! { <= },
        BinaryOp::Gt => quote! { > },
        BinaryOp::Ge => quote! { >= },
        BinaryOp::And => quote! { && },
        BinaryOp::Or => quote! { || },
        BinaryOp::Add => quote! { + },
        BinaryOp::Sub => quote! { - },
        BinaryOp::Mul => quote! { * },
        BinaryOp::Div => quote! { / },
    };

    quote! { #left #op #right }
}

/// Generate unary operation without .to_string() conversion
fn generate_unary_op_raw(expr: &UnaryOpExpr) -> TokenStream {
    let operand = generate_bool_expr(&expr.operand);
    let op = match expr.op {
        UnaryOp::Not => quote! { ! },
        UnaryOp::Neg => quote! { - },
    };

    quote! { #op #operand }
}

/// Generate conditional expression without .to_string() conversion
fn generate_conditional_raw(expr: &ConditionalExpr) -> TokenStream {
    let condition = generate_bool_expr(&expr.condition);
    let then_branch = generate_bool_expr(&expr.then_branch);
    let else_branch = generate_bool_expr(&expr.else_branch);

    quote! {
        if #condition {
            #then_branch
        } else {
            #else_branch
        }
    }
}

/// Generate literal without .to_string() conversion
fn generate_literal_raw(expr: &LiteralExpr) -> TokenStream {
    match expr {
        LiteralExpr::String(s) => {
            let lit = proc_macro2::Literal::string(s);
            quote! { #lit }
        }
        LiteralExpr::Integer(n) => {
            let lit = proc_macro2::Literal::i64_unsuffixed(*n);
            quote! { #lit }
        }
        LiteralExpr::Float(f) => {
            let lit = proc_macro2::Literal::f64_unsuffixed(*f);
            quote! { #lit }
        }
        LiteralExpr::Bool(b) => {
            quote! { #b }
        }
    }
}