knot 1.14.1

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, C#, Build Systems, and HTML/CSS codebases
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
678
679
680
681
682
683
684
use super::context::ClassContext;
use super::utils::*;
use crate::models::EntityKind;
use tree_sitter::Node;

/// Extract docstring (preceding comments) and inline_comments from an entity node.
///
/// **Docstring extraction (upward pass):**
/// - Walks backward from the node using `prev_sibling()` to find comment nodes
/// - Groups consecutive comment lines together (tolerates single blank lines)
/// - Stops when hitting non-comment, non-whitespace nodes
/// - Handles both `/* */` block comments and `//` line comments
///
/// **Inline comments extraction (downward pass):**
/// - Walks the entity's body looking for comment nodes
/// - For classes: captures comments in the class body but NOT inside nested methods
/// - For methods/functions: captures comments in the method/function body
/// - Aggregates all found comments into a list
#[expect(
    clippy::excessive_nesting,
    reason = "function is verbose but correct — extraction deferred"
)]
pub(crate) fn extract_comments(
    entity_node: Node<'_>,
    source: &[u8],
    lang_name: &str,
    kind: &EntityKind,
    _class_contexts: &[ClassContext],
) -> (Option<String>, Vec<String>) {
    let mut docstring: Option<String> = None;
    let mut inline_comments: Vec<String> = Vec::new();

    // **Upward pass (Docstring):** Find preceding comments
    if let Some(_parent) = entity_node.parent() {
        let mut current = entity_node.prev_sibling();
        let mut comment_buffer: Vec<String> = Vec::new();

        while let Some(node) = current {
            match node.kind() {
                "line_comment" => {
                    // For Rust, the actual doc text is in a child `doc_comment` node
                    let text = if lang_name == "rust" {
                        // Try to find the doc_comment child node by iterating through children
                        let mut doc_text = None;
                        for i in 0..node.child_count() {
                            if let Some(child) = node.child(i)
                                && child.kind() == "doc_comment"
                            {
                                doc_text = Some(node_text(child, source));
                                break;
                            }
                        }
                        // If found, use the doc_comment text; otherwise fallback to full node
                        doc_text.unwrap_or_else(|| node_text(node, source))
                    } else {
                        node_text(node, source)
                    };
                    comment_buffer.insert(0, strip_comment_markers(&text));
                    current = node.prev_sibling();
                }
                "comment" | "block_comment" => {
                    let text = node_text(node, source);
                    let stripped = strip_comment_markers(&text);
                    // C# XML doc comments wrap prose in tags (`<summary>`,
                    // `</summary>`, …). Stripping the known doc tags keeps
                    // the actual prose (which is what gets displayed and
                    // embedded) instead of a leading `<summary>` line.
                    let stripped = if lang_name == "csharp" {
                        strip_xml_doc_tags(&stripped)
                    } else {
                        stripped
                    };
                    comment_buffer.insert(0, stripped);
                    current = node.prev_sibling();
                }
                // Allow single blank lines between comments
                _ if node.utf8_text(source).unwrap_or("").trim().is_empty() => {
                    // Check if there's a comment further back
                    if let Some(next) = node.prev_sibling()
                        && matches!(next.kind(), "comment" | "line_comment" | "block_comment")
                    {
                        current = Some(next);
                        continue;
                    }
                    break;
                }
                _ => break,
            }
        }

        if !comment_buffer.is_empty() {
            let combined = comment_buffer
                .iter()
                .filter(|s| !s.trim().is_empty())
                .cloned()
                .collect::<Vec<_>>()
                .join("\n");
            if !combined.trim().is_empty() {
                docstring = Some(combined);
            }
        }
    }

    // **Downward pass (Inline Comments):** Find comments within the entity body
    // Build a set of extracted entity nodes to avoid capturing their comments
    let extracted_child_entities = extract_child_entity_nodes(entity_node, lang_name);

    extract_inline_comments_recursive(
        entity_node,
        source,
        kind,
        &extracted_child_entities,
        &mut inline_comments,
    );

    (docstring, inline_comments)
}

/// Extract decorators/annotations from an entity node.
///
fn collect_nested_child_text(
    node: Node<'_>,
    source: &[u8],
    container_kind: &str,
    item_kinds: &[&str],
) -> Vec<String> {
    let mut results = Vec::new();
    let mut child = node.child(0);
    while let Some(c) = child {
        if c.kind() == container_kind {
            let mut item_child = c.child(0);
            while let Some(ic) = item_child {
                if item_kinds.contains(&ic.kind()) {
                    let text = node_text(ic, source);
                    if !text.is_empty() {
                        results.push(text);
                    }
                }
                item_child = ic.next_sibling();
            }
        }
        child = c.next_sibling();
    }
    results
}

/// Kotlin annotations of a declaration. tree-sitter-kotlin-ng sometimes
/// parses the annotations of a top-level declaration as an
/// `annotated_expression` right before it (`@RequestMapping` and its
/// `("/api")` arguments as an annotation plus a parenthesized expression),
/// leaving the declaration without modifiers; those are recovered.
fn kotlin_annotations(entity_node: Node<'_>, source: &[u8]) -> Vec<String> {
    let own = collect_nested_child_text(entity_node, source, "modifiers", &["annotation"]);
    if !own.is_empty() {
        return own;
    }
    let Some(prev) = entity_node.prev_named_sibling() else {
        return own;
    };
    if prev.kind() != "annotated_expression"
        || prev.end_position().row + 1 < entity_node.start_position().row
    {
        return own;
    }
    let mut annotations = Vec::new();
    let mut current = Some(prev);
    while let Some(expr) = current.take() {
        let mut cursor = expr.walk();
        let children: Vec<Node<'_>> = expr.named_children(&mut cursor).collect();
        let annotation_count = children.iter().filter(|c| c.kind() == "annotation").count();
        for child in &children {
            match child.kind() {
                "annotation" => annotations.push(node_text(*child, source)),
                "annotated_expression" => current = Some(*child),
                _ if annotation_count > 0 => {
                    // The annotation's arguments, split off by the parser.
                    if let Some(last) = annotations.last_mut() {
                        last.push_str(node_text(*child, source).trim());
                    }
                }
                _ => {}
            }
        }
    }
    annotations
}

fn typescript_decorators(entity_node: Node<'_>, source: &[u8]) -> Vec<String> {
    let mut decorators = Vec::new();
    let mut child = entity_node.child(0);
    while let Some(c) = child {
        if c.kind() == "decorator" {
            let decorator_text = node_text(c, source);
            if !decorator_text.is_empty() {
                decorators.push(decorator_text);
            }
        }
        child = c.next_sibling();
    }

    if decorators.is_empty() {
        // tree-sitter-typescript emits member decorators as siblings in
        // `class_body` (and exported-class decorators before `export`), so
        // walk backwards from the entity: only the decorators written
        // directly before it belong to it, never an earlier member's (#47).
        // Comments and anonymous tokens (`export`, `;`) are skipped; any
        // other node ends the run.
        let mut sibling = entity_node.prev_sibling();
        while let Some(s) = sibling {
            if s.kind() == "decorator" {
                let decorator_text = node_text(s, source);
                if !decorator_text.is_empty() {
                    decorators.push(decorator_text);
                }
            } else if s.is_named() && !s.kind().contains("comment") {
                break;
            }
            sibling = s.prev_sibling();
        }
        decorators.reverse();
    }
    decorators
}

/// **TypeScript:** Looks for `decorator` nodes preceding the entity.
/// Example: `@OnEvent('foo')` or `@Override`
///
/// **Java:** Looks for `annotation` nodes in the modifiers.
/// Examples: `@Override`, `@GetMapping("/path")`, `@OnEvent('foo')`
///
/// Returns a vector of decorator strings (e.g., `["@Override", "@OnEvent('foo')"]`).
pub(crate) fn extract_decorators(
    entity_node: Node<'_>,
    source: &[u8],
    lang_name: &str,
) -> Vec<String> {
    match lang_name {
        "typescript" => typescript_decorators(entity_node, source),
        "java" => collect_nested_child_text(
            entity_node,
            source,
            "modifiers",
            &["annotation", "marker_annotation"],
        ),
        "kotlin" => kotlin_annotations(entity_node, source),
        "csharp" => {
            collect_nested_child_text(entity_node, source, "attribute_list", &["attribute"])
        }
        _ => Vec::new(),
    }
}

/// Extract all child method/function/class declarations within a node.
/// Used to prevent parent entities from capturing comments of their children.
pub(crate) fn extract_child_entity_nodes<'a>(node: Node<'a>, lang_name: &str) -> Vec<Node<'a>> {
    let mut children = Vec::new();
    let mut child = node.child(0);

    let entity_kinds = if lang_name == "java" {
        vec![
            "method_declaration",
            "class_declaration",
            "interface_declaration",
        ]
    } else if lang_name == "csharp" {
        // C# child declarations whose comments belong to the child, not the
        // enclosing type.
        vec![
            "method_declaration",
            "constructor_declaration",
            "property_declaration",
            "class_declaration",
            "interface_declaration",
            "struct_declaration",
            "record_declaration",
            "enum_declaration",
        ]
    } else {
        vec![
            "method_definition",
            "method_signature",
            "abstract_method_signature",
            "function_declaration",
            "class_declaration",
            "abstract_class_declaration",
            "interface_declaration",
            "lexical_declaration",
            "export_statement",
        ]
    };

    while let Some(c) = child {
        if entity_kinds.contains(&c.kind()) {
            children.push(c);
        }
        child = c.next_sibling();
    }

    children
}

/// Recursively extract inline comments from within an entity's body,
/// skipping over any child entity declarations.
pub(crate) fn extract_inline_comments_recursive(
    node: Node<'_>,
    source: &[u8],
    _kind: &EntityKind,
    extracted_children: &[Node<'_>],
    comments: &mut Vec<String>,
) {
    if matches!(node.kind(), "comment" | "line_comment" | "block_comment") {
        let text = node_text(node, source);
        let cleaned = strip_comment_markers(&text);
        if !cleaned.trim().is_empty() {
            comments.push(cleaned);
        }
        return;
    }

    // Skip child entities to avoid capturing their comments
    if extracted_children
        .iter()
        .any(|child| child.id() == node.id())
    {
        return;
    }

    let mut child = node.child(0);
    while let Some(c) = child {
        extract_inline_comments_recursive(c, source, _kind, extracted_children, comments);
        child = c.next_sibling();
    }
}

/// Remove common comment markers from a doc-comment string.
///
/// Strips `/**`, `*/`, leading `*`, `//`, `///`, and surrounding whitespace.
pub(crate) fn strip_comment_markers(raw: &str) -> String {
    raw.lines()
        .map(|line| {
            let trimmed = line.trim();
            let trimmed = trimmed.strip_prefix("/**").unwrap_or(trimmed);
            let trimmed = trimmed.strip_prefix("/*").unwrap_or(trimmed);
            let trimmed = trimmed.strip_suffix("*/").unwrap_or(trimmed);
            let trimmed = trimmed.strip_prefix("///").unwrap_or(trimmed);
            let trimmed = trimmed.strip_prefix("//").unwrap_or(trimmed);
            let trimmed = trimmed.strip_prefix('*').unwrap_or(trimmed);
            trimmed.trim()
        })
        .filter(|l| !l.is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

/// XML documentation tags recognized by [`strip_xml_doc_tags`]. Tags whose
/// name (ignoring `/` closers, `?` declarations, and attributes) is in this
/// set are removed together with their angle brackets; unknown text in angle
/// brackets (e.g. a generic `List<T>` mention in prose) is preserved.
const XML_DOC_TAGS: &[&str] = &[
    "summary",
    "remarks",
    "param",
    "typeparam",
    "returns",
    "value",
    "example",
    "exception",
    "permission",
    "see",
    "seealso",
    "paramref",
    "typeparamref",
    "cref",
    "para",
    "c",
    "code",
    "list",
    "item",
    "term",
    "description",
    "inheritdoc",
    "include",
    "br",
    "b",
    "i",
    "langword",
];

/// Strip XML doc-comment tags (`<summary>`, `</summary>`, `<param name="x">`,
/// `<see cref="Y"/>`, …) from a C# doc string so the prose survives.
pub(crate) fn strip_xml_doc_tags(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut rest = raw;

    while let Some(start) = rest.find('<') {
        let Some(end_offset) = rest[start..].find('>') else {
            break;
        };
        let end = start + end_offset;
        out.push_str(&rest[..start]);

        let tag = &rest[start + 1..end];
        let tag_name = tag
            .trim()
            .trim_start_matches('/')
            .trim_start_matches('?')
            .split(|c: char| c.is_whitespace() || c == '/' || c == '>')
            .next()
            .unwrap_or("");
        if !XML_DOC_TAGS.contains(&tag_name) {
            out.push_str(&rest[start..=end]);
        }
        rest = &rest[end + 1..];
    }
    out.push_str(rest);
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn find_class(node: Node) -> Option<Node> {
        if node.kind() == "class_declaration" {
            return Some(node);
        }
        let mut i = 0u32;
        while let Some(child) = node.child(i) {
            if let Some(found) = find_class(child) {
                return Some(found);
            }
            i += 1;
        }
        None
    }

    #[test]
    fn test_strip_comment_markers_java_block() {
        let raw = "/**\n * This is a doc comment\n * With multiple lines\n */";
        let stripped = strip_comment_markers(raw);
        assert_eq!(stripped, "This is a doc comment\nWith multiple lines");
    }

    #[test]
    fn test_strip_comment_markers_java_line() {
        let raw = "// This is a line comment";
        let stripped = strip_comment_markers(raw);
        assert_eq!(stripped, "This is a line comment");
    }

    #[test]
    fn test_strip_comment_markers_typescript_triple_slash() {
        let raw = "/// TypeScript doc comment\n/// Second line";
        let stripped = strip_comment_markers(raw);
        assert_eq!(stripped, "TypeScript doc comment\nSecond line");
    }

    #[test]
    fn test_strip_comment_markers_mixed_block() {
        let raw = "/* Comment start\n * Middle line\n * End */";
        let stripped = strip_comment_markers(raw);
        assert_eq!(stripped, "Comment start\nMiddle line\nEnd");
    }

    #[test]
    fn test_strip_comment_markers_empty_lines() {
        let raw = "// First\n//\n// Third";
        let stripped = strip_comment_markers(raw);
        assert_eq!(stripped, "First\nThird");
    }

    #[test]
    fn test_strip_comment_markers_whitespace_only() {
        let raw = "//   \n//\n//";
        let stripped = strip_comment_markers(raw);
        assert_eq!(stripped, "");
    }

    #[ignore = "Tree-sitter query structure varies by language"]
    #[test]
    fn test_extract_child_entity_nodes_java() {
        // Test extract_child_entity_nodes with Java code
        let code = "class Test { void method1() {} void method2() {} }";
        let tree = crate::pipeline::parser::test_utils::parse_java_snippet(code)
            .expect("Failed to parse Java code");

        if let Some(class_node) = find_class(tree.root_node()) {
            let children = extract_child_entity_nodes(class_node, "java");
            // Should find methods
            assert!(!children.is_empty());
        }
    }

    #[ignore = "Tree-sitter query structure varies by language"]
    #[test]
    fn test_extract_child_entity_nodes_typescript() {
        let code = "class Test { method1() {} method2() {} }";
        let tree = crate::pipeline::parser::test_utils::parse_typescript_snippet(code)
            .expect("Failed to parse TypeScript code");

        if let Some(class_node) = find_class(tree.root_node()) {
            let children = extract_child_entity_nodes(class_node, "typescript");
            // Should find methods or method definitions
            assert!(!children.is_empty());
        }
    }

    #[test]
    fn test_extract_decorators_kotlin() {
        let code = r#"
@Service
class UserService {
    fun getUser(id: Int): User? {
        return null
    }
}
"#;
        let lang = tree_sitter_kotlin_ng::LANGUAGE.into();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(code, None).unwrap();

        if let Some(class_node) = find_class(tree.root_node()) {
            let decorators = extract_decorators(class_node, code.as_bytes(), "kotlin");
            assert!(
                !decorators.is_empty(),
                "Expected to find decorators on Kotlin class"
            );
            assert!(
                decorators.iter().any(|d| d.contains("Service")),
                "Expected to find @Service decorator"
            );
        } else {
            panic!("Could not find class declaration in Kotlin code");
        }
    }

    #[test]
    fn test_extract_decorators_java() {
        let code = r#"
@Service
@RequestMapping("/users")
public class UserService {
}
"#;
        let lang = tree_sitter_java::LANGUAGE.into();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(code, None).unwrap();

        if let Some(class_node) = find_class(tree.root_node()) {
            let decorators = extract_decorators(class_node, code.as_bytes(), "java");
            assert_eq!(decorators.len(), 2);
            assert!(decorators.iter().any(|d| d.contains("Service")));
            assert!(decorators.iter().any(|d| d.contains("RequestMapping")));
        } else {
            panic!("Could not find class declaration in Java code");
        }
    }

    #[test]
    fn test_extract_decorators_typescript() {
        let code = r#"
@Component({ selector: 'app-root' })
class AppComponent {
}
"#;
        let lang = tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(code, None).unwrap();

        if let Some(class_node) = find_class(tree.root_node()) {
            let decorators = extract_decorators(class_node, code.as_bytes(), "typescript");
            assert_eq!(decorators.len(), 1);
            assert!(decorators[0].contains("Component"));
        } else {
            panic!("Could not find class declaration in TypeScript code");
        }
    }

    /// Decorators written before `export` belong to the exported class.
    #[test]
    fn test_extract_decorators_typescript_exported_class() {
        let code =
            "@Injectable()\n@Component({ selector: 'app-root' })\nexport class AppComponent {}\n";
        let lang = tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(code, None).unwrap();
        let class_node = find_class(tree.root_node()).expect("class declaration");
        assert_eq!(
            extract_decorators(class_node, code.as_bytes(), "typescript"),
            vec!["@Injectable()", "@Component({ selector: 'app-root' })"]
        );
    }

    /// `(method name, decorators)` of every `method_definition` in `code`.
    fn method_decorators(code: &str, lang: tree_sitter::Language) -> Vec<(String, Vec<String>)> {
        fn walk(node: Node<'_>, source: &[u8], out: &mut Vec<(String, Vec<String>)>) {
            if node.kind() == "method_definition"
                && let Some(name) = node.child_by_field_name("name")
            {
                out.push((
                    node_text(name, source),
                    extract_decorators(node, source, "typescript"),
                ));
            }
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                walk(child, source, out);
            }
        }
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(code, None).unwrap();
        let mut out = Vec::new();
        walk(tree.root_node(), code.as_bytes(), &mut out);
        out
    }

    /// Issue #47: a class member takes only the decorators written directly
    /// before it, never those of an earlier member.
    #[test]
    fn test_typescript_member_decorators_do_not_leak() {
        let code = r#"
export class CartStore {
  constructor() { makeObservable(this); }
  helper(): void {}
  @computed
  get total(): number { return 1; }
  get plain(): number { return 2; }
  @action
  // the action resets the cart
  @bound
  reset(): void {}
  update(): void {}
}
"#;
        let expected: Vec<(String, Vec<String>)> = [
            ("constructor", vec![]),
            ("helper", vec![]),
            ("total", vec!["@computed"]),
            ("plain", vec![]),
            ("reset", vec!["@action", "@bound"]),
            ("update", vec![]),
        ]
        .into_iter()
        .map(|(name, decorators)| {
            (
                name.to_string(),
                decorators.into_iter().map(str::to_string).collect(),
            )
        })
        .collect();
        for lang in [
            tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
            tree_sitter_typescript::LANGUAGE_TSX,
        ] {
            assert_eq!(method_decorators(code, lang.into()), expected);
        }
    }

    #[test]
    fn test_extract_decorators_csharp() {
        let code = r#"
[Obsolete("Use V2")]
class UserService {
}
"#;
        let lang = tree_sitter_c_sharp::LANGUAGE.into();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(code, None).unwrap();

        if let Some(class_node) = find_class(tree.root_node()) {
            let decorators = extract_decorators(class_node, code.as_bytes(), "csharp");
            assert_eq!(decorators.len(), 1);
            assert!(decorators[0].contains("Obsolete"));
        } else {
            panic!("Could not find class declaration in C# code");
        }
    }
}