cgx-engine 0.1.8

Core engine for cgx — Tree-sitter parsing, DuckDB graph storage, git analysis, and clustering
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
use tree_sitter::{Node, Parser, Query, QueryCursor};

use crate::parser::{
    CommentKind, CommentTag, EdgeDef, EdgeKind, LanguageParser, NodeDef, NodeKind, ParseResult,
};
use crate::walker::SourceFile;

pub struct TypeScriptParser;

impl TypeScriptParser {
    pub fn new() -> Self {
        Self
    }
}

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

fn is_jsx_extension(path: &str) -> bool {
    path.ends_with(".tsx") || path.ends_with(".jsx")
}

impl LanguageParser for TypeScriptParser {
    fn extensions(&self) -> &[&str] {
        &["ts", "tsx", "js", "jsx", "mjs", "cjs"]
    }

    fn extract(&self, file: &SourceFile) -> anyhow::Result<ParseResult> {
        // TSX/JSX files must use the TSX grammar; TypeScript grammar rejects JSX syntax
        // and produces error nodes with wrong line positions for every JSX element.
        let language = if is_jsx_extension(&file.relative_path) {
            tree_sitter_typescript::language_tsx()
        } else {
            tree_sitter_typescript::language_typescript()
        };

        let mut parser = Parser::new();
        parser.set_language(&language)?;

        let tree = parser
            .parse(&file.content, None)
            .ok_or_else(|| anyhow::anyhow!("failed to parse {}", file.relative_path))?;

        let source_bytes = file.content.as_bytes();
        let root = tree.root_node();
        let mut nodes = Vec::new();
        let mut edges = Vec::new();

        let fp = file_node_id(&file.relative_path);

        // Parse function declarations
        if let Ok(query) = Query::new(
            &language,
            "(function_declaration name: (identifier) @name) @fn",
        ) {
            extract_nodes(
                &mut nodes,
                &mut edges,
                file,
                &query,
                root,
                source_bytes,
                NodeKind::Function,
                "fn",
                &fp,
            );
        }

        // Parse arrow functions / variable declarations with arrow
        if let Ok(query) = Query::new(
            &language,
            "(variable_declarator name: (identifier) @name value: (arrow_function) @fn)",
        ) {
            extract_nodes(
                &mut nodes,
                &mut edges,
                file,
                &query,
                root,
                source_bytes,
                NodeKind::Function,
                "fn",
                &fp,
            );
        }

        // Parse variable declarations with function expressions
        if let Ok(query) = Query::new(
            &language,
            "(variable_declarator name: (identifier) @name value: (function_expression) @fn)",
        ) {
            extract_nodes(
                &mut nodes,
                &mut edges,
                file,
                &query,
                root,
                source_bytes,
                NodeKind::Function,
                "fn",
                &fp,
            );
        }

        // Parse class declarations
        if let Ok(query) = Query::new(
            &language,
            "(class_declaration name: (type_identifier) @name) @cls",
        ) {
            extract_nodes(
                &mut nodes,
                &mut edges,
                file,
                &query,
                root,
                source_bytes,
                NodeKind::Class,
                "cls",
                &fp,
            );
        }

        // Parse method definitions
        if let Ok(query) = Query::new(
            &language,
            "(method_definition name: (property_identifier) @name) @m",
        ) {
            extract_nodes(
                &mut nodes,
                &mut edges,
                file,
                &query,
                root,
                source_bytes,
                NodeKind::Function,
                "fn",
                &fp,
            );
        }

        // Parse imports — walk the tree directly to find import statements
        extract_imports(&mut edges, root, source_bytes, &fp, file);

        // Parse exports
        if let Ok(query) = Query::new(
            &language,
            "(export_statement (function_declaration name: (identifier) @name) @expr)",
        ) {
            process_exports(
                &mut nodes,
                &mut edges,
                file,
                &query,
                root,
                source_bytes,
                &fp,
                "fn",
            );
        }

        if let Ok(query) = Query::new(
            &language,
            "(export_statement (class_declaration name: (type_identifier) @name) @expr)",
        ) {
            process_exports(
                &mut nodes,
                &mut edges,
                file,
                &query,
                root,
                source_bytes,
                &fp,
                "cls",
            );
        }

        // Extract CALLS edges by walking the AST with function context tracking
        extract_calls(&mut edges, root, source_bytes, file);

        // Extract JSX expression comments and annotation tags (TODO/FIXME/etc.)
        let mut comment_tags = Vec::new();
        extract_jsx_comments(&mut comment_tags, root, source_bytes, false);

        Ok(ParseResult {
            nodes,
            edges,
            comment_tags,
        })
    }
}

fn file_node_id(rel_path: &str) -> String {
    format!("file:{}", rel_path)
}

#[allow(clippy::too_many_arguments)]
fn extract_nodes(
    nodes: &mut Vec<NodeDef>,
    edges: &mut Vec<EdgeDef>,
    file: &SourceFile,
    query: &Query,
    root: tree_sitter::Node,
    source_bytes: &[u8],
    kind: NodeKind,
    prefix: &str,
    file_id: &str,
) {
    let mut cursor = QueryCursor::new();
    for m in cursor.matches(query, root, source_bytes) {
        let Some(name_capture) = m
            .captures
            .iter()
            .find(|c| query.capture_names()[c.index as usize] == "name")
        else {
            continue;
        };

        let name = unquote_str(&source_bytes[name_capture.node.byte_range()]);
        let node_start = name_capture.node.start_position();

        // Use the body node's end position so the snippet covers the full function/class body
        let body_end = m
            .captures
            .iter()
            .find(|c| {
                let cap_name = &query.capture_names()[c.index as usize];
                *cap_name == "fn" || *cap_name == "cls" || *cap_name == "m"
            })
            .map(|c| c.node.end_position())
            .unwrap_or_else(|| name_capture.node.end_position());

        let Some(_fn_capture) = m.captures.iter().find(|c| {
            let cap_name = &query.capture_names()[c.index as usize];
            *cap_name == "fn" || *cap_name == "cls" || *cap_name == "m"
        }) else {
            continue;
        };

        let id = format!("{}:{}:{}", prefix, file.relative_path, name);

        nodes.push(NodeDef {
            id,
            kind: kind.clone(),
            name,
            path: file.relative_path.clone(),
            line_start: node_start.row as u32 + 1,
            line_end: body_end.row as u32 + 1,
            ..Default::default()
        });

        edges.push(EdgeDef {
            src: file_id.to_string(),
            dst: format!(
                "{}:{}:{}",
                prefix,
                file.relative_path,
                unquote_str(&source_bytes[name_capture.node.byte_range()])
            ),
            kind: EdgeKind::Exports,
            ..Default::default()
        });
    }
}

#[allow(clippy::too_many_arguments)]
fn process_exports(
    _nodes: &mut Vec<NodeDef>,
    edges: &mut Vec<EdgeDef>,
    file: &SourceFile,
    query: &Query,
    root: tree_sitter::Node,
    source_bytes: &[u8],
    file_id: &str,
    prefix: &str,
) {
    let mut cursor = QueryCursor::new();
    for m in cursor.matches(query, root, source_bytes) {
        let Some(name_capture) = m
            .captures
            .iter()
            .find(|c| query.capture_names()[c.index as usize] == "name")
        else {
            continue;
        };

        let name = node_text(name_capture.node, source_bytes);

        edges.push(EdgeDef {
            src: file_id.to_string(),
            dst: format!("{}:{}:{}", prefix, file.relative_path, name),
            kind: EdgeKind::Exports,
            ..Default::default()
        });
    }
}

fn node_text(node: tree_sitter::Node, source: &[u8]) -> String {
    node.utf8_text(source).unwrap_or("").to_string()
}

fn extract_imports(
    edges: &mut Vec<EdgeDef>,
    root: tree_sitter::Node,
    source_bytes: &[u8],
    file_id: &str,
    file: &SourceFile,
) {
    // Walk the entire tree (not just root children) to find imports and requires
    let mut cursor = root.walk();
    traverse_imports(edges, root, source_bytes, file_id, file, &mut cursor);
}

fn traverse_imports(
    edges: &mut Vec<EdgeDef>,
    node: tree_sitter::Node,
    source_bytes: &[u8],
    file_id: &str,
    file: &SourceFile,
    cursor: &mut tree_sitter::TreeCursor,
) {
    if node.kind() == "import_statement" {
        for j in 0..node.child_count() {
            let Some(import_child) = node.child(j) else {
                continue;
            };
            if import_child.kind() == "string" {
                let import_path = unquote_str(&source_bytes[import_child.byte_range()]);
                if import_path.starts_with('.') {
                    let resolved = resolve_import_path(&file.relative_path, &import_path);
                    if !resolved.is_empty() {
                        edges.push(EdgeDef {
                            src: file_id.to_string(),
                            dst: file_node_id(&resolved),
                            kind: EdgeKind::Imports,
                            ..Default::default()
                        });
                    }
                }
                break;
            }
        }
    } else if node.kind() == "call_expression" {
        // Check for require('...')
        if let Some(func) = node.child_by_field_name("function") {
            if func.kind() == "identifier" && node_text(func, source_bytes) == "require" {
                if let Some(args) = node.child_by_field_name("arguments") {
                    for k in 0..args.child_count() {
                        let Some(arg) = args.child(k) else { continue };
                        if arg.kind() == "string" {
                            let import_path = unquote_str(&source_bytes[arg.byte_range()]);
                            if import_path.starts_with('.') {
                                let resolved =
                                    resolve_import_path(&file.relative_path, &import_path);
                                if !resolved.is_empty() {
                                    edges.push(EdgeDef {
                                        src: file_id.to_string(),
                                        dst: file_node_id(&resolved),
                                        kind: EdgeKind::Imports,
                                        ..Default::default()
                                    });
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            traverse_imports(edges, child, source_bytes, file_id, file, cursor);
            if !cursor.goto_next_sibling() {
                break;
            }
        }
        cursor.goto_parent();
    }
}

fn unquote_str(s: &[u8]) -> String {
    let s = std::str::from_utf8(s).unwrap_or("");
    s.trim().trim_matches('\'').trim_matches('"').to_string()
}

fn resolve_import_path(current: &str, import: &str) -> String {
    let mut parts: Vec<&str> = current.split('/').collect();
    parts.pop(); // remove filename

    for segment in import.split('/') {
        match segment {
            "." => {}
            ".." => {
                parts.pop();
            }
            _ => parts.push(segment),
        }
    }

    parts.join("/")
}

/// Walk the AST tracking function context, emitting CALLS edges for each call_expression.
fn extract_calls(edges: &mut Vec<EdgeDef>, root: Node, source: &[u8], file: &SourceFile) {
    let mut fn_stack: Vec<String> = Vec::new();
    walk_for_calls(edges, root, source, file, &mut fn_stack);
}

fn is_fn_node(kind: &str) -> bool {
    matches!(
        kind,
        "function_declaration"
            | "function"
            | "arrow_function"
            | "method_definition"
            | "generator_function_declaration"
            | "generator_function"
    )
}

fn fn_name_from_node<'a>(node: Node<'a>, source: &[u8], file: &SourceFile) -> Option<String> {
    // function_declaration / generator_function_declaration: has `name` field
    if let Some(name_node) = node.child_by_field_name("name") {
        let name = name_node.utf8_text(source).unwrap_or("").to_string();
        if !name.is_empty() {
            return Some(format!("fn:{}:{}", file.relative_path, name));
        }
    }
    // Arrow/anonymous assigned to variable: look at parent variable_declarator
    let parent = node.parent()?;
    if parent.kind() == "variable_declarator" {
        if let Some(name_node) = parent.child_by_field_name("name") {
            let name = name_node.utf8_text(source).unwrap_or("").to_string();
            if !name.is_empty() {
                return Some(format!("fn:{}:{}", file.relative_path, name));
            }
        }
    }
    None
}

fn walk_for_calls(
    edges: &mut Vec<EdgeDef>,
    node: Node,
    source: &[u8],
    file: &SourceFile,
    fn_stack: &mut Vec<String>,
) {
    let kind = node.kind();
    let pushed = is_fn_node(kind);

    if pushed {
        if let Some(id) = fn_name_from_node(node, source, file) {
            fn_stack.push(id);
        } else {
            // anonymous — push a sentinel so pop is balanced
            fn_stack.push(String::new());
        }
    }

    if kind == "call_expression" {
        if let Some(caller_id) = fn_stack.last().filter(|s| !s.is_empty()) {
            let callee_name = node
                .child_by_field_name("function")
                .and_then(|func| match func.kind() {
                    "identifier" => Some(func.utf8_text(source).unwrap_or("").to_string()),
                    "member_expression" => func
                        .child_by_field_name("property")
                        .map(|p| p.utf8_text(source).unwrap_or("").to_string()),
                    _ => None,
                })
                .unwrap_or_default();

            if !callee_name.is_empty() && callee_name != "require" {
                edges.push(EdgeDef {
                    src: caller_id.clone(),
                    dst: callee_name,
                    kind: EdgeKind::Calls,
                    confidence: 0.7,
                    ..Default::default()
                });
            }
        }
    }

    // JSX component usage: <ComponentName ... /> and <ComponentName ...>
    // Treat JSX elements as calls from the enclosing function to the component.
    if kind == "jsx_opening_element" || kind == "jsx_self_closing_element" {
        if let Some(caller_id) = fn_stack.last().filter(|s| !s.is_empty()) {
            let tag_name = node
                .child_by_field_name("name")
                .map(|n| n.utf8_text(source).unwrap_or("").to_string())
                .unwrap_or_default();

            // Only emit edges for PascalCase or camelCase user-defined components.
            // Lowercase tags like <div>, <span> are HTML intrinsics — skip them.
            let is_component = tag_name
                .chars()
                .next()
                .map(|c| {
                    c.is_uppercase()
                        || (c.is_lowercase() && tag_name.len() > 3 && tag_name.contains('.'))
                })
                .unwrap_or(false);

            if is_component {
                // Strip member access for <Namespace.Component /> — use only the last segment
                let callee = tag_name
                    .split('.')
                    .next_back()
                    .unwrap_or(&tag_name)
                    .to_string();
                edges.push(EdgeDef {
                    src: caller_id.clone(),
                    dst: callee,
                    kind: EdgeKind::Calls,
                    confidence: 0.6,
                    ..Default::default()
                });
            }
        }
    }

    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            walk_for_calls(edges, cursor.node(), source, file, fn_stack);
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }

    if pushed {
        fn_stack.pop();
    }
}

const ANNOTATION_TAGS: &[&str] = &[
    "TODO", "FIXME", "HACK", "NOTE", "BUG", "OPTIMIZE", "WARN", "XXX",
];

/// Recursively walk the AST extracting annotation comments (TODO/FIXME/etc.).
/// `in_jsx_expression` tracks whether we are inside a `jsx_expression` node,
/// which is how `{/* ... */}` comments appear in the TSX grammar.
fn extract_jsx_comments(
    tags: &mut Vec<CommentTag>,
    node: Node,
    source: &[u8],
    in_jsx_expression: bool,
) {
    let kind = node.kind();

    // Track whether we're entering a jsx_expression wrapper
    let now_in_jsx = in_jsx_expression || kind == "jsx_expression";

    if kind == "comment" {
        let raw = node.utf8_text(source).unwrap_or("").trim();

        let comment_kind = if in_jsx_expression {
            // Strip `/*` / `*/` delimiters and check for commented-out JSX code
            let inner = raw.trim_start_matches("/*").trim_end_matches("*/").trim();
            if inner.starts_with('<') || inner.contains("</") || inner.contains("/>") {
                CommentKind::JsxCommentedCode
            } else {
                CommentKind::JsxExpression
            }
        } else {
            CommentKind::Standard
        };

        let upper = raw.to_uppercase();
        for &tag in ANNOTATION_TAGS {
            if upper.contains(tag) {
                tags.push(CommentTag {
                    tag_type: tag.to_string(),
                    text: raw.to_string(),
                    line: node.start_position().row as u32 + 1,
                    comment_kind: comment_kind.clone(),
                });
                break;
            }
        }
    }

    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            extract_jsx_comments(tags, cursor.node(), source, now_in_jsx);
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
}