Skip to content

Commit 2ae9a46

Browse files
committed
feat: Add complete Svelte language support with template call extraction
Addresses Svelte function calls invisible in template expressions and ugly destructured variable names. Adds SvelteExtractor that delegates `
1 parent b872459 commit 2ae9a46

3 files changed

Lines changed: 93 additions & 0 deletions

File tree

docs/SEARCH_QUALITY_LOOP.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,10 @@ test().catch(console.error);
455455
| Kotlin `navigation_expression` calls not resolved cleanly | `navigation_expression` fell through to `getNodeText` producing messy names with parentheses | `src/extraction/tree-sitter.ts: extractCall` — handle `navigation_expression` by extracting method name from `navigation_suffix > simple_identifier` |
456456
| Kotlin `fun interface` declarations invisible | Tree-sitter-kotlin doesn't support `fun interface` syntax (Kotlin 1.4+), producing ERROR or misparse as `function_declaration` | `src/extraction/languages/kotlin.ts: visitNode` detects three misparse patterns: (1) ERROR node + lambda body, (2) function_declaration with `user_type("interface")` direct child + name in ERROR child, (3) function_declaration with ERROR child containing `user_type("interface")` + name. `isFunInterfaceNode` checks both direct and ERROR-nested `user_type` children |
457457
| Kotlin class/interface methods missing when nested `fun interface` present | Tree-sitter misparsed parent body as ERROR (starting with `{`) + class_body (nested interface body); `resolveBody` found wrong body | `src/extraction/languages/kotlin.ts: resolveBody` prefers ERROR bodies starting with `{`; `visitNode` excludes body-like ERROR from `fun interface` detection |
458+
| Svelte `$props()` destructuring produces ugly variable names | `let { x, y } = $props()` has `object_pattern` as variable name node; `getNodeText` returns full pattern | `src/extraction/tree-sitter.ts: extractVariable` skips `object_pattern`/`array_pattern` named declarators |
459+
| Svelte template function calls invisible (e.g. `class={cn(...)}`) | SvelteExtractor only parsed `<script>` blocks, missing calls in template markup | `src/extraction/svelte-extractor.ts: extractTemplateCalls` scans `{expression}` blocks in template for call patterns |
460+
| Svelte `$state`/`$derived` rune calls creating noise | Runes are compiler builtins, not real function calls | `src/extraction/svelte-extractor.ts` filters `SVELTE_RUNES` set from unresolved references |
461+
| Object literal getters/setters extracted as standalone functions | `method_definition` inside `object` literals treated same as class methods | `src/extraction/tree-sitter.ts: extractMethod` skips `method_definition` nodes whose parent is `object`/`object_expression` |
458462

459463
## After Fixing Issues
460464

@@ -541,6 +545,7 @@ if (receiverType) {
541545
- [x] **TypeScript** — NOT needed for `getReceiverType`. Methods nested in class body. Added `abstract_class_declaration` to `classTypes` so abstract classes are properly extracted. Fixed single-expression arrow function extraction (`const fn = () => expr` was silently dropped because `extractName` picked up the body identifier instead of returning `<anonymous>` for parent name resolution). Verified against Grafana
542546
- [x] **Dart** — NOT needed for `getReceiverType`. Methods nested in class body. Added bare call extraction for selector-based method calls (e.g. `object.method()`). Verified against Flutter
543547
- [x] **Kotlin**`getReceiverType` extracts receiver from extension functions `fun Type.method()`. Added `classifyClassNode` to distinguish interfaces/enums from classes (all use `class_declaration` AST node). Added `resolveBody` hook since Kotlin's tree-sitter grammar doesn't use field names. Added `navigation_expression` handling for method call extraction. Added `object_declaration` via `extraClassNodeTypes`. Added `delegation_specifier` handling in `extractInheritance` for Kotlin's `: Parent, Interface` syntax. Also fixed `extractInterface` to visit body children (interface methods were not being extracted). Added `visitNode` hook to handle `fun interface` (SAM) declarations — tree-sitter-kotlin doesn't support this Kotlin 1.4+ syntax, producing ERROR or function_declaration misparse; the hook detects both patterns and extracts the interface. Verified against Koin, LeakCanary
548+
- [x] **Svelte** — Custom `SvelteExtractor` delegates `<script>` blocks to TS/JS parser; creates `component` nodes for each `.svelte` file. Added template expression call extraction: scans `{expression}` blocks in markup for function calls (e.g. `class={cn(...)}`), creating call edges from component to callees — increased Svelte call edges from 29 to 387. Filtered Svelte 5 rune calls (`$state`, `$props`, `$derived`, `$effect`, `$bindable`). Also fixed: destructured `$props()` patterns (e.g. `let { x, y } = $props()`) no longer extracted as ugly multi-line variable names (skip `object_pattern`/`array_pattern` in `extractVariable`). Object literal getter/setter methods no longer extracted as standalone functions. Verified against shadcn-svelte
544549

545550
### Needs Verification
546551

src/extraction/svelte-extractor.ts

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,22 @@ import { generateNodeId } from './tree-sitter-helpers';
33
import { TreeSitterExtractor } from './tree-sitter';
44
import { isLanguageSupported } from './grammars';
55

6+
/** Svelte 5 rune names — compiler builtins, not real functions */
7+
const SVELTE_RUNES = new Set([
8+
'$props', '$state', '$derived', '$effect', '$bindable',
9+
'$inspect', '$host', '$snippet',
10+
]);
11+
612
/**
713
* SvelteExtractor - Extracts code relationships from Svelte component files
814
*
915
* Svelte files are multi-language (script + template + style). Rather than
1016
* parsing the full Svelte grammar, we extract the <script> block content
1117
* and delegate it to the TypeScript/JavaScript TreeSitterExtractor.
1218
*
19+
* Also extracts function calls from template expressions (`{fn(...)}`) so
20+
* cross-file call edges are captured even when calls live in markup.
21+
*
1322
* Every .svelte file produces a component node (Svelte components are always importable).
1423
*/
1524
export class SvelteExtractor {
@@ -41,6 +50,14 @@ export class SvelteExtractor {
4150
for (const block of scriptBlocks) {
4251
this.processScriptBlock(block, componentNode.id);
4352
}
53+
54+
// Extract function calls from template expressions ({fn(...)})
55+
this.extractTemplateCalls(componentNode.id, scriptBlocks);
56+
57+
// Filter out Svelte rune calls ($state, $props, $derived, etc.)
58+
this.unresolvedReferences = this.unresolvedReferences.filter(
59+
ref => !SVELTE_RUNES.has(ref.referenceName)
60+
);
4461
} catch (error) {
4562
this.errors.push({
4663
message: `Svelte extraction error: ${error instanceof Error ? error.message : String(error)}`,
@@ -196,4 +213,64 @@ export class SvelteExtractor {
196213
this.errors.push(error);
197214
}
198215
}
216+
217+
/**
218+
* Extract function calls from Svelte template expressions.
219+
*
220+
* In Svelte, many function calls happen in markup (e.g., `class={cn(...)}`),
221+
* not inside `<script>` blocks. We scan the template portion for `{expression}`
222+
* blocks and extract call patterns from them.
223+
*/
224+
private extractTemplateCalls(
225+
componentNodeId: string,
226+
_scriptBlocks: Array<{ content: string; startLine: number }>
227+
): void {
228+
// Build a set of line ranges covered by <script> and <style> blocks so we skip them
229+
const coveredRanges: Array<[number, number]> = [];
230+
231+
// Find all <script>...</script> and <style>...</style> ranges
232+
const tagRegex = /<(script|style)(\s[^>]*)?>[\s\S]*?<\/\1>/g;
233+
let tagMatch;
234+
while ((tagMatch = tagRegex.exec(this.source)) !== null) {
235+
const startLine = (this.source.substring(0, tagMatch.index).match(/\n/g) || []).length;
236+
const endLine = startLine + (tagMatch[0].match(/\n/g) || []).length;
237+
coveredRanges.push([startLine, endLine]);
238+
}
239+
240+
// Find template expressions: {...} outside of script/style blocks
241+
// Matches curly-brace expressions, excluding Svelte block syntax ({#if}, {:else}, {/if}, {@html}, {@render})
242+
const lines = this.source.split('\n');
243+
const exprRegex = /\{([^}#/:@][^}]*)\}/g;
244+
245+
for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
246+
// Skip lines inside script/style blocks
247+
if (coveredRanges.some(([start, end]) => lineIdx >= start && lineIdx <= end)) continue;
248+
249+
const line = lines[lineIdx]!;
250+
let exprMatch;
251+
while ((exprMatch = exprRegex.exec(line)) !== null) {
252+
const expr = exprMatch[1]!;
253+
// Extract function calls: identifiers followed by (
254+
// Matches: cn(...), buttonVariants(...), obj.method(...)
255+
const callRegex = /\b([a-zA-Z_$][\w$.]*)\s*\(/g;
256+
let callMatch;
257+
while ((callMatch = callRegex.exec(expr)) !== null) {
258+
const calleeName = callMatch[1]!;
259+
// Skip Svelte runes, control flow keywords, and common non-function patterns
260+
if (SVELTE_RUNES.has(calleeName)) continue;
261+
if (calleeName === 'if' || calleeName === 'else' || calleeName === 'each' || calleeName === 'await') continue;
262+
263+
this.unresolvedReferences.push({
264+
fromNodeId: componentNodeId,
265+
referenceName: calleeName,
266+
referenceKind: 'calls',
267+
line: lineIdx + 1, // 1-indexed
268+
column: exprMatch.index + callMatch.index,
269+
filePath: this.filePath,
270+
language: 'svelte',
271+
});
272+
}
273+
}
274+
}
275+
}
199276
}

src/extraction/tree-sitter.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,12 @@ export class TreeSitterExtractor {
590590
// Languages with methodsAreTopLevel (e.g. Go) always treat them as methods
591591
// Languages with getReceiverType (e.g. Rust) extract as method when receiver is found
592592
if (!this.isInsideClassLikeNode() && !this.extractor.methodsAreTopLevel && !receiverType) {
593+
// Skip method_definition nodes inside object literals (getters/setters/methods
594+
// in inline objects). These are ephemeral and create noise (e.g., Svelte context
595+
// objects: `ctx.set({ get view() { ... } })`).
596+
if (node.parent?.type === 'object' || node.parent?.type === 'object_expression') {
597+
return;
598+
}
593599
// Not inside a class-like node and no receiver type, treat as function
594600
this.extractFunction(node);
595601
return;
@@ -929,6 +935,11 @@ export class TreeSitterExtractor {
929935
const valueNode = getChildByField(child, 'value');
930936

931937
if (nameNode) {
938+
// Skip destructured patterns (e.g., `let { x, y } = $props()` in Svelte)
939+
// These produce ugly multi-line names like "{ class: className }"
940+
if (nameNode.type === 'object_pattern' || nameNode.type === 'array_pattern') {
941+
continue;
942+
}
932943
const name = getNodeText(nameNode, this.source);
933944
// Arrow functions / function expressions: extract as function instead of variable
934945
if (valueNode && (valueNode.type === 'arrow_function' || valueNode.type === 'function_expression')) {

0 commit comments

Comments
 (0)