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/// Prefix for a field's type stored on a struct node: `field:draft:Draft`.
83///
84/// The type is the one a method call on the field reaches, with references,
85/// smart pointers, locks and containers already stripped (`Mutex<Draft>` and
86/// `Option<Box<Draft>>` both record `Draft`). The graph builder follows these
87/// to resolve `state.draft.run_started()` when `state`'s struct lives in
88/// another file.
89pub const FIELD_REF_PREFIX: &str = "field:";
90
91/// Encodes a struct field's type as a reference.
92pub fn field_ref(field: &str, type_name: &str) -> String {
93    format!("{FIELD_REF_PREFIX}{field}:{type_name}")
94}
95
96/// Splits a `field:name:Type` reference into the field name and its type.
97pub fn field_type_ref(reference: &str) -> Option<(&str, &str)> {
98    let (field, type_name) = reference.strip_prefix(FIELD_REF_PREFIX)?.split_once(':')?;
99    (!field.is_empty() && !type_name.is_empty()).then_some((field, type_name))
100}
101
102/// Prefix for the type a function returns, stored on its node:
103/// `returns:PreparedDraft` for `-> Option<mac::PreparedDraft>`.
104/// Stripped like a field type, with `Self` already replaced by the impl type.
105pub const RETURNS_REF_PREFIX: &str = "returns:";
106
107/// Encodes a function's (stripped) return type as a reference.
108pub fn returns_ref(type_name: &str) -> String {
109    format!("{RETURNS_REF_PREFIX}{type_name}")
110}
111
112/// The return type recorded by a `returns:Type` reference.
113pub fn return_type_ref(reference: &str) -> Option<&str> {
114    reference
115        .strip_prefix(RETURNS_REF_PREFIX)
116        .filter(|type_name| !type_name.is_empty())
117}
118
119/// Encodes a method call whose receiver's type is known from the code:
120/// `.run_started@Draft`, or `.run_started@AppState.draft` for a call on a
121/// field of a value of type `AppState`.
122///
123/// The type path starts at a type name or at a call whose return type
124/// decides it (`prepare()`, `mac::Draft::capture()`), then reads fields
125/// (`.draft`) and method results (`.load()`) in order.
126///
127/// A plain `.name` reference means the receiver's type is unknown.
128pub fn typed_receiver_ref(method: &str, receiver_type: &str) -> String {
129    format!(".{method}@{receiver_type}")
130}
131
132/// Splits a typed receiver reference into the method name and the receiver's
133/// type path (`Type` or `Type.field.field`).
134pub fn typed_receiver(reference: &str) -> Option<(&str, &str)> {
135    let (method, receiver) = reference.strip_prefix('.')?.split_once('@')?;
136    (!method.is_empty() && !receiver.is_empty()).then_some((method, receiver))
137}
138
139/// A type relationship stored on a node until the graph builder resolves it.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum TypeRelationKind {
142    /// `class Middle(Base)` — subclass depends on the base.
143    Extends,
144    /// `class Foo implements Bar` — implementor depends on the interface.
145    Implements,
146}
147
148/// Splits an `extends:` / `implements:` reference into its kind and type name.
149///
150/// Returns `None` for ordinary call references.
151pub fn type_relation_ref(reference: &str) -> Option<(TypeRelationKind, &str)> {
152    let reference = reference.trim();
153    if let Some(name) = reference.strip_prefix(EXTENDS_REF_PREFIX) {
154        let name = name.trim();
155        if !name.is_empty() {
156            return Some((TypeRelationKind::Extends, name));
157        }
158    }
159    if let Some(name) = reference.strip_prefix(IMPLEMENTS_REF_PREFIX) {
160        let name = name.trim();
161        if !name.is_empty() {
162            return Some((TypeRelationKind::Implements, name));
163        }
164    }
165    None
166}
167
168/// Strips pointers, references, and generic arguments from a type name.
169///
170/// `*Base`, `Foo<T>`, and `pkg.Base` become `Base`, `Foo`, and `pkg.Base`.
171/// Keywords and anything that is not a type path become empty.
172pub fn clean_type_name(raw: &str) -> String {
173    let mut raw = raw.trim();
174    loop {
175        if let Some(rest) = raw.strip_prefix('*').or_else(|| raw.strip_prefix('&')) {
176            raw = rest.trim_start();
177            continue;
178        }
179        if let Some(rest) = raw.strip_prefix("mut ") {
180            raw = rest.trim_start();
181            continue;
182        }
183        break;
184    }
185    let raw = raw.split(['<', '[']).next().unwrap_or(raw).trim();
186    let raw = raw.trim_end_matches('?').trim();
187    if raw.is_empty() || is_type_keyword(raw) || !is_type_path(raw) {
188        return String::new();
189    }
190    raw.to_string()
191}
192
193fn is_type_path(name: &str) -> bool {
194    let mut chars = name.chars();
195    let Some(first) = chars.next() else {
196        return false;
197    };
198    if !(first.is_alphabetic() || first == '_') {
199        return false;
200    }
201    name.chars()
202        .all(|c| c.is_alphanumeric() || c == '_' || c == '.' || c == ':')
203}
204
205fn is_type_keyword(name: &str) -> bool {
206    matches!(
207        name,
208        "public"
209            | "private"
210            | "protected"
211            | "virtual"
212            | "override"
213            | "abstract"
214            | "static"
215            | "final"
216            | "sealed"
217            | "partial"
218            | "readonly"
219            | "const"
220            | "class"
221            | "struct"
222            | "interface"
223            | "enum"
224            | "extends"
225            | "implements"
226            | "with"
227            | "where"
228            | "new"
229            | "base"
230            | "this"
231            | "super"
232            | "mut"
233            | "pub"
234            | "crate"
235            | "object"
236    )
237}
238
239fn push_type_relation(references: &mut Vec<String>, kind: TypeRelationKind, name: &str) {
240    let name = clean_type_name(name);
241    if name.is_empty() {
242        return;
243    }
244    let prefix = match kind {
245        TypeRelationKind::Extends => EXTENDS_REF_PREFIX,
246        TypeRelationKind::Implements => IMPLEMENTS_REF_PREFIX,
247    };
248    let encoded = format!("{prefix}{name}");
249    if !references.iter().any(|existing| existing == &encoded) {
250        references.push(encoded);
251    }
252}
253
254/// Visibility of a code entity.
255#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
256#[serde(rename_all = "snake_case")]
257pub enum Visibility {
258    #[default]
259    Private,
260    Public,
261    Protected,
262    /// Rust's pub(crate) or similar restricted visibility.
263    Internal,
264}
265
266/// A code entity extracted from source.
267///
268/// This is the core data type that flows through Arbor. It's designed
269/// to be language-agnostic while still capturing the structure we need.
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct CodeNode {
272    /// Unique identifier, derived from file path + qualified name + kind.
273    pub id: String,
274
275    /// The simple name (e.g., "validate_user").
276    pub name: String,
277
278    /// Fully qualified name including parent scope (e.g., "UserService.validate_user").
279    pub qualified_name: String,
280
281    /// What kind of entity this is.
282    pub kind: NodeKind,
283
284    /// Path to the source file, relative to project root.
285    pub file: String,
286
287    /// Starting line (1-indexed, like editors show).
288    pub line_start: u32,
289
290    /// Ending line (inclusive).
291    pub line_end: u32,
292
293    /// Column of the name identifier.
294    pub column: u32,
295
296    /// Function/method signature if applicable.
297    pub signature: Option<String>,
298
299    /// Visibility modifier.
300    pub visibility: Visibility,
301
302    /// Whether this is async.
303    pub is_async: bool,
304
305    /// Whether this is static/class-level.
306    pub is_static: bool,
307
308    /// Whether this is exported (TS/ES modules).
309    pub is_exported: bool,
310
311    /// Docstring or leading comment.
312    pub docstring: Option<String>,
313
314    /// Byte offset range in source for incremental updates.
315    pub byte_start: u32,
316    pub byte_end: u32,
317
318    /// Entities this node references (call targets, type refs, etc).
319    /// These are names, not IDs - resolution happens in the graph crate.
320    pub references: Vec<String>,
321}
322
323impl CodeNode {
324    /// Creates a deterministic ID for this node.
325    ///
326    /// The ID is a hash of (file, qualified_name, kind) so the same
327    /// entity always gets the same ID across parses.
328    pub fn compute_id(file: &str, qualified_name: &str, kind: NodeKind) -> String {
329        use std::collections::hash_map::DefaultHasher;
330
331        let mut hasher = DefaultHasher::new();
332        file.hash(&mut hasher);
333        qualified_name.hash(&mut hasher);
334        kind.hash(&mut hasher);
335
336        format!("{:016x}", hasher.finish())
337    }
338
339    /// Creates a new node and automatically computes its ID.
340    pub fn new(
341        name: impl Into<String>,
342        qualified_name: impl Into<String>,
343        kind: NodeKind,
344        file: impl Into<String>,
345    ) -> Self {
346        let name = name.into();
347        let qualified_name = qualified_name.into();
348        let file = file.into();
349        let id = Self::compute_id(&file, &qualified_name, kind);
350
351        Self {
352            id,
353            name,
354            qualified_name,
355            kind,
356            file,
357            line_start: 0,
358            line_end: 0,
359            column: 0,
360            signature: None,
361            visibility: Visibility::default(),
362            is_async: false,
363            is_static: false,
364            is_exported: false,
365            docstring: None,
366            byte_start: 0,
367            byte_end: 0,
368            references: Vec::new(),
369        }
370    }
371
372    /// Builder pattern: set line range.
373    pub fn with_lines(mut self, start: u32, end: u32) -> Self {
374        self.line_start = start;
375        self.line_end = end;
376        self
377    }
378
379    /// Builder pattern: set byte range.
380    pub fn with_bytes(mut self, start: u32, end: u32) -> Self {
381        self.byte_start = start;
382        self.byte_end = end;
383        self
384    }
385
386    /// Builder pattern: set column.
387    pub fn with_column(mut self, column: u32) -> Self {
388        self.column = column;
389        self
390    }
391
392    /// Builder pattern: set signature.
393    pub fn with_signature(mut self, sig: impl Into<String>) -> Self {
394        self.signature = Some(sig.into());
395        self
396    }
397
398    /// Builder pattern: set visibility.
399    pub fn with_visibility(mut self, vis: Visibility) -> Self {
400        self.visibility = vis;
401        self
402    }
403
404    /// Builder pattern: mark as async.
405    pub fn as_async(mut self) -> Self {
406        self.is_async = true;
407        self
408    }
409
410    /// Builder pattern: mark as static.
411    pub fn as_static(mut self) -> Self {
412        self.is_static = true;
413        self
414    }
415
416    /// Builder pattern: mark as exported.
417    pub fn as_exported(mut self) -> Self {
418        self.is_exported = true;
419        self
420    }
421
422    /// Builder pattern: add references.
423    pub fn with_references(mut self, refs: Vec<String>) -> Self {
424        self.references = refs;
425        self
426    }
427
428    /// Records a superclass. Appends to [`references`](Self::references); it
429    /// does not replace call references already stored there.
430    pub fn add_type_relation(&mut self, kind: TypeRelationKind, name: &str) {
431        push_type_relation(&mut self.references, kind, name);
432    }
433
434    /// Records superclasses this type extends.
435    pub fn with_extends<I, S>(mut self, bases: I) -> Self
436    where
437        I: IntoIterator<Item = S>,
438        S: AsRef<str>,
439    {
440        for name in bases {
441            self.add_type_relation(TypeRelationKind::Extends, name.as_ref());
442        }
443        self
444    }
445
446    /// Records interfaces or traits this type implements.
447    pub fn with_implements<I, S>(mut self, interfaces: I) -> Self
448    where
449        I: IntoIterator<Item = S>,
450        S: AsRef<str>,
451    {
452        for name in interfaces {
453            self.add_type_relation(TypeRelationKind::Implements, name.as_ref());
454        }
455        self
456    }
457}
458
459impl PartialEq for CodeNode {
460    fn eq(&self, other: &Self) -> bool {
461        self.id == other.id
462    }
463}
464
465impl Eq for CodeNode {}
466
467impl Hash for CodeNode {
468    fn hash<H: Hasher>(&self, state: &mut H) {
469        self.id.hash(state);
470    }
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    use std::collections::HashSet;
477
478    #[test]
479    fn test_node_kind_display_all_variants() {
480        // Exhaustive check of Display for every NodeKind variant
481        assert_eq!(NodeKind::Function.to_string(), "function");
482        assert_eq!(NodeKind::Method.to_string(), "method");
483        assert_eq!(NodeKind::Class.to_string(), "class");
484        assert_eq!(NodeKind::Struct.to_string(), "struct");
485        assert_eq!(NodeKind::Interface.to_string(), "interface");
486        assert_eq!(NodeKind::Enum.to_string(), "enum");
487        assert_eq!(NodeKind::Module.to_string(), "module");
488        assert_eq!(NodeKind::Field.to_string(), "field");
489        assert_eq!(NodeKind::Constant.to_string(), "constant");
490        assert_eq!(NodeKind::Constructor.to_string(), "constructor");
491        assert_eq!(NodeKind::Import.to_string(), "import");
492        assert_eq!(NodeKind::Export.to_string(), "export");
493        assert_eq!(NodeKind::TypeAlias.to_string(), "type_alias");
494        assert_eq!(NodeKind::Variable.to_string(), "variable");
495    }
496
497    #[test]
498    fn test_visibility_default_is_private() {
499        let vis = Visibility::default();
500        assert!(matches!(vis, Visibility::Private));
501    }
502
503    #[test]
504    fn test_builder_pattern_chain() {
505        // Verify that all builder methods compose correctly
506        let node = CodeNode::new("foo", "pkg.foo", NodeKind::Function, "main.rs")
507            .with_lines(10, 20)
508            .with_bytes(100, 300)
509            .with_column(4)
510            .with_signature("fn foo(x: i32) -> bool")
511            .with_visibility(Visibility::Public)
512            .as_async()
513            .as_static()
514            .as_exported()
515            .with_references(vec!["bar".to_string(), "baz".to_string()]);
516
517        assert_eq!(node.name, "foo");
518        assert_eq!(node.qualified_name, "pkg.foo");
519        assert_eq!(node.file, "main.rs");
520        assert_eq!(node.line_start, 10);
521        assert_eq!(node.line_end, 20);
522        assert_eq!(node.byte_start, 100);
523        assert_eq!(node.byte_end, 300);
524        assert_eq!(node.column, 4);
525        assert_eq!(node.signature.as_deref(), Some("fn foo(x: i32) -> bool"));
526        assert!(matches!(node.visibility, Visibility::Public));
527        assert!(node.is_async);
528        assert!(node.is_static);
529        assert!(node.is_exported);
530        assert_eq!(node.references.len(), 2);
531    }
532
533    #[test]
534    fn test_code_node_equality_by_id() {
535        // PartialEq compares by ID only, not by other fields
536        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
537        let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
538        // Same inputs → same ID → equal
539        assert_eq!(node1, node2);
540
541        // Different kind → different ID → not equal
542        let node3 = CodeNode::new("foo", "foo", NodeKind::Method, "a.rs");
543        assert_ne!(node1, node3);
544    }
545
546    #[test]
547    fn test_code_node_hash_consistency() {
548        // Same node should hash identically, and be usable in HashSet
549        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "main.rs");
550        let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "main.rs");
551
552        let mut set = HashSet::new();
553        set.insert(node1.clone());
554        assert!(set.contains(&node2));
555        // Inserting duplicate should not increase size
556        set.insert(node2);
557        assert_eq!(set.len(), 1);
558    }
559
560    #[test]
561    fn test_compute_id_deterministic() {
562        // Same inputs must always produce the same ID
563        let id1 = CodeNode::compute_id("test.rs", "main", NodeKind::Function);
564        let id2 = CodeNode::compute_id("test.rs", "main", NodeKind::Function);
565        assert_eq!(id1, id2);
566    }
567
568    #[test]
569    fn test_compute_id_different_kinds_differ() {
570        // A function and a struct with the same name should have different IDs
571        let id_fn = CodeNode::compute_id("test.rs", "Foo", NodeKind::Function);
572        let id_struct = CodeNode::compute_id("test.rs", "Foo", NodeKind::Struct);
573        assert_ne!(id_fn, id_struct);
574    }
575
576    #[test]
577    fn test_compute_id_different_files_differ() {
578        let id1 = CodeNode::compute_id("a.rs", "main", NodeKind::Function);
579        let id2 = CodeNode::compute_id("b.rs", "main", NodeKind::Function);
580        assert_ne!(id1, id2);
581    }
582
583    #[test]
584    fn field_and_typed_receiver_refs_round_trip() {
585        assert_eq!(
586            field_type_ref(&field_ref("draft", "Draft")),
587            Some(("draft", "Draft"))
588        );
589        assert_eq!(field_type_ref("field:draft"), None);
590        assert_eq!(field_type_ref("draft"), None);
591        assert_eq!(
592            typed_receiver(&typed_receiver_ref("run_started", "AppState.draft")),
593            Some(("run_started", "AppState.draft"))
594        );
595        // A plain unknown-receiver call and a `self` call are not typed.
596        assert_eq!(typed_receiver(".run_started"), None);
597        assert_eq!(typed_receiver("self.run_started"), None);
598        assert_eq!(type_relation_ref(&field_ref("draft", "Draft")), None);
599        assert_eq!(return_type_ref(&returns_ref("Draft")), Some("Draft"));
600        assert_eq!(return_type_ref("returns:"), None);
601        assert_eq!(
602            typed_receiver(".run_started@mac::Draft::capture().load()"),
603            Some(("run_started", "mac::Draft::capture().load()"))
604        );
605    }
606
607    #[test]
608    fn type_relation_refs_round_trip() {
609        assert_eq!(
610            type_relation_ref("extends:Base"),
611            Some((TypeRelationKind::Extends, "Base"))
612        );
613        assert_eq!(
614            type_relation_ref("implements:Reader"),
615            Some((TypeRelationKind::Implements, "Reader"))
616        );
617        assert!(type_relation_ref("helper").is_none());
618        assert!(type_relation_ref("extends:").is_none());
619    }
620
621    #[test]
622    fn clean_type_name_strips_generics_and_pointers() {
623        assert_eq!(clean_type_name("*Base"), "Base");
624        assert_eq!(clean_type_name("Foo<T>"), "Foo");
625        assert_eq!(clean_type_name("pkg.Base"), "pkg.Base");
626        assert_eq!(clean_type_name("std::fmt::Display"), "std::fmt::Display");
627        assert_eq!(clean_type_name("object"), "");
628        assert_eq!(clean_type_name("public"), "");
629    }
630
631    #[test]
632    fn with_extends_appends_without_dropping_calls() {
633        let node = CodeNode::new("Middle", "Middle", NodeKind::Class, "a.py")
634            .with_references(vec!["helper".to_string()])
635            .with_extends(["Base"])
636            .with_implements(["Proto"]);
637        assert!(node.references.iter().any(|r| r == "helper"));
638        assert!(node.references.iter().any(|r| r == "extends:Base"));
639        assert!(node.references.iter().any(|r| r == "implements:Proto"));
640    }
641
642    #[test]
643    fn test_node_default_values() {
644        // Verify sensible defaults for a freshly created node
645        let node = CodeNode::new("f", "f", NodeKind::Function, "x.rs");
646        assert_eq!(node.line_start, 0);
647        assert_eq!(node.line_end, 0);
648        assert_eq!(node.byte_start, 0);
649        assert_eq!(node.byte_end, 0);
650        assert_eq!(node.column, 0);
651        assert!(node.signature.is_none());
652        assert!(!node.is_async);
653        assert!(!node.is_static);
654        assert!(!node.is_exported);
655        assert!(node.references.is_empty());
656        assert!(matches!(node.visibility, Visibility::Private));
657    }
658}