knot 1.6.2

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, 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
use super::languages::{java, javascript, kotlin, python, typescript};
use crate::models::{EntityKind, ParsedEntity, ReferenceIntent};
use tree_sitter::Node;

/// Third pass: find call_expression / new_expression / jsx nodes that fall outside
/// the byte ranges of extracted entities, and assign them to the nearest entity.
/// If no entities exist, create a synthetic <module> entity.
#[expect(
    clippy::too_many_arguments,
    reason = "function is verbose but correct — extraction deferred"
)]
pub(crate) fn collect_orphaned_references(
    root: Node<'_>,
    source: &[u8],
    lang_name: &str,
    entities: &mut Vec<ParsedEntity>,
    covered_ranges: &[(usize, usize)],
    file_path: &str,
    repo_name: &str,
) {
    // Collect all reference intents from the entire file
    let mut all_intents: Vec<(ReferenceIntent, usize)> = Vec::new();
    collect_all_reference_intents_with_byte_pos(root, source, lang_name, &mut all_intents);

    // Filter to orphaned intents (not covered by any entity)
    let orphaned_intents: Vec<ReferenceIntent> = all_intents
        .into_iter()
        .filter(|(_, byte_pos)| {
            !covered_ranges
                .iter()
                .any(|(start, end)| byte_pos >= start && byte_pos < end)
        })
        .map(|(intent, _)| intent)
        .collect();

    if orphaned_intents.is_empty() {
        return;
    }

    // Create a synthetic <module> entity that spans the entire file (fallback for
    // module-level orphans not contained by any real entity). Always present so
    // find_nearest_entity_by_line containment pass can match it when needed.
    let module_kind = match lang_name {
        "python" => EntityKind::PythonModule,
        "rust" => EntityKind::RustModule,
        _ => EntityKind::Function,
    };
    let mut module_entity = ParsedEntity::new(
        "<module>",
        module_kind,
        "<module>",
        None,
        None,
        lang_name,
        file_path,
        1,
        usize::MAX,
        None,
        repo_name,
    );

    if entities.is_empty() {
        module_entity.reference_intents = orphaned_intents;
        entities.push(module_entity);
        return;
    }

    // Push module entity at the end so containment check prefers real entities
    // (smaller range) over the module (usize::MAX range)
    entities.push(module_entity);

    // Assign each orphan individually to its nearest entity by line
    for intent in orphaned_intents {
        let orphan_line = match &intent {
            ReferenceIntent::Call { line, .. } => *line,
            ReferenceIntent::Extends { line, .. } => *line,
            ReferenceIntent::Implements { line, .. } => *line,
            ReferenceIntent::TypeReference { line, .. } => *line,
            ReferenceIntent::ValueReference { line, .. } => *line,
            ReferenceIntent::DomElementReference { line, .. } => *line,
            ReferenceIntent::CssClassUsage { line, .. } => *line,
            ReferenceIntent::HtmlFileImport { line, .. } => *line,
            ReferenceIntent::CssFileImport { line, .. } => *line,
            ReferenceIntent::RustMacroCall { line, .. } => *line,
            ReferenceIntent::VclSubCall { line, .. } => *line,
            ReferenceIntent::VclBackendRef { line, .. } => *line,
            ReferenceIntent::VclProbeRef { line, .. } => *line,
            ReferenceIntent::VclAclRef { line, .. } => *line,
            ReferenceIntent::VclInclude { line, .. } => *line,
            ReferenceIntent::VclVmodImport { line, .. } => *line,
            ReferenceIntent::VclUnusedRef { line, .. } => *line,
        };
        let target_idx = find_nearest_entity_by_line(entities, orphan_line);
        entities[target_idx].reference_intents.push(intent);
    }
}

/// Collect ALL call/new/jsx intents from the entire AST, paired with byte position.
pub(crate) fn collect_all_reference_intents_with_byte_pos(
    node: Node<'_>,
    source: &[u8],
    lang_name: &str,
    intents: &mut Vec<(ReferenceIntent, usize)>,
) {
    if lang_name == "typescript" {
        typescript::collect_all_reference_intents_typescript(node, source, intents);
    } else if lang_name == "java" {
        java::collect_all_reference_intents_java(node, source, intents);
    } else if lang_name == "javascript" {
        javascript::collect_all_reference_intents_javascript(node, source, intents);
    } else if lang_name == "python" {
        let mut python_call_intents = Vec::new();
        python::extract_call_intents_python(node, source, &mut python_call_intents);
        for call in python_call_intents {
            intents.push((
                ReferenceIntent::Call {
                    method: call.method,
                    receiver: call.receiver,
                    line: call.line,
                    arg_count: call.arg_count,
                },
                0, // Byte pos not strictly needed for Python yet
            ));
        }
        let mut python_import_intents = Vec::new();
        python::extract_import_intents_python(node, source, &mut python_import_intents);
        for intent in python_import_intents {
            intents.push((intent, node.start_byte()));
        }
        let mut python_value_intents = Vec::new();
        python::extract_value_references_python(node, source, &mut python_value_intents);
        for intent in python_value_intents {
            intents.push((intent, node.start_byte()));
        }
    } else if lang_name == "c" || lang_name == "cpp" {
        let mut cpp_call_intents = Vec::new();
        crate::pipeline::parser::languages::cpp::extract_call_intents_cpp(
            node,
            source,
            &mut cpp_call_intents,
        );
        for call in cpp_call_intents {
            intents.push((
                ReferenceIntent::Call {
                    method: call.method,
                    receiver: call.receiver,
                    line: call.line,
                    arg_count: call.arg_count,
                },
                0, // Byte pos not strictly needed for C++ basic resolution
            ));
        }
    } else if lang_name == "kotlin" {
        // collect_all_reference_intents_kotlin emits each intent with its correct byte_pos,
        // ensuring calls inside method bodies fall within covered ranges and are NOT orphaned.
        kotlin::collect_all_reference_intents_kotlin(node, source, intents);
    }
}

/// Find the entity index nearest to the given line number.
/// First pass: tries to find an entity that CONTAINS the target line (start_line <= target_line <= end_line).
/// Second pass: falls back to closest entity at or before target_line.
/// Third pass: falls back to closest entity overall.
pub(crate) fn find_nearest_entity_by_line(entities: &[ParsedEntity], target_line: usize) -> usize {
    let mut best_idx = 0;
    let mut best_distance = usize::MAX;

    // First pass: find entity that contains the target line (start_line <= target_line <= end_line)
    for (idx, entity) in entities.iter().enumerate() {
        if target_line >= entity.start_line && target_line <= entity.end_line {
            // Prefer the entity with smallest range that contains the target
            let range_size = entity.end_line - entity.start_line;
            if range_size < best_distance {
                best_distance = range_size;
                best_idx = idx;
            }
        }
    }

    // If no entity contains the target, second pass: find closest entity at or before target_line
    if best_distance == usize::MAX {
        for (idx, entity) in entities.iter().enumerate() {
            let entity_line = entity.start_line;
            if entity_line <= target_line {
                let distance = target_line - entity_line;
                if distance < best_distance {
                    best_distance = distance;
                    best_idx = idx;
                }
            }
        }
    }

    // If still no match, third pass: fall back to closest entity overall
    if best_distance == usize::MAX {
        for (idx, entity) in entities.iter().enumerate() {
            let distance = entity.start_line.abs_diff(target_line);
            if distance < best_distance {
                best_distance = distance;
                best_idx = idx;
            }
        }
    }

    best_idx
}

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

    #[test]
    fn test_find_nearest_entity_by_line_before() {
        // Create mock entities at specific lines
        let entity1 = ParsedEntity::new(
            "Entity1",
            EntityKind::Class,
            "Entity1",
            None,
            None,
            "java",
            "/test.java",
            10,
            20,
            None,
            "test-repo",
        );
        let entity2 = ParsedEntity::new(
            "Entity2",
            EntityKind::Method,
            "Entity2",
            None,
            None,
            "java",
            "/test.java",
            30,
            40,
            None,
            "test-repo",
        );
        let entity3 = ParsedEntity::new(
            "Entity3",
            EntityKind::Function,
            "Entity3",
            None,
            None,
            "java",
            "/test.java",
            50,
            60,
            None,
            "test-repo",
        );

        let entities = vec![entity1, entity2, entity3];

        // Target line 25 should be assigned to entity1 (at line 10, since 25 > 10 and closest entity before it)
        let idx = find_nearest_entity_by_line(&entities, 25);
        assert_eq!(idx, 0, "Line 25 should be assigned to entity1 (line 10)");
    }

    #[test]
    fn test_find_nearest_entity_by_line_exact() {
        let entity1 = ParsedEntity::new(
            "Entity1",
            EntityKind::Class,
            "Entity1",
            None,
            None,
            "java",
            "/test.java",
            10,
            20,
            None,
            "test-repo",
        );

        let entities = vec![entity1];

        let idx = find_nearest_entity_by_line(&entities, 10);
        assert_eq!(idx, 0);
    }

    #[test]
    fn test_find_nearest_entity_by_line_after() {
        let entity1 = ParsedEntity::new(
            "Entity1",
            EntityKind::Class,
            "Entity1",
            None,
            None,
            "java",
            "/test.java",
            10,
            20,
            None,
            "test-repo",
        );
        let entity2 = ParsedEntity::new(
            "Entity2",
            EntityKind::Method,
            "Entity2",
            None,
            None,
            "java",
            "/test.java",
            30,
            40,
            None,
            "test-repo",
        );

        let entities = vec![entity1, entity2];

        // Target line 50 is after both entities, should be assigned to closest (entity2)
        let idx = find_nearest_entity_by_line(&entities, 50);
        assert_eq!(idx, 1);
    }

    #[test]
    fn test_find_nearest_entity_by_line_before_all() {
        let entity1 = ParsedEntity::new(
            "Entity1",
            EntityKind::Class,
            "Entity1",
            None,
            None,
            "java",
            "/test.java",
            10,
            20,
            None,
            "test-repo",
        );
        let entity2 = ParsedEntity::new(
            "Entity2",
            EntityKind::Method,
            "Entity2",
            None,
            None,
            "java",
            "/test.java",
            30,
            40,
            None,
            "test-repo",
        );

        let entities = vec![entity1, entity2];

        // Target line 5 is before all entities, should be assigned to closest (entity1)
        let idx = find_nearest_entity_by_line(&entities, 5);
        assert_eq!(idx, 0);
    }

    #[test]
    fn test_find_nearest_entity_containment_preferred() {
        // Entity1 spans lines 10-20, Entity2 spans lines 30-40
        let entity1 = ParsedEntity::new(
            "Entity1",
            EntityKind::Class,
            "Entity1",
            None,
            None,
            "java",
            "/test.java",
            10,
            20,
            None,
            "test-repo",
        );
        let entity2 = ParsedEntity::new(
            "Entity2",
            EntityKind::Method,
            "Entity2",
            None,
            None,
            "java",
            "/test.java",
            30,
            40,
            None,
            "test-repo",
        );

        let entities = vec![entity1, entity2];

        // Target line 15 is CONTAINED in entity1 (10-20), should return index 0
        // even though it's closer to entity2's start (30)
        let idx = find_nearest_entity_by_line(&entities, 15);
        assert_eq!(
            idx, 0,
            "Line 15 should be assigned to entity1 (contained in 10-20)"
        );
    }

    #[test]
    fn test_find_nearest_entity_containment_chooses_smallest_range() {
        // Entity1 spans lines 5-50 (large range), Entity2 spans lines 20-30 (small range)
        let entity1 = ParsedEntity::new(
            "Entity1",
            EntityKind::Class,
            "Entity1",
            None,
            None,
            "java",
            "/test.java",
            5,
            50,
            None,
            "test-repo",
        );
        let entity2 = ParsedEntity::new(
            "Entity2",
            EntityKind::Method,
            "Entity2",
            None,
            None,
            "java",
            "/test.java",
            20,
            30,
            None,
            "test-repo",
        );

        let entities = vec![entity1, entity2];

        // Target line 25 is contained in both entities, should prefer entity2 (smallest range)
        let idx = find_nearest_entity_by_line(&entities, 25);
        assert_eq!(
            idx, 1,
            "Line 25 should be assigned to entity2 (smallest containing range)"
        );
    }
}