code2graph 0.0.0-beta.6

Purpose-neutral code-graph extraction: source files → symbols, references, and cross-file edges. Tree-sitter based, no storage opinion.
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
// SPDX-License-Identifier: Apache-2.0

//! Svelte single-file component extractor.
//!
//! Parses the `.svelte` file with tree-sitter-svelte-ng, locates every
//! `<script>` block, delegates the inner source to the existing TypeScript /
//! JavaScript extraction core (`extract_ecmascript`), then remaps all byte
//! offsets back into the full `.svelte` file.  Two script blocks may be
//! present: the normal instance block and `<script context="module">`;
//! symbols and references from both are merged into a single [`FileFacts`].
//!
//! The merger pushes one document-spanning root [`ScopeKind::Module`] scope at
//! index 0, then re-parents each `<script>` block's own root scope under it so
//! the merged file has exactly one root (`parent == None`) — mirroring every
//! other language's one-module-per-file shape.  `ScopeId` indices from each
//! block are shifted by `scope_base` before the block's scopes are appended.
//!
//! Per-block [`SymbolKind::Module`] symbols are filtered out during the merge;
//! a single Module symbol spanning the whole document is synthesized once,
//! after the loop, giving the component a stable SCIP identity regardless of
//! how many `<script>` blocks it contains.

use tree_sitter::{Node, Parser};

use crate::error::{CodegraphError, Result};
use crate::graph::types::{ByteSpan, FileFacts, ScopeId, ScopeKind, SymbolKind};
use crate::lang::Language;

use super::Extractor;
use super::module_symbol;
use super::push_scope;
use super::shift_offsets;
use super::typescript::{extract_ecmascript, module_namespaces};

/// Extracts facts from a Svelte single-file component.
pub struct SvelteExtractor;

impl Extractor for SvelteExtractor {
    fn lang(&self) -> Language {
        Language::Svelte
    }

    fn extract(&self, source: &str, file: &str) -> Result<FileFacts> {
        let ts_lang = crate::grammar::svelte();
        let mut parser = Parser::new();
        parser
            .set_language(&ts_lang)
            .map_err(|_| CodegraphError::Parse {
                path: file.to_owned(),
            })?;

        let tree = parser
            .parse(source.as_bytes(), None)
            .ok_or_else(|| CodegraphError::Parse {
                path: file.to_owned(),
            })?;

        let root = tree.root_node();
        let bytes = source.as_bytes();

        // Collect all script_element nodes anywhere in the document.
        let mut script_nodes = Vec::new();
        collect_script_elements(&root, &mut script_nodes);

        // Start with an empty merged result.
        let mut merged = FileFacts {
            file: file.to_owned(),
            lang: "svelte".to_owned(),
            symbols: Vec::new(),
            references: Vec::new(),
            scopes: Vec::new(),
            bindings: Vec::new(),
            ffi_exports: Vec::new(),
        };

        // A single document-spanning root scope. Each `<script>` block's former
        // root scope is re-parented under this so the merged file has exactly one
        // root (`parent == None`) — mirroring every other language's one-module-
        // per-file shape.
        let doc_root: ScopeId = push_scope(
            &mut merged.scopes,
            None,
            ByteSpan {
                start: 0,
                end: source.len(),
            },
            ScopeKind::Module,
        );

        for script_el in script_nodes {
            // Find the raw_text child — skip empty script blocks.
            let raw_text = match find_raw_text(&script_el) {
                Some(n) => n,
                None => continue,
            };

            let delta = raw_text.start_byte();
            let inner_source =
                std::str::from_utf8(&bytes[raw_text.byte_range()]).unwrap_or_default();

            // Detect lang="ts"/"typescript" inside the start_tag.
            let inner_lang = detect_script_lang(&script_el, bytes);

            let mut block_facts = extract_ecmascript(inner_source, file, inner_lang)?;
            shift_offsets(&mut block_facts, delta, file, "svelte", bytes);

            // Merge: fix up ScopeId indices before extending. `scope_base` is >= 1
            // for every block (the doc root occupies index 0), so the shifts apply
            // uniformly.
            let scope_base: ScopeId = merged.scopes.len();
            // Shift scope field on bindings from this block.
            for b in &mut block_facts.bindings {
                b.scope += scope_base;
            }
            // Shift scope field on references from this block.
            for r in &mut block_facts.references {
                if let Some(s) = r.scope.as_mut() {
                    *s += scope_base;
                }
            }
            // Shift parent ScopeId on scopes from this block.
            for sc in &mut block_facts.scopes {
                if let Some(p) = sc.parent.as_mut() {
                    *p += scope_base;
                }
            }
            // Re-parent the block's former root scope (local index 0, parent None,
            // untouched by the Some(p) shift above) under the document root.
            if let Some(first) = block_facts.scopes.first_mut() {
                first.parent = Some(doc_root);
            }

            // Drop the per-block module symbols — they share one SCIP id and would
            // be duplicate identities. The single document module symbol is
            // synthesized once, after the loop.
            merged.symbols.extend(
                block_facts
                    .symbols
                    .into_iter()
                    .filter(|s| s.kind != SymbolKind::Module),
            );
            merged.references.extend(block_facts.references);
            merged.scopes.extend(block_facts.scopes);
            merged.bindings.extend(block_facts.bindings);
            // ffi_exports: Svelte scripts don't emit FFI exports.
        }

        // Exactly one module symbol spanning the whole document — its SCIP id is
        // identical to a single-script `.svelte` (the rendered id ignores `lang`).
        let namespaces = module_namespaces(file);
        merged.symbols.push(module_symbol(
            Language::Svelte,
            &namespaces,
            file,
            source.len(),
        ));

        Ok(merged)
    }
}

/// Walk the tree recursively and collect every `script_element` node.
fn collect_script_elements<'a>(node: &Node<'a>, out: &mut Vec<Node<'a>>) {
    if node.kind() == "script_element" {
        out.push(*node);
        return; // script_element children are its own internals, not nested scripts
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_script_elements(&child, out);
    }
}

/// Return the `raw_text` child of a `script_element`, if one exists.
fn find_raw_text<'a>(script_el: &Node<'a>) -> Option<Node<'a>> {
    let mut cursor = script_el.walk();
    script_el
        .children(&mut cursor)
        .find(|n| n.kind() == "raw_text")
}

/// Detect whether `<script lang="ts">` or `<script lang="typescript">` is
/// present on the script element.  Falls back to [`Language::JavaScript`].
fn detect_script_lang(script_el: &Node<'_>, bytes: &[u8]) -> Language {
    let mut cursor = script_el.walk();
    for child in script_el.children(&mut cursor) {
        if child.kind() == "start_tag" {
            let mut tag_cursor = child.walk();
            for attr in child.children(&mut tag_cursor) {
                if attr.kind() != "attribute" {
                    continue;
                }
                // Check attribute_name == "lang"
                let name_matches = {
                    let mut c = attr.walk();
                    attr.children(&mut c)
                        .any(|n| n.kind() == "attribute_name" && &bytes[n.byte_range()] == b"lang")
                };
                if !name_matches {
                    continue;
                }
                // Look for quoted_attribute_value → attribute_value
                let mut attr_cursor = attr.walk();
                for child2 in attr.children(&mut attr_cursor) {
                    if child2.kind() == "quoted_attribute_value" {
                        let mut qav_cursor = child2.walk();
                        for av in child2.children(&mut qav_cursor) {
                            if av.kind() == "attribute_value" {
                                let val = &bytes[av.byte_range()];
                                if val == b"ts" || val == b"typescript" {
                                    return Language::TypeScript;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    Language::JavaScript
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::types::SymbolKind;

    fn svelte_source_with_ts_script() -> &'static str {
        r#"<script lang="ts">
import { foo } from './util';
export function run(x: number) { foo(x); }
let count = 0;
</script>
<main>Hello</main>"#
    }

    #[test]
    fn extracts_run_symbol_and_reference_lang_ts() {
        let source = svelte_source_with_ts_script();
        let facts = SvelteExtractor
            .extract(source, "src/App.svelte")
            .expect("extraction should succeed");

        assert_eq!(facts.lang, "svelte");
        assert_eq!(facts.file, "src/App.svelte");

        let run_sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "run" && s.kind == SymbolKind::Function);
        assert!(
            run_sym.is_some(),
            "expected `run` function symbol; got: {:?}",
            facts.symbols
        );

        // Must have at least a call/import reference (foo, or import {foo}).
        assert!(
            !facts.references.is_empty(),
            "expected at least one reference"
        );
    }

    #[test]
    fn offset_remap_is_correct() {
        let source = svelte_source_with_ts_script();
        let facts = SvelteExtractor
            .extract(source, "src/App.svelte")
            .expect("extraction should succeed");

        let run_sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "run" && s.kind == SymbolKind::Function)
            .expect("`run` symbol must be present");

        // The span.start of `run` must point at the declaration in the FULL
        // .svelte source — not at its offset in the inner script. The TS
        // extractor spans an exported function from the `export` keyword, so the
        // span must align with `export function run` in the embedding document.
        let expected_start = source
            .find("export function run")
            .expect("`export function run` must appear in source");
        assert_eq!(
            run_sym.span.start, expected_start,
            "span.start should be the byte offset of the `run` declaration in the full .svelte source"
        );
        // And the span must slice back to real source containing the name.
        assert!(
            source[run_sym.span.start..run_sym.span.end].contains("run"),
            "remapped span must slice the run declaration out of the .svelte source"
        );
    }

    #[test]
    fn extracts_js_script_no_lang_attr() {
        let source = r#"<script>
export function greet(name) { return name; }
</script>
<p>Hi</p>"#;
        let facts = SvelteExtractor
            .extract(source, "src/Comp.svelte")
            .expect("extraction should succeed");

        assert_eq!(facts.lang, "svelte", "lang should always be 'svelte'");
        let greet = facts.symbols.iter().find(|s| s.name == "greet");
        assert!(
            greet.is_some(),
            "expected `greet` symbol; got: {:?}",
            facts.symbols
        );
    }

    #[test]
    fn two_script_blocks_both_extracted_and_scope_indices_valid() {
        let source = r#"<script context="module">
export function preload() {}
</script>
<script>
export function setup() {}
</script>
<div>content</div>"#;
        let facts = SvelteExtractor
            .extract(source, "src/Page.svelte")
            .expect("extraction should succeed");

        let has_preload = facts.symbols.iter().any(|s| s.name == "preload");
        let has_setup = facts.symbols.iter().any(|s| s.name == "setup");
        assert!(has_preload, "expected `preload` from module script block");
        assert!(has_setup, "expected `setup` from instance script block");

        // Exactly ONE module symbol, spanning the whole document — both script
        // blocks no longer emit duplicate module symbols.
        let module_syms: Vec<_> = facts
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Module)
            .collect();
        assert_eq!(
            module_syms.len(),
            1,
            "expected exactly one Module symbol, got {module_syms:?}"
        );
        assert_eq!(module_syms[0].span.start, 0, "module span must start at 0");
        assert_eq!(
            module_syms[0].span.end,
            source.len(),
            "module span must cover the whole document"
        );

        // Exactly one root scope (`parent == None`), spanning the whole document.
        let root_scopes: Vec<_> = facts.scopes.iter().filter(|s| s.parent.is_none()).collect();
        assert_eq!(
            root_scopes.len(),
            1,
            "expected exactly one root scope, got {root_scopes:?}"
        );
        assert_eq!(root_scopes[0].span.start, 0, "root scope must start at 0");
        assert_eq!(
            root_scopes[0].span.end,
            source.len(),
            "root scope must cover the whole document"
        );

        // Each block's former root scope is now re-parented under the doc root
        // (index 0). The doc root is the only scope with parent None; every other
        // module-kind scope must point at it.
        let block_roots: Vec<_> = facts
            .scopes
            .iter()
            .enumerate()
            .filter(|(i, s)| *i != 0 && s.kind == ScopeKind::Module)
            .collect();
        assert!(
            !block_roots.is_empty(),
            "expected at least one re-parented block root scope"
        );
        for (i, sc) in &block_roots {
            assert_eq!(
                sc.parent,
                Some(0),
                "block root scope at index {i} must be re-parented under the doc root"
            );
        }

        // All binding scope indices must be valid (in-bounds for the merged scopes vec).
        for b in &facts.bindings {
            assert!(
                b.scope < facts.scopes.len() || facts.scopes.is_empty(),
                "binding scope {} out of range (scopes.len={})",
                b.scope,
                facts.scopes.len()
            );
        }
        // All reference scope indices must be valid.
        for r in &facts.references {
            if let Some(s) = r.scope {
                assert!(
                    s < facts.scopes.len(),
                    "reference scope {} out of range (scopes.len={})",
                    s,
                    facts.scopes.len()
                );
            }
        }
    }

    #[test]
    fn no_script_block_emits_single_module_symbol_and_root_scope() {
        let source = r#"<main><p>Hello world</p></main>"#;
        let facts = SvelteExtractor
            .extract(source, "src/NoScript.svelte")
            .expect("extraction should succeed even with no script");

        assert_eq!(facts.lang, "svelte");
        assert_eq!(facts.file, "src/NoScript.svelte");

        // A script-less component still emits exactly one Module symbol spanning
        // the whole document (consistent with every other language) and no refs.
        assert_eq!(facts.symbols.len(), 1, "expected exactly one symbol");
        assert_eq!(facts.symbols[0].kind, SymbolKind::Module);
        assert_eq!(facts.symbols[0].span.start, 0);
        assert_eq!(facts.symbols[0].span.end, source.len());
        assert!(facts.references.is_empty(), "expected no references");

        // Exactly one root scope spanning the whole document.
        assert_eq!(facts.scopes.len(), 1, "expected exactly one (root) scope");
        assert_eq!(facts.scopes[0].parent, None);
        assert_eq!(facts.scopes[0].span.start, 0);
        assert_eq!(facts.scopes[0].span.end, source.len());
    }

    #[test]
    fn single_script_emits_one_module_symbol_spanning_document() {
        let source = svelte_source_with_ts_script();
        let facts = SvelteExtractor
            .extract(source, "src/App.svelte")
            .expect("extraction should succeed");

        let module_syms: Vec<_> = facts
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Module)
            .collect();
        assert_eq!(
            module_syms.len(),
            1,
            "single-script .svelte must yield exactly one Module symbol, got {module_syms:?}"
        );
        assert_eq!(module_syms[0].span.start, 0, "module span must start at 0");
        assert_eq!(
            module_syms[0].span.end,
            source.len(),
            "module span must cover the whole document"
        );
        // The SCIP id ignores `lang`, so it matches the file's module path.
        assert_eq!(
            module_syms[0].id.to_scip_string(),
            "codegraph . . . src/App/"
        );
    }
}