tldr-core 0.2.4

Core analysis engine for TLDR code analysis tool
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
//! Java-specific API surface extraction.
//!
//! Java surfaces only `public` declarations by default. When `include_private`
//! is set, package-private, protected, and private members are also returned.

use std::path::{Path, PathBuf};

use crate::ast::extract::extract_from_tree;
use crate::ast::parser::parse;
use crate::types::{ClassInfo, Language};
use crate::TldrResult;

use super::language_profile::strip_layout_segments;
use super::triggers::extract_triggers;
use super::types::{ApiEntry, ApiKind, ApiSurface, Location, Param, ResolvedPackage, Signature};

/// Extract the public Java API surface for a resolved package.
pub fn extract_java_api_surface(
    resolved: &ResolvedPackage,
    include_private: bool,
    limit: Option<usize>,
) -> TldrResult<ApiSurface> {
    let mut apis = Vec::new();

    for file_path in find_java_files(&resolved.root_dir) {
        apis.extend(extract_from_java_file(
            &file_path,
            &resolved.root_dir,
            &resolved.package_name,
            include_private,
        )?);
    }

    if let Some(max) = limit {
        apis.truncate(max);
    }

    let total = apis.len();
    Ok(ApiSurface {
        package: resolved.package_name.clone(),
        language: "java".to_string(),
        total,
        apis,
    })
}

fn find_java_files(dir: &Path) -> Vec<PathBuf> {
    if dir.is_file() {
        return dir
            .extension()
            .and_then(|ext| ext.to_str())
            .filter(|ext| *ext == "java")
            .map(|_| vec![dir.to_path_buf()])
            .unwrap_or_default();
    }

    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                    if !name.starts_with('.') {
                        files.extend(find_java_files(&path));
                    }
                }
            } else if path.extension().and_then(|ext| ext.to_str()) == Some("java") {
                files.push(path);
            }
        }
    }
    files.sort();
    files
}

fn extract_from_java_file(
    file_path: &Path,
    root_dir: &Path,
    package_name: &str,
    include_private: bool,
) -> TldrResult<Vec<ApiEntry>> {
    let source = std::fs::read_to_string(file_path).map_err(|e| {
        crate::error::TldrError::parse_error(
            file_path.to_path_buf(),
            None,
            format!("Cannot read: {}", e),
        )
    })?;

    let tree = parse(&source, Language::Java)?;
    let module_info = extract_from_tree(&tree, &source, Language::Java, file_path, Some(root_dir))?;
    let module_path = compute_java_module_path(file_path, root_dir, package_name);
    let relative_path = file_path
        .strip_prefix(root_dir)
        .unwrap_or(file_path)
        .to_path_buf();

    let mut apis = Vec::new();

    for class in &module_info.classes {
        if !include_private && !is_java_public_at_line(&source, class.line_number as usize) {
            continue;
        }

        let qualified_name = format!("{}.{}", module_path, class.name);
        let kind = determine_java_kind(class, &source);
        let is_interface = kind == ApiKind::Interface;

        apis.push(ApiEntry {
            qualified_name: qualified_name.clone(),
            kind,
            module: module_path.clone(),
            signature: None,
            docstring: class.docstring.clone().map(|doc| truncate_docstring(&doc)),
            example: Some(generate_java_type_example(&class.name, kind)),
            triggers: extract_triggers(&class.name, class.docstring.as_deref()),
            is_property: false,
            return_type: None,
            location: Some(Location {
                file: relative_path.clone(),
                line: class.line_number as usize,
                column: None,
            }),
        });

        for method in &class.methods {
            // Interface methods are implicitly public in Java — no modifier
            // needed. Bypass the per-method visibility check when the enclosing
            // type is an interface. Mirrors rust_lang.rs:L174-L180 trait pattern.
            if !include_private
                && !is_interface
                && !is_java_public_at_line(&source, method.line_number as usize)
            {
                continue;
            }

            let params = convert_java_params(&method.params);
            let return_type = method.return_type.clone();
            let kind = if line_contains_word(&source, method.line_number as usize, "static") {
                ApiKind::StaticMethod
            } else {
                ApiKind::Method
            };

            apis.push(ApiEntry {
                qualified_name: format!("{}.{}", qualified_name, method.name),
                kind,
                module: module_path.clone(),
                signature: Some(Signature {
                    params: params.clone(),
                    return_type: return_type.clone(),
                    is_async: false,
                    is_generator: false,
                }),
                docstring: method.docstring.clone().map(|doc| truncate_docstring(&doc)),
                example: Some(generate_java_method_example(
                    &class.name,
                    &method.name,
                    &params,
                )),
                triggers: extract_triggers(&method.name, method.docstring.as_deref()),
                is_property: false,
                return_type,
                location: Some(Location {
                    file: relative_path.clone(),
                    line: method.line_number as usize,
                    column: None,
                }),
            });
        }

        for field in &class.fields {
            let is_public = field.visibility.as_deref() == Some("public");
            if !include_private && !is_public {
                continue;
            }

            apis.push(ApiEntry {
                qualified_name: format!("{}.{}", qualified_name, field.name),
                kind: if field.is_constant {
                    ApiKind::Constant
                } else {
                    ApiKind::Property
                },
                module: module_path.clone(),
                signature: None,
                docstring: None,
                example: Some(format!("{}.{}", class.name, field.name)),
                triggers: extract_triggers(&field.name, None),
                is_property: !field.is_constant,
                return_type: field.field_type.clone(),
                location: Some(Location {
                    file: relative_path.clone(),
                    line: field.line_number as usize,
                    column: None,
                }),
            });
        }
    }

    Ok(apis)
}

fn compute_java_module_path(file_path: &Path, root_dir: &Path, package_name: &str) -> String {
    let relative = file_path.strip_prefix(root_dir).unwrap_or(file_path);
    let parent = relative.parent().unwrap_or_else(|| Path::new(""));
    let parts: Vec<String> = parent
        .iter()
        .map(|part| part.to_string_lossy().to_string())
        .collect();
    let parts = strip_layout_segments(Language::Java, Path::new(&parts.join("/")));

    if parts.is_empty() {
        package_name.to_string()
    } else {
        format!("{}.{}", package_name, parts.join("."))
    }
}

fn is_java_public_at_line(source: &str, line_number: usize) -> bool {
    line_contains_word(source, line_number, "public")
}

fn line_contains_word(source: &str, line_number: usize, word: &str) -> bool {
    source
        .lines()
        .nth(line_number.saturating_sub(1))
        .map(|line| {
            line.split(|ch: char| !ch.is_alphanumeric() && ch != '_')
                .any(|part| part == word)
        })
        .unwrap_or(false)
}

fn determine_java_kind(class: &ClassInfo, source: &str) -> ApiKind {
    let line = source
        .lines()
        .nth(class.line_number.saturating_sub(1) as usize)
        .unwrap_or("");

    if line.contains(" interface ") || line.trim_start().starts_with("interface ") {
        ApiKind::Interface
    } else if line.contains(" enum ") || line.trim_start().starts_with("enum ") {
        ApiKind::Enum
    } else {
        ApiKind::Class
    }
}

fn convert_java_params(raw_params: &[String]) -> Vec<Param> {
    raw_params
        .iter()
        .filter(|param| !param.is_empty())
        .map(|param| Param {
            name: param.clone(),
            type_annotation: None,
            default: None,
            is_variadic: false,
            is_keyword: false,
        })
        .collect()
}

fn truncate_docstring(doc: &str) -> String {
    let first_para = doc.split("\n\n").next().unwrap_or(doc);
    let cleaned = first_para
        .replace("/**", "")
        .replace("*/", "")
        .lines()
        .map(|line| line.trim().trim_start_matches('*').trim())
        .collect::<Vec<_>>()
        .join(" ");

    if cleaned.len() <= 200 {
        cleaned
    } else {
        format!(
            "{}...",
            crate::util::truncate_at_char_boundary(&cleaned, 197)
        )
    }
}

fn generate_java_type_example(name: &str, kind: ApiKind) -> String {
    match kind {
        ApiKind::Interface => format!("{} value = null;", name),
        ApiKind::Enum => format!("{} value = {}.values()[0];", name, name),
        _ => format!("{} value = new {}();", name, name),
    }
}

fn generate_java_method_example(class_name: &str, method_name: &str, params: &[Param]) -> String {
    let args = params
        .iter()
        .map(|param| param.name.clone())
        .collect::<Vec<_>>()
        .join(", ");
    format!("new {}().{}({})", class_name, method_name, args)
}

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

    fn write_file(dir: &TempDir, rel: &str, source: &str) {
        let path = dir.path().join(rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, source).unwrap();
    }

    #[test]
    fn test_truncate_docstring_handles_unicode_char_boundaries() {
        // 67 × 3-byte char (U+2500) = 201 bytes. Pre-fix: panic at
        // `&cleaned[..197]` (197 % 3 = 2 → mid-codepoint). Post-fix: snap
        // down to the largest char-boundary <= 197 (= 195 bytes = 65 chars).
        let doc = "".repeat(67);
        let truncated = truncate_docstring(&doc);
        assert!(truncated.ends_with("..."));
        assert!(std::str::from_utf8(truncated.as_bytes()).is_ok());
        assert_eq!(truncated, format!("{}...", "".repeat(65)));
    }

    #[test]
    fn test_find_java_files_recurses() {
        let dir = TempDir::new().unwrap();
        write_file(
            &dir,
            "src/main/java/com/example/App.java",
            "public class App {}",
        );
        write_file(
            &dir,
            "src/test/java/com/example/AppTest.java",
            "class AppTest {}",
        );

        let files = find_java_files(dir.path());
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_extract_java_surface_filters_package_private_members() {
        let dir = TempDir::new().unwrap();
        write_file(
            &dir,
            "src/main/java/com/example/Greeter.java",
            r#"
public class Greeter {
    public static final String VERSION = "1";
    String hidden = "no";

    public String hello(String name) {
        return name;
    }

    String secret(String token) {
        return token;
    }
}
"#,
        );

        let resolved = ResolvedPackage {
            root_dir: dir.path().to_path_buf(),
            package_name: "example".to_string(),
            is_pure_source: true,
            public_names: None,
        };

        let surface = extract_java_api_surface(&resolved, false, None).unwrap();
        let names: Vec<&str> = surface
            .apis
            .iter()
            .map(|api| api.qualified_name.as_str())
            .collect();

        assert!(names.iter().any(|name| name.ends_with("Greeter")));
        assert!(names.iter().any(|name| name.ends_with("Greeter.hello")));
        assert!(names.iter().any(|name| name.ends_with("Greeter.VERSION")));
        assert!(!names.iter().any(|name| name.ends_with("Greeter.secret")));
        assert!(!names.iter().any(|name| name.ends_with("Greeter.hidden")));
    }

    #[test]
    fn test_extract_java_surface_includes_non_public_when_requested() {
        let dir = TempDir::new().unwrap();
        write_file(
            &dir,
            "src/main/java/com/example/Helper.java",
            r#"
class Helper {
    String value() {
        return "ok";
    }
}
"#,
        );

        let resolved = ResolvedPackage {
            root_dir: dir.path().to_path_buf(),
            package_name: "example".to_string(),
            is_pure_source: true,
            public_names: None,
        };

        let surface = extract_java_api_surface(&resolved, true, None).unwrap();
        assert!(surface
            .apis
            .iter()
            .any(|api| api.qualified_name.ends_with("Helper.value")));
    }

    #[test]
    fn test_compute_java_module_path_strips_nested_src_main_java_prefix() {
        let root = Path::new("/repo");
        let file = Path::new("/repo/module-a/src/main/java/com/example/http/Client.java");

        assert_eq!(
            compute_java_module_path(file, root, "example_pkg"),
            "example_pkg.module-a.com.example.http"
        );
    }

    #[test]
    fn test_extract_java_surface_interface_methods_are_public_by_default() {
        let dir = TempDir::new().unwrap();
        write_file(
            &dir,
            "src/main/java/com/example/IService.java",
            r#"
public interface IService {
    void execute();
    String getName();
    int compute(int x);
}
"#,
        );

        let resolved = ResolvedPackage {
            root_dir: dir.path().to_path_buf(),
            package_name: "example".to_string(),
            is_pure_source: true,
            public_names: None,
        };

        // include_private = false — without the fix, interface methods are filtered out.
        let surface = extract_java_api_surface(&resolved, false, None).unwrap();
        let names: Vec<&str> = surface
            .apis
            .iter()
            .map(|api| api.qualified_name.as_str())
            .collect();

        assert!(
            names.iter().any(|n| n.ends_with("IService")),
            "Interface type should be in surface: {:?}",
            names
        );
        assert!(
            names.iter().any(|n| n.ends_with("IService.execute")),
            "execute should be in surface: {:?}",
            names
        );
        assert!(
            names.iter().any(|n| n.ends_with("IService.getName")),
            "getName should be in surface: {:?}",
            names
        );
        assert!(
            names.iter().any(|n| n.ends_with("IService.compute")),
            "compute should be in surface: {:?}",
            names
        );
    }
}