Skip to main content

code_analyze_core/
lib.rs

1// SPDX-FileCopyrightText: 2026 code-analyze-mcp 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 code_analyze_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 formatter;
34pub mod graph;
35pub mod lang;
36pub mod languages;
37pub mod pagination;
38pub mod parser;
39pub mod test_detection;
40pub mod traversal;
41pub mod types;
42
43#[cfg(feature = "schemars")]
44pub mod schema_helpers;
45
46pub(crate) const EXCLUDED_DIRS: &[&str] = &[
47    "node_modules",
48    "vendor",
49    ".git",
50    "__pycache__",
51    "target",
52    "dist",
53    "build",
54    ".venv",
55];
56
57// Re-exports of key public APIs
58pub use analyze::{
59    AnalysisOutput, AnalyzeError, CallChainEntry, FileAnalysisOutput, FocusedAnalysisConfig,
60    FocusedAnalysisOutput, analyze_directory, analyze_directory_with_progress, analyze_file,
61    analyze_focused, analyze_focused_with_progress, analyze_focused_with_progress_with_entries,
62    analyze_module_file, analyze_str,
63};
64pub use config::AnalysisConfig;
65pub use lang::{language_for_extension, supported_languages};
66pub use parser::ParserError;
67pub use types::*;
68
69/// Captures from a custom tree-sitter query.
70#[derive(Debug, Clone)]
71pub struct QueryCapture {
72    /// The capture name from the query (without leading `@`).
73    pub capture_name: String,
74    /// The matched source text.
75    pub text: String,
76    /// Start line (0-indexed).
77    pub start_line: usize,
78    /// End line (0-indexed, inclusive).
79    pub end_line: usize,
80    /// Start byte offset.
81    pub start_byte: usize,
82    /// End byte offset.
83    pub end_byte: usize,
84}
85
86/// Execute a custom tree-sitter query against source code.
87///
88/// # Arguments
89///
90/// * `language` - Language name (e.g., "rust", "python"). Must be an enabled language feature.
91/// * `source` - Source code to query.
92/// * `query` - A tree-sitter query string (S-expression syntax).
93///
94/// # Returns
95///
96/// A vector of [`QueryCapture`] results, or a [`ParserError`] if the query is malformed
97/// or the language is not supported.
98///
99/// # Security note
100///
101/// This function accepts user-controlled `query` strings. Pathological queries against
102/// large `source` inputs may cause CPU exhaustion. Callers in untrusted environments
103/// should bound the length of both `source` and `query` before calling this function.
104/// `Query::new()` returns `Err` on malformed queries rather than panicking.
105pub fn execute_query(
106    language: &str,
107    source: &str,
108    query: &str,
109) -> Result<Vec<QueryCapture>, parser::ParserError> {
110    parser::execute_query_impl(language, source, query)
111}