niblits 0.3.8

Token-aware, multi-format text chunking library with language-aware semantic splitting
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
use tree_sitter::{Node, Tree, TreeCursor};

use crate::types::{ChunkError, ChunkMetadata, FileSymbols, LineIndex, OutlineUnit};

/// Extracts metadata from a pre-parsed tree-sitter Tree for a code chunk.
pub fn extract_metadata_from_tree(
  tree: &Tree,
  content: &str,
  chunk_start: usize,
  chunk_end: usize,
  language_name: &str,
) -> Result<ChunkMetadata, ChunkError> {
  let root_node = tree.root_node();

  // Find the primary node that contains the chunk.
  let primary_node = find_primary_node_for_range(root_node, chunk_start, chunk_end);

  // Extract node type.
  let node_type = primary_node.kind().to_string();

  // Extract node name (e.g., function name, class name).
  let node_name = extract_node_name(&primary_node, content);

  // Build scope path by traversing parents.
  let scope_path = build_scope_path(&primary_node, content);

  // Extract parent context.
  let parent_context = extract_parent_context(&primary_node, content);

  // Extract definitions and references within the chunk.
  let (definitions, references) = extract_symbols_in_range(root_node, content, chunk_start, chunk_end);

  Ok(ChunkMetadata {
    node_type,
    node_name,
    language: language_name.to_string(),
    parent_context,
    scope_path,
    definitions,
    references,
  })
}

/// Extract file-level outline units plus aggregate definitions/references.
pub fn extract_file_symbols(tree: &Tree, content: &str) -> FileSymbols {
  let root_node = tree.root_node();
  let mut cursor = root_node.walk();
  let line_index = LineIndex::new(content);
  let mut outline = Vec::new();

  extract_outline_units(&mut cursor, content, &line_index, &mut outline);
  outline.sort_by(|a, b| {
    a.start_byte
      .cmp(&b.start_byte)
      .then_with(|| a.end_byte.cmp(&b.end_byte))
      .then_with(|| a.kind.cmp(&b.kind))
      .then_with(|| a.name.as_deref().unwrap_or("").cmp(b.name.as_deref().unwrap_or("")))
  });

  let (definitions, references) = extract_symbols_in_range(root_node, content, 0, content.len());

  FileSymbols {
    outline,
    definitions,
    references,
  }
}

/// Find the most specific node that fully contains the given byte range.
fn find_primary_node_for_range(node: Node, start_byte: usize, end_byte: usize) -> Node {
  let mut cursor = node.walk();
  let mut best_node = node;

  // DFS to find the most specific node containing the range.
  visit_node(&mut cursor, &mut best_node, start_byte, end_byte);

  best_node
}

fn visit_node<'a>(cursor: &mut TreeCursor<'a>, best_node: &mut Node<'a>, start_byte: usize, end_byte: usize) {
  let node = cursor.node();

  // Check if this node fully contains our range.
  if node.start_byte() <= start_byte && node.end_byte() >= end_byte {
    // This node is a better match if it's more specific (smaller).
    if node.byte_range().len() < best_node.byte_range().len() {
      *best_node = node;
    }

    // Check children for an even more specific match.
    if cursor.goto_first_child() {
      loop {
        visit_node(cursor, best_node, start_byte, end_byte);
        if !cursor.goto_next_sibling() {
          break;
        }
      }
      cursor.goto_parent();
    }
  }
}

fn extract_outline_units(
  cursor: &mut TreeCursor,
  content: &str,
  line_index: &LineIndex,
  outline: &mut Vec<OutlineUnit>,
) {
  let node = cursor.node();
  if is_significant_scope(node.kind()) {
    let (start_line, end_line) = line_index.line_numbers(node.start_byte(), node.end_byte());
    outline.push(OutlineUnit {
      kind: node.kind().to_string(),
      name: extract_node_name(&node, content),
      start_byte: node.start_byte(),
      end_byte: node.end_byte(),
      start_line,
      end_line,
    });
  }

  if cursor.goto_first_child() {
    loop {
      extract_outline_units(cursor, content, line_index, outline);
      if !cursor.goto_next_sibling() {
        break;
      }
    }
    cursor.goto_parent();
  }
}

/// Extract the name of a node (e.g., function name, class name).
fn extract_node_name(node: &Node, content: &str) -> Option<String> {
  match node.kind() {
    // Functions and methods.
    "function_declaration"
    | "function_definition"
    | "method_definition"
    | "function_item"
    | "function"
    | "method_declaration" => find_child_by_kind(node, "identifier")
      .or_else(|| find_child_by_kind(node, "property_identifier"))
      .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string()),

    // Classes and similar constructs.
    "class_declaration" | "class_definition" | "class" => find_child_by_kind(node, "identifier")
      .or_else(|| find_child_by_kind(node, "type_identifier"))
      .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string()),

    // Interfaces and traits.
    "interface_declaration" | "trait_item" | "trait_definition" => find_child_by_kind(node, "identifier")
      .or_else(|| find_child_by_kind(node, "type_identifier"))
      .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string()),

    // Enums.
    "enum_declaration" | "enum_specifier" => find_child_by_kind(node, "identifier")
      .or_else(|| find_child_by_kind(node, "type_identifier"))
      .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string()),

    // Structs.
    "struct_item" | "struct_declaration" | "struct_specifier" => find_child_by_kind(node, "type_identifier")
      .or_else(|| find_child_by_kind(node, "identifier"))
      .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string()),

    // Constructors.
    "constructor_declaration" => {
      find_child_by_kind(node, "identifier").map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string())
    }

    // Properties.
    "property_declaration" => {
      find_child_by_kind(node, "identifier").map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string())
    }

    // Modules.
    "module" | "module_definition" => find_child_by_kind(node, "identifier")
      .or_else(|| find_child_by_kind(node, "module_name"))
      .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string()),

    // Rust-specific.
    "impl_item" => {
      if let Some(type_id) = find_child_by_kind(node, "type_identifier") {
        Some(type_id.utf8_text(content.as_bytes()).unwrap_or("").to_string())
      } else if let Some(generic_type) = find_child_by_kind(node, "generic_type") {
        find_child_by_kind(&generic_type, "type_identifier")
          .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string())
      } else {
        None
      }
    }
    "enum_item" | "const_item" | "static_item" | "mod_item" => find_child_by_kind(node, "identifier")
      .or_else(|| find_child_by_kind(node, "type_identifier"))
      .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string()),

    // Language-specific function-like constructs.
    "def" | "defn" | "defp" | "defmodule" | "defprotocol" => {
      find_child_by_kind(node, "identifier").map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string())
    }

    // Additional important block-level constructs.
    "object_definition" | "object_declaration" => find_child_by_kind(node, "identifier")
      .or_else(|| find_child_by_kind(node, "type_identifier"))
      .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string()),

    "namespace_declaration" | "namespace_definition" => {
      find_child_by_kind(node, "identifier").map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string())
    }

    _ => None,
  }
}

/// Find a child node by its kind.
fn find_child_by_kind<'a>(node: &'a Node, kind: &str) -> Option<Node<'a>> {
  let mut cursor = node.walk();
  node.children(&mut cursor).find(|&child| child.kind() == kind)
}

/// Build a scope path by traversing parent nodes.
fn build_scope_path(node: &Node, content: &str) -> Vec<String> {
  let mut path = Vec::new();
  let mut current = Some(*node);

  while let Some(n) = current {
    if let Some(name) = extract_node_name(&n, content) {
      path.push(name);
    } else if is_significant_scope(n.kind()) {
      path.push(n.kind().to_string());
    }
    current = n.parent();
  }

  path.reverse();
  path
}

/// Check if a node type represents a significant scope.
fn is_significant_scope(kind: &str) -> bool {
  matches!(
    kind,
    // Functions and methods.
    "function_declaration" | "function_definition" | "method_definition" |
        "function_item" | "function" | "method_declaration" |

        // Classes and similar.
        "class_declaration" | "class_definition" | "class" |

        // Interfaces and traits.
        "interface_declaration" | "trait_item" | "trait_definition" |

        // Enums.
        "enum_declaration" | "enum_specifier" |

        // Structs.
        "struct_item" | "struct_declaration" | "struct_specifier" |

        // Constructors and properties.
        "constructor_declaration" | "property_declaration" |

        // Modules.
        "module" | "module_definition" |

        // Rust-specific.
        "impl_item" | "enum_item" | "const_item" | "static_item" | "mod_item" |

        // Language-specific constructs.
        "def" | "defn" | "defp" | "defmodule" | "defprotocol" | "defimpl" |

        // Additional important block-level constructs.
        "object_definition" | "object_declaration" |

        // Other scopes.
        "namespace" | "namespace_declaration" | "namespace_definition"
  )
}

/// Extract parent context (e.g., class name for a method).
fn extract_parent_context(node: &Node, content: &str) -> Option<String> {
  let mut parent = node.parent();

  while let Some(p) = parent {
    if is_significant_scope(p.kind()) {
      return extract_node_name(&p, content);
    }
    parent = p.parent();
  }

  None
}

/// Extract definitions and references within a byte range.
fn extract_symbols_in_range(
  root: Node,
  content: &str,
  start_byte: usize,
  end_byte: usize,
) -> (Vec<String>, Vec<String>) {
  let mut definitions = Vec::new();
  let mut references = Vec::new();

  let mut cursor = root.walk();
  extract_symbols_recursive(
    &mut cursor,
    content,
    start_byte,
    end_byte,
    &mut definitions,
    &mut references,
  );

  // Remove duplicates.
  definitions.sort();
  definitions.dedup();
  references.sort();
  references.dedup();

  (definitions, references)
}

fn extract_symbols_recursive(
  cursor: &mut TreeCursor,
  content: &str,
  start_byte: usize,
  end_byte: usize,
  definitions: &mut Vec<String>,
  references: &mut Vec<String>,
) {
  let node = cursor.node();

  // Only process nodes within our range.
  if node.end_byte() < start_byte || node.start_byte() > end_byte {
    return;
  }

  match node.kind() {
    // Variable/parameter definitions.
    "variable_declarator" | "parameter" | "identifier" if is_definition_context(&node) => {
      if let Ok(text) = node.utf8_text(content.as_bytes()) {
        definitions.push(text.to_string());
      }
    }

    // Function/method definitions.
    "function_declaration"
    | "function_definition"
    | "method_definition"
    | "function_item"
    | "function"
    | "method_declaration" => {
      if let Some(name_node) = find_child_by_kind(&node, "identifier")
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    // Class/struct/interface/trait definitions.
    "class_declaration"
    | "class_definition"
    | "struct_item"
    | "interface_declaration"
    | "struct_declaration"
    | "struct_specifier"
    | "trait_definition" => {
      if let Some(name_node) =
        find_child_by_kind(&node, "identifier").or_else(|| find_child_by_kind(&node, "type_identifier"))
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    // Enum definitions.
    "enum_declaration" | "enum_specifier" | "enum_item" => {
      if let Some(name_node) =
        find_child_by_kind(&node, "identifier").or_else(|| find_child_by_kind(&node, "type_identifier"))
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    // Constructor and property definitions.
    "constructor_declaration" | "property_declaration" => {
      if let Some(name_node) = find_child_by_kind(&node, "identifier")
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    // Module definitions.
    "module" | "module_definition" | "mod_item" => {
      if let Some(name_node) =
        find_child_by_kind(&node, "identifier").or_else(|| find_child_by_kind(&node, "module_name"))
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    // Rust-specific definitions.
    "const_item" | "static_item" => {
      if let Some(name_node) = find_child_by_kind(&node, "identifier")
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    // Language-specific function definitions.
    "def" | "defn" | "defp" | "defmodule" | "defprotocol" | "defimpl" => {
      if let Some(name_node) = find_child_by_kind(&node, "identifier")
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    // Additional important definitions.
    "object_definition" | "object_declaration" => {
      if let Some(name_node) =
        find_child_by_kind(&node, "identifier").or_else(|| find_child_by_kind(&node, "type_identifier"))
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    "namespace_declaration" | "namespace_definition" => {
      if let Some(name_node) = find_child_by_kind(&node, "identifier")
        && let Ok(text) = name_node.utf8_text(content.as_bytes())
      {
        definitions.push(text.to_string());
      }
    }

    // References (function calls, variable usage).
    "call_expression" | "call" => {
      if let Some(func_node) = node.child(0)
        && let Ok(text) = func_node.utf8_text(content.as_bytes())
      {
        references.push(text.to_string());
      }
    }

    _ => {}
  }

  if cursor.goto_first_child() {
    loop {
      extract_symbols_recursive(cursor, content, start_byte, end_byte, definitions, references);
      if !cursor.goto_next_sibling() {
        break;
      }
    }
    cursor.goto_parent();
  }
}

/// Check if an identifier node is in a definition context.
fn is_definition_context(node: &Node) -> bool {
  if let Some(parent) = node.parent() {
    matches!(
      parent.kind(),
      "variable_declarator" | "parameter" | "formal_parameters" | "pattern" | "shorthand_property_identifier_pattern"
    )
  } else {
    false
  }
}