-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathlib.rs
More file actions
4091 lines (3517 loc) · 123 KB
/
Copy pathlib.rs
File metadata and controls
4091 lines (3517 loc) · 123 KB
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::Result;
use ck_core::Span;
use serde::{Deserialize, Serialize};
mod query_chunker;
/// Import token estimation from ck-embed
pub use ck_embed::TokenEstimator;
/// Fallback to estimation if precise tokenization fails
fn estimate_tokens(text: &str) -> usize {
TokenEstimator::estimate_tokens(text)
}
/// Get model-specific chunk configuration (target_tokens, overlap_tokens)
/// Balanced for precision vs context - larger models can handle bigger chunks but not too big
pub fn get_model_chunk_config(model_name: Option<&str>) -> (usize, usize) {
let model = model_name.unwrap_or("nomic-embed-text-v1.5");
match model {
// Small models - keep chunks smaller for better precision
"BAAI/bge-small-en-v1.5" | "sentence-transformers/all-MiniLM-L6-v2" => {
(400, 80) // 400 tokens target, 80 token overlap (~20%)
}
// Large context models - can use bigger chunks while preserving precision
// Sweet spot: enough context to be meaningful, small enough to be precise
"nomic-embed-text-v1" | "nomic-embed-text-v1.5" | "jina-embeddings-v2-base-code" => {
(1024, 200) // 1024 tokens target, 200 token overlap (~20%) - good balance
}
// BGE variants - stick to smaller for precision
"BAAI/bge-base-en-v1.5" | "BAAI/bge-large-en-v1.5" => {
(400, 80) // 400 tokens target, 80 token overlap (~20%)
}
// Default to large model config since nomic-v1.5 is default
_ => (1024, 200), // Good balance of context vs precision
}
}
/// Information about chunk striding for large chunks that exceed token limits
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StrideInfo {
/// Unique ID for the original chunk before striding
pub original_chunk_id: String,
/// Index of this stride (0-based)
pub stride_index: usize,
/// Total number of strides for the original chunk
pub total_strides: usize,
/// Byte offset where overlap with previous stride begins
pub overlap_start: usize,
/// Byte offset where overlap with next stride ends
pub overlap_end: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ChunkMetadata {
pub ancestry: Vec<String>,
pub breadcrumb: Option<String>,
pub leading_trivia: Vec<String>,
pub trailing_trivia: Vec<String>,
pub byte_length: usize,
pub estimated_tokens: usize,
}
impl ChunkMetadata {
fn from_context(
text: &str,
ancestry: Vec<String>,
leading_trivia: Vec<String>,
trailing_trivia: Vec<String>,
) -> Self {
let breadcrumb = if ancestry.is_empty() {
None
} else {
Some(ancestry.join("::"))
};
Self {
ancestry,
breadcrumb,
leading_trivia,
trailing_trivia,
byte_length: text.len(),
estimated_tokens: estimate_tokens(text),
}
}
fn from_text(text: &str) -> Self {
Self {
ancestry: Vec::new(),
breadcrumb: None,
leading_trivia: Vec::new(),
trailing_trivia: Vec::new(),
byte_length: text.len(),
estimated_tokens: estimate_tokens(text),
}
}
fn with_updated_text(&self, text: &str) -> Self {
let mut cloned = self.clone();
cloned.byte_length = text.len();
cloned.estimated_tokens = estimate_tokens(text);
cloned
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Chunk {
pub span: Span,
pub text: String,
pub chunk_type: ChunkType,
/// Stride information if this chunk was created by striding a larger chunk
pub stride_info: Option<StrideInfo>,
pub metadata: ChunkMetadata,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ChunkType {
Text,
Function,
Class,
Method,
Module,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseableLanguage {
Python,
TypeScript,
JavaScript,
Haskell,
Rust,
Ruby,
Go,
C,
Cpp,
CSharp,
Zig,
Dart,
Elixir,
Markdown,
}
impl std::fmt::Display for ParseableLanguage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let name = match self {
ParseableLanguage::Python => "python",
ParseableLanguage::TypeScript => "typescript",
ParseableLanguage::JavaScript => "javascript",
ParseableLanguage::Haskell => "haskell",
ParseableLanguage::Rust => "rust",
ParseableLanguage::Ruby => "ruby",
ParseableLanguage::Go => "go",
ParseableLanguage::C => "c",
ParseableLanguage::Cpp => "cpp",
ParseableLanguage::CSharp => "csharp",
ParseableLanguage::Zig => "zig",
ParseableLanguage::Dart => "dart",
ParseableLanguage::Elixir => "elixir",
ParseableLanguage::Markdown => "markdown",
};
write!(f, "{name}")
}
}
impl TryFrom<ck_core::Language> for ParseableLanguage {
type Error = anyhow::Error;
fn try_from(lang: ck_core::Language) -> Result<Self, Self::Error> {
match lang {
ck_core::Language::Python => Ok(ParseableLanguage::Python),
ck_core::Language::TypeScript => Ok(ParseableLanguage::TypeScript),
ck_core::Language::JavaScript => Ok(ParseableLanguage::JavaScript),
ck_core::Language::Haskell => Ok(ParseableLanguage::Haskell),
ck_core::Language::Rust => Ok(ParseableLanguage::Rust),
ck_core::Language::Ruby => Ok(ParseableLanguage::Ruby),
ck_core::Language::Go => Ok(ParseableLanguage::Go),
ck_core::Language::C => Ok(ParseableLanguage::C),
ck_core::Language::Cpp => Ok(ParseableLanguage::Cpp),
ck_core::Language::CSharp => Ok(ParseableLanguage::CSharp),
ck_core::Language::Zig => Ok(ParseableLanguage::Zig),
ck_core::Language::Dart => Ok(ParseableLanguage::Dart),
ck_core::Language::Elixir => Ok(ParseableLanguage::Elixir),
ck_core::Language::Markdown => Ok(ParseableLanguage::Markdown),
_ => Err(anyhow::anyhow!(
"Language {lang:?} is not supported for parsing"
)),
}
}
}
pub fn chunk_text(text: &str, language: Option<ck_core::Language>) -> Result<Vec<Chunk>> {
chunk_text_with_config(text, language, &ChunkConfig::default())
}
/// Configuration for chunking behavior
#[derive(Debug, Clone)]
pub struct ChunkConfig {
/// Maximum tokens per chunk (for striding)
pub max_tokens: usize,
/// Overlap size for striding (in tokens)
pub stride_overlap: usize,
/// Enable striding for chunks that exceed max_tokens
pub enable_striding: bool,
}
impl Default for ChunkConfig {
fn default() -> Self {
Self {
max_tokens: 8192, // Default to Nomic model limit
stride_overlap: 1024, // 12.5% overlap
enable_striding: true,
}
}
}
/// New function that accepts model name for model-specific chunking
pub fn chunk_text_with_model(
text: &str,
language: Option<ck_core::Language>,
model_name: Option<&str>,
) -> Result<Vec<Chunk>> {
let (target_tokens, overlap_tokens) = get_model_chunk_config(model_name);
// Create a config based on model-specific parameters
let config = ChunkConfig {
max_tokens: target_tokens,
stride_overlap: overlap_tokens,
enable_striding: true,
};
chunk_text_with_config_and_model(text, language, &config, model_name)
}
pub fn chunk_text_with_config(
text: &str,
language: Option<ck_core::Language>,
config: &ChunkConfig,
) -> Result<Vec<Chunk>> {
chunk_text_with_config_and_model(text, language, config, None)
}
fn chunk_text_with_config_and_model(
text: &str,
language: Option<ck_core::Language>,
config: &ChunkConfig,
model_name: Option<&str>,
) -> Result<Vec<Chunk>> {
tracing::debug!(
"Chunking text with language: {:?}, length: {} chars, config: {:?}",
language,
text.len(),
config
);
let result = match language.map(ParseableLanguage::try_from) {
Some(Ok(lang)) => {
tracing::debug!("Using {} tree-sitter parser", lang);
chunk_language_with_model(text, lang, model_name)
}
Some(Err(_)) => {
tracing::debug!("Language not supported for parsing, using generic chunking strategy");
chunk_generic_with_token_config(text, model_name)
}
None => {
tracing::debug!("Using generic chunking strategy");
chunk_generic_with_token_config(text, model_name)
}
};
let mut chunks = result?;
// Apply striding if enabled and necessary
if config.enable_striding {
chunks = apply_striding(chunks, config)?;
}
tracing::debug!("Successfully created {} final chunks", chunks.len());
Ok(chunks)
}
fn chunk_generic(text: &str) -> Result<Vec<Chunk>> {
chunk_generic_with_token_config(text, None)
}
fn chunk_generic_with_token_config(text: &str, model_name: Option<&str>) -> Result<Vec<Chunk>> {
let mut chunks = Vec::new();
let lines: Vec<&str> = text.lines().collect();
// Get model-specific optimal chunk size in tokens
let (target_tokens, overlap_tokens) = get_model_chunk_config(model_name);
// Convert token targets to approximate line counts
// This is a rough heuristic - we'll validate with actual token counting
let avg_tokens_per_line = 10.0; // Rough estimate for code
let target_lines = ((target_tokens as f32) / avg_tokens_per_line) as usize;
let overlap_lines = ((overlap_tokens as f32) / avg_tokens_per_line) as usize;
let chunk_size = target_lines.max(5); // Minimum 5 lines
let overlap = overlap_lines.max(1); // Minimum 1 line overlap
// Pre-compute cumulative byte offsets for O(1) lookup, accounting for different line endings
let mut line_byte_offsets = Vec::with_capacity(lines.len() + 1);
line_byte_offsets.push(0);
let mut cumulative_offset = 0;
let mut byte_pos = 0;
for line in lines.iter() {
cumulative_offset += line.len();
// Find the actual line ending length in the original text
let line_end_pos = byte_pos + line.len();
let newline_len = if line_end_pos < text.len() && text.as_bytes()[line_end_pos] == b'\r' {
if line_end_pos + 1 < text.len() && text.as_bytes()[line_end_pos + 1] == b'\n' {
2 // CRLF
} else {
1 // CR only (old Mac)
}
} else if line_end_pos < text.len() && text.as_bytes()[line_end_pos] == b'\n' {
1 // LF only (Unix)
} else {
0 // No newline at this position (could be last line without newline)
};
cumulative_offset += newline_len;
byte_pos = cumulative_offset;
line_byte_offsets.push(cumulative_offset);
}
let mut i = 0;
while i < lines.len() {
let end = (i + chunk_size).min(lines.len());
let chunk_lines = &lines[i..end];
let chunk_text = chunk_lines.join("\n");
let byte_start = line_byte_offsets[i];
let byte_end = line_byte_offsets[end];
let metadata = ChunkMetadata::from_text(&chunk_text);
chunks.push(Chunk {
span: Span {
byte_start,
byte_end,
line_start: i + 1,
line_end: end,
},
text: chunk_text,
chunk_type: ChunkType::Text,
stride_info: None,
metadata,
});
i += chunk_size - overlap;
if i >= lines.len() {
break;
}
}
Ok(chunks)
}
pub(crate) fn tree_sitter_language(language: ParseableLanguage) -> Result<tree_sitter::Language> {
if language == ParseableLanguage::Markdown {
return Ok(tree_sitter_md::LANGUAGE.into());
}
let ts_language = match language {
ParseableLanguage::Python => tree_sitter_python::LANGUAGE,
ParseableLanguage::TypeScript | ParseableLanguage::JavaScript => {
tree_sitter_typescript::LANGUAGE_TYPESCRIPT
}
ParseableLanguage::Haskell => tree_sitter_haskell::LANGUAGE,
ParseableLanguage::Rust => tree_sitter_rust::LANGUAGE,
ParseableLanguage::Ruby => tree_sitter_ruby::LANGUAGE,
ParseableLanguage::Go => tree_sitter_go::LANGUAGE,
ParseableLanguage::C => tree_sitter_c::LANGUAGE,
ParseableLanguage::Cpp => tree_sitter_cpp::LANGUAGE,
ParseableLanguage::CSharp => tree_sitter_c_sharp::LANGUAGE,
ParseableLanguage::Zig => tree_sitter_zig::LANGUAGE,
ParseableLanguage::Dart => tree_sitter_dart::LANGUAGE,
ParseableLanguage::Elixir => tree_sitter_elixir::LANGUAGE,
ParseableLanguage::Markdown => unreachable!("Handled above via early return"),
};
Ok(ts_language.into())
}
fn chunk_language(text: &str, language: ParseableLanguage) -> Result<Vec<Chunk>> {
let mut parser = tree_sitter::Parser::new();
let ts_language = tree_sitter_language(language)?;
parser.set_language(&ts_language)?;
let tree = parser
.parse(text, None)
.ok_or_else(|| anyhow::anyhow!("Failed to parse {language} code"))?;
let mut chunks = match query_chunker::chunk_with_queries(language, ts_language, &tree, text)? {
Some(query_chunks) if !query_chunks.is_empty() => query_chunks,
_ => {
let mut legacy_chunks = Vec::new();
let mut cursor = tree.walk();
extract_code_chunks(&mut cursor, text, &mut legacy_chunks, language);
legacy_chunks
}
};
if chunks.is_empty() {
return chunk_generic(text);
}
// Post-process Haskell chunks to merge function equations
if language == ParseableLanguage::Haskell {
chunks = merge_haskell_functions(chunks, text);
}
// Fill gaps between chunks with remainder content. This must happen
// BEFORE suppress_contained_text_chunks so that gap-produced Text
// chunks (e.g., the run of field declarations and access specifiers
// inside a class body) are also subject to suppression — otherwise
// they leak through as standalone Text chunks (issue #136).
chunks = fill_gaps(chunks, text);
// Merge template-prefix gap chunks into the following C++ definition chunk
if language == ParseableLanguage::Cpp {
chunks = merge_cpp_template_prefix_chunks(chunks, text);
}
// Suppress text chunks fully contained by class/method/function chunks for C/C++
if matches!(language, ParseableLanguage::C | ParseableLanguage::Cpp) {
chunks = suppress_contained_text_chunks(chunks);
}
// Merge small chunks if Markdown
if language == ParseableLanguage::Markdown {
let (target_tokens, _) = get_model_chunk_config(None);
chunks = merge_small_chunks(chunks, text, target_tokens);
}
Ok(chunks)
}
fn suppress_contained_text_chunks(chunks: Vec<Chunk>) -> Vec<Chunk> {
if chunks.is_empty() {
return chunks;
}
let mut containers: Vec<(usize, usize)> = chunks
.iter()
.filter(|chunk| {
matches!(
chunk.chunk_type,
ChunkType::Class | ChunkType::Method | ChunkType::Function
)
})
.map(|chunk| (chunk.span.byte_start, chunk.span.byte_end))
.collect();
if containers.is_empty() {
return chunks;
}
containers.sort_by_key(|(start, _)| *start);
chunks
.into_iter()
.filter(|chunk| {
if chunk.chunk_type != ChunkType::Text {
return true;
}
let start = chunk.span.byte_start;
let end = chunk.span.byte_end;
!containers
.iter()
.any(|(c_start, c_end)| *c_start <= start && end <= *c_end)
})
.collect()
}
fn merge_cpp_template_prefix_chunks(chunks: Vec<Chunk>, text: &str) -> Vec<Chunk> {
if chunks.len() < 2 {
return chunks;
}
let mut merged = Vec::with_capacity(chunks.len());
let mut idx = 0;
while idx < chunks.len() {
if idx + 1 < chunks.len() && is_template_prefix_chunk(&chunks[idx]) {
let template_chunk = &chunks[idx];
let mut next_chunk = chunks[idx + 1].clone();
// Adjacency: byte_end may be <= next.byte_start, with only
// whitespace in between. Previously required strict equality
// which missed multiline templates and blank lines between
// the template clause and the definition (issue #136).
let gap_is_whitespace = template_chunk.span.byte_end <= next_chunk.span.byte_start
&& text
.get(template_chunk.span.byte_end..next_chunk.span.byte_start)
.is_some_and(|gap| gap.chars().all(char::is_whitespace));
if gap_is_whitespace
&& template_chunk.span.byte_start < next_chunk.span.byte_end
&& next_chunk.span.byte_end <= text.len()
{
let new_start = template_chunk.span.byte_start;
let new_end = next_chunk.span.byte_end;
if let Some(new_text) = text.get(new_start..new_end) {
let (line_start, line_end) = line_range_for_span(text, new_start, new_end);
next_chunk.span.byte_start = new_start;
next_chunk.span.line_start = line_start;
next_chunk.span.line_end = line_end;
next_chunk.text = new_text.to_string();
next_chunk.metadata = next_chunk.metadata.with_updated_text(new_text);
merged.push(next_chunk);
idx += 2;
continue;
}
}
}
merged.push(chunks[idx].clone());
idx += 1;
}
merged
}
fn is_template_prefix_chunk(chunk: &Chunk) -> bool {
if chunk.chunk_type != ChunkType::Text {
return false;
}
let mut has_template = false;
for line in chunk.text.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if trimmed.starts_with("template <") || trimmed.starts_with("template<") {
has_template = true;
continue;
}
return false;
}
has_template
}
fn line_range_for_span(text: &str, byte_start: usize, byte_end: usize) -> (usize, usize) {
let line_start = text[..byte_start].matches('\n').count() + 1;
let newlines_up_to_end = text[..byte_end].matches('\n').count();
let line_end = if newlines_up_to_end >= line_start - 1 {
newlines_up_to_end.max(line_start)
} else {
line_start
};
(line_start, line_end)
}
/// Fill gaps between chunks with remainder content
/// This ensures that leading imports, trailing code, and content between functions gets indexed
/// Combines contiguous gaps into single chunks (excluding standalone blank lines)
fn fill_gaps(mut chunks: Vec<Chunk>, text: &str) -> Vec<Chunk> {
if chunks.is_empty() {
return chunks;
}
// Sort chunks by byte position to identify gaps
chunks.sort_by_key(|c| c.span.byte_start);
let mut result = Vec::new();
let mut last_end = 0;
// Collect all gaps, splitting on blank lines
let mut gaps = Vec::new();
for chunk in &chunks {
if last_end < chunk.span.byte_start {
// Split this gap by blank lines - use split to make it simple
let gap_start = last_end;
let gap_text = &text[gap_start..chunk.span.byte_start];
// Split on sequences of blank lines
let mut current_byte = gap_start;
let mut segment_start = gap_start;
for line in gap_text.split('\n') {
let line_start_in_gap = current_byte - gap_start;
let _line_end_in_gap = line_start_in_gap + line.len();
if line.trim().is_empty() {
// Found a blank line - save segment before it if it has content
if segment_start < current_byte {
let segment_text = &text[segment_start..current_byte];
if !segment_text.trim().is_empty() {
gaps.push((segment_start, current_byte));
}
}
// Next segment starts after this blank line and its newline
segment_start = current_byte + line.len() + 1;
}
current_byte += line.len() + 1; // +1 for the \n
}
// Handle final segment (after last newline or if no newlines)
if segment_start < chunk.span.byte_start {
let remaining = &text[segment_start..chunk.span.byte_start];
if !remaining.trim().is_empty() {
gaps.push((segment_start, chunk.span.byte_start));
}
}
}
last_end = last_end.max(chunk.span.byte_end);
}
// Handle trailing content
if last_end < text.len() {
let gap_text = &text[last_end..];
if !gap_text.trim().is_empty() {
gaps.push((last_end, text.len()));
}
}
let combined_gaps = gaps;
// Now interleave chunks and combined gap chunks
let mut gap_idx = 0;
for chunk in chunks {
// Add any gap chunks that come before this structural chunk
while gap_idx < combined_gaps.len() && combined_gaps[gap_idx].1 <= chunk.span.byte_start {
let (gap_start, gap_end) = combined_gaps[gap_idx];
let gap_text = &text[gap_start..gap_end];
// Calculate line numbers by counting newlines before each position
let line_start = text[..gap_start].matches('\n').count() + 1;
// For line_end, count newlines in the text including the gap
// This gives us the line number of the last line with gap content
let newlines_up_to_end = text[..gap_end].matches('\n').count();
let line_end = if newlines_up_to_end >= line_start - 1 {
newlines_up_to_end.max(line_start)
} else {
line_start
};
let gap_chunk = Chunk {
text: gap_text.to_string(),
span: Span {
byte_start: gap_start,
byte_end: gap_end,
line_start,
line_end,
},
chunk_type: ChunkType::Text,
metadata: ChunkMetadata::from_text(gap_text),
stride_info: None,
};
result.push(gap_chunk);
gap_idx += 1;
}
result.push(chunk.clone());
}
// Add any remaining gap chunks after the last structural chunk
while gap_idx < combined_gaps.len() {
let (gap_start, gap_end) = combined_gaps[gap_idx];
let gap_text = &text[gap_start..gap_end];
// Calculate line numbers by counting newlines before each position
let line_start = text[..gap_start].matches('\n').count() + 1;
// For line_end, count newlines in the text including the gap
let newlines_up_to_end = text[..gap_end].matches('\n').count();
let line_end = if newlines_up_to_end >= line_start - 1 {
newlines_up_to_end.max(line_start)
} else {
line_start
};
let gap_chunk = Chunk {
text: gap_text.to_string(),
span: Span {
byte_start: gap_start,
byte_end: gap_end,
line_start,
line_end,
},
chunk_type: ChunkType::Text,
metadata: ChunkMetadata::from_text(gap_text),
stride_info: None,
};
result.push(gap_chunk);
gap_idx += 1;
}
result
}
/// Merge Haskell function equations that belong to the same function definition
fn merge_haskell_functions(chunks: Vec<Chunk>, source: &str) -> Vec<Chunk> {
if chunks.is_empty() {
return chunks;
}
let mut merged = Vec::new();
let mut i = 0;
while i < chunks.len() {
let chunk = &chunks[i];
// Skip chunks that are just fragments or comments
let trimmed = chunk.text.trim();
if trimmed.is_empty()
|| trimmed.starts_with("--")
|| trimmed.starts_with("{-")
|| !chunk.text.contains(|c: char| c.is_alphanumeric())
{
i += 1;
continue;
}
// Extract function name from the chunk text
// Check if it's a signature first (contains ::)
let is_signature = chunk.text.contains("::");
let function_name = if is_signature {
// For signatures like "factorial :: Integer -> Integer", extract "factorial"
chunk
.text
.split("::")
.next()
.and_then(|s| s.split_whitespace().next())
.map(std::string::ToString::to_string)
} else {
extract_haskell_function_name(&chunk.text)
};
if function_name.is_none() {
// Not a function (might be data, newtype, etc.), keep as-is
merged.push(chunk.clone());
i += 1;
continue;
}
let name = function_name.unwrap();
let group_start = chunk.span.byte_start;
let mut group_end = chunk.span.byte_end;
let line_start = chunk.span.line_start;
let mut line_end = chunk.span.line_end;
let mut trailing_trivia = chunk.metadata.trailing_trivia.clone();
// Look ahead for function equations with the same name
let mut j = i + 1;
while j < chunks.len() {
let next_chunk = &chunks[j];
// Skip comments
let next_trimmed = next_chunk.text.trim();
if next_trimmed.starts_with("--") || next_trimmed.starts_with("{-") {
j += 1;
continue;
}
let next_is_signature = next_chunk.text.contains("::");
let next_name = if next_is_signature {
next_chunk
.text
.split("::")
.next()
.and_then(|s| s.split_whitespace().next())
.map(std::string::ToString::to_string)
} else {
extract_haskell_function_name(&next_chunk.text)
};
if next_name == Some(name.clone()) {
// Extend the group to include this equation
group_end = next_chunk.span.byte_end;
line_end = next_chunk.span.line_end;
trailing_trivia = next_chunk.metadata.trailing_trivia.clone();
j += 1;
} else {
break;
}
}
// Create merged chunk
let merged_text = source.get(group_start..group_end).unwrap_or("").to_string();
let mut metadata = chunk.metadata.with_updated_text(&merged_text);
metadata.trailing_trivia = trailing_trivia;
merged.push(Chunk {
span: Span {
byte_start: group_start,
byte_end: group_end,
line_start,
line_end,
},
text: merged_text,
chunk_type: ChunkType::Function,
stride_info: None,
metadata,
});
i = j; // Skip past all merged chunks
}
merged
}
/// Extract the function name from a Haskell function equation
fn extract_haskell_function_name(text: &str) -> Option<String> {
// Haskell function equations start with the function name followed by patterns or =
// Examples: "factorial 0 = 1", "map f [] = []"
let trimmed = text.trim();
// Find the first word (function name)
let first_word = trimmed
.split_whitespace()
.next()?
.trim_end_matches(|c: char| !c.is_alphanumeric() && c != '_' && c != '\'');
// Validate it's a valid Haskell identifier (starts with lowercase or underscore)
if first_word.is_empty() {
return None;
}
let first_char = first_word.chars().next()?;
if first_char.is_lowercase() || first_char == '_' {
Some(first_word.to_string())
} else {
None
}
}
fn chunk_language_with_model(
text: &str,
language: ParseableLanguage,
_model_name: Option<&str>,
) -> Result<Vec<Chunk>> {
// For now, language-based chunking doesn't need model-specific behavior
// since it's based on semantic code boundaries rather than token counts
// We could potentially optimize this in the future by validating chunk token counts
chunk_language(text, language)
}
fn extract_code_chunks(
cursor: &mut tree_sitter::TreeCursor,
source: &str,
chunks: &mut Vec<Chunk>,
language: ParseableLanguage,
) {
let node = cursor.node();
// For Haskell: skip "function" nodes that are nested anywhere inside "signature" nodes
// (these are type expressions, not actual function definitions)
let should_skip = if language == ParseableLanguage::Haskell && node.kind() == "function" {
// Walk up parent chain to check if we're inside a signature
let mut current = node.parent();
while let Some(parent) = current {
if parent.kind() == "signature" {
return; // Skip this node and don't recurse
}
current = parent.parent();
}
false
} else {
false
};
if !should_skip
&& let Some(initial_chunk_type) = chunk_type_for_node(language, &node)
&& let Some(chunk) = build_chunk(node, source, initial_chunk_type, language)
{
let is_duplicate = chunks.iter().any(|existing| {
existing.span.byte_start == chunk.span.byte_start
&& existing.span.byte_end == chunk.span.byte_end
});
if !is_duplicate {
chunks.push(chunk);
}
}
// For Haskell signatures: don't recurse into children (they're just type expressions)
let should_recurse = !(language == ParseableLanguage::Haskell && node.kind() == "signature");
if should_recurse && cursor.goto_first_child() {
loop {
extract_code_chunks(cursor, source, chunks, language);
if !cursor.goto_next_sibling() {
break;
}
}
cursor.goto_parent();
}
}
fn chunk_type_for_node(
language: ParseableLanguage,
node: &tree_sitter::Node<'_>,
) -> Option<ChunkType> {
let kind = node.kind();
let supported = match language {
ParseableLanguage::Python => matches!(kind, "function_definition" | "class_definition"),
ParseableLanguage::TypeScript | ParseableLanguage::JavaScript => matches!(
kind,
"function_declaration" | "class_declaration" | "method_definition" | "arrow_function"
),
ParseableLanguage::Haskell => matches!(
kind,
"function" // Capture function equations
| "signature" // Capture type signatures (will be merged with functions)
| "data_type"
| "newtype"
| "type_synonym"
| "type_family"
| "class"
| "instance"
),
ParseableLanguage::Rust => matches!(
kind,
"function_item" | "impl_item" | "struct_item" | "enum_item" | "trait_item" | "mod_item"
),
ParseableLanguage::Ruby => {
matches!(kind, "method" | "class" | "module" | "singleton_method")
}
ParseableLanguage::Go => matches!(
kind,
"function_declaration"
| "method_declaration"
| "type_declaration"
| "var_declaration"
| "const_declaration"
),
ParseableLanguage::C => matches!(
kind,
"function_definition"
| "struct_specifier"
| "enum_specifier"
| "union_specifier"
| "type_definition"
| "declaration"
| "preproc_function_def"
| "preproc_def"
),
ParseableLanguage::Cpp => matches!(
kind,
"function_definition"
| "class_specifier"
| "struct_specifier"
| "enum_specifier"
| "union_specifier"
| "namespace_definition"
| "template_declaration"
| "type_definition"
| "alias_declaration"
| "declaration"
| "preproc_function_def"
| "preproc_def"
),
ParseableLanguage::CSharp => matches!(
kind,
"method_declaration"
| "class_declaration"
| "interface_declaration"
| "variable_declaration"
),
ParseableLanguage::Dart => matches!(
kind,
"class_definition"
| "class_declaration"
| "mixin_declaration"
| "enum_declaration"
| "function_declaration"
| "method_declaration"
| "constructor_declaration"
| "variable_declaration"
| "local_variable_declaration"
| "lambda_expression"