use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeKind {
Function,
Method,
Class,
Interface,
Struct,
Enum,
Variable,
Constant,
TypeAlias,
Module,
Import,
Export,
Constructor,
Field,
Section,
}
impl std::fmt::Display for NodeKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::Function => "function",
Self::Method => "method",
Self::Class => "class",
Self::Interface => "interface",
Self::Struct => "struct",
Self::Enum => "enum",
Self::Variable => "variable",
Self::Constant => "constant",
Self::TypeAlias => "type_alias",
Self::Module => "module",
Self::Import => "import",
Self::Export => "export",
Self::Constructor => "constructor",
Self::Field => "field",
Self::Section => "section",
};
write!(f, "{}", s)
}
}
pub const EXTENDS_REF_PREFIX: &str = "extends:";
pub const IMPLEMENTS_REF_PREFIX: &str = "implements:";
pub const FIELD_REF_PREFIX: &str = "field:";
pub fn field_ref(field: &str, type_name: &str) -> String {
format!("{FIELD_REF_PREFIX}{field}:{type_name}")
}
pub fn field_type_ref(reference: &str) -> Option<(&str, &str)> {
let (field, type_name) = reference.strip_prefix(FIELD_REF_PREFIX)?.split_once(':')?;
(!field.is_empty() && !type_name.is_empty()).then_some((field, type_name))
}
pub const RETURNS_REF_PREFIX: &str = "returns:";
pub fn returns_ref(type_name: &str) -> String {
format!("{RETURNS_REF_PREFIX}{type_name}")
}
pub fn return_type_ref(reference: &str) -> Option<&str> {
reference
.strip_prefix(RETURNS_REF_PREFIX)
.filter(|type_name| !type_name.is_empty())
}
pub fn typed_receiver_ref(method: &str, receiver_type: &str) -> String {
format!(".{method}@{receiver_type}")
}
pub fn typed_receiver(reference: &str) -> Option<(&str, &str)> {
let (method, receiver) = reference.strip_prefix('.')?.split_once('@')?;
(!method.is_empty() && !receiver.is_empty()).then_some((method, receiver))
}
pub const IMPORT_ALIAS_REF_PREFIX: &str = "alias:";
pub fn import_alias_ref(local: &str, imported: &str) -> String {
format!("{IMPORT_ALIAS_REF_PREFIX}{local}:{imported}")
}
pub fn import_alias(reference: &str) -> Option<(&str, &str)> {
let (local, imported) = reference
.strip_prefix(IMPORT_ALIAS_REF_PREFIX)?
.split_once(':')?;
(!local.is_empty() && !imported.is_empty()).then_some((local, imported))
}
pub fn import_qualified_name(module: &str, start_byte: usize) -> String {
format!("{module}@{start_byte}")
}
pub const RUNTIME_BINDING_REF_PREFIX: &str = "bound:";
pub fn runtime_binding_ref(local: &str, name: &str) -> String {
format!("{RUNTIME_BINDING_REF_PREFIX}{local}:{name}")
}
pub fn runtime_binding(reference: &str) -> Option<(&str, &str)> {
let (local, name) = reference
.strip_prefix(RUNTIME_BINDING_REF_PREFIX)?
.split_once(':')?;
(!local.is_empty() && !name.is_empty()).then_some((local, name))
}
pub const MODULE_FILE_REF: &str = "module:";
pub const LOCAL_BINDING_REF_PREFIX: &str = "local:";
pub fn local_binding_ref(name: &str) -> String {
format!("{LOCAL_BINDING_REF_PREFIX}{name}")
}
pub fn local_binding(reference: &str) -> Option<&str> {
reference
.strip_prefix(LOCAL_BINDING_REF_PREFIX)
.filter(|name| !name.is_empty())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeRelationKind {
Extends,
Implements,
}
pub fn type_relation_ref(reference: &str) -> Option<(TypeRelationKind, &str)> {
let reference = reference.trim();
if let Some(name) = reference.strip_prefix(EXTENDS_REF_PREFIX) {
let name = name.trim();
if !name.is_empty() {
return Some((TypeRelationKind::Extends, name));
}
}
if let Some(name) = reference.strip_prefix(IMPLEMENTS_REF_PREFIX) {
let name = name.trim();
if !name.is_empty() {
return Some((TypeRelationKind::Implements, name));
}
}
None
}
pub fn clean_type_name(raw: &str) -> String {
let mut raw = raw.trim();
loop {
if let Some(rest) = raw.strip_prefix('*').or_else(|| raw.strip_prefix('&')) {
raw = rest.trim_start();
continue;
}
if let Some(rest) = raw.strip_prefix("mut ") {
raw = rest.trim_start();
continue;
}
break;
}
let raw = raw.split(['<', '[']).next().unwrap_or(raw).trim();
let raw = raw.trim_end_matches('?').trim();
if raw.is_empty() || is_type_keyword(raw) || !is_type_path(raw) {
return String::new();
}
raw.to_string()
}
fn is_type_path(name: &str) -> bool {
let mut chars = name.chars();
let Some(first) = chars.next() else {
return false;
};
if !(first.is_alphabetic() || first == '_') {
return false;
}
name.chars()
.all(|c| c.is_alphanumeric() || c == '_' || c == '.' || c == ':')
}
fn is_type_keyword(name: &str) -> bool {
matches!(
name,
"public"
| "private"
| "protected"
| "virtual"
| "override"
| "abstract"
| "static"
| "final"
| "sealed"
| "partial"
| "readonly"
| "const"
| "class"
| "struct"
| "interface"
| "enum"
| "extends"
| "implements"
| "with"
| "where"
| "new"
| "base"
| "this"
| "super"
| "mut"
| "pub"
| "crate"
| "object"
)
}
fn push_type_relation(references: &mut Vec<String>, kind: TypeRelationKind, name: &str) {
let name = clean_type_name(name);
if name.is_empty() {
return;
}
let prefix = match kind {
TypeRelationKind::Extends => EXTENDS_REF_PREFIX,
TypeRelationKind::Implements => IMPLEMENTS_REF_PREFIX,
};
let encoded = format!("{prefix}{name}");
if !references.iter().any(|existing| existing == &encoded) {
references.push(encoded);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum Visibility {
#[default]
Private,
Public,
Protected,
Internal,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeNode {
pub id: String,
pub name: String,
pub qualified_name: String,
pub kind: NodeKind,
pub file: String,
pub line_start: u32,
pub line_end: u32,
pub column: u32,
pub signature: Option<String>,
pub visibility: Visibility,
pub is_async: bool,
pub is_static: bool,
pub is_exported: bool,
pub docstring: Option<String>,
pub byte_start: u32,
pub byte_end: u32,
pub references: Vec<String>,
}
impl CodeNode {
pub fn compute_id(file: &str, qualified_name: &str, kind: NodeKind) -> String {
use std::collections::hash_map::DefaultHasher;
let mut hasher = DefaultHasher::new();
file.hash(&mut hasher);
qualified_name.hash(&mut hasher);
kind.hash(&mut hasher);
format!("{:016x}", hasher.finish())
}
pub fn new(
name: impl Into<String>,
qualified_name: impl Into<String>,
kind: NodeKind,
file: impl Into<String>,
) -> Self {
let name = name.into();
let qualified_name = qualified_name.into();
let file = file.into();
let id = Self::compute_id(&file, &qualified_name, kind);
Self {
id,
name,
qualified_name,
kind,
file,
line_start: 0,
line_end: 0,
column: 0,
signature: None,
visibility: Visibility::default(),
is_async: false,
is_static: false,
is_exported: false,
docstring: None,
byte_start: 0,
byte_end: 0,
references: Vec::new(),
}
}
pub fn with_lines(mut self, start: u32, end: u32) -> Self {
self.line_start = start;
self.line_end = end;
self
}
pub fn with_bytes(mut self, start: u32, end: u32) -> Self {
self.byte_start = start;
self.byte_end = end;
self
}
pub fn with_column(mut self, column: u32) -> Self {
self.column = column;
self
}
pub fn with_signature(mut self, sig: impl Into<String>) -> Self {
self.signature = Some(sig.into());
self
}
pub fn with_visibility(mut self, vis: Visibility) -> Self {
self.visibility = vis;
self
}
pub fn as_async(mut self) -> Self {
self.is_async = true;
self
}
pub fn as_static(mut self) -> Self {
self.is_static = true;
self
}
pub fn as_exported(mut self) -> Self {
self.is_exported = true;
self
}
pub fn with_references(mut self, refs: Vec<String>) -> Self {
self.references = refs;
self
}
pub fn add_type_relation(&mut self, kind: TypeRelationKind, name: &str) {
push_type_relation(&mut self.references, kind, name);
}
pub fn with_extends<I, S>(mut self, bases: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
for name in bases {
self.add_type_relation(TypeRelationKind::Extends, name.as_ref());
}
self
}
pub fn with_implements<I, S>(mut self, interfaces: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
for name in interfaces {
self.add_type_relation(TypeRelationKind::Implements, name.as_ref());
}
self
}
}
impl PartialEq for CodeNode {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for CodeNode {}
impl Hash for CodeNode {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn test_node_kind_display_all_variants() {
assert_eq!(NodeKind::Function.to_string(), "function");
assert_eq!(NodeKind::Method.to_string(), "method");
assert_eq!(NodeKind::Class.to_string(), "class");
assert_eq!(NodeKind::Struct.to_string(), "struct");
assert_eq!(NodeKind::Interface.to_string(), "interface");
assert_eq!(NodeKind::Enum.to_string(), "enum");
assert_eq!(NodeKind::Module.to_string(), "module");
assert_eq!(NodeKind::Field.to_string(), "field");
assert_eq!(NodeKind::Constant.to_string(), "constant");
assert_eq!(NodeKind::Constructor.to_string(), "constructor");
assert_eq!(NodeKind::Import.to_string(), "import");
assert_eq!(NodeKind::Export.to_string(), "export");
assert_eq!(NodeKind::TypeAlias.to_string(), "type_alias");
assert_eq!(NodeKind::Variable.to_string(), "variable");
}
#[test]
fn test_visibility_default_is_private() {
let vis = Visibility::default();
assert!(matches!(vis, Visibility::Private));
}
#[test]
fn test_builder_pattern_chain() {
let node = CodeNode::new("foo", "pkg.foo", NodeKind::Function, "main.rs")
.with_lines(10, 20)
.with_bytes(100, 300)
.with_column(4)
.with_signature("fn foo(x: i32) -> bool")
.with_visibility(Visibility::Public)
.as_async()
.as_static()
.as_exported()
.with_references(vec!["bar".to_string(), "baz".to_string()]);
assert_eq!(node.name, "foo");
assert_eq!(node.qualified_name, "pkg.foo");
assert_eq!(node.file, "main.rs");
assert_eq!(node.line_start, 10);
assert_eq!(node.line_end, 20);
assert_eq!(node.byte_start, 100);
assert_eq!(node.byte_end, 300);
assert_eq!(node.column, 4);
assert_eq!(node.signature.as_deref(), Some("fn foo(x: i32) -> bool"));
assert!(matches!(node.visibility, Visibility::Public));
assert!(node.is_async);
assert!(node.is_static);
assert!(node.is_exported);
assert_eq!(node.references.len(), 2);
}
#[test]
fn test_code_node_equality_by_id() {
let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
assert_eq!(node1, node2);
let node3 = CodeNode::new("foo", "foo", NodeKind::Method, "a.rs");
assert_ne!(node1, node3);
}
#[test]
fn test_code_node_hash_consistency() {
let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "main.rs");
let node2 = CodeNode::new("foo", "foo", NodeKind::Function, "main.rs");
let mut set = HashSet::new();
set.insert(node1.clone());
assert!(set.contains(&node2));
set.insert(node2);
assert_eq!(set.len(), 1);
}
#[test]
fn test_compute_id_deterministic() {
let id1 = CodeNode::compute_id("test.rs", "main", NodeKind::Function);
let id2 = CodeNode::compute_id("test.rs", "main", NodeKind::Function);
assert_eq!(id1, id2);
}
#[test]
fn test_compute_id_different_kinds_differ() {
let id_fn = CodeNode::compute_id("test.rs", "Foo", NodeKind::Function);
let id_struct = CodeNode::compute_id("test.rs", "Foo", NodeKind::Struct);
assert_ne!(id_fn, id_struct);
}
#[test]
fn test_compute_id_different_files_differ() {
let id1 = CodeNode::compute_id("a.rs", "main", NodeKind::Function);
let id2 = CodeNode::compute_id("b.rs", "main", NodeKind::Function);
assert_ne!(id1, id2);
}
#[test]
fn field_and_typed_receiver_refs_round_trip() {
assert_eq!(
field_type_ref(&field_ref("draft", "Draft")),
Some(("draft", "Draft"))
);
assert_eq!(field_type_ref("field:draft"), None);
assert_eq!(field_type_ref("draft"), None);
assert_eq!(
typed_receiver(&typed_receiver_ref("run_started", "AppState.draft")),
Some(("run_started", "AppState.draft"))
);
assert_eq!(typed_receiver(".run_started"), None);
assert_eq!(typed_receiver("self.run_started"), None);
assert_eq!(type_relation_ref(&field_ref("draft", "Draft")), None);
assert_eq!(return_type_ref(&returns_ref("Draft")), Some("Draft"));
assert_eq!(return_type_ref("returns:"), None);
assert_eq!(
typed_receiver(".run_started@mac::Draft::capture().load()"),
Some(("run_started", "mac::Draft::capture().load()"))
);
}
#[test]
fn import_alias_refs_round_trip() {
assert_eq!(
import_alias(&import_alias_ref("to_minor", "money_to_minor_units")),
Some(("to_minor", "money_to_minor_units"))
);
assert_eq!(import_alias("alias:to_minor"), None);
assert_eq!(import_alias("alias::money_to_minor_units"), None);
assert_eq!(import_alias("alias:to_minor:"), None);
assert_eq!(import_alias("to_minor"), None);
assert_eq!(import_alias("*as:types"), None);
}
#[test]
fn binding_refs_round_trip() {
assert_eq!(
runtime_binding(&runtime_binding_ref("set", "setFilters")),
Some(("set", "setFilters"))
);
assert_eq!(runtime_binding("bound:set"), None);
assert_eq!(runtime_binding("bound::setFilters"), None);
assert_eq!(runtime_binding("alias:set:setFilters"), None);
assert_eq!(local_binding(&local_binding_ref("onSave")), Some("onSave"));
assert_eq!(local_binding("local:"), None);
assert_eq!(local_binding("onSave"), None);
assert_eq!(import_alias("bound:set:setFilters"), None);
assert_eq!(import_alias("local:onSave"), None);
}
#[test]
fn type_relation_refs_round_trip() {
assert_eq!(
type_relation_ref("extends:Base"),
Some((TypeRelationKind::Extends, "Base"))
);
assert_eq!(
type_relation_ref("implements:Reader"),
Some((TypeRelationKind::Implements, "Reader"))
);
assert!(type_relation_ref("helper").is_none());
assert!(type_relation_ref("extends:").is_none());
}
#[test]
fn clean_type_name_strips_generics_and_pointers() {
assert_eq!(clean_type_name("*Base"), "Base");
assert_eq!(clean_type_name("Foo<T>"), "Foo");
assert_eq!(clean_type_name("pkg.Base"), "pkg.Base");
assert_eq!(clean_type_name("std::fmt::Display"), "std::fmt::Display");
assert_eq!(clean_type_name("object"), "");
assert_eq!(clean_type_name("public"), "");
}
#[test]
fn with_extends_appends_without_dropping_calls() {
let node = CodeNode::new("Middle", "Middle", NodeKind::Class, "a.py")
.with_references(vec!["helper".to_string()])
.with_extends(["Base"])
.with_implements(["Proto"]);
assert!(node.references.iter().any(|r| r == "helper"));
assert!(node.references.iter().any(|r| r == "extends:Base"));
assert!(node.references.iter().any(|r| r == "implements:Proto"));
}
#[test]
fn test_node_default_values() {
let node = CodeNode::new("f", "f", NodeKind::Function, "x.rs");
assert_eq!(node.line_start, 0);
assert_eq!(node.line_end, 0);
assert_eq!(node.byte_start, 0);
assert_eq!(node.byte_end, 0);
assert_eq!(node.column, 0);
assert!(node.signature.is_none());
assert!(!node.is_async);
assert!(!node.is_static);
assert!(!node.is_exported);
assert!(node.references.is_empty());
assert!(matches!(node.visibility, Visibility::Private));
}
}