leann-core 0.2.3

LEANN is a revolutionary vector database that democratizes personal AI. Transform your laptop into a powerful RAG system that can index and search through millions of documents while using 97% less storage than traditional solutions without accuracy loss.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
use std::collections::HashMap;

/// Language detection from file extension.
pub fn detect_language(filename: &str) -> Option<&'static str> {
    let ext = filename.rsplit('.').next()?.to_lowercase();
    match ext.as_str() {
        "py" => Some("python"),
        "rs" => Some("rust"),
        "js" | "jsx" => Some("javascript"),
        "ts" | "tsx" => Some("typescript"),
        "java" => Some("java"),
        "go" => Some("go"),
        "c" | "h" => Some("c"),
        "cpp" | "cxx" | "cc" | "hpp" => Some("cpp"),
        "rb" => Some("ruby"),
        "sh" | "bash" => Some("bash"),
        _ => None,
    }
}

/// A code chunk extracted from AST analysis.
#[derive(Debug, Clone)]
pub struct CodeChunk {
    pub text: String,
    pub chunk_type: String, // "function", "class", "method", "module", etc.
    pub name: Option<String>,
    pub start_line: usize,
    pub end_line: usize,
    pub language: String,
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Chunk source code using AST analysis.
///
/// When tree-sitter features are enabled, uses grammar-based parsing for
/// accurate AST boundaries. Falls back to heuristic-based parsing otherwise.
pub fn chunk_code(source: &str, filename: &str, max_chunk_size: usize) -> Vec<CodeChunk> {
    #[cfg(any(
        feature = "tree-sitter-python",
        feature = "tree-sitter-java",
        feature = "tree-sitter-c-sharp",
        feature = "tree-sitter-typescript",
        feature = "tree-sitter-javascript",
    ))]
    if let Some(chunks) =
        super::tree_sitter::chunk_code_tree_sitter(source, filename, max_chunk_size)
        && !chunks.is_empty()
    {
        return chunks;
    }

    // Heuristic fallback
    let language = detect_language(filename).unwrap_or("unknown");

    match language {
        "python" => chunk_python(source, filename, max_chunk_size),
        "rust" => chunk_rust(source, filename, max_chunk_size),
        "javascript" | "typescript" => chunk_js_ts(source, filename, max_chunk_size),
        _ => chunk_generic(source, filename, language, max_chunk_size),
    }
}

/// Chunk Python source code by detecting function and class definitions.
fn chunk_python(source: &str, filename: &str, max_chunk_size: usize) -> Vec<CodeChunk> {
    let lines: Vec<&str> = source.lines().collect();
    let mut chunks = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        let line = lines[i];
        let trimmed = line.trim();

        // Detect function or class definition
        if trimmed.starts_with("def ")
            || trimmed.starts_with("class ")
            || trimmed.starts_with("async def ")
        {
            let indent = line.len() - line.trim_start().len();
            let chunk_type = if trimmed.starts_with("class ") {
                "class"
            } else {
                "function"
            };

            let name = extract_name(trimmed);
            let start_line = i;

            // Find the end of this block (next line at same or lower indentation)
            let mut end_line = i + 1;
            while end_line < lines.len() {
                let next = lines[end_line];
                if next.trim().is_empty() {
                    end_line += 1;
                    continue;
                }
                let next_indent = next.len() - next.trim_start().len();
                if next_indent <= indent && !next.trim().is_empty() {
                    // Check if this is a decorator for the next function
                    if next.trim().starts_with('@') {
                        break;
                    }
                    // Same or lower indent means block ended
                    break;
                }
                end_line += 1;
            }

            let text: String = lines[start_line..end_line].join("\n");
            if text.len() <= max_chunk_size {
                chunks.push(CodeChunk {
                    text,
                    chunk_type: chunk_type.to_string(),
                    name: Some(name),
                    start_line: start_line + 1,
                    end_line,
                    language: "python".to_string(),
                    metadata: make_metadata(filename, start_line + 1, end_line),
                });
            } else {
                // Split large blocks
                let sub_chunks = split_large_block(&lines[start_line..end_line], max_chunk_size);
                for sub in sub_chunks {
                    chunks.push(CodeChunk {
                        text: sub,
                        chunk_type: format!("{}_part", chunk_type),
                        name: None,
                        start_line: start_line + 1,
                        end_line,
                        language: "python".to_string(),
                        metadata: make_metadata(filename, start_line + 1, end_line),
                    });
                }
            }

            i = end_line;
        } else {
            i += 1;
        }
    }

    // If no chunks were found, fall back to generic chunking
    if chunks.is_empty() {
        return chunk_generic(source, filename, "python", max_chunk_size);
    }

    chunks
}

/// Chunk Rust source code by detecting fn, struct, impl, enum blocks.
fn chunk_rust(source: &str, filename: &str, max_chunk_size: usize) -> Vec<CodeChunk> {
    let lines: Vec<&str> = source.lines().collect();
    let mut chunks = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        let trimmed = lines[i].trim();

        let is_block_start = trimmed.starts_with("pub fn ")
            || trimmed.starts_with("fn ")
            || trimmed.starts_with("pub struct ")
            || trimmed.starts_with("struct ")
            || trimmed.starts_with("pub enum ")
            || trimmed.starts_with("enum ")
            || trimmed.starts_with("impl ")
            || trimmed.starts_with("pub impl ")
            || trimmed.starts_with("pub trait ")
            || trimmed.starts_with("trait ")
            || trimmed.starts_with("pub mod ")
            || trimmed.starts_with("mod ");

        if is_block_start {
            let chunk_type = if trimmed.contains("fn ") {
                "function"
            } else if trimmed.contains("struct ") {
                "struct"
            } else if trimmed.contains("enum ") {
                "enum"
            } else if trimmed.contains("impl ") {
                "impl"
            } else if trimmed.contains("trait ") {
                "trait"
            } else {
                "module"
            };

            let name = extract_rust_name(trimmed);
            let start_line = i;

            // Find matching closing brace using brace counting
            let mut brace_count = 0;
            let mut end_line = i;
            let mut found_open = false;

            for (j, line) in lines.iter().enumerate().skip(i) {
                for ch in line.chars() {
                    if ch == '{' {
                        brace_count += 1;
                        found_open = true;
                    } else if ch == '}' {
                        brace_count -= 1;
                    }
                }
                end_line = j + 1;
                if found_open && brace_count == 0 {
                    break;
                }
            }

            let text: String = lines[start_line..end_line].join("\n");
            if text.len() <= max_chunk_size {
                chunks.push(CodeChunk {
                    text,
                    chunk_type: chunk_type.to_string(),
                    name: Some(name),
                    start_line: start_line + 1,
                    end_line,
                    language: "rust".to_string(),
                    metadata: make_metadata(filename, start_line + 1, end_line),
                });
            } else {
                let sub_chunks = split_large_block(&lines[start_line..end_line], max_chunk_size);
                for sub in sub_chunks {
                    chunks.push(CodeChunk {
                        text: sub,
                        chunk_type: format!("{}_part", chunk_type),
                        name: None,
                        start_line: start_line + 1,
                        end_line,
                        language: "rust".to_string(),
                        metadata: make_metadata(filename, start_line + 1, end_line),
                    });
                }
            }

            i = end_line;
        } else {
            i += 1;
        }
    }

    if chunks.is_empty() {
        return chunk_generic(source, filename, "rust", max_chunk_size);
    }

    chunks
}

/// Chunk JavaScript/TypeScript source code.
fn chunk_js_ts(source: &str, filename: &str, max_chunk_size: usize) -> Vec<CodeChunk> {
    let lines: Vec<&str> = source.lines().collect();
    let mut chunks = Vec::new();
    let mut i = 0;
    let language = detect_language(filename).unwrap_or("javascript");

    while i < lines.len() {
        let trimmed = lines[i].trim();

        let is_block_start = trimmed.starts_with("function ")
            || trimmed.starts_with("async function ")
            || trimmed.starts_with("export function ")
            || trimmed.starts_with("export async function ")
            || trimmed.starts_with("export default function ")
            || trimmed.starts_with("class ")
            || trimmed.starts_with("export class ")
            || trimmed.starts_with("export default class ")
            || trimmed.contains("=> {");

        if is_block_start {
            let chunk_type = if trimmed.contains("class ") {
                "class"
            } else {
                "function"
            };

            let start_line = i;
            let mut brace_count = 0;
            let mut end_line = i;
            let mut found_open = false;

            for (j, line) in lines.iter().enumerate().skip(i) {
                for ch in line.chars() {
                    if ch == '{' {
                        brace_count += 1;
                        found_open = true;
                    } else if ch == '}' {
                        brace_count -= 1;
                    }
                }
                end_line = j + 1;
                if found_open && brace_count == 0 {
                    break;
                }
            }

            let text: String = lines[start_line..end_line].join("\n");
            if text.len() <= max_chunk_size {
                chunks.push(CodeChunk {
                    text,
                    chunk_type: chunk_type.to_string(),
                    name: None,
                    start_line: start_line + 1,
                    end_line,
                    language: language.to_string(),
                    metadata: make_metadata(filename, start_line + 1, end_line),
                });
            }

            i = end_line;
        } else {
            i += 1;
        }
    }

    if chunks.is_empty() {
        return chunk_generic(source, filename, language, max_chunk_size);
    }

    chunks
}

/// Generic line-based chunking for unsupported languages.
fn chunk_generic(
    source: &str,
    filename: &str,
    language: &str,
    max_chunk_size: usize,
) -> Vec<CodeChunk> {
    let lines: Vec<&str> = source.lines().collect();
    let mut chunks = Vec::new();
    let mut current = String::new();
    let mut start_line = 0;

    for (i, line) in lines.iter().enumerate() {
        if current.len() + line.len() + 1 > max_chunk_size && !current.is_empty() {
            chunks.push(CodeChunk {
                text: std::mem::take(&mut current),
                chunk_type: "block".to_string(),
                name: None,
                start_line: start_line + 1,
                end_line: i,
                language: language.to_string(),
                metadata: make_metadata(filename, start_line + 1, i),
            });
            start_line = i;
        }

        if !current.is_empty() {
            current.push('\n');
        }
        current.push_str(line);
    }

    if !current.trim().is_empty() {
        chunks.push(CodeChunk {
            text: current,
            chunk_type: "block".to_string(),
            name: None,
            start_line: start_line + 1,
            end_line: lines.len(),
            language: language.to_string(),
            metadata: make_metadata(filename, start_line + 1, lines.len()),
        });
    }

    chunks
}

fn extract_name(definition_line: &str) -> String {
    let trimmed = definition_line.trim();
    // "def foo(..." or "class Foo:" or "async def bar(..."
    let parts: Vec<&str> = trimmed.split_whitespace().collect();
    for (i, &part) in parts.iter().enumerate() {
        if (part == "def" || part == "class")
            && let Some(name) = parts.get(i + 1)
        {
            return name.trim_end_matches('(').trim_end_matches(':').to_string();
        }
    }
    "unknown".to_string()
}

fn extract_rust_name(definition_line: &str) -> String {
    let trimmed = definition_line.trim();
    let keywords = ["fn", "struct", "enum", "impl", "trait", "mod"];
    let parts: Vec<&str> = trimmed.split_whitespace().collect();
    for (i, &part) in parts.iter().enumerate() {
        if keywords.contains(&part)
            && let Some(name) = parts.get(i + 1)
        {
            return name
                .trim_end_matches('{')
                .trim_end_matches('<')
                .trim_end_matches('(')
                .to_string();
        }
    }
    "unknown".to_string()
}

pub(crate) fn split_large_block(lines: &[&str], max_size: usize) -> Vec<String> {
    let mut chunks = Vec::new();
    let mut current = String::new();

    for line in lines {
        if current.len() + line.len() + 1 > max_size && !current.is_empty() {
            chunks.push(std::mem::take(&mut current));
        }

        // If a single line exceeds max_size, split it by characters
        if line.len() > max_size && current.is_empty() {
            let mut offset = 0;
            while offset < line.len() {
                let end = (offset + max_size).min(line.len());
                chunks.push(line[offset..end].to_string());
                offset = end;
            }
            continue;
        }

        if !current.is_empty() {
            current.push('\n');
        }
        current.push_str(line);
    }

    if !current.trim().is_empty() {
        chunks.push(current);
    }

    chunks
}

pub(crate) fn make_metadata(
    filename: &str,
    start_line: usize,
    end_line: usize,
) -> HashMap<String, serde_json::Value> {
    let mut m = HashMap::new();
    m.insert("source".to_string(), serde_json::json!(filename));
    m.insert("start_line".to_string(), serde_json::json!(start_line));
    m.insert("end_line".to_string(), serde_json::json!(end_line));
    m
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_detect_language() {
        assert_eq!(detect_language("foo.py"), Some("python"));
        assert_eq!(detect_language("bar.rs"), Some("rust"));
        assert_eq!(detect_language("baz.js"), Some("javascript"));
        assert_eq!(detect_language("qux.txt"), None);
    }

    #[test]
    fn test_chunk_python() {
        let source = r#"
def hello():
    print("hello")

def world():
    print("world")

class Foo:
    def bar(self):
        pass
"#;
        let chunks = chunk_code(source, "test.py", 1000);
        assert!(
            chunks.len() >= 2,
            "Expected at least 2 chunks, got {}",
            chunks.len()
        );
    }

    #[test]
    fn test_chunk_rust() {
        let source = r#"
fn hello() {
    println!("hello");
}

fn world() {
    println!("world");
}

struct Foo {
    bar: i32,
}
"#;
        let chunks = chunk_code(source, "test.rs", 1000);
        assert!(
            chunks.len() >= 2,
            "Expected at least 2 chunks, got {}",
            chunks.len()
        );
    }

    #[test]
    fn test_chunk_generic() {
        let source = "line 1\nline 2\nline 3\nline 4\nline 5";
        let chunks = chunk_code(source, "test.txt", 20);
        assert!(!chunks.is_empty());
    }
}