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
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum TypeRelationKind {
142 Extends,
144 Implements,
146}
147
148pub 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
168pub 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#[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 Internal,
264}
265
266#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct CodeNode {
272 pub id: String,
274
275 pub name: String,
277
278 pub qualified_name: String,
280
281 pub kind: NodeKind,
283
284 pub file: String,
286
287 pub line_start: u32,
289
290 pub line_end: u32,
292
293 pub column: u32,
295
296 pub signature: Option<String>,
298
299 pub visibility: Visibility,
301
302 pub is_async: bool,
304
305 pub is_static: bool,
307
308 pub is_exported: bool,
310
311 pub docstring: Option<String>,
313
314 pub byte_start: u32,
316 pub byte_end: u32,
317
318 pub references: Vec<String>,
321}
322
323impl CodeNode {
324 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 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 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 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 pub fn with_column(mut self, column: u32) -> Self {
388 self.column = column;
389 self
390 }
391
392 pub fn with_signature(mut self, sig: impl Into<String>) -> Self {
394 self.signature = Some(sig.into());
395 self
396 }
397
398 pub fn with_visibility(mut self, vis: Visibility) -> Self {
400 self.visibility = vis;
401 self
402 }
403
404 pub fn as_async(mut self) -> Self {
406 self.is_async = true;
407 self
408 }
409
410 pub fn as_static(mut self) -> Self {
412 self.is_static = true;
413 self
414 }
415
416 pub fn as_exported(mut self) -> Self {
418 self.is_exported = true;
419 self
420 }
421
422 pub fn with_references(mut self, refs: Vec<String>) -> Self {
424 self.references = refs;
425 self
426 }
427
428 pub fn add_type_relation(&mut self, kind: TypeRelationKind, name: &str) {
431 push_type_relation(&mut self.references, kind, name);
432 }
433
434 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 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 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 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 let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
537 let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
538 assert_eq!(node1, node2);
540
541 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 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 set.insert(node2);
557 assert_eq!(set.len(), 1);
558 }
559
560 #[test]
561 fn test_compute_id_deterministic() {
562 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 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 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 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}