ryo-pattern 0.1.0

RyoPattern - AST pattern matching and lint rules for Ryo
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! Pattern matcher for PureExpr
//!
//! Matches CodePattern against ryo-source's PureExpr AST nodes.

use crate::{
    ArmPattern, CapturedNode, CodePattern, MatchResult, NameMatcher, NodeKind, PatternExpr, Span,
};
use ryo_source::pure::{PureBlock, PureExpr, PureFn, PureMatchArm, PurePattern, PureStmt};
use std::collections::HashMap;

/// Matcher context for accumulating captures
#[derive(Debug, Default)]
pub struct MatchContext {
    /// Captured nodes during matching
    pub captures: HashMap<String, CapturedNode>,
}

impl MatchContext {
    /// Construct an empty `MatchContext`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a capture
    pub fn capture(&mut self, name: impl Into<String>, text: impl Into<String>) {
        let name = name.into();
        self.captures
            .insert(name, CapturedNode::new(Span::point(0, 0), text.into()));
    }

    /// Merge another context's captures
    pub fn merge(&mut self, other: MatchContext) {
        self.captures.extend(other.captures);
    }

    /// Convert to MatchResult
    pub fn into_match_result(self) -> MatchResult {
        let mut result = MatchResult::matched();
        result.captures = self.captures;
        result
    }
}

/// Pattern matcher for expressions
pub struct ExprMatcher<'p> {
    pattern: &'p CodePattern,
}

impl<'p> ExprMatcher<'p> {
    /// Construct a new `ExprMatcher` borrowing the given pattern.
    pub fn new(pattern: &'p CodePattern) -> Self {
        Self { pattern }
    }

    /// Match against a PureExpr
    pub fn matches(&self, expr: &PureExpr) -> Option<MatchContext> {
        let mut ctx = MatchContext::new();

        if self.match_expr(expr, &mut ctx) {
            // Add capture if pattern has capture variable
            if let Some(ref capture_name) = self.pattern.capture {
                ctx.capture(capture_name.clone(), expr_to_string(expr));
            }
            Some(ctx)
        } else {
            None
        }
    }

    /// Match expression against pattern
    fn match_expr(&self, expr: &PureExpr, ctx: &mut MatchContext) -> bool {
        match (&self.pattern.node, expr) {
            // MethodCall pattern
            (
                NodeKind::MethodCall,
                PureExpr::MethodCall {
                    receiver,
                    method,
                    args,
                    ..
                },
            ) => {
                // Check method name if specified
                if let Some(PatternExpr::Name(name_matcher)) = self.pattern.children.get("method") {
                    if !match_name(name_matcher, method) {
                        return false;
                    }
                }

                // Check receiver if specified
                if let Some(receiver_pattern) = self.pattern.children.get("receiver") {
                    if !self.match_pattern_expr(receiver_pattern, receiver, ctx) {
                        return false;
                    }
                }

                // Check args if specified
                if let Some(PatternExpr::Pattern(args_pattern)) = self.pattern.children.get("args")
                {
                    // TODO: Implement args matching
                    let _ = args_pattern;
                    let _ = args;
                }

                true
            }

            // FunctionCall pattern
            (NodeKind::FunctionCall, PureExpr::Call { func, args }) => {
                // Check function name if specified
                if let Some(func_pattern) = self.pattern.children.get("func") {
                    if !self.match_pattern_expr(func_pattern, func, ctx) {
                        return false;
                    }
                }
                let _ = args;
                true
            }

            // MacroCall pattern
            (NodeKind::MacroCall, PureExpr::Macro { name, .. }) => {
                // YAML uses "macro" key (e.g., `macro: "todo"`), not "name"
                if let Some(PatternExpr::Name(name_matcher)) = self.pattern.children.get("macro") {
                    if !match_name(name_matcher, name) {
                        return false;
                    }
                }
                true
            }

            // Try (?) pattern
            (NodeKind::Try, PureExpr::Try(expr)) => {
                if let Some(expr_pattern) = self.pattern.children.get("expr") {
                    if !self.match_pattern_expr(expr_pattern, expr, ctx) {
                        return false;
                    }
                }
                true
            }

            // Await pattern
            (NodeKind::Await, PureExpr::Await(expr)) => {
                if let Some(expr_pattern) = self.pattern.children.get("expr") {
                    if !self.match_pattern_expr(expr_pattern, expr, ctx) {
                        return false;
                    }
                }
                true
            }

            // BinaryOp pattern
            (NodeKind::BinaryOp, PureExpr::Binary { op, left, right }) => {
                if let Some(PatternExpr::Name(name_matcher)) = self.pattern.children.get("op") {
                    if !match_name(name_matcher, op) {
                        return false;
                    }
                }
                if let Some(left_pattern) = self.pattern.children.get("left") {
                    if !self.match_pattern_expr(left_pattern, left, ctx) {
                        return false;
                    }
                }
                if let Some(right_pattern) = self.pattern.children.get("right") {
                    if !self.match_pattern_expr(right_pattern, right, ctx) {
                        return false;
                    }
                }
                true
            }

            // Path pattern (variable/identifier)
            (NodeKind::Path, PureExpr::Path(path)) => {
                if let Some(PatternExpr::Name(name_matcher)) = self.pattern.children.get("path") {
                    if !match_name(name_matcher, path) {
                        return false;
                    }
                }
                true
            }

            // Literal pattern
            (NodeKind::Literal, PureExpr::Lit(lit)) => {
                if let Some(value_pattern) = self.pattern.children.get("value") {
                    match value_pattern {
                        PatternExpr::Literal(expected) => {
                            if let Some(expected_str) = expected.as_str() {
                                if lit != expected_str {
                                    return false;
                                }
                            }
                        }
                        // Handle case where YAML "value: true" is parsed as Name(Exact("true"))
                        // due to serde untagged enum ordering
                        PatternExpr::Name(NameMatcher::Exact(expected_str))
                            if lit != expected_str =>
                        {
                            return false;
                        }
                        _ => {}
                    }
                }
                true
            }

            // Generic Expr matches any expression
            (NodeKind::Expr, _) => true,

            // Block pattern
            (NodeKind::Block, PureExpr::Block { .. }) => true,

            // If pattern
            (
                NodeKind::If,
                PureExpr::If {
                    cond,
                    then_branch,
                    else_branch,
                },
            ) => {
                if let Some(cond_pattern) = self.pattern.children.get("cond") {
                    if !self.match_pattern_expr(cond_pattern, cond, ctx) {
                        return false;
                    }
                }
                let _ = (then_branch, else_branch);
                true
            }

            // Match pattern
            (NodeKind::Match, PureExpr::Match { expr, arms }) => {
                if let Some(expr_pattern) = self.pattern.children.get("expr") {
                    if !self.match_pattern_expr(expr_pattern, expr, ctx) {
                        return false;
                    }
                }
                // Check arm count
                if let Some(expected) = self.pattern.arm_count {
                    if arms.len() != expected {
                        return false;
                    }
                }
                // Check arm patterns (order-independent: each ArmPattern must match some arm)
                if let Some(arm_patterns) = &self.pattern.arms {
                    for ap in arm_patterns {
                        if !arms.iter().any(|arm| match_arm_pattern(ap, arm, ctx)) {
                            return false;
                        }
                    }
                }
                true
            }

            // Return pattern
            (NodeKind::Return, PureExpr::Return(maybe_expr)) => {
                if let Some(expr_pattern) = self.pattern.children.get("expr") {
                    if let Some(expr) = maybe_expr {
                        if !self.match_pattern_expr(expr_pattern, expr, ctx) {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
                true
            }

            // Loop pattern
            (NodeKind::Loop, PureExpr::Loop { .. }) => true,
            (NodeKind::Loop, PureExpr::While { .. }) => true,
            (NodeKind::Loop, PureExpr::For { .. }) => true,

            // Closure pattern
            (NodeKind::Closure, PureExpr::Closure { .. }) => true,

            // Index pattern (e.g., arr[i])
            (NodeKind::Index, PureExpr::Index { expr, index }) => {
                if let Some(expr_pattern) = self.pattern.children.get("expr") {
                    if !self.match_pattern_expr(expr_pattern, expr, ctx) {
                        return false;
                    }
                }
                if let Some(index_pattern) = self.pattern.children.get("index") {
                    if !self.match_pattern_expr(index_pattern, index, ctx) {
                        return false;
                    }
                }
                true
            }

            _ => false,
        }
    }

    /// Match a PatternExpr against a PureExpr
    fn match_pattern_expr(
        &self,
        pattern: &PatternExpr,
        expr: &PureExpr,
        ctx: &mut MatchContext,
    ) -> bool {
        match pattern {
            PatternExpr::Pattern(nested) => {
                let matcher = ExprMatcher::new(nested);
                if let Some(nested_ctx) = matcher.matches(expr) {
                    ctx.merge(nested_ctx);
                    true
                } else {
                    false
                }
            }
            PatternExpr::Capture(var_name) => {
                // Capture variable matches anything and stores the value
                ctx.capture(var_name.clone(), expr_to_string(expr));
                true
            }
            PatternExpr::Wildcard => true,
            PatternExpr::Name(name_matcher) => {
                if let PureExpr::Path(path) = expr {
                    match_name(name_matcher, path)
                } else {
                    false
                }
            }
            PatternExpr::Literal(expected) => {
                if let PureExpr::Lit(lit) = expr {
                    if let Some(expected_str) = expected.as_str() {
                        lit == expected_str
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
        }
    }
}

/// Match a name against a NameMatcher
fn match_name(matcher: &NameMatcher, name: &str) -> bool {
    match matcher {
        NameMatcher::Exact(expected) => name == expected,
        NameMatcher::Pattern(pattern) => {
            if let Some(ref prefix) = pattern.starts_with {
                if !name.starts_with(prefix) {
                    return false;
                }
            }
            if let Some(ref suffix) = pattern.ends_with {
                if !name.ends_with(suffix) {
                    return false;
                }
            }
            if let Some(ref substr) = pattern.contains {
                if !name.contains(substr) {
                    return false;
                }
            }
            if let Some(ref glob) = pattern.glob {
                if !match_glob(glob, name) {
                    return false;
                }
            }
            true
        }
    }
}

/// Simple glob matching (supports * wildcard)
fn match_glob(pattern: &str, name: &str) -> bool {
    if pattern == "*" {
        return true;
    }
    if let Some(prefix) = pattern.strip_suffix('*') {
        return name.starts_with(prefix);
    }
    if let Some(suffix) = pattern.strip_prefix('*') {
        return name.ends_with(suffix);
    }
    pattern == name
}

/// Check if a PureMatchArm matches an ArmPattern.
fn match_arm_pattern(ap: &ArmPattern, arm: &PureMatchArm, _ctx: &mut MatchContext) -> bool {
    // Check pattern_path: the arm's pattern must contain this path
    if let Some(ref expected_path) = ap.pattern_path {
        if !pattern_contains_path(&arm.pattern, expected_path) {
            return false;
        }
    }
    // Check body: the arm's body must match the CodePattern
    if let Some(ref body_pattern) = ap.body {
        let matcher = ExprMatcher::new(body_pattern);
        if matcher.matches(&arm.body).is_none() {
            return false;
        }
    }
    true
}

/// Check if a PurePattern contains a given path (e.g., "Some", "None").
fn pattern_contains_path(pat: &PurePattern, expected: &str) -> bool {
    match pat {
        PurePattern::Path(p) => p == expected || p.ends_with(&format!("::{}", expected)),
        PurePattern::Struct { path, .. } => {
            path == expected || path.ends_with(&format!("::{}", expected))
        }
        PurePattern::Ident { name, .. } => name == expected,
        PurePattern::Or(patterns) => patterns.iter().any(|p| pattern_contains_path(p, expected)),
        PurePattern::Ref { pattern, .. } => pattern_contains_path(pattern, expected),
        PurePattern::Tuple(patterns) => patterns.iter().any(|p| pattern_contains_path(p, expected)),
        _ => false,
    }
}

/// Convert PureExpr to string representation
pub fn expr_to_string(expr: &PureExpr) -> String {
    match expr {
        PureExpr::Lit(s) => s.clone(),
        PureExpr::Path(s) => s.clone(),
        PureExpr::MethodCall {
            receiver,
            method,
            args,
            turbofish,
        } => {
            let receiver_str = expr_to_string(receiver);
            let turbofish_str = turbofish
                .as_ref()
                .map(|t| format!("::{}", t))
                .unwrap_or_default();
            let args_str = args
                .iter()
                .map(expr_to_string)
                .collect::<Vec<_>>()
                .join(", ");
            format!("{}.{}{}({})", receiver_str, method, turbofish_str, args_str)
        }
        PureExpr::Call { func, args } => {
            let func_str = expr_to_string(func);
            let args_str = args
                .iter()
                .map(expr_to_string)
                .collect::<Vec<_>>()
                .join(", ");
            format!("{}({})", func_str, args_str)
        }
        PureExpr::Binary { op, left, right } => {
            format!("{} {} {}", expr_to_string(left), op, expr_to_string(right))
        }
        PureExpr::Unary { op, expr } => {
            format!("{}{}", op, expr_to_string(expr))
        }
        PureExpr::Try(expr) => {
            format!("{}?", expr_to_string(expr))
        }
        PureExpr::Await(expr) => {
            format!("{}.await", expr_to_string(expr))
        }
        PureExpr::Field { expr, field } => {
            format!("{}.{}", expr_to_string(expr), field)
        }
        PureExpr::Return(Some(e)) => format!("return {}", expr_to_string(e)),
        PureExpr::Return(None) => "return".to_string(),
        PureExpr::Block { .. } => "{ ... }".to_string(),
        PureExpr::If { .. } => "if ...".to_string(),
        PureExpr::Match { .. } => "match ...".to_string(),
        PureExpr::Closure { .. } => "|...| ...".to_string(),
        PureExpr::Tuple(items) => {
            let items_str = items
                .iter()
                .map(expr_to_string)
                .collect::<Vec<_>>()
                .join(", ");
            format!("({})", items_str)
        }
        PureExpr::Array(items) => {
            let items_str = items
                .iter()
                .map(expr_to_string)
                .collect::<Vec<_>>()
                .join(", ");
            format!("[{}]", items_str)
        }
        PureExpr::Macro { name, .. } => format!("{}!(...)", name),
        _ => "<expr>".to_string(),
    }
}

/// Scan a function body for pattern matches
pub struct BodyScanner<'p> {
    pattern: &'p CodePattern,
}

impl<'p> BodyScanner<'p> {
    /// Construct a new `BodyScanner` borrowing the given pattern.
    pub fn new(pattern: &'p CodePattern) -> Self {
        Self { pattern }
    }

    /// Scan a function and return all matches
    pub fn scan_fn(&self, func: &PureFn) -> Vec<MatchResult> {
        let mut results = Vec::new();
        self.scan_block(&func.body, &mut results);
        results
    }

    /// Scan a block for matches
    fn scan_block(&self, block: &PureBlock, results: &mut Vec<MatchResult>) {
        for stmt in &block.stmts {
            self.scan_stmt(stmt, results);
        }
    }

    /// Scan a statement for matches
    fn scan_stmt(&self, stmt: &PureStmt, results: &mut Vec<MatchResult>) {
        match stmt {
            PureStmt::Local {
                init: Some(expr), ..
            } => {
                self.scan_expr(expr, results);
            }
            PureStmt::Semi(expr) | PureStmt::Expr(expr) => {
                self.scan_expr(expr, results);
            }
            _ => {}
        }
    }

    /// Recursively scan an expression
    fn scan_expr(&self, expr: &PureExpr, results: &mut Vec<MatchResult>) {
        // Try to match current expression
        let matcher = ExprMatcher::new(self.pattern);
        if let Some(ctx) = matcher.matches(expr) {
            results.push(ctx.into_match_result());
        }

        // Recursively scan children
        match expr {
            PureExpr::MethodCall { receiver, args, .. } => {
                self.scan_expr(receiver, results);
                for arg in args {
                    self.scan_expr(arg, results);
                }
            }
            PureExpr::Call { func, args } => {
                self.scan_expr(func, results);
                for arg in args {
                    self.scan_expr(arg, results);
                }
            }
            PureExpr::Binary { left, right, .. } => {
                self.scan_expr(left, results);
                self.scan_expr(right, results);
            }
            PureExpr::Unary { expr, .. } => {
                self.scan_expr(expr, results);
            }
            PureExpr::Try(expr) => {
                self.scan_expr(expr, results);
            }
            PureExpr::Await(expr) => {
                self.scan_expr(expr, results);
            }
            PureExpr::Field { expr, .. } => {
                self.scan_expr(expr, results);
            }
            PureExpr::Index { expr, index } => {
                self.scan_expr(expr, results);
                self.scan_expr(index, results);
            }
            PureExpr::Block { block, .. } => {
                self.scan_block(block, results);
            }
            PureExpr::If {
                cond,
                then_branch,
                else_branch,
            } => {
                self.scan_expr(cond, results);
                self.scan_block(then_branch, results);
                if let Some(else_expr) = else_branch {
                    self.scan_expr(else_expr, results);
                }
            }
            PureExpr::Match { expr, arms } => {
                self.scan_expr(expr, results);
                for arm in arms {
                    self.scan_expr(&arm.body, results);
                }
            }
            PureExpr::Loop { body, .. } => {
                self.scan_block(body, results);
            }
            PureExpr::While { cond, body, .. } => {
                self.scan_expr(cond, results);
                self.scan_block(body, results);
            }
            PureExpr::For { expr, body, .. } => {
                self.scan_expr(expr, results);
                self.scan_block(body, results);
            }
            PureExpr::Return(Some(e)) => {
                self.scan_expr(e, results);
            }
            PureExpr::Break { expr: Some(e), .. } => {
                self.scan_expr(e, results);
            }
            PureExpr::Closure { body, .. } => {
                self.scan_expr(body, results);
            }
            PureExpr::Struct { fields, .. } => {
                for (_, field_expr) in fields {
                    self.scan_expr(field_expr, results);
                }
            }
            PureExpr::Tuple(items) | PureExpr::Array(items) => {
                for item in items {
                    self.scan_expr(item, results);
                }
            }
            _ => {}
        }
    }
}

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

    #[test]
    fn test_match_method_call() {
        let pattern = CodePattern::new(NodeKind::MethodCall).with_child(
            "method",
            PatternExpr::Name(NameMatcher::Exact("unwrap".into())),
        );

        let expr = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("result".into())),
            method: "unwrap".into(),
            turbofish: None,
            args: vec![],
        };

        let matcher = ExprMatcher::new(&pattern);
        assert!(matcher.matches(&expr).is_some());
    }

    #[test]
    fn test_no_match_different_method() {
        let pattern = CodePattern::new(NodeKind::MethodCall).with_child(
            "method",
            PatternExpr::Name(NameMatcher::Exact("unwrap".into())),
        );

        let expr = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("result".into())),
            method: "expect".into(),
            turbofish: None,
            args: vec![],
        };

        let matcher = ExprMatcher::new(&pattern);
        assert!(matcher.matches(&expr).is_none());
    }

    #[test]
    fn test_capture_receiver() {
        let pattern = CodePattern::new(NodeKind::MethodCall)
            .with_child(
                "method",
                PatternExpr::Name(NameMatcher::Exact("unwrap".into())),
            )
            .with_child("receiver", PatternExpr::Capture("$x".into()))
            .with_capture("$call");

        let expr = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("my_result".into())),
            method: "unwrap".into(),
            turbofish: None,
            args: vec![],
        };

        let matcher = ExprMatcher::new(&pattern);
        let ctx = matcher.matches(&expr).unwrap();

        assert!(ctx.captures.contains_key("$x"));
        assert!(ctx.captures.contains_key("$call"));
        assert_eq!(ctx.captures["$x"].text, "my_result");
    }

    #[test]
    fn test_glob_matching() {
        assert!(match_glob("get_*", "get_name"));
        assert!(match_glob("*_id", "user_id"));
        assert!(match_glob("*", "anything"));
        assert!(!match_glob("get_*", "set_name"));
    }

    #[test]
    fn test_literal_match_with_name_pattern() {
        // Test that PatternExpr::Name(Exact("true")) matches literal "true"
        // This is important because YAML `value: "true"` gets parsed as Name(Exact)
        // due to serde untagged enum ordering
        let pattern = CodePattern::new(NodeKind::Literal).with_child(
            "value",
            PatternExpr::Name(NameMatcher::Exact("true".into())),
        );

        // Should match literal "true"
        let expr_true = PureExpr::Lit("true".into());
        let matcher = ExprMatcher::new(&pattern);
        assert!(matcher.matches(&expr_true).is_some());

        // Should NOT match literal "false"
        let expr_false = PureExpr::Lit("false".into());
        assert!(matcher.matches(&expr_false).is_none());

        // Should NOT match literal "42"
        let expr_num = PureExpr::Lit("42".into());
        assert!(matcher.matches(&expr_num).is_none());
    }

    #[test]
    fn test_literal_match_with_literal_pattern() {
        // Test that PatternExpr::Literal also still works
        let pattern = CodePattern::new(NodeKind::Literal)
            .with_child("value", PatternExpr::Literal(serde_json::json!("true")));

        let expr_true = PureExpr::Lit("true".into());
        let matcher = ExprMatcher::new(&pattern);
        assert!(matcher.matches(&expr_true).is_some());

        let expr_false = PureExpr::Lit("false".into());
        assert!(matcher.matches(&expr_false).is_none());
    }

    #[test]
    fn test_macro_call_match() {
        // Test that MacroCall pattern uses "macro" key (as defined in YAML rules)
        let pattern = CodePattern::new(NodeKind::MacroCall).with_child(
            "macro",
            PatternExpr::Name(NameMatcher::Exact("todo".into())),
        );

        // Should match todo!()
        let expr_todo = PureExpr::Macro {
            name: "todo".into(),
            delimiter: MacroDelimiter::Paren,
            tokens: "".into(),
        };
        let matcher = ExprMatcher::new(&pattern);
        assert!(matcher.matches(&expr_todo).is_some());

        // Should NOT match println!()
        let expr_println = PureExpr::Macro {
            name: "println".into(),
            delimiter: MacroDelimiter::Paren,
            tokens: "".into(),
        };
        assert!(matcher.matches(&expr_println).is_none());

        // Should NOT match vec![]
        let expr_vec = PureExpr::Macro {
            name: "vec".into(),
            delimiter: MacroDelimiter::Bracket,
            tokens: "".into(),
        };
        assert!(matcher.matches(&expr_vec).is_none());
    }

    #[test]
    fn test_macro_call_no_filter_matches_all() {
        // MacroCall without "macro" child should match any macro
        let pattern = CodePattern::new(NodeKind::MacroCall);

        let expr_todo = PureExpr::Macro {
            name: "todo".into(),
            delimiter: MacroDelimiter::Paren,
            tokens: "".into(),
        };
        let matcher = ExprMatcher::new(&pattern);
        assert!(matcher.matches(&expr_todo).is_some());

        let expr_vec = PureExpr::Macro {
            name: "vec".into(),
            delimiter: MacroDelimiter::Bracket,
            tokens: "".into(),
        };
        assert!(matcher.matches(&expr_vec).is_some());
    }

    #[test]
    fn test_path_match_exact() {
        let pattern = CodePattern::new(NodeKind::Path).with_child(
            "path",
            PatternExpr::Name(NameMatcher::Exact("Filter::Recurse".into())),
        );

        let expr_match = PureExpr::Path("Filter::Recurse".into());
        let matcher = ExprMatcher::new(&pattern);
        assert!(matcher.matches(&expr_match).is_some());

        let expr_no_match = PureExpr::Path("Filter::Include".into());
        assert!(matcher.matches(&expr_no_match).is_none());

        let expr_unrelated = PureExpr::Path("something_else".into());
        assert!(matcher.matches(&expr_unrelated).is_none());
    }

    #[test]
    fn test_path_no_filter_matches_all() {
        // Path without "path" child should match any path
        let pattern = CodePattern::new(NodeKind::Path);

        let expr = PureExpr::Path("anything".into());
        let matcher = ExprMatcher::new(&pattern);
        assert!(matcher.matches(&expr).is_some());
    }
}