use super::*;
pub(crate) fn member_fact(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
member: &str,
arguments: Option<&[String]>,
) -> Known<(DeclFact, PathBuf)> {
let started = std::time::Instant::now();
let answer = member_fact_inner(shapes, index, scopes, root, path, class, member, arguments);
if crate::probes::timing() && started.elapsed().as_millis() > 10 {
eprintln!(
"[member_fact] {:>5} ms {class}::{member}",
started.elapsed().as_millis()
);
}
answer
}
pub(crate) fn member_fact_inner(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
member: &str,
arguments: Option<&[String]>,
) -> Known<(DeclFact, PathBuf)> {
let class = a_type_spelling_with_its_arguments(class).to_string();
let class = &resolve_aliases(shapes, index, scopes, root, path, &class);
let from_the_spelling: Option<Vec<String>> = class.split_once('<').map(|(_, rest)| {
crate::sema::builtins::split_arguments(rest.trim_end().strip_suffix('>').unwrap_or(rest))
});
let arguments = arguments.or(from_the_spelling.as_deref());
if let Some(found) = direct_member(shapes, index, scopes, root, path, class, member, arguments)
{
return Known::Yes(found);
}
if !class.contains("::") {
let bare = without_arguments(class);
if let Some(declared_in) = qualified_from_the_index(index, path, bare)
&& let Some(found) = direct_member(
shapes,
index,
scopes,
root,
path,
&declared_in,
member,
arguments,
)
{
return Known::Yes(found);
}
}
let parameters = class_template_parameters(shapes, index, scopes, root, path, class);
let mut level: Vec<(String, String)> = bases_of(index, scopes, root, path, class)
.value()
.unwrap_or_default()
.into_iter()
.filter(|base| !names_a_template_parameter(base, ¶meters))
.map(|base| (base, class.to_string()))
.collect();
let mut visited: Vec<String> = vec![class.to_string()];
while !level.is_empty() {
let mut found: Vec<(DeclFact, PathBuf)> = Vec::new();
let mut next: Vec<(String, String)> = Vec::new();
for (written, owner) in level {
let base = resolved_in_the_enclosing_scopes(index, scopes, path, &owner, &written);
if visited.contains(&base) {
continue;
}
visited.push(base.clone());
if let Some(member_found) =
direct_member(shapes, index, scopes, root, path, &base, member, arguments)
{
found.push(member_found);
}
next.extend(
bases_of(index, scopes, root, path, &base)
.value()
.unwrap_or_default()
.into_iter()
.filter(|base_of_base| !names_a_template_parameter(base_of_base, ¶meters))
.map(|base_of_base| (base_of_base, base.clone())),
);
}
match found.len() {
0 => level = next,
1 => return Known::Yes(found.remove(0)),
_ => return Known::Unknown(UnknownReason::Ambiguous(Box::from(member))),
}
}
if let Some(found) =
through_an_operator_arrow(index, scopes, root, path, class, member, arguments)
{
return Known::Yes(found);
}
Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(format!(
"{class}::{member}"
))))
}
pub(crate) fn without_arguments(class: &str) -> &str {
let trimmed = class.trim();
if !trimmed.ends_with('>') {
return trimmed;
}
let mut depth = 0usize;
for (at, character) in trimmed.char_indices().rev() {
match character {
'>' => depth += 1,
'<' => {
depth -= 1;
if depth == 0 {
let name = trimmed[..at].trim();
return if name.is_empty() { trimmed } else { name };
}
}
_ => {}
}
}
trimmed
}
pub(crate) fn member_bindings(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
arguments: &[Type],
) -> crate::sema::types::TypeBindings {
if arguments.is_empty() {
return crate::sema::types::TypeBindings::default();
}
let names = class_template_parameters(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
class,
);
crate::sema::types::TypeBindings::new(names, arguments.to_vec())
}
pub(crate) fn deduced_class_template_arguments(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
class: &str,
initializer: &crate::sema::types::Type,
) -> Option<String> {
let parameters = class_template_parameters(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
class,
);
let [only] = parameters.as_slice() else {
return None;
};
let simple = class.rsplit("::").next().unwrap_or(class);
if let Some(deduced) = the_deduction_guide_deduces(root, class, simple, only, initializer) {
return Some(deduced);
}
if the_constructor_takes(root, class, simple, only) {
return Some(format!("{class}<{initializer}>"));
}
for declared in index.files_declaring(simple, path) {
if declared.file == path {
continue;
}
let Some(view) = declaring(&declared.file) else {
continue;
};
if let Some(deduced) =
the_deduction_guide_deduces(&view.root, class, simple, only, initializer)
{
return Some(deduced);
}
if the_constructor_takes(&view.root, class, simple, only) {
return Some(format!("{class}<{initializer}>"));
}
}
None
}
pub(crate) fn the_constructor_takes(
root: &cpp_parser::CppSyntaxNode,
_class: &str,
simple: &str,
only: &str,
) -> bool {
let in_the_tree = root.descendants().find(|node| {
matches!(
cpp_parser::CppSyntaxKind::from(node.kind()),
cpp_parser::CppSyntaxKind::ClassDef
| cpp_parser::CppSyntaxKind::StructDef
| cpp_parser::CppSyntaxKind::UnionDef
) && node.children().any(|child| {
cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::NameExpr
&& child.text().to_string().trim() == simple
})
});
if let Some(node) = in_the_tree {
for declaration in node.descendants() {
if cpp_parser::CppSyntaxKind::from(declaration.kind())
!= cpp_parser::CppSyntaxKind::Declaration
{
continue;
}
let text = declaration.text().to_string();
let head = text
.trim_start()
.trim_start_matches("explicit")
.trim_start();
if !(head.starts_with(simple) && head[simple.len()..].trim_start().starts_with('(')) {
continue;
}
let Some(parameters) = declaration.descendants().find(|child| {
cpp_parser::CppSyntaxKind::from(child.kind())
== cpp_parser::CppSyntaxKind::ParameterList
}) else {
continue;
};
if the_first_parameter_is(¶meters.text().to_string(), only) {
return true;
}
}
return false;
}
false
}
pub(crate) fn the_deduction_guide_deduces(
root: &cpp_parser::CppSyntaxNode,
class: &str,
simple: &str,
only: &str,
initializer: &crate::sema::types::Type,
) -> Option<String> {
let deduces_to = format!("{simple}<{only}>");
for declaration in root.descendants() {
if cpp_parser::CppSyntaxKind::from(declaration.kind())
!= cpp_parser::CppSyntaxKind::Declaration
{
continue;
}
let text = declaration.text().to_string();
let Some((head, tail)) = text.split_once("->") else {
continue;
};
let returns = tail.trim().trim_end_matches(';').trim();
if returns != deduces_to {
continue;
}
let head = head.trim();
let Some(open) = head.rfind('(') else {
continue;
};
let name = head[..open]
.rsplit(|character: char| character.is_whitespace() || character == '>')
.find(|word| !word.is_empty())
.unwrap_or_default();
if name != simple {
continue;
}
if the_first_parameter_is(&head[open..], only) {
return Some(format!("{class}<{initializer}>"));
}
}
None
}
pub(crate) fn the_first_parameter_is(list: &str, only: &str) -> bool {
list.trim_start_matches('(')
.split(',')
.next()
.unwrap_or_default()
.split(|character: char| !character.is_alphanumeric() && character != '_')
.any(|word| word == only)
}
pub(crate) fn class_template_parameters(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Vec<String> {
if let Some(scope) = scopes.scope_with_qualified_name(class)
&& let Some(binding) = scopes.scope(scope).and_then(|scope| {
scope
.bindings
.iter()
.find(|binding| binding.kind == crate::BindingKind::Class)
})
{
let found = crate::sema::declarations::declared_template_parameters_with(
crate::sema::declarations::shapes_from(shapes, root),
binding,
);
if !found.is_empty() {
return found;
}
}
index.template_parameters_of(class, path)
}
pub(crate) const MAX_ALIAS_DEPTH: usize = 8;
pub(crate) fn resolve_aliases(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> String {
resolve_aliases_with_arguments(shapes, index, scopes, root, path, class).0
}
pub(crate) fn resolve_aliases_with_arguments(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> (String, Vec<Type>) {
let (name, carried, _unresolved) =
resolve_aliases_or_unresolved(shapes, index, scopes, root, path, class);
(name, carried)
}
pub(crate) fn resolve_aliases_or_unresolved(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> (String, Vec<Type>, Option<String>) {
let mut current = class.to_string();
let mut carried: Vec<Type> = Vec::new();
let mut seen: Vec<String> = Vec::new();
for _ in 0..MAX_ALIAS_DEPTH {
if seen.contains(¤t) {
break;
}
seen.push(current.clone());
let followed = alias_target_of(shapes, index, scopes, root, path, ¤t).or_else(|| {
let segments: Vec<&str> = current.split("::").collect();
(1..segments.len()).rev().find_map(|take| {
let prefix = segments[..take].join("::");
let (target, scope) = alias_target_of(shapes, index, scopes, root, path, &prefix)?;
let target =
a_class_name_without_spaces(parse_type_spelling(&target).class_name()?);
Some((format!("{target}::{}", segments[take..].join("::")), scope))
})
});
let Some((target, scope)) = followed else {
break;
};
let target_type = parse_type_spelling(&target);
let (named, arguments) = match target_type.class_name() {
Some(named) => (Some(named.to_string()), target_type.arguments().to_vec()),
None => match target_type.pointee() {
Some(pointee) => (
pointee.class_name().map(str::to_string),
pointee.arguments().to_vec(),
),
None => (None, Vec::new()),
},
};
let Some(target) = named.map(|named| a_class_name_without_spaces(&named)) else {
break;
};
if target.is_empty() {
break;
}
if !arguments.is_empty() {
carried = arguments;
}
let candidates: Vec<String> = match &scope {
Some(prefix) if !target.starts_with("::") => {
let prefix = a_class_name_without_spaces(prefix);
let prefix = prefix.as_str();
let (first, rest) = match target.split_once("::") {
Some((first, rest)) => (first, Some(rest)),
None => (target.as_str(), None),
};
let segments: Vec<&str> = prefix.split("::").collect();
let mut candidates: Vec<String> = (1..=segments.len())
.rev()
.map(|take| match rest {
Some(rest) => format!("{}::{first}::{rest}", segments[..take].join("::")),
None => format!("{}::{first}", segments[..take].join("::")),
})
.collect();
candidates.push(target.clone());
candidates
}
_ => vec![target.clone()],
};
let nested = |candidate: &str| {
let (prefix, name) = candidate.rsplit_once("::")?;
let mut best: Option<(usize, String)> = None;
for found in index.files_declaring(name, path) {
if found.fact.kind != crate::DeclKind::Type || found.fact.type_of.is_some() {
continue;
}
let Some(scope) = found.fact.scope.as_deref() else {
continue;
};
let Some(rest) = scope.strip_prefix(prefix)?.strip_prefix("::") else {
continue;
};
let depth = rest.split("::").count();
if depth == 1 && best.as_ref().is_none_or(|(least, _)| depth < *least) {
best = Some((depth, format!("{scope}::{name}")));
}
}
best.map(|(_, spelling)| spelling)
};
let found = candidates
.iter()
.find(|candidate| is_declared(index, scopes, path, candidate))
.map(|candidate| candidate.trim_start_matches("::").to_string())
.or_else(|| candidates.iter().find_map(|candidate| nested(candidate)));
let Some(next) = found else {
let named = candidates[0].trim_start_matches("::").to_string();
return (named.clone(), carried, Some(named));
};
if next == current {
break;
}
current = next;
}
(current, carried, None)
}
pub(crate) fn a_class_name_without_spaces(name: &str) -> String {
name.chars()
.filter(|character| !character.is_whitespace())
.collect()
}
pub(crate) fn without_template_arguments(written: &str) -> String {
let mut stripped = String::with_capacity(written.len());
let mut depth = 0usize;
for character in written.chars() {
match character {
'<' => depth += 1,
'>' if depth > 0 => depth -= 1,
_ if depth == 0 => stripped.push(character),
_ => {}
}
}
stripped
}
pub(crate) fn alias_target_of(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Option<(String, Option<String>)> {
let qualifier_ends_before_the_last_scope = match class.find('<') {
Some(open) => the_close_of(class, open).is_some_and(|close| class[close..].contains("::")),
None => false,
};
let stripped_qualifier = without_template_arguments(class);
let class = if qualifier_ends_before_the_last_scope {
stripped_qualifier.as_str()
} else {
class
};
let (head, written_arguments) = match class.split_once('<') {
Some((head, rest)) => {
let inside = rest.trim_end().strip_suffix('>').unwrap_or(rest);
(
head.trim().to_string(),
crate::sema::builtins::split_arguments(inside),
)
}
None => (class.to_string(), Vec::new()),
};
let class = head.as_str();
let (scope_name, short) = match class.rsplit_once("::") {
Some((prefix, short)) => (prefix.to_string(), short.to_string()),
None => (String::new(), class.to_string()),
};
if let Some(scope) = scopes.scope_with_qualified_name(&scope_name)
&& let Some(data) = scopes.scope(scope)
&& let Some(binding) = data
.bindings
.iter()
.find(|binding| binding.name.identifier_text() == Some(short.as_str()))
&& let Some(target) = crate::sema::declarations::declared_alias_target_with(
crate::sema::declarations::shapes_from(shapes, root),
binding,
)
{
let target = crate::sema::types::substituted_spelling(
&target,
&crate::sema::declarations::declared_template_parameters_with(
crate::sema::declarations::shapes_from(shapes, root),
binding,
),
&written_arguments,
);
return Some((
target,
(!scope_name.is_empty()).then_some(scope_name.clone()),
));
}
match index.definitions(class, path) {
Known::Yes(found) => found.found.iter().find_map(|declaration| {
(declaration.fact.kind == crate::DeclKind::Type)
.then(|| declaration.fact.type_of.clone())
.flatten()
.map(|target| target.to_string())
.map(|target| {
(
crate::sema::types::substituted_spelling(
&target,
declaration.fact.parameters(),
&written_arguments,
),
declaration
.fact
.scope
.clone()
.map(|scope| scope.to_string()),
)
})
}),
Known::Unknown(_) | Known::No => None,
}
}
fn the_close_of(text: &str, open: usize) -> Option<usize> {
let mut depth = 0usize;
for (at, character) in text.char_indices().skip_while(|(at, _)| *at < open) {
match character {
'<' => depth += 1,
'>' => {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(at);
}
}
_ => {}
}
}
None
}
pub(crate) fn is_declared(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
path: &Path,
spelling: &str,
) -> bool {
if scopes.scope_with_qualified_name(spelling).is_some() {
return true;
}
matches!(
index.definition(spelling, path),
Known::Yes(_) | Known::Unknown(UnknownReason::Ambiguous(_))
)
}
pub(crate) fn through_a_namespace_alias(
index: &ProjectIndex,
path: &Path,
spelling: &str,
) -> String {
const DEPTH: usize = 4;
let mut rewritten = spelling.to_string();
for _ in 0..DEPTH {
let segments: Vec<&str> = rewritten.split("::").collect();
if segments.len() < 2 {
return rewritten;
}
let mut changed = false;
for take in (1..segments.len()).rev() {
let prefix = segments[..take].join("::");
let Some(found) = index.definition(&prefix, path).value() else {
continue;
};
if found.fact.kind != crate::DeclKind::Namespace {
continue;
}
let Some(target) = found.fact.type_of.as_deref() else {
continue;
};
if target == prefix {
continue;
}
let qualified = if target.contains("::") {
target.to_string()
} else {
match &found.fact.scope {
Some(scope) => format!("{scope}::{target}"),
None => target.to_string(),
}
};
if qualified == prefix {
continue;
}
rewritten = format!("{qualified}::{}", segments[take..].join("::"));
changed = true;
break;
}
if !changed {
return rewritten;
}
}
rewritten
}
#[cfg(test)]
mod tests {
use super::the_close_of;
#[test]
fn the_close_of_an_argument_list_is_its_matching_angle() {
assert_eq!(the_close_of("outer<int>::handle_type", 5), Some(9));
assert_eq!(the_close_of("ContainerOf<std::vector, int>", 11), Some(28));
assert_eq!(
the_close_of("A<B<C>>::D", 1),
Some(6),
"a nested list closes at its own matching angle, not its first `>`"
);
assert_eq!(the_close_of("Unclosed<int", 8), None);
}
}