1#[cfg(feature = "tree-sitter")]
10use tree_sitter::{Node, Parser, Query, QueryCursor, StreamingIterator};
11
12use super::bm25_index::{ChunkKind, CodeChunk};
13
14#[cfg(feature = "tree-sitter")]
15const CHUNK_QUERY_RUST: &str = r"
16(function_item name: (identifier) @name) @chunk
17(struct_item name: (type_identifier) @name) @chunk
18(enum_item name: (type_identifier) @name) @chunk
19(trait_item name: (type_identifier) @name) @chunk
20(impl_item type: (type_identifier) @name) @chunk
21(const_item name: (identifier) @name) @chunk
22";
23
24#[cfg(feature = "tree-sitter")]
25const CHUNK_QUERY_TYPESCRIPT: &str = r"
26(function_declaration name: (identifier) @name) @chunk
27(class_declaration name: (type_identifier) @name) @chunk
28(abstract_class_declaration name: (type_identifier) @name) @chunk
29(interface_declaration name: (type_identifier) @name) @chunk
30(type_alias_declaration name: (type_identifier) @name) @chunk
31(method_definition name: (property_identifier) @name) @chunk
32(variable_declarator name: (identifier) @name value: (arrow_function)) @chunk
33";
34
35#[cfg(feature = "tree-sitter")]
36const CHUNK_QUERY_JAVASCRIPT: &str = r"
37(function_declaration name: (identifier) @name) @chunk
38(class_declaration name: (identifier) @name) @chunk
39(method_definition name: (property_identifier) @name) @chunk
40(variable_declarator name: (identifier) @name value: (arrow_function)) @chunk
41";
42
43#[cfg(feature = "tree-sitter")]
44const CHUNK_QUERY_PYTHON: &str = r"
45(function_definition name: (identifier) @name) @chunk
46(class_definition name: (identifier) @name) @chunk
47";
48
49#[cfg(feature = "tree-sitter")]
50const CHUNK_QUERY_GO: &str = r"
51(function_declaration name: (identifier) @name) @chunk
52(method_declaration name: (field_identifier) @name) @chunk
53(type_spec name: (type_identifier) @name) @chunk
54";
55
56#[cfg(feature = "tree-sitter")]
57const CHUNK_QUERY_JAVA: &str = r"
58(method_declaration name: (identifier) @name) @chunk
59(class_declaration name: (identifier) @name) @chunk
60(interface_declaration name: (identifier) @name) @chunk
61(enum_declaration name: (identifier) @name) @chunk
62(constructor_declaration name: (identifier) @name) @chunk
63";
64
65#[cfg(feature = "tree-sitter")]
66const CHUNK_QUERY_C: &str = r"
67(function_definition
68 declarator: (function_declarator
69 declarator: (identifier) @name)) @chunk
70(struct_specifier name: (type_identifier) @name) @chunk
71(enum_specifier name: (type_identifier) @name) @chunk
72";
73
74#[cfg(feature = "tree-sitter")]
75const CHUNK_QUERY_CPP: &str = r"
76(function_definition
77 declarator: (function_declarator
78 declarator: (_) @name)) @chunk
79(struct_specifier name: (type_identifier) @name) @chunk
80(class_specifier name: (type_identifier) @name) @chunk
81(enum_specifier name: (type_identifier) @name) @chunk
82(namespace_definition name: (identifier) @name) @chunk
83";
84
85#[cfg(feature = "tree-sitter")]
90fn get_cached_query(file_ext: &str) -> Option<&'static Query> {
91 use std::collections::HashMap;
92 use std::sync::OnceLock;
93
94 static QUERY_CACHE: OnceLock<HashMap<&'static str, Query>> = OnceLock::new();
95
96 let cache = QUERY_CACHE.get_or_init(|| {
97 let mut map = HashMap::new();
98 let exts: &[&str] = &[
99 "rs", "ts", "tsx", "js", "jsx", "py", "go", "java", "c", "h", "cpp", "cc", "cxx", "hpp",
100 ];
101 for &ext in exts {
102 if let (Some(lang), Some(src)) = (get_language(ext), get_chunk_query(ext))
103 && let Ok(q) = Query::new(&lang, src)
104 {
105 map.insert(ext, q);
106 }
107 }
108 map
109 });
110
111 cache.get(file_ext)
112}
113
114#[cfg(feature = "tree-sitter")]
119#[doc(hidden)]
121pub fn for_each_chunk_node(
122 content: &str,
123 file_ext: &str,
124 mut visitor: impl FnMut(Node, &str, ChunkKind, usize, usize),
125) -> Option<()> {
126 for_each_chunk_node_while(
127 content,
128 file_ext,
129 || true,
130 |node, name, kind, start, end| {
131 visitor(node, name, kind, start, end);
132 true
133 },
134 )
135}
136
137#[cfg(feature = "tree-sitter")]
139pub(crate) fn for_each_chunk_node_while(
140 content: &str,
141 file_ext: &str,
142 mut continue_scan: impl FnMut() -> bool,
143 mut visitor: impl FnMut(Node, &str, ChunkKind, usize, usize) -> bool,
144) -> Option<()> {
145 let language = get_language(file_ext)?;
146
147 thread_local! {
148 static PARSER: std::cell::RefCell<Parser> = std::cell::RefCell::new(Parser::new());
149 }
150
151 let tree = PARSER.with(|p| {
152 let mut parser = p.borrow_mut();
153 let _ = parser.set_language(&language);
154 parser.parse(content, None)
155 })?;
156
157 let query = get_cached_query(file_ext)?;
158 let chunk_idx = find_capture_index(query, "chunk")?;
159 let name_idx = find_capture_index(query, "name")?;
160
161 let source = content.as_bytes();
162 let mut cursor = QueryCursor::new();
163 let mut matches = cursor.matches(query, tree.root_node(), source);
164 let mut seen_ranges = Vec::new();
165
166 while let Some(m) = matches.next() {
167 if !continue_scan() {
169 break;
170 }
171 let mut chunk_node: Option<Node> = None;
172 let mut name_text = String::new();
173
174 for cap in m.captures {
175 if cap.index == chunk_idx {
176 chunk_node = Some(cap.node);
177 } else if cap.index == name_idx
178 && let Ok(text) = cap.node.utf8_text(source)
179 {
180 name_text = text.to_string();
181 }
182 }
183
184 if let Some(node) = chunk_node {
185 if name_text.is_empty() {
186 continue;
187 }
188
189 let start_row0 = node.start_position().row;
190 let end_row0 = node.end_position().row;
191
192 let range = (start_row0, end_row0);
193 if seen_ranges
194 .iter()
195 .any(|&(s, e)| s <= start_row0 && end_row0 <= e && range != (s, e))
196 {
197 continue;
198 }
199 seen_ranges.push(range);
200
201 let kind = node_kind_to_chunk_kind(node.kind());
202 if !visitor(node, name_text.as_str(), kind, start_row0 + 1, end_row0 + 1) {
203 break;
204 }
205 }
206 }
207
208 Some(())
209}
210
211#[cfg(feature = "tree-sitter")]
212pub fn extract_chunks_ts(file_path: &str, content: &str, file_ext: &str) -> Option<Vec<CodeChunk>> {
213 let mut chunks = Vec::new();
214
215 for_each_chunk_node(
216 content,
217 file_ext,
218 |node, name_text, kind, start_line, end_line| {
219 let block = match node.utf8_text(content.as_bytes()) {
220 Ok(text) => text.to_owned(),
221 Err(_) => return,
222 };
223 let token_count = super::bm25_index::tokenize_for_index(&block).len();
224
225 chunks.push(CodeChunk {
226 input_origin: None,
227 file_path: file_path.to_string(),
228 symbol_name: name_text.to_string(),
229 kind,
230 start_line,
231 end_line,
232 content: block,
233 tokens: Vec::new(),
234 token_count,
235 });
236 },
237 )?;
238
239 if chunks.is_empty() {
240 return None;
241 }
242
243 chunks.sort_by_key(|c| c.start_line);
244 Some(chunks)
245}
246
247#[cfg(not(feature = "tree-sitter"))]
248pub fn extract_chunks_ts(
249 _file_path: &str,
250 _content: &str,
251 _file_ext: &str,
252) -> Option<Vec<CodeChunk>> {
253 None
254}
255
256#[cfg(feature = "tree-sitter")]
257use lean_ctx_syntax::chunk_grammar::chunk_language as get_language;
258
259#[cfg(feature = "tree-sitter")]
260fn get_chunk_query(ext: &str) -> Option<&'static str> {
261 Some(match ext {
262 "rs" => CHUNK_QUERY_RUST,
263 "ts" | "tsx" => CHUNK_QUERY_TYPESCRIPT,
264 "js" | "jsx" => CHUNK_QUERY_JAVASCRIPT,
265 "py" => CHUNK_QUERY_PYTHON,
266 "go" => CHUNK_QUERY_GO,
267 "java" => CHUNK_QUERY_JAVA,
268 "c" | "h" => CHUNK_QUERY_C,
269 "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "hh" => CHUNK_QUERY_CPP,
270 _ => return None,
271 })
272}
273
274#[cfg(feature = "tree-sitter")]
275fn find_capture_index(query: &Query, name: &str) -> Option<u32> {
276 query
277 .capture_names()
278 .iter()
279 .position(|n| *n == name)
280 .map(|i| i as u32)
281}
282
283fn node_kind_to_chunk_kind(kind: &str) -> ChunkKind {
284 match kind {
285 "function_item"
286 | "function_declaration"
287 | "function_definition"
288 | "method_declaration"
289 | "method_definition"
290 | "constructor_declaration"
291 | "variable_declarator" => ChunkKind::Function,
292
293 "struct_item"
294 | "struct_specifier"
295 | "struct_declaration"
296 | "enum_item"
297 | "enum_specifier"
298 | "enum_declaration"
299 | "trait_item"
300 | "interface_declaration"
301 | "type_alias_declaration"
302 | "type_spec" => ChunkKind::Struct,
303
304 "impl_item" => ChunkKind::Impl,
305
306 "class_declaration"
307 | "abstract_class_declaration"
308 | "class_specifier"
309 | "class_definition" => ChunkKind::Class,
310
311 "namespace_definition" | "namespace_declaration" => ChunkKind::Module,
312
313 _ => ChunkKind::Other,
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 #[test]
322 fn extract_rust_chunks() {
323 let src = r#"use std::io;
324
325pub fn process(input: &str) -> String {
326 input.to_uppercase()
327}
328
329pub struct Config {
330 pub name: String,
331 pub port: u16,
332}
333
334impl Config {
335 pub fn new() -> Self {
336 Self { name: "default".into(), port: 8080 }
337 }
338}
339
340fn helper() -> bool {
341 true
342}
343"#;
344 let chunks = extract_chunks_ts("main.rs", src, "rs").unwrap();
345 assert!(
346 chunks.len() >= 4,
347 "expected >=4 chunks, got {}",
348 chunks.len()
349 );
350
351 let names: Vec<&str> = chunks.iter().map(|c| c.symbol_name.as_str()).collect();
352 assert!(names.contains(&"process"), "got {names:?}");
353 assert!(names.contains(&"Config"), "got {names:?}");
354 assert!(names.contains(&"helper"), "got {names:?}");
355
356 let process = chunks.iter().find(|c| c.symbol_name == "process").unwrap();
357 assert!(matches!(process.kind, ChunkKind::Function));
358 assert!(process.content.contains("to_uppercase"));
359 }
360
361 #[test]
362 fn extract_typescript_chunks() {
363 let src = r"
364export function greet(name: string): string {
365 return `Hello ${name}`;
366}
367
368export class UserService {
369 findUser(id: number): User {
370 return db.find(id);
371 }
372}
373
374const handler = async (req: Request): Promise<Response> => {
375 return new Response();
376};
377";
378 let chunks = extract_chunks_ts("app.ts", src, "ts").unwrap();
379 assert!(
380 chunks.len() >= 3,
381 "expected >=3 chunks, got {}",
382 chunks.len()
383 );
384
385 let names: Vec<&str> = chunks.iter().map(|c| c.symbol_name.as_str()).collect();
386 assert!(names.contains(&"greet"), "got {names:?}");
387 assert!(names.contains(&"UserService"), "got {names:?}");
388 }
389
390 #[test]
391 fn extract_python_chunks() {
392 let src = r"
393class AuthService:
394 def __init__(self, db):
395 self.db = db
396
397 def authenticate(self, email: str) -> bool:
398 user = self.db.find(email)
399 return user is not None
400
401def create_app():
402 return Flask(__name__)
403";
404 let chunks = extract_chunks_ts("app.py", src, "py").unwrap();
405 assert!(
406 chunks.len() >= 2,
407 "expected >=2 chunks, got {}",
408 chunks.len()
409 );
410
411 let names: Vec<&str> = chunks.iter().map(|c| c.symbol_name.as_str()).collect();
412 assert!(names.contains(&"AuthService"), "got {names:?}");
413 assert!(names.contains(&"create_app"), "got {names:?}");
414
415 let auth = chunks
416 .iter()
417 .find(|c| c.symbol_name == "AuthService")
418 .unwrap();
419 assert!(auth.content.contains("authenticate"));
420 }
421
422 #[test]
423 fn chunks_contain_full_body() {
424 let src = r#"
425pub fn complex(x: i32, y: i32) -> Result<String, Error> {
426 let sum = x + y;
427 let result = format!("Sum: {}", sum);
428 if sum > 100 {
429 return Err(Error::new("too large"));
430 }
431 Ok(result)
432}
433"#;
434 let chunks = extract_chunks_ts("math.rs", src, "rs").unwrap();
435 let complex = chunks.iter().find(|c| c.symbol_name == "complex").unwrap();
436 assert!(complex.content.contains("sum > 100"));
437 assert!(complex.content.contains("Ok(result)"));
438 }
439
440 #[test]
441 fn unsupported_language_returns_none() {
442 assert!(extract_chunks_ts("file.xyz", "content", "xyz").is_none());
443 }
444
445 #[test]
446 fn empty_file_returns_none() {
447 assert!(extract_chunks_ts("empty.rs", "", "rs").is_none());
448 }
449
450 #[test]
451 fn javascript_same_line_functions_use_exact_node_content() {
452 let src = "function alpha(){return 1;}function beta(){return 2;}";
453 let chunks = extract_chunks_ts("min.js", src, "js").unwrap();
454
455 let alpha = chunks.iter().find(|c| c.symbol_name == "alpha").unwrap();
456 let beta = chunks.iter().find(|c| c.symbol_name == "beta").unwrap();
457
458 assert_eq!(alpha.content, "function alpha(){return 1;}");
459 assert_eq!(beta.content, "function beta(){return 2;}");
460 }
461
462 #[test]
463 fn chunks_sorted_by_line() {
464 let src = r"
465fn b_func() {}
466fn a_func() {}
467";
468 let chunks = extract_chunks_ts("sort.rs", src, "rs").unwrap();
469 assert!(chunks[0].start_line <= chunks[1].start_line);
470 }
471}