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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! Concrete Syntax Parser
//!
//! Parses Rust-like pattern syntax with metavariables into `CodePattern`.
//!
//! # Syntax
//!
//! | Syntax | Meaning | Example |
//! |--------|---------|---------|
//! | `$VAR` | Capture single node | `$receiver.unwrap()` |
//! | `$_` | Match but don't capture | `foo($_, $second)` |
//! | `$...VAR` | Capture sequence (ellipsis) | `fn $name($...args)` |
//!
//! # Important
//!
//! Patterns must be **valid Rust syntax** after metavariable substitution.
//! For example, `match $x { $_ }` is invalid because match arms require `=> body`.
//!
//! # Examples
//!
//! ```ignore
//! use ryo_pattern::concrete::parse_pattern;
//!
//! // Parse a method call pattern
//! let pattern = parse_pattern("$receiver.unwrap()").unwrap();
//!
//! // Parse a macro call pattern
//! let pattern = parse_pattern("vec![$x]").unwrap();
//!
//! // Parse a match expression (requires complete arm syntax)
//! let pattern = parse_pattern("match $x { _ => $body }").unwrap();
//! ```

use crate::{CodePattern, NameMatcher, NodeKind, PatternExpr};
use std::collections::HashMap;
use thiserror::Error;

/// Errors that can occur during pattern parsing
#[derive(Debug, Error)]
pub enum ParseError {
    /// `syn` parse failure.
    #[error("Failed to parse pattern: {0}")]
    SynError(#[from] syn::Error),

    /// Syntax category that the concrete parser does not yet support.
    #[error("Unsupported syntax: {0}")]
    UnsupportedSyntax(String),

    /// Metavariable name is invalid (e.g. empty or malformed).
    #[error("Invalid metavariable: {0}")]
    InvalidMetavariable(String),
}

/// Result type for pattern parsing
pub type ParseResult<T> = Result<T, ParseError>;

/// Parse a concrete syntax pattern string into a CodePattern
pub fn parse_pattern(input: &str) -> ParseResult<CodePattern> {
    let parser = ConcreteParser::new();
    parser.parse(input)
}

/// Prefix for metavariable placeholders during parsing
const METAVAR_PREFIX: &str = "__mv_";
/// Prefix for ellipsis metavariable placeholders
const ELLIPSIS_PREFIX: &str = "__ell_";

/// Parser for concrete syntax patterns
pub struct ConcreteParser {
    // Reserved for future configuration
}

impl ConcreteParser {
    /// Construct a new `ConcreteParser`.
    pub fn new() -> Self {
        Self {}
    }

    /// Parse a pattern string into CodePattern
    pub fn parse(&self, input: &str) -> ParseResult<CodePattern> {
        // Preprocess: replace $...VAR and $VAR with valid Rust identifiers
        let preprocessed = self.preprocess(input);

        // Try to parse as expression first
        if let Ok(expr) = syn::parse_str::<syn::Expr>(&preprocessed) {
            return self.convert_expr(&expr);
        }

        // Try to parse as statement
        if let Ok(stmt) = syn::parse_str::<syn::Stmt>(&preprocessed) {
            return self.convert_stmt(&stmt);
        }

        // Try to parse as item
        if let Ok(item) = syn::parse_str::<syn::Item>(&preprocessed) {
            return self.convert_item(&item);
        }

        Err(ParseError::UnsupportedSyntax(format!(
            "Could not parse as expression, statement, or item: {}",
            input
        )))
    }

    /// Preprocess input to replace metavariables with valid Rust identifiers
    fn preprocess(&self, input: &str) -> String {
        let mut result = String::with_capacity(input.len() * 2);
        let mut chars = input.chars().peekable();

        while let Some(c) = chars.next() {
            if c == '$' {
                // Check for ellipsis pattern: $...VAR
                let mut is_ellipsis = false;
                let mut dots = String::new();

                while chars.peek() == Some(&'.') {
                    dots.push(chars.next().unwrap());
                }

                if dots.len() >= 3 {
                    is_ellipsis = true;
                } else {
                    // Not ellipsis, put dots back by adding to result
                    // Actually we can't put back, so we handle differently
                }

                // Collect the variable name
                let mut var_name = String::new();
                while let Some(&ch) = chars.peek() {
                    if ch.is_alphanumeric() || ch == '_' {
                        var_name.push(chars.next().unwrap());
                    } else {
                        break;
                    }
                }

                if is_ellipsis {
                    result.push_str(ELLIPSIS_PREFIX);
                    result.push_str(&var_name);
                } else if !var_name.is_empty() {
                    result.push_str(METAVAR_PREFIX);
                    result.push_str(&dots); // Include any dots that weren't 3+
                    result.push_str(&var_name);
                } else {
                    // Standalone $ or $. - keep as is (will likely fail parse)
                    result.push('$');
                    result.push_str(&dots);
                }
            } else {
                result.push(c);
            }
        }

        result
    }

    /// Convert a syn::Expr to CodePattern
    fn convert_expr(&self, expr: &syn::Expr) -> ParseResult<CodePattern> {
        match expr {
            syn::Expr::MethodCall(mc) => self.convert_method_call(mc),
            syn::Expr::Call(call) => self.convert_call(call),
            syn::Expr::Macro(mac) => self.convert_macro(mac),
            syn::Expr::Path(path) => self.convert_path(path),
            syn::Expr::If(if_expr) => self.convert_if(if_expr),
            syn::Expr::Match(match_expr) => self.convert_match(match_expr),
            syn::Expr::Block(block) => self.convert_block(block),
            syn::Expr::Binary(bin) => self.convert_binary(bin),
            syn::Expr::Unary(unary) => self.convert_unary(unary),
            syn::Expr::Lit(lit) => self.convert_literal(lit),
            syn::Expr::Try(try_expr) => self.convert_try(try_expr),
            syn::Expr::Return(ret) => self.convert_return(ret),
            syn::Expr::Await(await_expr) => self.convert_await(await_expr),
            syn::Expr::Closure(closure) => self.convert_closure(closure),
            _ => Err(ParseError::UnsupportedSyntax(
                "Unsupported expression type".to_string(),
            )),
        }
    }

    /// Convert a method call expression: $receiver.method($args)
    fn convert_method_call(&self, mc: &syn::ExprMethodCall) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::MethodCall);
        let mut children = HashMap::new();

        // Convert receiver
        if let Some(capture) = self.extract_metavar_from_expr(&mc.receiver) {
            children.insert(
                "receiver".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let receiver_pattern = self.convert_expr(&mc.receiver)?;
            children.insert(
                "receiver".to_string(),
                PatternExpr::Pattern(Box::new(receiver_pattern)),
            );
        }

        // Convert method name
        let method_name = mc.method.to_string();
        if is_metavariable(&method_name) {
            children.insert(
                "method".to_string(),
                PatternExpr::Capture(to_metavar_name(&method_name)),
            );
        } else {
            children.insert(
                "method".to_string(),
                PatternExpr::Name(NameMatcher::Exact(method_name)),
            );
        }

        // Convert arguments
        if !mc.args.is_empty() {
            let args_pattern = self.convert_args(&mc.args)?;
            children.insert("args".to_string(), args_pattern);
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert a function call expression: func($args)
    fn convert_call(&self, call: &syn::ExprCall) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::FunctionCall);
        let mut children = HashMap::new();

        // Convert function
        if let Some(capture) = self.extract_metavar_from_expr(&call.func) {
            children.insert(
                "func".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let func_pattern = self.convert_expr(&call.func)?;
            children.insert(
                "func".to_string(),
                PatternExpr::Pattern(Box::new(func_pattern)),
            );
        }

        // Convert arguments
        if !call.args.is_empty() {
            let args_pattern = self.convert_args(&call.args)?;
            children.insert("args".to_string(), args_pattern);
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert a macro call: macro!($...args)
    fn convert_macro(&self, mac: &syn::ExprMacro) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::MacroCall);
        let mut children = HashMap::new();

        // Get macro name
        let macro_name = mac
            .mac
            .path
            .segments
            .last()
            .map(|s| s.ident.to_string())
            .unwrap_or_default();

        children.insert(
            "name".to_string(),
            PatternExpr::Name(NameMatcher::Exact(macro_name)),
        );

        // Check if tokens contain ellipsis metavariable
        let tokens_str = mac.mac.tokens.to_string();
        if let Some(ellipsis_var) = extract_ellipsis_var(&tokens_str) {
            pattern.ellipsis = true;
            pattern.capture = Some(ellipsis_var);
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert a path expression (identifier or qualified path)
    fn convert_path(&self, path: &syn::ExprPath) -> ParseResult<CodePattern> {
        let path_str = path_to_string(&path.path);

        if is_metavariable(&path_str) {
            // This is a metavariable capture
            let mut pattern = CodePattern::new(NodeKind::Expr);
            pattern.capture = Some(to_metavar_name(&path_str));
            Ok(pattern)
        } else {
            let mut pattern = CodePattern::new(NodeKind::Path);
            pattern.children.insert(
                "path".to_string(),
                PatternExpr::Name(NameMatcher::Exact(path_str)),
            );
            Ok(pattern)
        }
    }

    /// Convert if expression
    fn convert_if(&self, if_expr: &syn::ExprIf) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::If);
        let mut children = HashMap::new();

        // Convert condition
        if let Some(capture) = self.extract_metavar_from_expr(&if_expr.cond) {
            children.insert(
                "condition".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let cond_pattern = self.convert_expr(&if_expr.cond)?;
            children.insert(
                "condition".to_string(),
                PatternExpr::Pattern(Box::new(cond_pattern)),
            );
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert match expression
    fn convert_match(&self, match_expr: &syn::ExprMatch) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::Match);
        let mut children = HashMap::new();

        // Convert scrutinee
        if let Some(capture) = self.extract_metavar_from_expr(&match_expr.expr) {
            children.insert(
                "scrutinee".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let scrutinee_pattern = self.convert_expr(&match_expr.expr)?;
            children.insert(
                "scrutinee".to_string(),
                PatternExpr::Pattern(Box::new(scrutinee_pattern)),
            );
        }

        // Add arm count if relevant
        children.insert(
            "arms_count".to_string(),
            PatternExpr::Literal(serde_json::json!(match_expr.arms.len())),
        );

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert block expression
    fn convert_block(&self, _block: &syn::ExprBlock) -> ParseResult<CodePattern> {
        let pattern = CodePattern::new(NodeKind::Block);
        // Block patterns typically use ellipsis for body
        Ok(pattern)
    }

    /// Convert binary expression
    fn convert_binary(&self, bin: &syn::ExprBinary) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::BinaryOp);
        let mut children = HashMap::new();

        // Convert left operand
        if let Some(capture) = self.extract_metavar_from_expr(&bin.left) {
            children.insert(
                "left".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let left_pattern = self.convert_expr(&bin.left)?;
            children.insert(
                "left".to_string(),
                PatternExpr::Pattern(Box::new(left_pattern)),
            );
        }

        // Convert operator
        let op_str = binop_to_string(&bin.op);
        children.insert(
            "op".to_string(),
            PatternExpr::Literal(serde_json::json!(op_str)),
        );

        // Convert right operand
        if let Some(capture) = self.extract_metavar_from_expr(&bin.right) {
            children.insert(
                "right".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let right_pattern = self.convert_expr(&bin.right)?;
            children.insert(
                "right".to_string(),
                PatternExpr::Pattern(Box::new(right_pattern)),
            );
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert unary expression
    fn convert_unary(&self, unary: &syn::ExprUnary) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::UnaryOp);
        let mut children = HashMap::new();

        // Convert operand
        if let Some(capture) = self.extract_metavar_from_expr(&unary.expr) {
            children.insert(
                "operand".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let operand_pattern = self.convert_expr(&unary.expr)?;
            children.insert(
                "operand".to_string(),
                PatternExpr::Pattern(Box::new(operand_pattern)),
            );
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert literal expression
    fn convert_literal(&self, lit: &syn::ExprLit) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::Literal);

        let value = match &lit.lit {
            syn::Lit::Str(s) => serde_json::json!(s.value()),
            syn::Lit::Int(i) => serde_json::json!(i.base10_parse::<i64>().unwrap_or(0)),
            syn::Lit::Float(f) => serde_json::json!(f.base10_parse::<f64>().unwrap_or(0.0)),
            syn::Lit::Bool(b) => serde_json::json!(b.value()),
            syn::Lit::Char(c) => serde_json::json!(c.value().to_string()),
            _ => serde_json::json!(null),
        };

        pattern
            .children
            .insert("value".to_string(), PatternExpr::Literal(value));
        Ok(pattern)
    }

    /// Convert try expression (?)
    fn convert_try(&self, try_expr: &syn::ExprTry) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::Try);
        let mut children = HashMap::new();

        if let Some(capture) = self.extract_metavar_from_expr(&try_expr.expr) {
            children.insert(
                "expr".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let expr_pattern = self.convert_expr(&try_expr.expr)?;
            children.insert(
                "expr".to_string(),
                PatternExpr::Pattern(Box::new(expr_pattern)),
            );
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert return expression
    fn convert_return(&self, ret: &syn::ExprReturn) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::Return);

        if let Some(expr) = &ret.expr {
            if let Some(capture) = self.extract_metavar_from_expr(expr) {
                pattern.children.insert(
                    "value".to_string(),
                    PatternExpr::Capture(to_metavar_name(&capture)),
                );
            } else {
                let expr_pattern = self.convert_expr(expr)?;
                pattern.children.insert(
                    "value".to_string(),
                    PatternExpr::Pattern(Box::new(expr_pattern)),
                );
            }
        }

        Ok(pattern)
    }

    /// Convert await expression
    fn convert_await(&self, await_expr: &syn::ExprAwait) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::Await);
        let mut children = HashMap::new();

        if let Some(capture) = self.extract_metavar_from_expr(&await_expr.base) {
            children.insert(
                "base".to_string(),
                PatternExpr::Capture(to_metavar_name(&capture)),
            );
        } else {
            let base_pattern = self.convert_expr(&await_expr.base)?;
            children.insert(
                "base".to_string(),
                PatternExpr::Pattern(Box::new(base_pattern)),
            );
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert closure expression
    fn convert_closure(&self, _closure: &syn::ExprClosure) -> ParseResult<CodePattern> {
        let pattern = CodePattern::new(NodeKind::Closure);
        // Closure patterns typically use ellipsis
        Ok(pattern)
    }

    /// Convert statement
    fn convert_stmt(&self, stmt: &syn::Stmt) -> ParseResult<CodePattern> {
        match stmt {
            syn::Stmt::Expr(expr, _) => self.convert_expr(expr),
            syn::Stmt::Local(local) => self.convert_local(local),
            _ => Err(ParseError::UnsupportedSyntax(
                "Unsupported statement type".to_string(),
            )),
        }
    }

    /// Convert local (let) statement
    fn convert_local(&self, local: &syn::Local) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::LetExpr);

        // Extract pattern
        if let syn::Pat::Ident(ident) = &local.pat {
            let name = ident.ident.to_string();
            if is_metavariable(&name) {
                pattern.children.insert(
                    "pattern".to_string(),
                    PatternExpr::Capture(to_metavar_name(&name)),
                );
            }
        }

        // Extract init expression
        if let Some(init) = &local.init {
            if let Some(capture) = self.extract_metavar_from_expr(&init.expr) {
                pattern.children.insert(
                    "init".to_string(),
                    PatternExpr::Capture(to_metavar_name(&capture)),
                );
            } else {
                let init_pattern = self.convert_expr(&init.expr)?;
                pattern.children.insert(
                    "init".to_string(),
                    PatternExpr::Pattern(Box::new(init_pattern)),
                );
            }
        }

        Ok(pattern)
    }

    /// Convert item (fn, struct, etc.)
    fn convert_item(&self, item: &syn::Item) -> ParseResult<CodePattern> {
        match item {
            syn::Item::Fn(func) => self.convert_fn(func),
            syn::Item::Struct(s) => self.convert_struct(s),
            _ => Err(ParseError::UnsupportedSyntax(
                "Unsupported item type".to_string(),
            )),
        }
    }

    /// Convert function item
    fn convert_fn(&self, func: &syn::ItemFn) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::Function);
        let mut children = HashMap::new();

        let name = func.sig.ident.to_string();
        if is_metavariable(&name) {
            children.insert(
                "name".to_string(),
                PatternExpr::Capture(to_metavar_name(&name)),
            );
        } else {
            children.insert(
                "name".to_string(),
                PatternExpr::Name(NameMatcher::Exact(name)),
            );
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert struct item
    fn convert_struct(&self, s: &syn::ItemStruct) -> ParseResult<CodePattern> {
        let mut pattern = CodePattern::new(NodeKind::Struct);
        let mut children = HashMap::new();

        let name = s.ident.to_string();
        if is_metavariable(&name) {
            children.insert(
                "name".to_string(),
                PatternExpr::Capture(to_metavar_name(&name)),
            );
        } else {
            children.insert(
                "name".to_string(),
                PatternExpr::Name(NameMatcher::Exact(name)),
            );
        }

        pattern.children = children;
        Ok(pattern)
    }

    /// Convert arguments list
    fn convert_args(
        &self,
        args: &syn::punctuated::Punctuated<syn::Expr, syn::token::Comma>,
    ) -> ParseResult<PatternExpr> {
        // Check for ellipsis pattern in any argument
        for arg in args {
            if let Some(ellipsis_var) = self.extract_ellipsis_from_expr(arg) {
                return Ok(PatternExpr::Capture(to_metavar_name(&ellipsis_var)));
            }
        }

        // Otherwise, create a list of patterns
        let mut arg_patterns = Vec::new();
        for arg in args {
            if let Some(capture) = self.extract_metavar_from_expr(arg) {
                arg_patterns.push(serde_json::json!({ "capture": to_metavar_name(&capture) }));
            } else {
                let pattern = self.convert_expr(arg)?;
                arg_patterns.push(serde_json::to_value(&pattern).unwrap_or_default());
            }
        }

        Ok(PatternExpr::Literal(serde_json::json!(arg_patterns)))
    }

    /// Extract metavariable from expression if it's a simple $VAR
    fn extract_metavar_from_expr(&self, expr: &syn::Expr) -> Option<String> {
        if let syn::Expr::Path(path) = expr {
            let path_str = path_to_string(&path.path);
            if is_metavariable(&path_str) {
                return Some(path_str);
            }
        }
        None
    }

    /// Extract ellipsis metavariable ($...VAR) from expression
    fn extract_ellipsis_from_expr(&self, expr: &syn::Expr) -> Option<String> {
        if let syn::Expr::Path(path) = expr {
            let path_str = path_to_string(&path.path);
            if is_ellipsis_metavariable(&path_str) {
                return Some(path_str);
            }
        }
        None
    }
}

impl Default for ConcreteParser {
    fn default() -> Self {
        Self::new()
    }
}

// ========== Helper Functions ==========

/// Check if a string is a metavariable (preprocessed form: __mv_VAR)
fn is_metavariable(s: &str) -> bool {
    s.starts_with(METAVAR_PREFIX) || s.starts_with(ELLIPSIS_PREFIX)
}

/// Check if a string is an ellipsis metavariable (__ell_VAR)
fn is_ellipsis_metavariable(s: &str) -> bool {
    s.starts_with(ELLIPSIS_PREFIX)
}

/// Convert preprocessed metavariable back to $VAR form
fn to_metavar_name(s: &str) -> String {
    if let Some(stripped) = s.strip_prefix(ELLIPSIS_PREFIX) {
        format!("$...{}", stripped)
    } else if let Some(stripped) = s.strip_prefix(METAVAR_PREFIX) {
        format!("${}", stripped)
    } else {
        s.to_string()
    }
}

/// Extract ellipsis variable from token string
fn extract_ellipsis_var(tokens: &str) -> Option<String> {
    // Look for __ell_VAR or __mv_VAR pattern in tokens
    let trimmed = tokens.trim();
    if trimmed.starts_with(ELLIPSIS_PREFIX) {
        Some(to_metavar_name(trimmed))
    } else if trimmed.starts_with(METAVAR_PREFIX) {
        // Single metavar in args, treat as ellipsis for macro args
        Some(to_metavar_name(trimmed))
    } else {
        None
    }
}

/// Convert syn::Path to string
fn path_to_string(path: &syn::Path) -> String {
    path.segments
        .iter()
        .map(|s| s.ident.to_string())
        .collect::<Vec<_>>()
        .join("::")
}

/// Convert binary operator to string
fn binop_to_string(op: &syn::BinOp) -> &'static str {
    match op {
        syn::BinOp::Add(_) => "+",
        syn::BinOp::Sub(_) => "-",
        syn::BinOp::Mul(_) => "*",
        syn::BinOp::Div(_) => "/",
        syn::BinOp::Rem(_) => "%",
        syn::BinOp::And(_) => "&&",
        syn::BinOp::Or(_) => "||",
        syn::BinOp::BitXor(_) => "^",
        syn::BinOp::BitAnd(_) => "&",
        syn::BinOp::BitOr(_) => "|",
        syn::BinOp::Shl(_) => "<<",
        syn::BinOp::Shr(_) => ">>",
        syn::BinOp::Eq(_) => "==",
        syn::BinOp::Lt(_) => "<",
        syn::BinOp::Le(_) => "<=",
        syn::BinOp::Ne(_) => "!=",
        syn::BinOp::Ge(_) => ">=",
        syn::BinOp::Gt(_) => ">",
        syn::BinOp::AddAssign(_) => "+=",
        syn::BinOp::SubAssign(_) => "-=",
        syn::BinOp::MulAssign(_) => "*=",
        syn::BinOp::DivAssign(_) => "/=",
        syn::BinOp::RemAssign(_) => "%=",
        syn::BinOp::BitXorAssign(_) => "^=",
        syn::BinOp::BitAndAssign(_) => "&=",
        syn::BinOp::BitOrAssign(_) => "|=",
        syn::BinOp::ShlAssign(_) => "<<=",
        syn::BinOp::ShrAssign(_) => ">>=",
        _ => "?",
    }
}

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

    #[test]
    fn test_preprocess() {
        let parser = ConcreteParser::new();

        // Simple metavariable
        assert_eq!(parser.preprocess("$var"), "__mv_var");
        assert_eq!(
            parser.preprocess("$receiver.unwrap()"),
            "__mv_receiver.unwrap()"
        );

        // Ellipsis
        assert_eq!(parser.preprocess("$...args"), "__ell_args");

        // Multiple
        assert_eq!(parser.preprocess("$a + $b"), "__mv_a + __mv_b");
    }

    #[test]
    fn test_parse_method_call() {
        let pattern = parse_pattern("$receiver.unwrap()").unwrap();
        assert_eq!(pattern.node, NodeKind::MethodCall);
        assert!(pattern.children.contains_key("receiver"));
        assert!(pattern.children.contains_key("method"));

        // Check that receiver is captured as $receiver
        if let Some(PatternExpr::Capture(name)) = pattern.children.get("receiver") {
            assert_eq!(name, "$receiver");
        } else {
            panic!("Expected receiver to be a capture");
        }
    }

    #[test]
    fn test_parse_method_call_with_args() {
        let pattern = parse_pattern("$receiver.expect($msg)").unwrap();
        assert_eq!(pattern.node, NodeKind::MethodCall);
        assert!(pattern.children.contains_key("args"));
    }

    #[test]
    fn test_parse_macro_call() {
        let pattern = parse_pattern("panic!($msg)").unwrap();
        assert_eq!(pattern.node, NodeKind::MacroCall);
        assert!(pattern.children.contains_key("name"));
    }

    #[test]
    fn test_parse_function_call() {
        let pattern = parse_pattern("foo($a, $b)").unwrap();
        assert_eq!(pattern.node, NodeKind::FunctionCall);
    }

    #[test]
    fn test_parse_binary_op() {
        let pattern = parse_pattern("$a + $b").unwrap();
        assert_eq!(pattern.node, NodeKind::BinaryOp);
        assert!(pattern.children.contains_key("left"));
        assert!(pattern.children.contains_key("right"));

        // Check captures
        if let Some(PatternExpr::Capture(name)) = pattern.children.get("left") {
            assert_eq!(name, "$a");
        }
        if let Some(PatternExpr::Capture(name)) = pattern.children.get("right") {
            assert_eq!(name, "$b");
        }
    }

    #[test]
    fn test_parse_if_expr() {
        let pattern = parse_pattern("if $cond { }").unwrap();
        assert_eq!(pattern.node, NodeKind::If);
        assert!(pattern.children.contains_key("condition"));
    }

    #[test]
    fn test_parse_try_expr() {
        let pattern = parse_pattern("$expr?").unwrap();
        assert_eq!(pattern.node, NodeKind::Try);
    }

    #[test]
    fn test_metavariable_detection() {
        // After preprocessing, metavars have __mv_ prefix
        assert!(is_metavariable("__mv_VAR"));
        assert!(is_metavariable("__mv_receiver"));
        assert!(is_metavariable("__ell_args"));
        assert!(!is_metavariable("var"));
    }

    #[test]
    fn test_ellipsis_detection() {
        assert!(is_ellipsis_metavariable("__ell_args"));
        assert!(!is_ellipsis_metavariable("__mv_args"));
    }

    #[test]
    fn test_to_metavar_name() {
        assert_eq!(to_metavar_name("__mv_receiver"), "$receiver");
        assert_eq!(to_metavar_name("__ell_args"), "$...args");
        assert_eq!(to_metavar_name("normal"), "normal");
    }

    #[test]
    fn test_parse_qualified_path() {
        let pattern = parse_pattern("Filter::Recurse").unwrap();
        assert_eq!(pattern.node, NodeKind::Path);
        // Should store path as Name(Exact(...)) under "path" key
        if let Some(PatternExpr::Name(NameMatcher::Exact(path))) = pattern.children.get("path") {
            assert_eq!(path, "Filter::Recurse");
        } else {
            panic!(
                "Expected Name(Exact(\"Filter::Recurse\")) under \"path\" key, got: {:?}",
                pattern.children
            );
        }
    }

    #[test]
    fn test_parse_simple_path() {
        let pattern = parse_pattern("foo").unwrap();
        assert_eq!(pattern.node, NodeKind::Path);
        if let Some(PatternExpr::Name(NameMatcher::Exact(path))) = pattern.children.get("path") {
            assert_eq!(path, "foo");
        } else {
            panic!("Expected Name(Exact(\"foo\")) under \"path\" key");
        }
    }
}