aptu_coder_core/lib.rs
1// SPDX-FileCopyrightText: 2026 aptu-coder contributors
2// SPDX-License-Identifier: Apache-2.0
3//! Multi-language code structure analysis library using tree-sitter.
4//!
5//! This crate provides core analysis functionality for extracting code structure
6//! from multiple programming languages. It is designed to be used as a library
7//! by MCP servers and other tools.
8//!
9//! # Features
10//!
11//! - **Language support**: Rust, Go, Java, Python, TypeScript, TSX, Fortran, JavaScript, C/C++, C# (feature-gated)
12//! - **Schema generation**: Optional JSON schema support via the `schemars` feature
13//! - **Async-friendly**: Uses tokio for concurrent analysis
14//! - **Cancellation support**: Built-in cancellation token support
15//!
16//! # Examples
17//!
18//! ```no_run
19//! use aptu_coder_core::analyze::analyze_directory;
20//! use std::path::Path;
21//!
22//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
23//! let output = analyze_directory(Path::new("src"), None)?;
24//! println!("Files: {:?}", output.files.len());
25//! # Ok(())
26//! # }
27//! ```
28
29pub mod analyze;
30pub mod cache;
31pub mod completion;
32mod config;
33pub mod edit;
34pub mod formatter;
35pub mod formatter_defuse;
36pub mod graph;
37pub mod lang;
38pub mod languages;
39pub mod pagination;
40pub mod parser;
41pub mod test_detection;
42pub mod traversal;
43pub mod types;
44
45#[cfg(feature = "schemars")]
46pub mod schema_helpers;
47
48pub(crate) const EXCLUDED_DIRS: &[&str] = &[
49 "node_modules",
50 "vendor",
51 ".git",
52 "__pycache__",
53 "target",
54 "dist",
55 "build",
56 ".venv",
57];
58
59// Re-exports of key public APIs
60pub use analyze::{
61 AnalysisOutput, AnalyzeError, CallChainEntry, FileAnalysisOutput, FocusedAnalysisConfig,
62 FocusedAnalysisOutput, analyze_directory, analyze_directory_with_progress, analyze_file,
63 analyze_focused, analyze_focused_with_progress, analyze_focused_with_progress_with_entries,
64 analyze_module_file, analyze_str,
65};
66pub use config::AnalysisConfig;
67pub use edit::{EditError, edit_overwrite_content, edit_replace_block};
68pub use lang::{language_for_extension, supported_languages};
69pub use parser::ParserError;
70pub use types::{
71 AnalysisMode, AnalysisResult, AnalyzeDirectoryParams, AnalyzeFileField, AnalyzeFileParams,
72 AnalyzeModuleParams, AnalyzeSymbolParams, CallChain, CallEdge, CallInfo, ClassInfo, DefUseKind,
73 DefUseSite, EditOverwriteOutput, EditOverwriteParams, EditReplaceOutput, EditReplaceParams,
74 ErrorMeta, ExecCommandParams, FileInfo, FocusedAnalysisData, FunctionInfo, ImplTraitInfo,
75 ImportInfo, ModuleFunctionInfo, ModuleImportInfo, ModuleInfo, OutputControlParams,
76 PaginationParams, ReferenceInfo, ReferenceType, STDIN_MAX_BYTES, SemanticAnalysis, ShellOutput,
77 SymbolMatchMode,
78};
79
80/// Captures from a custom tree-sitter query.
81#[derive(Debug, Clone, PartialEq, Eq, Hash)]
82pub struct QueryCapture {
83 /// The capture name from the query (without leading `@`).
84 pub capture_name: String,
85 /// The matched source text.
86 pub text: String,
87 /// Start line (0-indexed).
88 pub start_line: usize,
89 /// End line (0-indexed, inclusive).
90 pub end_line: usize,
91 /// Start byte offset.
92 pub start_byte: usize,
93 /// End byte offset.
94 pub end_byte: usize,
95}
96
97/// Execute a custom tree-sitter query against source code.
98///
99/// # Arguments
100///
101/// * `language` - Language name (e.g., "rust", "python"). Must be an enabled language feature.
102/// * `source` - Source code to query.
103/// * `query` - A tree-sitter query string (S-expression syntax).
104///
105/// # Returns
106///
107/// A vector of [`QueryCapture`] results, or a [`ParserError`] if the query is malformed
108/// or the language is not supported.
109///
110/// # Security note
111///
112/// This function accepts user-controlled `query` strings. Pathological queries against
113/// large `source` inputs may cause CPU exhaustion. Callers in untrusted environments
114/// should bound the length of both `source` and `query` before calling this function.
115/// `Query::new()` returns `Err` on malformed queries rather than panicking.
116pub fn execute_query(
117 language: &str,
118 source: &str,
119 query: &str,
120) -> Result<Vec<QueryCapture>, parser::ParserError> {
121 parser::execute_query_impl(language, source, query)
122}