Skip to main content

arbor_core/
node.rs

1//! Code node representation.
2//!
3//! A CodeNode is our abstraction over raw AST nodes. It captures
4//! the semantically meaningful parts of code: what it is, where it lives,
5//! and enough metadata to be useful for graph construction.
6
7use serde::{Deserialize, Serialize};
8use std::hash::{Hash, Hasher};
9
10/// The kind of code entity this node represents.
11///
12/// We intentionally keep this list focused on the entities that matter
13/// for understanding code structure. Helper nodes like expressions
14/// or statements are filtered out during extraction.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum NodeKind {
18    /// A standalone function (not attached to a class).
19    Function,
20    /// A method inside a class or impl block.
21    Method,
22    /// A class definition.
23    Class,
24    /// An interface, protocol, or trait.
25    Interface,
26    /// A struct (Rust, Go).
27    Struct,
28    /// An enum definition.
29    Enum,
30    /// A module-level variable.
31    Variable,
32    /// A constant or static value.
33    Constant,
34    /// A type alias.
35    TypeAlias,
36    /// The file/module itself as a container.
37    Module,
38    /// An import statement.
39    Import,
40    /// An export declaration.
41    Export,
42    /// A constructor (Java, TypeScript class constructors).
43    Constructor,
44    /// A class field.
45    Field,
46    /// A document section or heading (for Markdown knowledge graphs in Lattice).
47    Section,
48}
49
50impl std::fmt::Display for NodeKind {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        let s = match self {
53            Self::Function => "function",
54            Self::Method => "method",
55            Self::Class => "class",
56            Self::Interface => "interface",
57            Self::Struct => "struct",
58            Self::Enum => "enum",
59            Self::Variable => "variable",
60            Self::Constant => "constant",
61            Self::TypeAlias => "type_alias",
62            Self::Module => "module",
63            Self::Import => "import",
64            Self::Export => "export",
65            Self::Constructor => "constructor",
66            Self::Field => "field",
67            Self::Section => "section",
68        };
69        write!(f, "{}", s)
70    }
71}
72
73/// Prefix on [`CodeNode::references`] for a superclass name.
74///
75/// These are not call targets. The graph builder turns them into `extends`
76/// edges and does not feed them to PageRank.
77pub const EXTENDS_REF_PREFIX: &str = "extends:";
78
79/// Prefix on [`CodeNode::references`] for an implemented interface or trait.
80pub const IMPLEMENTS_REF_PREFIX: &str = "implements:";
81
82/// A type relationship stored on a node until the graph builder resolves it.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum TypeRelationKind {
85    /// `class Middle(Base)` — subclass depends on the base.
86    Extends,
87    /// `class Foo implements Bar` — implementor depends on the interface.
88    Implements,
89}
90
91/// Splits an `extends:` / `implements:` reference into its kind and type name.
92///
93/// Returns `None` for ordinary call references.
94pub fn type_relation_ref(reference: &str) -> Option<(TypeRelationKind, &str)> {
95    let reference = reference.trim();
96    if let Some(name) = reference.strip_prefix(EXTENDS_REF_PREFIX) {
97        let name = name.trim();
98        if !name.is_empty() {
99            return Some((TypeRelationKind::Extends, name));
100        }
101    }
102    if let Some(name) = reference.strip_prefix(IMPLEMENTS_REF_PREFIX) {
103        let name = name.trim();
104        if !name.is_empty() {
105            return Some((TypeRelationKind::Implements, name));
106        }
107    }
108    None
109}
110
111/// Strips pointers, references, and generic arguments from a type name.
112///
113/// `*Base`, `Foo<T>`, and `pkg.Base` become `Base`, `Foo`, and `pkg.Base`.
114/// Keywords and anything that is not a type path become empty.
115pub fn clean_type_name(raw: &str) -> String {
116    let mut raw = raw.trim();
117    loop {
118        if let Some(rest) = raw.strip_prefix('*').or_else(|| raw.strip_prefix('&')) {
119            raw = rest.trim_start();
120            continue;
121        }
122        if let Some(rest) = raw.strip_prefix("mut ") {
123            raw = rest.trim_start();
124            continue;
125        }
126        break;
127    }
128    let raw = raw.split(['<', '[']).next().unwrap_or(raw).trim();
129    let raw = raw.trim_end_matches('?').trim();
130    if raw.is_empty() || is_type_keyword(raw) || !is_type_path(raw) {
131        return String::new();
132    }
133    raw.to_string()
134}
135
136fn is_type_path(name: &str) -> bool {
137    let mut chars = name.chars();
138    let Some(first) = chars.next() else {
139        return false;
140    };
141    if !(first.is_alphabetic() || first == '_') {
142        return false;
143    }
144    name.chars()
145        .all(|c| c.is_alphanumeric() || c == '_' || c == '.' || c == ':')
146}
147
148fn is_type_keyword(name: &str) -> bool {
149    matches!(
150        name,
151        "public"
152            | "private"
153            | "protected"
154            | "virtual"
155            | "override"
156            | "abstract"
157            | "static"
158            | "final"
159            | "sealed"
160            | "partial"
161            | "readonly"
162            | "const"
163            | "class"
164            | "struct"
165            | "interface"
166            | "enum"
167            | "extends"
168            | "implements"
169            | "with"
170            | "where"
171            | "new"
172            | "base"
173            | "this"
174            | "super"
175            | "mut"
176            | "pub"
177            | "crate"
178            | "object"
179    )
180}
181
182fn push_type_relation(references: &mut Vec<String>, kind: TypeRelationKind, name: &str) {
183    let name = clean_type_name(name);
184    if name.is_empty() {
185        return;
186    }
187    let prefix = match kind {
188        TypeRelationKind::Extends => EXTENDS_REF_PREFIX,
189        TypeRelationKind::Implements => IMPLEMENTS_REF_PREFIX,
190    };
191    let encoded = format!("{prefix}{name}");
192    if !references.iter().any(|existing| existing == &encoded) {
193        references.push(encoded);
194    }
195}
196
197/// Visibility of a code entity.
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
199#[serde(rename_all = "snake_case")]
200pub enum Visibility {
201    #[default]
202    Private,
203    Public,
204    Protected,
205    /// Rust's pub(crate) or similar restricted visibility.
206    Internal,
207}
208
209/// A code entity extracted from source.
210///
211/// This is the core data type that flows through Arbor. It's designed
212/// to be language-agnostic while still capturing the structure we need.
213#[derive(Debug, Clone, Serialize, Deserialize)]
214pub struct CodeNode {
215    /// Unique identifier, derived from file path + qualified name + kind.
216    pub id: String,
217
218    /// The simple name (e.g., "validate_user").
219    pub name: String,
220
221    /// Fully qualified name including parent scope (e.g., "UserService.validate_user").
222    pub qualified_name: String,
223
224    /// What kind of entity this is.
225    pub kind: NodeKind,
226
227    /// Path to the source file, relative to project root.
228    pub file: String,
229
230    /// Starting line (1-indexed, like editors show).
231    pub line_start: u32,
232
233    /// Ending line (inclusive).
234    pub line_end: u32,
235
236    /// Column of the name identifier.
237    pub column: u32,
238
239    /// Function/method signature if applicable.
240    pub signature: Option<String>,
241
242    /// Visibility modifier.
243    pub visibility: Visibility,
244
245    /// Whether this is async.
246    pub is_async: bool,
247
248    /// Whether this is static/class-level.
249    pub is_static: bool,
250
251    /// Whether this is exported (TS/ES modules).
252    pub is_exported: bool,
253
254    /// Docstring or leading comment.
255    pub docstring: Option<String>,
256
257    /// Byte offset range in source for incremental updates.
258    pub byte_start: u32,
259    pub byte_end: u32,
260
261    /// Entities this node references (call targets, type refs, etc).
262    /// These are names, not IDs - resolution happens in the graph crate.
263    pub references: Vec<String>,
264}
265
266impl CodeNode {
267    /// Creates a deterministic ID for this node.
268    ///
269    /// The ID is a hash of (file, qualified_name, kind) so the same
270    /// entity always gets the same ID across parses.
271    pub fn compute_id(file: &str, qualified_name: &str, kind: NodeKind) -> String {
272        use std::collections::hash_map::DefaultHasher;
273
274        let mut hasher = DefaultHasher::new();
275        file.hash(&mut hasher);
276        qualified_name.hash(&mut hasher);
277        kind.hash(&mut hasher);
278
279        format!("{:016x}", hasher.finish())
280    }
281
282    /// Creates a new node and automatically computes its ID.
283    pub fn new(
284        name: impl Into<String>,
285        qualified_name: impl Into<String>,
286        kind: NodeKind,
287        file: impl Into<String>,
288    ) -> Self {
289        let name = name.into();
290        let qualified_name = qualified_name.into();
291        let file = file.into();
292        let id = Self::compute_id(&file, &qualified_name, kind);
293
294        Self {
295            id,
296            name,
297            qualified_name,
298            kind,
299            file,
300            line_start: 0,
301            line_end: 0,
302            column: 0,
303            signature: None,
304            visibility: Visibility::default(),
305            is_async: false,
306            is_static: false,
307            is_exported: false,
308            docstring: None,
309            byte_start: 0,
310            byte_end: 0,
311            references: Vec::new(),
312        }
313    }
314
315    /// Builder pattern: set line range.
316    pub fn with_lines(mut self, start: u32, end: u32) -> Self {
317        self.line_start = start;
318        self.line_end = end;
319        self
320    }
321
322    /// Builder pattern: set byte range.
323    pub fn with_bytes(mut self, start: u32, end: u32) -> Self {
324        self.byte_start = start;
325        self.byte_end = end;
326        self
327    }
328
329    /// Builder pattern: set column.
330    pub fn with_column(mut self, column: u32) -> Self {
331        self.column = column;
332        self
333    }
334
335    /// Builder pattern: set signature.
336    pub fn with_signature(mut self, sig: impl Into<String>) -> Self {
337        self.signature = Some(sig.into());
338        self
339    }
340
341    /// Builder pattern: set visibility.
342    pub fn with_visibility(mut self, vis: Visibility) -> Self {
343        self.visibility = vis;
344        self
345    }
346
347    /// Builder pattern: mark as async.
348    pub fn as_async(mut self) -> Self {
349        self.is_async = true;
350        self
351    }
352
353    /// Builder pattern: mark as static.
354    pub fn as_static(mut self) -> Self {
355        self.is_static = true;
356        self
357    }
358
359    /// Builder pattern: mark as exported.
360    pub fn as_exported(mut self) -> Self {
361        self.is_exported = true;
362        self
363    }
364
365    /// Builder pattern: add references.
366    pub fn with_references(mut self, refs: Vec<String>) -> Self {
367        self.references = refs;
368        self
369    }
370
371    /// Records a superclass. Appends to [`references`](Self::references); it
372    /// does not replace call references already stored there.
373    pub fn add_type_relation(&mut self, kind: TypeRelationKind, name: &str) {
374        push_type_relation(&mut self.references, kind, name);
375    }
376
377    /// Records superclasses this type extends.
378    pub fn with_extends<I, S>(mut self, bases: I) -> Self
379    where
380        I: IntoIterator<Item = S>,
381        S: AsRef<str>,
382    {
383        for name in bases {
384            self.add_type_relation(TypeRelationKind::Extends, name.as_ref());
385        }
386        self
387    }
388
389    /// Records interfaces or traits this type implements.
390    pub fn with_implements<I, S>(mut self, interfaces: I) -> Self
391    where
392        I: IntoIterator<Item = S>,
393        S: AsRef<str>,
394    {
395        for name in interfaces {
396            self.add_type_relation(TypeRelationKind::Implements, name.as_ref());
397        }
398        self
399    }
400}
401
402impl PartialEq for CodeNode {
403    fn eq(&self, other: &Self) -> bool {
404        self.id == other.id
405    }
406}
407
408impl Eq for CodeNode {}
409
410impl Hash for CodeNode {
411    fn hash<H: Hasher>(&self, state: &mut H) {
412        self.id.hash(state);
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use std::collections::HashSet;
420
421    #[test]
422    fn test_node_kind_display_all_variants() {
423        // Exhaustive check of Display for every NodeKind variant
424        assert_eq!(NodeKind::Function.to_string(), "function");
425        assert_eq!(NodeKind::Method.to_string(), "method");
426        assert_eq!(NodeKind::Class.to_string(), "class");
427        assert_eq!(NodeKind::Struct.to_string(), "struct");
428        assert_eq!(NodeKind::Interface.to_string(), "interface");
429        assert_eq!(NodeKind::Enum.to_string(), "enum");
430        assert_eq!(NodeKind::Module.to_string(), "module");
431        assert_eq!(NodeKind::Field.to_string(), "field");
432        assert_eq!(NodeKind::Constant.to_string(), "constant");
433        assert_eq!(NodeKind::Constructor.to_string(), "constructor");
434        assert_eq!(NodeKind::Import.to_string(), "import");
435        assert_eq!(NodeKind::Export.to_string(), "export");
436        assert_eq!(NodeKind::TypeAlias.to_string(), "type_alias");
437        assert_eq!(NodeKind::Variable.to_string(), "variable");
438    }
439
440    #[test]
441    fn test_visibility_default_is_private() {
442        let vis = Visibility::default();
443        assert!(matches!(vis, Visibility::Private));
444    }
445
446    #[test]
447    fn test_builder_pattern_chain() {
448        // Verify that all builder methods compose correctly
449        let node = CodeNode::new("foo", "pkg.foo", NodeKind::Function, "main.rs")
450            .with_lines(10, 20)
451            .with_bytes(100, 300)
452            .with_column(4)
453            .with_signature("fn foo(x: i32) -> bool")
454            .with_visibility(Visibility::Public)
455            .as_async()
456            .as_static()
457            .as_exported()
458            .with_references(vec!["bar".to_string(), "baz".to_string()]);
459
460        assert_eq!(node.name, "foo");
461        assert_eq!(node.qualified_name, "pkg.foo");
462        assert_eq!(node.file, "main.rs");
463        assert_eq!(node.line_start, 10);
464        assert_eq!(node.line_end, 20);
465        assert_eq!(node.byte_start, 100);
466        assert_eq!(node.byte_end, 300);
467        assert_eq!(node.column, 4);
468        assert_eq!(node.signature.as_deref(), Some("fn foo(x: i32) -> bool"));
469        assert!(matches!(node.visibility, Visibility::Public));
470        assert!(node.is_async);
471        assert!(node.is_static);
472        assert!(node.is_exported);
473        assert_eq!(node.references.len(), 2);
474    }
475
476    #[test]
477    fn test_code_node_equality_by_id() {
478        // PartialEq compares by ID only, not by other fields
479        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
480        let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
481        // Same inputs → same ID → equal
482        assert_eq!(node1, node2);
483
484        // Different kind → different ID → not equal
485        let node3 = CodeNode::new("foo", "foo", NodeKind::Method, "a.rs");
486        assert_ne!(node1, node3);
487    }
488
489    #[test]
490    fn test_code_node_hash_consistency() {
491        // Same node should hash identically, and be usable in HashSet
492        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "main.rs");
493        let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "main.rs");
494
495        let mut set = HashSet::new();
496        set.insert(node1.clone());
497        assert!(set.contains(&node2));
498        // Inserting duplicate should not increase size
499        set.insert(node2);
500        assert_eq!(set.len(), 1);
501    }
502
503    #[test]
504    fn test_compute_id_deterministic() {
505        // Same inputs must always produce the same ID
506        let id1 = CodeNode::compute_id("test.rs", "main", NodeKind::Function);
507        let id2 = CodeNode::compute_id("test.rs", "main", NodeKind::Function);
508        assert_eq!(id1, id2);
509    }
510
511    #[test]
512    fn test_compute_id_different_kinds_differ() {
513        // A function and a struct with the same name should have different IDs
514        let id_fn = CodeNode::compute_id("test.rs", "Foo", NodeKind::Function);
515        let id_struct = CodeNode::compute_id("test.rs", "Foo", NodeKind::Struct);
516        assert_ne!(id_fn, id_struct);
517    }
518
519    #[test]
520    fn test_compute_id_different_files_differ() {
521        let id1 = CodeNode::compute_id("a.rs", "main", NodeKind::Function);
522        let id2 = CodeNode::compute_id("b.rs", "main", NodeKind::Function);
523        assert_ne!(id1, id2);
524    }
525
526    #[test]
527    fn type_relation_refs_round_trip() {
528        assert_eq!(
529            type_relation_ref("extends:Base"),
530            Some((TypeRelationKind::Extends, "Base"))
531        );
532        assert_eq!(
533            type_relation_ref("implements:Reader"),
534            Some((TypeRelationKind::Implements, "Reader"))
535        );
536        assert!(type_relation_ref("helper").is_none());
537        assert!(type_relation_ref("extends:").is_none());
538    }
539
540    #[test]
541    fn clean_type_name_strips_generics_and_pointers() {
542        assert_eq!(clean_type_name("*Base"), "Base");
543        assert_eq!(clean_type_name("Foo<T>"), "Foo");
544        assert_eq!(clean_type_name("pkg.Base"), "pkg.Base");
545        assert_eq!(clean_type_name("std::fmt::Display"), "std::fmt::Display");
546        assert_eq!(clean_type_name("object"), "");
547        assert_eq!(clean_type_name("public"), "");
548    }
549
550    #[test]
551    fn with_extends_appends_without_dropping_calls() {
552        let node = CodeNode::new("Middle", "Middle", NodeKind::Class, "a.py")
553            .with_references(vec!["helper".to_string()])
554            .with_extends(["Base"])
555            .with_implements(["Proto"]);
556        assert!(node.references.iter().any(|r| r == "helper"));
557        assert!(node.references.iter().any(|r| r == "extends:Base"));
558        assert!(node.references.iter().any(|r| r == "implements:Proto"));
559    }
560
561    #[test]
562    fn test_node_default_values() {
563        // Verify sensible defaults for a freshly created node
564        let node = CodeNode::new("f", "f", NodeKind::Function, "x.rs");
565        assert_eq!(node.line_start, 0);
566        assert_eq!(node.line_end, 0);
567        assert_eq!(node.byte_start, 0);
568        assert_eq!(node.byte_end, 0);
569        assert_eq!(node.column, 0);
570        assert!(node.signature.is_none());
571        assert!(!node.is_async);
572        assert!(!node.is_static);
573        assert!(!node.is_exported);
574        assert!(node.references.is_empty());
575        assert!(matches!(node.visibility, Visibility::Private));
576    }
577}