harn-rules 0.8.64

Declarative structural rule engine for Harn — rule model, pattern compiler, and matcher built on the harn-hostlib tree-sitter machinery.
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
//! The pattern compiler: a code snippet with metavariable holes → a
//! tree-sitter query.
//!
//! This is the atomic-tier `pattern` form. The idea (from ast-grep) is to
//! let rule authors write a *snippet of real code* with `$VAR` holes
//! instead of hand-authoring a tree-sitter S-expression query:
//!
//! ```text
//!   $SRC?.$KEY ?? $DEFAULT
//! ```
//!
//! compiles to
//!
//! ```text
//!   ((binary_expression
//!      left: (member_expression object: (_) @SRC (optional_chain) property: (_) @KEY)
//!      "??"
//!      right: (_) @DEFAULT) @__match)
//! ```
//!
//! ## How it works
//!
//! 1. Each `$VAR` is replaced with a unique placeholder identifier so the
//!    snippet parses as ordinary code in the target grammar.
//! 2. We parse the substituted snippet — bare, then in a per-language
//!    wrapper context (e.g. a function body) when the fragment is not a
//!    valid compilation unit — and locate the snippet's own subtree by its
//!    byte range in the parsed source.
//! 3. We walk that subtree and mirror it into a query: every named child is
//!    emitted with its field name, every anonymous token (operators,
//!    keywords, punctuation) is emitted as a quoted literal so the structure
//!    is matched precisely, and every placeholder becomes a `(_) @VAR`
//!    wildcard capture.
//! 4. Repeated metavariables unify: the second and later occurrences get
//!    helper captures plus an `(#eq? …)` predicate so `$X$X` only matches
//!    when both holes carry identical text.
//!
//! ## Typed placeholders (`$VAR:kind`, #2839)
//!
//! A metavariable may carry a **syntactic-class constraint** so it matches
//! only nodes of a given kind (rust-analyzer SSR `$x:expr`):
//!
//! ```text
//!   $FN($ARG:identifier)   // matches `f(x)`, not `f(g())`
//!   $X:expression          // matches any expression-position node
//! ```
//!
//! `:kind` is either a small **semantic alias** (`expr`/`expression`,
//! `stmt`/`statement`, `ty`/`type`, `ident`/`identifier`) resolved to the
//! grammar's supertype, or an **exact tree-sitter node kind**. The constraint
//! lowers a `(_) @VAR` wildcard to `(kind) @VAR`, so it narrows what binds.
//! A constraint that names no kind in the target grammar is a compile error
//! (the alias supertypes exist only in some grammars — e.g. `expression` in
//! TypeScript/JS/Python but not Rust/Go, where exact kinds are used instead).
//!
//! Variadic `$$$` holes are not yet supported (tracked for the relational
//! tier, #2833); they compile to a clear error.

use std::collections::HashMap;

use harn_hostlib::ast::{api, Language};
use tree_sitter::Node;

/// The capture name bound to the whole matched pattern, used for range
/// extraction. Chosen to not collide with a user metavar (which are
/// uppercase by convention and never start with `__`).
pub const ROOT_CAPTURE: &str = "__match";

/// Placeholder identifier stem substituted for each `$VAR`. Lowercase +
/// `__` prefix keeps it a valid identifier across grammars and unlikely to
/// collide with real snippet text.
const PLACEHOLDER_STEM: &str = "__harn_hole_";

/// A snippet pattern compiled to a tree-sitter query string.
#[derive(Debug, Clone)]
pub struct CompiledPattern {
    /// The generated S-expression query. Always binds the pattern root to
    /// `@__match` ([`ROOT_CAPTURE`]).
    pub query: String,
    /// Metavar names in first-appearance order (without the leading `$`).
    pub metavars: Vec<String>,
}

/// Compile a `pattern` snippet for `language` into a tree-sitter query.
///
/// A snippet is often a *fragment* (`a + a`, `foo(bar)`) that is not a
/// valid compilation unit on its own. We therefore try the snippet bare
/// first (works for expression-statement languages like TS/JS/Python),
/// then in a small set of per-language wrapper contexts (e.g. a function
/// body for Rust/Go), and locate the snippet's own subtree by byte range.
pub fn compile_pattern(snippet: &str, language: Language) -> Result<CompiledPattern, String> {
    let sub = substitute(snippet)?;

    // Resolve each `$VAR:kind` constraint to its query node-pattern once,
    // against the target grammar (so an invalid kind errors clearly here
    // rather than as an opaque query-compile failure later).
    let mut metavar_node_patterns: HashMap<String, String> = HashMap::new();
    for (metavar, constraint) in &sub.metavar_constraints {
        metavar_node_patterns.insert(metavar.clone(), resolve_constraint(constraint, language)?);
    }

    let mut last_err: Option<String> = None;

    for (prefix, suffix) in contexts(language) {
        let wrapped = format!("{prefix}{}{suffix}", sub.text);
        let tree = api::parse_tree(&wrapped, language).map_err(|err| err.to_string())?;
        let root = tree.root_node();
        if root.has_error() {
            last_err = Some(format!(
                "snippet did not parse cleanly in `{}`: `{snippet}`",
                language.name()
            ));
            continue;
        }

        // The snippet occupies `[start, end)` inside the wrapped source; the
        // deepest node spanning that range is its own subtree (no need to
        // descend wrappers — and no risk of over-descending a single-child
        // node like a unary expression).
        let start = prefix.len();
        let end = start + sub.text.len();
        let Some(pattern_root) = root.descendant_for_byte_range(start, end.saturating_sub(1))
        else {
            last_err = Some(format!(
                "could not locate snippet subtree in `{}`",
                language.name()
            ));
            continue;
        };

        let bytes = wrapped.as_bytes();
        let mut builder =
            QueryBuilder::new(bytes, &sub.placeholder_to_metavar, &metavar_node_patterns);
        let body = builder.build(pattern_root);
        let predicates = builder.predicates();
        let query = if predicates.is_empty() {
            format!("({body} @{ROOT_CAPTURE})")
        } else {
            format!("({body} @{ROOT_CAPTURE} {predicates})")
        };
        return Ok(CompiledPattern {
            query,
            metavars: sub.metavar_order,
        });
    }

    Err(last_err.unwrap_or_else(|| format!("snippet did not parse in `{}`", language.name())))
}

/// Candidate parse contexts for a snippet, tried in order. The bare context
/// (`""`, `""`) comes first; item-required languages add a wrapper that
/// makes an expression/statement fragment parse. Languages whose top level
/// already accepts expression statements (TS/JS/Python/Ruby/…) only need
/// the bare context.
fn contexts(language: Language) -> Vec<(&'static str, &'static str)> {
    let mut v = vec![("", "")];
    let wrapper = match language {
        Language::Rust => Some(("fn __harn_probe() { ", " }")),
        Language::Go => Some(("package p\nfunc __harn_probe() { ", " }")),
        Language::Java | Language::CSharp => {
            Some(("class __HarnProbe { void __harn_probe() { ", " } }"))
        }
        Language::C | Language::Cpp => Some(("void __harn_probe() { ", " }")),
        Language::Kotlin => Some(("fun __harn_probe() { ", " }")),
        Language::Swift => Some(("func __harn_probe() { ", " }")),
        Language::Scala => Some(("def __harn_probe() = { ", " }")),
        _ => None,
    };
    v.extend(wrapper);
    v
}

// ---------------------------------------------------------------------------
// Step 1: metavar substitution
// ---------------------------------------------------------------------------

struct Substituted {
    /// Snippet with `$VAR` replaced by placeholder identifiers.
    text: String,
    /// placeholder identifier → metavar name.
    placeholder_to_metavar: HashMap<String, String>,
    /// Metavar names in first-appearance order.
    metavar_order: Vec<String>,
    /// metavar name → its `:kind` constraint (raw, before grammar
    /// resolution), for metavars written `$VAR:kind`.
    metavar_constraints: HashMap<String, String>,
}

fn substitute(snippet: &str) -> Result<Substituted, String> {
    let mut text = String::with_capacity(snippet.len());
    let mut placeholder_to_metavar = HashMap::new();
    let mut metavar_to_placeholder: HashMap<String, String> = HashMap::new();
    let mut metavar_order: Vec<String> = Vec::new();
    let mut metavar_constraints: HashMap<String, String> = HashMap::new();

    let bytes = snippet.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'$' {
            // Copy this UTF-8 scalar verbatim. Indexing the &str at byte
            // boundaries is safe because we only special-case ASCII `$`.
            let ch = snippet[i..].chars().next().unwrap();
            text.push(ch);
            i += ch.len_utf8();
            continue;
        }
        if snippet[i..].starts_with("$$$") {
            return Err(
                "variadic `$$$` metavariables are not yet supported (tracked in #2833)".into(),
            );
        }
        // Parse `$NAME` where NAME is `[A-Za-z_][A-Za-z0-9_]*`.
        let name_start = i + 1;
        let mut j = name_start;
        if j < bytes.len() && is_ident_start(bytes[j]) {
            j += 1;
            while j < bytes.len() && is_ident_continue(bytes[j]) {
                j += 1;
            }
        }
        if j == name_start {
            // A lone `$` that is not a metavar — keep it literal.
            text.push('$');
            i += 1;
            continue;
        }
        let name = &snippet[name_start..j];
        // Optional `:kind` syntactic-class constraint (`$X:expression`). It is
        // a constraint only when `:` is immediately followed by an identifier,
        // so `$X: $T` (a typed binding, space after `:`) and `$X::foo` (a Rust
        // path) are left as literal snippet text.
        let mut consumed_end = j;
        if j < bytes.len() && bytes[j] == b':' {
            let kind_start = j + 1;
            if kind_start < bytes.len() && is_ident_start(bytes[kind_start]) {
                let mut k = kind_start + 1;
                while k < bytes.len() && is_ident_continue(bytes[k]) {
                    k += 1;
                }
                let constraint = &snippet[kind_start..k];
                match metavar_constraints.get(name) {
                    Some(existing) if existing != constraint => {
                        return Err(format!(
                            "metavariable `${name}` has conflicting type constraints \
                             `:{existing}` and `:{constraint}`"
                        ));
                    }
                    _ => {
                        metavar_constraints.insert(name.to_string(), constraint.to_string());
                    }
                }
                consumed_end = k;
            }
        }
        let placeholder = metavar_to_placeholder
            .entry(name.to_string())
            .or_insert_with(|| {
                let placeholder = format!("{PLACEHOLDER_STEM}{}", metavar_order.len());
                metavar_order.push(name.to_string());
                placeholder
            })
            .clone();
        placeholder_to_metavar.insert(placeholder.clone(), name.to_string());
        text.push_str(&placeholder);
        i = consumed_end;
    }

    // A pattern with no metavars is a valid *literal* pattern (it matches a
    // fixed structure), so we do not require one.

    Ok(Substituted {
        text,
        placeholder_to_metavar,
        metavar_order,
        metavar_constraints,
    })
}

/// Resolve a `$VAR:kind` constraint against the target grammar into the
/// node-pattern atom the query uses in place of the `(_)` wildcard — `(kind)`
/// for one kind, `[(k1) (k2)]` for an alias that maps to several. Errors when
/// the constraint names no node kind in this grammar.
fn resolve_constraint(constraint: &str, language: Language) -> Result<String, String> {
    let ts = language
        .ts_language()
        .ok_or_else(|| format!("no grammar for `{}`", language.name()))?;
    // A small set of cross-grammar semantic aliases map to the grammar's
    // supertype; anything else is treated as an exact tree-sitter kind.
    let candidates: Vec<&str> = match constraint {
        "expr" | "expression" => vec!["expression"],
        "stmt" | "statement" => vec!["statement"],
        "ty" | "type" => vec!["type"],
        "ident" | "identifier" => vec!["identifier"],
        other => vec![other],
    };
    let valid: Vec<String> = candidates
        .iter()
        .filter(|kind| ts.id_for_node_kind(kind, true) != 0)
        .map(|kind| format!("({kind})"))
        .collect();
    if valid.is_empty() {
        return Err(format!(
            "typed placeholder `:{constraint}` is not a node kind in `{}` \
             (use an exact tree-sitter kind)",
            language.name()
        ));
    }
    Ok(if valid.len() == 1 {
        valid.into_iter().next().unwrap()
    } else {
        format!("[{}]", valid.join(" "))
    })
}

fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == b'_'
}

fn is_ident_continue(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

// ---------------------------------------------------------------------------
// Step 2: walk the located subtree into a query
// ---------------------------------------------------------------------------

struct QueryBuilder<'a> {
    src: &'a [u8],
    placeholder_to_metavar: &'a HashMap<String, String>,
    /// metavar name → resolved node-pattern atom (`(kind)` / `[(a) (b)]`) for
    /// typed `$VAR:kind` placeholders. Absent metavars use the `(_)` wildcard.
    metavar_node_patterns: &'a HashMap<String, String>,
    /// occurrence count per metavar, to mint unification helper captures.
    occurrences: HashMap<String, usize>,
    /// `(#eq? …)` predicates for repeated metavars and literal leaves.
    eq_predicates: Vec<String>,
    /// counter for literal-leaf text-constraint captures.
    literal_count: usize,
}

impl<'a> QueryBuilder<'a> {
    fn new(
        src: &'a [u8],
        placeholder_to_metavar: &'a HashMap<String, String>,
        metavar_node_patterns: &'a HashMap<String, String>,
    ) -> Self {
        QueryBuilder {
            src,
            placeholder_to_metavar,
            metavar_node_patterns,
            occurrences: HashMap::new(),
            eq_predicates: Vec::new(),
            literal_count: 0,
        }
    }

    fn build(&mut self, node: Node<'_>) -> String {
        // A placeholder leaf is a metavar hole.
        if node.child_count() == 0 {
            let text = self.node_text(node);
            if let Some(metavar) = self.placeholder_to_metavar.get(text) {
                let node_pattern = self
                    .metavar_node_patterns
                    .get(metavar)
                    .map(String::as_str)
                    .unwrap_or("(_)");
                return format!("{node_pattern} @{}", self.capture_for(metavar));
            }
            if node.is_named() {
                // A literal named leaf (a specific identifier / literal in
                // the snippet): constrain it to its exact text so `foo()`
                // matches calls to `foo`, not any call.
                let cap = format!("__lit_{}", self.literal_count);
                self.literal_count += 1;
                self.eq_predicates
                    .push(format!("(#eq? @{cap} {})", quote_literal(text)));
                return format!("({}) @{cap}", node.kind());
            }
            return quote_literal(text);
        }

        let mut parts: Vec<String> = Vec::new();
        let mut cursor = node.walk();
        for (i, child) in node.children(&mut cursor).enumerate() {
            let sub = self.build(child);
            // Field names only attach to named children; an anonymous token
            // in a field slot is matched positionally as a literal, which
            // tree-sitter accepts where `field: "literal"` may not.
            match node.field_name_for_child(i as u32) {
                Some(field) if child.is_named() => parts.push(format!("{field}: {sub}")),
                _ => parts.push(sub),
            }
        }
        format!("({} {})", node.kind(), parts.join(" "))
    }

    /// Mint the capture name for this occurrence of `metavar`. The first
    /// occurrence is `@NAME`; later ones are `@NAME.k` plus an `(#eq? …)`
    /// predicate tying them to the first (metavar unification).
    fn capture_for(&mut self, metavar: &str) -> String {
        let count = self.occurrences.entry(metavar.to_string()).or_insert(0);
        *count += 1;
        if *count == 1 {
            metavar.to_string()
        } else {
            let helper = format!("{metavar}.{count}");
            self.eq_predicates
                .push(format!("(#eq? @{metavar} @{helper})"));
            helper
        }
    }

    fn predicates(&self) -> String {
        self.eq_predicates.join(" ")
    }

    fn node_text(&self, node: Node<'_>) -> &'a str {
        std::str::from_utf8(&self.src[node.start_byte()..node.end_byte()]).unwrap_or_default()
    }
}

/// Quote an anonymous token as a tree-sitter query literal, escaping `"`
/// and `\`.
fn quote_literal(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for ch in text.chars() {
        if ch == '"' || ch == '\\' {
            out.push('\\');
        }
        out.push(ch);
    }
    out.push('"');
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use streaming_iterator::StreamingIterator;
    use tree_sitter::{Query, QueryCursor};

    /// Compile `snippet`, run the query against `code`, and return the
    /// captured text for each requested metavar from the first match.
    fn run(snippet: &str, language: Language, code: &str) -> Vec<(String, Vec<String>)> {
        let compiled = compile_pattern(snippet, language).expect("compiles");
        let ts_language = language.ts_language().expect("grammar");
        let query = Query::new(&ts_language, &compiled.query)
            .unwrap_or_else(|e| panic!("query rejected: {e}\nquery: {}", compiled.query));
        let tree = api::parse_tree(code, language).expect("parse code");
        let names: Vec<&str> = query.capture_names().to_vec();
        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(&query, tree.root_node(), code.as_bytes());
        let mut out = Vec::new();
        while let Some(m) = matches.next() {
            let mut per_capture: HashMap<String, Vec<String>> = HashMap::new();
            for cap in m.captures {
                let name = names[cap.index as usize].to_string();
                let text = code[cap.node.start_byte()..cap.node.end_byte()].to_string();
                per_capture.entry(name).or_default().push(text);
            }
            for (name, texts) in per_capture {
                out.push((name, texts));
            }
        }
        out
    }

    fn capture<'a>(binds: &'a [(String, Vec<String>)], name: &str) -> &'a [String] {
        binds
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| v.as_slice())
            .unwrap_or(&[])
    }

    #[test]
    fn compiles_destructuring_default_in_typescript() {
        // The #2824 / burin-code#1629 codemod shape.
        let snippet = "$SRC?.$KEY ?? $DEFAULT";
        let compiled = compile_pattern(snippet, Language::TypeScript).expect("compiles");
        assert_eq!(compiled.metavars, vec!["SRC", "KEY", "DEFAULT"]);
        // It captures the optional-chain object/property and the fallback.
        let binds = run(
            snippet,
            Language::TypeScript,
            "const a = cfg?.timeout ?? 30;",
        );
        assert_eq!(capture(&binds, "SRC"), ["cfg".to_string()]);
        assert_eq!(capture(&binds, "KEY"), ["timeout".to_string()]);
        assert_eq!(capture(&binds, "DEFAULT"), ["30".to_string()]);
    }

    #[test]
    fn compiles_optional_chain_nil_coalescing_in_harn() {
        let snippet = "$SRC?.$KEY ?? $DEFAULT";
        let compiled = compile_pattern(snippet, Language::Harn).expect("compiles");
        assert_eq!(compiled.metavars, vec!["SRC", "KEY", "DEFAULT"]);
        let binds = run(
            snippet,
            Language::Harn,
            "fn main() {\n  let timeout = cfg?.timeout ?? 30\n}\n",
        );
        assert_eq!(capture(&binds, "SRC"), ["cfg".to_string()]);
        assert_eq!(capture(&binds, "KEY"), ["timeout".to_string()]);
        assert_eq!(capture(&binds, "DEFAULT"), ["30".to_string()]);
    }

    #[test]
    fn operator_is_constrained_not_just_structure() {
        // The `??` literal in the query must reject a `||` with the same
        // structural shape — otherwise the codemod would be unsound.
        let snippet = "$SRC?.$KEY ?? $DEFAULT";
        let binds = run(
            snippet,
            Language::TypeScript,
            "const a = cfg?.timeout || 30;",
        );
        assert!(
            capture(&binds, "SRC").is_empty(),
            "|| must not match the ?? pattern"
        );
    }

    #[test]
    fn round_trips_the_assignment_form() {
        // The literal acceptance pattern: `$NAME = $SRC?.$KEY ?? $DEFAULT`.
        let snippet = "$NAME = $SRC?.$KEY ?? $DEFAULT";
        let compiled = compile_pattern(snippet, Language::TypeScript).expect("compiles");
        assert_eq!(compiled.metavars, vec!["NAME", "SRC", "KEY", "DEFAULT"]);
        let binds = run(
            snippet,
            Language::TypeScript,
            "x = src?.userId ?? fallback;",
        );
        assert_eq!(capture(&binds, "NAME"), ["x".to_string()]);
        assert_eq!(capture(&binds, "SRC"), ["src".to_string()]);
        assert_eq!(capture(&binds, "KEY"), ["userId".to_string()]);
        assert_eq!(capture(&binds, "DEFAULT"), ["fallback".to_string()]);
    }

    #[test]
    fn lifts_metavars_in_rust() {
        let snippet = "let $NAME = $VALUE;";
        let binds = run(snippet, Language::Rust, "fn f() { let total = compute(); }");
        assert_eq!(capture(&binds, "NAME"), ["total".to_string()]);
        assert_eq!(capture(&binds, "VALUE"), ["compute()".to_string()]);
    }

    #[test]
    fn lifts_metavars_in_python() {
        let snippet = "$FN($ARG)";
        let binds = run(snippet, Language::Python, "print(value)");
        assert_eq!(capture(&binds, "FN"), ["print".to_string()]);
        assert_eq!(capture(&binds, "ARG"), ["value".to_string()]);
    }

    #[test]
    fn lifts_metavars_in_go() {
        let snippet = "$FN($ARG)";
        let binds = run(snippet, Language::Go, "package main\nfunc m() { log(err) }");
        assert_eq!(capture(&binds, "FN"), ["log".to_string()]);
        assert_eq!(capture(&binds, "ARG"), ["err".to_string()]);
    }

    #[test]
    fn repeated_metavar_unifies() {
        // `$X + $X` must match `a + a` but not `a + b`.
        let snippet = "$X + $X";
        let same = run(snippet, Language::Rust, "fn f() { let _ = a + a; }");
        assert_eq!(capture(&same, "X"), ["a".to_string()]);
        let different = run(snippet, Language::Rust, "fn f() { let _ = a + b; }");
        assert!(
            capture(&different, "X").is_empty(),
            "unification must reject `a + b`"
        );
    }

    #[test]
    fn rejects_unparseable_snippet() {
        let err = compile_pattern("$A ?? ?? $B", Language::TypeScript).unwrap_err();
        assert!(err.contains("did not parse"), "got: {err}");
    }

    #[test]
    fn rejects_variadic_for_now() {
        let err = compile_pattern("foo($$$ARGS)", Language::TypeScript).unwrap_err();
        assert!(err.contains("variadic"), "got: {err}");
    }

    #[test]
    fn typed_placeholder_narrows_to_kind() {
        // `$ARG:identifier` binds only when the argument is an identifier.
        let snippet = "$FN($ARG:identifier)";
        let compiled = compile_pattern(snippet, Language::TypeScript).expect("compiles");
        // The constraint is stripped from the metavar name.
        assert_eq!(compiled.metavars, vec!["FN", "ARG"]);
        // Matches `f(x)` …
        let hit = run(snippet, Language::TypeScript, "f(x);");
        assert_eq!(capture(&hit, "ARG"), ["x".to_string()]);
        // … but not `f(g())` — `g()` is a call_expression, not an identifier.
        let miss = run(snippet, Language::TypeScript, "f(g());");
        assert!(
            capture(&miss, "ARG").is_empty(),
            "a call argument must not match `:identifier`: {miss:?}"
        );
    }

    #[test]
    fn typed_placeholder_expression_alias_matches_any_expression() {
        // `:expression` (a supertype alias) matches expression-position nodes
        // of any concrete kind — the #2839 acceptance: `$x:expr` matches only
        // expression-position captures, but every expression kind qualifies.
        let snippet = "$FN($ARG:expression)";
        let ident = run(snippet, Language::TypeScript, "f(x);");
        assert_eq!(capture(&ident, "ARG"), ["x".to_string()]);
        let call = run(snippet, Language::TypeScript, "f(g());");
        assert_eq!(capture(&call, "ARG"), ["g()".to_string()]);
    }

    #[test]
    fn typed_placeholder_unknown_kind_is_an_error() {
        let err = compile_pattern("$X:not_a_real_kind", Language::TypeScript).unwrap_err();
        assert!(err.contains("not a node kind"), "got: {err}");
    }

    #[test]
    fn typed_placeholder_alias_unavailable_in_grammar_errors() {
        // Rust has no public `expression` supertype, so the alias must error
        // (directing the author to an exact kind) rather than silently widen.
        let err = compile_pattern("let $X = $V:expression;", Language::Rust).unwrap_err();
        assert!(err.contains("not a node kind"), "got: {err}");
    }

    #[test]
    fn typed_placeholder_unifies_and_constrains() {
        // `$X:identifier + $X` must both unify AND keep the kind constraint.
        let snippet = "$X:identifier + $X";
        let same = run(snippet, Language::Rust, "fn f() { let _ = a + a; }");
        assert_eq!(capture(&same, "X"), ["a".to_string()]);
        let different = run(snippet, Language::Rust, "fn f() { let _ = a + b; }");
        assert!(
            capture(&different, "X").is_empty(),
            "unification still holds"
        );
    }

    #[test]
    fn colon_without_constraint_is_left_literal() {
        // `$KEY: $VAL` (space after the colon) is a normal object entry, not a
        // typed placeholder — both metavars bind and `:` stays in the snippet.
        let snippet = "{$KEY: $VAL}";
        let compiled = compile_pattern(snippet, Language::TypeScript).expect("compiles");
        assert_eq!(compiled.metavars, vec!["KEY", "VAL"]);
        let binds = run(snippet, Language::TypeScript, "let o = {a: 1};");
        assert_eq!(capture(&binds, "KEY"), ["a".to_string()]);
        assert_eq!(capture(&binds, "VAL"), ["1".to_string()]);
    }

    #[test]
    fn literal_pattern_matches_exact_text() {
        // A metavar-free pattern is a literal pattern: `foo()` matches calls
        // to `foo`, not to other functions.
        let snippet = "foo()";
        let compiled = compile_pattern(snippet, Language::TypeScript).expect("compiles");
        assert!(compiled.metavars.is_empty());
        // It matches `foo()` …
        let hit = run(snippet, Language::TypeScript, "foo();");
        assert!(!hit.is_empty());
        // … but not `bar()` (the literal identifier is constrained).
        let miss = run(snippet, Language::TypeScript, "bar();");
        assert!(
            miss.is_empty(),
            "bar() must not match foo()'s literal pattern: {miss:?}"
        );
    }
}