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
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum TypeRelationKind {
85 Extends,
87 Implements,
89}
90
91pub 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
111pub 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#[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 Internal,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
214pub struct CodeNode {
215 pub id: String,
217
218 pub name: String,
220
221 pub qualified_name: String,
223
224 pub kind: NodeKind,
226
227 pub file: String,
229
230 pub line_start: u32,
232
233 pub line_end: u32,
235
236 pub column: u32,
238
239 pub signature: Option<String>,
241
242 pub visibility: Visibility,
244
245 pub is_async: bool,
247
248 pub is_static: bool,
250
251 pub is_exported: bool,
253
254 pub docstring: Option<String>,
256
257 pub byte_start: u32,
259 pub byte_end: u32,
260
261 pub references: Vec<String>,
264}
265
266impl CodeNode {
267 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 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 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 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 pub fn with_column(mut self, column: u32) -> Self {
331 self.column = column;
332 self
333 }
334
335 pub fn with_signature(mut self, sig: impl Into<String>) -> Self {
337 self.signature = Some(sig.into());
338 self
339 }
340
341 pub fn with_visibility(mut self, vis: Visibility) -> Self {
343 self.visibility = vis;
344 self
345 }
346
347 pub fn as_async(mut self) -> Self {
349 self.is_async = true;
350 self
351 }
352
353 pub fn as_static(mut self) -> Self {
355 self.is_static = true;
356 self
357 }
358
359 pub fn as_exported(mut self) -> Self {
361 self.is_exported = true;
362 self
363 }
364
365 pub fn with_references(mut self, refs: Vec<String>) -> Self {
367 self.references = refs;
368 self
369 }
370
371 pub fn add_type_relation(&mut self, kind: TypeRelationKind, name: &str) {
374 push_type_relation(&mut self.references, kind, name);
375 }
376
377 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 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 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 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 let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
480 let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
481 assert_eq!(node1, node2);
483
484 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 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 set.insert(node2);
500 assert_eq!(set.len(), 1);
501 }
502
503 #[test]
504 fn test_compute_id_deterministic() {
505 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 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 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}