use std::ops::Range;
use std::path::{Path, PathBuf};
use cpp_parser::{CppDocComment, CppSyntaxElement, CppSyntaxKind, CppSyntaxNode, CppTokenKind};
use crate::index::project::{Callee, callees_of_a_call};
use crate::sema::call_syntax::{arguments_of, parameter_list_of};
use crate::sema::scopes::parameters_of;
use crate::{FileView, Known, ProjectIndex};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallSignature {
pub label: String,
pub parameters: Vec<(Range<usize>, String)>,
pub active_parameter: Option<usize>,
pub declared_in: PathBuf,
pub declared_at: usize,
pub documentation: Option<CppDocComment>,
}
pub fn signatures_at<F>(
index: &ProjectIndex,
view: &FileView,
offset: usize,
mut view_of: F,
) -> Vec<CallSignature>
where
F: FnMut(&Path) -> Option<FileView>,
{
if let Some(signature) = a_macro_signature(index, view, offset, &mut view_of) {
return vec![signature];
}
if let Some((class, list)) = directly_initialized_at(&view.root, offset) {
let active = active_parameter(&list, offset);
let constructors = constructors_in_the_index(index, &view.path, &class, active);
if !constructors.is_empty() {
return constructors;
}
}
let Some(call) = call_around(&view.root, offset) else {
return Vec::new();
};
let Some(callee) = call.children().next() else {
return Vec::new();
};
let Known::Yes(candidates) = callees_of_a_call(
index,
&mut view_of,
&view.scopes,
&view.root,
&view.path,
&call,
) else {
return Vec::new();
};
let callee_text = callee.text().to_string();
let callee_text = callee_text.trim();
let member = callee_text
.rfind("->")
.map(|at| at + "->".len())
.into_iter()
.chain(callee_text.rfind('.').map(|at| at + 1))
.max();
let spelling = member.map_or(callee_text, |at| &callee_text[at..]);
let active = active_parameter(&call, offset);
let mut parsed: std::collections::HashMap<PathBuf, Option<FileView>> =
std::collections::HashMap::new();
let mut signatures = Vec::new();
let mut rankable: Vec<(Vec<String>, Vec<String>)> = Vec::new();
for candidate in candidates {
let declared_in: &FileView = if candidate.file == view.path {
view
} else {
let held = parsed
.entry(candidate.file.clone())
.or_insert_with(|| view_of(&candidate.file));
let Some(held) = held.as_ref() else {
if let Some(parameters) = &candidate.parameters {
let (tidy, _) = crate::sema::call_syntax::tidy_list_text(parameters);
signatures.push(CallSignature {
label: format!("{spelling}{tidy}"),
parameters: Vec::new(),
active_parameter: active,
declared_in: candidate.file.clone(),
declared_at: candidate.name_offset,
documentation: None,
});
rankable.push((Vec::new(), Vec::new()));
} else {
let from_the_index =
constructors_in_the_index(index, &view.path, spelling, active);
if !from_the_index.is_empty() {
signatures.extend(from_the_index);
rankable.push((Vec::new(), Vec::new()));
}
}
continue;
};
held
};
let sources: Vec<Callee> = match parameter_list_of(declared_in, candidate.name_offset) {
Some(_) => vec![candidate.clone()],
None => constructors_of(declared_in, candidate.name_offset),
};
if sources.is_empty() && candidate.parameters.is_none() {
let from_the_index = constructors_in_the_index(index, &view.path, spelling, active);
if !from_the_index.is_empty() {
signatures.extend(from_the_index);
rankable.push((Vec::new(), Vec::new()));
continue;
}
}
if sources.is_empty()
&& let Some(parameters) = &candidate.parameters
{
let (tidy, _) = crate::sema::call_syntax::tidy_list_text(parameters);
signatures.push(CallSignature {
label: format!("{spelling}{tidy}"),
parameters: Vec::new(),
active_parameter: active,
declared_in: candidate.file.clone(),
declared_at: candidate.name_offset,
documentation: None,
});
rankable.push((Vec::new(), Vec::new()));
continue;
}
for source in sources {
let Some(list) = parameter_list_of(declared_in, source.name_offset) else {
continue;
};
let list_text = list.text().to_string();
let list_text = list_text.trim_end();
let list_begin = usize::from(list.text_range().start());
let raw: Vec<(Range<usize>, String)> = parameters_of(&list)
.into_iter()
.map(|(parameter, _)| {
let text = parameter.text().to_string();
let text = text.trim_end();
let start = usize::from(parameter.text_range().start()) - list_begin;
(start..start + text.len(), text.to_string())
})
.collect();
let (tidy, moved) = crate::sema::call_syntax::tidy_list_text(list_text);
let list_start = spelling.len();
let label = format!("{spelling}{tidy}");
let parameters: Vec<(Range<usize>, String)> = raw
.into_iter()
.map(|(range, text)| {
(
list_start + moved[range.start]..list_start + moved[range.end],
text,
)
})
.collect();
let plain: Vec<String> = parameters
.iter()
.map(|(_, text)| crate::sema::overload::a_type_without_its_name(text))
.collect();
let templates = crate::sema::deduction::template_parameters_before(
&declared_in.source,
source.name_offset,
);
signatures.push(CallSignature {
label,
parameters,
active_parameter: active,
declared_in: source.file.clone(),
declared_at: source.name_offset,
documentation: None,
});
rankable.push((plain, templates));
}
}
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
signatures.retain(|signature| seen.insert(signature.label.clone()));
if signatures.len() > 1 {
let model = crate::sema::model::SemanticModel::new(
index,
&view.root,
&view.scopes,
&view.source,
&view.path,
Box::new(|wanted: &Path| view_of(wanted)),
);
let arguments = arguments_of(&call).unwrap_or_default();
let types: Vec<crate::Known<String>> = arguments
.iter()
.map(|argument| match model.type_of(argument) {
crate::Known::Yes((a_type, _)) => crate::Known::Yes(a_type.to_string()),
crate::Known::No => crate::Known::No,
crate::Known::Unknown(reason) => crate::Known::Unknown(reason),
})
.collect();
let ranked: Vec<crate::sema::overload::Candidate> = signatures
.iter()
.enumerate()
.map(|(at, signature)| {
let (plain, templates) = rankable.get(at).cloned().unwrap_or_default();
let plain_for_ordering = plain.clone();
let parameters = match crate::sema::deduction::deduce(&templates, &plain, &types) {
Some(arguments) => plain
.iter()
.map(|spelling| {
crate::sema::types::substituted_spelling(
spelling, &templates, &arguments,
)
})
.collect(),
None => plain,
};
let candidate = crate::sema::overload::Candidate::new(
parameters,
signature.label.trim_end().ends_with("...)"),
signature.label.clone(),
);
candidate.with_declaration(plain_for_ordering, templates.clone())
})
.collect();
if let crate::sema::overload::Choice::One(chosen) =
crate::sema::overload::choose(&types, &ranked)
{
let chosen = signatures.remove(chosen);
signatures.insert(0, chosen);
}
}
signatures
}
fn constructors_of(declared_in: &FileView, name_offset: usize) -> Vec<Callee> {
use cpp_parser::{CppAstNode, CppAstToken, CppClassDef, CppDeclaration, CppTokenKind};
let Some(class) = declared_in
.root
.descendants()
.filter_map(CppClassDef::cast)
.find(|class| {
class
.get_name()
.is_some_and(|name| usize::from(name.syntax().text_range().start()) == name_offset)
})
else {
return Vec::new();
};
let class_name = class.get_name_text().unwrap_or_default().trim().to_string();
if class_name.is_empty() {
return Vec::new();
}
let mut constructors = Vec::new();
for declaration in class.descendants::<CppDeclaration>() {
let Some(name) = declaration
.syntax()
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.find(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Identifier)
else {
continue;
};
if name.text() != class_name {
continue;
}
constructors.push(Callee {
file: declared_in.path.clone(),
name_offset: usize::from(name.text_range().start()),
parameters: None,
});
}
constructors
}
pub(crate) fn a_macro_signature<F>(
index: &ProjectIndex,
view: &FileView,
in_the_file: usize,
view_of: &mut F,
) -> Option<CallSignature>
where
F: FnMut(&Path) -> Option<FileView>,
{
let text = view.written_text().unwrap_or(&view.source);
let before = text.get(..in_the_file)?;
let mut depth = 0i32;
let mut open = None;
for (at, character) in before.char_indices().rev() {
match character {
')' | ']' | '}' => depth += 1,
'(' | '[' | '{' => {
if depth == 0 {
if character == '(' {
open = Some(at);
}
break;
}
depth -= 1;
}
_ => {}
}
}
let open = open?;
let head = before.get(..open)?;
let end = head.trim_end().len();
let start = head[..end]
.rfind(|character: char| !(character.is_alphanumeric() || character == '_'))
.map(|at| at + 1)
.unwrap_or(0);
let name = &head[start..end];
if name.is_empty()
|| !name
.chars()
.all(|character| character.is_alphanumeric() || character == '_')
{
return None;
}
let Known::Yes(found) = index.macro_definition(name, &view.path, in_the_file) else {
return None;
};
if !found.fact.function_like {
return None;
}
let declared_in_the_text: String = if found.file == view.path {
text.to_string()
} else {
let other = view_of(&found.file)?;
other
.written_text()
.map(str::to_string)
.unwrap_or_else(|| other.source.to_string())
};
let tail = declared_in_the_text.get(found.fact.range.start_offset..)?;
let name_end = name.len().min(tail.len());
let list_open = tail[name_end..].find('(')? + name_end;
let list_close = matching_paren(tail, list_open)?;
let inside = &tail[list_open + 1..list_close];
let mut parameters: Vec<(Range<usize>, String)> = Vec::new();
let mut depth = 0i32;
let mut start = 0usize;
let mut push = |start: usize, end: usize| {
let text = &inside[start..end];
let trimmed = text.trim();
if trimmed.is_empty() {
return;
}
let leading = text.len() - text.trim_start().len();
let from = name.len() + 1 + start + leading;
parameters.push((from..from + trimmed.len(), trimmed.to_string()));
};
for (at, character) in inside.char_indices() {
match character {
'<' | '(' | '[' => depth += 1,
'>' | ')' | ']' => depth -= 1,
',' if depth == 0 => {
push(start, at);
start = at + 1;
}
_ => {}
}
}
push(start, inside.len());
let mut active = 0usize;
let mut depth = 0i32;
for character in text.get(open + 1..in_the_file)?.chars() {
match character {
'<' | '(' | '[' => depth += 1,
'>' | ')' | ']' => depth -= 1,
',' if depth == 0 => active += 1,
_ => {}
}
}
Some(CallSignature {
label: format!("{name}({inside})"),
parameters,
active_parameter: Some(active),
declared_in: found.file,
declared_at: found.fact.range.start_offset,
documentation: None,
})
}
fn matching_paren(text: &str, open: usize) -> Option<usize> {
let mut depth = 0usize;
for (at, character) in text[open..].char_indices() {
match character {
'(' => depth += 1,
')' => {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(open + at);
}
}
_ => {}
}
}
None
}
fn call_around(root: &CppSyntaxNode, offset: usize) -> Option<CppSyntaxNode> {
let mut found = None;
let mut node = root.clone();
loop {
if !node_contains(&node, offset) {
return found;
}
if CppSyntaxKind::from(node.kind()) == CppSyntaxKind::CallExpr {
let arguments_begin = node
.children()
.next()
.map(|callee| usize::from(callee.text_range().end()));
if arguments_begin.is_some_and(|start| offset >= start) {
found = Some(node.clone());
}
}
match node
.children_with_tokens()
.find(|element| element_contains(element, offset))
.and_then(|element| element.into_node())
{
Some(child) => node = child,
None => return found,
}
}
}
fn active_parameter(call: &CppSyntaxNode, offset: usize) -> Option<usize> {
let callee_range = call.children().next().map(|callee| {
(
usize::from(callee.text_range().start()),
usize::from(callee.text_range().end()),
)
});
let mut commas = 0usize;
fn scan(
node: &CppSyntaxNode,
callee_range: Option<(usize, usize)>,
offset: usize,
commas: &mut usize,
) {
for element in node.children_with_tokens() {
if let Some(token) = element.as_token() {
let start = usize::from(element.text_range().start());
if CppTokenKind::from(token.kind()) == CppTokenKind::Comma && start < offset {
*commas += 1;
}
continue;
}
let Some(child) = element.into_node() else {
continue;
};
let range = (
usize::from(child.text_range().start()),
usize::from(child.text_range().end()),
);
if Some(range) == callee_range {
continue;
}
if CppSyntaxKind::from(child.kind()) == CppSyntaxKind::ArgumentList {
scan(&child, None, offset, commas);
}
}
}
scan(call, callee_range, offset, &mut commas);
Some(commas)
}
fn node_contains(node: &CppSyntaxNode, offset: usize) -> bool {
within(
node.text_range().start().into(),
node.text_range().end().into(),
offset,
)
}
fn element_contains(element: &CppSyntaxElement, offset: usize) -> bool {
within(
element.text_range().start().into(),
element.text_range().end().into(),
offset,
)
}
fn within(start: usize, end: usize, offset: usize) -> bool {
offset >= start && offset <= end
}
fn constructors_in_the_index(
index: &ProjectIndex,
path: &Path,
spelling: &str,
active: Option<usize>,
) -> Vec<CallSignature> {
let class = spelling.trim();
let class = class.rsplit("::").next().unwrap_or(class).trim();
if class.is_empty() {
return Vec::new();
}
let Known::Yes(found) = index.definitions(class, path) else {
return Vec::new();
};
let mut constructors = Vec::new();
for declaration in &found.found {
if declaration.fact.name != class {
continue;
}
if declaration.fact.kind != crate::DeclKind::Function {
continue;
}
let Some(scope) = declaration.fact.scope.as_deref() else {
continue;
};
if scope.rsplit("::").next().map(str::trim) != Some(class) {
continue;
}
let Some(parameters) = declaration.fact.parameter_list() else {
continue;
};
let (tidy, _) = crate::sema::call_syntax::tidy_list_text(parameters);
constructors.push(CallSignature {
label: format!("{class}{tidy}"),
parameters: Vec::new(),
active_parameter: active,
declared_in: declaration.file.clone(),
declared_at: declaration.fact.name_range.start_offset,
documentation: None,
});
}
constructors
}
fn directly_initialized_at(root: &CppSyntaxNode, offset: usize) -> Option<(String, CppSyntaxNode)> {
let mut node = root.clone();
loop {
let mut child = None;
for candidate in node.children() {
let range = candidate.text_range();
let start = usize::from(range.start());
let end = usize::from(range.end());
if offset >= start && offset < end {
child = Some(candidate);
break;
}
}
let child = child?;
if CppSyntaxKind::from(child.kind()) == CppSyntaxKind::ParameterList {
let declarator = child.parent()?;
if CppSyntaxKind::from(declarator.kind()) != CppSyntaxKind::Declarator {
return None;
}
let initializer = declarator.parent()?;
let declaration = initializer.parent()?;
if CppSyntaxKind::from(declaration.kind()) != CppSyntaxKind::Declaration {
return None;
}
if declaration.children().any(|sibling| {
matches!(
CppSyntaxKind::from(sibling.kind()),
CppSyntaxKind::CompoundStat
)
}) {
return None;
}
let specifiers = declaration.children().find(|sibling| {
CppSyntaxKind::from(sibling.kind()) == CppSyntaxKind::DeclSpecifierSeq
})?;
let class = specifiers
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| {
cpp_parser::CppTokenKind::from(token.kind())
== cpp_parser::CppTokenKind::Identifier
})
.last()
.map(|token| token.text().to_string())?;
return Some((class, child));
}
node = child;
}
}