use std::collections::HashMap;
use crate::models::{CallIntent, ReferenceIntent};
use crate::pipeline::parser::utils::{find_parent_by_kind_any, is_capitalized, node_text};
use tree_sitter::Node;
pub(crate) fn extract_reference_intents_csharp(
node: Node<'_>,
source: &[u8],
out: &mut Vec<ReferenceIntent>,
) {
let field_types = collect_field_types(node, source);
let mut calls = Vec::new();
extract_call_intents_csharp(node, source, &field_types, &mut calls);
for call in calls {
out.push(ReferenceIntent::Call {
method: call.method,
receiver: call.receiver,
line: call.line,
arg_count: call.arg_count,
});
}
extract_type_references_csharp(node, source, out);
}
pub(crate) fn extract_class_inheritance_csharp(
class_node: Node<'_>,
source: &[u8],
out: &mut Vec<ReferenceIntent>,
) {
let line = class_node.start_position().row + 1;
let mut child = class_node.child(0);
while let Some(c) = child {
if c.kind() == "base_list" {
let entries: Vec<String> = base_entries(c, source);
let is_record_struct =
class_node.kind() == "record_declaration" && record_is_struct(class_node);
for (idx, name) in entries.iter().enumerate() {
let intent = match class_node.kind() {
"interface_declaration" => ReferenceIntent::Extends {
parent: name.clone(),
line,
},
"struct_declaration" => ReferenceIntent::Implements {
interface: name.clone(),
line,
},
"record_declaration" if is_record_struct => ReferenceIntent::Implements {
interface: name.clone(),
line,
},
"class_declaration" | "record_declaration" => {
if idx == 0 && !is_interface_prefix(name) {
ReferenceIntent::Extends {
parent: name.clone(),
line,
}
} else {
ReferenceIntent::Implements {
interface: name.clone(),
line,
}
}
}
_ => ReferenceIntent::Implements {
interface: name.clone(),
line,
},
};
out.push(intent);
}
}
child = c.next_sibling();
}
}
pub(crate) fn extract_attribute_references(
node: Node<'_>,
source: &[u8],
out: &mut Vec<ReferenceIntent>,
) {
if node.kind() == "attribute_list" {
let line = node.start_position().row + 1;
let mut child = node.child(0);
while let Some(c) = child {
if c.kind() == "attribute"
&& let Some(name_node) = c.child_by_field_name("name")
&& let Some(name) = base_name_from_type_node(name_node, source)
{
out.push(ReferenceIntent::Call {
method: name,
receiver: None,
line,
arg_count: None,
});
}
child = c.next_sibling();
}
return;
}
let mut child = node.child(0);
while let Some(c) = child {
extract_attribute_references(c, source, out);
child = c.next_sibling();
}
}
pub(crate) fn extract_type_references_csharp(
node: Node<'_>,
source: &[u8],
out: &mut Vec<ReferenceIntent>,
) {
if (node.kind() == "member_access_expression" || node.kind() == "qualified_name")
&& is_outermost_member_access(node)
&& !is_invocation_function(node)
&& let Some(path) = dotted_path(node, source)
{
let segments: Vec<&str> = path.split('.').collect();
if segments.len() >= 2 && is_capitalized(segments[segments.len() - 2]) {
out.push(ReferenceIntent::TypeReference {
type_name: path,
line: node.start_position().row + 1,
});
}
}
if node.kind() == "identifier" && !is_member_access_name(node) && !is_declaration_name(node) {
let type_name = node_text(node, source);
if is_capitalized(&type_name) {
out.push(ReferenceIntent::TypeReference {
type_name,
line: node.start_position().row + 1,
});
}
return;
}
let mut child = node.child(0);
while let Some(c) = child {
extract_type_references_csharp(c, source, out);
child = c.next_sibling();
}
}
pub(crate) fn collect_all_reference_intents_csharp(
node: Node<'_>,
source: &[u8],
out: &mut Vec<(ReferenceIntent, usize)>,
) {
let byte_pos = node.start_byte();
let line = node.start_position().row + 1;
match node.kind() {
"member_access_expression" | "qualified_name"
if is_outermost_member_access(node) && !is_invocation_function(node) =>
{
if let Some(path) = dotted_path(node, source) {
let segments: Vec<&str> = path.split('.').collect();
if segments.len() >= 2 {
let penultimate = segments[segments.len() - 2];
if is_capitalized(penultimate) {
out.push((
ReferenceIntent::TypeReference {
type_name: path,
line,
},
byte_pos,
));
}
}
}
}
"invocation_expression" | "object_creation_expression" => {
let field_types = HashMap::new();
let calls = single_call_intents(node, source, &field_types);
for call in calls {
out.push((
ReferenceIntent::Call {
method: call.method,
receiver: call.receiver,
line,
arg_count: call.arg_count,
},
byte_pos,
));
}
}
"attribute" => {
if let Some(name_node) = node.child_by_field_name("name")
&& let Some(name) = base_name_from_type_node(name_node, source)
{
out.push((
ReferenceIntent::Call {
method: name,
receiver: None,
line,
arg_count: None,
},
byte_pos,
));
}
}
"using_directive" => {
if let Some(type_name) = using_directive_type_name(node, source) {
out.push((ReferenceIntent::TypeReference { type_name, line }, byte_pos));
}
}
"identifier" if !is_member_access_name(node) && !is_declaration_name(node) => {
let type_name = node_text(node, source);
if is_capitalized(&type_name) {
out.push((ReferenceIntent::TypeReference { type_name, line }, byte_pos));
}
}
_ => {}
}
let mut child = node.child(0);
while let Some(c) = child {
collect_all_reference_intents_csharp(c, source, out);
child = c.next_sibling();
}
}
fn extract_call_intents_csharp(
node: Node<'_>,
source: &[u8],
field_types: &HashMap<String, String>,
out: &mut Vec<CallIntent>,
) {
out.extend(single_call_intents(node, source, field_types));
let mut child = node.child(0);
while let Some(c) = child {
extract_call_intents_csharp(c, source, field_types, out);
child = c.next_sibling();
}
}
fn single_call_intents(
node: Node<'_>,
source: &[u8],
field_types: &HashMap<String, String>,
) -> Vec<CallIntent> {
let mut intents = Vec::new();
let line = node.start_position().row + 1;
if node.kind() == "invocation_expression" {
if let Some(function) = node.child_by_field_name("function") {
match function.kind() {
"identifier" => intents.push(CallIntent {
method: node_text(function, source),
receiver: None,
line,
arg_count: argument_count(node),
}),
"generic_name" => {
if let Some(id) = first_identifier(function) {
intents.push(CallIntent {
method: node_text(id, source),
receiver: None,
line,
arg_count: argument_count(node),
});
}
}
"member_access_expression" => {
if let Some(name_node) = function.child_by_field_name("name")
&& let Some(method) = base_name_from_type_node(name_node, source)
{
let receiver = function
.child_by_field_name("expression")
.map(|expr| receiver_text(expr, source, field_types));
intents.push(CallIntent {
method,
receiver,
line,
arg_count: argument_count(node),
});
}
}
_ => {}
}
}
} else if node.kind() == "object_creation_expression"
&& let Some(type_node) = node.child_by_field_name("type")
&& let Some(name) = base_name_from_type_node(type_node, source)
{
intents.push(CallIntent {
method: name,
receiver: None,
line,
arg_count: None,
});
}
intents
}
fn argument_count(invocation: Node<'_>) -> Option<usize> {
let args = invocation.child_by_field_name("arguments")?;
let mut count = 0;
let mut child = args.child(0);
while let Some(c) = child {
if c.kind() == "argument" {
count += 1;
}
child = c.next_sibling();
}
Some(count)
}
fn receiver_text(expr: Node<'_>, source: &[u8], field_types: &HashMap<String, String>) -> String {
let raw = node_text(expr, source);
if expr.kind() == "base_expression" || raw == "base" {
return "super".to_string();
}
if expr.kind() == "identifier"
&& let Some(declared) = field_types.get(raw.as_str())
{
return declared.clone();
}
raw
}
fn collect_field_types(node: Node<'_>, source: &[u8]) -> HashMap<String, String> {
let mut map = HashMap::new();
let enclosing = find_parent_by_kind_any(
node,
&[
"class_declaration",
"interface_declaration",
"struct_declaration",
"record_declaration",
],
);
let Some(type_node) = enclosing else {
return map;
};
let body = first_child_of_kind(type_node, "declaration_list").unwrap_or(type_node);
let mut child = body.child(0);
while let Some(c) = child {
if c.kind() == "field_declaration"
&& let Some(var_decl) = first_child_of_kind(c, "variable_declaration")
&& let Some(type_node) = var_decl.child_by_field_name("type")
{
let base_type = base_type_text(type_node, source);
let mut declarator = var_decl.child(0);
while let Some(d) = declarator {
if d.kind() == "variable_declarator"
&& let Some(name_node) = d.child_by_field_name("name")
{
map.insert(node_text(name_node, source), base_type.clone());
}
declarator = d.next_sibling();
}
}
child = c.next_sibling();
}
map
}
fn base_type_text(type_node: Node<'_>, source: &[u8]) -> String {
let raw = node_text(type_node, source);
raw.split(['<', '[', '?'])
.next()
.unwrap_or(&raw)
.trim()
.to_string()
}
fn is_interface_prefix(name: &str) -> bool {
let bytes = name.as_bytes();
bytes.len() >= 2 && bytes[0] == b'I' && bytes[1].is_ascii_uppercase()
}
pub(crate) fn record_is_struct(record_node: Node<'_>) -> bool {
let mut child = record_node.child(0);
while let Some(c) = child {
if c.kind() == "struct" && !c.is_named() {
return true;
}
child = c.next_sibling();
}
false
}
fn base_entries(base_list: Node<'_>, source: &[u8]) -> Vec<String> {
let mut entries = Vec::new();
let mut child = base_list.child(0);
while let Some(c) = child {
if c.is_named()
&& let Some(name) = base_name_from_type_node(c, source)
{
entries.push(name);
}
child = c.next_sibling();
}
entries
}
fn base_name_from_type_node(node: Node<'_>, source: &[u8]) -> Option<String> {
match node.kind() {
"identifier" => Some(node_text(node, source)),
"generic_name" => first_identifier(node).map(|id| node_text(id, source)),
"qualified_name" | "alias_qualified_name" => node
.child_by_field_name("name")
.and_then(|n| base_name_from_type_node(n, source)),
"nullable_type" => node
.child_by_field_name("type")
.and_then(|n| base_name_from_type_node(n, source)),
"primary_constructor_base_type" => node
.child_by_field_name("type")
.and_then(|n| base_name_from_type_node(n, source)),
_ => None,
}
}
fn is_member_access_name(node: Node<'_>) -> bool {
node.parent().is_some_and(|p| {
(p.kind() == "member_access_expression" || p.kind() == "qualified_name")
&& p.child_by_field_name("name")
.is_some_and(|n| n.id() == node.id())
})
}
fn dotted_path(node: Node<'_>, source: &[u8]) -> Option<String> {
let mut current = node;
let mut segments = Vec::new();
loop {
let parent_field = match current.kind() {
"member_access_expression" => "expression",
"qualified_name" => "qualifier",
"identifier" => {
segments.push(node_text(current, source));
break;
}
_ => return None,
};
let name_node = current.child_by_field_name("name")?;
if name_node.kind() != "identifier" {
return None;
}
segments.push(node_text(name_node, source));
current = current.child_by_field_name(parent_field)?;
}
segments.reverse();
Some(segments.join("."))
}
fn is_outermost_member_access(node: Node<'_>) -> bool {
if let Some(parent) = node.parent() {
match parent.kind() {
"member_access_expression" => {
parent.child_by_field_name("expression").map(|e| e.id()) != Some(node.id())
}
"qualified_name" => {
parent.child_by_field_name("qualifier").map(|q| q.id()) != Some(node.id())
}
_ => true,
}
} else {
true
}
}
fn is_invocation_function(node: Node<'_>) -> bool {
if let Some(parent) = node.parent() {
parent.kind() == "invocation_expression"
&& parent.child_by_field_name("function").map(|f| f.id()) == Some(node.id())
} else {
false
}
}
fn is_declaration_name(node: Node<'_>) -> bool {
if let Some(parent) = node.parent() {
let parent_kind = parent.kind();
let is_decl_kind = matches!(
parent_kind,
"enum_member_declaration"
| "class_declaration"
| "interface_declaration"
| "struct_declaration"
| "record_declaration"
| "enum_declaration"
| "method_declaration"
| "constructor_declaration"
| "destructor_declaration"
| "property_declaration"
| "event_declaration"
| "delegate_declaration"
| "namespace_declaration"
| "file_scoped_namespace_declaration"
| "local_function_statement"
| "variable_declarator"
| "parameter"
| "type_parameter"
| "catch_declaration"
| "declaration_expression"
| "declaration_pattern"
);
if is_decl_kind
&& let Some(name_node) = parent.child_by_field_name("name")
&& name_node.id() == node.id()
{
return true;
}
}
false
}
fn using_directive_type_name(directive: Node<'_>, source: &[u8]) -> Option<String> {
let mut last: Option<String> = None;
let mut stack = vec![directive];
while let Some(n) = stack.pop() {
match n.kind() {
"identifier" => last = Some(node_text(n, source)),
"generic_name" | "qualified_name" | "alias_qualified_name" => {
if let Some(name_node) = n.child_by_field_name("name") {
stack.push(name_node);
} else {
let mut child = n.child(0);
while let Some(c) = child {
if c.is_named() {
stack.push(c);
}
child = c.next_sibling();
}
}
}
_ => {
let mut child = n.child(0);
while let Some(c) = child {
if c.is_named() {
stack.push(c);
}
child = c.next_sibling();
}
}
}
}
let name = last?;
if is_capitalized(&name) {
Some(name)
} else {
None
}
}
fn first_identifier(node: Node<'_>) -> Option<Node<'_>> {
if node.kind() == "identifier" {
return Some(node);
}
let mut child = node.child(0);
while let Some(c) = child {
if let Some(found) = first_identifier(c) {
return Some(found);
}
child = c.next_sibling();
}
None
}
fn first_child_of_kind<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
let mut child = node.child(0);
while let Some(c) = child {
if c.kind() == kind {
return Some(c);
}
child = c.next_sibling();
}
None
}