use std::collections::HashMap;
use std::path::{Path, PathBuf};
use cpp_parser::{CppSyntaxKind, CppSyntaxNode, SourceRange};
use crate::index::project::{Callee, callee_of_a_call};
use crate::sema::scopes::parameters_of;
use crate::{FileView, Known, ProjectIndex};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParameterHint {
pub offset: usize,
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeHint {
pub offset: usize,
pub label: String,
pub kind: TypeHintKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeHintKind {
Auto,
StructuredBinding,
DeducedReturn,
}
pub fn type_hints<F, G>(
view: &FileView,
range: SourceRange,
mut type_at: F,
mut returns_at: G,
) -> Vec<TypeHint>
where
F: FnMut(usize) -> Option<String>,
G: FnMut(usize) -> Option<String>,
{
let mut hints: Vec<TypeHint> = Vec::new();
for node in view.root.descendants() {
let kind = CppSyntaxKind::from(node.kind());
match kind {
CppSyntaxKind::InitDeclarator => {
if node.descendants().any(|child| {
CppSyntaxKind::from(child.kind()) == CppSyntaxKind::StructuredBinding
}) {
continue;
}
if !contains(range, node.text_range().start().into())
|| !writes_auto_in_the_declaration(&node)
{
continue;
}
let Some(name) = the_name_of_a_declarator(&node) else {
continue;
};
let at = usize::from(name.text_range().end());
if !contains(range, at) {
continue;
}
if let Some(label) = type_at(usize::from(name.text_range().start()))
&& is_a_type_spelling(&label)
{
hints.push(TypeHint {
offset: at,
label,
kind: TypeHintKind::Auto,
});
}
}
CppSyntaxKind::StructuredBinding => {
if !contains(range, node.text_range().start().into()) {
continue;
}
for name in node.children() {
if CppSyntaxKind::from(name.kind()) != CppSyntaxKind::NameExpr {
continue;
}
let at = usize::from(name.text_range().end());
if !contains(range, at) {
continue;
}
if let Some(label) = type_at(usize::from(name.text_range().start()))
&& is_a_type_spelling(&label)
{
hints.push(TypeHint {
offset: at,
label,
kind: TypeHintKind::StructuredBinding,
});
}
}
}
CppSyntaxKind::LambdaExpr => {
if !contains(range, node.text_range().start().into()) {
continue;
}
let Some(body) = node
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::CompoundStat)
else {
continue;
};
let written = node.text().to_string();
let before_the_body = written
.find(&body.text().to_string())
.map(|at| &written[..at])
.unwrap_or("");
if before_the_body.contains("->") {
continue;
}
let at = usize::from(body.text_range().start());
if !contains(range, at) {
continue;
}
if let Some(label) = crate::sema::declarations::a_lambdas_return_type(&node, &[])
&& is_a_type_spelling(&label)
{
hints.push(TypeHint {
offset: at,
label,
kind: TypeHintKind::DeducedReturn,
});
}
}
CppSyntaxKind::Declaration | CppSyntaxKind::FunctionDef => {
if !contains(range, node.text_range().start().into()) {
continue;
}
let Some(declarator) = node.children().find(|child| {
matches!(
CppSyntaxKind::from(child.kind()),
CppSyntaxKind::Declarator | CppSyntaxKind::InitDeclarator
)
}) else {
continue;
};
let Some(list) = declarator.descendants().find(|child| {
CppSyntaxKind::from(child.kind()) == CppSyntaxKind::ParameterList
}) else {
continue;
};
if !writes_auto_in_the_declaration(&node) {
continue;
}
let at = usize::from(list.text_range().end());
if !contains(range, at) {
continue;
}
let Some(name) = the_name_of_a_declarator(&node) else {
continue;
};
if let Some(label) = returns_at(usize::from(name.text_range().start()))
&& is_a_type_spelling(&label)
{
hints.push(TypeHint {
offset: at,
label,
kind: TypeHintKind::DeducedReturn,
});
}
}
_ => {}
}
}
hints
}
fn writes_auto_in_the_declaration(node: &CppSyntaxNode) -> bool {
let own = node
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::DeclSpecifierSeq);
let enclosing = node.ancestors().take(4).find_map(|ancestor| {
ancestor
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::DeclSpecifierSeq)
});
own.or(enclosing).into_iter().any(|specifiers| {
specifiers.descendants().any(|child| {
let kind = CppSyntaxKind::from(child.kind());
kind == CppSyntaxKind::AutoType
|| (kind == CppSyntaxKind::BuiltinType && child.text().to_string().trim() == "auto")
})
})
}
fn the_name_of_a_declarator(node: &CppSyntaxNode) -> Option<CppSyntaxNode> {
let name = node
.descendants()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::NameExpr)?;
if name.text().to_string().trim().is_empty() {
return None;
}
Some(name)
}
fn is_a_type_spelling(label: &str) -> bool {
let label = label.trim();
!label.is_empty() && label != "auto" && !label.contains("auto")
}
pub fn parameter_hints<F>(
index: &ProjectIndex,
view: &FileView,
range: SourceRange,
mut view_of: F,
) -> Vec<ParameterHint>
where
F: FnMut(&Path) -> Option<FileView>,
{
let mut hints = Vec::new();
let mut declaring: HashMap<PathBuf, FileView> = HashMap::new();
for call in call_expressions(&view.root, range) {
let Some(arguments) = arguments_of(&call) else {
continue;
};
let asked_about = arguments
.iter()
.any(|argument| contains(range, argument.text_range().start().into()));
if !asked_about {
continue;
}
let trace = crate::probes::inlay();
let started = std::time::Instant::now();
let Known::Yes(callee) = callee_of_a_call(
index,
&mut |_: &Path| None,
&view.scopes,
&view.root,
&view.path,
&call,
) else {
continue;
};
let resolved = started.elapsed();
let names =
parameter_names_for(view, &callee, &mut declaring, &mut view_of).or_else(|| {
callee
.parameters
.as_deref()
.and_then(parameter_names_from_text)
});
if trace {
eprintln!(
"[inlay] {} -> {:?}: callee {:?}, names {:?}, {} name(s)",
call.text()
.to_string()
.lines()
.next()
.unwrap_or_default()
.chars()
.take(40)
.collect::<String>(),
callee.file.display(),
resolved,
started.elapsed() - resolved,
names.as_ref().map(Vec::len).unwrap_or(0)
);
}
let Some(names) = names else {
continue;
};
for (argument, name) in arguments.iter().zip(names.iter()) {
let Some(name) = name else {
continue;
};
if !contains(range, argument.text_range().start().into()) {
continue;
}
if argument.text().to_string().trim() == name {
continue;
}
hints.push(ParameterHint {
offset: argument.text_range().start().into(),
name: name.clone(),
});
}
}
hints
}
fn parameter_names_for<F>(
view: &FileView,
callee: &Callee,
declaring: &mut HashMap<PathBuf, FileView>,
view_of: &mut F,
) -> Option<Vec<Option<String>>>
where
F: FnMut(&Path) -> Option<FileView>,
{
let declared_in = if callee.file == view.path {
view
} else {
if !declaring.contains_key(&callee.file) {
declaring.insert(callee.file.clone(), view_of(&callee.file)?);
}
declaring.get(&callee.file).expect("just inserted")
};
let list = parameter_list_of(declared_in, callee.name_offset)?;
let names: Vec<Option<String>> = parameters_of(&list)
.into_iter()
.map(|(_, declared)| declared.map(|(name, _)| name.text()))
.collect();
(!names.is_empty()).then_some(names)
}
pub(crate) fn parameter_names_from_text(parameter_list: &str) -> Option<Vec<Option<String>>> {
let text = format!("void __hint{parameter_list};");
let tree = cpp_parser::CppParser::parse(&text, cpp_parser::ParserConfig::default());
let root = tree.get_red_root();
let declarator = root
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Declarator)?;
let list = cpp_parser::first_child_of_kind(&declarator, &[CppSyntaxKind::ParameterList])?;
let names: Vec<Option<String>> = parameters_of(&list)
.into_iter()
.map(|(_, declared)| declared.map(|(name, _)| name.text()))
.collect();
(!names.is_empty()).then_some(names)
}
pub(crate) fn parameter_list_of(view: &FileView, offset: usize) -> Option<CppSyntaxNode> {
let token = cpp_parser::token_at(&view.root, offset)?;
let declarator = token
.parent_ancestors()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Declarator)?;
cpp_parser::first_child_of_kind(&declarator, &[CppSyntaxKind::ParameterList])
}
pub(crate) fn parameter_list_text(declarator: &CppSyntaxNode) -> Option<String> {
let list = cpp_parser::first_child_of_kind(declarator, &[CppSyntaxKind::ParameterList])?;
Some(tidy_list_text(&list.text().to_string()).0)
}
pub(crate) fn tidy_list_text(text: &str) -> (String, Vec<usize>) {
let bytes = text.as_bytes();
let mut out = String::with_capacity(text.len());
let mut map = vec![0usize; text.len() + 1];
let mut wrote_a_word = false;
let mut at = 0usize;
while at < bytes.len() {
if bytes[at].is_ascii_whitespace() {
map[at] = out.len();
at += 1;
continue;
}
let mut end = at;
while end < bytes.len() && !bytes[end].is_ascii_whitespace() {
end += 1;
}
let word = &text[at..end];
if wrote_a_word {
let after_an_open = out.ends_with('(') || out.ends_with('[');
let before_a_close =
word.starts_with(')') || word.starts_with(']') || word.starts_with(',');
if !after_an_open && !before_a_close {
out.push(' ');
}
}
for (offset, slot) in map[at..end].iter_mut().enumerate() {
*slot = out.len() + offset;
}
out.push_str(word);
wrote_a_word = true;
at = end;
}
map[text.len()] = out.len();
(out, map)
}
pub(crate) fn arguments_of(call: &CppSyntaxNode) -> Option<Vec<CppSyntaxNode>> {
let mut children = call.children();
children.next()?;
let arguments: Vec<CppSyntaxNode> = children.collect();
let unread = arguments
.iter()
.any(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::ArgumentList);
(!arguments.is_empty() && !unread).then_some(arguments)
}
fn call_expressions(root: &CppSyntaxNode, range: SourceRange) -> Vec<CppSyntaxNode> {
root.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::CallExpr)
.filter(|node| contains(range, node.text_range().start().into()))
.collect()
}
fn contains(range: SourceRange, offset: usize) -> bool {
offset >= range.start_offset && offset <= range.end_offset()
}