symforge 10.0.2

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
use crate::domain::{LanguageId, ReferenceKind, ReferenceRecord, SymbolKind, SymbolRecord};

use super::store::IndexedFile;
pub(super) fn parse_reference_kind_filter(kind_filter: Option<&str>) -> Option<ReferenceKind> {
    match kind_filter {
        Some("call") => Some(ReferenceKind::Call),
        Some("import") => Some(ReferenceKind::Import),
        Some("type_usage") => Some(ReferenceKind::TypeUsage),
        Some("macro_use") => Some(ReferenceKind::MacroUse),
        Some("value_use") => Some(ReferenceKind::ValueUse),
        Some("all") | None => None,
        _ => None,
    }
}

pub(super) fn matches_exact_symbol_qualified_name(
    language: &LanguageId,
    qualified_name: &str,
    target_name: &str,
    module_path: Option<&str>,
) -> bool {
    let separator = match language {
        LanguageId::Python => ".",
        LanguageId::JavaScript | LanguageId::TypeScript => "/",
        _ => "::",
    };

    let Some(module_path) = module_path else {
        return false;
    };

    let full_path = format!("{module_path}{separator}{target_name}");

    // Exact match: qualified_name == "crate::engine::optimize_deterministic"
    if qualified_name == full_path {
        return true;
    }

    // Suffix match: qualified_name "engine::optimize_deterministic" is a suffix of
    // "crate::engine::optimize_deterministic".  This handles qualified calls where
    // tree-sitter captures a partial path (no crate:: prefix).
    if full_path.ends_with(qualified_name)
        && full_path[..full_path.len() - qualified_name.len()].ends_with(separator)
    {
        return true;
    }

    false
}

pub(super) fn matches_exact_symbol_reference(
    reference: &ReferenceRecord,
    target_name: &str,
    target_language: &LanguageId,
    target_kind: SymbolKind,
    module_path: Option<&str>,
    reference_file: Option<&IndexedFile>,
    kind_filter: Option<ReferenceKind>,
) -> bool {
    if let Some(kind_filter) = kind_filter
        && reference.kind != kind_filter
    {
        return false;
    }

    if reference
        .qualified_name
        .as_deref()
        .is_some_and(|qualified_name| {
            matches_exact_symbol_qualified_name(
                target_language,
                qualified_name,
                target_name,
                module_path,
            )
        })
    {
        return true;
    }

    if reference.name != target_name {
        return false;
    }

    if target_kind == SymbolKind::Function && *target_language == LanguageId::Rust {
        if reference.qualified_name.is_some() {
            return false;
        }
        if is_rust_receiver_method_call(reference_file, reference) {
            return false;
        }
    }

    true
}

fn is_rust_receiver_method_call(
    reference_file: Option<&IndexedFile>,
    reference: &ReferenceRecord,
) -> bool {
    let Some(file) = reference_file else {
        return false;
    };
    if file.language != LanguageId::Rust {
        return false;
    }
    is_receiver_method_call(file, reference)
}

/// Language-agnostic test for whether a `Call` reference is a receiver method
/// call (`receiver.method()`), detected by the byte immediately preceding the
/// call name being a `.`.
///
/// Used by the SF-002 self-member-call guards. It is intentionally only applied
/// in narrow contexts (a same-named call inside the target's own body, or a
/// same-named callee), never broadened into a global caller filter — doing so
/// would reclassify legitimate intra-class `this.target()` callers from OTHER
/// methods as non-callers.
pub(super) fn is_receiver_method_call(file: &IndexedFile, reference: &ReferenceRecord) -> bool {
    if reference.kind != ReferenceKind::Call {
        return false;
    }
    let start = reference.byte_range.0 as usize;
    start > 0 && file.content.get(start - 1) == Some(&b'.')
}

pub(crate) enum SymbolSelectorMatch<'a> {
    Selected(usize, &'a SymbolRecord),
    NotFound,
    Ambiguous(Vec<u32>),
}

/// Returns a disambiguation tier for a SymbolKind.  Lower number = higher
/// priority.  Used by `resolve_symbol_selector` to auto-pick the most
/// likely intended symbol when multiple candidates share the same name but
/// differ in kind.
///
/// Tier 1 — type definitions (class, struct, enum, interface, trait)
/// Tier 2 — namespace containers (module)
/// Tier 3 — callables (function, method, impl)
/// Tier 4 — everything else (constant, variable, type alias, key, section, other)
pub(super) fn kind_disambiguation_tier(kind: &SymbolKind) -> u8 {
    match kind {
        SymbolKind::Class
        | SymbolKind::Struct
        | SymbolKind::Enum
        | SymbolKind::Interface
        | SymbolKind::Trait => 1,
        SymbolKind::Module => 2,
        SymbolKind::Function | SymbolKind::Method | SymbolKind::Impl => 3,
        _ => 4, // Constant, Variable, Type, Key, Section, Other
    }
}

pub(crate) fn resolve_symbol_selector<'a>(
    file: &'a IndexedFile,
    name: &str,
    symbol_kind: Option<&str>,
    symbol_line: Option<u32>,
) -> SymbolSelectorMatch<'a> {
    let candidates = find_candidates_cascade(file, name, symbol_kind, symbol_line);

    match candidates.len() {
        0 => SymbolSelectorMatch::NotFound,
        1 => {
            let (idx, symbol) = candidates[0];
            SymbolSelectorMatch::Selected(idx, symbol)
        }
        _ => {
            // Kind-tier disambiguation: when the user did NOT specify
            // symbol_kind, group candidates by kind tier and auto-select
            // if the highest tier has exactly one candidate.  This resolves
            // the common C#/Java/Kotlin pattern where a class and its
            // constructor share the same name (class=tier 1, constructor
            // mapped to Function=tier 3).
            if symbol_kind.is_none() {
                let min_tier = candidates
                    .iter()
                    .map(|(_, sym)| kind_disambiguation_tier(&sym.kind))
                    .min()
                    .unwrap(); // safe: candidates.len() >= 2

                let top_tier: Vec<usize> = candidates
                    .iter()
                    .enumerate()
                    .filter(|(_, (_, sym))| kind_disambiguation_tier(&sym.kind) == min_tier)
                    .map(|(i, _)| i)
                    .collect();

                if top_tier.len() == 1 {
                    let (idx, symbol) = candidates[top_tier[0]];
                    return SymbolSelectorMatch::Selected(idx, symbol);
                }
            }

            SymbolSelectorMatch::Ambiguous(
                candidates
                    .into_iter()
                    .map(|(_, symbol)| symbol.line_range.0)
                    .collect(),
            )
        }
    }
}

/// True when `candidate` (a method/function) is defined inside a container in
/// the SAME file whose target type resolves to `type_name`, decided by
/// line-range containment.
///
/// The index stores methods hierarchically under their `impl`/type block, so a
/// candidate `Y` belongs to type `X` when some `impl X` /
/// `struct|enum|trait|class|interface X` symbol's `line_range` encloses the
/// candidate's. This is the deterministic "method Y belongs to type X" signal
/// used by `plan_edit`'s `Type::method` fallback. It reuses existing
/// `SymbolRecord` ranges only (no new index data) and matches the impl's
/// target-type TOKEN (`impl X` and `impl Trait for X` both resolve to `X`),
/// never the raw display string.
pub(crate) fn symbol_belongs_to_type(
    file: &IndexedFile,
    candidate: &SymbolRecord,
    type_name: &str,
) -> bool {
    let (cand_start, cand_end) = candidate.line_range;
    file.symbols.iter().any(|container| {
        let (start, end) = container.line_range;
        start <= cand_start
            && cand_end <= end
            && container_target_type(container).is_some_and(|ty| ty == type_name)
    })
}

/// The type token a container symbol defines methods for: the target type of an
/// `impl` block (`impl X` / `impl Trait for X` → `X`), or the name of a type
/// definition (`struct`/`enum`/`trait`/`class`/`interface`). Returns `None` for
/// any other kind. Generic parameters and path qualifiers are stripped so
/// `impl Cache<K, V>` and `crate::foo::Cache` both resolve to `Cache`.
fn container_target_type(symbol: &SymbolRecord) -> Option<&str> {
    let raw = match symbol.kind {
        SymbolKind::Impl => {
            let name = symbol.name.as_str();
            match name.rsplit_once(" for ") {
                Some((_, ty)) => ty,
                None => name.strip_prefix("impl ").unwrap_or(name),
            }
        }
        SymbolKind::Struct
        | SymbolKind::Enum
        | SymbolKind::Trait
        | SymbolKind::Class
        | SymbolKind::Interface => symbol.name.as_str(),
        _ => return None,
    };
    Some(base_type_token(raw.trim()))
}

/// Strip generic parameters and path qualifiers from a type token:
/// `Cache<K, V>` → `Cache`, `crate::foo::Repo` → `Repo`, `Repo` → `Repo`.
fn base_type_token(ty: &str) -> &str {
    let ty = ty.split('<').next().unwrap_or(ty).trim();
    ty.rsplit("::").next().unwrap_or(ty).trim()
}

/// Owner type name of the innermost `impl` block enclosing the symbol that
/// starts at `def_start_line`, or `None` when no enclosing `impl` exists.
///
/// A method definition lives inside its `impl X` / `impl Trait for X` block; the
/// index stores that block as a `SymbolKind::Impl` symbol whose `line_range`
/// encloses the method's. We pick the INNERMOST such impl (latest start line,
/// same "innermost" rule as [`crate::domain::find_enclosing_symbol`]) and parse
/// its target-type token via [`container_target_type`] (`impl X` and
/// `impl Trait for X` both → `X`). This is the shared owner-name primitive for
/// 019 recall-recovery: both `batch_rename` and `detect_impact` compute a def's
/// owner this way to match a call/ref's immediate qualifier against it.
///
/// ponytail: owner recovery is Rust-`impl`-shaped. Non-Rust grammars whose
/// containers are not modeled as `SymbolKind::Impl` blocks (or whose display
/// names don't parse via `container_target_type`) yield `None` here, so the
/// qualifier→owner match simply does not fire and those languages keep today's
/// demote/drop behavior. Widening owner recovery to more grammars is a future
/// step, not this fix.
pub(crate) fn enclosing_impl_owner(
    symbols: &[SymbolRecord],
    def_start_line: u32,
) -> Option<String> {
    let mut best: Option<(u32, &str)> = None; // (impl_start_line, owner_token)
    for sym in symbols {
        if sym.kind != SymbolKind::Impl {
            continue;
        }
        let (start, end) = sym.line_range;
        if def_start_line < start || def_start_line > end {
            continue;
        }
        let Some(owner) = container_target_type(sym) else {
            continue;
        };
        match best {
            Some((best_start, _)) if start <= best_start => {}
            _ => best = Some((start, owner)),
        }
    }
    best.map(|(_, owner)| owner.to_string())
}

// ---------------------------------------------------------------------------
// Cascading name resolution
// ---------------------------------------------------------------------------

/// Try progressively fuzzier name-matching strategies, returning candidates
/// from the first strategy that produces any matches.  Ordered from most
/// specific to least specific to minimise false-positive risk.
///
/// 1. True exact match (no allocation, covers ~99% of lookups)
/// 2. Whitespace-normalised match (Rust generics, CSS spacing)
/// 3. `impl` prefix prepend (Rust: LLMs drop "impl " from impl block names)
/// 4. Qualification stripping (C++ `Foo::bar` → `bar`, Go `Type.Method` → `Method`)
/// 5. CSS/SCSS selector prefix (LLM sends `@media`, index has `@media (max-width: …)`)
/// 6. Swift extension prefix (LLM sends `extension MyClass: Drawable`, index has `MyClass`)
fn find_candidates_cascade<'a>(
    file: &'a IndexedFile,
    name: &str,
    symbol_kind: Option<&str>,
    symbol_line: Option<u32>,
) -> Vec<(usize, &'a SymbolRecord)> {
    // 1. True exact match — fast path, no allocation.
    let c = match_symbols(file, |s| s.name == name, symbol_kind, symbol_line);
    if !c.is_empty() {
        return c;
    }

    let norm_query = normalize_symbol_name(name);

    // 2. Whitespace-normalised match (handles Rust generics, CSS spacing).
    //    Only try when normalisation actually changed the string.
    if norm_query != name {
        let c = match_symbols(
            file,
            |s| normalize_symbol_name(&s.name) == norm_query,
            symbol_kind,
            symbol_line,
        );
        if !c.is_empty() {
            return c;
        }
    }

    // 3. Impl prefix: "Trait for Type" → "impl Trait for Type"
    //    Also handles the combined case of missing prefix + whitespace diff.
    let impl_query = format!("impl {norm_query}");
    let c = match_symbols(
        file,
        |s| normalize_symbol_name(&s.name) == impl_query,
        symbol_kind,
        symbol_line,
    );
    if !c.is_empty() {
        return c;
    }

    // 4. Qualification stripping: "Foo::bar" → "bar", "Type.Method" → "Method"
    //    Covers C++ qualified method definitions and Go receiver methods.
    if let Some(bare) = strip_qualification(name) {
        let c = match_symbols(file, |s| s.name == bare, symbol_kind, symbol_line);
        if !c.is_empty() {
            return c;
        }
    }

    // 5. CSS/SCSS selector/at-rule prefix matching.
    //    "@media" matches "@media (max-width: 768px)"; ".btn" matches ".btn, .btn-primary".
    //    Only for names starting with CSS-like prefixes to avoid false positives.
    if name.starts_with('@') || name.starts_with('.') || name.starts_with('#') {
        let c = match_symbols(
            file,
            |s| is_selector_prefix_match(&s.name, name),
            symbol_kind,
            symbol_line,
        );
        if !c.is_empty() {
            return c;
        }
    }

    // 6. Swift extension: "extension MyClass: Drawable" → "MyClass"
    if let Some(type_name) = strip_swift_extension(name) {
        let c = match_symbols(file, |s| s.name == type_name, symbol_kind, symbol_line);
        if !c.is_empty() {
            return c;
        }
    }

    Vec::new()
}

/// Collect symbols matching a name predicate, kind filter, and optional line filter.
fn match_symbols<'a, F>(
    file: &'a IndexedFile,
    name_pred: F,
    symbol_kind: Option<&str>,
    symbol_line: Option<u32>,
) -> Vec<(usize, &'a SymbolRecord)>
where
    F: Fn(&SymbolRecord) -> bool,
{
    let mut candidates: Vec<(usize, &SymbolRecord)> = file
        .symbols
        .iter()
        .enumerate()
        .filter(|(_, s)| {
            name_pred(s)
                && symbol_kind
                    .map(|k| s.kind.to_string().eq_ignore_ascii_case(k))
                    .unwrap_or(true)
        })
        .collect();
    if let Some(sl) = symbol_line {
        // symbol_line is 1-based (from search_symbols output); line_range is 0-based.
        candidates.retain(|(_, s)| s.line_range.0 + 1 == sl);
    }
    candidates
}

/// Normalise a symbol name for fuzzy comparison.
/// Collapses whitespace runs to single spaces and strips spaces around
/// generic brackets and commas so `"Vec< T >"` matches `"Vec<T>"` and
/// `"HashMap< K , V >"` matches `"HashMap<K,V>"`.
fn normalize_symbol_name(s: &str) -> String {
    let collapsed: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
    collapsed
        .replace("< ", "<")
        .replace(" >", ">")
        .replace(" ,", ",")
        .replace(", ", ",")
}

/// Strip namespace/type qualification.
/// `"Foo::bar"` → `Some("bar")`, `"Type.Method"` → `Some("Method")`, `"plain"` → `None`.
fn strip_qualification(name: &str) -> Option<&str> {
    name.rsplit_once("::")
        .map(|(_, bare)| bare)
        .or_else(|| name.rsplit_once('.').map(|(_, bare)| bare))
}

/// Check whether `stored` is a CSS selector or at-rule that starts with `query`
/// followed by a delimiter (comma, space, paren, brace) or end-of-string.
/// Prevents `".btn"` from matching `".btn-group"` while still matching
/// `".btn, .btn-primary"`.
fn is_selector_prefix_match(stored: &str, query: &str) -> bool {
    if !stored.starts_with(query) {
        return false;
    }
    stored.len() == query.len()
        || matches!(
            stored.as_bytes()[query.len()],
            b',' | b' ' | b'(' | b'{' | b'\t' | b'\n' | b')'
        )
}

/// Strip Swift `extension` prefix and optional protocol conformance.
/// `"extension MyClass: Drawable"` → `Some("MyClass")`,
/// `"extension MyClass"` → `Some("MyClass")`,
/// `"MyClass"` → `None`.
fn strip_swift_extension(name: &str) -> Option<&str> {
    let rest = name.strip_prefix("extension ")?;
    Some(rest.split(':').next().unwrap_or(rest).trim())
}

pub(crate) fn render_symbol_selector(
    name: &str,
    symbol_kind: Option<&str>,
    symbol_line: Option<u32>,
) -> String {
    match (symbol_kind, symbol_line) {
        (Some(symbol_kind), Some(symbol_line)) => {
            format!("{symbol_kind} {name} at line {symbol_line}")
        }
        (Some(symbol_kind), None) => format!("{symbol_kind} {name}"),
        (None, Some(symbol_line)) => format!("{name} at line {symbol_line}"),
        (None, None) => name.to_string(),
    }
}