use crate::domain::{LanguageId, ReferenceKind, ReferenceRecord, SymbolKind, SymbolRecord};
use super::store::IndexedFile;
pub(super) fn parse_reference_kind_filter(kind_filter: Option<&str>) -> Option<ReferenceKind> {
match kind_filter {
Some("call") => Some(ReferenceKind::Call),
Some("import") => Some(ReferenceKind::Import),
Some("type_usage") => Some(ReferenceKind::TypeUsage),
Some("macro_use") => Some(ReferenceKind::MacroUse),
Some("value_use") => Some(ReferenceKind::ValueUse),
Some("all") | None => None,
_ => None,
}
}
pub(super) fn matches_exact_symbol_qualified_name(
language: &LanguageId,
qualified_name: &str,
target_name: &str,
module_path: Option<&str>,
) -> bool {
let separator = match language {
LanguageId::Python => ".",
LanguageId::JavaScript | LanguageId::TypeScript => "/",
_ => "::",
};
let Some(module_path) = module_path else {
return false;
};
let full_path = format!("{module_path}{separator}{target_name}");
if qualified_name == full_path {
return true;
}
if full_path.ends_with(qualified_name)
&& full_path[..full_path.len() - qualified_name.len()].ends_with(separator)
{
return true;
}
false
}
pub(super) fn matches_exact_symbol_reference(
reference: &ReferenceRecord,
target_name: &str,
target_language: &LanguageId,
target_kind: SymbolKind,
module_path: Option<&str>,
reference_file: Option<&IndexedFile>,
kind_filter: Option<ReferenceKind>,
) -> bool {
if let Some(kind_filter) = kind_filter
&& reference.kind != kind_filter
{
return false;
}
if reference
.qualified_name
.as_deref()
.is_some_and(|qualified_name| {
matches_exact_symbol_qualified_name(
target_language,
qualified_name,
target_name,
module_path,
)
})
{
return true;
}
if reference.name != target_name {
return false;
}
if target_kind == SymbolKind::Function && *target_language == LanguageId::Rust {
if reference.qualified_name.is_some() {
return false;
}
if is_rust_receiver_method_call(reference_file, reference) {
return false;
}
}
true
}
fn is_rust_receiver_method_call(
reference_file: Option<&IndexedFile>,
reference: &ReferenceRecord,
) -> bool {
let Some(file) = reference_file else {
return false;
};
if file.language != LanguageId::Rust {
return false;
}
is_receiver_method_call(file, reference)
}
pub(super) fn is_receiver_method_call(file: &IndexedFile, reference: &ReferenceRecord) -> bool {
if reference.kind != ReferenceKind::Call {
return false;
}
let start = reference.byte_range.0 as usize;
start > 0 && file.content.get(start - 1) == Some(&b'.')
}
pub(crate) enum SymbolSelectorMatch<'a> {
Selected(usize, &'a SymbolRecord),
NotFound,
Ambiguous(Vec<u32>),
}
pub(super) fn kind_disambiguation_tier(kind: &SymbolKind) -> u8 {
match kind {
SymbolKind::Class
| SymbolKind::Struct
| SymbolKind::Enum
| SymbolKind::Interface
| SymbolKind::Trait => 1,
SymbolKind::Module => 2,
SymbolKind::Function | SymbolKind::Method | SymbolKind::Impl => 3,
_ => 4, }
}
pub(crate) fn resolve_symbol_selector<'a>(
file: &'a IndexedFile,
name: &str,
symbol_kind: Option<&str>,
symbol_line: Option<u32>,
) -> SymbolSelectorMatch<'a> {
let candidates = find_candidates_cascade(file, name, symbol_kind, symbol_line);
match candidates.len() {
0 => SymbolSelectorMatch::NotFound,
1 => {
let (idx, symbol) = candidates[0];
SymbolSelectorMatch::Selected(idx, symbol)
}
_ => {
if symbol_kind.is_none() {
let min_tier = candidates
.iter()
.map(|(_, sym)| kind_disambiguation_tier(&sym.kind))
.min()
.unwrap();
let top_tier: Vec<usize> = candidates
.iter()
.enumerate()
.filter(|(_, (_, sym))| kind_disambiguation_tier(&sym.kind) == min_tier)
.map(|(i, _)| i)
.collect();
if top_tier.len() == 1 {
let (idx, symbol) = candidates[top_tier[0]];
return SymbolSelectorMatch::Selected(idx, symbol);
}
}
SymbolSelectorMatch::Ambiguous(
candidates
.into_iter()
.map(|(_, symbol)| symbol.line_range.0)
.collect(),
)
}
}
}
pub(crate) fn symbol_belongs_to_type(
file: &IndexedFile,
candidate: &SymbolRecord,
type_name: &str,
) -> bool {
let (cand_start, cand_end) = candidate.line_range;
file.symbols.iter().any(|container| {
let (start, end) = container.line_range;
start <= cand_start
&& cand_end <= end
&& container_target_type(container).is_some_and(|ty| ty == type_name)
})
}
fn container_target_type(symbol: &SymbolRecord) -> Option<&str> {
let raw = match symbol.kind {
SymbolKind::Impl => {
let name = symbol.name.as_str();
match name.rsplit_once(" for ") {
Some((_, ty)) => ty,
None => name.strip_prefix("impl ").unwrap_or(name),
}
}
SymbolKind::Struct
| SymbolKind::Enum
| SymbolKind::Trait
| SymbolKind::Class
| SymbolKind::Interface => symbol.name.as_str(),
_ => return None,
};
Some(base_type_token(raw.trim()))
}
fn base_type_token(ty: &str) -> &str {
let ty = ty.split('<').next().unwrap_or(ty).trim();
ty.rsplit("::").next().unwrap_or(ty).trim()
}
fn find_candidates_cascade<'a>(
file: &'a IndexedFile,
name: &str,
symbol_kind: Option<&str>,
symbol_line: Option<u32>,
) -> Vec<(usize, &'a SymbolRecord)> {
let c = match_symbols(file, |s| s.name == name, symbol_kind, symbol_line);
if !c.is_empty() {
return c;
}
let norm_query = normalize_symbol_name(name);
if norm_query != name {
let c = match_symbols(
file,
|s| normalize_symbol_name(&s.name) == norm_query,
symbol_kind,
symbol_line,
);
if !c.is_empty() {
return c;
}
}
let impl_query = format!("impl {norm_query}");
let c = match_symbols(
file,
|s| normalize_symbol_name(&s.name) == impl_query,
symbol_kind,
symbol_line,
);
if !c.is_empty() {
return c;
}
if let Some(bare) = strip_qualification(name) {
let c = match_symbols(file, |s| s.name == bare, symbol_kind, symbol_line);
if !c.is_empty() {
return c;
}
}
if name.starts_with('@') || name.starts_with('.') || name.starts_with('#') {
let c = match_symbols(
file,
|s| is_selector_prefix_match(&s.name, name),
symbol_kind,
symbol_line,
);
if !c.is_empty() {
return c;
}
}
if let Some(type_name) = strip_swift_extension(name) {
let c = match_symbols(file, |s| s.name == type_name, symbol_kind, symbol_line);
if !c.is_empty() {
return c;
}
}
Vec::new()
}
fn match_symbols<'a, F>(
file: &'a IndexedFile,
name_pred: F,
symbol_kind: Option<&str>,
symbol_line: Option<u32>,
) -> Vec<(usize, &'a SymbolRecord)>
where
F: Fn(&SymbolRecord) -> bool,
{
let mut candidates: Vec<(usize, &SymbolRecord)> = file
.symbols
.iter()
.enumerate()
.filter(|(_, s)| {
name_pred(s)
&& symbol_kind
.map(|k| s.kind.to_string().eq_ignore_ascii_case(k))
.unwrap_or(true)
})
.collect();
if let Some(sl) = symbol_line {
candidates.retain(|(_, s)| s.line_range.0 + 1 == sl);
}
candidates
}
fn normalize_symbol_name(s: &str) -> String {
let collapsed: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
collapsed
.replace("< ", "<")
.replace(" >", ">")
.replace(" ,", ",")
.replace(", ", ",")
}
fn strip_qualification(name: &str) -> Option<&str> {
name.rsplit_once("::")
.map(|(_, bare)| bare)
.or_else(|| name.rsplit_once('.').map(|(_, bare)| bare))
}
fn is_selector_prefix_match(stored: &str, query: &str) -> bool {
if !stored.starts_with(query) {
return false;
}
stored.len() == query.len()
|| matches!(
stored.as_bytes()[query.len()],
b',' | b' ' | b'(' | b'{' | b'\t' | b'\n' | b')'
)
}
fn strip_swift_extension(name: &str) -> Option<&str> {
let rest = name.strip_prefix("extension ")?;
Some(rest.split(':').next().unwrap_or(rest).trim())
}
pub(crate) fn render_symbol_selector(
name: &str,
symbol_kind: Option<&str>,
symbol_line: Option<u32>,
) -> String {
match (symbol_kind, symbol_line) {
(Some(symbol_kind), Some(symbol_line)) => {
format!("{symbol_kind} {name} at line {symbol_line}")
}
(Some(symbol_kind), None) => format!("{symbol_kind} {name}"),
(None, Some(symbol_line)) => format!("{name} at line {symbol_line}"),
(None, None) => name.to_string(),
}
}