1use serde::{Deserialize, Serialize};
8use std::hash::{Hash, Hasher};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum NodeKind {
18 Function,
20 Method,
22 Class,
24 Interface,
26 Struct,
28 Enum,
30 Variable,
32 Constant,
34 TypeAlias,
36 Module,
38 Import,
40 Export,
42 Constructor,
44 Field,
46 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
73pub const EXTENDS_REF_PREFIX: &str = "extends:";
78
79pub const IMPLEMENTS_REF_PREFIX: &str = "implements:";
81
82pub const FIELD_REF_PREFIX: &str = "field:";
90
91pub fn field_ref(field: &str, type_name: &str) -> String {
93 format!("{FIELD_REF_PREFIX}{field}:{type_name}")
94}
95
96pub 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
102pub const RETURNS_REF_PREFIX: &str = "returns:";
106
107pub fn returns_ref(type_name: &str) -> String {
109 format!("{RETURNS_REF_PREFIX}{type_name}")
110}
111
112pub 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
119pub fn typed_receiver_ref(method: &str, receiver_type: &str) -> String {
129 format!(".{method}@{receiver_type}")
130}
131
132pub 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
139pub const IMPORT_ALIAS_REF_PREFIX: &str = "alias:";
147
148pub fn import_alias_ref(local: &str, imported: &str) -> String {
150 format!("{IMPORT_ALIAS_REF_PREFIX}{local}:{imported}")
151}
152
153pub 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
162pub fn import_qualified_name(module: &str, start_byte: usize) -> String {
172 format!("{module}@{start_byte}")
173}
174
175pub const RUNTIME_BINDING_REF_PREFIX: &str = "bound:";
184
185pub fn runtime_binding_ref(local: &str, name: &str) -> String {
187 format!("{RUNTIME_BINDING_REF_PREFIX}{local}:{name}")
188}
189
190pub 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
199pub const MODULE_FILE_REF: &str = "module:";
205
206pub const LOCAL_BINDING_REF_PREFIX: &str = "local:";
212
213pub fn local_binding_ref(name: &str) -> String {
215 format!("{LOCAL_BINDING_REF_PREFIX}{name}")
216}
217
218pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum TypeRelationKind {
228 Extends,
230 Implements,
232}
233
234pub 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
254pub 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#[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 Internal,
350}
351
352#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct CodeNode {
358 pub id: String,
360
361 pub name: String,
363
364 pub qualified_name: String,
366
367 pub kind: NodeKind,
369
370 pub file: String,
372
373 pub line_start: u32,
375
376 pub line_end: u32,
378
379 pub column: u32,
381
382 pub signature: Option<String>,
384
385 pub visibility: Visibility,
387
388 pub is_async: bool,
390
391 pub is_static: bool,
393
394 pub is_exported: bool,
396
397 pub docstring: Option<String>,
399
400 pub byte_start: u32,
402 pub byte_end: u32,
403
404 pub references: Vec<String>,
407}
408
409impl CodeNode {
410 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 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 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 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 pub fn with_column(mut self, column: u32) -> Self {
474 self.column = column;
475 self
476 }
477
478 pub fn with_signature(mut self, sig: impl Into<String>) -> Self {
480 self.signature = Some(sig.into());
481 self
482 }
483
484 pub fn with_visibility(mut self, vis: Visibility) -> Self {
486 self.visibility = vis;
487 self
488 }
489
490 pub fn as_async(mut self) -> Self {
492 self.is_async = true;
493 self
494 }
495
496 pub fn as_static(mut self) -> Self {
498 self.is_static = true;
499 self
500 }
501
502 pub fn as_exported(mut self) -> Self {
504 self.is_exported = true;
505 self
506 }
507
508 pub fn with_references(mut self, refs: Vec<String>) -> Self {
510 self.references = refs;
511 self
512 }
513
514 pub fn add_type_relation(&mut self, kind: TypeRelationKind, name: &str) {
517 push_type_relation(&mut self.references, kind, name);
518 }
519
520 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 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 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 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 let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
623 let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
624 assert_eq!(node1, node2);
626
627 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 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 set.insert(node2);
643 assert_eq!(set.len(), 1);
644 }
645
646 #[test]
647 fn test_compute_id_deterministic() {
648 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 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 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 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 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 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}