knot 1.16.2

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
//! Groovy language support (`.groovy`) — hybrid lexical parser.
//!
//! tree-sitter-groovy (v0.1.2) query compilation is unreliable on CI runners
//! with tree-sitter 0.26 (disabled since v1.2.0), so entity extraction is
//! driven by an ad-hoc lexical parser that provides equivalent entity coverage
//! (classes, interfaces, enums, traits, methods, properties) plus scope
//! tracking and reference-intent extraction not available via tree-sitter
//! alone. [`capture`] stays wired for the query-driven path and the `.scm`
//! contract tests.
//!
//! Submodules group the pipeline by responsibility:
//!
//! | Submodule       | Responsibility |
//! |-----------------|----------------|
//! | [`capture`]     | Tree-sitter capture name → entity mapping |
//! | [`inheritance`] | Type declarations (`class`/`interface`/`enum`/`trait`) and `extends` / `implements` intents |
//! | [`methods`]     | `def` / typed / multi-line method detection and body-extent fixup |
//! | [`properties`]  | Property, field and script-variable detection |
//! | [`accessors`]   | Synthetic getter/setter emission for properties |
//! | [`refs`]        | Method-call reference-intent scanning |
//! | [`utils`]       | Comment stripping, FQN construction, GroovyDoc extraction, validators |

mod accessors;
mod capture;
mod inheritance;
mod methods;
mod properties;
mod refs;
mod utils;

#[cfg(test)]
mod tests;

pub(crate) use capture::handle_groovy_capture;

use crate::models::{EntityKind, ParsedEntity, ReferenceIntent};

use accessors::synthesize_property_accessors;
use inheritance::{
    build_type_declaration, extract_inheritance_intents, try_extract_type_declaration,
};
use methods::{
    find_method_body_end, try_extract_def_method, try_extract_typed_method,
    try_extract_typed_method_multiline,
};
use properties::{GroovyPropertyDecl, try_extract_property};
use refs::{body_on_declaration_line, extract_method_calls, scan_line_for_calls};
use utils::{build_fqn, extract_package, extract_preceding_docstring, strip_comments_line};

/// Extracts entities from a Groovy source file with the ad-hoc lexical parser.
pub(crate) fn extract_entities_groovy(
    source: &str,
    file_path: &str,
    repo_name: &str,
) -> Vec<ParsedEntity> {
    // tree-sitter-groovy (v0.1.2) query compilation fails intermittently on CI
    // runners with tree-sitter 0.26. The ad-hoc lexical parser provides equivalent
    // entity coverage (classes, interfaces, enums, traits, methods, properties) plus
    // scope tracking and reference intent extraction not available via tree-sitter alone.
    let mut entities: Vec<ParsedEntity> = vec![];

    // Extract package declaration
    let package = extract_package(source);

    // Keep track of lines where entities were found to avoid duplicates
    let mut known_lines = std::collections::HashSet::new();

    // Post-process entities from Tree-sitter
    postprocess_tree_sitter_entities(&mut entities, source, &package, &mut known_lines);

    let mut scan = GroovyScan {
        source,
        file_path,
        repo_name,
        package: &package,
        lines: source.lines().collect(),
        known_lines,
        scope_stack: Vec::new(),
        brace_count: 0,
        in_block_comment: false,
        prop_decls: std::collections::HashMap::new(),
        entities,
    };

    for (line_idx, line) in source.lines().enumerate() {
        scan.process_line(line_idx, line);
    }

    let GroovyScan {
        mut entities,
        prop_decls,
        ..
    } = scan;

    // Fix end_line for all methods (both tree-sitter and ad-hoc) that
    // couldn't determine their body closing line.
    fix_method_end_lines(&mut entities, source);

    // Phase 3: emit synthetic accessor entities for Groovy properties
    // so OVERRIDES linking can match against interface getters/setters.
    synthesize_property_accessors(&mut entities, &package, file_path, repo_name, &prop_decls);

    // Extract reference intents: for each method, scan source lines after its signature
    assign_method_call_references(source, &mut entities);

    entities
}

/// Marks lines claimed by tree-sitter entities, fixes the `trait` misparse
/// and sets package-qualified FQNs for type entities.
fn postprocess_tree_sitter_entities(
    entities: &mut [ParsedEntity],
    source: &str,
    package: &Option<String>,
    known_lines: &mut std::collections::HashSet<usize>,
) {
    for entity in entities.iter_mut() {
        known_lines.insert(entity.start_line);

        // Fix: tree-sitter-groovy parses `trait` as `class_declaration`.
        if entity.kind == EntityKind::GroovyClass
            && let Some(line_content) = source.lines().nth(entity.start_line.saturating_sub(1))
        {
            let trimmed = line_content.trim();
            if trimmed.starts_with("trait ") || trimmed.contains(" trait ") {
                entity.kind = EntityKind::GroovyTrait;
            }
        }

        // Set FQN for tree-sitter entities
        if let Some(pkg) = package {
            entity.fqn = match entity.kind {
                EntityKind::GroovyClass
                | EntityKind::GroovyInterface
                | EntityKind::GroovyTrait
                | EntityKind::GroovyEnum => format!("{}.{}", pkg, entity.name),
                _ => continue,
            };
        }
    }
}

/// State threaded through the ad-hoc line scan: scope tracking for
/// `enclosing_class`, the line registry claimed by tree-sitter, and the
/// property side-car needed for accessor synthesis.
struct GroovyScan<'a> {
    source: &'a str,
    file_path: &'a str,
    repo_name: &'a str,
    package: &'a Option<String>,
    /// Materialized once: docstring extraction walks backwards from each
    /// declaration and must not pay O(n²) re-scanning the source per entity.
    lines: Vec<&'a str>,
    known_lines: std::collections::HashSet<usize>,
    /// Scope stack: (name, brace_count_when_entered)
    scope_stack: Vec<(String, usize)>,
    brace_count: usize,
    in_block_comment: bool,
    /// Side-car: property metadata needed for accessor synthesis (Phase 3).
    prop_decls: std::collections::HashMap<(String, String), GroovyPropertyDecl>,
    entities: Vec<ParsedEntity>,
}

impl<'a> GroovyScan<'a> {
    /// Ad-hoc extraction with scope tracking for `enclosing_class`.
    fn process_line(&mut self, line_idx: usize, line: &'a str) {
        let line_num = line_idx + 1;

        let effective = strip_comments_line(line, &mut self.in_block_comment);

        // Track braces on the effective (code-bearing) line only.
        let opened = effective.matches('{').count();
        let closed = effective.matches('}').count();
        let prev_brace_count = self.brace_count;
        self.brace_count += opened;

        let mut early_pop = false;
        if closed > opened {
            let temp_brace = self.brace_count.saturating_sub(closed);
            while let Some((_, entry_brace)) = self.scope_stack.last() {
                if temp_brace < *entry_brace {
                    self.scope_stack.pop();
                    early_pop = true;
                } else {
                    break;
                }
            }
        }

        if effective.is_empty() {
            return;
        }

        // Try to extract class/interface/enum/trait if tree-sitter missed it
        self.try_type_declaration(effective.as_ref(), line_num);

        // Re-read enclosing after potential scope push
        let enclosing = self.scope_stack.last().map(|(n, _)| n.clone());

        // Ad-hoc method/field/closure extraction only if tree-sitter didn't
        // already find an entity at this line. A consumed line skips property
        // extraction and the trailing brace/scope update (original `continue`).
        if self.try_methods(effective.as_ref(), line_num, &enclosing) {
            return;
        }

        self.try_property(effective.as_ref(), line_num, &enclosing, prev_brace_count);

        self.brace_count = self.brace_count.saturating_sub(closed);
        if !early_pop {
            while let Some((_, entry_brace)) = self.scope_stack.last() {
                if self.brace_count < *entry_brace {
                    self.scope_stack.pop();
                } else {
                    break;
                }
            }
        }
    }

    /// Extracts class/interface/enum/trait declarations tree-sitter missed.
    fn try_type_declaration(&mut self, effective: &str, line_num: usize) {
        if !self.known_lines.contains(&line_num)
            && let Some((name, kind)) = try_extract_type_declaration(effective)
        {
            // Push to scope stack BEFORE brace_count is updated for the current line's `{`
            let fqn = if let Some(pkg) = self.package {
                format!("{}.{}", pkg, name)
            } else {
                name.clone()
            };
            let current_brace = self.brace_count;
            // Build a multi-line declaration so that `extends X` / `implements Y`
            // on a following line still feed `extract_inheritance_intents`.
            // Falls back to the single trimmed line when no `{` is in the
            // lookahead window.
            let decl_text = build_type_declaration(self.source, line_num - 1)
                .unwrap_or_else(|| effective.to_string());
            let inheritance_intents = extract_inheritance_intents(&decl_text, &kind, line_num);
            let docstring = extract_preceding_docstring(&self.lines, line_num - 1);
            let mut new_entity = ParsedEntity::new(
                &name,
                kind,
                &fqn,
                None,
                docstring,
                "groovy",
                self.file_path,
                line_num,
                line_num,
                None,
                self.repo_name,
            );
            new_entity.reference_intents.extend(inheritance_intents);
            self.entities.push(new_entity);
            self.scope_stack.push((name, current_brace));
        }
    }

    /// Tries the three method-extraction heuristics (def, typed single-line,
    /// typed multi-line). Returns `true` when the line was consumed — the
    /// caller then skips property extraction and the trailing brace/scope
    /// update, mirroring the original `continue` paths.
    fn try_methods(
        &mut self,
        effective: &str,
        line_num: usize,
        enclosing: &Option<String>,
    ) -> bool {
        // Ad-hoc method/field/closure extraction only if tree-sitter didn't already find an entity at this line
        if self.known_lines.contains(&line_num) {
            return false;
        }
        let line_idx = line_num - 1;

        // Try to find a `def` method declaration
        if let Some((method_name, signature)) = try_extract_def_method(effective) {
            let fqn = build_fqn(self.package, enclosing, &method_name);
            let docstring = extract_preceding_docstring(&self.lines, line_idx);
            self.entities.push(ParsedEntity::new(
                &method_name,
                EntityKind::GroovyMethod,
                &fqn,
                Some(signature),
                docstring,
                "groovy",
                self.file_path,
                line_num,
                line_num,
                enclosing.clone(),
                self.repo_name,
            ));
            return true;
        }

        // Try to find typed methods or script-level methods missed by tree-sitter
        // First, try single-line detection
        if let Some((method_name, _signature)) = try_extract_typed_method(effective) {
            // Filter false positives: method names that contain dots or look like object.method()
            if method_name.contains('.')
                || method_name.chars().all(|c| c.is_uppercase() || c == '_')
            {
                // False positive — still consume the line (original `continue`)
                return true;
            }
            let sig_end = effective.find('{').unwrap_or(effective.len());
            let signature_full = effective[..sig_end].trim().to_string();
            let fqn = build_fqn(self.package, enclosing, &method_name);
            let docstring = extract_preceding_docstring(&self.lines, line_idx);
            self.entities.push(ParsedEntity::new(
                &method_name,
                EntityKind::GroovyMethod,
                &fqn,
                Some(signature_full),
                docstring,
                "groovy",
                self.file_path,
                line_num,
                line_num,
                enclosing.clone(),
                self.repo_name,
            ));
            return true;
        }

        // Multi-line method detection: method signature with `(` but no `)` on this line,
        // spanning multiple lines (e.g., closure default parameter values)
        if let Some((method_name, method_start_line)) =
            try_extract_typed_method_multiline(self.source, line_idx)
            && !method_name.contains('.')
        {
            let fqn = build_fqn(self.package, enclosing, &method_name);
            // The docstring sits above the first line of the signature
            // (method_start_line is 1-based → subtract 1 for the 0-based index).
            let docstring = extract_preceding_docstring(&self.lines, method_start_line - 1);
            self.entities.push(ParsedEntity::new(
                &method_name,
                EntityKind::GroovyMethod,
                &fqn,
                None,
                docstring,
                "groovy",
                self.file_path,
                method_start_line,
                line_num,
                enclosing.clone(),
                self.repo_name,
            ));
            return true;
        }

        false
    }

    /// Extracts properties or script-level variables. Gated at type-body
    /// depth, or at script level when no enclosing type is in scope.
    /// `at_type_body_depth` uses the post-increment brace_count so that a
    /// single-line class declaration (`class Foo { String name }`) matches:
    /// the type's `{` opens before the body's `at_type_body_depth` check
    /// happens on the same line. `at_script_level` uses `prev_brace_count ==
    /// 0` so that a script-level property declaring a closure literal on the
    /// same line (`def foo = { ... }`) also matches.
    fn try_property(
        &mut self,
        effective: &str,
        line_num: usize,
        enclosing: &Option<String>,
        prev_brace_count: usize,
    ) {
        let at_type_body_depth = self
            .scope_stack
            .last()
            .is_some_and(|(_, entry_brace)| self.brace_count == *entry_brace);
        let at_script_level = self.scope_stack.is_empty() && prev_brace_count == 0;

        if !(at_type_body_depth || at_script_level) || self.known_lines.contains(&line_num) {
            return;
        }
        let Some(prop_decl) = try_extract_property(effective) else {
            return;
        };
        self.push_property(prop_decl, line_num, enclosing);
    }

    /// Pushes one property entity and registers it in the accessor-synthesis
    /// side-car keyed by (enclosing type, property name).
    fn push_property(
        &mut self,
        prop_decl: GroovyPropertyDecl,
        line_num: usize,
        enclosing: &Option<String>,
    ) {
        let fqn = build_fqn(self.package, enclosing, &prop_decl.name);
        let docstring = extract_preceding_docstring(&self.lines, line_num - 1);
        let enclosing_for_prop = enclosing.clone();
        let name_clone = prop_decl.name.clone();
        let enc_clone = enclosing_for_prop.clone();
        self.entities.push(ParsedEntity::new(
            &prop_decl.name,
            EntityKind::GroovyProperty,
            &fqn,
            None,
            docstring,
            "groovy",
            self.file_path,
            line_num,
            line_num,
            enclosing_for_prop,
            self.repo_name,
        ));
        if let Some(enc) = enc_clone {
            self.prop_decls.insert((enc, name_clone), prop_decl);
        }
    }
}

/// Fix end_line for all methods (both tree-sitter and ad-hoc) that couldn't
/// determine their body closing line.
fn fix_method_end_lines(entities: &mut [ParsedEntity], source: &str) {
    for entity in entities.iter_mut() {
        if entity.kind == EntityKind::GroovyMethod
            && entity.end_line == entity.start_line
            && let Some(end_line) = find_method_body_end(source, entity.start_line)
            && end_line > entity.start_line
        {
            entity.end_line = end_line;
        }
    }
}

/// Extracts call reference intents and assigns each to the innermost
/// containing method. When methods are nested (e.g., hyperlinkUpdate inside
/// showGrabbingFinishedMessage), the call is assigned to the deepest method,
/// not the outer container.
///
/// Calls carry a line but no column, so a call on a method's declaration
/// line cannot be told apart from the declaration itself (its own name,
/// typed parameters that read like command calls). Those lines are skipped
/// and only the body text opening on them is rescanned, so one-line methods
/// keep their calls (issue #40).
fn assign_method_call_references(source: &str, entities: &mut [ParsedEntity]) {
    let mut method_spans: Vec<(usize, usize, usize)> = entities
        .iter()
        .enumerate()
        .filter(|(_, e)| {
            matches!(
                e.kind,
                EntityKind::GroovyMethod | EntityKind::GroovyFunction
            )
        })
        .map(|(i, e)| (e.start_line, e.end_line, i))
        .collect();
    method_spans.sort_by_key(|(s, _, _)| *s);

    let refs = extract_method_calls(source, entities);

    for method_ref in refs {
        if let ReferenceIntent::Call { line, .. } = method_ref
            && let Some(m_eidx) = innermost_method(&method_spans, line)
            && entities[m_eidx].start_line != line
        {
            entities[m_eidx].reference_intents.push(method_ref);
        }
    }

    let lines: Vec<&str> = source.lines().collect();
    for &(start, _, m_eidx) in &method_spans {
        let Some(body) = lines
            .get(start.wrapping_sub(1))
            .and_then(|line| body_on_declaration_line(line, &entities[m_eidx].name))
        else {
            continue;
        };
        let mut calls = Vec::new();
        scan_line_for_calls(body.trim(), start, &mut calls);
        entities[m_eidx].reference_intents.extend(calls);
    }
}

/// The innermost method span containing `line` (smallest `end - start`;
/// the earliest start among equal spans).
fn innermost_method(method_spans: &[(usize, usize, usize)], line: usize) -> Option<usize> {
    method_spans
        .iter()
        .filter(|(start, end, _)| line >= *start && line <= *end)
        .min_by_key(|(start, end, _)| end.saturating_sub(*start))
        .map(|&(_, _, idx)| idx)
}