ryo-executor 0.1.0

[experimental] Mutation execution engine for RYO - parallel execution, conflict detection, workspace management
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! ASTRegApply implementation for struct literal field mutations
//!
//! V2 implementation that operates directly on ASTRegistry.
//! These mutations add/remove fields from struct literal expressions
//! (e.g., `Config { field: value }`) throughout the codebase.
//!
//! # Design Notes
//!
//! Unlike function-specific mutations (like AddMatchArm), these mutations
//! operate on ALL struct literals matching the target struct name across
//! the entire codebase. This requires walking all symbols in the registry.
//!
//! ## Self Resolution
//!
//! Inside impl blocks, `Self { ... }` must be correctly resolved to the
//! impl's target type. The `self_ty` parameter tracks this context.
//!
//! ## Future Improvements (TODO)
//!
//! - **Conflict detection**: Since this mutation affects ALL matching struct
//!   literals globally, conflict detection is difficult. Consider decomposing
//!   at Spec → Mutation conversion into individual symbol-targeted mutations.
//!
//! - **Granularity**: Current design is too coarse. Ideally:
//!   Spec (AddStructLiteralField)
//!   → Analyze (find all struct literals)
//!   → Decompose into individual Mutations with symbol_id
//!
//! - **Type-aware matching**: Currently matches by struct name string.
//!   Ideally would use type system for precise matching.
//!
//! - **Scope control**: Add ability to limit changes to specific files
//!   or modules rather than global changes.

use ryo_mutations::basic::{AddStructLiteralFieldMutation, RemoveStructLiteralFieldMutation};
use ryo_mutations::MutationResult;
use ryo_source::pure::macro_utils;
use ryo_source::pure::{PureBlock, PureExpr, PureImplItem, PureItem, PureStmt, ToSynError};

use crate::engine::{ASTMutationContext, ASTRegApply, ModificationType};

// ============================================================================
// ASTRegApply for AddStructLiteralFieldMutation
// ============================================================================

impl ASTRegApply for AddStructLiteralFieldMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Get struct name from registry via SymbolId
        let struct_name = ctx
            .symbol_registry
            .path(self.struct_id)
            .map(|p| p.name().to_string())
            .unwrap_or_else(|| format!("{:?}", self.struct_id));

        let mut total_changes = 0;

        // Collect all symbol IDs first to avoid borrow conflict
        let symbol_ids: Vec<_> = ctx.symbol_registry.iter().map(|(id, _)| id).collect();

        for id in symbol_ids {
            // Skip methods - they're handled via their parent Impl block
            if let Some(kind) = ctx.symbol_registry.kind(id) {
                if kind == ryo_symbol::SymbolKind::Method {
                    continue;
                }
            }

            let ast = match ctx.get_ast_mut(id) {
                Some(ast) => ast,
                None => continue,
            };

            let changes = match ast {
                PureItem::Fn(f) => match walk_and_add_field(
                    &mut f.body,
                    &struct_name,
                    &self.field_name,
                    &self.value,
                    None,
                ) {
                    Ok(c) => c,
                    Err(e) => {
                        return MutationResult {
                            mutation_type: "AddStructLiteralField".to_string(),
                            changes: 0,
                            description: format!("Failed to serialize macro tokens: {}", e),
                        };
                    }
                },
                PureItem::Impl(impl_block) => {
                    let self_ty = Some(impl_block.self_ty.as_str());
                    let mut count = 0;
                    for item in &mut impl_block.items {
                        if let PureImplItem::Fn(method) = item {
                            match walk_and_add_field(
                                &mut method.body,
                                &struct_name,
                                &self.field_name,
                                &self.value,
                                self_ty,
                            ) {
                                Ok(c) => count += c,
                                Err(e) => {
                                    return MutationResult {
                                        mutation_type: "AddStructLiteralField".to_string(),
                                        changes: 0,
                                        description: format!(
                                            "Failed to serialize macro tokens: {}",
                                            e
                                        ),
                                    };
                                }
                            }
                        }
                    }
                    count
                }
                _ => 0,
            };

            if changes > 0 {
                ctx.emit_modified(
                    id,
                    ModificationType::Other("StructLiteralFieldAdded".into()),
                );
                total_changes += changes;
            }
        }

        MutationResult {
            mutation_type: "AddStructLiteralField".to_string(),
            changes: total_changes,
            description: if total_changes > 0 {
                format!(
                    "Added field '{}' to {} struct literal(s) of '{}'",
                    self.field_name, total_changes, struct_name
                )
            } else {
                format!(
                    "No struct literals of '{}' found or field already exists",
                    struct_name
                )
            },
        }
    }
}

// ============================================================================
// ASTRegApply for RemoveStructLiteralFieldMutation
// ============================================================================

impl ASTRegApply for RemoveStructLiteralFieldMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Get struct name from registry via SymbolId
        let struct_name = ctx
            .symbol_registry
            .path(self.struct_id)
            .map(|p| p.name().to_string())
            .unwrap_or_else(|| format!("{:?}", self.struct_id));

        let mut total_changes = 0;

        // Collect all symbol IDs first to avoid borrow conflict
        let symbol_ids: Vec<_> = ctx.symbol_registry.iter().map(|(id, _)| id).collect();

        for id in symbol_ids {
            // Skip methods - they're handled via their parent Impl block
            if let Some(kind) = ctx.symbol_registry.kind(id) {
                if kind == ryo_symbol::SymbolKind::Method {
                    continue;
                }
            }

            let ast = match ctx.get_ast_mut(id) {
                Some(ast) => ast,
                None => continue,
            };

            let changes = match ast {
                PureItem::Fn(f) => {
                    match walk_and_remove_field(&mut f.body, &struct_name, &self.field_name, None) {
                        Ok(c) => c,
                        Err(e) => {
                            return MutationResult {
                                mutation_type: "RemoveStructLiteralField".to_string(),
                                changes: 0,
                                description: format!("Failed to serialize macro tokens: {}", e),
                            };
                        }
                    }
                }
                PureItem::Impl(impl_block) => {
                    let self_ty = Some(impl_block.self_ty.as_str());
                    let mut count = 0;
                    for item in &mut impl_block.items {
                        if let PureImplItem::Fn(method) = item {
                            match walk_and_remove_field(
                                &mut method.body,
                                &struct_name,
                                &self.field_name,
                                self_ty,
                            ) {
                                Ok(c) => count += c,
                                Err(e) => {
                                    return MutationResult {
                                        mutation_type: "RemoveStructLiteralField".to_string(),
                                        changes: 0,
                                        description: format!(
                                            "Failed to serialize macro tokens: {}",
                                            e
                                        ),
                                    };
                                }
                            }
                        }
                    }
                    count
                }
                _ => 0,
            };

            if changes > 0 {
                ctx.emit_modified(
                    id,
                    ModificationType::Other("StructLiteralFieldRemoved".into()),
                );
                total_changes += changes;
            }
        }

        MutationResult {
            mutation_type: "RemoveStructLiteralField".to_string(),
            changes: total_changes,
            description: if total_changes > 0 {
                format!(
                    "Removed field '{}' from {} struct literal(s) of '{}'",
                    self.field_name, total_changes, struct_name
                )
            } else {
                format!(
                    "No struct literals of '{}' with field '{}' found",
                    struct_name, self.field_name
                )
            },
        }
    }
}

// ============================================================================
// Helper functions
// ============================================================================

/// Check if path matches target struct name
fn matches_struct(path: &str, struct_name: &str, self_ty: Option<&str>) -> bool {
    // Direct match
    if path.ends_with(struct_name) || path == struct_name {
        return true;
    }
    // Match Self if we're in an impl block for target struct
    if path == "Self" {
        if let Some(ty) = self_ty {
            return ty.ends_with(struct_name) || ty == struct_name;
        }
    }
    false
}

/// Parse value string into PureExpr
fn parse_value(value: &str) -> PureExpr {
    let value = value.trim();

    // Handle None
    if value == "None" {
        return PureExpr::Path("None".to_string());
    }

    // Handle Some(...)
    if value.starts_with("Some(") && value.ends_with(')') {
        let inner = &value[5..value.len() - 1];
        return PureExpr::Call {
            func: Box::new(PureExpr::Path("Some".to_string())),
            args: vec![PureExpr::Other(inner.to_string())],
        };
    }

    // Handle Default::default()
    if value == "Default::default()" {
        return PureExpr::Call {
            func: Box::new(PureExpr::Path("Default::default".to_string())),
            args: vec![],
        };
    }

    // Handle numeric literals
    if value.parse::<i64>().is_ok() || value.parse::<f64>().is_ok() {
        return PureExpr::Lit(value.to_string());
    }

    // Default: treat as Other expression
    PureExpr::Other(value.to_string())
}

/// Walk block and add field to matching struct literals
fn walk_and_add_field(
    block: &mut PureBlock,
    struct_name: &str,
    field_name: &str,
    value: &str,
    self_ty: Option<&str>,
) -> Result<usize, ToSynError> {
    let mut count = 0;
    for stmt in &mut block.stmts {
        count += walk_stmt_and_add_field(stmt, struct_name, field_name, value, self_ty)?;
    }
    Ok(count)
}

/// Walk block and remove field from matching struct literals
fn walk_and_remove_field(
    block: &mut PureBlock,
    struct_name: &str,
    field_name: &str,
    self_ty: Option<&str>,
) -> Result<usize, ToSynError> {
    let mut count = 0;
    for stmt in &mut block.stmts {
        count += walk_stmt_and_remove_field(stmt, struct_name, field_name, self_ty)?;
    }
    Ok(count)
}

fn walk_stmt_and_add_field(
    stmt: &mut PureStmt,
    struct_name: &str,
    field_name: &str,
    value: &str,
    self_ty: Option<&str>,
) -> Result<usize, ToSynError> {
    match stmt {
        PureStmt::Local {
            init: Some(expr), ..
        } => {
            return walk_expr_and_add_field(expr, struct_name, field_name, value, self_ty);
        }
        PureStmt::Expr(expr) | PureStmt::Semi(expr) => {
            return walk_expr_and_add_field(expr, struct_name, field_name, value, self_ty);
        }
        _ => {}
    }
    Ok(0)
}

fn walk_stmt_and_remove_field(
    stmt: &mut PureStmt,
    struct_name: &str,
    field_name: &str,
    self_ty: Option<&str>,
) -> Result<usize, ToSynError> {
    match stmt {
        PureStmt::Local {
            init: Some(expr), ..
        } => {
            return walk_expr_and_remove_field(expr, struct_name, field_name, self_ty);
        }
        PureStmt::Expr(expr) | PureStmt::Semi(expr) => {
            return walk_expr_and_remove_field(expr, struct_name, field_name, self_ty);
        }
        _ => {}
    }
    Ok(0)
}

fn walk_expr_and_add_field(
    expr: &mut PureExpr,
    struct_name: &str,
    field_name: &str,
    value: &str,
    self_ty: Option<&str>,
) -> Result<usize, ToSynError> {
    let mut count = 0;

    // Check if this is a target struct literal
    if let PureExpr::Struct { path, fields } = expr {
        if matches_struct(path, struct_name, self_ty) {
            // Check if field already exists
            if !fields.iter().any(|(name, _)| name == field_name) {
                fields.push((field_name.to_string(), parse_value(value)));
                count += 1;
            }
        }
    }

    // Recursively walk children
    count += walk_expr_children_and_add_field(expr, struct_name, field_name, value, self_ty)?;
    Ok(count)
}

fn walk_expr_and_remove_field(
    expr: &mut PureExpr,
    struct_name: &str,
    field_name: &str,
    self_ty: Option<&str>,
) -> Result<usize, ToSynError> {
    let mut count = 0;

    // Check if this is a target struct literal
    if let PureExpr::Struct { path, fields } = expr {
        if matches_struct(path, struct_name, self_ty) {
            let original_len = fields.len();
            fields.retain(|(name, _)| name != field_name);
            if fields.len() < original_len {
                count += 1;
            }
        }
    }

    // Recursively walk children
    count += walk_expr_children_and_remove_field(expr, struct_name, field_name, self_ty)?;
    Ok(count)
}

fn walk_expr_children_and_add_field(
    expr: &mut PureExpr,
    struct_name: &str,
    field_name: &str,
    value: &str,
    self_ty: Option<&str>,
) -> Result<usize, ToSynError> {
    match expr {
        PureExpr::Block { block, .. } => {
            walk_and_add_field(block, struct_name, field_name, value, self_ty)
        }
        PureExpr::If {
            cond,
            then_branch,
            else_branch,
        } => {
            let mut count = walk_expr_and_add_field(cond, struct_name, field_name, value, self_ty)?;
            count += walk_and_add_field(then_branch, struct_name, field_name, value, self_ty)?;
            if let Some(else_expr) = else_branch {
                count +=
                    walk_expr_and_add_field(else_expr, struct_name, field_name, value, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Match { expr: e, arms } => {
            let mut count = walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)?;
            for arm in arms {
                count += walk_expr_and_add_field(
                    &mut arm.body,
                    struct_name,
                    field_name,
                    value,
                    self_ty,
                )?;
            }
            Ok(count)
        }
        PureExpr::Loop { body: block, .. } | PureExpr::Unsafe(block) => {
            walk_and_add_field(block, struct_name, field_name, value, self_ty)
        }
        PureExpr::While { cond, body, .. } => {
            Ok(
                walk_expr_and_add_field(cond, struct_name, field_name, value, self_ty)?
                    + walk_and_add_field(body, struct_name, field_name, value, self_ty)?,
            )
        }
        PureExpr::For { expr: e, body, .. } => {
            Ok(
                walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)?
                    + walk_and_add_field(body, struct_name, field_name, value, self_ty)?,
            )
        }
        PureExpr::Async { body, .. } => {
            walk_and_add_field(body, struct_name, field_name, value, self_ty)
        }
        PureExpr::Closure { body, .. } => {
            walk_expr_and_add_field(body, struct_name, field_name, value, self_ty)
        }
        PureExpr::Call { func, args } => {
            let mut count = walk_expr_and_add_field(func, struct_name, field_name, value, self_ty)?;
            for arg in args {
                count += walk_expr_and_add_field(arg, struct_name, field_name, value, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::MethodCall { receiver, args, .. } => {
            let mut count =
                walk_expr_and_add_field(receiver, struct_name, field_name, value, self_ty)?;
            for arg in args {
                count += walk_expr_and_add_field(arg, struct_name, field_name, value, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Binary { left, right, .. } => {
            Ok(
                walk_expr_and_add_field(left, struct_name, field_name, value, self_ty)?
                    + walk_expr_and_add_field(right, struct_name, field_name, value, self_ty)?,
            )
        }
        PureExpr::Unary { expr: e, .. }
        | PureExpr::Field { expr: e, .. }
        | PureExpr::Await(e)
        | PureExpr::Try(e) => walk_expr_and_add_field(e, struct_name, field_name, value, self_ty),
        PureExpr::Index { expr: e, index } => {
            Ok(
                walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)?
                    + walk_expr_and_add_field(index, struct_name, field_name, value, self_ty)?,
            )
        }
        PureExpr::Tuple(exprs) | PureExpr::Array(exprs) => {
            let mut count = 0;
            for e in exprs {
                count += walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Return(Some(e)) | PureExpr::Break { expr: Some(e), .. } => {
            walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)
        }
        PureExpr::Let { expr: e, .. }
        | PureExpr::Cast { expr: e, .. }
        | PureExpr::Ref { expr: e, .. } => {
            walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)
        }
        PureExpr::Struct { fields, .. } => {
            // Recurse into field values (struct already handled above)
            let mut count = 0;
            for (_, field_expr) in fields {
                count +=
                    walk_expr_and_add_field(field_expr, struct_name, field_name, value, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Range { start, end, .. } => {
            let mut count = 0;
            if let Some(s) = start {
                count += walk_expr_and_add_field(s, struct_name, field_name, value, self_ty)?;
            }
            if let Some(e) = end {
                count += walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Repeat { expr: e, len } => {
            Ok(
                walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)?
                    + walk_expr_and_add_field(len, struct_name, field_name, value, self_ty)?,
            )
        }
        PureExpr::Macro { name, tokens, .. } => {
            // Try to parse and walk expressions inside known macros (vec![], etc.)
            if let Some(mut exprs) = macro_utils::try_extract_exprs(name, tokens) {
                let mut count = 0;
                for e in &mut exprs {
                    count += walk_expr_and_add_field(e, struct_name, field_name, value, self_ty)?;
                }
                if count > 0 {
                    *tokens = macro_utils::exprs_to_tokens(&exprs)?;
                }
                Ok(count)
            } else {
                Ok(0)
            }
        }
        _ => Ok(0),
    }
}

fn walk_expr_children_and_remove_field(
    expr: &mut PureExpr,
    struct_name: &str,
    field_name: &str,
    self_ty: Option<&str>,
) -> Result<usize, ToSynError> {
    match expr {
        PureExpr::Block { block, .. } => {
            walk_and_remove_field(block, struct_name, field_name, self_ty)
        }
        PureExpr::If {
            cond,
            then_branch,
            else_branch,
        } => {
            let mut count = walk_expr_and_remove_field(cond, struct_name, field_name, self_ty)?;
            count += walk_and_remove_field(then_branch, struct_name, field_name, self_ty)?;
            if let Some(else_expr) = else_branch {
                count += walk_expr_and_remove_field(else_expr, struct_name, field_name, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Match { expr: e, arms } => {
            let mut count = walk_expr_and_remove_field(e, struct_name, field_name, self_ty)?;
            for arm in arms {
                count +=
                    walk_expr_and_remove_field(&mut arm.body, struct_name, field_name, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Loop { body: block, .. } | PureExpr::Unsafe(block) => {
            walk_and_remove_field(block, struct_name, field_name, self_ty)
        }
        PureExpr::While { cond, body, .. } => {
            Ok(
                walk_expr_and_remove_field(cond, struct_name, field_name, self_ty)?
                    + walk_and_remove_field(body, struct_name, field_name, self_ty)?,
            )
        }
        PureExpr::For { expr: e, body, .. } => {
            Ok(
                walk_expr_and_remove_field(e, struct_name, field_name, self_ty)?
                    + walk_and_remove_field(body, struct_name, field_name, self_ty)?,
            )
        }
        PureExpr::Async { body, .. } => {
            walk_and_remove_field(body, struct_name, field_name, self_ty)
        }
        PureExpr::Closure { body, .. } => {
            walk_expr_and_remove_field(body, struct_name, field_name, self_ty)
        }
        PureExpr::Call { func, args } => {
            let mut count = walk_expr_and_remove_field(func, struct_name, field_name, self_ty)?;
            for arg in args {
                count += walk_expr_and_remove_field(arg, struct_name, field_name, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::MethodCall { receiver, args, .. } => {
            let mut count = walk_expr_and_remove_field(receiver, struct_name, field_name, self_ty)?;
            for arg in args {
                count += walk_expr_and_remove_field(arg, struct_name, field_name, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Binary { left, right, .. } => {
            Ok(
                walk_expr_and_remove_field(left, struct_name, field_name, self_ty)?
                    + walk_expr_and_remove_field(right, struct_name, field_name, self_ty)?,
            )
        }
        PureExpr::Unary { expr: e, .. }
        | PureExpr::Field { expr: e, .. }
        | PureExpr::Await(e)
        | PureExpr::Try(e) => walk_expr_and_remove_field(e, struct_name, field_name, self_ty),
        PureExpr::Index { expr: e, index } => {
            Ok(
                walk_expr_and_remove_field(e, struct_name, field_name, self_ty)?
                    + walk_expr_and_remove_field(index, struct_name, field_name, self_ty)?,
            )
        }
        PureExpr::Tuple(exprs) | PureExpr::Array(exprs) => {
            let mut count = 0;
            for e in exprs {
                count += walk_expr_and_remove_field(e, struct_name, field_name, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Return(Some(e)) | PureExpr::Break { expr: Some(e), .. } => {
            walk_expr_and_remove_field(e, struct_name, field_name, self_ty)
        }
        PureExpr::Let { expr: e, .. }
        | PureExpr::Cast { expr: e, .. }
        | PureExpr::Ref { expr: e, .. } => {
            walk_expr_and_remove_field(e, struct_name, field_name, self_ty)
        }
        PureExpr::Struct { fields, .. } => {
            // Recurse into field values (struct already handled above)
            let mut count = 0;
            for (_, field_expr) in fields {
                count += walk_expr_and_remove_field(field_expr, struct_name, field_name, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Range { start, end, .. } => {
            let mut count = 0;
            if let Some(s) = start {
                count += walk_expr_and_remove_field(s, struct_name, field_name, self_ty)?;
            }
            if let Some(e) = end {
                count += walk_expr_and_remove_field(e, struct_name, field_name, self_ty)?;
            }
            Ok(count)
        }
        PureExpr::Repeat { expr: e, len } => {
            Ok(
                walk_expr_and_remove_field(e, struct_name, field_name, self_ty)?
                    + walk_expr_and_remove_field(len, struct_name, field_name, self_ty)?,
            )
        }
        PureExpr::Macro { name, tokens, .. } => {
            // Try to parse and walk expressions inside known macros (vec![], etc.)
            if let Some(mut exprs) = macro_utils::try_extract_exprs(name, tokens) {
                let mut count = 0;
                for e in &mut exprs {
                    count += walk_expr_and_remove_field(e, struct_name, field_name, self_ty)?;
                }
                if count > 0 {
                    *tokens = macro_utils::exprs_to_tokens(&exprs)?;
                }
                Ok(count)
            } else {
                Ok(0)
            }
        }
        _ => Ok(0),
    }
}