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 (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, FileAnalysisOutput, FocusedAnalysisConfig, FocusedAnalysisOutput,
60    analyze_directory, analyze_directory_with_progress, analyze_file, analyze_focused,
61    analyze_focused_with_progress, analyze_focused_with_progress_with_entries, analyze_module_file,
62};
63pub use config::AnalysisConfig;
64pub use lang::{language_for_extension, supported_languages};
65pub use parser::ParserError;
66pub use types::*;
67
68/// Captures from a custom tree-sitter query.
69#[derive(Debug, Clone)]
70pub struct QueryCapture {
71    /// The capture name from the query (without leading `@`).
72    pub capture_name: String,
73    /// The matched source text.
74    pub text: String,
75    /// Start line (0-indexed).
76    pub start_line: usize,
77    /// End line (0-indexed, inclusive).
78    pub end_line: usize,
79    /// Start byte offset.
80    pub start_byte: usize,
81    /// End byte offset.
82    pub end_byte: usize,
83}
84
85/// Execute a custom tree-sitter query against source code.
86///
87/// # Arguments
88///
89/// * `language` - Language name (e.g., "rust", "python"). Must be an enabled language feature.
90/// * `source` - Source code to query.
91/// * `query` - A tree-sitter query string (S-expression syntax).
92///
93/// # Returns
94///
95/// A vector of [`QueryCapture`] results, or a [`ParserError`] if the query is malformed
96/// or the language is not supported.
97///
98/// # Security note
99///
100/// This function accepts user-controlled `query` strings. Pathological queries against
101/// large `source` inputs may cause CPU exhaustion. Callers in untrusted environments
102/// should bound the length of both `source` and `query` before calling this function.
103/// `Query::new()` returns `Err` on malformed queries rather than panicking.
104pub fn execute_query(
105    language: &str,
106    source: &str,
107    query: &str,
108) -> Result<Vec<QueryCapture>, parser::ParserError> {
109    parser::execute_query_impl(language, source, query)
110}