use super::*;
pub fn member_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> {
member_across_files_with(
&TypeMemo::default(),
&crate::sema::declarations::ShapeTable::new(),
index,
declaring,
scopes,
root,
path,
offset,
)
}
pub(crate) fn member_across_files_with(
memo: &TypeMemo,
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<ProjectDefinition> {
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((written, _)) = type_of_expression_memoed(
memo,
shapes,
index,
declaring,
scopes,
root,
path,
&access.object,
0,
) else {
let Known::Unknown(reason) = type_of_expression_memoed(
memo,
shapes,
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(&written) else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written.to_string())));
};
let found = member_fact(
shapes,
index,
scopes,
root,
path,
&class,
&access.member,
None,
);
let Known::Yes((fact, file)) = found else {
let Known::Unknown(reason) = found else {
unreachable!("the first match established that this is an `Unknown`")
};
return Known::Unknown(reason);
};
Known::Yes(ProjectDefinition { file, fact })
}
pub(crate) fn the_braced_initialiser_of(
root: &cpp_parser::CppSyntaxNode,
named: &NamedDeclaration,
) -> Option<cpp_parser::CppSyntaxNode> {
let NamedDeclaration::Here(binding) = named else {
return None;
};
let declarator = crate::sema::types::declarator_declaring(root, binding.name_range)?;
let parent = declarator.parent()?;
let initializer = parent.children().find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::Initializer
})?;
initializer.children().find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::InitListExpr
})
}
pub(crate) fn a_member_of_the_enclosing_class(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
callee: &cpp_parser::CppSyntaxNode,
a_finished_type_only: bool,
) -> Option<ProjectDefinition> {
let name = callee.text().to_string();
let name = name.trim();
let bare = !name.is_empty()
&& name
.chars()
.all(|character| character.is_alphanumeric() || character == '_');
if !bare {
return None;
}
let class =
class_of_the_enclosing_definition(scopes, usize::from(callee.text_range().start()))?;
let Known::Yes(listed) = members_of(index, scopes, root, path, &class) else {
return None;
};
let member = listed
.members
.iter()
.find(|member| member.fact.name == name)?;
let names_a_parameter = |written: &str| {
written
.split(|character: char| !character.is_alphanumeric() && character != '_')
.any(|word| {
member
.fact
.parameters()
.iter()
.any(|parameter| !parameter.is_empty() && parameter == word)
})
};
if a_finished_type_only
&& (member
.fact
.returns
.as_deref()
.is_some_and(names_a_parameter)
|| member
.fact
.type_of
.as_deref()
.is_some_and(names_a_parameter))
{
return None;
}
Some(ProjectDefinition {
file: member.file.clone(),
fact: member.fact.clone(),
})
}
pub(crate) fn the_elements_of_a_braced_list(
expression: &cpp_parser::CppSyntaxNode,
) -> Vec<cpp_parser::CppSyntaxNode> {
let mut elements: Vec<cpp_parser::CppSyntaxNode> = Vec::new();
for child in expression.children().skip(1) {
match cpp_parser::CppSyntaxKind::from(child.kind())
== cpp_parser::CppSyntaxKind::InitListExpr
{
true => elements.extend(child.children()),
false => elements.push(child),
}
}
elements
}
pub(crate) fn a_type_the_expression_names(
index: &ProjectIndex,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
) -> Option<String> {
let spelled = expression.text().to_string();
let spelled = spelled.trim();
if spelled.is_empty() || spelled.contains(' ') {
return None;
}
if spelled.contains('<') {
return Some(spelled.to_string());
}
let names_a_type = match index.definition(spelled, path) {
Known::Yes(found) => found.fact.kind == crate::DeclKind::Type,
Known::Unknown(UnknownReason::Ambiguous(_)) => index
.definitions(spelled, path)
.value()
.is_some_and(|found| {
found
.found
.iter()
.any(|declaration| declaration.fact.kind == crate::DeclKind::Type)
}),
Known::Unknown(_) | Known::No => {
let bare = spelled.rsplit("::").next().unwrap_or(spelled);
bare != spelled
&& index.definitions(bare, path).value().is_some_and(|found| {
found
.found
.iter()
.any(|declaration| declaration.fact.kind == crate::DeclKind::Type)
})
}
};
names_a_type.then(|| spelled.to_string())
}
pub(crate) fn a_namespace_aliass_target(
index: &ProjectIndex,
path: &Path,
class: &str,
) -> Option<String> {
let found = index.definition(class, path).value()?;
if found.fact.kind != crate::DeclKind::Namespace {
return None;
}
let written = found.fact.type_of.clone()?.to_string();
if written.contains("::") || written.is_empty() {
return Some(written);
}
match &found.fact.scope {
Some(scope) => Some(format!("{scope}::{written}")),
None => Some(written),
}
}
pub(crate) fn the_deduction_the_standard_fixes(
name: &str,
class_as_written: &str,
element_types: &[crate::sema::types::Type],
) -> Option<Vec<crate::sema::types::Type>> {
let plain = class_as_written
.rsplit("::")
.next()
.unwrap_or(class_as_written);
let in_the_library = class_as_written.contains("std::") || name.starts_with("std::");
if !in_the_library {
return None;
}
match plain {
"pair" if element_types.len() == 2 => {
return Some(element_types.to_vec());
}
"tuple" if !element_types.is_empty() => {
return Some(element_types.to_vec());
}
_ => {}
}
let from_the_first = matches!(
plain,
"optional"
| "vector"
| "list"
| "deque"
| "set"
| "multiset"
| "unordered_set"
| "unordered_multiset"
| "basic_string"
| "valarray"
| "initializer_list"
| "stack"
| "queue"
| "priority_queue"
| "span"
);
if from_the_first && element_types.len() == 1 {
return Some(element_types.to_vec());
}
None
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn the_arguments_a_braced_initialisation_deduces(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
elements: &[cpp_parser::CppSyntaxNode],
spelled: &str,
depth: usize,
) -> Option<Type> {
if spelled.contains('<') {
return None;
}
let class = crate::sema::types::parse_type_spelling(spelled);
let crate::sema::types::Type::Named { name, arguments } = &class else {
return None;
};
if !arguments.is_empty() {
return None;
}
let element_types: Vec<crate::sema::types::Type> = elements
.iter()
.filter_map(|element| {
match type_of_expression_memoed(
memo,
&crate::sema::declarations::ShapeTable::new(),
index,
declaring,
scopes,
root,
path,
element,
depth + 1,
) {
Known::Yes((type_of, _)) => Some(type_of),
_ => None,
}
})
.collect();
if element_types.is_empty() || element_types.len() != elements.len() {
return None;
}
let declared = index
.definitions(name, path)
.value()
.and_then(|found| {
found
.found
.into_iter()
.find(|declaration| !declaration.fact.parameters().is_empty())
})
.or_else(|| index.definition(name, path).value());
let class_as_written = match &declared {
Some(declaration) => declaration.fact.qualified_name(),
None => name.clone(),
};
if let Some(deduced) = the_deduction_the_standard_fixes(name, &class_as_written, &element_types)
{
return Some(crate::sema::types::Type::Named {
name: class_as_written,
arguments: deduced,
});
}
let constructor_name = class_as_written
.rsplit("::")
.next()
.unwrap_or(&class_as_written);
let Known::Yes(listed) = members_of(index, scopes, root, path, &class_as_written) else {
return None;
};
let parameters = match declared {
Some(declaration) if !declaration.fact.parameters().is_empty() => {
declaration.fact.parameters().to_vec()
}
_ => listed
.members
.iter()
.find(|member| !member.fact.parameters().is_empty())
.map(|member| member.fact.parameters().to_vec())?,
};
if parameters.is_empty() {
return None;
}
let mut agreed: Option<Vec<crate::sema::types::Type>> = None;
for constructor in listed
.members
.iter()
.filter(|member| member.fact.kind == crate::DeclKind::Function)
.filter(|member| member.fact.name == constructor_name)
{
let deduced = deduce_the_parameters(
¶meters,
constructor.fact.parameter_list(),
&element_types,
);
let every = deduced.iter().all(|argument| {
!matches!(argument, crate::sema::types::Type::Named { name, .. }
if parameters.iter().any(|parameter| parameter == name))
});
if !every {
continue;
}
match &agreed {
Some(previous) if *previous != deduced => return None,
Some(_) => {}
None => agreed = Some(deduced),
}
}
agreed.map(|arguments| crate::sema::types::Type::Named {
name: name.clone(),
arguments,
})
}
pub(crate) fn the_pointee_of_a_handle(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
arguments: &[crate::sema::types::Type],
) -> Option<(String, Vec<crate::sema::types::Type>)> {
let written: Vec<String> = arguments
.iter()
.map(|argument| argument.to_string())
.collect();
let Known::Yes((fact, file)) = member_fact(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
class,
"element_type",
Some(&written),
) else {
return None;
};
let written_type = fact.type_of.as_deref()?;
let bindings = member_bindings(index, scopes, root, path, class, arguments);
let finished = bindings.applied_to(&parse_type_spelling(written_type));
let finished = finish_a_nested_name(
index,
scopes,
root,
path,
class,
&bindings,
finished,
file,
vec![fact.name.to_string()],
);
match finished.0 {
Type::Named { name, arguments } => {
let declared = index.files_declaring(base_type_name(&name), path);
declared
.iter()
.any(|declaration| declaration.fact.kind == crate::DeclKind::Type)
.then_some((name, arguments))
}
_ => None,
}
}
pub(crate) fn member_access_class(written: &Type) -> Option<String> {
if let Some(class) = written.class_name() {
return Some(class.to_string());
}
written.pointee()?.class_name().map(str::to_string)
}
pub(crate) fn the_class_spelling(type_of: &Type) -> String {
match type_of {
Type::Reference { to, .. } => the_class_spelling(to),
Type::Qualified { of } => the_class_spelling(of),
other => other.to_string(),
}
}
pub(crate) fn member_access_class_and_arguments(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
written: &Type,
) -> (String, Vec<Type>) {
let (class, from_the_alias) =
resolve_aliases_with_arguments(shapes, index, scopes, root, path, class);
let arguments = if written.arguments().is_empty() {
from_the_alias
} else {
written.arguments().to_vec()
};
(class, arguments)
}
pub(crate) fn offerable_members(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
members: &mut MemberList,
) -> usize {
members
.members
.retain(|member| !is_reserved_to_the_implementation(&member.fact));
let open_to_the_cursor = classes_the_cursor_is_in(index, scopes, root, path, offset);
let before = members.members.len();
members.members.retain(|member| {
let Some(access) = member.fact.access else {
return true;
};
if access.is_open_to_everyone() {
return true;
}
member
.fact
.scope
.as_deref()
.is_some_and(|owner| open_to_the_cursor.iter().any(|seen| seen == owner))
});
before - members.members.len()
}
pub(crate) fn classes_the_cursor_is_in(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Vec<String> {
let Some(innermost) = scopes.scope_at(offset) else {
return Vec::new();
};
let mut classes: Vec<String> = scopes
.scope_chain(innermost)
.into_iter()
.filter(|scope| {
scopes.scope(*scope).is_some_and(|data| {
matches!(data.kind, crate::ScopeKind::Class | crate::ScopeKind::Enum)
})
})
.filter_map(|scope| scopes.qualification_prefix_of(scope))
.collect();
let mut level: Vec<String> = classes.clone();
let mut depth = 0usize;
while !level.is_empty() && depth < MAX_NESTED_TYPE_DEPTH {
let mut next: Vec<String> = Vec::new();
for class in &level {
for base in bases_of(index, scopes, root, path, class)
.value()
.unwrap_or_default()
{
if !classes.contains(&base) {
classes.push(base.clone());
next.push(base);
}
}
}
level = next;
depth += 1;
}
classes
}
pub fn own_members_of(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<Vec<(PathBuf, DeclFact)>> {
own_members_of_with(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
class,
)
}
pub fn own_members_of_with(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<Vec<(PathBuf, DeclFact)>> {
direct_members(shapes, index, scopes, root, path, class)
}
pub fn members_of(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<MemberList> {
members_of_with(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
class,
)
}
pub fn members_of_with(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<MemberList> {
let started = std::time::Instant::now();
let key = (class.to_string(), path.to_path_buf());
if let Some(known) = index.cached_member_list(&key) {
if crate::probes::timing() && started.elapsed().as_micros() >= 300 {
eprintln!(
"[member] {:>5.1} ms hit {class}",
started.elapsed().as_secs_f64() * 1000.0
);
}
return known;
}
let listed = members_of_inner(shapes, index, scopes, root, path, class);
let listed = match &listed {
Known::No | Known::Unknown(_) => match class.contains("::") {
true => listed,
false => {
let bare = base_type_name(class);
match qualified_from_the_index(index, path, bare) {
Some(qualified) if qualified != bare => {
let qualified = match class.find('<') {
Some(at) => format!("{qualified}{}", &class[at..]),
None => qualified.to_string(),
};
members_of_inner(shapes, index, scopes, root, path, &qualified)
}
_ => listed,
}
}
},
Known::Yes(list) if list.members.is_empty() && !class.contains("::") => {
match qualified_from_the_index(index, path, base_type_name(class)) {
Some(qualified) if qualified != class => {
let qualified = match class.find('<') {
Some(at) => format!("{qualified}{}", &class[at..]),
None => qualified,
};
members_of_inner(shapes, index, scopes, root, path, &qualified)
}
_ => listed,
}
}
Known::Yes(_) => listed,
};
if let Known::Yes(list) = &listed {
index.remember_member_list(key, list);
}
if crate::probes::timing() && started.elapsed().as_micros() >= 300 {
let held = index
.member_lists
.lock()
.map(|known| known.len())
.unwrap_or(0);
eprintln!(
"[member] {:>5.1} ms miss {class} ({} member(s), {} unlisted base(s), {held} held)",
started.elapsed().as_secs_f64() * 1000.0,
match &listed {
Known::Yes(list) => list.members.len(),
_ => 0,
},
match &listed {
Known::Yes(list) => list.unlisted.len(),
_ => 0,
}
);
}
if crate::probes::members()
&& let Known::Yes(list) = &listed
{
eprintln!(
"members_of({class}) -> {} member(s), unlisted {:?}",
list.members.len(),
list.unlisted
.iter()
.map(|base| format!("{} ({:?})", base.spelling, base.reason))
.collect::<Vec<_>>()
);
}
listed
}
impl ProjectIndex {
pub(crate) fn cached_member_list(&self, key: &(String, PathBuf)) -> Option<Known<MemberList>> {
let known = self.member_lists.lock().ok()?;
let read_now = self.summaries.len();
let cached = known
.get(key)
.or_else(|| known.get(&(key.0.clone(), PathBuf::new())))?;
if !cached.list.unlisted.is_empty() && cached.read_at != read_now {
return None;
}
if crate::probes::members() {
eprintln!(
"members_of({}) -> {} member(s), cached",
key.0,
cached.list.members.len()
);
}
Some(Known::Yes(cached.list.clone()))
}
pub(crate) fn remember_member_list(&self, key: (String, PathBuf), list: &MemberList) {
if list.members.is_empty() {
return;
}
let mut contributors: Vec<PathBuf> = Vec::new();
for member in &list.members {
if !contributors.contains(&member.file) {
contributors.push(member.file.clone());
}
}
let read_at = self.summaries.len();
if let Ok(mut known) = self.member_lists.lock() {
if known.len() >= MAX_CACHED_MEMBER_LISTS {
known.clear();
}
if !contributors.iter().any(|file| file == &key.1) {
known.insert(
(key.0.clone(), PathBuf::new()),
CachedMemberList {
contributors: contributors.clone(),
list: list.clone(),
read_at,
},
);
}
known.insert(
key,
CachedMemberList {
contributors,
list: list.clone(),
read_at,
},
);
}
}
pub fn the_guard_is_taken(&self, file: &Path, guard: crate::FactGuard, offset: usize) -> bool {
self.a_guard_is_taken(file, guard, offset)
}
pub(crate) fn a_guard_is_taken(
&self,
file: &Path,
guard: crate::FactGuard,
offset: usize,
) -> bool {
let region = match guard {
crate::FactGuard::Unconditional => return true,
crate::FactGuard::Region(region) => region,
};
let key = (file.to_path_buf(), offset, region);
if let Ok(known) = self.guard_answers.lock()
&& let Some(answer) = known.get(&key)
{
return *answer != crate::Visibility::Inactive;
}
let visibility = crate::index::environment::visibility_at(self, file, guard, offset);
if let Ok(mut known) = self.guard_answers.lock() {
if known.len() >= MAX_GUARD_ANSWERS {
known.clear();
}
known.insert(key, visibility);
}
visibility != crate::Visibility::Inactive
}
pub(crate) fn forget_guard_answers(&self, path: &Path) {
let wanted = normalize(path);
if let Ok(mut known) = self.guard_answers.lock() {
known.retain(|(file, _, _), _| normalize(file) != wanted);
}
}
pub(crate) fn forget_macro_walks(&self, path: &Path, known_to_the_index: bool) {
let wanted = normalize(path);
if let Ok(mut walks) = self.macro_environments.lock() {
if known_to_the_index {
walks.retain(|_, cached| {
!cached
.contributors
.iter()
.any(|file| file.as_str() == wanted.as_str())
});
} else {
walks.clear();
}
}
if let Ok(mut names) = self.macro_names.lock() {
if known_to_the_index {
names.retain(|_, cached| {
!cached
.contributors
.iter()
.any(|file| file.as_str() == wanted.as_str())
});
} else {
names.clear();
}
}
}
pub(crate) fn forget_member_lists(&self, path: &Path) {
let wanted = normalize(path);
if let Ok(mut known) = self.member_lists.lock() {
known.retain(|_, cached| {
!cached
.contributors
.iter()
.any(|file| normalize(file) == wanted)
});
}
}
}
pub(crate) fn members_of_inner(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<MemberList> {
let original = base_type_name(class).to_string();
let with_arguments = class.to_string();
let (resolved, _arguments, missing) =
resolve_aliases_or_unresolved(
shapes,
index,
scopes,
root,
path,
a_type_spelling_with_its_arguments(class),
);
if let Some(missing) = missing {
if crate::probes::members() {
eprintln!("members_of_inner: {class} names {missing}, which nothing declares");
}
return Known::Yes(MemberList {
members: Vec::new(),
unlisted: vec![UnlistedBase {
spelling: missing.clone(),
reason: UnknownReason::NotDeclaredHere(Box::from(missing)),
}],
});
}
let mut class = base_type_name(&resolved).to_string();
let own = match direct_members(shapes, index, scopes, root, path, &class) {
Known::Yes(members) => members,
Known::Unknown(UnknownReason::NotDeclaredHere(_)) => {
let last = without_the_namespace(&class);
if last == class {
return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class)));
}
match direct_members(shapes, index, scopes, root, path, &last) {
Known::Yes(members) => {
class = last;
members
}
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => {
return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class)));
}
}
}
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class))),
};
if crate::probes::members() && own.is_empty() {
eprintln!("members_of_inner: {class} has no own members (after alias resolution)");
}
let mut own = own;
if own.is_empty()
&& let Some(target) = a_namespace_aliass_target(index, path, &class)
&& let Known::Yes(found) = direct_members(shapes, index, scopes, root, path, &target)
&& !found.is_empty()
{
own = found;
class = target;
}
let mut list = MemberList::default();
let mut hidden: HashSet<String> = HashSet::new();
let mut visited: HashSet<String> = HashSet::from([class.to_string()]);
let mut own: Vec<ProjectMember> = own
.into_iter()
.map(|(file, fact)| ProjectMember {
file,
fact,
declared_in: class.to_string(),
depth: 0,
ambiguous: false,
})
.collect();
own.sort_by(|one, other| one.fact.name.cmp(&other.fact.name));
mark_ambiguity(&mut own);
hidden.extend(recorded_names(&own));
list.members.extend(own);
let parameters = class_template_parameters(shapes, index, scopes, root, path, &class);
let mut level: Vec<(String, String)> =
match the_base_clauses_of(shapes, index, scopes, root, path, &class) {
Known::Yes(bases) => bases
.into_iter()
.filter(|written| !names_a_template_parameter(base_type_name(written), ¶meters))
.map(|written| substitute_a_base_clause(index, path, &with_arguments, &written))
.filter(
|substituted| match why_a_clause_cannot_be_walked(substituted) {
Some(reason) => {
list.unlisted.push(UnlistedBase {
spelling: substituted.clone(),
reason,
});
false
}
None => true,
},
)
.map(|substituted| (substituted, class.to_string()))
.collect(),
Known::Unknown(reason) => {
list.unlisted.push(UnlistedBase {
spelling: class.to_string(),
reason,
});
Vec::new()
}
Known::No => Vec::new(),
};
let mut depth = 1;
while !level.is_empty() {
let mut found: Vec<ProjectMember> = Vec::new();
let mut next: Vec<(String, String)> = Vec::new();
for (written, owner) in level {
let head = base_type_name(&written).to_string();
let base = resolved_in_the_enclosing_scopes(index, scopes, path, &owner, &head);
let shown = match written.find('<') {
Some(at) => format!("{base}{}", &written[at..]),
None => base.clone(),
};
if !visited.insert(shown.clone()) {
continue;
}
if crate::probes::members() {
eprintln!("[members] {class} level {depth}: {shown}");
}
let head_is_an_alias = index
.files_declaring(&head, path)
.into_iter()
.any(|declared| {
declared.fact.kind == crate::DeclKind::Type && declared.fact.type_of.is_some()
});
if head_is_an_alias {
let candidates = the_classes_a_base_clause_names(index, path, &written);
for one in candidates.into_iter().filter(|one| !visited.contains(one)) {
next.push((one, owner.clone()));
}
continue;
}
let members = match direct_members(shapes, index, scopes, root, path, &base) {
Known::Yes(members) => members,
Known::Unknown(reason) => {
let candidates = the_classes_a_base_clause_names(index, path, &written);
let fresh: Vec<String> = candidates
.into_iter()
.filter(|one| !visited.contains(one))
.collect();
if !fresh.is_empty() {
for one in fresh {
next.push((one, owner.clone()));
}
continue;
}
list.unlisted.push(UnlistedBase {
spelling: shown,
reason,
});
continue;
}
Known::No => continue,
};
let listed = MemberList {
members: members
.into_iter()
.map(|(file, fact)| ProjectMember {
file,
fact,
declared_in: shown.clone(),
depth,
ambiguous: false,
})
.collect(),
unlisted: Vec::new(),
};
let Known::Yes(listed) = substituted_members(index, path, &shown, Known::Yes(listed))
else {
continue;
};
found.extend(listed.members);
let further = the_base_clauses_of(shapes, index, scopes, root, path, &base);
match further {
Known::Yes(clauses) => next.extend(
clauses
.into_iter()
.map(|clause| substitute_a_base_clause(index, path, &shown, &clause))
.filter(|clause| {
!names_a_template_parameter(base_type_name(clause), ¶meters)
})
.filter_map(|clause| match why_a_clause_cannot_be_walked(&clause) {
Some(reason) => {
list.unlisted.push(UnlistedBase {
spelling: clause,
reason,
});
None
}
None => Some((clause, base.clone())),
}),
),
Known::Unknown(reason) => list.unlisted.push(UnlistedBase {
spelling: base,
reason,
}),
Known::No => {}
}
}
found.retain(|member| !hidden.contains(member.fact.name.as_str()));
found.sort_by(|one, other| one.fact.name.cmp(&other.fact.name));
mark_ambiguity(&mut found);
hidden.extend(recorded_names(&found));
list.members.extend(found);
level = next;
depth += 1;
}
if list.members.is_empty() && list.unlisted.is_empty() && class != base_type_name(&original) {
list.unlisted.push(UnlistedBase {
spelling: class.to_string(),
reason: UnknownReason::NotDeclaredHere(Box::from(class.to_string())),
});
}
Known::Yes(list)
}
pub(crate) fn the_base_clauses_of(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<Vec<String>> {
if let Some(scope) = scopes.scope_with_qualified_name(class)
&& let Some(data) = scopes.scope(scope)
&& let Some(parent) = data.parent
&& let Some(name) = class.rsplit("::").next()
&& let Some(binding) = scopes.scope(parent).and_then(|scope| {
scope
.bindings
.iter()
.find(|binding| binding.name.identifier_text() == Some(name))
})
{
return Known::Yes(crate::sema::declarations::declared_bases_of_with(
crate::sema::declarations::shapes_from(shapes, root),
binding,
));
}
let base = base_type_name(class).to_string();
let candidates = index.files_declaring(&base, path);
let is_a_type = |declared: &VisibleDeclaration<'_>| declared.fact.kind == crate::DeclKind::Type;
let chosen = candidates
.iter()
.position(|declared| is_a_type(declared) && declared.fact.definition)
.or_else(|| candidates.iter().position(is_a_type));
if let Some(at) = chosen {
return Known::Yes(candidates[at].fact.bases().to_vec());
}
bases_of(index, scopes, root, path, class)
}
fn why_a_clause_cannot_be_walked(clause: &str) -> Option<UnknownReason> {
if clause.contains("...") {
return Some(UnknownReason::UnknownType(Box::from(clause)));
}
const OPERATORS: [&str; 6] = [" + ", " - ", " * ", " / ", " % ", " << "];
if OPERATORS.iter().any(|operator| clause.contains(operator)) {
return Some(UnknownReason::UnknownType(Box::from(clause)));
}
None
}
fn the_file_of_a_class_body(index: &ProjectIndex, path: &Path, class: &str) -> Option<String> {
let decl = index.definitions(class, path).value()?;
let mut types: Vec<&ProjectDefinition> = decl
.found
.iter()
.filter(|one| one.fact.kind == crate::DeclKind::Type)
.collect();
if types.is_empty() {
return None;
}
types.sort_by_key(|one| {
(
!one.fact.definition,
std::cmp::Reverse(one.fact.parameters().len()),
)
});
Some(normalize(&types[0].file))
}
pub(crate) fn substitute_a_base_clause(
index: &ProjectIndex,
path: &Path,
shown: &str,
clause: &str,
) -> String {
let Some((head, mut arguments)) = split_template_arguments(shown) else {
if crate::probes::inference() {
eprintln!("[clause] {shown:?} is not a template id; clause {clause:?}");
}
return clause.to_string();
};
if crate::probes::inference() {
eprintln!("[clause] {shown:?} -> head {head:?}, arguments {arguments:?}");
}
let mut candidates = index.files_declaring(&head, path);
if candidates.is_empty() {
let bare = head.rsplit("::").next().unwrap_or(&head).to_string();
candidates = index.files_declaring(&bare, path);
}
let Some(declared) = candidates
.iter()
.find(|declared| declared.fact.kind == crate::DeclKind::Type)
else {
return clause.to_string();
};
let mut names = declared.fact.parameters().to_vec();
names.truncate(arguments.len());
arguments.truncate(names.len());
if names.is_empty() {
if crate::probes::inference() {
eprintln!(
"[clause] {shown:?}: no parameters for {head:?} ({} candidate(s))",
candidates.len()
);
}
return clause.to_string();
}
let substituted = crate::sema::types::substituted_spelling(clause, &names, &arguments);
if crate::probes::inference() {
eprintln!("[clause] {shown:?}: {names:?} <- {arguments:?} gives {substituted:?}");
}
substituted
}
pub(crate) fn the_classes_a_base_clause_names(
index: &ProjectIndex,
path: &Path,
clause: &str,
) -> Vec<String> {
let mut spelling = clause.trim().to_string();
if crate::probes::inference() {
eprintln!("[base-clause] asked about {clause:?}");
}
for _ in 0..MAX_ALIAS_HOPS {
let without_typename = spelling
.strip_prefix("typename ")
.unwrap_or(&spelling)
.trim()
.to_string();
if crate::probes::inference() {
eprintln!("[base-clause] step: {without_typename:?}");
}
if let Some((class, member)) = split_at_the_last_scope(&without_typename) {
let (head, arguments) = match split_template_arguments(&class) {
Some((head, arguments)) => (head, arguments),
None => (class.trim().to_string(), Vec::new()),
};
let bare = head.rsplit("::").next().unwrap_or(&head).trim();
if bare == "conditional" && member.trim() == "type" && arguments.len() >= 3 {
return match the_bool_a_trait_has(index, path, arguments[0].trim()) {
Some(true) => vec![arguments[1].clone()],
Some(false) => vec![arguments[2].clone()],
None => vec![arguments[1].clone(), arguments[2].clone()],
};
}
let parameters = index
.files_declaring(&head, path)
.into_iter()
.find(|declared| declared.fact.kind == crate::DeclKind::Type)
.map(|declared| declared.fact.parameters().to_vec())
.unwrap_or_default();
let scope = index
.definition(bare, path)
.value()
.map(|found| found.fact.qualified_name())
.unwrap_or_else(|| head.clone());
let Some(fact) = index
.declarations_in(&scope, path)
.into_iter()
.find(|one| one.fact.name == member.trim())
else {
return Vec::new();
};
let Some(target) = fact.fact.type_of.clone() else {
return Vec::new();
};
let substituted =
crate::sema::types::substituted_spelling(&target, ¶meters, &arguments);
if substituted == spelling {
return Vec::new();
}
spelling = substituted;
continue;
}
let Some((head, arguments)) = split_template_arguments(&without_typename) else {
return Vec::new();
};
let declared = index.files_declaring(&head, path);
if let Some(alias) = declared.iter().find(|declared| {
declared.fact.kind == crate::DeclKind::Type && declared.fact.type_of.is_some()
}) {
let Some(target) = alias.fact.type_of.clone() else {
return Vec::new();
};
let substituted = crate::sema::types::substituted_spelling(
&target,
alias.fact.parameters(),
&arguments,
);
if substituted == spelling {
return Vec::new();
}
spelling = substituted;
continue;
}
if declared
.iter()
.any(|declared| declared.fact.kind == crate::DeclKind::Type)
{
return vec![without_typename];
}
return Vec::new();
}
Vec::new()
}
pub(crate) fn the_bool_a_trait_has(
index: &ProjectIndex,
path: &Path,
spelled: &str,
) -> Option<bool> {
let (class, member) = split_at_the_last_scope(spelled)?;
if member.trim() != "value" {
return None;
}
let (head, arguments) = split_template_arguments(&class)?;
let facts = index.files_declaring(&head, path);
let declarations: Vec<&VisibleDeclaration<'_>> = facts
.iter()
.filter(|declared| declared.fact.kind == crate::DeclKind::Type)
.collect();
let matches = |declared: &&&VisibleDeclaration<'_>| {
declared.fact.pattern().is_some()
&& a_pattern_matches(
declared.fact.pattern(),
declared.fact.parameters(),
Some(&arguments),
)
};
let chosen = declarations
.iter()
.find(matches)
.or_else(|| {
declarations
.iter()
.find(|declared| declared.fact.pattern().is_none())
})
.copied()?;
for base in chosen.fact.bases() {
match base.rsplit("::").next().unwrap_or(base).trim() {
"true_type" => return Some(true),
"false_type" => return Some(false),
_ => {}
}
}
None
}
pub(crate) fn direct_members(
shapes: &crate::sema::declarations::ShapeTable,
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<Vec<(PathBuf, DeclFact)>> {
let class = if scopes.scope_with_qualified_name(class).is_some() {
class.to_string()
} else {
resolve_aliases(shapes, index, scopes, root, path, class)
};
let class = through_a_namespace_alias(index, path, &class);
let class = &class;
if let Some(scope) = scopes.scope_with_qualified_name(class)
&& let Some(data) = scopes.scope(scope)
{
let shapes = crate::sema::declarations::shapes_from(shapes, root);
return Known::Yes(
data.bindings
.iter()
.map(|binding| {
(
path.to_path_buf(),
fact_from_binding_with(shapes, root, class, binding),
)
})
.collect(),
);
}
if let Some(scope) = a_class_nested_in_another(scopes, class)
&& let Some(data) = scopes.scope(scope)
{
let shapes = crate::sema::declarations::shapes_from(shapes, root);
let qualified = scopes
.qualified_name_of(scope)
.unwrap_or_else(|| class.to_string());
return Known::Yes(
data.bindings
.iter()
.map(|binding| {
(
path.to_path_buf(),
fact_from_binding_with(shapes, root, &qualified, binding),
)
})
.collect(),
);
}
let found = index.declarations_in(class, path);
if !found.is_empty() {
let own_body = the_file_of_a_class_body(index, path, class);
let found: Vec<_> = match &own_body {
Some(body) => found
.into_iter()
.filter(|declaration| normalize(&declaration.file) == *body)
.collect(),
None => found,
};
return Known::Yes(
found
.into_iter()
.map(|declaration| (declaration.file.clone(), declaration.fact.clone()))
.collect(),
);
}
if let Known::Yes(resolved) = index.definition(without_arguments(class), path) {
let qualified = resolved.fact.qualified_name();
if qualified != *class {
let found = index.declarations_in(&qualified, path);
if !found.is_empty() {
return Known::Yes(
found
.into_iter()
.map(|declaration| (declaration.file.clone(), declaration.fact.clone()))
.collect(),
);
}
}
}
match index.definition(class, path) {
Known::Yes(found) if found.fact.qualified_name() == *class => Known::Yes(Vec::new()),
Known::Unknown(UnknownReason::Ambiguous(_)) => {
if let Known::Yes(found) = index.definitions(class, path) {
let names: std::collections::BTreeSet<String> = found
.found
.iter()
.filter(|declaration| declaration.fact.kind == crate::DeclKind::Type)
.map(|declaration| declaration.fact.qualified_name())
.collect();
if let [qualified] = names.iter().collect::<Vec<_>>().as_slice() {
let found = index.declarations_in(qualified, path);
if !found.is_empty() {
return Known::Yes(
found
.into_iter()
.map(|declaration| {
(declaration.file.clone(), declaration.fact.clone())
})
.collect(),
);
}
}
}
Known::Yes(Vec::new())
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::Yes(_) | Known::No => {
Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class.as_str())))
}
}
}
pub(crate) fn a_class_nested_in_another(
scopes: &crate::ScopeTree,
class: &str,
) -> Option<crate::ScopeId> {
let mut found = None;
for (index, scope) in scopes.scopes().iter().enumerate() {
if scope.kind != crate::ScopeKind::Class || scope.name.as_deref() != Some(class) {
continue;
}
let id = crate::ScopeId(index);
match scopes.qualified_name_of(id) {
Some(qualified) if qualified == class => return None,
Some(_) => {}
None => continue,
}
if found.is_some() {
return None;
}
found = Some(id);
}
found
}
pub(crate) fn recorded_names(members: &[ProjectMember]) -> impl Iterator<Item = String> + '_ {
members
.iter()
.map(|member| member.fact.name.to_string())
.filter(|name| !name.is_empty())
}
pub(crate) fn mark_ambiguity(members: &mut [ProjectMember]) {
let mut declaring: HashMap<String, HashSet<String>> = HashMap::new();
for member in members.iter().filter(|member| !member.fact.name.is_empty()) {
declaring
.entry(member.fact.name.to_string())
.or_default()
.insert(member.declared_in.clone());
}
for member in members.iter_mut() {
member.ambiguous = !member.fact.name.is_empty()
&& declaring
.get(member.fact.name.as_str())
.is_some_and(|classes| classes.len() > 1);
}
}