sephera_core 0.4.0

Shared analysis engine behind the Sephera CLI for LOC metrics, context building, and Tree-sitter AST compression.
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
//! AST node extraction for code compression.
//!
//! Given a parsed Tree-sitter tree, the extractor walks the root-level nodes
//! and emits a compressed representation that retains structural information
//! (function signatures, type definitions, imports) while discarding
//! implementation bodies.
//!
//! Two extraction strategies are available:
//!
//! * **Signatures** — keep only declarations; replace bodies with `{ … }`.
//! * **Skeleton** — keep declarations plus top-level control flow; drop only
//!   deeply nested logic.

use tree_sitter::{Node, Tree};

use super::{
    parser::SupportedLanguage,
    types::{CompressedOutput, CompressionMode},
};

/// Extracts a compressed representation from a fully parsed Tree-sitter tree.
///
/// # Arguments
///
/// * `source` — the original source bytes that the tree was parsed from.
/// * `tree`   — the parse tree returned by [`tree_sitter::Parser::parse`].
/// * `language` — determines which node types are treated as structurally
///   significant.
/// * `mode` — the compression level to apply.
///
/// When `mode` is [`CompressionMode::None`] the function returns the full
/// source unchanged.
///
/// # Examples
///
/// ```
/// use sephera_core::core::compression::{
///     CompressionMode, SupportedLanguage, extract_compressed, new_parser,
/// };
///
/// let source = b"fn greet(name: &str) -> String {\n    format!(\"hi {name}\")\n}\n";
/// let mut parser = new_parser(SupportedLanguage::Rust).unwrap();
/// let tree = parser.parse(source, None).unwrap();
/// let result = extract_compressed(source, &tree, SupportedLanguage::Rust, CompressionMode::Signatures);
/// assert!(result.content.contains("fn greet("));
/// assert!(result.content.contains("{ … }"));
/// assert!(!result.content.contains("format!"));
/// ```
#[must_use]
pub fn extract_compressed(
    source: &[u8],
    tree: &Tree,
    language: SupportedLanguage,
    mode: CompressionMode,
) -> CompressedOutput {
    if mode == CompressionMode::None {
        return CompressedOutput {
            content: String::from_utf8_lossy(source).into_owned(),
            items_extracted: 0,
            had_parse_errors: tree.root_node().has_error(),
        };
    }

    let root = tree.root_node();
    let had_parse_errors = root.has_error();
    let rules = extraction_rules(language);

    let mut output_lines: Vec<String> = Vec::new();
    let mut items_extracted: u64 = 0;

    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if let Some(extracted) = extract_node(source, &child, &rules, mode) {
            output_lines.push(extracted);
            items_extracted += 1;
        }
    }

    CompressedOutput {
        content: output_lines.join("\n\n"),
        items_extracted,
        had_parse_errors,
    }
}

/// The set of node type names that are structurally significant for a given
/// language.
struct ExtractionRules {
    /// Node types whose signature line is kept and whose body is replaced
    /// (functions, methods, closures, etc.).
    body_nodes: &'static [&'static str],

    /// Node types that are kept in full (struct definitions, type aliases,
    /// imports, const declarations, etc.).
    keep_nodes: &'static [&'static str],

    /// Node types that denote a block body to elide (`block`,
    /// `function_body`, etc.).
    body_field_names: &'static [&'static str],

    /// Additional node types to include in skeleton mode but not in
    /// signatures mode.
    skeleton_nodes: &'static [&'static str],
}

/// Returns the extraction rules for the given language.
#[allow(clippy::too_many_lines)]
const fn extraction_rules(language: SupportedLanguage) -> ExtractionRules {
    match language {
        SupportedLanguage::Rust => ExtractionRules {
            body_nodes: &["function_item", "impl_item", "trait_item"],
            keep_nodes: &[
                "use_declaration",
                "struct_item",
                "enum_item",
                "type_item",
                "const_item",
                "static_item",
                "mod_item",
                "extern_crate_declaration",
                "attribute_item",
                "macro_definition",
            ],
            body_field_names: &["block", "declaration_list"],
            skeleton_nodes: &[],
        },
        SupportedLanguage::Python => ExtractionRules {
            body_nodes: &["function_definition", "class_definition"],
            keep_nodes: &[
                "import_statement",
                "import_from_statement",
                "global_statement",
                "expression_statement",
            ],
            body_field_names: &["block", "body"],
            skeleton_nodes: &[
                "if_statement",
                "for_statement",
                "while_statement",
            ],
        },
        SupportedLanguage::TypeScript => ExtractionRules {
            body_nodes: &[
                "function_declaration",
                "method_definition",
                "arrow_function",
                "class_declaration",
            ],
            keep_nodes: &[
                "import_statement",
                "export_statement",
                "interface_declaration",
                "type_alias_declaration",
                "enum_declaration",
                "lexical_declaration",
                "variable_declaration",
            ],
            body_field_names: &["statement_block", "body", "class_body"],
            skeleton_nodes: &["if_statement", "for_statement"],
        },
        SupportedLanguage::JavaScript => ExtractionRules {
            body_nodes: &[
                "function_declaration",
                "method_definition",
                "arrow_function",
                "class_declaration",
            ],
            keep_nodes: &[
                "import_statement",
                "export_statement",
                "lexical_declaration",
                "variable_declaration",
            ],
            body_field_names: &["statement_block", "body", "class_body"],
            skeleton_nodes: &["if_statement", "for_statement"],
        },
        SupportedLanguage::Go => ExtractionRules {
            body_nodes: &["function_declaration", "method_declaration"],
            keep_nodes: &[
                "import_declaration",
                "package_clause",
                "type_declaration",
                "const_declaration",
                "var_declaration",
            ],
            body_field_names: &["block", "body"],
            skeleton_nodes: &[],
        },
        SupportedLanguage::Java => ExtractionRules {
            body_nodes: &[
                "method_declaration",
                "constructor_declaration",
                "class_declaration",
            ],
            keep_nodes: &[
                "import_declaration",
                "package_declaration",
                "interface_declaration",
                "enum_declaration",
                "annotation_type_declaration",
                "field_declaration",
            ],
            body_field_names: &["block", "body", "class_body"],
            skeleton_nodes: &[],
        },
        SupportedLanguage::Cpp | SupportedLanguage::C => ExtractionRules {
            body_nodes: &["function_definition", "template_declaration"],
            keep_nodes: &[
                "preproc_include",
                "preproc_def",
                "preproc_ifdef",
                "type_definition",
                "declaration",
                "struct_specifier",
                "enum_specifier",
                "namespace_definition",
                "using_declaration",
            ],
            body_field_names: &["compound_statement", "body"],
            skeleton_nodes: &[],
        },
    }
}

/// Attempts to extract a compressed representation of a single top-level node.
///
/// Returns `None` if the node is not structurally significant (e.g. whitespace,
/// comments that are already captured by surrounding context, or implementation
/// detail lines).
fn extract_node(
    source: &[u8],
    node: &Node<'_>,
    rules: &ExtractionRules,
    mode: CompressionMode,
) -> Option<String> {
    let kind = node.kind();

    // Comments are always kept.
    if kind == "comment" || kind == "line_comment" || kind == "block_comment" {
        let text = node_text(source, node);
        if !text.is_empty() {
            return Some(text);
        }
        return None;
    }

    // Nodes whose body should be elided.
    if rules.body_nodes.contains(&kind) {
        return Some(extract_with_elided_body(source, node, rules));
    }

    // Nodes kept verbatim.
    if rules.keep_nodes.contains(&kind) {
        return Some(node_text(source, node));
    }

    // In skeleton mode, include additional structural nodes.
    if mode == CompressionMode::Skeleton && rules.skeleton_nodes.contains(&kind)
    {
        return Some(extract_with_elided_body(source, node, rules));
    }

    None
}

/// Returns the text of a node, preserving the original source encoding.
fn node_text(source: &[u8], node: &Node<'_>) -> String {
    let start_byte = node.start_byte();
    let end_byte = node.end_byte();
    if start_byte >= source.len() {
        return String::new();
    }
    let end = end_byte.min(source.len());
    String::from_utf8_lossy(&source[start_byte..end])
        .trim_end()
        .to_owned()
}

/// Returns the node text up to the start of its body, followed by `{ … }`.
///
/// If the node has no recognisable body child, the full text is returned
/// instead.
fn extract_with_elided_body(
    source: &[u8],
    node: &Node<'_>,
    rules: &ExtractionRules,
) -> String {
    // Try to find a body child to elide.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if rules.body_field_names.contains(&child.kind()) {
            let signature_end = child.start_byte();
            let signature = String::from_utf8_lossy(
                &source[node.start_byte()..signature_end],
            )
            .trim_end()
            .to_owned();
            return format!("{signature} {{}}");
        }
    }

    // Fallback: no body found; return full text.
    node_text(source, node)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::compression::parser::new_parser;

    fn compress(
        source: &str,
        language: SupportedLanguage,
        mode: CompressionMode,
    ) -> CompressedOutput {
        let bytes = source.as_bytes();
        let mut parser = new_parser(language).unwrap();
        let tree = parser.parse(bytes, None).unwrap();
        extract_compressed(bytes, &tree, language, mode)
    }

    // ---- Rust ----

    #[test]
    fn rust_signatures_elides_function_body() {
        let result = compress(
            "fn add(a: i32, b: i32) -> i32 {\n    a + b\n}\n",
            SupportedLanguage::Rust,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("fn add(a: i32, b: i32) -> i32"));
        assert!(result.content.contains("{ … }"));
        assert!(!result.content.contains("a + b"));
        assert_eq!(result.items_extracted, 1);
    }

    #[test]
    fn rust_keeps_use_declarations() {
        let result = compress(
            "use std::collections::HashMap;\n\nfn main() {}\n",
            SupportedLanguage::Rust,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("use std::collections::HashMap;"));
    }

    #[test]
    fn rust_keeps_struct_definitions() {
        let result = compress(
            "pub struct Point {\n    pub x: f64,\n    pub y: f64,\n}\n",
            SupportedLanguage::Rust,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("pub struct Point"));
        assert!(result.content.contains("pub x: f64"));
    }

    #[test]
    fn rust_keeps_enum_definitions() {
        let result = compress(
            "pub enum Color {\n    Red,\n    Green,\n    Blue,\n}\n",
            SupportedLanguage::Rust,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("pub enum Color"));
        assert!(result.content.contains("Red"));
    }

    #[test]
    fn rust_none_mode_returns_full_source() {
        let source = "fn main() {\n    println!(\"hello\");\n}\n";
        let result =
            compress(source, SupportedLanguage::Rust, CompressionMode::None);
        assert_eq!(result.content, source);
        assert_eq!(result.items_extracted, 0);
    }

    // ---- Python ----

    #[test]
    fn python_signatures_elides_function_body() {
        let result = compress(
            "def greet(name: str) -> str:\n    return f\"Hello {name}\"\n",
            SupportedLanguage::Python,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("def greet("));
        assert!(!result.content.contains("return"));
    }

    #[test]
    fn python_keeps_imports() {
        let result = compress(
            "import os\nfrom pathlib import Path\n\ndef main():\n    pass\n",
            SupportedLanguage::Python,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("import os"));
        assert!(result.content.contains("from pathlib import Path"));
    }

    // ---- Go ----

    #[test]
    fn go_signatures_elides_function_body() {
        let result = compress(
            "package main\n\nfunc Add(a int, b int) int {\n\treturn a + b\n}\n",
            SupportedLanguage::Go,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("func Add(a int, b int) int"));
        assert!(result.content.contains("{ … }"));
        assert!(!result.content.contains("return a + b"));
    }

    #[test]
    fn go_keeps_package_and_imports() {
        let result = compress(
            "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hi\")\n}\n",
            SupportedLanguage::Go,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("package main"));
        assert!(result.content.contains("import \"fmt\""));
    }

    // ---- JavaScript ----

    #[test]
    fn javascript_signatures_elides_function_body() {
        let result = compress(
            "function greet(name) {\n  return `Hello ${name}`;\n}\n",
            SupportedLanguage::JavaScript,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("function greet(name)"));
        assert!(result.content.contains("{ … }"));
    }

    #[test]
    fn javascript_keeps_imports() {
        let result = compress(
            "import { foo } from './bar';\n\nfunction main() {}\n",
            SupportedLanguage::JavaScript,
            CompressionMode::Signatures,
        );
        assert!(result.content.contains("import { foo } from './bar'"));
    }

    // ---- Parse error handling ----

    #[test]
    fn reports_parse_errors() {
        let result = compress(
            "fn broken( {\n",
            SupportedLanguage::Rust,
            CompressionMode::Signatures,
        );
        assert!(result.had_parse_errors);
    }

    // ---- Multiple items ----

    #[test]
    fn extracts_multiple_items() {
        let result = compress(
            concat!(
                "use std::io;\n\n",
                "pub struct Config {\n    pub path: String,\n}\n\n",
                "pub fn run(config: Config) -> Result<(), String> {\n",
                "    Ok(())\n",
                "}\n\n",
                "pub fn helper() -> bool {\n    true\n}\n",
            ),
            SupportedLanguage::Rust,
            CompressionMode::Signatures,
        );
        assert!(result.items_extracted >= 4);
        assert!(result.content.contains("use std::io"));
        assert!(result.content.contains("pub struct Config"));
        assert!(result.content.contains("pub fn run("));
        assert!(result.content.contains("pub fn helper("));
    }
}