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/// Prefix on an import node's references for a name imported under another
140/// name: `alias:to_minor:money_to_minor_units` for
141/// `from money import money_to_minor_units as to_minor`.
142///
143/// Calls use the local name; the module defines the imported one. Recording
144/// both lets the graph builder resolve `to_minor()` to the definition instead
145/// of looking for a function called `to_minor`.
146pub const IMPORT_ALIAS_REF_PREFIX: &str = "alias:";
147
148/// Encodes an aliased import as a reference on the import node.
149pub fn import_alias_ref(local: &str, imported: &str) -> String {
150    format!("{IMPORT_ALIAS_REF_PREFIX}{local}:{imported}")
151}
152
153/// Splits an `alias:local:imported` reference into the local name and the
154/// imported name.
155pub fn import_alias(reference: &str) -> Option<(&str, &str)> {
156    let (local, imported) = reference
157        .strip_prefix(IMPORT_ALIAS_REF_PREFIX)?
158        .split_once(':')?;
159    (!local.is_empty() && !imported.is_empty()).then_some((local, imported))
160}
161
162/// The qualified name of an import node: its module, then the byte where the
163/// statement starts (`./hooks@120`). The node's `name` stays the module.
164///
165/// The index cache stores nodes by id, and an id hashes the qualified name.
166/// A file can import one module more than once (`import { a } from './m'`
167/// and `import type { T } from './m'`, two `from m import ...` lines, a
168/// function-scoped `require('./m')`), and with the module alone as the
169/// qualified name those nodes would share an id and the cache would keep
170/// only the last.
171pub fn import_qualified_name(module: &str, start_byte: usize) -> String {
172    format!("{module}@{start_byte}")
173}
174
175/// Prefix for a name an import node records as bound at run time from a value
176/// its module produced: `bound:setFilters:setFilters` for
177/// `const { setFilters } = useListFilters()` after
178/// `import { useListFilters } from "./hooks"`.
179///
180/// The value is the module's, but not necessarily one of its top-level names,
181/// so the graph builder first looks for the name inside that module and, when
182/// the module doesn't define it, treats it as any other local binding.
183pub const RUNTIME_BINDING_REF_PREFIX: &str = "bound:";
184
185/// Encodes a name bound from a value its module produced.
186pub fn runtime_binding_ref(local: &str, name: &str) -> String {
187    format!("{RUNTIME_BINDING_REF_PREFIX}{local}:{name}")
188}
189
190/// Splits a `bound:local:name` reference into the local name and the name to
191/// look for in the module.
192pub fn runtime_binding(reference: &str) -> Option<(&str, &str)> {
193    let (local, name) = reference
194        .strip_prefix(RUNTIME_BINDING_REF_PREFIX)?
195        .split_once(':')?;
196    (!local.is_empty() && !name.is_empty()).then_some((local, name))
197}
198
199/// A reference on the empty-module import node of a JavaScript or
200/// TypeScript file that is a module: it has a top-level `import` or `export`
201/// statement (TypeScript draws the line the same way), or a top-level
202/// CommonJS `module.exports` / `exports.f` assignment. A file without one is
203/// a script, whose top-level names are globals.
204pub const MODULE_FILE_REF: &str = "module:";
205
206/// Prefix for a name the file binds itself (a variable, a parameter, a
207/// destructured value), recorded on an import node with an empty module.
208///
209/// A call to such a name may reach any function the value holds. A call to a
210/// name the file never binds can only reach a global.
211pub const LOCAL_BINDING_REF_PREFIX: &str = "local:";
212
213/// Encodes a name the file binds itself.
214pub fn local_binding_ref(name: &str) -> String {
215    format!("{LOCAL_BINDING_REF_PREFIX}{name}")
216}
217
218/// The name in a `local:name` reference.
219pub fn local_binding(reference: &str) -> Option<&str> {
220    reference
221        .strip_prefix(LOCAL_BINDING_REF_PREFIX)
222        .filter(|name| !name.is_empty())
223}
224
225/// A type relationship stored on a node until the graph builder resolves it.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum TypeRelationKind {
228    /// `class Middle(Base)` — subclass depends on the base.
229    Extends,
230    /// `class Foo implements Bar` — implementor depends on the interface.
231    Implements,
232}
233
234/// Splits an `extends:` / `implements:` reference into its kind and type name.
235///
236/// Returns `None` for ordinary call references.
237pub fn type_relation_ref(reference: &str) -> Option<(TypeRelationKind, &str)> {
238    let reference = reference.trim();
239    if let Some(name) = reference.strip_prefix(EXTENDS_REF_PREFIX) {
240        let name = name.trim();
241        if !name.is_empty() {
242            return Some((TypeRelationKind::Extends, name));
243        }
244    }
245    if let Some(name) = reference.strip_prefix(IMPLEMENTS_REF_PREFIX) {
246        let name = name.trim();
247        if !name.is_empty() {
248            return Some((TypeRelationKind::Implements, name));
249        }
250    }
251    None
252}
253
254/// Strips pointers, references, and generic arguments from a type name.
255///
256/// `*Base`, `Foo<T>`, and `pkg.Base` become `Base`, `Foo`, and `pkg.Base`.
257/// Keywords and anything that is not a type path become empty.
258pub fn clean_type_name(raw: &str) -> String {
259    let mut raw = raw.trim();
260    loop {
261        if let Some(rest) = raw.strip_prefix('*').or_else(|| raw.strip_prefix('&')) {
262            raw = rest.trim_start();
263            continue;
264        }
265        if let Some(rest) = raw.strip_prefix("mut ") {
266            raw = rest.trim_start();
267            continue;
268        }
269        break;
270    }
271    let raw = raw.split(['<', '[']).next().unwrap_or(raw).trim();
272    let raw = raw.trim_end_matches('?').trim();
273    if raw.is_empty() || is_type_keyword(raw) || !is_type_path(raw) {
274        return String::new();
275    }
276    raw.to_string()
277}
278
279fn is_type_path(name: &str) -> bool {
280    let mut chars = name.chars();
281    let Some(first) = chars.next() else {
282        return false;
283    };
284    if !(first.is_alphabetic() || first == '_') {
285        return false;
286    }
287    name.chars()
288        .all(|c| c.is_alphanumeric() || c == '_' || c == '.' || c == ':')
289}
290
291fn is_type_keyword(name: &str) -> bool {
292    matches!(
293        name,
294        "public"
295            | "private"
296            | "protected"
297            | "virtual"
298            | "override"
299            | "abstract"
300            | "static"
301            | "final"
302            | "sealed"
303            | "partial"
304            | "readonly"
305            | "const"
306            | "class"
307            | "struct"
308            | "interface"
309            | "enum"
310            | "extends"
311            | "implements"
312            | "with"
313            | "where"
314            | "new"
315            | "base"
316            | "this"
317            | "super"
318            | "mut"
319            | "pub"
320            | "crate"
321            | "object"
322    )
323}
324
325fn push_type_relation(references: &mut Vec<String>, kind: TypeRelationKind, name: &str) {
326    let name = clean_type_name(name);
327    if name.is_empty() {
328        return;
329    }
330    let prefix = match kind {
331        TypeRelationKind::Extends => EXTENDS_REF_PREFIX,
332        TypeRelationKind::Implements => IMPLEMENTS_REF_PREFIX,
333    };
334    let encoded = format!("{prefix}{name}");
335    if !references.iter().any(|existing| existing == &encoded) {
336        references.push(encoded);
337    }
338}
339
340/// Visibility of a code entity.
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
342#[serde(rename_all = "snake_case")]
343pub enum Visibility {
344    #[default]
345    Private,
346    Public,
347    Protected,
348    /// Rust's pub(crate) or similar restricted visibility.
349    Internal,
350}
351
352/// A code entity extracted from source.
353///
354/// This is the core data type that flows through Arbor. It's designed
355/// to be language-agnostic while still capturing the structure we need.
356#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct CodeNode {
358    /// Unique identifier, derived from file path + qualified name + kind.
359    pub id: String,
360
361    /// The simple name (e.g., "validate_user").
362    pub name: String,
363
364    /// Fully qualified name including parent scope (e.g., "UserService.validate_user").
365    pub qualified_name: String,
366
367    /// What kind of entity this is.
368    pub kind: NodeKind,
369
370    /// Path to the source file, relative to project root.
371    pub file: String,
372
373    /// Starting line (1-indexed, like editors show).
374    pub line_start: u32,
375
376    /// Ending line (inclusive).
377    pub line_end: u32,
378
379    /// Column of the name identifier.
380    pub column: u32,
381
382    /// Function/method signature if applicable.
383    pub signature: Option<String>,
384
385    /// Visibility modifier.
386    pub visibility: Visibility,
387
388    /// Whether this is async.
389    pub is_async: bool,
390
391    /// Whether this is static/class-level.
392    pub is_static: bool,
393
394    /// Whether this is exported (TS/ES modules).
395    pub is_exported: bool,
396
397    /// Docstring or leading comment.
398    pub docstring: Option<String>,
399
400    /// Byte offset range in source for incremental updates.
401    pub byte_start: u32,
402    pub byte_end: u32,
403
404    /// Entities this node references (call targets, type refs, etc).
405    /// These are names, not IDs - resolution happens in the graph crate.
406    pub references: Vec<String>,
407}
408
409impl CodeNode {
410    /// Creates a deterministic ID for this node.
411    ///
412    /// The ID is a hash of (file, qualified_name, kind) so the same
413    /// entity always gets the same ID across parses.
414    pub fn compute_id(file: &str, qualified_name: &str, kind: NodeKind) -> String {
415        use std::collections::hash_map::DefaultHasher;
416
417        let mut hasher = DefaultHasher::new();
418        file.hash(&mut hasher);
419        qualified_name.hash(&mut hasher);
420        kind.hash(&mut hasher);
421
422        format!("{:016x}", hasher.finish())
423    }
424
425    /// Creates a new node and automatically computes its ID.
426    pub fn new(
427        name: impl Into<String>,
428        qualified_name: impl Into<String>,
429        kind: NodeKind,
430        file: impl Into<String>,
431    ) -> Self {
432        let name = name.into();
433        let qualified_name = qualified_name.into();
434        let file = file.into();
435        let id = Self::compute_id(&file, &qualified_name, kind);
436
437        Self {
438            id,
439            name,
440            qualified_name,
441            kind,
442            file,
443            line_start: 0,
444            line_end: 0,
445            column: 0,
446            signature: None,
447            visibility: Visibility::default(),
448            is_async: false,
449            is_static: false,
450            is_exported: false,
451            docstring: None,
452            byte_start: 0,
453            byte_end: 0,
454            references: Vec::new(),
455        }
456    }
457
458    /// Builder pattern: set line range.
459    pub fn with_lines(mut self, start: u32, end: u32) -> Self {
460        self.line_start = start;
461        self.line_end = end;
462        self
463    }
464
465    /// Builder pattern: set byte range.
466    pub fn with_bytes(mut self, start: u32, end: u32) -> Self {
467        self.byte_start = start;
468        self.byte_end = end;
469        self
470    }
471
472    /// Builder pattern: set column.
473    pub fn with_column(mut self, column: u32) -> Self {
474        self.column = column;
475        self
476    }
477
478    /// Builder pattern: set signature.
479    pub fn with_signature(mut self, sig: impl Into<String>) -> Self {
480        self.signature = Some(sig.into());
481        self
482    }
483
484    /// Builder pattern: set visibility.
485    pub fn with_visibility(mut self, vis: Visibility) -> Self {
486        self.visibility = vis;
487        self
488    }
489
490    /// Builder pattern: mark as async.
491    pub fn as_async(mut self) -> Self {
492        self.is_async = true;
493        self
494    }
495
496    /// Builder pattern: mark as static.
497    pub fn as_static(mut self) -> Self {
498        self.is_static = true;
499        self
500    }
501
502    /// Builder pattern: mark as exported.
503    pub fn as_exported(mut self) -> Self {
504        self.is_exported = true;
505        self
506    }
507
508    /// Builder pattern: add references.
509    pub fn with_references(mut self, refs: Vec<String>) -> Self {
510        self.references = refs;
511        self
512    }
513
514    /// Records a superclass. Appends to [`references`](Self::references); it
515    /// does not replace call references already stored there.
516    pub fn add_type_relation(&mut self, kind: TypeRelationKind, name: &str) {
517        push_type_relation(&mut self.references, kind, name);
518    }
519
520    /// Records superclasses this type extends.
521    pub fn with_extends<I, S>(mut self, bases: I) -> Self
522    where
523        I: IntoIterator<Item = S>,
524        S: AsRef<str>,
525    {
526        for name in bases {
527            self.add_type_relation(TypeRelationKind::Extends, name.as_ref());
528        }
529        self
530    }
531
532    /// Records interfaces or traits this type implements.
533    pub fn with_implements<I, S>(mut self, interfaces: I) -> Self
534    where
535        I: IntoIterator<Item = S>,
536        S: AsRef<str>,
537    {
538        for name in interfaces {
539            self.add_type_relation(TypeRelationKind::Implements, name.as_ref());
540        }
541        self
542    }
543}
544
545impl PartialEq for CodeNode {
546    fn eq(&self, other: &Self) -> bool {
547        self.id == other.id
548    }
549}
550
551impl Eq for CodeNode {}
552
553impl Hash for CodeNode {
554    fn hash<H: Hasher>(&self, state: &mut H) {
555        self.id.hash(state);
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562    use std::collections::HashSet;
563
564    #[test]
565    fn test_node_kind_display_all_variants() {
566        // Exhaustive check of Display for every NodeKind variant
567        assert_eq!(NodeKind::Function.to_string(), "function");
568        assert_eq!(NodeKind::Method.to_string(), "method");
569        assert_eq!(NodeKind::Class.to_string(), "class");
570        assert_eq!(NodeKind::Struct.to_string(), "struct");
571        assert_eq!(NodeKind::Interface.to_string(), "interface");
572        assert_eq!(NodeKind::Enum.to_string(), "enum");
573        assert_eq!(NodeKind::Module.to_string(), "module");
574        assert_eq!(NodeKind::Field.to_string(), "field");
575        assert_eq!(NodeKind::Constant.to_string(), "constant");
576        assert_eq!(NodeKind::Constructor.to_string(), "constructor");
577        assert_eq!(NodeKind::Import.to_string(), "import");
578        assert_eq!(NodeKind::Export.to_string(), "export");
579        assert_eq!(NodeKind::TypeAlias.to_string(), "type_alias");
580        assert_eq!(NodeKind::Variable.to_string(), "variable");
581    }
582
583    #[test]
584    fn test_visibility_default_is_private() {
585        let vis = Visibility::default();
586        assert!(matches!(vis, Visibility::Private));
587    }
588
589    #[test]
590    fn test_builder_pattern_chain() {
591        // Verify that all builder methods compose correctly
592        let node = CodeNode::new("foo", "pkg.foo", NodeKind::Function, "main.rs")
593            .with_lines(10, 20)
594            .with_bytes(100, 300)
595            .with_column(4)
596            .with_signature("fn foo(x: i32) -> bool")
597            .with_visibility(Visibility::Public)
598            .as_async()
599            .as_static()
600            .as_exported()
601            .with_references(vec!["bar".to_string(), "baz".to_string()]);
602
603        assert_eq!(node.name, "foo");
604        assert_eq!(node.qualified_name, "pkg.foo");
605        assert_eq!(node.file, "main.rs");
606        assert_eq!(node.line_start, 10);
607        assert_eq!(node.line_end, 20);
608        assert_eq!(node.byte_start, 100);
609        assert_eq!(node.byte_end, 300);
610        assert_eq!(node.column, 4);
611        assert_eq!(node.signature.as_deref(), Some("fn foo(x: i32) -> bool"));
612        assert!(matches!(node.visibility, Visibility::Public));
613        assert!(node.is_async);
614        assert!(node.is_static);
615        assert!(node.is_exported);
616        assert_eq!(node.references.len(), 2);
617    }
618
619    #[test]
620    fn test_code_node_equality_by_id() {
621        // PartialEq compares by ID only, not by other fields
622        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
623        let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
624        // Same inputs → same ID → equal
625        assert_eq!(node1, node2);
626
627        // Different kind → different ID → not equal
628        let node3 = CodeNode::new("foo", "foo", NodeKind::Method, "a.rs");
629        assert_ne!(node1, node3);
630    }
631
632    #[test]
633    fn test_code_node_hash_consistency() {
634        // Same node should hash identically, and be usable in HashSet
635        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "main.rs");
636        let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "main.rs");
637
638        let mut set = HashSet::new();
639        set.insert(node1.clone());
640        assert!(set.contains(&node2));
641        // Inserting duplicate should not increase size
642        set.insert(node2);
643        assert_eq!(set.len(), 1);
644    }
645
646    #[test]
647    fn test_compute_id_deterministic() {
648        // Same inputs must always produce the same ID
649        let id1 = CodeNode::compute_id("test.rs", "main", NodeKind::Function);
650        let id2 = CodeNode::compute_id("test.rs", "main", NodeKind::Function);
651        assert_eq!(id1, id2);
652    }
653
654    #[test]
655    fn test_compute_id_different_kinds_differ() {
656        // A function and a struct with the same name should have different IDs
657        let id_fn = CodeNode::compute_id("test.rs", "Foo", NodeKind::Function);
658        let id_struct = CodeNode::compute_id("test.rs", "Foo", NodeKind::Struct);
659        assert_ne!(id_fn, id_struct);
660    }
661
662    #[test]
663    fn test_compute_id_different_files_differ() {
664        let id1 = CodeNode::compute_id("a.rs", "main", NodeKind::Function);
665        let id2 = CodeNode::compute_id("b.rs", "main", NodeKind::Function);
666        assert_ne!(id1, id2);
667    }
668
669    #[test]
670    fn field_and_typed_receiver_refs_round_trip() {
671        assert_eq!(
672            field_type_ref(&field_ref("draft", "Draft")),
673            Some(("draft", "Draft"))
674        );
675        assert_eq!(field_type_ref("field:draft"), None);
676        assert_eq!(field_type_ref("draft"), None);
677        assert_eq!(
678            typed_receiver(&typed_receiver_ref("run_started", "AppState.draft")),
679            Some(("run_started", "AppState.draft"))
680        );
681        // A plain unknown-receiver call and a `self` call are not typed.
682        assert_eq!(typed_receiver(".run_started"), None);
683        assert_eq!(typed_receiver("self.run_started"), None);
684        assert_eq!(type_relation_ref(&field_ref("draft", "Draft")), None);
685        assert_eq!(return_type_ref(&returns_ref("Draft")), Some("Draft"));
686        assert_eq!(return_type_ref("returns:"), None);
687        assert_eq!(
688            typed_receiver(".run_started@mac::Draft::capture().load()"),
689            Some(("run_started", "mac::Draft::capture().load()"))
690        );
691    }
692
693    #[test]
694    fn import_alias_refs_round_trip() {
695        assert_eq!(
696            import_alias(&import_alias_ref("to_minor", "money_to_minor_units")),
697            Some(("to_minor", "money_to_minor_units"))
698        );
699        assert_eq!(import_alias("alias:to_minor"), None);
700        assert_eq!(import_alias("alias::money_to_minor_units"), None);
701        assert_eq!(import_alias("alias:to_minor:"), None);
702        // Plain and namespace imports are not aliases.
703        assert_eq!(import_alias("to_minor"), None);
704        assert_eq!(import_alias("*as:types"), None);
705    }
706
707    #[test]
708    fn binding_refs_round_trip() {
709        assert_eq!(
710            runtime_binding(&runtime_binding_ref("set", "setFilters")),
711            Some(("set", "setFilters"))
712        );
713        assert_eq!(runtime_binding("bound:set"), None);
714        assert_eq!(runtime_binding("bound::setFilters"), None);
715        assert_eq!(runtime_binding("alias:set:setFilters"), None);
716        assert_eq!(local_binding(&local_binding_ref("onSave")), Some("onSave"));
717        assert_eq!(local_binding("local:"), None);
718        assert_eq!(local_binding("onSave"), None);
719        // The other import encodings are neither.
720        assert_eq!(import_alias("bound:set:setFilters"), None);
721        assert_eq!(import_alias("local:onSave"), None);
722    }
723
724    #[test]
725    fn type_relation_refs_round_trip() {
726        assert_eq!(
727            type_relation_ref("extends:Base"),
728            Some((TypeRelationKind::Extends, "Base"))
729        );
730        assert_eq!(
731            type_relation_ref("implements:Reader"),
732            Some((TypeRelationKind::Implements, "Reader"))
733        );
734        assert!(type_relation_ref("helper").is_none());
735        assert!(type_relation_ref("extends:").is_none());
736    }
737
738    #[test]
739    fn clean_type_name_strips_generics_and_pointers() {
740        assert_eq!(clean_type_name("*Base"), "Base");
741        assert_eq!(clean_type_name("Foo<T>"), "Foo");
742        assert_eq!(clean_type_name("pkg.Base"), "pkg.Base");
743        assert_eq!(clean_type_name("std::fmt::Display"), "std::fmt::Display");
744        assert_eq!(clean_type_name("object"), "");
745        assert_eq!(clean_type_name("public"), "");
746    }
747
748    #[test]
749    fn with_extends_appends_without_dropping_calls() {
750        let node = CodeNode::new("Middle", "Middle", NodeKind::Class, "a.py")
751            .with_references(vec!["helper".to_string()])
752            .with_extends(["Base"])
753            .with_implements(["Proto"]);
754        assert!(node.references.iter().any(|r| r == "helper"));
755        assert!(node.references.iter().any(|r| r == "extends:Base"));
756        assert!(node.references.iter().any(|r| r == "implements:Proto"));
757    }
758
759    #[test]
760    fn test_node_default_values() {
761        // Verify sensible defaults for a freshly created node
762        let node = CodeNode::new("f", "f", NodeKind::Function, "x.rs");
763        assert_eq!(node.line_start, 0);
764        assert_eq!(node.line_end, 0);
765        assert_eq!(node.byte_start, 0);
766        assert_eq!(node.byte_end, 0);
767        assert_eq!(node.column, 0);
768        assert!(node.signature.is_none());
769        assert!(!node.is_async);
770        assert!(!node.is_static);
771        assert!(!node.is_exported);
772        assert!(node.references.is_empty());
773        assert!(matches!(node.visibility, Visibility::Private));
774    }
775}