use super::*;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemberCompletions {
pub class: String,
pub members: MemberList,
pub member_range: cpp_parser::SourceRange,
pub prefix: String,
pub hidden_by_access: usize,
}
pub fn member_completions_at(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<MemberCompletions> {
let memo = TypeMemo::default();
let crate::completion::CompletionContext::Member(access) =
crate::completion::context_at(root, offset)
else {
return Known::Unknown(UnknownReason::UnparsableName);
};
let written = match type_of_expression_memoed(
&memo,
&crate::sema::declarations::ShapeTable::new(),
index,
declaring,
scopes,
root,
path,
&access.object,
0,
) {
Known::Yes((written, _)) => written,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => {
return Known::Unknown(UnknownReason::UnknownType(Box::from(
access.object.text().to_string().trim(),
)));
}
};
let Some(class) = member_access_class(&written) else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written.to_string())));
};
let spelled = written.to_string();
let names_a_class = |name: &str| {
let bare = base_type_name(name);
index
.files_declaring(bare, path)
.iter()
.any(|found| found.fact.kind == crate::DeclKind::Type && found.fact.type_of.is_none())
};
let class = match access.arrow {
true => crate::completion::the_class_after_the_operator(
index, scopes, root, path, &written, true,
)
.map(|(class, _)| class)
.filter(|class| names_a_class(class))
.or_else(|| the_class_an_arrow_points_at(index, scopes, root, path, &spelled, None))
.unwrap_or(class),
false => class,
};
match members_of(index, scopes, root, path, &class) {
Known::Yes(mut members) => {
let hidden_by_access =
offerable_members(index, scopes, root, path, offset, &mut members);
Known::Yes(MemberCompletions {
class: class.to_string(),
members,
hidden_by_access,
member_range: access.member_range,
prefix: written_before_the_cursor(&access, offset),
})
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class))),
}
}
pub(crate) fn written_before_the_cursor(
access: &crate::sema::resolve::MemberAccess,
offset: usize,
) -> String {
let start = access.member_range.start_offset;
let end = access.member_range.end_offset().min(offset);
if end <= start {
return String::new();
}
access
.member
.get(..end - start)
.unwrap_or(&access.member)
.to_string()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OfferedName {
pub file: PathBuf,
pub fact: DeclFact,
pub depth: usize,
pub from: NameProvenance,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NameProvenance {
Scope,
ThisFile,
DirectInclude,
IndirectInclude,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NameCompletions {
pub scope: String,
pub names: Vec<OfferedName>,
pub prefix: String,
pub name_range: cpp_parser::SourceRange,
}
pub fn names_for_a_doc_comment(
index: &ProjectIndex,
path: &Path,
scope: &str,
written: &str,
range: cpp_parser::SourceRange,
) -> NameCompletions {
let names = if scope.is_empty() {
declarations_in_scope(index, path, None, written)
} else {
declarations_in_scope(index, path, Some(scope), written)
};
NameCompletions {
scope: scope.to_string(),
names: names
.into_iter()
.map(|candidate| OfferedName {
fact: candidate.fact,
file: candidate.file,
depth: 0,
from: candidate.from,
})
.collect(),
prefix: written.to_string(),
name_range: range,
}
}
pub fn name_completions_at(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<NameCompletions> {
let Some(position) = crate::sema::resolve::name_position_at(root, offset) else {
return Known::Unknown(UnknownReason::UnparsableName);
};
let phase = std::time::Instant::now();
if crate::probes::completion() {
eprintln!(
"[completion] the position: scope {:?}, written {:?}",
position.scope, position.written
);
}
let names = if position.scope.is_empty() {
match visible_names(index, scopes, root, path, offset, &position.written) {
Known::Yes(names) => names,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => return Known::Unknown(UnknownReason::UnparsableName),
}
} else {
match names_in_a_scope(
index,
scopes,
root,
path,
&position.scope,
&position.written,
) {
Known::Yes(names) => names,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => return Known::Unknown(UnknownReason::UnparsableName),
}
};
if crate::probes::completion() {
eprintln!(
"[completion] the listing took {:?} for {} name(s)",
phase.elapsed(),
names.len()
);
}
let mut names = names;
if position.scope.is_empty()
&& let Some(summary) = index.summary(path)
{
let mut offered_macros: Vec<(&str, bool, cpp_parser::SourceRange, &Path)> = Vec::new();
for fact in &summary.macros {
offered_macros.push((
fact.name.as_str(),
fact.function_like,
fact.range,
&summary.path,
));
}
for include in &summary.includes {
let Some(resolved) = &include.resolved else {
continue;
};
let Some(included) = index.summary(resolved) else {
continue;
};
for fact in &included.macros {
offered_macros.push((
fact.name.as_str(),
fact.function_like,
fact.range,
included.path.as_path(),
));
}
}
offered_macros.sort_by(|left, right| left.0.cmp(right.0));
offered_macros.dedup_by(|left, right| left.0 == right.0);
for (name, function_like, range, written_in) in offered_macros {
if !position.written.is_empty() && !name.starts_with(&position.written) {
continue;
}
let Some(template) = summary.declarations.first() else {
continue;
};
let mut declaration = template.clone();
declaration.name = name.into();
declaration.kind = crate::DeclKind::MacroLike;
declaration.type_of = None;
declaration.returns = None;
declaration.detail_mut().bases.clear();
declaration.detail_mut().parameters.clear();
declaration.local = false;
declaration.name_range = range;
declaration.range = range;
declaration.scope = None;
declaration.detail_mut().in_namespace = None;
declaration.detail_mut().parameter_list = function_like.then(|| "(".to_string());
let ours = written_in == summary.path.as_path();
names.push(OfferedName {
file: written_in.to_path_buf(),
fact: declaration,
depth: 0,
from: match ours {
true => NameProvenance::ThisFile,
false => NameProvenance::DirectInclude,
},
});
}
}
Known::Yes(NameCompletions {
scope: position.scope,
names,
prefix: position.written,
name_range: position.range,
})
}
pub fn name_completions_traced(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
) -> Known<NameCompletions> {
name_completions_at(index, scopes, root, path, offset)
}
pub(crate) fn visible_names(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
offset: usize,
written: &str,
) -> Known<Vec<OfferedName>> {
let Some(innermost) = scopes.scope_at(offset) else {
return Known::Unknown(UnknownReason::UnparsableName);
};
let chain = scopes.scope_chain(innermost);
let mut names: Vec<OfferedName> = Vec::new();
let phase = std::time::Instant::now();
if let Some(class) = the_class_a_definition_belongs_to(root, offset)
&& let Known::Yes(members) = names_of_a_class(index, scopes, root, path, &class)
{
names.extend(offered(members, 0));
}
let in_this_file = normalize(path);
if crate::probes::completion() {
eprintln!("[completion] the class tier: {:?}", phase.elapsed());
}
let chain_phase = std::time::Instant::now();
for (depth, scope) in chain.iter().copied().enumerate() {
let Some(data) = scopes.scope(scope) else {
continue;
};
if data.kind == crate::ScopeKind::TranslationUnit {
continue;
}
if matches!(data.kind, crate::ScopeKind::Class | crate::ScopeKind::Enum)
&& let Some(class) = scopes.qualification_prefix_of(scope)
{
let members = match names_of_a_class(index, scopes, root, path, &class) {
Known::Yes(members) => members,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => Vec::new(),
};
names.extend(offered(members, depth));
continue;
}
let body = matches!(
data.kind,
crate::ScopeKind::Block | crate::ScopeKind::Function | crate::ScopeKind::Lambda
);
names.extend(offered(
bindings_of(root, path, &data.bindings, None, body)
.into_iter()
.filter(|candidate| !body || declared_above(candidate, offset, &in_this_file))
.collect(),
depth,
));
if let Some(prefix) = scopes.qualification_prefix_of(scope) {
names.extend(offered(
declarations_in(&prefix, index, path, written),
depth,
));
}
}
if crate::probes::completion() {
eprintln!("[completion] the chain: {:?}", chain_phase.elapsed());
}
let global_phase = std::time::Instant::now();
names.extend(global_offers(
index,
scopes,
root,
path,
chain.len(),
written,
));
if crate::probes::completion() {
eprintln!(
"[completion] the global tier: {:?}",
global_phase.elapsed()
);
}
let sort_phase = std::time::Instant::now();
sort_and_hide(&mut names);
if crate::probes::completion() {
eprintln!("[completion] the sort: {:?}", sort_phase.elapsed());
}
Known::Yes(names)
}
pub(crate) fn global_offers(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
depth: usize,
written: &str,
) -> Vec<OfferedName> {
let mut names = offered(global_names(index, scopes, root, path, written), depth);
sort_and_hide(&mut names);
names
}
pub(crate) fn a_spelling_names_a_type(index: &ProjectIndex, spelling: &str, path: &Path) -> bool {
let Some(found) = index.definitions(spelling, path).value() else {
return false;
};
let mut any_type = false;
for declaration in &found.found {
if declaration.fact.kind == crate::DeclKind::Type {
any_type = true;
continue;
}
if declaration.fact.scope.as_deref() != Some(spelling) {
return false;
}
}
any_type
}
pub(crate) fn names_in_a_scope(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
scope: &str,
written: &str,
) -> Known<Vec<OfferedName>> {
names_in_a_scope_at(index, scopes, root, path, scope, written, 0)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn names_in_a_scope_at(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
scope: &str,
written: &str,
depth: usize,
) -> Known<Vec<OfferedName>> {
if scope == "::" {
return Known::Yes(global_offers(index, scopes, root, path, 0, written));
}
let spelling = scope.trim_start_matches("::");
let in_the_tree = scopes.scope_with_qualified_name(spelling);
let kind = in_the_tree
.and_then(|id| scopes.scope(id))
.map(|scope| scope.kind);
let mut names: Vec<OfferedName> = Vec::new();
match kind {
Some(crate::ScopeKind::Class | crate::ScopeKind::Enum) => {
let members = match names_of_a_class(index, scopes, root, path, spelling) {
Known::Yes(members) => members,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => Vec::new(),
};
names.extend(offered(members, 0));
}
Some(_) => {
if let Some(data) = in_the_tree.and_then(|id| scopes.scope(id)) {
names.extend(offered(
bindings_of(root, path, &data.bindings, Some(spelling), false),
0,
));
}
names.extend(offered(declarations_in(spelling, index, path, written), 0));
if names.is_empty()
&& depth < 4
&& let Some(id) = in_the_tree
&& let Some(target) = the_target_of_a_namespace_alias(root, scopes, id)
{
let target = the_target_in_its_own_scope(scopes, spelling, &target);
if target != spelling {
return names_in_a_scope_at(index, scopes, root, path, &target, written, 0);
}
}
}
None => {
let names_a_type = a_spelling_names_a_type(index, spelling, path);
if crate::probes::members() {
let bare = spelling.rsplit("::").next().unwrap_or(spelling);
let facts: Vec<String> = index
.every_fact_named(bare)
.into_iter()
.map(|(file, fact)| {
format!(
"{:?} scope {:?} kind {:?} @ {}",
fact.name,
fact.scope,
fact.kind,
file.file_name().unwrap_or_default().to_string_lossy()
)
})
.collect();
eprintln!(
" names_in_a_scope({spelling}): in the tree {}, names_a_type {names_a_type}, \
definition {:?} | facts named {bare:?}: {facts:?}",
in_the_tree.is_some(),
match index.definition(spelling, path) {
Known::Yes(found) =>
format!("Yes({} {:?})", found.fact.qualified_name(), found.fact.kind),
Known::Unknown(reason) => format!("Unknown({reason:?})"),
Known::No => "No".to_string(),
}
);
if spelling == "std::string" {
let xstring = index.summaries_named_like("xstring");
let string = index.summaries_named_like("string");
eprintln!(
" index: {} summaries, {} distinct names | by_name: string {} basic_string {} \
vector {} | by_scope: std::basic_string {} | files: xstring {} string-ish {}",
index.len(),
index.distinct_names(),
index.name_postings("string"),
index.name_postings("basic_string"),
index.name_postings("vector"),
index.scope_postings("std::basic_string"),
xstring.len(),
string.len(),
);
for path in string.iter().take(6) {
eprintln!(" {}", path.display());
}
for (path, summary) in index.all_summaries() {
let name = path.to_string_lossy();
if !name.ends_with("xstring") && !name.ends_with("include/string") {
continue;
}
let mut named: Vec<String> = summary
.declarations
.iter()
.filter(|fact| fact.name.contains("basic"))
.map(|fact| {
format!(
"{:?} kind {:?} scope {:?} local {}",
fact.name, fact.kind, fact.scope, fact.local
)
})
.collect();
named.sort();
named.dedup();
eprintln!(
" {} has {} declaration(s); the {} named *basic*: {:?}",
name,
summary.declarations.len(),
named.len(),
named.iter().take(14).collect::<Vec<_>>()
);
}
}
}
if names_a_type {
let named = resolve_aliases(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
spelling,
);
let named = named.as_ref();
if crate::probes::members() {
eprintln!(" names_a_type({spelling}) -> alias resolved to {named:?}");
}
match names_of_a_class(index, scopes, root, path, named) {
Known::Yes(members) => names.extend(offered(members, 0)),
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => {}
}
} else {
let found = declarations_in(spelling, index, path, written);
if found.is_empty() {
if depth < 4
&& let Known::Yes(alias) = index.definition(spelling, path)
&& alias.fact.kind == crate::DeclKind::Namespace
&& let Some(target) = alias.fact.type_of.as_deref()
{
let mut candidates: Vec<String> = Vec::new();
if let Some(scope) = alias.fact.scope.as_deref() {
candidates.push(format!("{scope}::{target}"));
}
candidates.push(target.trim_start_matches("::").to_string());
for candidate in candidates {
if candidate != spelling
&& !declarations_in(&candidate, index, path, written).is_empty()
{
return names_in_a_scope_at(
index, scopes, root, path, &candidate, written, 0,
);
}
}
}
return match index.definition(spelling, path) {
Known::Yes(found) if found.fact.qualified_name() == spelling => {
Known::Yes(Vec::new())
}
Known::Unknown(reason) => Known::Unknown(reason),
_ => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(spelling))),
};
}
names.extend(offered(found, 0));
}
}
}
sort_and_hide(&mut names);
Known::Yes(names)
}
pub(crate) fn the_target_of_a_namespace_alias(
root: &cpp_parser::CppSyntaxNode,
scopes: &crate::ScopeTree,
id: crate::sema::symbol::ScopeId,
) -> Option<String> {
let scope = scopes.scope(id)?;
if scope.kind != crate::ScopeKind::Namespace {
return None;
}
let range = scope.range?;
let node = root.descendants().find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::NamespaceDecl
&& cpp_parser::source_range(node.text_range()) == range
})?;
if node.children().any(|child| {
cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::CompoundStat
}) {
return None;
}
node.children()
.find(|child| {
cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::NameExpr
})
.map(|child| child.text().to_string())
}
pub(crate) fn the_target_in_its_own_scope(
scopes: &crate::ScopeTree,
alias: &str,
target: &str,
) -> String {
let target = target.trim().trim_start_matches("::");
if let Some(at) = alias.rfind("::") {
let nearby = format!("{}::{target}", &alias[..at]);
if scopes.scope_with_qualified_name(&nearby).is_some() {
return nearby;
}
}
if scopes.scope_with_qualified_name(target).is_some() {
return target.to_string();
}
target.to_string()
}
pub(crate) fn declared_above(candidate: &Candidate, offset: usize, in_this_file: &str) -> bool {
if candidate.file != Path::new(in_this_file) {
return true;
}
let at = candidate.fact.name_range.start_offset;
at == 0 || at < offset
}
pub(crate) struct Candidate {
pub(crate) file: PathBuf,
pub(crate) fact: DeclFact,
pub(crate) steps: usize,
pub(crate) from: NameProvenance,
}
impl Candidate {
pub(crate) fn new(file: PathBuf, fact: DeclFact, from: NameProvenance) -> Candidate {
Candidate {
file,
fact,
steps: 0,
from,
}
}
}
pub(crate) const MAX_COLLECTED_NAMES: usize = 400;
pub(crate) const MAX_COLLECTED_IN_A_SCOPE: usize = 4096;
pub(crate) const POPULAR_NAME: usize = 4096;
pub(crate) fn bindings_of(
root: &cpp_parser::CppSyntaxNode,
path: &Path,
bindings: &[crate::Binding],
scope: Option<&str>,
local: bool,
) -> Vec<Candidate> {
let spelling = scope.unwrap_or_default();
bindings
.iter()
.map(|binding| {
let mut fact = fact_from_binding(root, spelling, binding);
fact.local = local;
Candidate::new(path.to_path_buf(), fact, NameProvenance::Scope)
})
.collect()
}
pub(crate) fn global_names(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
written: &str,
) -> Vec<Candidate> {
let mut names: Vec<Candidate> = scopes
.root()
.and_then(|root_scope| scopes.scope(root_scope))
.map(|data| bindings_of(root, path, &data.bindings, None, false))
.unwrap_or_default();
for name in &mut names {
name.from = NameProvenance::ThisFile;
}
names.extend(declarations_in_scope(index, path, None, written));
names
}
pub(crate) fn declarations_in_scope(
index: &ProjectIndex,
visible_from: &Path,
scope: Option<&str>,
written: &str,
) -> Vec<Candidate> {
let accepts = |fact: &DeclFact| name_starts_with(fact, written);
let found = match scope {
Some(spelling) => index.declarations_in_where(spelling, visible_from, accepts),
None => index.visible_declarations_where(visible_from, |fact| {
accepts(fact) && fact.scope.is_none() && !fact.local
}),
};
found
.into_iter()
.map(|declaration| {
Candidate::new(
declaration.file.clone(),
declaration.fact.clone(),
provenance_of(
index,
visible_from,
declaration.visibility,
&declaration.file,
),
)
})
.collect()
}
pub(crate) fn name_starts_with(fact: &DeclFact, written: &str) -> bool {
if written.is_empty() {
return true;
}
let name = fact.name.as_str();
name.len() >= written.len()
&& name
.chars()
.zip(written.chars())
.all(|(have, wanted)| have.eq_ignore_ascii_case(&wanted))
}
pub(crate) fn declarations_in(
spelling: &str,
index: &ProjectIndex,
visible_from: &Path,
written: &str,
) -> Vec<Candidate> {
declarations_in_scope(index, visible_from, Some(spelling), written)
}
pub(crate) fn provenance_of(
index: &ProjectIndex,
visible_from: &Path,
visibility: IncludeVisibility,
declaring: &Path,
) -> NameProvenance {
if visibility == IncludeVisibility::Conditional {
return NameProvenance::IndirectInclude;
}
let declaring = normalize(declaring);
let mut direct = false;
if let Some(summary) = index.summary(visible_from) {
for include in &summary.includes {
let Some(resolved) = &include.resolved else {
continue;
};
if normalize(resolved) == declaring {
direct = true;
break;
}
}
}
if direct {
return NameProvenance::DirectInclude;
}
NameProvenance::IndirectInclude
}
pub(crate) fn names_of_a_class(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<Vec<Candidate>> {
match members_of(index, scopes, root, path, class) {
Known::Yes(members) => Known::Yes(
members
.members
.into_iter()
.map(|member| {
let mut candidate =
Candidate::new(member.file, member.fact, NameProvenance::Scope);
candidate.steps = member.depth;
candidate
})
.collect(),
),
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class))),
}
}
pub(crate) fn offered(found: Vec<Candidate>, depth: usize) -> Vec<OfferedName> {
found
.into_iter()
.filter(|candidate| !candidate.fact.name.is_empty())
.filter(|candidate| !is_reserved_to_the_implementation(&candidate.fact))
.map(|candidate| OfferedName {
file: candidate.file,
fact: candidate.fact,
depth: depth.saturating_add(candidate.steps),
from: candidate.from,
})
.collect()
}
pub(crate) fn is_reserved_to_the_implementation(fact: &DeclFact) -> bool {
let name = fact.name.as_str();
let mut characters = name.chars();
if characters.next() != Some('_') {
return false;
}
match characters.next() {
Some('_') | None => true,
Some(second) if second.is_uppercase() => true,
Some(_) => fact.scope.is_none() && !fact.local,
}
}
pub(crate) fn sort_and_hide(names: &mut Vec<OfferedName>) {
names.sort_by(|one, other| {
one.depth
.cmp(&other.depth)
.then_with(|| one.fact.name.cmp(&other.fact.name))
});
let mut seen: HashSet<String> = HashSet::new();
names.retain(|name| seen.insert(name.fact.name.to_string()));
}