use super::*;
pub fn header_at(
index: &ProjectIndex,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<HeaderTarget> {
let Some((spelling, name_range)) = crate::sema::resolve::header_name_at(root, offset) else {
return Known::Unknown(UnknownReason::UnparsableName);
};
let Some(summary) = index.summary(path) else {
return Known::Unknown(UnknownReason::UnresolvedInclude(Box::from(
spelling.as_str(),
)));
};
let Some(fact) = summary.includes.iter().find(|include| {
include.range.start_offset <= name_range.start_offset
&& include.range.end_offset() >= name_range.end_offset()
}) else {
return Known::Unknown(UnknownReason::UnparsableName);
};
match fact.guard {
FactGuard::Unconditional => {}
FactGuard::Region(_) => {
return Known::Unknown(UnknownReason::ConditionalCompilation);
}
}
if fact.form == IncludeForm::Macro {
return Known::Unknown(UnknownReason::UnresolvedInclude(Box::from(
fact.spelling.as_str(),
)));
}
match &fact.resolved {
Some(resolved) => Known::Yes(HeaderTarget {
spelling: fact.spelling.clone(),
form: fact.form,
range: fact.range,
resolved: resolved.clone(),
}),
None => Known::Unknown(UnknownReason::UnresolvedInclude(Box::from(
fact.spelling.as_str(),
))),
}
}
pub fn definition_across_files(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<ProjectDefinition> {
let found = definitions_across_files(index, declaring, scopes, root, path, offset);
let written = crate::sema::resolve::qualified_name_at(root, offset)
.map(|(written, _)| written)
.unwrap_or_default();
let found = if !written.contains("::")
&& crate::sema::resolve::member_access_at(root, offset).is_none()
&& let Some(class) = the_class_a_definition_is_written_for(root, offset)
&& index.scope_names_a_class(&class, path)
&& let Known::Yes(list) = members_of(index, scopes, root, path, &class)
&& let Known::Unknown(UnknownReason::NotDeclaredHere(..)) | Known::Yes(_) = &found
{
let named: Vec<ProjectDefinition> = list
.members
.into_iter()
.filter(|member| member.fact.name.as_str() == written.as_str())
.map(|member| ProjectDefinition {
file: member.file,
fact: member.fact,
})
.collect();
if named.is_empty() {
Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(written)))
} else {
Known::Yes(ProjectDefinitions {
found: named,
conditional: 0,
})
}
} else {
found
};
match found {
Known::Yes(mut found) => {
if found
.found
.iter()
.any(|declaration| declaration.fact.kind != DeclKind::Other)
{
found
.found
.retain(|declaration| declaration.fact.kind != DeclKind::Other);
}
if found.found.len() > 1 {
let definitions: Vec<&ProjectDefinition> = found
.found
.iter()
.filter(|declaration| declaration.fact.definition)
.collect();
if let [only] = definitions.as_slice() {
return Known::Yes((*only).clone());
}
if definitions.len() > 1
&& definitions
.iter()
.all(|declaration| declaration.fact.kind == DeclKind::Type)
&& let Some(general) = definitions
.iter()
.max_by_key(|declaration| declaration.fact.parameters().len())
{
return Known::Yes((*general).clone());
}
}
match found.found.len() {
1 => Known::Yes(found.found.remove(0)),
_ => Known::Unknown(UnknownReason::Ambiguous(Box::from(
crate::sema::resolve::qualified_name_at(root, offset)
.map(|(written, _)| written)
.unwrap_or_default(),
))),
}
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::No,
}
}
pub fn member_definitions_across_files(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<ProjectDefinitions> {
let memo = TypeMemo::default();
let Some(access) = crate::sema::resolve::member_access_at(root, offset) else {
return Known::Unknown(UnknownReason::UnparsableName);
};
if access.member.is_empty() {
return Known::Unknown(UnknownReason::UnparsableName);
}
let Known::Yes((object_type, _)) = type_of_expression_memoed(
&memo,
&crate::sema::declarations::ShapeTable::new(),
index,
declaring,
scopes,
root,
path,
&access.object,
0,
) else {
let Known::Unknown(reason) = type_of_expression_memoed(
&memo,
&crate::sema::declarations::ShapeTable::new(),
index,
declaring,
scopes,
root,
path,
&access.object,
0,
) else {
unreachable!("the first match established that this is an `Unknown`")
};
return Known::Unknown(reason);
};
let Some(class) = member_access_class(&object_type) else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(
object_type.to_string(),
)));
};
let members = match members_of(index, scopes, root, path, &class) {
Known::Yes(members) => members,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => {
return Known::Unknown(UnknownReason::UnknownType(Box::from(
object_type.to_string(),
)));
}
};
let found: Vec<ProjectDefinition> = members
.members
.iter()
.filter(|member| member.fact.name == access.member)
.map(|member| ProjectDefinition {
file: member.file.clone(),
fact: member.fact.clone(),
})
.collect();
if found.is_empty() {
return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(format!(
"{class}::{}",
access.member
))));
}
Known::Yes(ProjectDefinitions {
found,
conditional: 0,
})
}
fn the_scope_of_the_answer(
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
offset: usize,
binding: &crate::Binding,
) -> Option<String> {
crate::sema::resolve::qualified_name_at(root, offset)
.and_then(|(written, _)| {
written
.rsplit_once("::")
.map(|(scope, _)| scope.trim_start_matches("::").to_string())
.filter(|scope| !scope.is_empty())
})
.or_else(|| scopes.qualified_name_of(binding.scope))
.filter(|scope| !scope.is_empty())
}
pub fn definitions_across_files(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<ProjectDefinitions> {
let naming_a_member = crate::sema::resolve::member_access_at(root, offset).is_some();
if naming_a_member {
match member_definitions_across_files(index, declaring, scopes, root, path, offset) {
Known::Yes(found) => return Known::Yes(found),
Known::Unknown(_) | Known::No => {}
}
}
match crate::sema::resolve::definitions_at(scopes, root, offset) {
Known::Yes(candidates) if candidates.len() > 1 => {
let chosen = the_overload_a_call_names(
index,
declaring,
scopes,
root,
path,
offset,
&candidates,
)
.unwrap_or_else(|| candidates[0].clone());
let scope = the_scope_of_the_answer(scopes, root, offset, &chosen);
let local = scopes.declares_a_local(chosen.scope);
return Known::Yes(ProjectDefinitions::one(ProjectDefinition::from_binding(
path, chosen, scope, local,
)));
}
Known::Yes(mut candidates) => {
let binding = candidates.remove(0);
let scope = the_scope_of_the_answer(scopes, root, offset, &binding);
let local = scopes.declares_a_local(binding.scope);
return Known::Yes(ProjectDefinitions::one(ProjectDefinition::from_binding(
path, binding, scope, local,
)));
}
Known::Unknown(UnknownReason::NotDeclaredHere(name)) => {
if let Some((qualifier, last)) = name.rsplit_once("::")
&& !qualifier.is_empty()
&& !last.is_empty()
&& index.scope_names_a_class(qualifier, path)
&& let Known::Yes(list) = members_of(index, scopes, root, path, qualifier)
{
let inherited: Vec<ProjectDefinition> = list
.members
.into_iter()
.filter(|member| member.fact.name == last)
.map(|member| ProjectDefinition {
file: member.file,
fact: member.fact,
})
.collect();
if !inherited.is_empty() {
return Known::Yes(ProjectDefinitions {
found: inherited,
conditional: 0,
});
}
}
if !(naming_a_member || inside_a_definition_written_with_a_qualifier(root, offset))
&& name.contains("::")
&& let Known::Yes(found) = index.definition(&name, path)
{
return Known::Yes(ProjectDefinitions::one(found));
}
return if naming_a_member || inside_a_definition_written_with_a_qualifier(root, offset)
{
index.definitions(&name, path)
} else {
index.definitions_in_scope(&name, path)
};
}
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => {}
}
Known::Unknown(UnknownReason::UnparsableName)
}
pub(crate) fn the_concept_parameters(
root: &cpp_parser::CppSyntaxNode,
name: &str,
) -> Option<String> {
for declaration in root.descendants() {
if cpp_parser::CppSyntaxKind::from(declaration.kind())
!= cpp_parser::CppSyntaxKind::ConceptDecl
{
continue;
}
let text = declaration.text().to_string();
let Some(at) = text.find('=') else {
continue;
};
let declared = text[..at].split_whitespace().last().unwrap_or_default();
if declared != name {
continue;
}
let with_the_parameters = declaration
.parent()
.map(|parent| parent.text().to_string())
.unwrap_or(text);
return template_parameters_in(&with_the_parameters)
.into_iter()
.next();
}
None
}
pub(crate) fn the_concept_definition(
root: &cpp_parser::CppSyntaxNode,
name: &str,
) -> Option<String> {
for declaration in root.descendants() {
if cpp_parser::CppSyntaxKind::from(declaration.kind())
!= cpp_parser::CppSyntaxKind::ConceptDecl
{
continue;
}
let text = declaration.text().to_string();
let Some(at) = text.find('=') else {
continue;
};
let declared = text[..at].split_whitespace().last().unwrap_or_default();
if declared != name {
continue;
}
let body = text[at + 1..].trim().trim_end_matches(';').trim();
if !body.is_empty() {
return Some(body.to_string());
}
}
None
}
pub(crate) fn the_overload_a_call_names(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
candidates: &[crate::Binding],
) -> Option<crate::Binding> {
let name = crate::sema::resolve::expression_at(root, offset)?;
let call = name.ancestors().find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::CallExpr
})?;
let arguments: Vec<cpp_parser::CppSyntaxNode> = match call.children().find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::ArgumentList
}) {
Some(list) => list.children().collect(),
None => call.children().skip(1).collect(),
};
let argument_types: Vec<Option<String>> = arguments
.iter()
.map(|argument| {
match type_of_expression(index, declaring, scopes, root, path, argument, 0) {
Known::Yes((found, _)) => Some(found.to_string()),
_ => None,
}
})
.collect();
if argument_types.is_empty() {
return None;
}
let mut survivors = Vec::new();
for candidate in candidates {
let Some(the_candidate) =
node_covering(root, candidate.name_range.start_offset, candidate.range)
else {
survivors.push(candidate.clone());
continue;
};
let declaration_node = the_candidate
.ancestors()
.find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind())
== cpp_parser::CppSyntaxKind::Declaration
})
.unwrap_or_else(|| the_candidate.clone());
let declaration = declaration_node.text().to_string();
let requires_clause = declaration_node
.descendants()
.find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind())
== cpp_parser::CppSyntaxKind::RequiresClause
})
.map(|node| node.text().to_string())
.and_then(|text| crate::sema::constraint::a_requires_clause(&text).map(str::to_string));
let condition_owned = requires_clause.as_deref().map(str::to_string).or_else(|| {
crate::sema::constraint::the_condition_of(&declaration).map(str::to_string)
});
let condition_owned = condition_owned.or_else(|| {
let name = crate::sema::constraint::a_concept_name(&declaration)?;
the_concept_definition(root, &name)
});
let Some(condition) = condition_owned.as_deref() else {
survivors.push(candidate.clone());
continue;
};
let parameters = template_parameters_in(&declaration);
let bound: Vec<(String, String)> = parameters
.into_iter()
.zip(argument_types.iter())
.filter_map(|(parameter, found)| Some((parameter, found.clone()?)))
.collect();
let verdict = crate::sema::constraint::satisfies_with(condition, &bound, &mut |name| {
the_concept_definition(root, name).and_then(|body| {
the_concept_parameters(root, name).map(|parameter| (parameter, body))
})
});
match verdict {
Some(false) => {}
_ => survivors.push(candidate.clone()),
}
}
(survivors.len() == 1).then(|| survivors.remove(0))
}
pub(crate) fn template_parameters_in(declaration: &str) -> Vec<String> {
let Some(at) = declaration.find("template") else {
return Vec::new();
};
let after = &declaration[at + "template".len()..];
let Some(open) = after.find('<') else {
return Vec::new();
};
let mut depth = 0isize;
let mut close = None;
for (index, character) in after[open..].char_indices() {
match character {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
close = Some(open + index);
break;
}
}
_ => {}
}
}
let Some(close) = close else {
return Vec::new();
};
after[open + 1..close]
.split(',')
.filter_map(|parameter| {
parameter
.split_whitespace()
.last()
.map(|word| word.trim_end_matches("...").trim().to_string())
.filter(|word| !word.is_empty())
})
.collect()
}
pub(crate) fn the_class_a_definition_is_written_for(
root: &cpp_parser::CppSyntaxNode,
offset: usize,
) -> Option<String> {
let mut node = cpp_parser::token_at(root, offset).and_then(|token| token.parent());
while let Some(current) = node {
let is_a_definition = cpp_parser::CppSyntaxKind::from(current.kind())
== cpp_parser::CppSyntaxKind::Declaration
&& current.children().any(|child| {
cpp_parser::CppSyntaxKind::from(child.kind())
== cpp_parser::CppSyntaxKind::CompoundStat
});
if is_a_definition {
let text = current.text().to_string();
let before_the_parameters = text.split('(').next().unwrap_or_default();
let name = before_the_parameters
.split_whitespace()
.next_back()
.unwrap_or_default();
if let Some((qualifier, _)) = name.rsplit_once("::")
&& !qualifier.is_empty()
{
return Some(qualifier.to_string());
}
}
node = current.parent();
}
None
}
pub(crate) fn inside_a_definition_written_with_a_qualifier(
root: &cpp_parser::CppSyntaxNode,
offset: usize,
) -> bool {
the_class_a_definition_is_written_for(root, offset).is_some()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectMacro {
pub file: PathBuf,
pub fact: MacroFact,
}
pub fn macro_across_files(
index: &ProjectIndex,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<ProjectMacro> {
match crate::sema::resolve::name_at(root, offset) {
Some((name, _)) => index.macro_definition(&name, path, offset),
None => Known::Unknown(UnknownReason::UnparsableName),
}
}