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
use crate::sizer::{ByteSizer, ChunkSizer};
use crate::{Chunker, Slab};
use tree_sitter::{Language, Node, Parser};
/// Supported programming languages for code chunking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeLanguage {
/// Rust
Rust,
/// Python
Python,
/// TypeScript/JavaScript
TypeScript,
/// Go
Go,
}
impl CodeLanguage {
/// Get the tree-sitter language for this code language.
pub fn get_language(&self) -> Language {
match self {
Self::Rust => tree_sitter_rust::LANGUAGE.into(),
Self::Python => tree_sitter_python::LANGUAGE.into(),
Self::TypeScript => tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
Self::Go => tree_sitter_go::LANGUAGE.into(),
}
}
/// Guess language from file extension.
pub fn from_extension(ext: &str) -> Option<Self> {
match ext {
"rs" => Some(Self::Rust),
"py" => Some(Self::Python),
"ts" | "tsx" | "js" | "jsx" => Some(Self::TypeScript),
"go" => Some(Self::Go),
_ => None,
}
}
/// Check if a node type represents a cohesive block (function, class, etc.).
pub fn is_block_node(&self, kind: &str) -> bool {
match self {
Self::Rust => matches!(
kind,
"function_item"
| "impl_item"
| "mod_item"
| "struct_item"
| "enum_item"
| "trait_item"
),
Self::Python => matches!(kind, "function_definition" | "class_definition"),
Self::TypeScript => matches!(
kind,
"function_declaration"
| "class_declaration"
| "method_definition"
| "interface_declaration"
| "enum_declaration"
),
Self::Go => matches!(
kind,
"function_declaration" | "method_declaration" | "type_declaration"
),
}
}
/// Check if a node type represents a top-level import.
pub fn is_import_node(&self, kind: &str) -> bool {
match self {
Self::Rust => matches!(kind, "use_declaration" | "extern_crate_declaration"),
Self::Python => matches!(kind, "import_statement" | "import_from_statement"),
Self::TypeScript => matches!(kind, "import_statement"),
Self::Go => matches!(kind, "import_declaration"),
}
}
}
/// A chunker that respects code structure using tree-sitter.
///
/// Functions, classes, and other AST blocks are kept intact when they fit
/// `max_chunk_size`; oversize nodes split recursively. The size unit
/// (bytes by default) is determined by the [`ChunkSizer`] — plug in a
/// tokenizer via [`with_sizer`](Self::with_sizer) to size in tokens.
/// Enable [`with_imports`](Self::with_imports) to prepend top-level
/// `use`/`import` statements to non-import chunks.
pub struct CodeChunker {
language: CodeLanguage,
max_chunk_size: usize,
chunk_overlap: usize,
sizer: Box<dyn ChunkSizer>,
inject_imports: bool,
}
impl CodeChunker {
/// Create a new code chunker.
///
/// `max_chunk_size` is in bytes by default (via [`ByteSizer`]). To size
/// chunks in tokens, attach a tokenizer-backed sizer with
/// [`with_sizer`](Self::with_sizer).
pub fn new(language: CodeLanguage, max_chunk_size: usize, chunk_overlap: usize) -> Self {
Self {
language,
max_chunk_size,
chunk_overlap,
sizer: Box::new(ByteSizer),
inject_imports: false,
}
}
/// Plug in a custom size metric (tokens, codepoints, etc.).
///
/// `max_chunk_size` is then interpreted in whatever unit the sizer returns.
#[must_use]
pub fn with_sizer<S: ChunkSizer + 'static>(mut self, sizer: S) -> Self {
self.sizer = Box::new(sizer);
self
}
/// Prepend top-level `use`/`import` declarations to chunks that don't
/// already contain them.
///
/// Method-only chunks lose the surrounding imports that name the types
/// they reference; this restores that context. Increases chunk size by
/// the import block length on every non-import chunk — the resulting
/// chunk may exceed `max_chunk_size`. The caller owns the budget
/// tradeoff; widen `max_chunk_size` to accommodate imports if your
/// embedding model has a strict context limit.
///
/// When enabled, `slab.text` may contain prepended import text not
/// present at the original `slab.start..slab.end` byte range.
#[must_use]
pub fn with_imports(mut self, inject: bool) -> Self {
self.inject_imports = inject;
self
}
/// Walk root children, collect import nodes, return (concatenated text, max end byte).
fn collect_imports(&self, root: Node, code: &str) -> (String, usize) {
let mut imports = String::new();
let mut max_end = 0usize;
let mut cursor = root.walk();
if cursor.goto_first_child() {
loop {
let node = cursor.node();
if self.language.is_import_node(node.kind()) {
let s = node.start_byte();
let e = node.end_byte();
imports.push_str(&code[s..e]);
imports.push('\n');
if e > max_end {
max_end = e;
}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
(imports, max_end)
}
fn collect_leafs(&self, node: Node, code: &str, chunks: &mut Vec<Slab>) {
let start_byte = node.start_byte();
let end_byte = node.end_byte();
let node_text = &code[start_byte..end_byte];
// If the node fits the size budget, take it as a unit.
// Block nodes (functions/classes) we especially want to keep together.
if self.sizer.size(node_text) <= self.max_chunk_size {
chunks.push(Slab::new(
node_text, start_byte, end_byte, 0, // Index fixed later
));
return;
}
// If it's too big, we MUST split it.
// We iterate children to break it down.
let mut cursor = node.walk();
if cursor.goto_first_child() {
let mut last_end = start_byte;
loop {
let child = cursor.node();
let child_start = child.start_byte();
// Gap before child
if child_start > last_end {
let gap_text = &code[last_end..child_start];
if !gap_text.trim().is_empty() {
chunks.push(Slab::new(gap_text, last_end, child_start, 0));
}
}
// Process child
self.collect_leafs(child, code, chunks);
last_end = child.end_byte();
if !cursor.goto_next_sibling() {
break;
}
}
// Gap after last child
if last_end < end_byte {
let gap_text = &code[last_end..end_byte];
if !gap_text.trim().is_empty() {
chunks.push(Slab::new(gap_text, last_end, end_byte, 0));
}
}
} else {
// Leaf node too big. Fall back to recursive text chunking.
// This handles long string literals or comments.
let leaf_text = &code[start_byte..end_byte];
let recursive = crate::recursive::RecursiveChunker::new(
self.max_chunk_size,
&["\n\n", "\n", " ", ""], // Standard separators
)
.with_overlap(0); // No internal overlap for atomic parts (handled by merger)
let sub_chunks = recursive.chunk(leaf_text);
for sub in sub_chunks {
// Adjust offsets relative to original code
chunks.push(Slab::new(
sub.text,
start_byte + sub.start,
start_byte + sub.end,
0,
));
}
}
}
}
impl Chunker for CodeChunker {
fn chunk_bytes(&self, text: &str) -> Vec<Slab> {
let mut parser = Parser::new();
if parser.set_language(&self.language.get_language()).is_err() {
return vec![];
}
let Some(tree) = parser.parse(text, None) else {
return vec![];
};
let root = tree.root_node();
let mut atomic_chunks = Vec::new();
// 1. Decompose into atomic chunks (leaves or small blocks)
self.collect_leafs(root, text, &mut atomic_chunks);
// 2. Merge atomic chunks into maximal slabs
let mut slabs = Vec::new();
let mut current_text = String::new();
let mut current_start = if atomic_chunks.is_empty() {
0
} else {
atomic_chunks[0].start
};
let mut current_end = current_start;
// Ensure atomic chunks are sorted
atomic_chunks.sort_by_key(|c| c.start);
for (i, chunk) in atomic_chunks.iter().enumerate() {
// Calculate potential gap between current end and next chunk start
// (collect_leafs should cover gaps, but just in case)
let gap = if chunk.start > current_end {
&text[current_end..chunk.start]
} else {
""
};
// Size check uses the sizer; for non-byte sizers we recompute
// current_text's size each iteration (O(N*T) for token sizers,
// acceptable for typical chunk sizes; tokenizer caching is the
// user's job if needed).
let projected = if current_text.is_empty() {
0
} else {
self.sizer.size(¤t_text) + self.sizer.size(gap) + self.sizer.size(&chunk.text)
};
if !current_text.is_empty() && projected > self.max_chunk_size {
// Emit current slab
slabs.push(Slab::new(
current_text.clone(),
current_start,
current_end,
slabs.len(),
));
current_text.clear();
// Overlap Logic
if self.chunk_overlap > 0 {
let mut overlap_size = 0;
let mut overlap_chunks = Vec::new();
// Walk backwards to find chunks that fit in overlap
for j in (0..i).rev() {
let prev_chunk = &atomic_chunks[j];
// Calculate gap after this prev_chunk
// If it's the last one before current (j = i-1), gap is `gap` (current_end..chunk.start)
// Wait, `gap` is between `current_end` and `chunk.start`.
// `current_end` aligns with `prev_chunk.end`.
let next_start = if j == i - 1 {
chunk.start
} else {
atomic_chunks[j + 1].start
};
let gap_len = next_start - prev_chunk.end;
let chunk_len = prev_chunk.len();
if overlap_size + chunk_len + gap_len > self.chunk_overlap {
if overlap_chunks.is_empty() {
overlap_chunks.push(j);
}
break;
}
overlap_chunks.push(j);
overlap_size += chunk_len + gap_len;
}
if !overlap_chunks.is_empty() {
overlap_chunks.reverse(); // Forward order
let first_idx = overlap_chunks[0];
let last_idx = overlap_chunks[overlap_chunks.len() - 1];
let first_chunk = &atomic_chunks[first_idx];
let last_chunk = &atomic_chunks[last_idx];
current_start = first_chunk.start;
// Include text up to end of last overlap chunk
// (Gaps between overlap chunks are included by slicing source text)
current_text = text[current_start..last_chunk.end].to_string();
} else {
current_start = chunk.start;
}
} else {
current_start = chunk.start;
}
}
if current_text.is_empty() {
current_start = chunk.start;
} else {
current_text.push_str(gap);
}
current_text.push_str(&chunk.text);
current_end = chunk.end;
}
// Flush last chunk
if !current_text.is_empty() {
slabs.push(Slab::new(
current_text,
current_start,
current_end,
slabs.len(),
));
}
// 3. Optional: prepend top-level imports to chunks that don't already
// cover them. Injection may push a chunk past `max_chunk_size` —
// the caller opted in and owns the budget tradeoff.
if self.inject_imports {
let (imports, import_end) = self.collect_imports(root, text);
if !imports.is_empty() {
let header = format!("{}\n", imports.trim_end());
for slab in slabs.iter_mut() {
if slab.start >= import_end {
slab.text = format!("{}{}", header, slab.text);
}
}
}
}
slabs
}
}