Skip to main content

semantic/
semantic_index.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Semantic-index *extraction*: turning a source blob into the per-file symbol
3//! list the merkle semantic index (heddle#1067) stores.
4//!
5//! The index node types and the canonical digest/hash byte layouts live in the
6//! `objects` crate ([`objects::object::semantic_index`]); this module owns the
7//! grammar-facing half — walking the AST to produce [`SymbolEntry`] values with
8//! their normalization-stable `semantic_hash`. Assembly of the tree and the
9//! store wiring live in the `repo` crate.
10//!
11//! A symbol's `semantic_hash` is a pure function of
12//! `(source bytes, grammar, extractor_version)`: a DFS in document order over
13//! the definition's node, comment subtrees skipped, each remaining leaf emitted
14//! as `u32-LE(byte_len) ‖ exact source bytes`. Whitespace and comments are not
15//! leaves, so reformatting and comment edits leave the hash untouched — while a
16//! one-token change perturbs exactly the symbols that contain it.
17
18use objects::object::{
19    ContentHash, SymbolEntry, SymbolKindTag, compute_file_scaffold_hash,
20    compute_symbol_semantic_hash,
21};
22
23use crate::{
24    parser::{Language, ParsedFile, walk_non_comment_leaves},
25    symbol_resolver::{DefinitionKind, visit_definitions},
26};
27
28/// Version of the extraction logic itself. Bump when the taxonomy, container
29/// resolution, or token-stream framing changes in a way that would alter a
30/// `semantic_hash` for unchanged source — it participates in the file node's
31/// identity so a bump forces a clean recompute via the supersedes chain.
32///
33/// v2: `hd-sem-file-v2`/`hd-sem-dir-v2` framed layouts, the `scaffold_hash`
34/// (non-definition file content), and mod-qualified `container_path`. Bumped so
35/// any same-version-but-old-layout nodes written by a pre-fix branch checkout
36/// are treated as stale and recomputed rather than digest-compared.
37///
38/// v3: Zig extraction added. `parent_is_reusable` only validates grammars
39/// *present* in the parent's map, so a pre-Zig index (no `"zig"` entry) would
40/// otherwise carry `.zig` files forward as `Opaque` indefinitely. The bump
41/// forces those to recompute so imported Zig repos gain granularity.
42pub const EXTRACTOR_VERSION: u32 = 3;
43
44/// Stable lowercase language name recorded in file nodes and the root's
45/// grammar map.
46pub fn language_name(language: Language) -> &'static str {
47    match language {
48        Language::Rust => "rust",
49        Language::Python => "python",
50        Language::JavaScript => "javascript",
51        Language::TypeScript => "typescript",
52        Language::Go => "go",
53        Language::C => "c",
54        Language::Cpp => "cpp",
55        Language::Java => "java",
56        Language::Zig => "zig",
57        Language::Unknown => "unknown",
58    }
59}
60
61/// Grammar version string for a language — the tree-sitter grammar crate
62/// version. Participates in node identity so a grammar bump recomputes cleanly.
63pub fn grammar_version(language: Language) -> &'static str {
64    match language {
65        Language::Rust => "tree-sitter-rust@0.24",
66        Language::Python => "tree-sitter-python@0.25",
67        Language::JavaScript => "tree-sitter-javascript@0.25",
68        Language::TypeScript => "tree-sitter-typescript@0.23",
69        Language::Go => "tree-sitter-go@0.25",
70        Language::C => "tree-sitter-c@0.24",
71        Language::Cpp => "tree-sitter-cpp@0.23",
72        Language::Java => "tree-sitter-java@0.23",
73        Language::Zig => "tree-sitter-zig@1.1",
74        Language::Unknown => "none",
75    }
76}
77
78/// The current grammar version for a language *name* (as recorded in a
79/// [`SemanticIndexRoot`](objects::object::SemanticIndexRoot)'s grammar map).
80/// Used by the builder to detect a grammar bump and refuse stale node reuse.
81pub fn grammar_version_by_name(name: &str) -> Option<&'static str> {
82    let language = match name {
83        "rust" => Language::Rust,
84        "python" => Language::Python,
85        "javascript" => Language::JavaScript,
86        "typescript" => Language::TypeScript,
87        "go" => Language::Go,
88        "c" => Language::C,
89        "cpp" => Language::Cpp,
90        "java" => Language::Java,
91        "zig" => Language::Zig,
92        _ => return None,
93    };
94    Some(grammar_version(language))
95}
96
97fn map_kind(kind: DefinitionKind) -> SymbolKindTag {
98    match kind {
99        DefinitionKind::Function => SymbolKindTag::Function,
100        DefinitionKind::Type => SymbolKindTag::Type,
101        DefinitionKind::Trait => SymbolKindTag::Trait,
102        DefinitionKind::Class => SymbolKindTag::Class,
103        DefinitionKind::Interface => SymbolKindTag::Interface,
104        DefinitionKind::TypeAlias => SymbolKindTag::TypeAlias,
105        DefinitionKind::EnumDef => SymbolKindTag::Enum,
106        DefinitionKind::ConstDecl => SymbolKindTag::Const,
107        DefinitionKind::Module => SymbolKindTag::Module,
108        DefinitionKind::Other => SymbolKindTag::Other,
109    }
110}
111
112/// The symbols extracted from one source file, plus the file scaffold hash,
113/// ready to be assembled into a
114/// [`SemanticFileNode`](objects::object::SemanticFileNode).
115pub struct ExtractedFile {
116    pub language: Language,
117    /// Hash of the residual non-definition top-level token stream — binds
118    /// use-decls, impl/attribute/macro tokens and definition-free files into
119    /// the file digest. See [`compute_file_scaffold_hash`].
120    pub scaffold_hash: ContentHash,
121    pub symbols: Vec<SymbolEntry>,
122}
123
124/// Parse `source` (as `language`) and extract its symbols with per-symbol
125/// normalization-stable hashes, plus the file scaffold hash.
126///
127/// Returns `None` when the language is unsupported or the file fails to parse —
128/// the caller records those as `Opaque` in the index (fingerprint = raw source
129/// blob hash).
130pub fn extract_semantic_file(source: &[u8], language: Language) -> Option<ExtractedFile> {
131    // Unsupported language → no grammar → Opaque.
132    language.parser_handle()?;
133    let source_text = std::str::from_utf8(source).ok()?;
134    let parsed = ParsedFile::parse(source_text, language)?;
135
136    let mut symbols = Vec::new();
137    // Byte ranges of every extracted definition node — used to carve the
138    // residual scaffold (everything NOT covered by a symbol).
139    let mut covered: Vec<(usize, usize)> = Vec::new();
140    visit_definitions(parsed.root_node(), source, &mut |site| {
141        let kind = map_kind(site.kind);
142        let semantic_hash = symbol_semantic_hash(site.node, source, kind);
143        let container_path = site.parent_name.map(|p| vec![p]).unwrap_or_default();
144        let range = site.node.byte_range();
145        covered.push((range.start, range.end));
146        symbols.push(SymbolEntry {
147            name: site.name,
148            kind,
149            container_path,
150            semantic_hash,
151            span: (site.start_line, site.end_line),
152        });
153    });
154
155    let scaffold_hash = compute_scaffold(parsed.root_node(), source, covered);
156
157    Some(ExtractedFile {
158        language,
159        scaffold_hash,
160        symbols,
161    })
162}
163
164/// Hash the file scaffold: every non-comment leaf under the root NOT covered by
165/// an extracted symbol's byte range, length-prefixed in document order. This is
166/// what carries use-decl swaps, `impl Trait` headers, attribute edits,
167/// `macro_rules!` bodies and definition-free files into the file digest.
168fn compute_scaffold(
169    root: tree_sitter::Node<'_>,
170    source: &[u8],
171    mut covered: Vec<(usize, usize)>,
172) -> ContentHash {
173    // Merge symbol ranges into disjoint sorted intervals (they nest — a module
174    // covers its children).
175    covered.sort_by_key(|&(start, _)| start);
176    let mut merged: Vec<(usize, usize)> = Vec::with_capacity(covered.len());
177    for (start, end) in covered {
178        match merged.last_mut() {
179            Some(last) if start <= last.1 => last.1 = last.1.max(end),
180            _ => merged.push((start, end)),
181        }
182    }
183
184    let mut stream: Vec<u8> = Vec::new();
185    walk_non_comment_leaves(root, |leaf| {
186        let range = leaf.byte_range();
187        if is_covered(&merged, range.start, range.end) {
188            return;
189        }
190        let bytes = &source[range];
191        stream.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
192        stream.extend_from_slice(bytes);
193    });
194    compute_file_scaffold_hash(&stream)
195}
196
197/// Whether `[start, end)` lies fully within one of the disjoint sorted
198/// intervals in `merged`.
199fn is_covered(merged: &[(usize, usize)], start: usize, end: usize) -> bool {
200    match merged.binary_search_by(|&(interval_start, _)| interval_start.cmp(&start)) {
201        Ok(i) => merged[i].1 >= end,
202        Err(0) => false,
203        Err(i) => merged[i - 1].1 >= end,
204    }
205}
206
207/// Build the canonical `hd-sem-sym-v1` token stream for a definition node and
208/// hash it. Length-prefixed leaves in document order, comment subtrees skipped.
209fn symbol_semantic_hash(
210    node: tree_sitter::Node<'_>,
211    source: &[u8],
212    kind: SymbolKindTag,
213) -> ContentHash {
214    let mut token_stream: Vec<u8> = Vec::new();
215    walk_non_comment_leaves(node, |leaf| {
216        let bytes = &source[leaf.byte_range()];
217        token_stream.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
218        token_stream.extend_from_slice(bytes);
219    });
220    compute_symbol_semantic_hash(kind, &token_stream)
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    fn extract(src: &str) -> Vec<SymbolEntry> {
228        extract_semantic_file(src.as_bytes(), Language::Rust)
229            .expect("rust parse")
230            .symbols
231    }
232
233    fn scaffold(src: &str) -> ContentHash {
234        extract_semantic_file(src.as_bytes(), Language::Rust)
235            .expect("rust parse")
236            .scaffold_hash
237    }
238
239    /// DEFECT 1: content that lives OUTSIDE any extracted symbol must still
240    /// perturb the file scaffold (and therefore the file digest). Covers all
241    /// five classes Fable flagged as digest false-negatives.
242    #[test]
243    fn scaffold_binds_non_definition_content() {
244        // 1. use-decl swap (same fn body)
245        assert_ne!(
246            scaffold("use a::x;\nfn f() { g(); }\n"),
247            scaffold("use b::x;\nfn f() { g(); }\n"),
248            "use-decl swap"
249        );
250        // 2. impl-trait change, identical method body
251        assert_ne!(
252            scaffold("struct S;\nimpl Display for S { fn fmt(&self) {} }\n"),
253            scaffold("struct S;\nimpl Debug for S { fn fmt(&self) {} }\n"),
254            "impl trait change"
255        );
256        // 3. attribute add/remove (attribute_item is a sibling of function_item)
257        assert_ne!(
258            scaffold("fn f() { g(); }\n"),
259            scaffold("#[inline]\nfn f() { g(); }\n"),
260            "attribute add"
261        );
262        // 4. macro_rules! body edit
263        assert_ne!(
264            scaffold("macro_rules! m { () => { 1 }; }\n"),
265            scaffold("macro_rules! m { () => { 2 }; }\n"),
266            "macro_rules body edit"
267        );
268        // 5. definition-free files (re-export only) — two different such files
269        //    must not share a digest.
270        assert_ne!(
271            scaffold("pub use crate::a::Foo;\n"),
272            scaffold("pub use crate::b::Bar;\n"),
273            "definition-free re-export files"
274        );
275    }
276
277    /// The scaffold must stay reformat- and comment-stable, like symbol hashes.
278    #[test]
279    fn scaffold_is_reformat_and_comment_stable() {
280        assert_eq!(
281            scaffold("use a::x;\nfn f() { g(); }\n"),
282            scaffold("use   a::x;\n\n// note\nfn f() {\n    g();\n}\n"),
283        );
284    }
285
286    #[test]
287    fn reformat_leaves_symbol_hash_stable() {
288        let a = "fn add(a: i32, b: i32) -> i32 { a + b }\n";
289        let b = "fn add(a: i32,   b: i32) -> i32 {\n    a + b\n}\n";
290        let sa = extract(a);
291        let sb = extract(b);
292        assert_eq!(sa.len(), 1);
293        assert_eq!(sb.len(), 1);
294        assert_eq!(
295            sa[0].semantic_hash, sb[0].semantic_hash,
296            "reformatting must not change the symbol semantic_hash"
297        );
298    }
299
300    #[test]
301    fn comment_edit_leaves_symbol_hash_stable() {
302        let a = "fn f() {\n    // old comment\n    g();\n}\n";
303        let b = "fn f() {\n    // a completely different comment\n    g();\n}\n";
304        assert_eq!(extract(a)[0].semantic_hash, extract(b)[0].semantic_hash);
305    }
306
307    #[test]
308    fn one_token_change_perturbs_only_that_symbol() {
309        let a = "fn f() -> i32 { 1 }\nfn g() -> i32 { 2 }\n";
310        let b = "fn f() -> i32 { 1 }\nfn g() -> i32 { 3 }\n";
311        let sa = extract(a);
312        let sb = extract(b);
313        let f_a = sa.iter().find(|s| s.name == "f").unwrap();
314        let f_b = sb.iter().find(|s| s.name == "f").unwrap();
315        let g_a = sa.iter().find(|s| s.name == "g").unwrap();
316        let g_b = sb.iter().find(|s| s.name == "g").unwrap();
317        assert_eq!(
318            f_a.semantic_hash, f_b.semantic_hash,
319            "untouched symbol stable"
320        );
321        assert_ne!(
322            g_a.semantic_hash, g_b.semantic_hash,
323            "edited symbol changes"
324        );
325    }
326
327    #[test]
328    fn string_literal_contents_included() {
329        let a = "fn f() { let s = \"hello\"; }\n";
330        let b = "fn f() { let s = \"world\"; }\n";
331        assert_ne!(
332            extract(a)[0].semantic_hash,
333            extract(b)[0].semantic_hash,
334            "string literal contents are part of the fingerprint"
335        );
336    }
337
338    #[test]
339    fn types_are_first_class() {
340        let src = "struct S { x: u32 }\nenum E { A, B }\ntrait T { fn m(&self); }\n";
341        let names: Vec<_> = extract(src).into_iter().map(|s| (s.name, s.kind)).collect();
342        assert!(names.contains(&("S".to_string(), SymbolKindTag::Type)));
343        assert!(names.contains(&("E".to_string(), SymbolKindTag::Enum)));
344        assert!(names.contains(&("T".to_string(), SymbolKindTag::Trait)));
345    }
346
347    #[test]
348    fn unsupported_language_is_none() {
349        assert!(extract_semantic_file(b"whatever", Language::Unknown).is_none());
350    }
351
352    // ── Zig (heddle#1068) ────────────────────────────────────────────────
353
354    /// A `.zig` blob must extract a real file node — symbols with per-symbol
355    /// `semantic_hash`es — not the `Opaque` fallback that `Language::Unknown`
356    /// produced before Zig support.
357    #[cfg(feature = "lang-zig")]
358    #[test]
359    fn zig_blob_extracts_real_symbols_with_hashes() {
360        let src = "pub const Point = struct {\n    x: f64,\n    pub fn dist(self: Point) f64 { return self.x; }\n};\n\ntest \"works\" { _ = 1; }\n";
361        let extracted = extract_semantic_file(src.as_bytes(), Language::Zig)
362            .expect("zig parses to a real node");
363        assert_eq!(language_name(extracted.language), "zig");
364
365        let by_name = |n: &str| extracted.symbols.iter().find(|s| s.name == n);
366        let point = by_name("Point").expect("Point type extracted");
367        assert_eq!(point.kind, SymbolKindTag::Type);
368        let dist = by_name("dist").expect("method extracted");
369        assert_eq!(dist.kind, SymbolKindTag::Function);
370        assert_eq!(dist.container_path, vec!["Point".to_string()]);
371        let test = by_name("test:\"works\"").expect("test block extracted");
372        assert_eq!(test.kind, SymbolKindTag::Function);
373
374        // Every symbol carries a non-degenerate per-symbol semantic_hash.
375        assert!(
376            extracted
377                .symbols
378                .iter()
379                .all(|s| s.semantic_hash != ContentHash::compute(b"")),
380            "symbols must carry real semantic hashes"
381        );
382    }
383
384    /// Reformatting a Zig file — whitespace + comments only — must leave the
385    /// file node's `semantic_digest` (and every symbol hash + the scaffold)
386    /// byte-identical.
387    #[cfg(feature = "lang-zig")]
388    #[test]
389    fn zig_reformat_leaves_semantic_digest_stable() {
390        use objects::object::SemanticFileNode;
391
392        let tight = "const std = @import(\"std\");\npub fn add(a: i32, b: i32) i32 { return a + b; }\npub const Point = struct { x: f64, pub fn dist(self: Point) f64 { return self.x; } };\n";
393        let loose = "const std = @import(\"std\");\n\n// a comment\npub fn add(a: i32,   b: i32) i32 {\n    return a + b;\n}\n\npub const Point = struct {\n    // fields\n    x: f64,\n    pub fn dist(self: Point) f64 {\n        return self.x;\n    }\n};\n";
394
395        let ea = extract_semantic_file(tight.as_bytes(), Language::Zig).expect("tight parses");
396        let eb = extract_semantic_file(loose.as_bytes(), Language::Zig).expect("loose parses");
397
398        assert_eq!(
399            ea.scaffold_hash, eb.scaffold_hash,
400            "scaffold must be reformat/comment stable"
401        );
402
403        let node = |e: &ExtractedFile, src: &str| {
404            SemanticFileNode::new(
405                language_name(e.language),
406                grammar_version(e.language),
407                EXTRACTOR_VERSION,
408                ContentHash::compute(src.as_bytes()),
409                e.scaffold_hash,
410                e.symbols.clone(),
411            )
412        };
413        // The source blobs differ, but the reformat-stable digest must not.
414        assert_eq!(
415            node(&ea, tight).semantic_digest,
416            node(&eb, loose).semantic_digest,
417            "reformatting must not perturb the file semantic_digest"
418        );
419    }
420}