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**: Astro, C/C++, C#, CSS, Fortran, Go, HTML, Java, JavaScript, JSON, Kotlin, Markdown, Python, Rust, TOML, TSX, TypeScript, YAML (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
29#![cfg_attr(test, allow(clippy::unwrap_used))]
30#![cfg_attr(test, allow(clippy::expect_used))]
31
32pub mod analyze;
33/// Internal implementation details for focused analysis. Use the `analyze` module for the public API.
34pub(crate) mod analyze_focused;
35pub mod cache;
36pub mod cache_disk;
37pub mod completion;
38mod config;
39pub mod edit;
40pub mod formatter;
41pub mod formatter_defuse;
42pub mod graph;
43pub mod lang;
44pub mod languages;
45pub mod pagination;
46pub mod parser;
47pub(crate) mod parser_elements;
48pub mod test_detection;
49pub mod traversal;
50pub mod types;
51
52#[cfg(feature = "schemars")]
53pub mod schema_helpers;
54
55pub const EXCLUDED_DIRS: &[&str] = &[
56 "node_modules",
57 "vendor",
58 ".git",
59 "__pycache__",
60 "target",
61 "dist",
62 "build",
63 ".venv",
64];
65
66// Re-exports of key public APIs
67pub use analyze::{
68 AnalysisOutput, AnalyzeError, CallChainEntry, FileAnalysisOutput, FocusedAnalysisConfig,
69 FocusedAnalysisOutput, analyze_directory, analyze_directory_with_progress, analyze_file,
70 analyze_focused, analyze_focused_with_progress, analyze_focused_with_progress_with_entries,
71 analyze_module_file, analyze_str,
72};
73pub use config::AnalysisConfig;
74pub use edit::{
75 EditError, edit_overwrite_content, edit_replace_block, edit_replace_block_with_options,
76};
77pub use graph::{GraphError, InternalCallChain};
78pub use lang::{language_for_extension, supported_languages};
79pub use pagination::{CursorData, PaginationError};
80pub use parser::ParserError;
81pub use traversal::{TraversalError, WalkEntry};
82pub use types::{
83 AnalysisMode, AnalyzeDirectoryParams, AnalyzeFileField, AnalyzeFileParams, AnalyzeModuleParams,
84 AnalyzeSymbolParams, CallEdge, CallInfo, ClassInfo, DefUseKind, DefUseSite,
85 EditOverwriteOutput, EditOverwriteParams, EditReplaceOutput, EditReplaceParams, FileInfo,
86 FilterRule, FunctionInfo, ImplTraitInfo, ImportInfo, ModuleFunctionInfo, ModuleImportInfo,
87 ModuleInfo, OutputControlParams, PaginationParams, ReferenceInfo, ReferenceType,
88 SemanticAnalysis, SymbolMatchMode,
89};
90
91/// Captures from a custom tree-sitter query.
92#[derive(Debug, Clone, PartialEq, Eq, Hash)]
93pub struct QueryCapture {
94 /// The capture name from the query (without leading `@`).
95 pub capture_name: String,
96 /// The matched source text.
97 pub text: String,
98 /// Start line (0-indexed).
99 pub start_line: usize,
100 /// End line (0-indexed, inclusive).
101 pub end_line: usize,
102 /// Start byte offset.
103 pub start_byte: usize,
104 /// End byte offset.
105 pub end_byte: usize,
106}
107
108/// Execute a custom tree-sitter query against source code.
109///
110/// # Arguments
111///
112/// * `language` - Language name (e.g., "rust", "python"). Must be an enabled language feature.
113/// * `source` - Source code to query.
114/// * `query` - A tree-sitter query string (S-expression syntax).
115///
116/// # Returns
117///
118/// A vector of [`QueryCapture`] results, or a [`ParserError`] if the query is malformed
119/// or the language is not supported.
120///
121/// # Security note
122///
123/// This function accepts user-controlled `query` strings. Pathological queries against
124/// large `source` inputs may cause CPU exhaustion. Callers in untrusted environments
125/// should bound the length of both `source` and `query` before calling this function.
126/// `Query::new()` returns `Err` on malformed queries rather than panicking.
127pub fn execute_query(
128 language: &str,
129 source: &str,
130 query: &str,
131) -> Result<Vec<QueryCapture>, parser::ParserError> {
132 parser::execute_query_impl(language, source, query)
133}