scope-cli 0.9.2

Code intelligence CLI for LLM coding agents — structural navigation, dependency graphs, and semantic search without reading full source files
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
/// Java-specific metadata extraction and language plugin.
///
/// Extracts access modifiers (public, protected, private, package-private),
/// Java-specific modifiers (static, final, abstract, synchronized),
/// annotations, return type, parameters, and throws declarations from
/// Java AST nodes.
use anyhow::Result;
use serde::Serialize;
use std::collections::HashMap;
use tree_sitter::Language;

use crate::core::graph::Edge;
use crate::core::parser::SupportedLanguage;
use crate::languages::{make_edge, resolve_scope_id, LanguagePlugin};

/// Java language plugin.
pub struct JavaPlugin;

impl LanguagePlugin for JavaPlugin {
    fn language(&self) -> SupportedLanguage {
        SupportedLanguage::Java
    }

    fn extensions(&self) -> &[&str] {
        &["java"]
    }

    fn ts_language(&self) -> Language {
        tree_sitter_java::language()
    }

    fn symbol_query_source(&self) -> &str {
        include_str!("../queries/java/symbols.scm")
    }

    fn edge_query_source(&self) -> &str {
        include_str!("../queries/java/edges.scm")
    }

    fn infer_symbol_kind(&self, node_kind: &str) -> &str {
        match node_kind {
            "class_declaration" => "class",
            "interface_declaration" => "interface",
            "enum_declaration" => "enum",
            "record_declaration" => "class",
            "method_declaration" => "method",
            "constructor_declaration" => "method",
            "field_declaration" => "property",
            "annotation_type_declaration" => "type",
            "enum_constant" => "variant",
            _ => "function",
        }
    }

    fn scope_node_types(&self) -> &[&str] {
        &[
            "class_declaration",
            "interface_declaration",
            "enum_declaration",
            "method_declaration",
            "constructor_declaration",
            "lambda_expression",
        ]
    }

    fn class_body_node_types(&self) -> &[&str] {
        &["class_body", "interface_body", "enum_body"]
    }

    fn class_decl_node_types(&self) -> &[&str] {
        &[
            "class_declaration",
            "interface_declaration",
            "enum_declaration",
        ]
    }

    fn extract_metadata(
        &self,
        node: &tree_sitter::Node,
        source: &str,
        kind: &str,
    ) -> Result<String> {
        extract_metadata(node, source, kind)
    }

    fn extract_edge(
        &self,
        pattern_index: usize,
        captures: &HashMap<String, (String, u32)>,
        file_path: &str,
        enclosing_scope_id: Option<&str>,
    ) -> Vec<Edge> {
        extract_java_edge(pattern_index, captures, file_path, enclosing_scope_id)
    }

    fn extract_docstring(&self, node: &tree_sitter::Node, source: &str) -> Option<String> {
        // Java uses block comments (/** ... */) as Javadoc, which tree-sitter
        // represents as `block_comment` or `line_comment` preceding siblings.
        let prev = node.prev_sibling()?;
        match prev.kind() {
            "block_comment" | "line_comment" => {
                let text = prev.utf8_text(source.as_bytes()).ok()?;
                Some(text.trim().to_string())
            }
            _ => None,
        }
    }

    fn generic_name_stopwords(&self) -> &[&str] {
        &[
            "toString", "hashCode", "equals", "get", "set", "of", "main", "run", "close",
        ]
    }
}

/// Structured metadata for a Java symbol.
#[derive(Debug, Clone, Serialize, Default)]
pub struct JavaMetadata {
    /// Access modifier: "public", "protected", "private", or "package".
    pub access: String,
    /// Whether the symbol is static.
    pub is_static: bool,
    /// Whether the symbol is final.
    pub is_final: bool,
    /// Whether the symbol is abstract.
    pub is_abstract: bool,
    /// Whether the symbol is synchronized.
    pub is_synchronized: bool,
    /// Annotations on this symbol (e.g., "Override", "Deprecated", "Autowired").
    pub annotations: Vec<String>,
    /// Return type, if present (for methods).
    pub return_type: Option<String>,
    /// Parameter list with names and types.
    pub parameters: Vec<JavaParameterInfo>,
    /// Checked exceptions declared in throws clause.
    pub throws: Vec<String>,
}

/// Information about a single Java method/constructor parameter.
#[derive(Debug, Clone, Serialize)]
pub struct JavaParameterInfo {
    /// Parameter name.
    pub name: String,
    /// Type annotation, if present.
    #[serde(rename = "type")]
    pub type_annotation: Option<String>,
    /// Whether the parameter is declared final.
    pub is_final: bool,
}

/// Extract metadata from a Java AST node.
///
/// Returns a JSON string suitable for the `metadata` column.
pub fn extract_metadata(node: &tree_sitter::Node, source: &str, kind: &str) -> Result<String> {
    let mut meta = JavaMetadata::default();

    // Walk direct children to find modifiers
    let mut child_cursor = node.walk();
    for child in node.children(&mut child_cursor) {
        if child.kind() == "modifiers" {
            let mut mod_cursor = child.walk();
            for mod_child in child.children(&mut mod_cursor) {
                match mod_child.kind() {
                    "public" => meta.access = "public".to_string(),
                    "protected" => meta.access = "protected".to_string(),
                    "private" => meta.access = "private".to_string(),
                    "static" => meta.is_static = true,
                    "final" => meta.is_final = true,
                    "abstract" => meta.is_abstract = true,
                    "synchronized" => meta.is_synchronized = true,
                    "marker_annotation" | "annotation" => {
                        if let Ok(text) = mod_child.utf8_text(source.as_bytes()) {
                            // Strip leading `@` and any arguments
                            let ann_name = text
                                .trim_start_matches('@')
                                .split('(')
                                .next()
                                .unwrap_or("")
                                .trim()
                                .to_string();
                            if !ann_name.is_empty() {
                                meta.annotations.push(ann_name);
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    // Default access if none was set — Java defaults to package-private
    if meta.access.is_empty() {
        meta.access = "package".to_string();
    }

    // Extract return type (for method_declaration)
    if kind == "method" {
        if let Some(type_node) = node.child_by_field_name("type") {
            if let Ok(text) = type_node.utf8_text(source.as_bytes()) {
                meta.return_type = Some(text.trim().to_string());
            }
        }
    }

    // Extract parameters
    if kind == "method" {
        if let Some(params_node) = node.child_by_field_name("parameters") {
            meta.parameters = extract_parameters(&params_node, source);
        }
    }

    // Extract throws clause
    let mut throws_cursor = node.walk();
    for child in node.children(&mut throws_cursor) {
        if child.kind() == "throws" {
            let mut tc = child.walk();
            for throw_child in child.children(&mut tc) {
                if throw_child.kind() == "type_identifier" {
                    if let Ok(text) = throw_child.utf8_text(source.as_bytes()) {
                        meta.throws.push(text.trim().to_string());
                    }
                }
            }
        }
    }

    let json = serde_json::to_string(&meta)?;
    Ok(json)
}

/// Extract parameter info from a formal_parameters node.
fn extract_parameters(params_node: &tree_sitter::Node, source: &str) -> Vec<JavaParameterInfo> {
    let mut params = Vec::new();
    let mut cursor = params_node.walk();

    for child in params_node.children(&mut cursor) {
        if child.kind() == "formal_parameter" || child.kind() == "spread_parameter" {
            let name = child
                .child_by_field_name("name")
                .and_then(|n| n.utf8_text(source.as_bytes()).ok())
                .unwrap_or_default()
                .to_string();

            let type_annotation = child
                .child_by_field_name("type")
                .and_then(|n| n.utf8_text(source.as_bytes()).ok())
                .map(|t| t.trim().to_string());

            // Check for final modifier on the parameter
            let mut is_final = false;
            let mut param_cursor = child.walk();
            for param_child in child.children(&mut param_cursor) {
                if param_child.kind() == "modifiers" {
                    let mut mc = param_child.walk();
                    for m in param_child.children(&mut mc) {
                        if m.kind() == "final" {
                            is_final = true;
                        }
                    }
                }
            }

            if !name.is_empty() {
                params.push(JavaParameterInfo {
                    name,
                    type_annotation,
                    is_final,
                });
            }
        }
    }

    params
}

/// Java edge extraction by pattern index.
///
/// Pattern indices map to the order of patterns in `queries/java/edges.scm`:
/// 0 = import declaration, 1 = member method call, 2 = direct method call,
/// 3 = this.method() call, 4 = object creation (new), 5 = extends (superclass),
/// 6 = class implements, 7 = interface extends, 8 = field type ref, 9 = param type ref,
/// 10 = super.method() call, 11 = switch case enum constant ref
fn extract_java_edge(
    pattern: usize,
    captures: &HashMap<String, (String, u32)>,
    file_path: &str,
    enclosing_scope_id: Option<&str>,
) -> Vec<Edge> {
    let mut edges = Vec::new();

    let from_fn = resolve_scope_id(enclosing_scope_id, file_path, "function");
    let from_cls = resolve_scope_id(enclosing_scope_id, file_path, "class");

    match pattern {
        // Import declaration
        0 => {
            if let Some((imported_name, line)) = captures.get("imported_name") {
                edges.push(make_edge(
                    format!("{file_path}::__module__::function"),
                    imported_name,
                    "imports",
                    file_path,
                    *line,
                ));
            }
        }
        // Member method invocation (e.g. service.processPayment())
        1 => {
            if let (Some((object, line)), Some((method, _))) =
                (captures.get("object"), captures.get("method"))
            {
                edges.push(make_edge(
                    from_fn.clone(),
                    format!("{object}.{method}"),
                    "calls",
                    file_path,
                    *line,
                ));
            }
        }
        // Direct method invocation (e.g. processPayment())
        2 => {
            if let Some((callee, line)) = captures.get("callee") {
                edges.push(make_edge(
                    from_fn.clone(),
                    callee,
                    "calls",
                    file_path,
                    *line,
                ));
            }
        }
        // this.method() call — captures method name only
        // super.method() call — captures method name only
        3 | 10 => {
            if let Some((method, line)) = captures.get("method") {
                edges.push(make_edge(
                    from_fn.clone(),
                    method,
                    "calls",
                    file_path,
                    *line,
                ));
            }
        }
        // Object creation (new Foo())
        4 => {
            if let Some((class_name, line)) = captures.get("class_name") {
                edges.push(make_edge(
                    from_fn.clone(),
                    class_name,
                    "instantiates",
                    file_path,
                    *line,
                ));
            }
        }
        // Superclass (extends)
        5 => {
            if let Some((base_type, line)) = captures.get("base_type") {
                edges.push(make_edge(
                    from_cls.clone(),
                    base_type,
                    "extends",
                    file_path,
                    *line,
                ));
            }
        }
        // Class implements
        6 => {
            if let Some((base_type, line)) = captures.get("base_type") {
                edges.push(make_edge(
                    from_cls.clone(),
                    base_type,
                    "implements",
                    file_path,
                    *line,
                ));
            }
        }
        // Interface extends
        7 => {
            if let Some((base_type, line)) = captures.get("base_type") {
                edges.push(make_edge(
                    from_cls.clone(),
                    base_type,
                    "extends",
                    file_path,
                    *line,
                ));
            }
        }
        // Field / parameter type reference
        8 | 9 => {
            if let Some((type_ref, line)) = captures.get("type_ref") {
                edges.push(make_edge(
                    from_fn.clone(),
                    type_ref,
                    "references_type",
                    file_path,
                    *line,
                ));
            }
        }
        // Switch case label referencing an enum constant (e.g. case SUCCESS:)
        11 => {
            if let Some((variant_ref, line)) = captures.get("variant_ref") {
                edges.push(make_edge(
                    from_fn.clone(),
                    variant_ref,
                    "references",
                    file_path,
                    *line,
                ));
            }
        }
        _ => {}
    }

    edges
}