use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use cpp_parser::CppSyntaxKind;
use super::names::{NameIndex, Posting};
use crate::Visibility;
use crate::file::paths::normalize_path;
use crate::include::graph::Marked;
use crate::preprocess::directive::IncludeForm;
use crate::sema::types::{Type, TypeBindings, parse_type_spelling};
use crate::summary::{DeclFact, DeclKind, FactGuard, FileSummary, MacroFact};
use crate::symbol::{Known, UnknownReason};
#[cfg(test)]
#[path = "project_cache_tests.rs"]
mod cache_tests;
const MAX_VISIBILITY_DEPTH: usize = 128;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeaderTarget {
pub spelling: String,
pub form: IncludeForm,
pub range: cpp_parser::SourceRange,
pub resolved: PathBuf,
}
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> {
match definitions_across_files(index, declaring, scopes, root, path, offset) {
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,
index,
declaring,
scopes,
root,
path,
&access.object,
0,
) else {
let Known::Unknown(reason) = type_of_expression_memoed(
&memo,
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,
})
}
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 =
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())
});
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 =
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())
});
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()
&& 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,
});
}
}
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)
}
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
}
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
}
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))
}
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()
}
fn inside_a_definition_written_with_a_qualifier(
root: &cpp_parser::CppSyntaxNode,
offset: usize,
) -> bool {
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 name.contains("::") {
return true;
}
}
node = current.parent();
}
false
}
#[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),
}
}
const MAX_COOKED_FILES: usize = 512;
#[derive(Debug, Clone, Default)]
pub struct CookedFile {
pub declarations: Vec<DeclFact>,
pub macros: Vec<MacroFact>,
pub diagnostics: Vec<crate::CookedDiagnostic>,
pub unplaced: usize,
}
impl CookedFile {
pub fn declarations(declarations: Vec<DeclFact>) -> Self {
CookedFile {
declarations,
macros: Vec::new(),
diagnostics: Vec::new(),
unplaced: 0,
}
}
}
impl From<crate::IndexedRendering> for CookedFile {
fn from(indexed: crate::IndexedRendering) -> Self {
CookedFile {
declarations: indexed.summary.declarations,
macros: indexed.summary.macros,
diagnostics: indexed.diagnostics,
unplaced: indexed.unplaced,
}
}
}
#[derive(Debug, Default)]
struct Readings {
on_its_own: Option<CookedFile>,
in_a_program: Vec<(u64, CookedFile)>,
last: Option<u64>,
}
impl Readings {
fn id_for(&self, program: u64) -> Option<u32> {
self.in_a_program
.iter()
.position(|(held, _)| *held == program)
.map(|at| at as u32 + 2)
}
fn reading(&self, id: u32) -> Option<&CookedFile> {
match id {
0 => None,
1 => self.on_its_own.as_ref(),
id => self
.in_a_program
.get(id as usize - 2)
.map(|(_, reading)| reading),
}
}
const ON_ITS_OWN: u32 = 1;
fn any(&self) -> Option<&CookedFile> {
self.last
.and_then(|program| self.id_for(program))
.and_then(|id| self.reading(id))
.or(self.on_its_own.as_ref())
.or_else(|| self.in_a_program.first().map(|(_, reading)| reading))
}
fn every(&self) -> impl Iterator<Item = (u32, &CookedFile)> {
self.on_its_own
.iter()
.map(|reading| (Self::ON_ITS_OWN, reading))
.chain(
self.in_a_program
.iter()
.enumerate()
.map(|(at, (_, reading))| (at as u32 + 2, reading)),
)
}
}
#[derive(Debug, Default)]
pub struct ProjectIndex {
summaries: HashMap<String, FileSummary>,
order: BTreeMap<u32, String>,
sequence: HashMap<String, u32>,
next_sequence: u32,
changed: u64,
names: NameIndex,
included_by: HashMap<String, BTreeSet<String>>,
module_interfaces: HashMap<String, String>,
unit_closures: std::sync::Mutex<HashMap<String, Vec<String>>>,
macros: Marked,
cooked: HashMap<String, Readings>,
cooked_order: std::collections::VecDeque<String>,
visibility: std::sync::Mutex<HashMap<String, std::sync::Arc<CachedWalk>>>,
walking: std::sync::Mutex<std::collections::HashSet<String>>,
walk_done: std::sync::Condvar,
pub walks_built: std::sync::atomic::AtomicU64,
pub walks_hit: std::sync::atomic::AtomicU64,
pub walks_met: std::sync::atomic::AtomicU64,
visibility_answers: std::sync::Mutex<HashMap<(String, u32), crate::Visibility>>,
type_answers: std::sync::Mutex<HashMap<u64, Known<(Type, PathBuf)>>>,
type_hits: std::sync::atomic::AtomicU64,
type_misses: std::sync::atomic::AtomicU64,
member_lists: std::sync::Mutex<HashMap<(String, PathBuf), CachedMemberList>>,
guard_answers: std::sync::Mutex<HashMap<(PathBuf, usize, u32), crate::Visibility>>,
macro_environments: std::sync::Mutex<HashMap<(String, String), CachedMacroWalk>>,
macro_names: std::sync::Mutex<HashMap<String, CachedMacroNames>>,
definition_answers: std::sync::Mutex<HashMap<(String, String), Known<ProjectDefinitions>>>,
known_paths: std::collections::HashSet<String>,
walk_inputs: std::collections::HashMap<String, u64>,
}
pub(crate) static CONDITION_ASKS: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(0);
pub(crate) static CONDITION_NANOS: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(0);
#[derive(Debug)]
struct CachedMemberList {
contributors: Vec<PathBuf>,
list: MemberList,
read_at: usize,
}
const MAX_CACHED_MEMBER_LISTS: usize = 96;
#[derive(Debug)]
struct CachedMacroWalk {
contributors: Vec<String>,
environment: MacroEnvironment,
}
#[derive(Debug)]
struct CachedMacroNames {
contributors: Vec<String>,
names: std::collections::HashSet<String>,
}
const MAX_CACHED_MACRO_WALKS: usize = 256;
const MAX_DEFINITION_ANSWERS: usize = 4096;
const MAX_GUARD_ANSWERS: usize = 16_384;
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> {
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((written, _)) = type_of_expression_memoed(
&memo,
index,
declaring,
scopes,
root,
path,
&access.object,
0,
) else {
let Known::Unknown(reason) = type_of_expression_memoed(
&memo,
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(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 })
}
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(),
})
}
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
}
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())
}
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()?;
if written.contains("::") || written.is_empty() {
return Some(written);
}
match &found.fact.scope {
Some(scope) => Some(format!("{scope}::{written}")),
None => Some(written),
}
}
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)]
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,
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(),
};
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,
_ => listed
.members
.iter()
.find(|member| !member.fact.parameters.is_empty())
.map(|member| member.fact.parameters.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,
});
}
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.as_deref(),
&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(
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.clone()],
);
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,
}
}
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)
}
fn member_access_class_and_arguments(
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(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)>> {
direct_members(index, scopes, root, path, class)
}
pub fn members_of(
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(index, scopes, root, path, class);
let listed = match &listed {
Known::No | Known::Unknown(_) => match class.contains("::") {
true => listed,
false => match qualified_from_the_index(index, path, class) {
Some(qualified) if qualified != class => {
members_of_inner(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(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 {
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()))
}
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,
},
);
}
}
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
}
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);
}
}
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();
}
}
}
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)
});
}
}
}
fn members_of_inner(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<MemberList> {
let original = base_type_name(class).to_string();
let (resolved, _arguments, missing) =
resolve_aliases_or_unresolved(index, scopes, root, path, base_type_name(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 = (*resolved).to_string();
let own = match direct_members(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(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(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(index, scopes, root, path, &class);
let mut level: Vec<(String, String)> =
match the_base_clauses_of(index, scopes, root, path, &class) {
Known::Yes(bases) => bases
.into_iter()
.filter(|written| !names_a_template_parameter(base_type_name(written), ¶meters))
.map(|written| (written, 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;
}
let members = match direct_members(index, scopes, root, path, &base) {
Known::Yes(members) => members,
Known::Unknown(reason) => {
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(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)
})
.map(|clause| (clause, base.clone())),
),
Known::Unknown(reason) => list.unlisted.push(UnlistedBase {
spelling: base,
reason,
}),
Known::No => {}
}
}
found.retain(|member| !hidden.contains(&member.fact.name));
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)
}
fn the_base_clauses_of(
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(root, binding));
}
let base = base_type_name(class).to_string();
if let Some(declared) = index
.files_declaring(&base, path)
.into_iter()
.find(|declared| declared.fact.kind == crate::DeclKind::Type)
{
return Known::Yes(declared.fact.bases.clone());
}
bases_of(index, scopes, root, path, class)
}
fn substitute_a_base_clause(
index: &ProjectIndex,
path: &Path,
shown: &str,
clause: &str,
) -> String {
let Some((head, mut arguments)) = split_template_arguments(shown) else {
return clause.to_string();
};
let Some(declared) = index
.files_declaring(&head, path)
.into_iter()
.find(|declared| declared.fact.kind == crate::DeclKind::Type)
else {
return clause.to_string();
};
let mut names = declared.fact.parameters.clone();
names.truncate(arguments.len());
arguments.truncate(names.len());
if names.is_empty() {
return clause.to_string();
}
crate::sema::types::substituted_spelling(clause, &names, &arguments)
}
fn direct_members(
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(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::DeclarationShapes::of(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::DeclarationShapes::of(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() {
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(_)) => Known::Yes(Vec::new()),
Known::Unknown(reason) => Known::Unknown(reason),
Known::Yes(_) | Known::No => {
Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class.as_str())))
}
}
}
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
}
fn recorded_names(members: &[ProjectMember]) -> impl Iterator<Item = String> + '_ {
members
.iter()
.map(|member| member.fact.name.clone())
.filter(|name| !name.is_empty())
}
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.clone())
.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)
.is_some_and(|classes| classes.len() > 1);
}
}
#[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,
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))),
}
}
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 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.to_string();
declaration.kind = crate::DeclKind::MacroLike;
declaration.type_of = None;
declaration.returns = None;
declaration.bases.clear();
declaration.parameters.clear();
declaration.local = false;
declaration.name_range = range;
declaration.range = range;
declaration.scope = None;
declaration.in_namespace = None;
declaration.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)
}
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)
}
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
}
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
}
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)]
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(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)
}
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())
}
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()
}
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
}
struct Candidate {
file: PathBuf,
fact: DeclFact,
steps: usize,
from: NameProvenance,
}
impl Candidate {
fn new(file: PathBuf, fact: DeclFact, from: NameProvenance) -> Candidate {
Candidate {
file,
fact,
steps: 0,
from,
}
}
}
const MAX_COLLECTED_NAMES: usize = 400;
const MAX_COLLECTED_IN_A_SCOPE: usize = 4096;
const POPULAR_NAME: usize = 4096;
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()
}
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
}
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()
}
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))
}
fn declarations_in(
spelling: &str,
index: &ProjectIndex,
visible_from: &Path,
written: &str,
) -> Vec<Candidate> {
declarations_in_scope(index, visible_from, Some(spelling), written)
}
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
}
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))),
}
}
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,
}
}
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.clone()));
}
const MAX_NESTED_TYPE_DEPTH: usize = 8;
const MAX_TYPE_DEPTH: usize = 8;
const MAX_TYPE_ANSWERS: usize = 8192;
fn the_type_key(path: &Path, expression: &cpp_parser::CppSyntaxNode) -> u64 {
let range = expression.text_range();
let mut bytes: Vec<u8> = Vec::with_capacity(96);
bytes.extend_from_slice(normalize_path(path, cfg!(windows)).as_bytes());
bytes.push(0x1f);
bytes.extend_from_slice(&u64::from(u32::from(range.start())).to_le_bytes());
bytes.extend_from_slice(&u64::from(u32::from(range.end())).to_le_bytes());
let kind = cpp_parser::CppSyntaxKind::from(expression.kind());
bytes.extend_from_slice(&u64::from(kind as u16).to_le_bytes());
bytes.push(0x1e);
bytes.extend_from_slice(expression.text().to_string().as_bytes());
crate::cache::fnv1a64(&bytes)
}
fn new_expression_allocates(expression: &cpp_parser::CppSyntaxNode) -> Option<String> {
let allocated = expression.children().find(|child| {
cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::TypeId
})?;
let written = allocated.text().to_string();
let written = written.trim();
let name = match written.find('[') {
Some(at) => written[..at].trim(),
None => written,
};
(!name.is_empty()).then(|| name.to_string())
}
pub(crate) fn type_of_expression(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
depth: usize,
) -> Known<(Type, PathBuf)> {
let memo = TypeMemo::default();
type_of_expression_memoed(
&memo, index, declaring, scopes, root, path, expression, depth,
)
}
#[derive(Default)]
pub(crate) struct TypeMemo {
types: std::cell::RefCell<std::collections::HashMap<(u32, u32), Known<(Type, PathBuf)>>>,
in_flight: std::cell::RefCell<std::collections::HashSet<(u32, u32)>>,
members:
std::cell::RefCell<std::collections::HashMap<(String, String), Known<(DeclFact, PathBuf)>>>,
}
impl TypeMemo {
fn remembered_type(&self, key: &(u32, u32)) -> Option<Known<(Type, PathBuf)>> {
self.types.borrow().get(key).cloned()
}
fn enter(&self, key: (u32, u32)) -> bool {
self.in_flight.borrow_mut().insert(key)
}
fn leave(&self, key: &(u32, u32)) {
self.in_flight.borrow_mut().remove(key);
}
fn member(
&self,
class: &str,
member: &str,
look: impl FnOnce() -> Known<(DeclFact, PathBuf)>,
) -> Known<(DeclFact, PathBuf)> {
let key = (class.to_string(), member.to_string());
if let Some(known) = self.members.borrow().get(&key).cloned() {
return known;
}
let answer = look();
self.members.borrow_mut().insert(key, answer.clone());
answer
}
}
pub(crate) fn type_of_expression_memoed(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
depth: usize,
) -> Known<(Type, PathBuf)> {
let range = expression.text_range();
let key = (
u32::try_from(usize::from(range.start())).unwrap_or(u32::MAX),
u32::try_from(usize::from(range.end())).unwrap_or(u32::MAX),
);
if let Some(known) = memo.remembered_type(&key) {
return known;
}
if depth == 0
&& let Some(known) = index.a_remembered_type(path, expression)
{
memo.types.borrow_mut().insert(key, known.clone());
return known;
}
if !memo.enter(key) {
let written = expression
.text()
.to_string()
.lines()
.next()
.unwrap_or_default()
.to_string();
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
}
let started = std::time::Instant::now();
if crate::probes::types() {
eprintln!(
"[type_of] depth {depth:>2} {:?}",
expression
.text()
.to_string()
.lines()
.next()
.unwrap_or_default()
.chars()
.take(60)
.collect::<String>()
);
}
let answer = type_of_expression_inner(
memo, index, declaring, scopes, root, path, expression, depth,
);
if crate::probes::timing() && started.elapsed().as_millis() > 5 {
eprintln!(
"[type_of] {:>5} ms depth {depth} {:?}",
started.elapsed().as_millis(),
expression
.text()
.to_string()
.lines()
.next()
.unwrap_or_default()
);
}
memo.leave(&key);
if depth == 0 {
index.remember_a_type(path, expression, &answer);
}
memo.types.borrow_mut().insert(key, answer.clone());
answer
}
fn type_of_expression_inner(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
depth: usize,
) -> Known<(Type, PathBuf)> {
let text = expression.text().to_string();
let written = text.trim();
if depth > MAX_TYPE_DEPTH {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
}
if let Some(operand) = a_co_awaits_operand(expression) {
let awaited = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&operand,
depth + 1,
);
if let Known::Yes((awaiter, _)) = awaited
&& let Some(returns) = operator_returns_of(
index,
declaring,
scopes,
root,
path,
&awaiter,
"await_resume",
)
&& !returns.trim().is_empty()
{
let settled = crate::sema::types::parse_type_spelling(&returns);
return Known::Yes((settled, path.to_path_buf()));
}
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
}
if let Some((kind, written_as)) = expression
.children_with_tokens()
.filter_map(|element| element.into_token())
.map(|token| {
(
cpp_parser::CppTokenKind::from(token.kind()),
token.text().to_string(),
)
})
.find(|(kind, _)| {
!matches!(
kind,
cpp_parser::CppTokenKind::Whitespace | cpp_parser::CppTokenKind::Newline
)
})
{
let literal = match kind {
cpp_parser::CppTokenKind::IntegerLiteral | cpp_parser::CppTokenKind::CharLiteral => {
Some("int")
}
cpp_parser::CppTokenKind::FloatingLiteral => Some("double"),
cpp_parser::CppTokenKind::BoolLiteral
| cpp_parser::CppTokenKind::TrueKeyword
| cpp_parser::CppTokenKind::FalseKeyword => Some("bool"),
cpp_parser::CppTokenKind::StringLiteral => Some(a_string_literals_type(&written_as)),
cpp_parser::CppTokenKind::NullptrLiteral | cpp_parser::CppTokenKind::NullptrKeyword => {
Some("nullptr_t")
}
cpp_parser::CppTokenKind::UserDefinedLiteral => None,
_ => None,
};
if kind == cpp_parser::CppTokenKind::UserDefinedLiteral {
let a_user_defined_literal_is = |returns: String| {
Known::Yes((
crate::sema::types::parse_type_spelling(&returns),
path.to_path_buf(),
))
};
if let Some(suffix) = a_user_defined_literals_suffix(&written_as)
&& let Some(declared) = index
.files_declaring(&format!("operator\"\"{suffix}"), path)
.into_iter()
.find(|declared| declared.fact.kind == crate::DeclKind::Function)
&& let Some(returns) = declared.fact.returns.as_deref()
&& !returns.trim().is_empty()
{
return a_user_defined_literal_is(returns.to_string());
}
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
}
if let Some(spelled) = literal {
return Known::Yes((
crate::sema::types::parse_type_spelling(spelled),
path.to_path_buf(),
));
}
}
fn a_user_defined_literals_suffix(written: &str) -> Option<&str> {
let written = written.trim_end();
let run_start = written
.rfind(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
.map(|boundary| boundary + 1)
.unwrap_or(0);
let run = &written[run_start..];
if run.is_empty() {
return None;
}
if let Some(underscore) = run.rfind('_') {
let suffix = &run[underscore..];
return (suffix.len() > 1).then_some(suffix);
}
run.find(|character: char| character.is_ascii_alphabetic())
.map(|at| &run[at..])
}
fn a_string_literals_type(written: &str) -> &'static str {
let written = written.trim_start();
if written.starts_with("u8") {
return "const char*";
}
if written.starts_with('L') {
return "const wchar_t*";
}
if written.starts_with('u') {
return "const char16_t*";
}
if written.starts_with('U') {
return "const char32_t*";
}
"const char*"
}
if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::CallExpr
&& let Some(callee) = written.strip_suffix("()")
&& callee.contains('<')
&& !callee.chars().any(char::is_whitespace)
&& index
.files_declaring(callee.split('<').next().unwrap_or(callee).trim(), path)
.iter()
.any(|declared| declared.fact.kind == crate::DeclKind::Type)
&& !callee
.split("::")
.next()
.unwrap_or(callee)
.split('<')
.next()
.unwrap_or(callee)
.chars()
.all(|character| !character.is_ascii_lowercase())
{
return Known::Yes((Type::named(callee.trim()), path.to_path_buf()));
}
if written == "this" {
let offset = usize::from(expression.text_range().start());
return match class_of_the_enclosing_definition(scopes, offset) {
Some(class) => Known::Yes((Type::named(class), path.to_path_buf())),
None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::NewExpr {
return match new_expression_allocates(expression) {
Some(allocated) => Known::Yes((
crate::sema::types::parse_type_spelling(&format!("{allocated}*")),
path.to_path_buf(),
)),
None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if let Some(answer) = structured_binding_type(
memo, index, declaring, scopes, root, path, expression, depth,
) {
return answer;
}
if writes_a_name(written) {
return match declaration_of_expression(index, scopes, root, path, expression) {
Known::Yes(named) => {
let dt = declared_type(memo, index, declaring, scopes, root, path, &named, depth);
match dt {
Known::Yes(type_of) => {
let type_of =
a_trait_alias_resolved(index, scopes, root, path, &named, &type_of)
.unwrap_or(type_of);
Known::Yes((
substituted_at_the_use(
index, scopes, root, path, expression, &named, type_of,
),
named.file(path),
))
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
}
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::InitListExpr
{
let Some(first) = expression.children().next() else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
};
let has_a_head = cpp_parser::CppSyntaxKind::from(first.kind())
!= cpp_parser::CppSyntaxKind::InitListExpr
&& expression.children().nth(1).is_some_and(|child| {
cpp_parser::CppSyntaxKind::from(child.kind())
== cpp_parser::CppSyntaxKind::InitListExpr
});
return match type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&first,
depth + 1,
) {
Known::Yes(_) if !has_a_head => {
Known::Unknown(UnknownReason::UnknownType(Box::from(written)))
}
_ => match declaration_of_expression(index, scopes, root, path, &first) {
Known::Yes(named) if named.type_of(root, scopes).is_none() => {
let spelled = first.text().to_string();
let spelled = spelled.trim();
let elements = the_elements_of_a_braced_list(expression);
let settled = the_arguments_a_braced_initialisation_deduces(
memo, index, declaring, scopes, root, path, &elements, spelled, depth,
)
.unwrap_or_else(|| crate::sema::types::parse_type_spelling(spelled));
Known::Yes((settled, named.file(path)))
}
_ => match a_type_the_expression_names(index, path, &first) {
Some(spelled) => {
let elements = the_elements_of_a_braced_list(expression);
let settled = the_arguments_a_braced_initialisation_deduces(
memo, index, declaring, scopes, root, path, &elements, &spelled, depth,
)
.unwrap_or_else(|| crate::sema::types::parse_type_spelling(&spelled));
Known::Yes((settled, path.to_path_buf()))
}
None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
},
},
};
}
if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::CallExpr {
return type_of_a_call(memo, index, declaring, scopes, root, path, expression);
}
if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::CastExpr {
let target = expression
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TypeId);
return match target {
Some(target) => {
let written = target.text().to_string();
let written = written.trim();
Known::Yes((
crate::sema::types::parse_type_spelling(written),
path.to_path_buf(),
))
}
None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::TernaryExpr
{
let branches: Vec<cpp_parser::CppSyntaxNode> = expression.children().collect();
if let (Some(one), Some(other)) = (branches.get(1), branches.get(2)) {
let one_type = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
one,
depth + 1,
);
let other_type = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
other,
depth + 1,
);
if let (Known::Yes((one_type, file)), Known::Yes((other_type, _))) =
(one_type, other_type)
{
let agreed = if one_type == other_type {
Some(one_type.clone())
} else {
crate::sema::declarations::the_widest_of(&[one_type, other_type])
.map(|widest| crate::sema::types::parse_type_spelling(&widest))
};
if let Some(agreed) = agreed {
return Known::Yes((agreed, file));
}
}
}
}
{
let spelled = expression.text().to_string();
let spelled = spelled.trim_start();
if spelled.starts_with("sizeof") || spelled.starts_with("alignof") {
return Known::Yes((
crate::sema::types::parse_type_spelling("size_t"),
path.to_path_buf(),
));
}
}
if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::ParenExpr {
return match expression.children().next() {
Some(inner) => type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&inner,
depth + 1,
),
None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if let Some((operator, left, right)) = binary_operands_of(expression) {
if !matches!(
operator.as_str(),
"=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>="
) && let Known::Yes((left_class, file)) =
type_of_expression_memoed(memo, index, declaring, scopes, root, path, &left, depth + 1)
&& matches!(left_class, Type::Named { .. })
&& let Some(returns) = operator_returns_of(
index,
declaring,
scopes,
root,
path,
&left_class,
&format!("operator{operator}"),
)
{
return Known::Yes((crate::sema::types::parse_type_spelling(&returns), file));
}
if matches!(
operator.as_str(),
"==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||"
) {
return Known::Yes((Type::named("bool"), path.to_path_buf()));
}
let left_type =
type_of_expression_memoed(memo, index, declaring, scopes, root, path, &left, depth + 1);
if matches!(
operator.as_str(),
"=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>="
) {
return left_type;
}
let Known::Yes((left_type, file)) = left_type else {
return match left_type {
Known::Unknown(reason) => Known::Unknown(reason),
_ => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
};
return match type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&right,
depth + 1,
) {
Known::Yes((right_type, _)) if right_type == left_type => {
if operator == "-" && left_type.pointee().is_some() {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
}
Known::Yes((left_type, file))
}
Known::Yes(_) => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if let Some(operand) = unary_operand_with(expression, "*") {
let operand_type = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&operand,
depth + 1,
);
return match operand_type {
Known::Yes((type_of, file)) => match type_of.pointee() {
Some(pointee)
if !matches!(type_of, Type::Named { .. } | Type::TemplateParameter { .. }) =>
{
Known::Yes(((*pointee).clone(), file))
}
Some(_) | None => {
if let Some(returns) = operator_returns_of(
index,
declaring,
scopes,
root,
path,
&type_of,
"operator*",
) {
return Known::Yes((
crate::sema::types::parse_type_spelling(&returns),
file,
));
}
match &type_of {
Type::Named { .. } | Type::TemplateParameter { .. } => {
Known::Yes((type_of, file))
}
_ => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
}
}
},
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if let Some(operand) = unary_operand_with(expression, "&") {
let operand_type = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&operand,
depth + 1,
);
return match operand_type {
Known::Yes((type_of, file)) => {
let pointed_at = type_of.decay();
Known::Yes((
Type::Pointer {
to: Arc::new(pointed_at),
},
file,
))
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
for symbol in ["-", "+", "~", "!"] {
let Some(operand) = unary_operand_with(expression, symbol) else {
continue;
};
let operand_type = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&operand,
depth + 1,
);
return match operand_type {
Known::Yes((type_of, file)) => {
if matches!(type_of, Type::Named { .. } | Type::TemplateParameter { .. })
&& let Some(returns) = operator_returns_of(
index,
declaring,
scopes,
root,
path,
&type_of,
&format!("operator{symbol}"),
)
{
return Known::Yes((crate::sema::types::parse_type_spelling(&returns), file));
}
if symbol == "!" {
Known::Yes((Type::named("bool"), path.to_path_buf()))
} else {
Known::Yes((type_of, file))
}
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if CppSyntaxKind::from(expression.kind()) == CppSyntaxKind::TernaryExpr {
let arms: Vec<cpp_parser::CppSyntaxNode> = expression.children().collect();
let (Some(then_arm), Some(else_arm)) = (arms.get(1), arms.get(2)) else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
};
let then_type = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
then_arm,
depth + 1,
);
let else_type = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
else_arm,
depth + 1,
);
return match (then_type, else_type) {
(Known::Yes((then_type, file)), Known::Yes((else_type, _)))
if then_type == else_type =>
{
Known::Yes((then_type, file))
}
(Known::Yes(_), Known::Yes(_)) => {
Known::Unknown(UnknownReason::UnknownType(Box::from(written)))
}
(Known::Unknown(reason), _) | (_, Known::Unknown(reason)) => Known::Unknown(reason),
_ => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if let Some(base) = subscript_base(expression) {
let base_type =
type_of_expression_memoed(memo, index, declaring, scopes, root, path, &base, depth + 1);
return match base_type {
Known::Yes((type_of, file)) => match type_of.pointee() {
Some(element) if matches!(type_of, Type::Pointer { .. }) => {
Known::Yes(((*element).clone(), file))
}
Some(element) if matches!(type_of, Type::Array { .. }) => {
Known::Yes(((*element).clone(), file))
}
_ => match operator_returns_of(
index,
declaring,
scopes,
root,
path,
&type_of,
"operator[]",
) {
Some(returns) => {
let written = a_members_answer_as_a_type(
index, scopes, root, path, &type_of, &returns,
);
if crate::probes::inference() {
eprintln!(
"[inference] subscript on {:?}: the member wrote {:?}, the type is {:?}",
type_of.to_string(),
returns,
written
);
}
Known::Yes((crate::sema::types::parse_type_spelling(&written), file))
}
None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
},
},
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if let Some(inner) = crate::sema::resolve::member_access_of(expression) {
let (inner_type, declared_in) = match type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&inner.object,
depth + 1,
) {
Known::Yes((inner_type, declared_in)) => (inner_type, declared_in),
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => {
return Known::Unknown(UnknownReason::UnknownType(Box::from(
inner.object.text().to_string().trim(),
)));
}
};
let reached_by_an_arrow = inner.arrow.then(|| {
crate::completion::the_class_after_the_operator(
index,
scopes,
root,
path,
&inner_type,
true,
)
});
let reached_by_an_arrow = reached_by_an_arrow.flatten();
let Some(class) = reached_by_an_arrow
.clone()
.map(|(reached, _)| reached)
.or_else(|| member_access_class(&inner_type))
else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(
inner_type.to_string(),
)));
};
let (class, arguments) =
member_access_class_and_arguments(index, scopes, root, path, &class, &inner_type);
let (class, arguments) = match inner.arrow {
true => the_pointee_of_a_handle(index, scopes, root, path, &class, &arguments)
.or_else(|| {
reached_by_an_arrow
.clone()
.map(|(reached, _)| (reached, Vec::new()))
})
.unwrap_or((class, arguments)),
false => (class, arguments),
};
let written_arguments: Vec<String> = arguments
.iter()
.map(|argument| argument.to_string())
.collect();
let found = memo.member(&class, &inner.member, || {
member_fact(
index,
scopes,
root,
path,
&class,
&inner.member,
Some(&written_arguments),
)
});
let found = match found {
Known::Yes(found) => Known::Yes(found),
Known::Unknown(reason) => match declared_class(index, &declared_in, &class) {
Some(qualified) => {
match memo.member(&qualified, &inner.member, || {
member_fact(
index,
scopes,
root,
path,
&qualified,
&inner.member,
Some(&written_arguments),
)
}) {
Known::Yes(found) => Known::Yes(found),
Known::Unknown(_) | Known::No => Known::Unknown(reason),
}
}
None => Known::Unknown(reason),
},
Known::No => Known::No,
};
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);
};
let arguments = arguments.to_vec();
let bindings = member_bindings(index, scopes, root, path, &class, &arguments);
let being_called = expression.parent().is_some_and(|parent| {
cpp_parser::CppSyntaxKind::from(parent.kind()) == cpp_parser::CppSyntaxKind::CallExpr
});
if let Some(type_of) = fact.type_of.as_deref() {
if let Some((named, member)) = the_alias_behind(index, &file, type_of) {
let chain = vec![fact.name.clone()];
let inner = named
.split_once('<')
.map(|(_, rest)| rest.trim_end().strip_suffix('>').unwrap_or(rest))
.unwrap_or_default();
let argument_types: Vec<crate::sema::types::Type> =
crate::sema::builtins::split_arguments(inner)
.iter()
.map(|one| crate::sema::types::parse_type_spelling(one))
.collect();
let bare_named = named
.split_once('<')
.map(|(head, _)| head.trim())
.unwrap_or(named.as_str());
let trait_bindings =
member_bindings(index, scopes, root, path, bare_named, &argument_types);
let finished = finish_a_nested_name(
index,
scopes,
root,
path,
&named,
&trait_bindings,
parse_type_spelling(&member),
file,
chain,
);
return Known::Yes(finished);
}
let finished = bindings.applied_to(&parse_type_spelling(type_of));
return Known::Yes(finish_a_nested_name(
index,
scopes,
root,
path,
&class,
&bindings,
finished,
file,
vec![fact.name.clone()],
));
}
if being_called && let Some(returns) = what_a_call_has_in(&fact) {
return Known::Yes(finish_a_nested_name(
index,
scopes,
root,
path,
&class,
&bindings,
bindings.applied_to(&returns),
file,
vec![fact.name.clone()],
));
}
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
}
Known::Unknown(UnknownReason::UnknownType(Box::from(written)))
}
fn agreeing_type(index: &ProjectIndex, path: &Path, name: &str) -> Option<(DeclFact, PathBuf)> {
let candidates = index.files_declaring(name, path);
let mut agreeing: Option<(DeclFact, PathBuf)> = None;
for found in &candidates {
let type_of = match found.fact.kind {
crate::DeclKind::Type => found.fact.qualified_name(),
_ => found.fact.type_of.clone()?,
};
match &agreeing {
None => agreeing = Some((found.fact.clone(), found.file.clone())),
Some((first, _)) if first.type_of.as_deref() == Some(type_of.as_str()) => {}
Some((first, _))
if first.kind == crate::DeclKind::Type && first.qualified_name() == type_of => {}
Some(_) => return None,
}
}
agreeing
}
fn declared_class(index: &ProjectIndex, declaring: &Path, class: &str) -> Option<String> {
if class.contains("::") {
return None;
}
if let Some((head, rest)) = class.split_once('<')
&& let Some(inside) = rest.trim_end().strip_suffix('>')
&& let Known::Yes(found) = index.definition(head.trim(), declaring)
&& found.fact.kind == crate::DeclKind::Type
&& let Some(target) = found.fact.type_of.as_deref()
{
let written = crate::sema::builtins::split_arguments(inside);
let target =
crate::sema::types::substituted_spelling(target, &found.fact.parameters, &written);
if let Some(named) = crate::sema::types::parse_type_spelling(&target).class_name() {
return Some(named.to_string());
}
}
match index.definition(class, declaring) {
Known::Yes(found) => {
let qualified = found.fact.qualified_name();
(qualified != class).then_some(qualified)
}
Known::Unknown(_) | Known::No => None,
}
}
fn binary_operands_of(
node: &cpp_parser::CppSyntaxNode,
) -> Option<(String, cpp_parser::CppSyntaxNode, cpp_parser::CppSyntaxNode)> {
if cpp_parser::CppSyntaxKind::from(node.kind()) != cpp_parser::CppSyntaxKind::BinaryExpr {
return None;
}
let mut operands = Vec::new();
let mut operator: Option<String> = None;
for element in node.children_with_tokens() {
if let Some(token) = element.as_token() {
if operator.is_none()
&& !matches!(
cpp_parser::CppTokenKind::from(token.kind()),
cpp_parser::CppTokenKind::Whitespace | cpp_parser::CppTokenKind::Newline
)
{
operator = Some(token.text().to_string());
}
} else if let Some(child) = element.into_node() {
operands.push(child);
}
}
match (operator, operands.as_slice()) {
(Some(operator), [left, right]) => Some((operator, left.clone(), right.clone())),
_ => None,
}
}
pub(crate) fn operator_returns_of(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class_type: &Type,
operator: &str,
) -> Option<String> {
let class = class_type.class_name()?.to_string();
let declared = index.files_declaring(&class, path);
let first = declared.first()?;
if first.fact.type_of.is_some() {
return None;
}
let class_file = Some(first.file.clone());
let wanted: String = operator
.chars()
.filter(|character| !character.is_whitespace())
.collect();
let symbol = wanted.strip_prefix("operator").unwrap_or(&wanted);
let written_arguments: Vec<String> = class_type
.arguments()
.iter()
.map(|argument| argument.to_string())
.collect();
let parameters = index.template_parameters_for(&class, path, &written_arguments);
let parameter_names = ¶meters;
if crate::probes::inference() {
eprintln!(
"[inference] operator_returns_of({class}, {operator}): parameters {parameters:?}, arguments {written_arguments:?}"
);
}
for spelling in [wanted.as_str(), symbol] {
if let Known::Yes((fact, _)) = member_fact(
index,
scopes,
root,
path,
&class_type.to_string(),
spelling,
None,
) {
let returns = fact.returns?;
return Some(crate::sema::types::substituted_spelling(
&returns,
parameter_names,
&written_arguments,
));
}
}
let class_view = class_file.as_deref().and_then(declaring);
let (class_scopes, class_root, class_path) = match &class_view {
Some(view) => (view.scopes.as_ref(), &view.root, view.path.as_path()),
None => (scopes, root, path),
};
let Known::Yes(list) = members_of(
index,
class_scopes,
class_root,
class_path,
&class_type.to_string(),
) else {
return None;
};
let found = list.members.iter().find(|member| {
let name: String = member
.fact
.name
.chars()
.filter(|character| !character.is_whitespace())
.collect();
name == wanted || name == symbol
})?;
let returns = found.fact.returns.clone()?;
if found.declared_in != class
&& let Some(substituted) = a_base_operators_return(
index,
scopes,
root,
path,
&class,
&found.declared_in,
&returns,
parameter_names,
&written_arguments,
)
{
return Some(substituted);
}
Some(crate::sema::types::substituted_spelling(
&returns,
parameter_names,
&written_arguments,
))
}
fn a_co_awaits_operand(
expression: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
if cpp_parser::CppSyntaxKind::from(expression.kind()) != cpp_parser::CppSyntaxKind::UnaryExpr {
return None;
}
let mut children = expression.children_with_tokens();
let keyword = children
.find_map(|element| element.into_token())
.filter(|token| {
cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::CoAwaitKeyword
})?;
let _ = keyword;
children.find_map(|element| element.into_node())
}
fn a_bare_type_and_its_operators(written: &str) -> Option<(&str, String)> {
let trimmed = written.trim();
let name_len = trimmed
.chars()
.take_while(|character| character.is_alphanumeric() || *character == '_')
.count();
if name_len == 0 {
return None;
}
let (name, rest) = trimmed.split_at(name_len);
let suffix: String = rest
.chars()
.filter(|character| !character.is_whitespace())
.collect();
if !suffix
.chars()
.all(|character| matches!(character, '*' | '&'))
{
return None;
}
Some((name, suffix))
}
fn a_base_operators_return(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
declared_in: &str,
returns: &str,
parameter_names: &[String],
written_arguments: &[String],
) -> Option<String> {
let Known::Yes(_) = bases_of(index, scopes, root, path, class) else {
return None;
};
let (parameters, arguments) = the_arguments_of_a_base(
index,
scopes,
root,
path,
class,
declared_in,
parameter_names,
written_arguments,
0,
)?;
if let Some((name, suffix)) = a_bare_type_and_its_operators(returns)
&& let Known::Yes((alias, _)) =
member_fact(index, scopes, root, path, declared_in, name, None)
&& let Some(target) = alias.type_of.clone()
{
let substituted =
crate::sema::types::substituted_spelling(&target, ¶meters, &arguments);
return Some(format!("{substituted}{suffix}"));
}
Some(crate::sema::types::substituted_spelling(
returns,
¶meters,
&arguments,
))
}
fn the_arguments_of_a_base(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
wanted: &str,
parameters: &[String],
arguments: &[String],
depth: usize,
) -> Option<(Vec<String>, Vec<String>)> {
if depth > 6 {
return None;
}
let leaf = |spelling: &str| spelling.rsplit("::").next().unwrap_or(spelling).to_string();
let Known::Yes(bases) = bases_of(index, scopes, root, path, class) else {
return None;
};
let mut at = 0usize;
while at < bases.len() {
let written = &bases[at];
let resolved = resolved_in_the_enclosing_scopes(index, scopes, path, class, written);
let arity = index.template_parameters_for(&resolved, path, &[]).len();
let of_the_base: Vec<String> = bases
.iter()
.skip(at + 1)
.take(arity)
.map(|argument| {
crate::sema::types::substituted_spelling(argument, parameters, arguments)
})
.collect();
let of_the_base_parameters = index.template_parameters_for(&resolved, path, &of_the_base);
if leaf(&resolved) == leaf(wanted) {
return Some((of_the_base_parameters, of_the_base));
}
if let Some(found) = the_arguments_of_a_base(
index,
scopes,
root,
path,
&resolved,
wanted,
&of_the_base_parameters,
&of_the_base,
depth + 1,
) {
return Some(found);
}
at += 1 + arity;
}
None
}
fn unary_operand_with(
node: &cpp_parser::CppSyntaxNode,
operator: &str,
) -> Option<cpp_parser::CppSyntaxNode> {
if cpp_parser::CppSyntaxKind::from(node.kind()) != cpp_parser::CppSyntaxKind::UnaryExpr {
return None;
}
let first = node.children_with_tokens().next()?;
if first
.as_token()
.is_none_or(|token| token.text() != operator)
{
return None;
}
node.children().next()
}
fn subscript_base(node: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSyntaxNode> {
if cpp_parser::CppSyntaxKind::from(node.kind()) != cpp_parser::CppSyntaxKind::IndexExpr {
return None;
}
let has_brackets = node
.children_with_tokens()
.any(|element| element.as_token().is_some_and(|token| token.text() == "["));
if !has_brackets {
return None;
}
node.children().next()
}
fn pointee_type_name(written: &str) -> Option<String> {
let mut name = written.trim().to_string();
loop {
let trimmed = name.trim_end();
let Some(rest) = trimmed
.strip_suffix("const")
.or_else(|| trimmed.strip_suffix("volatile"))
else {
break;
};
name = rest.trim_end().to_string();
}
let trimmed = name.trim_end();
let stripped = trimmed
.strip_suffix("&&")
.or_else(|| trimmed.strip_suffix('*'))
.or_else(|| trimmed.strip_suffix('&'))?;
let pointee = stripped.trim().to_string();
(!pointee.is_empty()).then_some(pointee)
}
#[allow(clippy::large_enum_variant)]
enum NamedDeclaration {
Here(crate::Binding),
Indexed(DeclFact, PathBuf, TypeBindings),
}
impl NamedDeclaration {
fn file(&self, here: &Path) -> PathBuf {
match self {
NamedDeclaration::Here(_) => here.to_path_buf(),
NamedDeclaration::Indexed(_, file, _) => file.clone(),
}
}
fn fact_kind(&self) -> crate::DeclKind {
match self {
NamedDeclaration::Here(binding) => match binding.kind {
crate::sema::symbol::BindingKind::Function
| crate::sema::symbol::BindingKind::Constructor
| crate::sema::symbol::BindingKind::Destructor
| crate::sema::symbol::BindingKind::ConversionFunction
| crate::sema::symbol::BindingKind::OperatorFunction
| crate::sema::symbol::BindingKind::LiteralOperator => crate::DeclKind::Function,
_ => crate::DeclKind::Variable,
},
NamedDeclaration::Indexed(fact, _, _) => fact.kind,
}
}
fn type_of(&self, root: &cpp_parser::CppSyntaxNode, scopes: &crate::ScopeTree) -> Option<Type> {
match self {
NamedDeclaration::Here(binding) => {
if matches!(
binding.kind,
crate::BindingKind::Function
| crate::BindingKind::Constructor
| crate::BindingKind::Destructor
| crate::BindingKind::ConversionFunction
| crate::BindingKind::OperatorFunction
| crate::BindingKind::LiteralOperator
) {
return None;
}
if binding.kind == crate::BindingKind::Enumerator {
return scopes
.scope(binding.scope)
.and_then(|scope| scope.name.clone())
.map(Type::named);
}
let declarator =
crate::sema::types::declarator_declaring(root, binding.name_range)?;
let specifiers = declarator.ancestors().find_map(|node| {
node.children().find(|child| {
CppSyntaxKind::from(child.kind()) == CppSyntaxKind::DeclSpecifierSeq
})
})?;
let written = crate::sema::types::type_of_declaration_named(
&specifiers,
Some(&declarator),
binding.name_range,
binding.name.identifier_text(),
matches!(binding.kind, crate::BindingKind::Variable),
);
let keyed_by_the_declarator = scopes
.scope_at(binding.name_range.start_offset)
.is_some_and(|scope| {
scopes.scope_chain(scope).into_iter().any(|id| {
scopes
.scope(id)
.is_some_and(|data| data.kind == crate::ScopeKind::Function)
})
});
match (
written.to_string().is_empty(),
an_unnamed_class_body(&specifiers),
) {
(true, Some(_)) if keyed_by_the_declarator => {
Some(Type::named(binding.name.identifier_text()?))
}
_ => Some(written),
}
}
NamedDeclaration::Indexed(fact, _, bindings) => {
let _ = scopes;
fact.type_of
.as_deref()
.map(|written| bindings.applied_to(&parse_type_spelling(written)))
}
}
}
fn what_a_call_has(
&self,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
written_arguments: &[Type],
argument_types: &[Type],
) -> Option<Type> {
let deduced;
let written_arguments = if written_arguments.is_empty() && !argument_types.is_empty() {
let (names, written_list) = self.parameters_of(index, scopes, root, path);
deduced = deduce_the_parameters(&names, written_list.as_deref(), argument_types);
&deduced[..]
} else {
written_arguments
};
match self {
NamedDeclaration::Here(binding) => {
if binding.kind == crate::BindingKind::Class {
return binding.name.identifier_text().map(Type::named);
}
let names_for_the_call =
crate::sema::declarations::declared_template_parameters_of(root, binding);
let returns = match crate::sema::declarations::declared_returns_of(root, binding)
.filter(|returns| !is_a_placeholder(returns))
{
Some(returns) => parse_type_spelling(&returns),
None => {
let substitutions = crate::sema::types::TypeSubstitutions::new(
&names_for_the_call,
written_arguments,
);
let written = crate::sema::declarations::deduced_returns_of_substituted(
root,
binding.clone(),
&substitutions,
argument_types,
)?;
parse_type_spelling(&written)
}
};
let names =
crate::sema::declarations::declared_template_parameters_of(root, binding);
if names.is_empty() || written_arguments.is_empty() {
return Some(returns);
}
let substitutions =
crate::sema::types::TypeSubstitutions::new(&names, written_arguments);
Some(returns.substituted(&substitutions))
}
NamedDeclaration::Indexed(fact, file, bindings) => {
let name = fact.name.clone();
let offset = fact.name_range.start_offset;
let returns = match what_a_call_has_in(fact) {
Some(returns) => returns,
None => {
let substitutions = crate::sema::types::TypeSubstitutions::new(
&fact.parameters,
written_arguments,
);
let declared_in = declaring(file.as_path())?;
let found = [
declared_in.reading_offset_of(
crate::file::coordinates::FileOffset::new(offset),
),
Some(crate::file::coordinates::ReadingOffset::new(offset)),
]
.into_iter()
.flatten()
.find_map(|in_the_reading| {
match crate::sema::resolve::definition_at(
&declared_in.scopes,
&declared_in.root,
in_the_reading.get(),
) {
Known::Yes(found)
if found.name.identifier_text() == Some(name.as_str()) =>
{
Some(found)
}
_ => None,
}
});
let binding = found?;
let written = crate::sema::declarations::deduced_returns_of_substituted(
&declared_in.root,
binding,
&substitutions,
argument_types,
)?;
parse_type_spelling(&written)
}
};
let _ = &name;
let started = bindings.applied_to(&returns);
let started = if fact.parameters.is_empty() || written_arguments.is_empty() {
started
} else {
let substitutions = crate::sema::types::TypeSubstitutions::new(
&fact.parameters,
written_arguments,
);
started.substituted(&substitutions)
};
let started = match started.class_name() {
Some(name)
if started.arguments().is_empty()
&& !bindings.arguments().is_empty()
&& fact
.scope
.as_deref()
.is_some_and(|scope| scope.rsplit("::").next() == Some(name)) =>
{
let arguments: Vec<String> = bindings
.arguments()
.iter()
.map(|argument| argument.to_string())
.collect();
crate::sema::types::parse_type_spelling(&format!(
"{name}<{}>",
arguments.join(", ")
))
}
_ => started,
};
let Some(class) = fact.scope.as_deref() else {
return Some(started);
};
let (finished, _) = finish_a_nested_name(
index,
scopes,
root,
path,
class,
bindings,
started,
file.clone(),
vec![fact.name.clone()],
);
Some(finished)
}
}
}
fn parameters_of(
&self,
index: &ProjectIndex,
_scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
_path: &Path,
) -> (Vec<String>, Option<String>) {
let _ = index;
match self {
NamedDeclaration::Here(binding) => (
crate::sema::declarations::declared_template_parameters_of(root, binding),
crate::sema::declarations::parameter_list_at(root, binding.name_range.start_offset),
),
NamedDeclaration::Indexed(fact, _, _) => {
(fact.parameters.clone(), fact.parameter_list.clone())
}
}
}
fn parameter_defaults_of(
&self,
_index: &ProjectIndex,
root: &cpp_parser::CppSyntaxNode,
) -> Vec<String> {
match self {
NamedDeclaration::Here(binding) => {
crate::sema::declarations::declared_parameter_defaults_of(root, binding)
}
NamedDeclaration::Indexed(fact, _, _) => fact.parameter_defaults.clone(),
}
}
fn name_offset(&self) -> usize {
match self {
NamedDeclaration::Here(binding) => binding.name_range.start_offset,
NamedDeclaration::Indexed(fact, _, _) => fact.name_range.start_offset,
}
}
fn parameter_list(&self) -> Option<String> {
match self {
NamedDeclaration::Here(_) => None,
NamedDeclaration::Indexed(fact, _, _) => fact.parameter_list.clone(),
}
}
}
#[allow(clippy::too_many_arguments)]
fn finish_a_nested_name(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
bindings: &crate::sema::types::TypeBindings,
mut current: Type,
mut current_file: PathBuf,
mut asked: Vec<String>,
) -> (Type, PathBuf) {
for _ in 0..MAX_NESTED_TYPE_DEPTH {
let class_with_arguments = if bindings.is_empty() || class.contains('<') {
class.to_string()
} else {
let arguments: Vec<String> = bindings
.arguments()
.iter()
.map(|argument| argument.to_string())
.collect();
format!("{class}<{}>", arguments.join(", "))
};
let class = class_with_arguments.as_str();
let spelling = current.to_string();
if spelling.contains("::") && !asked.contains(&spelling) {
let resolved = a_spelling_through_the_aliases(
index,
scopes,
root,
path,
&crate::sema::types::parse_type_spelling(class),
&spelling,
MAX_ALIAS_HOPS,
);
if resolved != spelling {
asked.push(spelling);
current = bindings.applied_to(&crate::sema::types::parse_type_spelling(&resolved));
continue;
}
}
let Some(nested) = current.class_name().map(str::to_string) else {
break;
};
if !writes_a_name(&nested) || asked.contains(&nested) {
break;
}
asked.push(nested.clone());
let found = match member_fact(index, scopes, root, path, class, &nested, None) {
Known::Yes(found) => Known::Yes(found),
miss => match the_head_and_the_member_of(&nested) {
Some((head, tail)) => {
let head = resolve_aliases(index, scopes, root, path, head).to_string();
let arguments: Vec<String> = parse_type_spelling(&head)
.arguments()
.iter()
.map(|argument| argument.to_string())
.collect();
match member_fact(
index,
scopes,
root,
path,
&head,
tail,
(!arguments.is_empty()).then_some(&arguments),
) {
Known::Yes(found) => Known::Yes(found),
_ => miss,
}
}
None => miss,
},
};
let Known::Yes((inner, inner_file)) = found else {
break;
};
let Some(inner_type) = inner.type_of.as_deref() else {
break;
};
let resolved = bindings.applied_to(&parse_type_spelling(inner_type));
current = current.replacing(&nested, &resolved);
current_file = inner_file;
}
(current, current_file)
}
fn the_head_and_the_member_of(nested: &str) -> Option<(&str, &str)> {
let mut depth = 0usize;
let mut boundary = None;
let bytes = nested.as_bytes();
let mut at = 0usize;
while at + 1 < bytes.len() {
match bytes[at] {
b'<' => depth += 1,
b'>' => depth = depth.saturating_sub(1),
b':' if depth == 0 && bytes[at + 1] == b':' => {
boundary = Some(at);
at += 1;
}
_ => {}
}
at += 1;
}
let boundary = boundary?;
let head = nested[..boundary].trim();
let tail = nested[boundary + 2..].trim();
(!head.is_empty() && !tail.is_empty()).then_some((head, tail))
}
fn a_trait_alias_resolved(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
named: &NamedDeclaration,
written: &Type,
) -> Option<Type> {
let spelling = written.to_string();
if !spelling.contains('<') {
return None;
}
let (class, member) = the_alias_behind(index, &named.file(path), &spelling)?;
let Known::Yes((fact, _)) = member_fact(index, scopes, root, path, &class, &member, None)
else {
return None;
};
let target = fact.type_of.as_deref()?;
let arguments: Vec<String> = crate::sema::types::parse_type_spelling(&class)
.arguments()
.iter()
.map(|one| one.to_string())
.collect();
let bare = crate::sema::types::parse_type_spelling(&class);
let class_name = bare.class_name()?;
let parameters = index.template_parameters_for(class_name, path, &arguments);
let defaults = index.template_parameter_defaults_for(class_name, path, &arguments);
let resolved = crate::sema::types::substituted_spelling_with_defaults(
target,
¶meters,
&defaults,
&arguments,
);
Some(crate::sema::types::parse_type_spelling(&resolved))
}
fn declared_type(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
named: &NamedDeclaration,
depth: usize,
) -> Known<Type> {
if let NamedDeclaration::Indexed(fact, _, _) = named
&& fact.type_of.is_none()
&& fact.kind == crate::DeclKind::Variable
&& let Some(scope) = fact.scope.as_deref()
&& let Known::Yes(enclosing) = index.definition(scope, path)
&& enclosing.fact.kind == crate::DeclKind::Type
{
return Known::Yes(Type::named(scope));
}
let declaration = named.type_of(root, scopes);
let Some(declaration) = declaration else {
return Known::No;
};
let placeholder = declaration.to_string();
if let crate::sema::types::Type::Named { name, arguments } = &declaration
&& arguments.is_empty()
&& !name.contains('<')
{
if let Some(initialisation) = the_braced_initialiser_of(root, named) {
let elements: Vec<cpp_parser::CppSyntaxNode> = initialisation.children().collect();
if let Some(with_arguments) = the_arguments_a_braced_initialisation_deduces(
memo,
index,
declaring,
scopes,
root,
path,
&elements,
name,
depth + 1,
) {
return Known::Yes(with_arguments);
}
}
if let Known::Yes((from_the_initializer, _)) =
initializer_type(memo, index, declaring, scopes, root, path, named, depth + 1)
&& let Some(with_arguments) = deduced_class_template_arguments(
index,
scopes,
root,
path,
declaring,
name,
&from_the_initializer,
)
{
return Known::Yes(crate::sema::types::parse_type_spelling(&with_arguments));
}
}
if let Some(payload) = a_typeof_payload(root, named)
&& let Known::Yes((type_of, _)) = type_of_expression(
index,
&mut |_: &Path| None,
scopes,
root,
path,
&payload,
depth + 1,
)
{
return Known::Yes(type_of);
}
if !writes_auto(&placeholder) {
return Known::Yes(declaration);
}
let unknown = || Known::Unknown(UnknownReason::UnknownType(Box::from(placeholder.clone())));
if let Some(element) =
range_for_element_type(memo, index, declaring, scopes, root, path, named, depth)
{
return element;
}
let Some((as_written, initializer)) = deduction_inputs(root, named) else {
return unknown();
};
let deduced =
match initializer_type(memo, index, declaring, scopes, root, path, named, depth + 1) {
Known::Yes((deduced, _)) => deduced,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => return unknown(),
};
match auto_substituted(&as_written, &deduced, an_lvalue(&initializer)) {
Some(type_of) => Known::Yes(parse_type_spelling(&type_of)),
None => unknown(),
}
}
fn an_lvalue(expression: &cpp_parser::CppSyntaxNode) -> bool {
use cpp_parser::CppSyntaxKind::{CallExpr, InitListExpr, LiteralExpr, NewExpr, ParenExpr};
let kind = cpp_parser::CppSyntaxKind::from(expression.kind());
if matches!(kind, LiteralExpr | CallExpr | InitListExpr | NewExpr) {
return false;
}
if kind == ParenExpr
&& let Some(inner) = expression.children().next()
{
return an_lvalue(&inner);
}
true
}
fn writes_auto(written: &str) -> bool {
written
.split(|character: char| !character.is_alphanumeric() && character != '_')
.any(|word| word == "auto" || word == "__auto_type")
}
fn range_for_element_type(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
named: &NamedDeclaration,
depth: usize,
) -> Option<Known<Type>> {
let NamedDeclaration::Here(binding) = named else {
return None;
};
let declared_at = binding.name_range.start_offset;
let loop_node = cpp_parser::token_at(root, declared_at)?
.parent_ancestors()
.find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::RangeForStat
})?;
let range = range_expression_of_the_pattern(&loop_node)?;
if let Some(element) = element_of_a_range_expression(
memo,
index,
declaring,
scopes,
root,
path,
&range,
depth + 1,
) {
return Some(element.map(|(type_of, _)| type_of));
}
let Known::Yes((container, _)) = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&range,
depth + 1,
) else {
return Some(Known::Unknown(UnknownReason::UnknownType(Box::from(
"auto",
))));
};
Some(match range_element_of(&container) {
Some(element) => Known::Yes(crate::sema::types::parse_type_spelling(&element)),
None => Known::Unknown(UnknownReason::UnknownType(Box::from(container.to_string()))),
})
}
fn element_of_a_range_expression(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
depth: usize,
) -> Option<Known<(Type, PathBuf)>> {
if let Some((left, right)) = the_two_operands_of_a_pipe(expression)
&& let Some(left_element) = element_of_a_range_expression(
memo,
index,
declaring,
scopes,
root,
path,
&left,
depth + 1,
)
{
return Some(adapted_element(&left_element, &right, index, path));
}
if CppSyntaxKind::from(expression.kind()) != CppSyntaxKind::BinaryExpr
&& a_call_to_a_function(expression).is_none()
&& let Known::Yes((container, file)) = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
expression,
depth + 1,
)
&& let Some(element) = range_element_of(&container)
{
return Some(Known::Yes((
crate::sema::types::parse_type_spelling(&element),
file,
)));
}
if let Some(callee) = a_call_to_a_function(expression) {
let written = callee.text().to_string();
let written = written.trim();
let name = written.rsplit("::").next().unwrap_or(written);
if name == "iota" {
let arguments = crate::inlay::arguments_of(expression).unwrap_or_default();
let first = arguments.first()?;
return Some(
match type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
first,
depth + 1,
) {
Known::Yes((type_of, file)) => Known::Yes((type_of, file)),
_ => Known::Unknown(UnknownReason::UnknownType(Box::from("std::views::iota"))),
},
);
}
if name == "subrange" {
let arguments = crate::inlay::arguments_of(expression).unwrap_or_default();
let first = arguments.first()?;
if let Some(element) = element_of_an_iterator_expression(
memo,
index,
declaring,
scopes,
root,
path,
first,
depth + 1,
) {
return Some(element);
}
}
}
None
}
fn the_two_operands_of_a_pipe(
expression: &cpp_parser::CppSyntaxNode,
) -> Option<(cpp_parser::CppSyntaxNode, cpp_parser::CppSyntaxNode)> {
if CppSyntaxKind::from(expression.kind()) != CppSyntaxKind::BinaryExpr {
return None;
}
let is_a_pipe = expression
.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| token.text() == "|");
if !is_a_pipe {
return None;
}
let mut operands = expression.children();
let left = operands.next()?;
let right = operands.next()?;
Some((left, right))
}
fn adapted_element(
element: &Known<(Type, PathBuf)>,
adaptor: &cpp_parser::CppSyntaxNode,
index: &ProjectIndex,
path: &Path,
) -> Known<(Type, PathBuf)> {
let Known::Yes((element, file)) = element else {
return element.clone();
};
let written = adaptor.text().to_string();
let written = written.trim();
let _ = (index, path);
if written.contains("views::transform") || written.contains("views::transform_view") {
let lambda = adaptor
.descendants()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::LambdaExpr);
return match lambda
.and_then(|lambda| crate::sema::declarations::a_lambdas_return_type(&lambda, &[]))
{
Some(label) => Known::Yes((
crate::sema::types::parse_type_spelling(&label),
file.clone(),
)),
None => Known::Unknown(UnknownReason::UnknownType(Box::from(
"std::views::transform",
))),
};
}
if written.contains("views::keys") {
return match pair_component(element, 0) {
Some(component) => Known::Yes((component, file.clone())),
None => Known::Unknown(UnknownReason::UnknownType(Box::from("std::views::keys"))),
};
}
if written.contains("views::values") {
return match pair_component(element, 1) {
Some(component) => Known::Yes((component, file.clone())),
None => Known::Unknown(UnknownReason::UnknownType(Box::from("std::views::values"))),
};
}
if written.contains("views::join") {
return match element_of_the_element(element) {
Some(inner) => Known::Yes((inner, file.clone())),
None => Known::Unknown(UnknownReason::UnknownType(Box::from("std::views::join"))),
};
}
Known::Yes((element.clone(), file.clone()))
}
fn pair_component(element: &Type, position: usize) -> Option<Type> {
let Type::Named { name, arguments } = element else {
return None;
};
let plain = name.rsplit("::").next().unwrap_or(name);
if plain != "pair" && plain != "tuple" {
return None;
}
let component = arguments.get(position)?.clone();
Some(strip_a_leading_const(&component))
}
fn strip_a_leading_const(type_of: &Type) -> Type {
let written = type_of.to_string();
match written.strip_prefix("const ") {
Some(rest) => crate::sema::types::parse_type_spelling(rest),
None => type_of.clone(),
}
}
fn element_of_the_element(element: &Type) -> Option<Type> {
let written = element_of(element, 0)?;
Some(crate::sema::types::parse_type_spelling(&written))
}
fn element_of_an_iterator_expression(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
depth: usize,
) -> Option<Known<(Type, PathBuf)>> {
if let Some(access) = crate::sema::resolve::member_access_of(expression) {
let written = access.member.clone();
if written == "begin" || written.ends_with(".begin") {
let Known::Yes((container, file)) = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&access.object,
depth + 1,
) else {
return None;
};
let element = range_element_of(&container)?;
return Some(Known::Yes((
crate::sema::types::parse_type_spelling(&element),
file,
)));
}
}
if CppSyntaxKind::from(expression.kind()) == CppSyntaxKind::BinaryExpr {
let left = expression.children().next()?;
return element_of_an_iterator_expression(
memo,
index,
declaring,
scopes,
root,
path,
&left,
depth + 1,
);
}
None
}
fn a_call_to_a_function(
expression: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
if CppSyntaxKind::from(expression.kind()) != CppSyntaxKind::CallExpr {
return None;
}
expression.children().next()
}
fn range_element_of(container: &Type) -> Option<String> {
let Type::Named { name, arguments } = container else {
return match container {
Type::Array { of, .. } => Some(of.to_string()),
_ => None,
};
};
let plain = name.rsplit("::").next().unwrap_or(name);
if matches!(
plain,
"map" | "unordered_map" | "multimap" | "unordered_multimap"
) && arguments.len() >= 2
{
return Some(format!(
"std::pair<const {}, {}>",
arguments[0], arguments[1]
));
}
if !arguments.is_empty()
&& matches!(
plain,
"vector"
| "list"
| "deque"
| "forward_list"
| "set"
| "unordered_set"
| "multiset"
| "unordered_multiset"
| "basic_string"
| "string"
| "span"
| "initializer_list"
| "valarray"
)
{
return Some(arguments[0].to_string());
}
if matches!(plain, "array") && !arguments.is_empty() {
return Some(arguments[0].to_string());
}
None
}
fn initializer_type(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
named: &NamedDeclaration,
depth: usize,
) -> Known<(Type, PathBuf)> {
let Some((_, expression)) = deduction_inputs(root, named) else {
return Known::Unknown(UnknownReason::UnknownType(Box::from("auto")));
};
type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&expression,
depth,
)
}
fn a_typeof_payload(
root: &cpp_parser::CppSyntaxNode,
named: &NamedDeclaration,
) -> Option<cpp_parser::CppSyntaxNode> {
let NamedDeclaration::Here(binding) = named else {
return None;
};
let declarator = node_covering(root, binding.name_range.start_offset, binding.range)?;
let specifiers = declarator.ancestors().find_map(|node| {
node.children().find(|child| {
cpp_parser::CppSyntaxKind::from(child.kind())
== cpp_parser::CppSyntaxKind::DeclSpecifierSeq
})
})?;
let typeof_node = specifiers.children().find(|child| {
let text = child.text().to_string();
let name = text
.trim()
.split('(')
.next()
.unwrap_or("")
.trim()
.to_string();
matches!(
name.as_str(),
"typeof" | "typeof_unqual" | "__typeof__" | "__typeof" | "__decltype" | "decltype"
)
})?;
typeof_node.children().find(|child| {
!matches!(
cpp_parser::CppSyntaxKind::from(child.kind()),
cpp_parser::CppSyntaxKind::TypeId | cpp_parser::CppSyntaxKind::DeclSpecifierSeq
)
})
}
fn an_unnamed_class_body(
specifiers: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
let body = specifiers.children().find(|child| {
matches!(
cpp_parser::CppSyntaxKind::from(child.kind()),
cpp_parser::CppSyntaxKind::ClassDef
| cpp_parser::CppSyntaxKind::StructDef
| cpp_parser::CppSyntaxKind::UnionDef
)
})?;
let tag = body.children().any(|child| {
cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::NameExpr
});
(!tag).then_some(body)
}
fn deduction_inputs(
root: &cpp_parser::CppSyntaxNode,
named: &NamedDeclaration,
) -> Option<(String, cpp_parser::CppSyntaxNode)> {
let NamedDeclaration::Here(binding) = named else {
return None;
};
let declarator = node_covering(root, binding.name_range.start_offset, binding.range)?;
let is_an_initializer = |node: &cpp_parser::CppSyntaxNode| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::Initializer
};
let declarator = if declarator.children().any(|child| is_an_initializer(&child)) {
declarator
} else {
declarator.children().find(|child| {
cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::Declarator
})?
};
let initializer = declarator
.children()
.find(|child| is_an_initializer(child))?;
let first = initializer.children().next()?;
let expression = if cpp_parser::CppSyntaxKind::from(first.kind())
== cpp_parser::CppSyntaxKind::ArgumentList
{
first.children().next()?
} else {
first
};
let specifiers = declarator
.ancestors()
.find_map(|node| {
node.children().find(|child| {
cpp_parser::CppSyntaxKind::from(child.kind())
== cpp_parser::CppSyntaxKind::DeclSpecifierSeq
})
})
.map(|node| node.text().to_string())
.unwrap_or_default();
let name_range = binding.name_range;
let name = root
.text()
.to_string()
.get(name_range.start_offset..name_range.end_offset())
.unwrap_or_default()
.to_string();
let operators: String = declarator
.children()
.find(|child| {
cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::Declarator
})
.map(|node| node.text().to_string())
.unwrap_or_default()
.replace(&name, "")
.split_whitespace()
.collect();
Some((
format!("{} {}", specifiers.trim(), operators)
.trim()
.to_string(),
expression,
))
}
fn node_covering(
root: &cpp_parser::CppSyntaxNode,
offset: usize,
range: cpp_parser::SourceRange,
) -> Option<cpp_parser::CppSyntaxNode> {
let matches = |node: &cpp_parser::CppSyntaxNode| {
usize::from(node.text_range().start()) == range.start_offset
&& usize::from(node.text_range().end()) == range.end_offset()
};
let mut node = root.clone();
loop {
if matches(&node) {
return Some(node);
}
let next = node
.children_with_tokens()
.find(|element| {
element.as_node().is_some_and(|child| {
let start = usize::from(child.text_range().start());
let end = usize::from(child.text_range().end());
offset >= start && offset < end
})
})
.and_then(|element| element.into_node())?;
node = next;
}
}
fn auto_substituted(
written: &str,
deduced: &Type,
initializer_is_an_lvalue: bool,
) -> Option<String> {
if written.trim() == "decltype(auto)" {
return Some(deduced.to_string().trim().to_string());
}
let deduced = deduced.to_string();
let deduced = deduced.as_str();
let is_word = |byte: u8| byte.is_ascii_alphanumeric() || byte == b'_';
let bytes = written.as_bytes();
let mut at = 0usize;
let mut found = None;
while at < bytes.len() {
if !is_word(bytes[at]) {
at += 1;
continue;
}
let start = at;
while at < bytes.len() && is_word(bytes[at]) {
at += 1;
}
if matches!(&written[start..at], "auto" | "__auto_type") {
found = Some((start, at));
break;
}
}
let (start, end) = found?;
let prefix = written[..start].trim();
let suffix = written[end..].trim();
let mut base = deduced.trim().to_string();
for _ in 0..suffix.matches('*').count() {
base = pointee_type_name(&base)?.to_string();
}
let mut reference = "";
if suffix.contains('&') {
let deduced_had_one = base.ends_with("&&") || base.ends_with('&');
if deduced_had_one {
let trimmed = base.trim_end_matches('&').trim_end().len();
base.truncate(trimmed);
base = base.trim_end().to_string();
}
reference = match (
suffix.contains("&&"),
deduced_had_one || initializer_is_an_lvalue,
) {
(true, false) => "&&",
_ => "&",
};
}
let stars = "*".repeat(suffix.matches('*').count());
let mut type_of = String::new();
if !prefix.is_empty() {
type_of.push_str(prefix);
type_of.push(' ');
}
type_of.push_str(base.trim());
type_of.push_str(&stars);
type_of.push_str(reference);
Some(type_of)
}
fn is_a_placeholder(written: &str) -> bool {
matches!(
written.trim(),
"auto" | "auto&" | "auto&&" | "const auto" | "const auto&" | "decltype(auto)"
)
}
fn what_a_call_has_in(fact: &DeclFact) -> Option<Type> {
match fact.kind {
crate::DeclKind::Type => Some(Type::named(fact.qualified_name())),
_ => fact
.returns
.as_deref()
.filter(|written| !is_a_placeholder(written))
.map(parse_type_spelling),
}
}
fn written_like_a_macro(word: &str) -> bool {
word.starts_with('_')
|| (word.len() > 1
&& word
.chars()
.all(|character| !character.is_alphabetic() || character.is_uppercase()))
}
fn structured_binding_type(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
depth: usize,
) -> Option<Known<(Type, PathBuf)>> {
let at = end_of_the_written_name(expression);
let Known::Yes(binding) = crate::sema::resolve::definition_at(scopes, root, at) else {
return None;
};
if binding.kind != crate::BindingKind::Variable {
return None;
}
let declared_at = binding.name_range.start_offset;
let pattern = cpp_parser::token_at(root, declared_at)?
.parent_ancestors()
.find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind())
== cpp_parser::CppSyntaxKind::StructuredBinding
})?;
let mut position = None;
let mut seen = 0usize;
for child in pattern.children() {
if cpp_parser::CppSyntaxKind::from(child.kind()) != cpp_parser::CppSyntaxKind::NameExpr {
continue;
}
let range = cpp_parser::source_range(child.text_range());
if range.start_offset == declared_at {
position = Some(seen);
break;
}
seen += 1;
}
let position = position?;
let container = match range_expression_of_the_pattern(&pattern) {
Some(range) => type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&range,
depth + 1,
),
None => {
let initializer = initializer_of_the_pattern(&pattern)?;
type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&initializer,
depth + 1,
)
}
};
let Known::Yes((container, file)) = container else {
return Some(container);
};
let element = element_of(&container, position).or_else(|| {
let Type::Named { name, .. } = &container else {
return None;
};
let wanted = match position {
0 => "first",
1 => "second",
_ => return None,
};
let Known::Yes(listed) = members_of(index, scopes, root, path, name) else {
return None;
};
let Known::Yes(listed) =
substituted_members(index, path, &container.to_string(), Known::Yes(listed))
else {
return None;
};
listed
.members
.iter()
.find(|member| {
member.fact.name == wanted && member.fact.kind == crate::DeclKind::Variable
})
.and_then(|member| member.fact.type_of.clone())
});
Some(match element {
Some(element) => Known::Yes((crate::sema::types::parse_type_spelling(&element), file)),
None => Known::Unknown(UnknownReason::UnknownType(Box::from(container.to_string()))),
})
}
fn range_expression_of_the_pattern(
binding: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
use cpp_parser::CppTokenKind;
let loop_node = binding.ancestors().find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::RangeForStat
})?;
let mut after_the_colon = false;
for child in loop_node.children_with_tokens() {
match child {
cpp_parser::CppSyntaxElement::Token(token) => {
if CppTokenKind::from(token.kind()) == CppTokenKind::Colon {
after_the_colon = true;
}
}
cpp_parser::CppSyntaxElement::Node(node) => {
if after_the_colon && node != *binding {
return Some(node);
}
}
}
}
None
}
fn initializer_of_the_pattern(
pattern: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
use cpp_parser::CppTokenKind;
let holders: Vec<cpp_parser::CppSyntaxNode> = pattern
.ancestors()
.take_while(|node| {
!matches!(
cpp_parser::CppSyntaxKind::from(node.kind()),
cpp_parser::CppSyntaxKind::FunctionDef | cpp_parser::CppSyntaxKind::TranslationUnit
)
})
.filter(|node| {
matches!(
cpp_parser::CppSyntaxKind::from(node.kind()),
cpp_parser::CppSyntaxKind::InitDeclarator | cpp_parser::CppSyntaxKind::Declaration
)
})
.collect();
for holder in holders {
let mut after_the_equals = false;
for child in holder.children_with_tokens() {
match child {
cpp_parser::CppSyntaxElement::Token(token) => {
if CppTokenKind::from(token.kind()) == CppTokenKind::Assign {
after_the_equals = true;
}
}
cpp_parser::CppSyntaxElement::Node(node) if after_the_equals => return Some(node),
cpp_parser::CppSyntaxElement::Node(_) => {}
}
}
}
None
}
fn element_of(container: &Type, position: usize) -> Option<String> {
let Type::Named { name, arguments } = container else {
return match container {
Type::Array { of, .. } => Some(of.to_string()),
_ => None,
};
};
let plain = name.rsplit("::").next().unwrap_or(name);
if matches!(
plain,
"map" | "unordered_map" | "multimap" | "unordered_multimap"
) && arguments.len() == 2
{
return match position {
0 => Some(format!("const {}", arguments[0])),
_ => Some(arguments[1].to_string()),
};
}
if matches!(plain, "array") && arguments.len() == 2 {
return Some(arguments[0].to_string());
}
if arguments.len() == 1
&& matches!(
plain,
"vector"
| "list"
| "deque"
| "forward_list"
| "set"
| "unordered_set"
| "multiset"
| "unordered_multiset"
| "basic_string"
| "string"
| "span"
| "initializer_list"
| "valarray"
)
{
return Some(arguments[0].to_string());
}
if matches!(plain, "pair" | "tuple") {
return arguments
.get(position)
.map(|component| component.to_string());
}
None
}
fn writes_a_name(written: &str) -> bool {
let spelling = written.strip_prefix("::").unwrap_or(written);
if spelling.contains('(')
|| spelling.contains(')')
|| spelling.contains(',')
|| spelling.contains('{')
|| spelling.contains('}')
{
return false;
}
!spelling.is_empty()
&& spelling
.split("::")
.all(|segment| {
let bare = segment.split('<').next().unwrap_or(segment);
let mut words = bare.split_whitespace();
words.clone().count() > 0 && words.all(is_an_identifier)
})
}
fn is_an_identifier(segment: &str) -> bool {
!segment.is_empty()
&& segment
.chars()
.all(|character| character.is_alphanumeric() || character == '_')
}
fn deduce_the_parameters(
names: &[String],
written_list: Option<&str>,
argument_types: &[Type],
) -> Vec<Type> {
let mut deduced: Vec<Type> = names.iter().map(Type::named).collect();
if names.is_empty() || argument_types.is_empty() {
return deduced;
}
let Some(list) = written_list else {
return deduced;
};
for (at, parameter) in written_parameters(list).into_iter().enumerate() {
let words: Vec<&str> = parameter.split_whitespace().collect();
let written_type = match words.len() {
0 => continue,
1 => words[0],
_ => {
¶meter[..parameter
.rfind(words[words.len() - 1])
.unwrap_or(parameter.len())]
}
};
let written_type = written_type.trim();
if written_type.is_empty() {
continue;
}
let bare = written_type
.strip_suffix("&&")
.or_else(|| written_type.strip_suffix('&'))
.map(str::trim)
.unwrap_or(written_type);
let Some(name_at) = names.iter().position(|name| name == bare) else {
continue;
};
let Some(argument) = argument_types.get(at) else {
continue;
};
deduced[name_at] = argument.clone();
}
deduced
}
fn written_parameters(list: &str) -> Vec<String> {
let body = list.trim();
let body = body.strip_prefix('(').unwrap_or(body);
let body = body.strip_suffix(')').unwrap_or(body);
let mut out = Vec::new();
let mut depth = 0usize;
let mut at = 0usize;
for (index, character) in body.char_indices() {
match character {
'(' | '[' | '<' => depth += 1,
')' | ']' | '>' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
out.push(body[at..index].to_string());
at = index + 1;
}
_ => {}
}
}
out.push(body[at..].to_string());
out
}
fn end_of_the_written_name(expression: &cpp_parser::CppSyntaxNode) -> usize {
let mut last = None;
for element in expression.descendants_with_tokens() {
let Some(token) = element.into_token() else {
continue;
};
if cpp_parser::CppTokenKind::from(token.kind()) != cpp_parser::CppTokenKind::Identifier {
continue;
}
if token
.parent_ancestors()
.any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TemplateArgumentList)
{
continue;
}
last = Some(usize::from(token.text_range().start()));
}
last.unwrap_or_else(|| usize::from(expression.text_range().start()))
}
fn declaration_of_expression(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
) -> Known<NamedDeclaration> {
let offset = end_of_the_written_name(expression);
let written = expression.text().to_string();
let written = written.trim();
let asked = crate::sema::resolve::definition_at(scopes, root, offset);
match asked {
Known::Yes(binding) => Known::Yes(NamedDeclaration::Here(binding)),
Known::Unknown(UnknownReason::NotDeclaredHere(name)) => {
let mut candidates: Vec<&str> = vec![name.as_ref()];
if let Some(without) = name.strip_prefix("::") {
candidates.push(without);
}
if let Some((_, without_the_prefix)) = name.split_once(' ') {
candidates.push(without_the_prefix.trim());
}
if let Some((first, rest)) = name.split_once("::")
&& written_like_a_macro(first)
{
candidates.push(rest);
}
let mut was_ambiguous = false;
for candidate in candidates {
let found: Option<(crate::DeclFact, PathBuf)> =
match index.definition(candidate, path) {
Known::Yes(found) => Some((found.fact, found.file)),
Known::Unknown(UnknownReason::Ambiguous(_)) => {
was_ambiguous = true;
agreeing_type(index, path, candidate)
}
Known::Unknown(_) | Known::No => None,
};
if let Some((fact, file)) = found {
return Known::Yes(NamedDeclaration::Indexed(
fact,
file,
TypeBindings::default(),
));
}
}
if was_ambiguous {
Known::Unknown(UnknownReason::Ambiguous(Box::from(written)))
} else {
Known::Unknown(UnknownReason::UnknownType(Box::from(written)))
}
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
}
}
fn a_function_pointer_returns(a_type: &Type) -> Option<Type> {
let Type::Pointer { to } = a_type else {
return None;
};
match to.as_ref() {
Type::Function { returns, .. } => Some(returns.as_ref().clone()),
_ => None,
}
}
fn a_lambdas_body_the_callee_names(
root: &cpp_parser::CppSyntaxNode,
scopes: &crate::ScopeTree,
callee: &cpp_parser::CppSyntaxNode,
argument_types: &[Type],
) -> Option<String> {
let inside = callee.text_range();
let Known::Yes(binding) =
crate::sema::resolve::definition_at(scopes, root, inside.start().into())
else {
return None;
};
let name = binding.name_range;
let declarator = root.descendants().find(|node| {
let range = node.text_range();
CppSyntaxKind::from(node.kind()) == CppSyntaxKind::InitDeclarator
&& usize::from(range.start()) <= name.start_offset
&& name.end_offset() <= usize::from(range.end())
})?;
let lambda = declarator
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::LambdaExpr)?;
crate::sema::declarations::a_lambdas_return_type(&lambda, argument_types)
}
fn type_of_a_call(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
call: &cpp_parser::CppSyntaxNode,
) -> Known<(Type, PathBuf)> {
let written = call.text().to_string();
let written = written.trim();
let Some(callee) = call.children().next() else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
};
if let Some(element) =
iterator_element_type(memo, index, declaring, scopes, root, path, &callee)
{
return element;
}
let written_arguments = {
let from_the_callee = written_template_arguments(&callee);
if from_the_callee.is_empty() {
call.children()
.take_while(|child| {
CppSyntaxKind::from(child.kind()) != CppSyntaxKind::ArgumentList
})
.filter_map(|child| {
if CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TemplateArgumentList {
return Some(child);
}
child.descendants().find(|node| {
CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TemplateArgumentList
})
})
.next()
.map(|list| crate::sema::types::read_template_arguments(&list))
.unwrap_or_default()
} else {
from_the_callee
}
};
let argument_types: Vec<Type> = if written_arguments.is_empty() {
crate::inlay::arguments_of(call)
.unwrap_or_default()
.iter()
.filter_map(|argument| {
match type_of_expression_memoed(
memo, index, declaring, scopes, root, path, argument, 0,
) {
Known::Yes((type_of, _)) => Some(type_of),
_ => None,
}
})
.collect()
} else {
Vec::new()
};
if let Known::Yes((callee_type, file)) =
type_of_expression_memoed(memo, index, declaring, scopes, root, path, &callee, 0)
&& let Some(returns) = a_function_pointer_returns(&callee_type)
{
return Known::Yes((returns, file));
}
if let Some(returns) = a_lambdas_body_the_callee_names(root, scopes, &callee, &argument_types) {
return Known::Yes((
crate::sema::types::parse_type_spelling(&returns),
path.to_path_buf(),
));
}
let resolved =
declaration_of_a_callee(memo, index, declaring, scopes, root, path, &callee, written);
let names_a_function = match &resolved {
Known::Yes(named) => named.fact_kind() == crate::DeclKind::Function,
_ => false,
};
if !names_a_function
&& let Known::Yes((callee_type, file)) =
type_of_expression_memoed(memo, index, declaring, scopes, root, path, &callee, 0)
&& matches!(callee_type, Type::Named { .. })
&& let Some(returns) = operator_returns_of(
index,
declaring,
scopes,
root,
path,
&callee_type,
"operator()",
)
{
return Known::Yes((crate::sema::types::parse_type_spelling(&returns), file));
}
if let Some(pointer) = the_factory_the_call_names(&callee)
&& let Some(argument) = written_arguments.first()
{
return Known::Yes((
crate::sema::types::parse_type_spelling(&format!("{pointer}<{argument}>")),
path.to_path_buf(),
));
}
if let Some(algorithm) = a_ranges_algorithm_the_call_names(&callee) {
let arguments = crate::inlay::arguments_of(call).unwrap_or_default();
match algorithm.as_str() {
"find" | "find_if" | "find_if_not" | "max" | "min" | "max_element" | "min_element"
| "lower_bound" | "upper_bound" | "equal_range" | "search" => {
if let Some(element) = arguments.first().and_then(|first| {
element_of_a_range_expression(
memo, index, declaring, scopes, root, path, first, 0,
)
}) {
return element;
}
}
"count" | "count_if" | "distance" | "ssize" => {
return Known::Yes((
crate::sema::types::parse_type_spelling("std::ptrdiff_t"),
path.to_path_buf(),
));
}
"size" => {
return Known::Yes((
crate::sema::types::parse_type_spelling("std::size_t"),
path.to_path_buf(),
));
}
"subrange" => {
if let Some(first) = arguments.first()
&& let Some(element) = element_of_an_iterator_expression(
memo, index, declaring, scopes, root, path, first, 0,
)
{
return element;
}
}
_ => {}
}
}
if let Some(spelling) = a_callee_that_names_a_type(index, path, &callee) {
return Known::Yes((
crate::sema::types::parse_type_spelling(&spelling),
path.to_path_buf(),
));
}
let resolved =
declaration_of_a_callee(memo, index, declaring, scopes, root, path, &callee, written);
let known_so_far = match resolved {
Known::Yes(named) => match named.what_a_call_has(
index,
declaring,
scopes,
root,
path,
&written_arguments,
&argument_types,
) {
Some(type_of) => return Known::Yes((type_of, named.file(path))),
None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
},
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
if let Some(returns) = the_return_the_overloads_agree_on(
index,
path,
&the_names_the_call_may_use(&callee),
&written_arguments,
&argument_types,
crate::inlay::arguments_of(call)
.map(|arguments| arguments.len())
.unwrap_or_default(),
) {
return Known::Yes((
crate::sema::types::parse_type_spelling(&returns),
path.to_path_buf(),
));
}
known_so_far
}
fn the_factory_the_call_names(callee: &cpp_parser::CppSyntaxNode) -> Option<&'static str> {
let spelled = callee.text().to_string();
let spelled = spelled.trim();
let bare = match spelled.find('<') {
Some(at) => spelled[..at].trim(),
None => spelled,
};
let last = bare.rsplit("::").next().unwrap_or(bare);
match last {
"make_shared" => Some("shared_ptr"),
"make_unique" | "make_unique_for_overwrite" => Some("unique_ptr"),
_ => None,
}
}
fn the_name_before_its_template_arguments(callee: &cpp_parser::CppSyntaxNode) -> Option<String> {
let kind = CppSyntaxKind::from(callee.kind());
if !matches!(
kind,
CppSyntaxKind::NameExpr | CppSyntaxKind::IdentifierExpr
) {
return None;
}
let text = callee.text().to_string();
let text = text.trim();
let open = text.find('<')?;
if open == 0 || !text.ends_with('>') {
return None;
}
let name = &text[..open];
let names_something = name
.chars()
.all(|character| character.is_alphanumeric() || character == '_' || character == ':');
names_something.then(|| name.to_string())
}
fn a_ranges_algorithm_the_call_names(callee: &cpp_parser::CppSyntaxNode) -> Option<String> {
let written = callee.text().to_string();
let written = written.trim();
let last = written.rsplit("::").next()?;
let in_the_ranges_namespace = written.contains("ranges::");
let is_an_algorithm = matches!(
last,
"find"
| "find_if"
| "find_if_not"
| "max"
| "min"
| "max_element"
| "min_element"
| "count"
| "count_if"
| "distance"
| "size"
| "ssize"
| "subrange"
| "lower_bound"
| "upper_bound"
| "equal_range"
| "search"
);
(in_the_ranges_namespace && is_an_algorithm).then(|| last.to_string())
}
fn a_callee_that_names_a_type(
index: &ProjectIndex,
path: &Path,
callee: &cpp_parser::CppSyntaxNode,
) -> Option<String> {
let spelled = callee.text().to_string();
let spelled = spelled.trim();
if spelled.is_empty() || spelled.contains(' ') {
return None;
}
let bare = match spelled.find('<') {
Some(at) => spelled[..at].trim(),
None => spelled,
};
let names_a_type = match index.definition(bare, path) {
Known::Yes(found) => found.fact.kind == crate::DeclKind::Type,
Known::Unknown(UnknownReason::Ambiguous(_)) => {
index.definitions(bare, path).value().is_some_and(|found| {
!found.found.is_empty()
&& found
.found
.iter()
.all(|declaration| declaration.fact.kind == crate::DeclKind::Type)
})
}
Known::Unknown(_) | Known::No => false,
};
names_a_type.then(|| spelled.to_string())
}
fn the_names_the_call_may_use(callee: &cpp_parser::CppSyntaxNode) -> Vec<String> {
let spelled = callee.text().to_string();
let spelled = spelled.trim();
let bare = match spelled.find('<') {
Some(at) => spelled[..at].trim(),
None => spelled,
};
let last = bare.rsplit("::").next().unwrap_or(bare);
let mut names = vec![bare.to_string()];
if last != bare {
names.push(last.to_string());
}
names
}
fn the_return_the_overloads_agree_on(
index: &ProjectIndex,
path: &Path,
names: &[String],
written_arguments: &[Type],
argument_types: &[Type],
how_many_arguments: usize,
) -> Option<String> {
for name in names {
let Known::Yes(found) = index.definitions(name, path) else {
continue;
};
let mut agreed: Option<String> = None;
let mut any = false;
for candidate in found
.found
.iter()
.filter(|declaration| declaration.fact.kind == crate::DeclKind::Function)
{
if candidate
.fact
.modifiers
.contains(crate::summary::DeclModifiers::DELETED)
{
continue;
}
let Some(written) = candidate.fact.returns.as_deref() else {
continue;
};
if !a_candidate_that_can_be_called_this_way(
candidate.fact.parameter_list.as_deref(),
argument_types,
how_many_arguments,
) {
continue;
}
let substituted =
if written_arguments.is_empty() || candidate.fact.parameters.is_empty() {
written.to_string()
} else {
let arguments: Vec<String> = written_arguments
.iter()
.map(|one| one.to_string())
.collect();
crate::sema::types::substituted_spelling(
written,
&candidate.fact.parameters,
&arguments,
)
};
let still_unsubstituted =
candidate.fact.parameters.iter().any(|parameter| {
!parameter.is_empty() && substituted.contains(parameter.as_str())
});
if still_unsubstituted {
continue;
}
let read_as_auto_reads_it = read_the_way_auto_does(&substituted);
if read_as_auto_reads_it.is_empty() {
continue;
}
any = true;
match &agreed {
None => agreed = Some(read_as_auto_reads_it),
Some(previous) if *previous == read_as_auto_reads_it => {}
Some(_) => return None,
}
}
if any && agreed.is_some() {
return agreed;
}
}
None
}
fn a_candidate_that_can_be_called_this_way(
parameter_list: Option<&str>,
argument_types: &[Type],
how_many_arguments: usize,
) -> bool {
let Some(parameter_list) = parameter_list else {
return false;
};
let parameters = crate::sema::overload::parameters_in(parameter_list).0;
let a_pack = parameter_list.contains("...");
if a_pack {
let fixed = parameters.len().saturating_sub(1);
if how_many_arguments < fixed {
return false;
}
} else if parameters.len() != how_many_arguments {
return false;
}
if argument_types.len() != how_many_arguments {
return true;
}
parameters
.iter()
.zip(argument_types)
.all(|(parameter, argument)| {
!crate::sema::convert::conversion(argument, parameter, |_| None).is_refused()
})
}
fn read_the_way_auto_does(written: &str) -> String {
let mut spelling = written.trim();
while let Some(rest) = spelling.strip_prefix("const ") {
spelling = rest.trim();
}
while let Some(rest) = spelling.strip_suffix('&') {
spelling = rest.trim();
}
spelling.to_string()
}
fn iterator_element_type(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
callee: &cpp_parser::CppSyntaxNode,
) -> Option<Known<(Type, PathBuf)>> {
let member = crate::sema::resolve::member_access_at(root, end_of_the_written_name(callee))?;
if !matches!(
member.member.as_str(),
"begin"
| "cbegin"
| "rbegin"
| "end"
| "cend"
| "rend"
| "find"
| "lower_bound"
| "upper_bound"
) {
return None;
}
let Known::Yes((object, file)) = type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&member.object,
0,
) else {
return None;
};
let element = range_element_of(&object)?;
Some(Known::Yes((
crate::sema::types::parse_type_spelling(&element),
file,
)))
}
fn written_template_arguments(callee: &cpp_parser::CppSyntaxNode) -> Vec<Type> {
let Some(list) = callee
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TemplateArgumentList)
else {
return Vec::new();
};
crate::sema::types::read_template_arguments(&list)
}
pub(crate) fn qualified_from_the_index(
index: &ProjectIndex,
from: &Path,
class: &str,
) -> Option<String> {
if class.contains("::") {
return None;
}
let declared = index.files_declaring(class, from);
let found = declared
.into_iter()
.find(|declared| declared.fact.kind == crate::DeclKind::Type)?;
let scope = found.fact.scope.as_deref()?;
(!scope.is_empty()).then(|| format!("{scope}::{class}"))
}
fn declaration_of_a_callee(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
callee: &cpp_parser::CppSyntaxNode,
written: &str,
) -> Known<NamedDeclaration> {
if let Some(access) = crate::sema::resolve::member_access_of(callee) {
let object = match type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&access.object,
0,
) {
Known::Yes((type_of, _)) => type_of,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => return Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
let class = if access.arrow
&& let Some((reached, _)) = crate::completion::the_class_after_the_operator(
index, scopes, root, path, &object, true,
) {
reached
} else {
let Some(own) = member_access_class(&object) else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(object.to_string())));
};
own
};
let (class, arguments) =
member_access_class_and_arguments(index, scopes, root, path, &class, &object);
let bindings = member_bindings(index, scopes, root, path, &class, &arguments);
if crate::probes::inference() {
eprintln!(
"[inference] callee: object {object:?} -> class {class:?}, arguments {arguments:?}, bindings empty {}",
bindings.is_empty()
);
}
let written_arguments: Vec<String> = arguments
.iter()
.map(|argument| argument.to_string())
.collect();
return match member_fact(
index,
scopes,
root,
path,
&class,
&access.member,
Some(&written_arguments),
) {
Known::Yes((fact, file)) => Known::Yes(NamedDeclaration::Indexed(fact, file, bindings)),
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
};
}
if let Some(call) = the_call_around(callee)
&& let Known::Yes(bindings) =
crate::sema::resolve::definitions_at(scopes, root, end_of_the_written_name(callee))
&& bindings.len() > 1
&& let Some(types) =
the_types_of_the_arguments(memo, index, declaring, scopes, root, path, &call)
{
let candidates: Vec<(DeclFact, PathBuf)> = bindings
.iter()
.map(|binding| (fact_from_binding(root, "", binding), path.to_path_buf()))
.collect();
let explicit_arguments: Vec<String> = call
.children()
.next()
.map(|callee| written_template_arguments(&callee))
.unwrap_or_default()
.iter()
.map(Type::to_string)
.collect();
if let Some(chosen) = the_one_the_arguments_select(&types, &candidates, &explicit_arguments)
&& let Some(binding) = bindings.get(chosen)
{
return Known::Yes(NamedDeclaration::Here(binding.clone()));
}
}
if matches!(
crate::sema::resolve::definition_at(scopes, root, end_of_the_written_name(callee)),
Known::No | Known::Unknown(UnknownReason::NotDeclaredHere(_))
) && let Some(member) =
a_member_of_the_enclosing_class(index, scopes, root, path, callee, true)
{
return Known::Yes(NamedDeclaration::Indexed(
member.fact,
member.file,
crate::sema::types::TypeBindings::new(Vec::new(), Vec::new()),
));
}
let known = declaration_of_expression(index, scopes, root, path, callee);
let known = match &known {
Known::No
| Known::Unknown(UnknownReason::NotDeclaredHere(_))
| Known::Unknown(UnknownReason::Ambiguous(_)) => {
match the_name_before_its_template_arguments(callee) {
Some(bare) => {
let start = usize::from(callee.text_range().start());
match crate::sema::resolve::definition_at(scopes, root, start + bare.len()) {
Known::Yes(binding) => Known::Yes(NamedDeclaration::Here(binding)),
_ => match index.definition(&bare, path) {
Known::Yes(found) => Known::Yes(NamedDeclaration::Indexed(
found.fact,
found.file,
crate::sema::types::TypeBindings::new(Vec::new(), Vec::new()),
)),
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::No,
},
}
}
None => known,
}
}
_ => known,
};
let Known::Unknown(UnknownReason::Ambiguous(name)) = &known else {
return known;
};
let Some(call) = the_call_around(callee) else {
return known;
};
match the_declaration_the_arguments_pick(
memo,
index,
declaring,
scopes,
root,
path,
&call,
name.as_ref(),
) {
Some((fact, file)) => Known::Yes(NamedDeclaration::Indexed(
fact,
file,
TypeBindings::default(),
)),
None => known,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Callee {
pub file: PathBuf,
pub name_offset: usize,
pub parameters: Option<String>,
}
pub(crate) fn callees_of_a_call(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
call: &cpp_parser::CppSyntaxNode,
) -> Known<Vec<Callee>> {
let memo = TypeMemo::default();
let written = call.text().to_string();
let written = written.trim();
let Some(callee) = call.children().next() else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
};
if let Some(access) = crate::sema::resolve::member_access_of(&callee) {
let members = member_callees(&memo, index, declaring, scopes, root, path, &access);
return match members {
Known::Yes(found) if !found.is_empty() => Known::Yes(found),
other => match other {
Known::Unknown(reason) => Known::Unknown(reason),
_ => match callee_of_a_call(index, declaring, scopes, root, path, call) {
Known::Yes(one) => Known::Yes(vec![one]),
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
},
},
};
}
let offset = end_of_the_written_name(&callee);
match crate::sema::resolve::definitions_at(scopes, root, offset) {
Known::Yes(bindings) if !bindings.is_empty() => Known::Yes(
bindings
.iter()
.map(|binding| Callee {
file: path.to_path_buf(),
name_offset: binding.name_range.start_offset,
parameters: None,
})
.collect(),
),
Known::Yes(_) => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
Known::Unknown(UnknownReason::NotDeclaredHere(name))
| Known::Unknown(UnknownReason::Ambiguous(name)) => match index.definitions(&name, path) {
Known::Yes(found) => Known::Yes(
found
.found
.iter()
.map(|declaration| Callee {
file: declaration.file.clone(),
name_offset: declaration.fact.name_range.start_offset,
parameters: declaration.fact.parameter_list.clone(),
})
.collect(),
),
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
},
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
}
}
fn the_call_around(callee: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSyntaxNode> {
let mut node = callee.parent();
for _ in 0..4 {
let inner = node?;
if cpp_parser::CppSyntaxKind::from(inner.kind()) == cpp_parser::CppSyntaxKind::CallExpr {
return Some(inner);
}
node = inner.parent();
}
None
}
fn the_declaration_the_arguments_pick(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
call: &cpp_parser::CppSyntaxNode,
name: &str,
) -> Option<(DeclFact, PathBuf)> {
let name = the_name_without_its_arguments(name);
let Known::Yes(definitions) = index.definitions(name, path) else {
return None;
};
if definitions.found.len() < 2 {
return None;
}
let candidates: Vec<(DeclFact, PathBuf)> = definitions
.found
.iter()
.map(|definition| (definition.fact.clone(), definition.file.clone()))
.collect();
let types = the_types_of_the_arguments(memo, index, declaring, scopes, root, path, call)?;
let explicit_arguments: Vec<String> = call
.children()
.next()
.map(|callee| written_template_arguments(&callee))
.unwrap_or_default()
.iter()
.map(Type::to_string)
.collect();
let chosen = the_one_the_arguments_select(&types, &candidates, &explicit_arguments)?;
candidates.get(chosen).cloned()
}
fn the_name_without_its_arguments(written: &str) -> &str {
let Some(open) = written.find('<') else {
return written;
};
let mut depth = 0i32;
for (at, character) in written[open..].char_indices() {
match character {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
let close = open + at;
return if close + character.len_utf8() == written.len() {
&written[..open]
} else {
written
};
}
}
_ => {}
}
}
written
}
fn the_types_of_the_arguments(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
call: &cpp_parser::CppSyntaxNode,
) -> Option<Vec<Known<String>>> {
let arguments = crate::inlay::arguments_of(call)?;
Some(
arguments
.iter()
.map(|argument| {
match type_of_expression_memoed(
memo, index, declaring, scopes, root, path, argument, 0,
) {
Known::Yes((type_of, _)) => Known::Yes(type_of.to_string()),
Known::No => Known::No,
Known::Unknown(reason) => Known::Unknown(reason),
}
})
.collect(),
)
}
fn the_one_the_arguments_select(
types: &[Known<String>],
candidates: &[(DeclFact, PathBuf)],
explicit_arguments: &[String],
) -> Option<usize> {
let usable: Vec<usize> = (0..candidates.len())
.filter(|at| {
!candidates[*at]
.0
.modifiers
.contains(crate::DeclModifiers::DELETED)
})
.collect();
if usable.is_empty() {
return None;
}
let built: Vec<crate::sema::overload::Candidate> = usable
.iter()
.enumerate()
.map(|(at, &index)| {
let (fact, _) = &candidates[index];
let (declared, variadic) = fact
.parameter_list
.as_deref()
.map(crate::sema::overload::parameters_in)
.unwrap_or_default();
let names = fact.parameters.clone();
let declared_for_ordering = declared.clone();
let substituted = match crate::sema::deduction::deduce_with_written(
&names,
&declared,
types,
explicit_arguments,
) {
Some(deduced) => (
declared
.iter()
.map(|spelling| {
crate::sema::types::substituted_spelling(spelling, &names, &deduced)
})
.collect::<Vec<String>>(),
true,
),
None => (declared, !names.is_empty()),
};
let candidate = crate::sema::overload::Candidate::new(
substituted.0,
variadic,
format!("declaration {at}"),
);
if substituted.1 {
candidate.with_declaration(declared_for_ordering, names)
} else {
candidate
}
})
.collect();
if crate::probes::inference() {
eprintln!(
"[inference] pick among {} candidates ({} usable), argument types {types:?} written {explicit_arguments:?}",
candidates.len(),
usable.len()
);
for (at, (fact, _)) in candidates.iter().enumerate() {
eprintln!(
"[inference] candidate {at}: bits={} deleted={} params={:?}",
fact.modifiers.bits(),
fact.modifiers.contains(crate::DeclModifiers::DELETED),
fact.parameter_list
);
}
for (at, (fact, _)) in candidates.iter().enumerate() {
eprintln!(
"[inference] candidate {at}: scope {:?} returns {:?} params {:?}",
fact.scope, fact.returns, fact.parameter_list
);
}
}
let choice = crate::sema::overload::choose(types, &built);
if crate::probes::inference() {
eprintln!("[inference] choice: {choice:?}");
}
match choice {
crate::sema::overload::Choice::One(at) => usable.get(at).copied(),
crate::sema::overload::Choice::Ambiguous => {
let written = types.iter().find_map(|argument| match argument {
Known::Yes(spelling) => the_character_width(spelling),
_ => None,
})?;
let definite: Vec<usize> = usable
.iter()
.filter(|at| {
let (fact, _) = &candidates[**at];
fact.parameter_list
.as_deref()
.and_then(|list| {
crate::sema::overload::parameters_in(list)
.0
.into_iter()
.next()
})
.and_then(|first| the_character_width(&first))
== Some(written)
})
.copied()
.collect();
match definite[..] {
[only] => Some(only),
_ => None,
}
}
crate::sema::overload::Choice::None => None,
}
}
fn the_character_width(spelling: &str) -> Option<bool> {
if spelling.contains("wchar_t")
|| spelling.contains("wstring")
|| spelling.contains("wformat")
|| spelling.contains("wint_t")
{
return Some(true);
}
if spelling.contains("char") || spelling.contains("string") {
return Some(false);
}
None
}
fn member_callees(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
access: &crate::sema::resolve::MemberAccess,
) -> Known<Vec<Callee>> {
let object = match type_of_expression_memoed(
memo,
index,
declaring,
scopes,
root,
path,
&access.object,
0,
) {
Known::Yes((type_of, _)) => type_of,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => {
return Known::Unknown(UnknownReason::UnknownType(Box::from(
access.object.text().to_string(),
)));
}
};
let Some(class) = member_access_class(&object) else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(object.to_string())));
};
let found = match members_of(index, scopes, root, path, &class) {
Known::Yes(found) => found,
Known::Unknown(reason) => return Known::Unknown(reason),
Known::No => return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class))),
};
let wanted = &*access.member;
let candidates: Vec<Callee> = found
.members
.iter()
.filter(|member| member.fact.name == wanted)
.map(|member| Callee {
file: member.file.clone(),
name_offset: member.fact.name_range.start_offset,
parameters: member.fact.parameter_list.clone(),
})
.collect();
Known::Yes(candidates)
}
pub(crate) fn callee_of_a_call(
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
call: &cpp_parser::CppSyntaxNode,
) -> Known<Callee> {
let memo = TypeMemo::default();
let written = call.text().to_string();
let written = written.trim();
let Some(callee) = call.children().next() else {
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
};
match declaration_of_a_callee(
&memo, index, declaring, scopes, root, path, &callee, written,
) {
Known::Yes(named) => Known::Yes(Callee {
file: named.file(path),
name_offset: named.name_offset(),
parameters: named.parameter_list(),
}),
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
}
}
fn a_members_answer_as_a_type(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class_type: &Type,
returns: &str,
) -> String {
let Some(class) = class_type.class_name() else {
return returns.to_string();
};
let arguments: Vec<String> = class_type
.arguments()
.iter()
.map(|argument| argument.to_string())
.collect();
let parameters = index.template_parameters_for(class, path, &arguments);
let defaults = index.template_parameter_defaults_for(class, path, &arguments);
let substituted = crate::sema::types::substituted_spelling_with_defaults(
returns,
¶meters,
&defaults,
&arguments,
);
let (leading, core, trailing) = split_the_operators_of(&substituted);
if core.is_empty()
|| !core
.chars()
.all(|character| character.is_alphanumeric() || character == '_')
{
return substituted;
}
let Known::Yes((fact, _)) = member_fact(
index,
scopes,
root,
path,
&class_type.to_string(),
&core,
None,
) else {
return substituted;
};
let Some(target) = fact.type_of.as_deref() else {
return substituted;
};
let target = crate::sema::types::substituted_spelling_with_defaults(
target,
¶meters,
&defaults,
&arguments,
);
let target = a_spelling_through_the_aliases(
index,
scopes,
root,
path,
class_type,
&target,
MAX_ALIAS_HOPS,
);
format!("{leading}{target}{trailing}")
}
const MAX_ALIAS_HOPS: usize = 6;
fn a_spelling_through_the_aliases(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &Type,
written: &str,
depth: usize,
) -> String {
if depth == 0 {
return written.to_string();
}
let (leading, core, trailing) = split_the_operators_of(written);
let a_name = !core.is_empty()
&& core.chars().all(|character| {
character.is_alphanumeric() || matches!(character, '_' | ':' | '<' | '>' | ',' | ' ')
});
if !a_name {
return written.to_string();
}
let Some(class_name) = class.class_name() else {
return written.to_string();
};
let arguments: Vec<String> = class
.arguments()
.iter()
.map(|one| one.to_string())
.collect();
let parameters = index.template_parameters_for(class_name, path, &arguments);
let defaults = index.template_parameter_defaults_for(class_name, path, &arguments);
if crate::probes::inference() {
eprintln!(
"[inference] alias step: {written:?} in {class:?} (class {class_name:?}, parameters {parameters:?}, \
arguments {arguments:?})"
);
}
let Some((qualifier, last)) = split_at_the_last_scope(&core) else {
if let Some((named, member)) = the_alias_behind(index, path, &core) {
let qualified = format!("{named}::{member}");
if qualified != core {
let followed = a_spelling_through_the_aliases(
index,
scopes,
root,
path,
class,
&qualified,
depth.saturating_sub(1),
);
if followed != core {
return format!("{leading}{followed}{trailing}");
}
}
}
let Some(fact) =
a_member_the_class_declares(index, scopes, root, path, &class.to_string(), &core)
else {
return written.to_string();
};
let Some(target) = fact.type_of.as_deref() else {
return written.to_string();
};
let target = crate::sema::types::substituted_spelling_with_defaults(
target,
¶meters,
&defaults,
&arguments,
);
if target == core {
return written.to_string();
}
let followed =
a_spelling_through_the_aliases(index, scopes, root, path, class, &target, depth - 1);
return format!("{leading}{followed}{trailing}");
};
let qualifier = {
let substituted = crate::sema::types::substituted_spelling_with_defaults(
&qualifier,
¶meters,
&defaults,
&arguments,
);
if substituted.trim().is_empty() {
qualifier
} else {
substituted
}
};
let inner =
a_spelling_through_the_aliases(index, scopes, root, path, class, &qualifier, depth - 1);
if inner.trim() == qualifier.trim()
&& !matches!(members_of(index, scopes, root, path, &inner), Known::Yes(_))
{
return written.to_string();
}
let inner_type = crate::sema::types::parse_type_spelling(&inner);
let Some(inner_name) = inner_type.class_name() else {
return written.to_string();
};
let inner_arguments: Vec<String> = crate::sema::builtins::split_arguments(
inner
.split_once('<')
.map(|(_, rest)| rest.trim_end().strip_suffix('>').unwrap_or(rest))
.unwrap_or_default(),
);
let inner_parameters = index.template_parameters_for(inner_name, path, &inner_arguments);
let inner_defaults = index.template_parameter_defaults_for(inner_name, path, &inner_arguments);
let found = a_member_the_class_declares(index, scopes, root, path, &inner, &last);
if crate::probes::inference() {
eprintln!(
"[inference] qualified: {written:?} -> qualifier {qualifier:?} resolved {inner:?}, member {last:?}, fact {:?}",
found
.as_ref()
.map(|fact| (fact.type_of.clone(), fact.pattern.clone()))
);
}
let Some(fact) = found else {
return written.to_string();
};
let Some(target) = fact.type_of.as_deref() else {
return written.to_string();
};
let (pattern_parameters, pattern_arguments) = fact
.pattern
.as_deref()
.map(|pattern| the_pairing_its_pattern_implies(pattern, &inner_arguments))
.filter(|(parameters, _)| !parameters.is_empty())
.unwrap_or_else(|| (inner_parameters.clone(), inner_arguments.clone()));
let target = crate::sema::types::substituted_spelling_with_defaults(
target,
&pattern_parameters,
&inner_defaults,
&pattern_arguments,
);
let followed =
a_spelling_through_the_aliases(index, scopes, root, path, &inner_type, &target, depth - 1);
format!("{leading}{followed}{trailing}")
}
fn a_member_the_class_declares(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
name: &str,
) -> Option<DeclFact> {
let listed = members_of(index, scopes, root, path, class);
if crate::probes::inference() {
match &listed {
Known::Yes(members) => eprintln!(
"[inference] member of {class:?}: {} listed, {} unlisted, looking for {name:?}",
members.members.len(),
members.unlisted.len()
),
other => eprintln!("[inference] member of {class:?}: {other:?}"),
}
}
if let Some(found) = listed.value().and_then(|members| {
members
.members
.iter()
.filter(|member| member.fact.name == name)
.map(|member| member.fact.clone())
.find(|fact| fact.type_of.is_some())
}) {
return Some(found);
}
direct_member(index, scopes, root, path, class, name, None).map(|(fact, _)| fact)
}
fn the_pairing_its_pattern_implies(
pattern: &str,
written: &[String],
) -> (Vec<String>, Vec<String>) {
let slots = arguments_in_a_spelling(pattern).unwrap_or_default();
let mut parameters = Vec::new();
let mut arguments = Vec::new();
for (at, slot) in slots.iter().enumerate() {
let slot = slot.trim();
let Some(argument) = written.get(at) else {
continue;
};
let a_name = !slot.is_empty()
&& slot
.chars()
.all(|character| character.is_alphanumeric() || character == '_')
&& !matches!(slot, "true" | "false");
if a_name {
parameters.push(slot.to_string());
arguments.push(argument.clone());
}
}
(parameters, arguments)
}
fn split_at_the_last_scope(spelling: &str) -> Option<(String, String)> {
let bytes = spelling.as_bytes();
let mut depth = 0usize;
let mut boundary = None;
let mut at = 0usize;
while at + 1 < bytes.len() {
match bytes[at] {
b'<' => depth += 1,
b'>' => depth = depth.saturating_sub(1),
b':' if depth == 0 && bytes[at + 1] == b':' => {
boundary = Some(at);
at += 1;
}
_ => {}
}
at += 1;
}
let boundary = boundary?;
let qualifier = spelling[..boundary].trim().to_string();
let last = spelling[boundary + 2..].trim().to_string();
(!qualifier.is_empty() && !last.is_empty()).then_some((qualifier, last))
}
fn split_the_operators_of(spelling: &str) -> (String, String, String) {
let mut leading = String::new();
let mut rest = spelling.trim();
for qualifier in ["const", "volatile", "constexpr", "static"] {
if let Some(after) = rest.strip_prefix(qualifier)
&& after.starts_with(char::is_whitespace)
{
leading.push_str(qualifier);
leading.push(' ');
rest = after.trim_start();
}
}
loop {
let trimmed = rest.trim_start();
let Some(after) = ["typename", "class", "struct", "union", "enum"]
.iter()
.find_map(|keyword| trimmed.strip_prefix(keyword))
else {
break;
};
if !after.starts_with(char::is_whitespace) {
break;
}
rest = after.trim_start();
}
let trimmed = rest.trim_end();
let mut trailing = String::new();
let mut core = trimmed;
for _ in 0..4 {
if let Some(before) = core
.strip_suffix("&&")
.or_else(|| core.strip_suffix('&'))
.or_else(|| core.strip_suffix('*'))
{
let operator = &core[before.len()..];
trailing.insert_str(0, operator);
core = before.trim_end();
continue;
}
break;
}
(leading, core.to_string(), trailing)
}
fn through_an_operator_arrow(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
member: &str,
arguments: Option<&[String]>,
) -> Option<(DeclFact, PathBuf)> {
let target = the_class_an_arrow_points_at(index, scopes, root, path, class, arguments)?;
direct_member(index, scopes, root, path, &target, member, None)
}
fn the_class_an_arrow_points_at(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
arguments: Option<&[String]>,
) -> Option<String> {
let bare = without_arguments(class).to_string();
let arguments: Vec<String> = arguments
.map(<[String]>::to_vec)
.or_else(|| {
class.split_once('<').map(|(_, rest)| {
crate::sema::builtins::split_arguments(
rest.trim_end().strip_suffix('>').unwrap_or(rest),
)
})
})
.unwrap_or_default();
let (arrow, _) = direct_member(
index,
scopes,
root,
path,
&bare,
"operator->",
Some(&arguments),
)?;
let returns = arrow.returns?;
if crate::probes::inference() {
eprintln!(
"[inference] operator-> of {bare} on arguments {arguments:?}: the member wrote {returns:?}"
);
}
if arguments.is_empty() {
return None;
}
let parameters = index.template_parameters_for(&bare, path, &arguments);
let defaults = index.template_parameter_defaults_for(&bare, path, &arguments);
let class_type = crate::sema::types::parse_type_spelling(class);
let resolved = a_spelling_through_the_aliases(
index,
scopes,
root,
path,
&class_type,
&returns,
MAX_ALIAS_HOPS,
);
let substituted = crate::sema::types::substituted_spelling_with_defaults(
&resolved,
¶meters,
&defaults,
&arguments,
);
let mut target = base_type_name(&substituted).to_string();
let names_nothing =
index.files_declaring(&target, path).is_empty() && !is_a_builtin_name(&target);
if target.is_empty()
|| target == bare
|| names_nothing
|| arrow.parameters.iter().any(|name| name == &target)
{
let names_a_class = |name: &str| {
let bare = base_type_name(name);
is_a_builtin_name(bare)
|| index.files_declaring(bare, path).iter().any(|found| {
found.fact.kind == crate::DeclKind::Type && found.fact.type_of.is_none()
})
};
let walked = the_element_type_of(index, scopes, root, path, class, &bare, &arguments);
target = match walked {
Some(walked) if names_a_class(&walked) => walked,
_ => match arguments.as_slice() {
[only] if names_a_class(only) => base_type_name(only).to_string(),
_ => target,
},
};
}
if crate::probes::inference() {
eprintln!(
"[inference] operator-> substitution: parameters {parameters:?}, the member's own {arrow_parameters:?}, {returns:?} -> {substituted:?} -> {target:?}",
arrow_parameters = arrow.parameters
);
}
(!target.is_empty() && target != bare).then_some(target)
}
fn is_a_builtin_name(name: &str) -> bool {
matches!(
name,
"int"
| "char"
| "bool"
| "void"
| "float"
| "double"
| "long"
| "short"
| "signed"
| "unsigned"
| "auto"
| "wchar_t"
| "char8_t"
| "char16_t"
| "char32_t"
| "size_t"
)
}
pub fn element_type_of(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
bare: &str,
arguments: &[String],
) -> Option<String> {
the_element_type_of(index, scopes, root, path, class, bare, arguments)
}
fn the_element_type_of(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
bare: &str,
arguments: &[String],
) -> Option<String> {
let parameters = index.template_parameters_for(bare, path, arguments);
let through_the_members = an_element_type_through_the_members(
index,
scopes,
root,
path,
class,
¶meters,
arguments,
0,
);
if through_the_members.is_some() {
return through_the_members;
}
let Known::Yes(members) = members_of(index, scopes, root, path, class) else {
if crate::probes::inference() {
eprintln!("[inference] element_type: no member list for {class}");
}
return None;
};
if crate::probes::inference() {
let found: Vec<String> = members
.members
.iter()
.filter(|member| matches!(member.fact.name.as_str(), "element_type" | "value_type"))
.map(|member| {
format!(
"{} kind {:?} type_of {:?}",
member.fact.name, member.fact.kind, member.fact.type_of
)
})
.collect();
eprintln!(
"[inference] element_type: {class} has {} member(s), {found:?}",
members.members.len()
);
}
for name in ["element_type", "value_type"] {
let Some(fact) = members
.members
.iter()
.find(|member| member.fact.name == name)
.map(|member| &member.fact)
else {
continue;
};
let Some(written) = fact.type_of.as_deref() else {
continue;
};
let substituted = crate::sema::types::substituted_spelling(written, ¶meters, arguments);
let target = base_type_name(&substituted).to_string();
if crate::probes::inference() {
eprintln!(
"[inference] element_type: {class}::{name} wrote {written:?} -> {substituted:?} -> {target:?} ({} member(s))",
members.members.len()
);
}
if !target.is_empty()
&& target != bare
&& !parameters.iter().any(|parameter| parameter == &target)
{
return Some(target);
}
}
None
}
fn member_fact(
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(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
}
fn member_fact_inner(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
member: &str,
arguments: Option<&[String]>,
) -> Known<(DeclFact, PathBuf)> {
let class = &resolve_aliases(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(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(index, scopes, root, path, &declared_in, member, arguments)
{
return Known::Yes(found);
}
}
let parameters = class_template_parameters(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(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}"
))))
}
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
}
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(index, scopes, root, path, class);
crate::sema::types::TypeBindings::new(names, arguments.to_vec())
}
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(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
}
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
}
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
}
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)
}
fn class_template_parameters(
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_of(root, binding);
if !found.is_empty() {
return found;
}
}
index.template_parameters_of(class, path)
}
const MAX_ALIAS_DEPTH: usize = 8;
fn resolve_aliases(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> String {
resolve_aliases_with_arguments(index, scopes, root, path, class).0
}
fn resolve_aliases_with_arguments(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> (String, Vec<Type>) {
let (name, carried, _unresolved) =
resolve_aliases_or_unresolved(index, scopes, root, path, class);
(name, carried)
}
fn resolve_aliases_or_unresolved(
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(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(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 Some(target) = target_type.class_name().map(a_class_name_without_spaces) else {
break;
};
if target.is_empty() {
break;
}
if !target_type.arguments().is_empty() {
carried = target_type.arguments().to_vec();
}
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)
}
fn a_class_name_without_spaces(name: &str) -> String {
name.chars()
.filter(|character| !character.is_whitespace())
.collect()
}
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
}
fn alias_target_of(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Option<(String, Option<String>)> {
let stripped_qualifier = without_template_arguments(class);
let class = match (class.rfind('<'), class.rfind("::")) {
(Some(argument_list), Some(scope)) if argument_list < scope => stripped_qualifier.as_str(),
_ => 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(root, binding)
{
let target = crate::sema::types::substituted_spelling(
&target,
&crate::sema::declarations::declared_template_parameters_of(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| {
(
crate::sema::types::substituted_spelling(
&target,
&declaration.fact.parameters,
&written_arguments,
),
declaration.fact.scope.clone(),
)
})
}),
Known::Unknown(_) | Known::No => None,
}
}
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(_))
)
}
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
}
fn direct_member(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
member: &str,
arguments: Option<&[String]>,
) -> Option<(DeclFact, PathBuf)> {
let class = &resolve_aliases(index, scopes, root, path, class);
if let Some(scope) = scopes.scope_with_qualified_name(class)
&& let Some(scope_data) = scopes.scope(scope)
&& let Some(binding) = scope_data
.bindings
.iter()
.find(|binding| binding.name.identifier_text() == Some(member))
{
return Some((fact_from_binding(root, class, binding), path.to_path_buf()));
}
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 (class, arguments) = match (class.split_once('<'), from_the_spelling.as_ref()) {
(Some((head, _)), Some(written)) => (head.trim(), Some(written.as_slice())),
_ => (class.as_str(), arguments),
};
if let Some(found) = index
.declarations_in(class, path)
.into_iter()
.find(|declaration| {
declaration.fact.name == member
&& a_pattern_matches(
declaration.fact.pattern.as_deref(),
&declaration.fact.parameters,
arguments,
)
})
{
return Some((found.fact.clone(), found.file.clone()));
}
match index.definition(&format!("{class}::{member}"), path) {
Known::Yes(found) => Some((found.fact, found.file)),
Known::Unknown(_) | Known::No => None,
}
}
fn a_pattern_matches(
pattern: Option<&str>,
parameters: &[String],
written: Option<&[String]>,
) -> bool {
let (Some(pattern), Some(written)) = (pattern, written) else {
return true;
};
let Some(slots) = arguments_in_a_spelling(pattern) else {
return true;
};
if slots.len() != written.len() {
return true;
}
slots.iter().zip(written).all(|(slot, argument)| {
let slot = slot.trim();
parameters.iter().any(|name| name == slot) || slot == folded_for_matching(argument).trim()
})
}
fn arguments_in_a_spelling(written: &str) -> Option<Vec<String>> {
let (_, after) = written.split_once('<')?;
let inside = after.trim_end().strip_suffix('>')?;
let mut out = Vec::new();
let mut depth = 0usize;
let mut at = 0usize;
for (index, character) in inside.char_indices() {
match character {
'<' | '(' | '[' => depth += 1,
'>' | ')' | ']' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
out.push(inside[at..index].to_string());
at = index + 1;
}
_ => {}
}
}
out.push(inside[at..].to_string());
let out: Vec<String> = out
.into_iter()
.map(|argument| argument.trim().to_string())
.filter(|argument| !argument.is_empty())
.collect();
(!out.is_empty()).then_some(out)
}
fn fact_from_binding(
root: &cpp_parser::CppSyntaxNode,
class: &str,
binding: &crate::Binding,
) -> DeclFact {
fact_from_binding_with(
&crate::sema::declarations::DeclarationShapes::of(root),
root,
class,
binding,
)
}
fn fact_from_binding_with(
shapes: &crate::sema::declarations::DeclarationShapes,
root: &cpp_parser::CppSyntaxNode,
class: &str,
binding: &crate::Binding,
) -> DeclFact {
let _ = root;
DeclFact {
name: binding.name.text(),
scope: (!class.is_empty()).then(|| class.to_string()),
local: false,
in_namespace: None,
kind: crate::DeclKind::from_binding_kind(binding.kind),
modifiers: crate::sema::declarations::declared_modifiers_with(shapes, binding),
frees: crate::sema::declarations::freed_parameters_of(root, binding),
reflection: None,
type_of: crate::sema::declarations::declared_type_of_with(shapes, binding),
returns: crate::sema::declarations::declared_returns_of_in(shapes, root, binding)
.or_else(|| crate::sema::declarations::declared_returns_of(root, binding)),
split_by_a_directive: crate::sema::declarations::split_by_a_directive_with(shapes, binding),
bases: crate::sema::declarations::declared_bases_of_with(shapes, binding),
parameters: crate::sema::declarations::declared_template_parameters_with(shapes, binding),
constraints: Vec::new(),
requires_clause: crate::sema::declarations::the_requires_clause_with(shapes, binding),
parameter_defaults: crate::sema::declarations::declared_parameter_defaults_with(
shapes, binding,
),
pattern: crate::sema::declarations::pattern_of(shapes, binding),
parameter_list: match binding.kind {
crate::BindingKind::Function
| crate::BindingKind::Constructor
| crate::BindingKind::Destructor
| crate::BindingKind::ConversionFunction
| crate::BindingKind::OperatorFunction
| crate::BindingKind::LiteralOperator => {
crate::sema::declarations::declared_parameters_with(shapes, binding)
}
_ => None,
},
access: shapes.access_at(binding.name_range.start_offset),
exported: shapes.exported_at(binding.name_range.start_offset),
definition: true,
range: binding.range,
name_range: binding.name_range,
clean: true,
guard: FactGuard::Unconditional,
}
}
fn names_a_template_parameter(spelling: &str, parameters: &[String]) -> bool {
if parameters.is_empty() {
return false;
}
let head = without_arguments(spelling.trim());
let head = head.strip_prefix("::").unwrap_or(head);
parameters
.iter()
.any(|parameter| parameter == head || parameter == head.rsplit("::").next().unwrap_or(head))
}
fn bases_of(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
) -> Known<Vec<String>> {
bases_of_inner(index, scopes, root, path, class)
}
fn bases_of_inner(
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(lookup_names(&crate::sema::declarations::declared_bases_of(
root, binding,
)));
}
match index.definitions(class, path) {
Known::Yes(found) => {
let mut bases: Vec<String> = Vec::new();
for declaration in &found.found {
for base in lookup_names(&declaration.fact.bases) {
if !bases.contains(&base) {
bases.push(base);
}
}
}
if bases.is_empty()
&& let Some(bare) = class.rsplit("::").next()
{
for (_, fact) in index.every_fact_named(bare) {
if fact.kind != crate::DeclKind::Type {
continue;
}
for base in lookup_names(&fact.bases) {
if !bases.contains(&base) {
bases.push(base);
}
}
}
}
Known::Yes(bases)
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::No,
}
}
fn lookup_names(bases: &[String]) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
for base in bases {
let parsed = crate::sema::types::parse_type_spelling(base);
collect_class_names(&parsed, &mut names);
}
names
}
fn collect_class_names(ty: &crate::sema::types::Type, into: &mut Vec<String>) {
if let Some(name) = ty.class_name()
&& !name.is_empty()
&& !into.iter().any(|kept| kept == name)
{
into.push(name.to_string());
}
for argument in ty.arguments() {
collect_class_names(argument, into);
}
}
fn resolved_in_the_enclosing_scopes(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
path: &Path,
owner: &str,
base: &str,
) -> String {
if base.contains("::") {
return base.to_string();
}
let mut enclosing = owner;
while let Some((outer, _)) = enclosing.rsplit_once("::") {
let candidate = format!("{outer}::{base}");
if is_declared(index, scopes, path, &candidate) {
return candidate;
}
enclosing = outer;
}
base.to_string()
}
fn enclosing_class(scopes: &crate::ScopeTree, offset: usize) -> Option<String> {
let innermost = scopes.scope_at(offset)?;
scopes.scope_chain(innermost).into_iter().find_map(|scope| {
let data = scopes.scope(scope)?;
(data.kind == crate::ScopeKind::Class)
.then(|| scopes.qualified_name_of(scope))
.flatten()
})
}
pub(crate) fn class_of_the_enclosing_definition(
scopes: &crate::ScopeTree,
offset: usize,
) -> Option<String> {
if let Some(class) = enclosing_class(scopes, offset) {
return Some(class);
}
let innermost = scopes.scope_at(offset)?;
let qualified = scopes.qualified_name_of(innermost)?;
let (class, _member) = qualified.rsplit_once("::")?;
(!class.is_empty()).then(|| class.to_string())
}
fn the_trailing_argument_list(written: &str) -> Option<usize> {
if !written.ends_with('>') {
return None;
}
let mut depth = 0usize;
for (at, character) in written.char_indices().rev() {
match character {
'>' => depth += 1,
'<' => {
if depth == 0 {
return None;
}
depth -= 1;
if depth == 0 {
return Some(at);
}
}
_ => {}
}
}
None
}
pub(crate) fn base_type_name(written: &str) -> &str {
let mut name = written.trim();
loop {
let before = name;
name = name.trim_end_matches(['*', '&']).trim();
name = name.strip_prefix("::").unwrap_or(name).trim();
if let Some(opening) = the_trailing_argument_list(name) {
name = name[..opening].trim();
}
if name == before {
break;
}
}
for keyword in ["struct ", "class ", "union ", "enum "] {
if let Some(rest) = name.strip_prefix(keyword) {
name = rest.trim();
break;
}
}
name
}
fn the_walk_inputs_of(summary: &FileSummary) -> u64 {
let mut bytes: Vec<u8> = Vec::new();
for include in &summary.includes {
bytes.extend_from_slice(include.spelling.as_bytes());
bytes.push(0);
match &include.resolved {
Some(path) => bytes.extend_from_slice(path.to_string_lossy().as_bytes()),
None => bytes.push(1),
}
bytes.push(0);
bytes.push(u8::from(include.is_next));
bytes.push(match include.guard {
crate::FactGuard::Unconditional => 0,
crate::FactGuard::Region(region) => 1 + (region.min(u32::from(u8::MAX) - 1) as u8),
});
}
for conditional in &summary.guards.conditionals {
for branch in &conditional.branches {
bytes.extend_from_slice(format!("{:?}", branch.kind).as_bytes());
bytes.push(0);
match &branch.condition {
Some(text) => bytes.extend_from_slice(text.as_bytes()),
None => bytes.push(1),
}
bytes.push(0);
}
}
for fact in &summary.macros {
bytes.extend_from_slice(fact.name.as_bytes());
bytes.push(0);
bytes.push(u8::from(fact.kind.is_definition()));
bytes.push(u8::from(fact.function_like));
match &fact.value {
Some(value) => bytes.extend_from_slice(value.as_bytes()),
None => bytes.push(1),
}
bytes.push(0);
match &fact.alias {
Some(alias) => bytes.extend_from_slice(alias.as_bytes()),
None => bytes.push(1),
}
bytes.push(0);
bytes.push(match fact.guard {
crate::FactGuard::Unconditional => 0,
crate::FactGuard::Region(region) => 1 + (region.min(u32::from(u8::MAX) - 1) as u8),
});
}
bytes.extend_from_slice(format!("{:?}", summary.modules).as_bytes());
crate::cache::fnv1a64(&bytes)
}
impl ProjectIndex {
pub fn new() -> Self {
ProjectIndex {
macros: Marked::default().incomplete(),
visibility_answers: std::sync::Mutex::new(HashMap::new()),
type_answers: std::sync::Mutex::new(HashMap::new()),
type_hits: std::sync::atomic::AtomicU64::new(0),
type_misses: std::sync::atomic::AtomicU64::new(0),
visibility: std::sync::Mutex::new(HashMap::new()),
walking: std::sync::Mutex::new(std::collections::HashSet::new()),
walks_built: std::sync::atomic::AtomicU64::new(0),
walks_hit: std::sync::atomic::AtomicU64::new(0),
walks_met: std::sync::atomic::AtomicU64::new(0),
..ProjectIndex::default()
}
}
fn claim_a_walk(&self, root: &str) -> bool {
match self.walking.lock() {
Ok(mut held) => held.insert(root.to_string()),
Err(_) => true,
}
}
fn a_walk_is_over(&self, root: &str) {
if let Ok(mut held) = self.walking.lock() {
held.remove(root);
self.walk_done.notify_all();
}
}
fn wait_for_the_walk(&self, root: &str) {
let Ok(mut held) = self.walking.lock() else {
return;
};
while held.contains(root) {
match self
.walk_done
.wait_timeout(held, std::time::Duration::from_millis(50))
{
Ok((next, _)) => held = next,
Err(_) => return,
}
}
}
pub fn walk_counts(&self) -> (u64, u64, u64) {
(
self.walks_built.load(std::sync::atomic::Ordering::Relaxed),
self.walks_hit.load(std::sync::atomic::Ordering::Relaxed),
self.walks_met.load(std::sync::atomic::Ordering::Relaxed),
)
}
pub fn with_macros(mut self, macros: Marked) -> Self {
self.macros = macros;
self
}
pub fn macros(&self) -> &Marked {
&self.macros
}
fn invalidate_visibility_answers(&self, path: &Path, known: bool) {
let affected = known.then(|| {
std::iter::once(normalize(path))
.chain(
self.dependents_of(path)
.iter()
.map(|dependent| normalize(dependent)),
)
.collect::<HashSet<_>>()
});
let mut answers = self
.visibility_answers
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(affected) = affected {
answers.retain(|(file, _), _| !affected.contains(file));
} else {
answers.clear();
}
}
pub fn insert(&mut self, summary: FileSummary) {
let path = summary.path.clone();
self.insert_at(&path, summary);
}
pub fn insert_at(&mut self, path: &Path, summary: FileSummary) {
self.changed = self.changed.wrapping_add(1);
let rewritten = normalize(path);
let known_to_the_index =
self.known_paths.contains(&rewritten) || self.summaries.contains_key(&rewritten);
self.invalidate_visibility_answers(path, known_to_the_index);
if let Ok(mut answers) = self.type_answers.lock() {
answers.clear();
}
if let Ok(mut declared) = self.definition_answers.lock() {
declared.clear();
}
self.known_paths.insert(rewritten.clone());
self.forget_member_lists(path);
self.forget_guard_answers(path);
self.forget_macro_walks(path, known_to_the_index);
let mut summary = summary;
summary.path = path.to_path_buf();
let path = normalize(path);
let sequence = if let Some(previous) = self.summaries.get(&path) {
let sequence = self.sequence[&path];
for target in include_targets(previous) {
if let Some(includers) = self.included_by.get_mut(&target) {
includers.remove(&path);
}
}
self.names
.remove_declarations(sequence, 0, &previous.declarations);
self.names.remove_macros(sequence, &previous.macros);
if previous.key != summary.key {
self.forget_the_readings_of(&path);
}
sequence
} else {
let sequence = match self.sequence.get(&path) {
Some(&known) => known,
None => {
let sequence = self.next_sequence;
self.next_sequence += 1;
sequence
}
};
self.order.insert(sequence, path.clone());
self.sequence.insert(path.clone(), sequence);
self.sequence.insert(normalize(Path::new(&path)), sequence);
if let Some(readings) = self.cooked.get(&path) {
for (id, reading) in readings.every() {
self.names
.add_declarations(sequence, id, &reading.declarations);
}
}
sequence
};
for target in include_targets(&summary) {
self.included_by
.entry(target)
.or_default()
.insert(path.clone());
}
self.module_interfaces
.retain(|_, declaring| declaring != &path);
if summary.modules.is_interface
&& let Some(module) = &summary.modules.module
&& summary.modules.partition.is_none()
{
self.module_interfaces
.insert(module.to_string(), path.clone());
}
self.names
.add_declarations(sequence, 0, &summary.declarations);
self.names.add_macros(sequence, &summary.macros);
self.walk_inputs
.insert(path.clone(), the_walk_inputs_of(&summary));
self.summaries.insert(path, summary);
}
pub fn forget(&mut self, path: &Path) -> bool {
self.changed = self.changed.wrapping_add(1);
let path = normalize(path);
let Some(summary) = self.summaries.remove(&path) else {
return false;
};
self.invalidate_visibility_answers(Path::new(&path), true);
self.walk_inputs.remove(&path);
if let Ok(mut answers) = self.type_answers.lock() {
answers.clear();
}
if let Ok(mut declared) = self.definition_answers.lock() {
declared.clear();
}
self.forget_member_lists(Path::new(&path));
self.forget_guard_answers(Path::new(&path));
self.forget_macro_walks(Path::new(&path), true);
for target in include_targets(&summary) {
if let Some(includers) = self.included_by.get_mut(&target) {
includers.remove(&path);
}
}
self.forget_the_readings_of(&path);
let sequence = self
.sequence
.get(&path)
.copied()
.or_else(|| self.sequence.get(&normalize(Path::new(&path))).copied());
if let Some(sequence) = sequence {
self.names
.remove_declarations(sequence, 0, &summary.declarations);
self.names.remove_macros(sequence, &summary.macros);
}
true
}
pub(crate) fn a_remembered_type(
&self,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
) -> Option<Known<(Type, PathBuf)>> {
let key = the_type_key(path, expression);
let remembered = self
.type_answers
.lock()
.ok()
.and_then(|answers| answers.get(&key).cloned());
if remembered.is_some() {
self.type_hits
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
} else {
self.type_misses
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
remembered
}
pub fn type_cache_stats(&self) -> (u64, u64) {
(
self.type_hits.load(std::sync::atomic::Ordering::Relaxed),
self.type_misses.load(std::sync::atomic::Ordering::Relaxed),
)
}
pub(crate) fn remember_a_type(
&self,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
answer: &Known<(Type, PathBuf)>,
) {
let key = the_type_key(path, expression);
if let Ok(mut answers) = self.type_answers.lock() {
if answers.len() >= MAX_TYPE_ANSWERS {
answers.clear();
}
answers.insert(key, answer.clone());
}
}
pub fn len(&self) -> usize {
self.summaries.len()
}
pub fn is_empty(&self) -> bool {
self.summaries.is_empty()
}
pub fn summary(&self, path: &Path) -> Option<&FileSummary> {
if crate::probes::summaries() {
crate::probes::a_summary_was_asked_for(path);
}
self.summaries.get(&normalize(path))
}
pub fn interface_unit_of(&self, name: &str) -> Option<&str> {
self.module_interfaces.get(name).map(String::as_str)
}
pub fn remember_the_unit_closure(&self, module: &str, mut files: Vec<String>) {
files.sort();
files.dedup();
if let Ok(mut closures) = self.unit_closures.lock() {
closures.insert(module.to_string(), files);
}
if let Ok(mut walks) = self.visibility.lock() {
walks.clear();
}
}
pub fn unit_closure_of(&self, module: &str) -> Option<Vec<String>> {
self.unit_closures
.lock()
.ok()
.and_then(|closures| closures.get(module).cloned())
}
pub fn interface_units(&self) -> Vec<(String, String)> {
let mut all: Vec<(String, String)> = self
.module_interfaces
.iter()
.map(|(name, unit)| (name.clone(), unit.clone()))
.collect();
all.sort();
all
}
pub fn summaries(&self) -> impl Iterator<Item = &FileSummary> {
self.order
.values()
.filter_map(|path| self.summaries.get(path))
}
pub fn includers_of(&self, path: &Path) -> Vec<PathBuf> {
self.included_by
.get(&normalize(path))
.map(|includers| includers.iter().map(PathBuf::from).collect())
.unwrap_or_default()
}
pub fn insert_cooked(&mut self, path: &Path, reading: CookedFile) {
self.insert_a_reading(path, None, reading);
}
pub fn insert_cooked_in_a_program(&mut self, path: &Path, program: u64, reading: CookedFile) {
self.insert_a_reading(path, Some(program), reading);
}
fn insert_a_reading(&mut self, path: &Path, program: Option<u64>, reading: CookedFile) {
let path = normalize(path);
let (id, changed) = {
let readings = self.cooked.get(&path);
let existing = match program {
None => Some(Readings::ON_ITS_OWN),
Some(program) => readings.and_then(|readings| readings.id_for(program)),
};
match existing {
Some(id) => (
id,
readings
.and_then(|readings| readings.reading(id))
.is_none_or(|previous| previous.declarations != reading.declarations),
),
None => (
readings.map_or(2, |readings| readings.in_a_program.len() as u32 + 2),
true,
),
}
};
if changed {
self.forget_member_lists(Path::new(&path));
}
self.definition_answers
.lock()
.expect("the definition memo is not poisoned")
.clear();
let tracing = std::env::var("CPPLS_TRACE_NAMES").is_ok()
&& (path.ends_with("stl_map.h") || path.ends_with("iostream"));
if tracing {
eprintln!(
"[names] insert_a_reading {}: sequence {:?} id {id} declarations {} diagnostics {:?}",
path,
self.sequence.get(&path),
reading.declarations.len(),
reading
.diagnostics
.iter()
.take(3)
.map(|diagnostic| &diagnostic.message)
.collect::<Vec<_>>()
);
}
if let Some(&sequence) = self.sequence.get(&path) {
let previous = self
.cooked
.get(&path)
.and_then(|readings| readings.reading(id))
.map(|previous| &previous.declarations);
if let Some(previous) = previous {
self.names.remove_declarations(sequence, id, previous);
}
self.names
.add_declarations(sequence, id, &reading.declarations);
}
let readings = self.cooked.entry(path.clone()).or_default();
match program {
None => readings.on_its_own = Some(reading),
Some(program) => {
match readings.id_for(program) {
Some(id) => readings.in_a_program[id as usize - 2] = (program, reading),
None => readings.in_a_program.push((program, reading)),
}
readings.last = Some(program);
}
}
debug_assert!(
readings.reading(id).is_some(),
"the id an insert decided on is the id it filled"
);
self.cooked_order.push_back(path);
while self.cooked.len() > MAX_COOKED_FILES {
let Some(oldest) = self.cooked_order.pop_front() else {
break;
};
self.forget_the_readings_of(&oldest);
}
}
fn forget_the_readings_of(&mut self, path: &str) {
let Some(readings) = self.cooked.remove(path) else {
return;
};
if let Some(&sequence) = self.sequence.get(path) {
for (id, reading) in readings.every() {
self.names
.remove_declarations(sequence, id, &reading.declarations);
}
}
}
pub fn cooked_size(&self) -> (usize, usize) {
let declarations = self
.cooked
.values()
.flat_map(|readings| readings.every())
.map(|(_, reading)| reading.declarations.len())
.sum();
(self.cooked.len(), declarations)
}
pub fn accounting(&self) -> (usize, usize, usize, usize) {
let summary_bytes = self
.summaries
.values()
.map(FileSummary::heap_bytes)
.sum::<usize>();
let mut cooked_bytes = 0usize;
for readings in self.cooked.values() {
for (_, reading) in readings.every() {
cooked_bytes += std::mem::size_of::<CookedFile>()
+ reading
.declarations
.iter()
.map(DeclFact::heap_bytes)
.sum::<usize>()
+ reading
.macros
.iter()
.map(MacroFact::heap_bytes)
.sum::<usize>()
+ reading.diagnostics.len() * std::mem::size_of::<crate::CookedDiagnostic>();
}
}
(
self.summaries.len(),
summary_bytes,
self.cooked.len(),
cooked_bytes,
)
}
pub fn table_accounting(&self) -> TableCost {
let names = self.names.accounting();
let mut edges = 0usize;
let mut edge_bytes = 0usize;
for (included, includers) in &self.included_by {
edges += includers.len();
edge_bytes += included.len() + std::mem::size_of::<BTreeSet<String>>();
edge_bytes += includers
.iter()
.map(|includer| includer.len() + std::mem::size_of::<String>())
.sum::<usize>();
}
edge_bytes += self
.included_by
.keys()
.map(|key| key.len() + std::mem::size_of::<String>())
.sum::<usize>();
let modules: usize = self
.module_interfaces
.iter()
.map(|(name, path)| name.len() + path.len() + 2 * std::mem::size_of::<String>())
.sum();
let (member_list_entries, member_lists, member_list_bytes) = self
.member_lists
.lock()
.map(|lists| {
let members: usize = lists.values().map(|held| held.list.members.len()).sum();
let bytes: usize = lists
.values()
.map(|held| {
let members: usize = held
.list
.members
.iter()
.map(|member| {
std::mem::size_of::<crate::ProjectMember>()
+ DeclFact::heap_bytes(&member.fact)
})
.sum();
let unlisted =
held.list.unlisted.len() * std::mem::size_of::<crate::UnlistedBase>();
members
+ unlisted
+ held.contributors.len() * std::mem::size_of::<PathBuf>()
+ held
.contributors
.iter()
.map(|path| path.to_string_lossy().len())
.sum::<usize>()
})
.sum();
(lists.len(), members, bytes)
})
.unwrap_or_default();
let (guard_entries, guard_bytes) = self
.guard_answers
.lock()
.map(|answers| {
(
answers.len(),
answers.len()
* (std::mem::size_of::<(PathBuf, usize, u32)>()
+ std::mem::size_of::<crate::Visibility>()),
)
})
.unwrap_or_default();
let (visibility_entries, visibility_bytes) = self
.visibility
.lock()
.map(|walks| {
let bytes: usize = walks
.values()
.map(|walk| {
let reached = walk.seen.visibility.len();
let names: usize = walk
.seen
.visibility
.keys()
.map(|path| path.len() * 2 + 48)
.sum();
names
+ reached * std::mem::size_of::<IncludeVisibility>()
+ walk.contributors.len() * std::mem::size_of::<String>()
})
.sum();
(walks.len(), bytes)
})
.unwrap_or_default();
let (condition_entries, condition_bytes) = self
.visibility_answers
.lock()
.map(|answers| {
(
answers.len(),
answers.len()
* (std::mem::size_of::<(String, u32)>()
+ std::mem::size_of::<crate::Visibility>()
+ 24),
)
})
.unwrap_or_default();
let path_bytes: usize = self
.order
.values()
.map(|path| path.len() + std::mem::size_of::<String>())
.sum::<usize>()
+ self
.sequence
.keys()
.map(|path| path.len() + std::mem::size_of::<String>())
.sum::<usize>();
TableCost {
names,
edges,
edge_bytes: edge_bytes + modules,
member_list_entries,
member_lists,
member_list_bytes,
guard_entries,
guard_bytes,
visibility_entries,
visibility_bytes,
condition_entries,
condition_bytes,
path_bytes,
}
}
pub fn cooked_declarations(&self, path: &Path) -> Option<&[DeclFact]> {
Some(self.cooked_reading(path)?.declarations.as_slice())
}
pub fn cooked_reading(&self, path: &Path) -> Option<&CookedFile> {
self.cooked.get(&normalize(path))?.any()
}
fn the_reading_for(&self, file: u32, asking: Option<u64>) -> u32 {
let Some(readings) = self.order.get(&file).and_then(|key| self.cooked.get(key)) else {
return 0;
};
if let Some(id) = asking.and_then(|program| readings.id_for(program)) {
return id;
}
if readings.on_its_own.is_some() {
return Readings::ON_ITS_OWN;
}
readings
.last
.and_then(|program| readings.id_for(program))
.unwrap_or(0)
}
pub fn the_program_that_read(&self, path: &Path) -> Option<u64> {
if let Some(summary) = self.summaries.get(&normalize(path)) {
for name in &summary.modules.imports {
let Some(interface) = self.module_interfaces.get(name.as_ref()) else {
continue;
};
if let Some(program) = self
.cooked
.get(&normalize(Path::new(interface.as_str())))
.and_then(|readings| readings.last)
{
return Some(program);
}
}
}
self.cooked
.get(&normalize(path))
.and_then(|readings| readings.last)
}
pub fn forget_cooked(&mut self, path: &Path) {
let path = normalize(path);
self.forget_member_lists(Path::new(&path));
self.forget_guard_answers(Path::new(&path));
if let Ok(mut declared) = self.definition_answers.lock() {
declared.clear();
}
self.forget_the_readings_of(&path);
}
pub fn symbols_matching(&self, query: &str, limit: usize) -> Vec<ProjectSymbol> {
let wanted = query.trim().to_lowercase();
let bare = wanted.trim_start_matches("::");
if bare.is_empty() || limit == 0 {
return Vec::new();
}
let mut hits: Vec<Hit<'_>> = Vec::new();
if !bare.contains("::") {
if let Some(spellings) = self.names.spellings_of(bare) {
self.open_group(spellings, Some(0), bare, limit, &mut hits);
}
if hits.len() < limit {
for (key, spellings) in self.names.lowered_from(bare) {
if !key.starts_with(bare) {
break;
}
if key == bare {
continue;
}
self.open_group(spellings, Some(1), bare, limit, &mut hits);
if hits.len() >= limit {
break;
}
}
}
if hits.len() < limit {
for (key, spellings) in self.names.lowered_from("") {
if key.starts_with(bare) || !key.contains(bare) {
continue;
}
self.open_group(spellings, Some(2), bare, limit, &mut hits);
if hits.len() >= limit {
break;
}
}
}
} else {
let last_asked = bare.rsplit("::").next().unwrap_or_default();
for (key, spellings) in self.names.lowered_from(last_asked) {
if !key.starts_with(last_asked) {
break;
}
self.open_group(spellings, None, bare, limit, &mut hits);
if hits.len() >= limit {
break;
}
}
if !last_asked.is_empty() {
self.open_group(&[Box::from("")], None, bare, limit, &mut hits);
}
}
sort_hits(&mut hits);
hits.into_iter()
.take(limit)
.map(|hit| ProjectSymbol {
file: hit.file.to_path_buf(),
fact: hit.fact.clone(),
})
.collect()
}
fn open_group<'a>(
&'a self,
spellings: &[Box<str>],
rank: Option<usize>,
wanted: &str,
limit: usize,
into: &mut Vec<Hit<'a>>,
) {
let start = into.len();
for spelling in spellings {
let postings = self.names.named(spelling);
let stop_at = match postings.len() > POPULAR_NAME {
true => start + limit,
false => usize::MAX,
};
self.hits_in(postings, rank, wanted, stop_at, into);
}
into[start..].sort_by(hit_order);
}
fn hits_in<'a>(
&'a self,
postings: &[Posting],
rank: Option<usize>,
wanted: &str,
stop_at: usize,
into: &mut Vec<Hit<'a>>,
) {
for posting in postings.iter() {
if into.len() >= stop_at {
break;
}
if posting.reading != self.the_reading_for(posting.file, None) {
continue;
}
let Some((summary, fact)) = self.resolve(*posting) else {
continue;
};
let qualified = fact.qualified_name();
let Some(rank) = rank.or_else(|| rank_of(&qualified, &fact.name, wanted)) else {
continue;
};
let qualified = qualified.to_lowercase();
let name = match fact.name.is_empty() {
false => crate::index::names::lowercase(&fact.name),
true => qualified
.rsplit("::")
.next()
.unwrap_or_default()
.to_string(),
};
into.push(Hit {
rank,
name,
qualified,
file: &summary.path,
posting: *posting,
fact,
});
}
}
fn resolve(&self, posting: Posting) -> Option<(&FileSummary, &DeclFact)> {
let key = self.order.get(&posting.file)?;
let summary = self.summaries.get(key)?;
let fact = match posting.reading {
0 => summary.declarations.get(posting.index())?,
reading => self
.cooked
.get(key)?
.reading(reading)?
.declarations
.get(posting.index())?,
};
Some((summary, fact))
}
pub fn forget_the_name_answers(&self) {
if let Ok(mut answers) = self.definition_answers.lock() {
answers.clear();
}
if let Ok(mut guards) = self.guard_answers.lock() {
guards.clear();
}
}
pub fn files_defining_macro(&self, name: &str) -> Vec<PathBuf> {
self.names
.definers_of(name)
.iter()
.filter_map(|sequence| self.order.get(sequence))
.filter_map(|key| self.summaries.get(key))
.map(|summary| summary.path.clone())
.collect()
}
pub fn files_defining_any_macro<'a>(
&self,
names: impl IntoIterator<Item = &'a str>,
) -> Vec<&FileSummary> {
let mut sequences: BTreeSet<u32> = BTreeSet::new();
for name in names {
sequences.extend(self.names.definers_of(name).iter().copied());
}
sequences
.into_iter()
.filter_map(|sequence| self.order.get(&sequence))
.filter_map(|key| self.summaries.get(key))
.collect()
}
pub fn distinct_names(&self) -> usize {
self.names.distinct_names()
}
pub fn template_parameters_for(
&self,
class: &str,
visible_from: &Path,
arguments: &[String],
) -> Vec<String> {
self.the_template_for(class, visible_from, arguments)
.map(|(parameters, _)| parameters)
.unwrap_or_default()
}
pub fn template_parameter_defaults_for(
&self,
class: &str,
visible_from: &Path,
arguments: &[String],
) -> Vec<String> {
self.the_template_for(class, visible_from, arguments)
.map(|(_, defaults)| defaults)
.unwrap_or_default()
}
fn the_template_for(
&self,
class: &str,
visible_from: &Path,
arguments: &[String],
) -> Option<(Vec<String>, Vec<String>)> {
let bare = class.strip_prefix("::").unwrap_or(class);
let last = bare.rsplit("::").next().unwrap_or(bare);
let mut candidates = self.files_declaring(class, visible_from);
if candidates.is_empty() {
candidates = self.files_declaring(last, visible_from);
}
let of_the_same_arity = |found: &&VisibleDeclaration<'_>| {
let pattern = found.fact.pattern.as_deref().unwrap_or_default();
let slots = arguments_in_a_spelling(pattern).unwrap_or_default();
slots.len() == arguments.len() && lists_usable_parameter_names(&found.fact.parameters)
};
candidates
.iter()
.filter(of_the_same_arity)
.find(|found| {
a_pattern_matches(
found.fact.pattern.as_deref(),
&found.fact.parameters,
Some(arguments),
)
})
.or_else(|| {
candidates
.iter()
.filter(|found| lists_usable_parameter_names(&found.fact.parameters))
.max_by_key(|found| found.fact.parameters.len())
})
.map(|found| {
(
found.fact.parameters.clone(),
found.fact.parameter_defaults.clone(),
)
})
}
pub fn template_parameters_of(&self, class: &str, visible_from: &Path) -> Vec<String> {
let bare = class.strip_prefix("::").unwrap_or(class);
let last = bare.rsplit("::").next().unwrap_or(bare);
let mut candidates = self.files_declaring(class, visible_from);
if candidates.is_empty() {
candidates = self.files_declaring(last, visible_from);
}
candidates
.iter()
.map(|found| &found.fact.parameters)
.find(|parameters| !parameters.is_empty())
.cloned()
.unwrap_or_default()
}
pub fn files_declaring(&self, name: &str, visible_from: &Path) -> Vec<VisibleDeclaration<'_>> {
let bare = name.strip_prefix("::").unwrap_or(name);
let last = bare.rsplit("::").next().unwrap_or(bare);
self.visible_declarations(
visible_from,
|fact| matches(fact, name),
Narrow::Named(&[bare, last]),
)
}
pub fn declarations_in(&self, scope: &str, visible_from: &Path) -> Vec<VisibleDeclaration<'_>> {
self.visible_declarations(
visible_from,
|fact| fact.scope.as_deref() == Some(scope),
Narrow::Scoped(scope),
)
}
pub fn declarations_in_where(
&self,
scope: &str,
visible_from: &Path,
accepts: impl Fn(&DeclFact) -> bool,
) -> Vec<VisibleDeclaration<'_>> {
self.visible_declarations_upto(
visible_from,
&|fact: &DeclFact| fact.scope.as_deref() == Some(scope) && accepts(fact),
MAX_COLLECTED_IN_A_SCOPE,
Narrow::Scoped(scope),
)
}
pub fn visible_declarations_where(
&self,
visible_from: &Path,
accepts: impl Fn(&DeclFact) -> bool,
) -> Vec<VisibleDeclaration<'_>> {
self.visible_declarations_upto(visible_from, &accepts, MAX_COLLECTED_NAMES, Narrow::Nothing)
}
pub fn include_closure(&self, from: &Path) -> std::collections::HashSet<String> {
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut pending: Vec<String> = vec![normalize(from)];
while let Some(path) = pending.pop() {
if !seen.insert(path.clone()) {
continue;
}
let Some(summary) = self.summaries.get(&path) else {
continue;
};
for include in &summary.includes {
if let Some(target) = &include.resolved {
let next = normalize(target);
if !seen.contains(&next) {
pending.push(next);
}
}
}
}
seen
}
pub fn visible_names(&self, from: &Path) -> std::collections::HashSet<String> {
self.visible_declarations_upto(from, &|_| true, usize::MAX, Narrow::Nothing)
.into_iter()
.map(|declaration| declaration.fact.name.to_string())
.collect()
}
pub fn name_postings(&self, name: &str) -> usize {
self.names.named(name).len()
}
pub fn scope_postings(&self, scope: &str) -> usize {
self.names.scoped(scope).len()
}
pub fn all_summaries(&self) -> Vec<(std::path::PathBuf, &FileSummary)> {
self.summaries
.values()
.map(|summary| (summary.path.clone(), summary))
.collect()
}
pub fn summaries_named_like(&self, needle: &str) -> Vec<std::path::PathBuf> {
self.summaries
.values()
.map(|summary| summary.path.clone())
.filter(|path| {
path.to_string_lossy()
.to_ascii_lowercase()
.contains(&needle.to_ascii_lowercase())
})
.collect()
}
pub fn every_fact_named(&self, name: &str) -> Vec<(std::path::PathBuf, &DeclFact)> {
let mut found = Vec::new();
for posting in self.names.named(name) {
let Some(key) = self.order.get(&posting.file) else {
continue;
};
let Some(summary) = self.summaries.get(key) else {
continue;
};
if let Some(fact) = summary.declarations.get(posting.index())
&& fact.name == name
{
found.push((summary.path.clone(), fact));
continue;
}
if let Some((_, fact)) = self.resolve(*posting)
&& fact.name == name
{
found.push((summary.path.clone(), fact));
}
}
found
}
fn visible_declarations<'a>(
&'a self,
visible_from: &Path,
accepts: impl Fn(&DeclFact) -> bool,
narrow: Narrow<'_>,
) -> Vec<VisibleDeclaration<'a>> {
self.visible_declarations_upto(visible_from, &accepts, usize::MAX, narrow)
}
fn visible_declarations_upto<'a>(
&'a self,
visible_from: &Path,
accepts: &impl Fn(&DeclFact) -> bool,
limit: usize,
narrow: Narrow<'_>,
) -> Vec<VisibleDeclaration<'a>> {
let asking = self.the_program_that_read(visible_from);
let walk_started = std::time::Instant::now();
let asks_before = CONDITION_ASKS.load(std::sync::atomic::Ordering::Relaxed);
let nanos_before = CONDITION_NANOS.load(std::sync::atomic::Ordering::Relaxed);
let (walk, walk_files) = self.the_visible_walk(visible_from);
let files = walk_files.as_ref();
let through_an_import = &walk.through_an_import;
if crate::probes::visibility() {
eprintln!(
"[visibility] {} file(s) after the order step, from {}",
files.len(),
visible_from.display()
);
}
if crate::probes::timing() && walk_started.elapsed().as_micros() >= 500 {
let asks = CONDITION_ASKS.load(std::sync::atomic::Ordering::Relaxed) - asks_before;
let nanos = CONDITION_NANOS.load(std::sync::atomic::Ordering::Relaxed) - nanos_before;
eprintln!(
"[visibility] {:>5.1} ms, {} file(s), from {} — {asks} condition(s)/{} ms",
walk_started.elapsed().as_secs_f64() * 1000.0,
files.len(),
visible_from
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| visible_from.display().to_string()),
nanos / 1_000_000,
);
}
let mut found = Vec::new();
let postings: Option<std::borrow::Cow<'_, [Posting]>> = match narrow {
Narrow::Nothing => None,
Narrow::Scoped(scope) => Some(std::borrow::Cow::Borrowed(self.names.scoped(scope))),
Narrow::Named(names) => {
let mut keys: Vec<&str> = names.to_vec();
keys.dedup();
match keys.as_slice() {
[one] => Some(std::borrow::Cow::Borrowed(self.names.named(one))),
_ => {
let mut merged: Vec<Posting> = keys
.iter()
.flat_map(|key| self.names.named(key).iter().copied())
.collect();
merged.sort_unstable();
merged.dedup();
Some(std::borrow::Cow::Owned(merged))
}
}
}
};
if std::env::var("CPPLS_TRACE_NAMES").is_ok()
&& let Narrow::Named(names) = narrow
&& names.iter().any(|name| *name == "cout" || *name == "map")
{
let postings = match &postings {
Some(postings) => postings
.iter()
.map(|posting| {
format!(
"file {} id {} index {}",
posting.file,
posting.reading,
posting.index()
)
})
.collect::<Vec<_>>(),
None => vec!["no narrow".to_string()],
};
eprintln!(
"[names] visible_declarations {:?}: {} posting(s) — {postings:?}",
names,
postings.len()
);
}
let mut next = 0;
let mut visible = files.iter();
loop {
if found.len() >= limit {
break;
}
let (file, visibility, group): (u32, IncludeVisibility, Option<&[Posting]>) =
match &postings {
None => {
let Some(&(file, visibility)) = visible.next() else {
break;
};
(file, visibility, None)
}
Some(postings) => {
let Some(first) = postings.get(next) else {
break;
};
let file = first.file;
let end = next + postings[next..].partition_point(|held| held.file == file);
let group = &postings[next..end];
next = end;
let Ok(at) = files.binary_search_by_key(&file, |visible| visible.0) else {
continue;
};
(file, files[at].1, Some(group))
}
};
let Some(key) = self.order.get(&file) else {
continue;
};
let Some(summary) = self.summaries.get(key) else {
continue;
};
let only_what_is_exported = through_an_import.contains(key);
let contributes =
|fact: &DeclFact| accepts(fact) && (!only_what_is_exported || fact.exported);
let reading = self.the_reading_for(file, asking);
let cooked = self
.cooked
.get(key)
.and_then(|readings| readings.reading(reading));
let the_askers_own = asking.is_some_and(|program| {
self.order
.get(&file)
.and_then(|key| self.cooked.get(key))
.and_then(|readings| readings.id_for(program))
.is_some()
});
let (facts, reading): (&[DeclFact], u32) = match cooked {
Some(cooked) if cooked.declarations.iter().any(&accepts) => {
(cooked.declarations.as_slice(), reading)
}
Some(_) if !the_askers_own && summary.declarations.iter().any(&accepts) => {
(summary.declarations.as_slice(), 0)
}
Some(cooked) => (cooked.declarations.as_slice(), reading),
None => (summary.declarations.as_slice(), 0),
};
let candidates: Box<dyn Iterator<Item = &DeclFact> + '_> = match group {
None => Box::new(facts.iter()),
Some(group) => Box::new(
group
.iter()
.filter(|posting| posting.reading == reading)
.filter_map(|posting| facts.get(posting.index())),
),
};
for fact in candidates.filter(|fact| contributes(fact)) {
found.push(VisibleDeclaration {
file: summary.path.clone(),
fact,
visibility,
});
}
}
found
}
fn visible_in_order_of(
&self,
visible: Vec<(String, IncludeVisibility)>,
) -> Vec<(u32, IncludeVisibility)> {
let mut files: Vec<(u32, IncludeVisibility)> = visible
.into_iter()
.filter_map(|(key, visibility)| Some((*self.sequence.get(&key)?, visibility)))
.collect();
files.sort_unstable_by_key(|(sequence, _)| *sequence);
files.dedup_by_key(|(sequence, _)| *sequence);
files
}
fn the_walks_fingerprint(&self, contributors: &[String]) -> u64 {
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
const NOT_IN_THE_INDEX: u64 = 0x1d57_9b40_c3e8_2a6f;
let mut fingerprint = FNV_OFFSET;
let mut eat = |value: u64| {
for byte in value.to_le_bytes() {
fingerprint ^= u64::from(byte);
fingerprint = fingerprint.wrapping_mul(FNV_PRIME);
}
};
for path in contributors {
eat(crate::cache::fnv1a64(path.as_bytes()));
eat(self
.walk_inputs
.get(path)
.copied()
.unwrap_or(NOT_IN_THE_INDEX));
}
fingerprint
}
pub fn dependents_of(&self, path: &Path) -> Vec<PathBuf> {
let start = normalize(path);
let mut seen: HashSet<String> = HashSet::from([start.clone()]);
let mut pending: VecDeque<(String, usize)> = VecDeque::from([(start, 0)]);
let mut dependents = Vec::new();
while let Some((current, depth)) = pending.pop_front() {
if depth >= MAX_VISIBILITY_DEPTH {
continue;
}
let Some(includers) = self.included_by.get(¤t) else {
continue;
};
for includer in includers {
if !seen.insert(includer.clone()) {
continue;
}
dependents.push(PathBuf::from(includer));
pending.push_back((includer.clone(), depth + 1));
}
}
dependents
}
pub fn visible_files(&self, from: &Path) -> Vec<(String, IncludeVisibility)> {
self.visible_files_with_modules(from).0
}
fn the_remembered_walk(
&self,
from: &str,
) -> Option<(Vec<(String, IncludeVisibility)>, HashSet<String>)> {
let remembered = self
.visibility
.lock()
.ok()
.and_then(|walks| walks.get(from).cloned())?;
let now = self.the_walks_fingerprint(&remembered.contributors);
if crate::probes::visibility() {
eprintln!(
"[visibility] remembered walk from {from}: {} ({} contributor(s))",
if now == remembered.fingerprint {
"hit"
} else {
"MISS — an input it was made of changed"
},
remembered.contributors.len()
);
}
if now != remembered.fingerprint {
return None;
}
let seen = &remembered.seen;
let mut order: Vec<(String, IncludeVisibility)> = Vec::with_capacity(seen.visibility.len());
order.push((from.to_string(), IncludeVisibility::Unconditional));
order.extend(
seen.visibility
.iter()
.filter(|(path, _)| path.as_str() != from)
.map(|(path, visibility)| (path.clone(), *visibility)),
);
Some((order, seen.through_an_import.clone()))
}
pub fn visible_files_with_modules(
&self,
from: &Path,
) -> (Vec<(String, IncludeVisibility)>, HashSet<String>) {
let from = normalize(from);
let waiting_since = std::time::Instant::now();
let mut met = false;
loop {
if let Some(answer) = self.the_remembered_walk(&from) {
self.walks_hit
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
return answer;
}
if self.claim_a_walk(&from) {
break;
}
if !met {
met = true;
self.walks_met
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
if waiting_since.elapsed() > std::time::Duration::from_secs(30) {
break;
}
self.wait_for_the_walk(&from);
}
self.walks_built
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let _claim = WalkClaim {
index: self,
root: from.clone(),
};
let mut seen = Seen::new(&from);
let macros_started = std::time::Instant::now();
let mut state = self.macros.clone();
let macros_cloned = macros_started.elapsed();
let certain = self.certainly_in_the_translation_unit(Path::new(&from));
if crate::probes::timing() && macros_started.elapsed().as_micros() >= 300 {
eprintln!(
"[visibility] the state: macro table cloned in {macros_cloned:?} ({} entry(ies)), \
the translation unit's certain set in {:?}",
self.macros.len(),
macros_started.elapsed() - macros_cloned
);
}
self.macro_candidates(
Path::new(&from),
&mut Vec::new(),
false,
&mut HashSet::new(),
&certain,
&mut Collecting::Visibility(&mut seen),
&mut state,
None,
);
let mut module_seen: HashSet<String> = HashSet::new();
self.add_the_closures_behind_the_imports(Path::new(&from), &mut seen);
while let Some(reached) = seen.module_work.pop() {
if !module_seen.insert(reached.clone()) {
continue;
}
self.add_the_closures_behind_the_imports(Path::new(&reached), &mut seen);
let mut state = self.macros.clone();
self.walk_the_module_edges(
Path::new(&reached),
&mut seen,
&mut state,
&mut module_seen,
);
}
let mut order: Vec<(String, IncludeVisibility)> = Vec::with_capacity(seen.visibility.len());
order.push((from.clone(), IncludeVisibility::Unconditional));
order.extend(
seen.visibility
.iter()
.filter(|(path, _)| **path != from)
.map(|(path, visibility)| (path.clone(), *visibility)),
);
let through_an_import = seen.through_an_import.clone();
let mut contributors: Vec<String> = Vec::with_capacity(seen.visibility.len() + 1);
contributors.push(from.clone());
contributors.extend(
seen.visibility
.keys()
.filter(|path| **path != from)
.map(|path| normalize(Path::new(path))),
);
contributors.sort_unstable();
contributors.dedup();
let fingerprint = self.the_walks_fingerprint(&contributors);
let files = self.visible_in_order_of(
seen.visibility
.iter()
.map(|(path, visibility)| (path.clone(), *visibility))
.collect(),
);
if let Ok(mut walks) = self.visibility.lock() {
walks.insert(
from,
std::sync::Arc::new(CachedWalk {
seen: std::sync::Arc::new(seen),
contributors: std::sync::Arc::new(contributors),
fingerprint,
files: std::sync::Arc::new(files),
stamp: self.changed,
}),
);
}
(order, through_an_import)
}
fn the_visible_walk(
&self,
from: &Path,
) -> (
std::sync::Arc<Seen>,
std::sync::Arc<Vec<(u32, IncludeVisibility)>>,
) {
let from = normalize(from);
let remembered = self
.visibility
.lock()
.ok()
.and_then(|walks| walks.get(&from).cloned());
if let Some(known) = remembered {
if known.stamp == self.changed {
return (
std::sync::Arc::clone(&known.seen),
std::sync::Arc::clone(&known.files),
);
}
if self.the_walks_fingerprint(&known.contributors) == known.fingerprint {
let files = if known.files.len() == known.seen.visibility.len() {
std::sync::Arc::clone(&known.files)
} else {
std::sync::Arc::new(
self.visible_in_order_of(
known
.seen
.visibility
.iter()
.map(|(path, visibility)| (path.clone(), *visibility))
.collect(),
),
)
};
if let Ok(mut walks) = self.visibility.lock() {
walks.insert(
from.clone(),
std::sync::Arc::new(CachedWalk {
seen: std::sync::Arc::clone(&known.seen),
contributors: std::sync::Arc::clone(&known.contributors),
fingerprint: known.fingerprint,
files: std::sync::Arc::clone(&files),
stamp: self.changed,
}),
);
}
return (std::sync::Arc::clone(&known.seen), files);
}
}
let _ = self.visible_files_with_modules(Path::new(&from));
if let Some(known) = self
.visibility
.lock()
.ok()
.and_then(|walks| walks.get(&from).cloned())
{
return (
std::sync::Arc::clone(&known.seen),
std::sync::Arc::clone(&known.files),
);
}
(
std::sync::Arc::new(Seen::default()),
std::sync::Arc::new(Vec::new()),
)
}
fn walk_the_module_edges(
&self,
path: &Path,
seen: &mut Seen,
state: &mut Marked,
module_seen: &mut HashSet<String>,
) {
let path = normalize(path);
let Some(summary) = self.summaries.get(&path) else {
return;
};
for fact in &summary.macros {
if fact.guard == FactGuard::Unconditional {
apply_fact(state, fact, false, FactReach::Active);
}
}
let mut verdicts: HashMap<(u32, usize), Option<bool>> = HashMap::new();
for unit in &summary.modules.header_units {
let next = normalize(unit);
seen.visibility
.entry(next.clone())
.or_insert(IncludeVisibility::Unconditional);
if module_seen.insert(next.clone()) {
seen.module_work.push(next);
}
}
for unit in &summary.modules.partitions {
let next = normalize(unit);
seen.visibility
.entry(next.clone())
.or_insert(IncludeVisibility::Unconditional);
if module_seen.insert(next.clone()) {
self.walk_the_module_edges(Path::new(&next), seen, state, module_seen);
}
}
for imported in &summary.modules.imports {
let Some(interface) = self.module_interfaces.get(imported.as_ref()) else {
continue;
};
seen.visibility
.entry(interface.clone())
.or_insert(IncludeVisibility::Unconditional);
seen.through_an_import.insert(interface.clone());
if module_seen.insert(interface.clone()) {
self.walk_the_module_edges(Path::new(interface), seen, state, module_seen);
}
}
for include in &summary.includes {
let visibility = self.include_visibility(
summary,
&mut verdicts,
state,
&mut Collecting::Visibility(&mut *seen),
include.guard,
include.range.start_offset,
);
if visibility == Visibility::Inactive {
continue;
}
let Some(target) = &include.resolved else {
continue;
};
let next = normalize(target);
let step = match visibility {
Visibility::Active => IncludeVisibility::Unconditional,
Visibility::Unknown => IncludeVisibility::Conditional,
Visibility::Inactive => continue,
};
match seen.visibility.get(&next) {
Some(known) if *known <= step => {}
_ => {
seen.visibility.insert(next.clone(), step);
}
}
seen.through_an_import.remove(&next);
if module_seen.insert(next.clone()) {
self.walk_the_module_edges(Path::new(&next), seen, state, module_seen);
}
}
}
fn add_the_closures_behind_the_imports(&self, of: &Path, seen: &mut Seen) {
let Some(summary) = self.summaries.get(&normalize(of)) else {
return;
};
if summary.modules.imports.is_empty() {
return;
}
let Ok(closures) = self.unit_closures.lock() else {
return;
};
for imported in &summary.modules.imports {
let Some(files) = closures.get(imported.as_ref()) else {
continue;
};
for file in files {
seen.visibility
.entry(file.clone())
.or_insert(IncludeVisibility::Unconditional);
seen.through_an_import.remove(file);
}
}
}
pub fn visible_files_by_asking_each_condition(
&self,
from: &Path,
) -> Vec<(String, IncludeVisibility)> {
let from = normalize(from);
let mut best: HashMap<String, IncludeVisibility> =
HashMap::from([(from.clone(), IncludeVisibility::Unconditional)]);
let mut order: Vec<String> = vec![from.clone()];
let mut pending: Vec<(String, IncludeVisibility, usize)> =
vec![(from, IncludeVisibility::Unconditional, 0)];
let mut through_an_import: HashSet<String> = HashSet::new();
while let Some((current, so_far, depth)) = pending.pop() {
if depth > MAX_VISIBILITY_DEPTH {
continue;
}
let Some(summary) = self.summaries.get(¤t) else {
continue;
};
for unit in &summary.modules.header_units {
let next = normalize(unit);
if let std::collections::hash_map::Entry::Vacant(slot) = best.entry(next.clone()) {
slot.insert(IncludeVisibility::Unconditional);
order.push(next.clone());
pending.push((next, IncludeVisibility::Unconditional, depth + 1));
}
}
for unit in &summary.modules.partitions {
let next = normalize(unit);
if let std::collections::hash_map::Entry::Vacant(slot) = best.entry(next.clone()) {
slot.insert(IncludeVisibility::Unconditional);
order.push(next.clone());
pending.push((next, IncludeVisibility::Unconditional, depth + 1));
}
}
for imported in &summary.modules.imports {
let Some(interface) = self.module_interfaces.get(imported.as_ref()) else {
continue;
};
if best.contains_key(interface) {
continue;
}
best.insert(interface.clone(), IncludeVisibility::Unconditional);
order.push(interface.clone());
through_an_import.insert(interface.clone());
pending.push((
interface.clone(),
IncludeVisibility::Unconditional,
depth + 1,
));
}
for include in &summary.includes {
let Some(resolved) = &include.resolved else {
continue;
};
let next = normalize(resolved);
let step = match include.guard {
FactGuard::Unconditional => so_far,
FactGuard::Region(region) => {
let key = (current.clone(), region);
let answer = match self
.visibility_answers
.lock()
.ok()
.and_then(|answers| answers.get(&key).copied())
{
Some(answer) => answer,
None => {
let started = std::time::Instant::now();
let answer = crate::index::environment::visibility_at(
self,
Path::new(¤t),
include.guard,
include.range.start_offset,
);
if crate::probes::timing() {
CONDITION_NANOS.fetch_add(
started.elapsed().as_nanos() as u64,
std::sync::atomic::Ordering::Relaxed,
);
CONDITION_ASKS
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
if let Ok(mut answers) = self.visibility_answers.lock() {
answers.insert(key, answer);
}
answer
}
};
match answer {
crate::Visibility::Active => so_far,
crate::Visibility::Inactive => continue,
crate::Visibility::Unknown => IncludeVisibility::Conditional,
}
}
};
match best.get(&next) {
Some(known) if *known <= step => continue,
Some(_) => {}
None => order.push(next.clone()),
}
through_an_import.remove(&next);
best.insert(next.clone(), step);
pending.push((next, step, depth + 1));
}
}
order
.into_iter()
.filter_map(|path| {
best.get(&path)
.map(|visibility| (path.clone(), *visibility))
})
.collect()
}
pub fn definition(&self, name: &str, visible_from: &Path) -> Known<ProjectDefinition> {
match self.definitions(name, visible_from) {
Known::Yes(mut found) if found.found.len() == 1 => Known::Yes(found.found.remove(0)),
Known::Yes(mut found) => {
found
.found
.retain(|declaration| declaration.fact.kind != DeclKind::Other);
let group: Vec<usize> = if !name.contains('<') {
let plain: Vec<usize> = found
.found
.iter()
.enumerate()
.filter(|(_, declaration)| declaration.fact.pattern.is_none())
.map(|(at, _)| at)
.collect();
if plain.is_empty() {
(0..found.found.len()).collect()
} else {
plain
}
} else {
(0..found.found.len()).collect()
};
let definitions: Vec<usize> = group
.iter()
.copied()
.filter(|at| found.found[*at].fact.definition)
.collect();
if definitions.len() == 1 {
return Known::Yes(found.found.remove(definitions[0]));
}
if group.len() == 1 {
return Known::Yes(found.found.remove(group[0]));
}
match found.found.len() {
1 => Known::Yes(found.found.remove(0)),
_ => Known::Unknown(UnknownReason::Ambiguous(Box::from(name))),
}
}
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::No,
}
}
pub fn definition_where_written(
&self,
written: &str,
in_scope: Option<&str>,
visible_from: &Path,
) -> Known<ProjectDefinition> {
let direct = self.definition(written, visible_from);
if !matches!(direct, Known::Unknown(UnknownReason::NotDeclaredHere(_))) {
return direct;
}
let Some(scope) = in_scope.filter(|_| !written.starts_with("::")) else {
return direct;
};
let segments: Vec<&str> = scope.split("::").collect();
for take in (1..=segments.len()).rev() {
let enclosing = segments[..take].join("::");
if enclosing.is_empty() {
continue;
}
let through_the_scope =
self.definition(&format!("{enclosing}::{written}"), visible_from);
if !matches!(
through_the_scope,
Known::Unknown(UnknownReason::NotDeclaredHere(_))
) {
return through_the_scope;
}
}
direct
}
pub fn definitions(&self, name: &str, visible_from: &Path) -> Known<ProjectDefinitions> {
if crate::probes::no_index_lookup() {
return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(name)));
}
let key = (name.to_string(), normalize(visible_from));
if let Some(known) = self
.definition_answers
.lock()
.ok()
.and_then(|memo| memo.get(&key).cloned())
{
return known;
}
let started = std::time::Instant::now();
let answer = self.definitions_inner(name, visible_from);
if crate::probes::timing() && started.elapsed().as_micros() >= 200 {
eprintln!(
"[lookup] {:>5.1} ms {name} ({} answer(s))",
started.elapsed().as_secs_f64() * 1000.0,
match &answer {
Known::Yes(found) => found.found.len(),
_ => 0,
}
);
}
if let Ok(mut memo) = self.definition_answers.lock() {
if memo.len() >= MAX_DEFINITION_ANSWERS {
memo.clear();
}
memo.insert(key, answer.clone());
}
answer
}
fn definitions_inner(&self, name: &str, visible_from: &Path) -> Known<ProjectDefinitions> {
let (mut certain, conditional) = match self.certain_declarations(name, visible_from) {
Ok(candidates) => candidates,
Err(reason) => return Known::Unknown(reason),
};
let all_namespaces = certain
.iter()
.all(|found| found.fact.kind == DeclKind::Namespace);
if all_namespaces {
certain.truncate(1);
}
let mut distinct: Vec<ProjectDeclaration> = Vec::new();
for found in certain {
if let Some(at) = distinct
.iter()
.position(|kept| the_same_declaration_in_one_file(kept, &found))
{
if found.fact.definition && !distinct[at].fact.definition {
distinct[at] = found;
}
continue;
}
distinct.push(found);
}
let mut certain = distinct;
if certain
.iter()
.any(|found| found.fact.kind != DeclKind::Other)
{
certain.retain(|found| found.fact.kind != DeclKind::Other);
}
Known::Yes(ProjectDefinitions {
found: certain
.into_iter()
.map(|found| ProjectDefinition {
file: found.file,
fact: found.fact,
})
.collect(),
conditional,
})
}
pub fn definitions_in_scope(
&self,
name: &str,
visible_from: &Path,
) -> Known<ProjectDefinitions> {
let mut found = match self.definitions(name, visible_from) {
Known::Yes(found) => found,
other => return other,
};
if name.contains("::") {
return Known::Yes(found);
}
let mut decided: Vec<(String, bool)> = Vec::new();
let mut kept = Vec::with_capacity(found.found.len());
for declaration in found.found {
let Some(scope) = declaration.fact.scope.clone() else {
kept.push(declaration);
continue;
};
let a_class = match decided.iter().find(|(known, _)| *known == scope) {
Some((_, answer)) => *answer,
None => {
let answer = self.scope_names_a_class(&scope, visible_from);
decided.push((scope.clone(), answer));
answer
}
};
if !a_class {
kept.push(declaration);
}
}
if kept.is_empty() {
return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(name)));
}
found.found = kept;
Known::Yes(found)
}
fn scope_names_a_class(&self, scope: &str, visible_from: &Path) -> bool {
self.files_declaring(scope, visible_from)
.iter()
.any(|declaration| {
declaration.fact.kind == DeclKind::Type
&& declaration.fact.qualified_name() == scope
})
}
pub fn kind_of(&self, name: &str, visible_from: &Path) -> Known<IndexedKind> {
let (certain, _) = match self.certain_declarations(name, visible_from) {
Ok(candidates) => candidates,
Err(reason) => return Known::Unknown(reason),
};
let certain: Vec<_> = certain
.into_iter()
.filter(|found| found.fact.scope.is_none() || found.fact.qualified_name() == name)
.collect();
let mut kinds: Vec<IndexedKind> = certain
.into_iter()
.map(|found| IndexedKind::of(&found.fact))
.collect();
kinds.sort_unstable();
kinds.dedup();
match kinds.as_slice() {
[only] => Known::Yes(only.clone()),
[] => Known::Unknown(UnknownReason::ConditionalCompilation),
_ => Known::Unknown(UnknownReason::Ambiguous(Box::from(name))),
}
}
fn one_entity_declared_twice(
left: &VisibleDeclaration<'_>,
right: &VisibleDeclaration<'_>,
) -> bool {
left.fact.kind == DeclKind::Function
&& right.fact.kind == DeclKind::Function
&& left.fact.name == right.fact.name
&& left.fact.scope == right.fact.scope
&& left.fact.parameter_list == right.fact.parameter_list
&& left.file != right.file
}
fn certain_declarations(
&self,
name: &str,
visible_from: &Path,
) -> Result<(Vec<ProjectDeclaration>, usize), UnknownReason> {
let mut candidates = self.files_declaring(name, visible_from);
if candidates.is_empty()
&& let Some(rewritten) = self.through_an_alias(name, visible_from)
{
candidates = self.files_declaring(&rewritten, visible_from);
}
if candidates.is_empty() {
return Err(UnknownReason::NotDeclaredHere(Box::from(name)));
}
let own = normalize(visible_from);
if candidates.iter().any(|found| normalize(&found.file) == own) {
let local: Vec<VisibleDeclaration<'_>> = candidates
.iter()
.filter(|found| normalize(&found.file) == own)
.cloned()
.collect();
candidates.retain(|found| {
normalize(&found.file) == own
|| local
.iter()
.any(|kept| Self::one_entity_declared_twice(kept, found))
|| !local
.iter()
.any(|kept| kept.fact.scope == found.fact.scope)
});
}
if !crate::probes::no_guard_filter() {
candidates.retain(|found| {
self.a_guard_is_taken(&found.file, found.fact.guard, found.fact.range.start_offset)
});
}
let conditional = candidates
.iter()
.filter(|found| found.visibility == IncludeVisibility::Conditional)
.count();
let mut certain: Vec<ProjectDeclaration> = candidates
.into_iter()
.filter(|found| found.visibility == IncludeVisibility::Unconditional)
.map(|found| ProjectDeclaration::of(&found))
.collect();
if certain.is_empty() {
return Err(UnknownReason::ConditionalCompilation);
}
certain.sort_by(|one, other| {
one.file
.cmp(&other.file)
.then_with(|| one.start_offset.cmp(&other.start_offset))
});
Ok((certain, conditional))
}
fn through_an_alias(&self, name: &str, visible_from: &Path) -> Option<String> {
const ALIAS_DEPTH: usize = 4;
let mut rewritten = name.to_string();
let tracing = std::env::var("CPPLS_TRACE_ALIAS").is_ok();
for _ in 0..ALIAS_DEPTH {
let segments: Vec<&str> = rewritten.split("::").collect();
if tracing {
eprintln!("[alias] trying {rewritten}");
}
let substituted = (1..segments.len()).rev().find_map(|take| {
let prefix = segments[..take].join("::");
let mut candidates = self.files_declaring(&prefix, visible_from);
candidates.sort_by_key(|found| found.fact.kind == DeclKind::Other);
if tracing {
eprintln!(
"[alias] prefix {prefix}: {:?}",
candidates
.iter()
.map(|found| format!(
"{} {:?} scope {:?} type {:?}",
found.fact.name,
found.fact.kind,
found.fact.scope,
found.fact.type_of
))
.collect::<Vec<_>>()
);
}
let alias = candidates.into_iter().next()?;
if let Some(qualified) = self.qualified_name_of_the_entity(alias.fact, &prefix)
&& qualified != prefix
{
return Some(format!("{qualified}::{}", segments[take..].join("::")));
}
if alias.fact.kind == DeclKind::Namespace
&& let Some(written_target) = alias.fact.type_of.as_deref()
{
let qualified = if written_target.contains("::") {
written_target.to_string()
} else {
match &alias.fact.scope {
Some(scope) => format!("{scope}::{written_target}"),
None => written_target.to_string(),
}
};
if qualified != prefix {
return Some(format!("{qualified}::{}", segments[take..].join("::")));
}
}
if alias.fact.kind != DeclKind::Type {
return None;
}
let target =
crate::sema::types::parse_type_spelling(alias.fact.type_of.as_deref()?);
let class = target.class_name()?;
let qualified = if class.contains("::") {
class.to_string()
} else {
match &alias.fact.scope {
Some(scope) => format!("{scope}::{class}"),
None => class.to_string(),
}
};
Some(format!("{qualified}::{}", segments[take..].join("::")))
});
let next = substituted?;
if next == rewritten {
return None;
}
rewritten = next;
if !self.files_declaring(&rewritten, visible_from).is_empty() {
return Some(rewritten);
}
}
None
}
fn qualified_name_of_the_entity(&self, fact: &DeclFact, prefix: &str) -> Option<String> {
if !matches!(fact.kind, DeclKind::Type | DeclKind::Namespace) {
return None;
}
let qualified = fact.qualified_name();
if qualified == prefix || qualified.is_empty() {
return None;
}
let tail = qualified.rsplit("::").next().unwrap_or_default();
let written = prefix.rsplit("::").next().unwrap_or_default();
(tail == written).then_some(qualified)
}
pub fn macro_definition(
&self,
name: &str,
visible_from: &Path,
offset: usize,
) -> Known<ProjectMacro> {
match self.macro_environment(name, visible_from).at(offset) {
Known::Yes(found) => Known::Yes(ProjectMacro {
file: found.file.clone(),
fact: found.fact.clone(),
}),
Known::Unknown(reason) => Known::Unknown(reason),
Known::No => Known::No,
}
}
pub fn macro_environment(&self, name: &str, visible_from: &Path) -> MacroEnvironment {
if self.names.definers_of(name).is_empty() && !self.macros.names_the_compilation(name) {
return MacroEnvironment {
name: name.to_string(),
candidates: Vec::new(),
};
}
let key = (normalize(visible_from), name.to_string());
if let Ok(memo) = self.macro_environments.lock()
&& let Some(cached) = memo.get(&key)
{
return cached.environment.clone();
}
let mut candidates = Vec::new();
let certain = self.certainly_in_the_translation_unit(visible_from);
let mut visited = HashSet::new();
self.macro_candidates(
visible_from,
&mut Vec::new(),
false,
&mut visited,
&certain,
&mut Collecting::Name(name, &mut candidates),
&mut self.macros.clone(),
None,
);
let environment = MacroEnvironment {
name: name.to_string(),
candidates,
};
let mut contributors: Vec<String> = visited.into_iter().collect();
contributors.sort();
if let Ok(mut memo) = self.macro_environments.lock() {
if memo.len() >= MAX_CACHED_MACRO_WALKS {
memo.clear();
}
memo.insert(
key,
CachedMacroWalk {
contributors,
environment: environment.clone(),
},
);
}
environment
}
pub fn macro_names_in_force(&self, visible_from: &Path) -> HashSet<String> {
let key = normalize(visible_from);
if let Ok(memo) = self.macro_names.lock()
&& let Some(cached) = memo.get(&key)
{
return cached.names.clone();
}
let mut names = HashSet::new();
let certain = self.certainly_in_the_translation_unit(visible_from);
let mut visited = HashSet::new();
self.macro_candidates(
visible_from,
&mut Vec::new(),
false,
&mut visited,
&certain,
&mut Collecting::Names(&mut names),
&mut self.macros.clone(),
None,
);
let mut contributors: Vec<String> = visited.into_iter().collect();
contributors.sort();
if let Ok(mut memo) = self.macro_names.lock() {
if memo.len() >= MAX_CACHED_MACRO_WALKS {
memo.clear();
}
memo.insert(
key,
CachedMacroNames {
contributors,
names: names.clone(),
},
);
}
names
}
pub fn macros_at(&self, path: &Path, offset: usize) -> Marked {
let mut state = self.macros.clone();
let certain = self.certainly_in_the_translation_unit(path);
self.macro_candidates(
path,
&mut Vec::new(),
false,
&mut HashSet::new(),
&certain,
&mut Collecting::Nothing,
&mut state,
Some(offset),
);
state
}
fn certainly_in_the_translation_unit(&self, from: &Path) -> HashSet<String> {
let from = normalize(from);
let mut certain = HashSet::from([from.clone()]);
let mut pending = vec![from];
while let Some(current) = pending.pop() {
let Some(summary) = self.summaries.get(¤t) else {
continue;
};
for include in &summary.includes {
if include.guard != FactGuard::Unconditional {
continue;
}
let Some(resolved) = &include.resolved else {
continue;
};
let next = normalize(resolved);
if certain.insert(next.clone()) {
pending.push(next);
}
}
}
certain
}
#[allow(clippy::too_many_arguments)]
fn macro_candidates(
&self,
path: &Path,
chain: &mut Vec<usize>,
path_conditional: bool,
visited: &mut HashSet<String>,
certain: &HashSet<String>,
collecting: &mut Collecting<'_>,
state: &mut Marked,
upto: Option<usize>,
) {
let path = normalize(path);
if !visited.insert(path.clone()) {
return;
}
let path_conditional = path_conditional && !certain.contains(&path);
let Some(summary) = self.summaries.get(&path) else {
state.mark_incomplete();
return;
};
for unit in &summary.modules.header_units {
collecting.crossed_a_module(&normalize(unit));
}
for unit in &summary.modules.partitions {
collecting.crossed_a_module(&normalize(unit));
}
for imported in &summary.modules.imports {
let Some(interface) = self.module_interfaces.get(imported.as_ref()) else {
continue;
};
collecting.crossed(interface, IncludeVisibility::Unconditional, true);
collecting.crossed_a_module(&normalize(Path::new(interface)));
}
if !summary.modules.is_interface
&& summary.modules.partition.is_none()
&& let Some(module) = &summary.modules.module
&& let Some(interface) = self.module_interfaces.get(module.as_ref())
{
collecting.crossed(interface, IncludeVisibility::Unconditional, true);
collecting.crossed_a_module(&normalize(Path::new(interface)));
}
let mut verdicts: HashMap<(u32, usize), Option<bool>> = HashMap::new();
let mut facts = summary.macros.iter().peekable();
let mut includes = summary.includes.iter().peekable();
loop {
let next_fact = facts.peek().map(|fact| fact.range.start_offset);
let next_include = includes.peek().map(|include| include.range.start_offset);
let (at, take_fact) = match (next_fact, next_include) {
(Some(fact), Some(include)) => (fact.min(include), fact <= include),
(Some(fact), None) => (fact, true),
(None, Some(include)) => (include, false),
(None, None) => break,
};
if upto.is_some_and(|upto| at >= upto) {
break;
}
if take_fact {
let fact = facts.next().expect("peeked");
let reach = self.fact_reach(
summary,
&mut verdicts,
state,
&mut *collecting,
fact.guard,
at,
);
if reach == FactReach::Inactive {
continue;
}
collecting.fact(summary, chain, fact, path_conditional, reach);
apply_fact(state, fact, path_conditional, reach);
continue;
}
let include = includes.next().expect("peeked");
let visibility = self.include_visibility(
summary,
&mut verdicts,
state,
&mut *collecting,
include.guard,
at,
);
if visibility == Visibility::Inactive {
continue;
}
let Some(target) = &include.resolved else {
state.mark_incomplete();
continue;
};
let step = match visibility {
Visibility::Active => IncludeVisibility::Unconditional,
Visibility::Unknown => IncludeVisibility::Conditional,
Visibility::Inactive => continue,
};
collecting.crossed(&normalize_path(target, cfg!(windows)), step, false);
collecting.reached_by_include(&normalize_path(target, cfg!(windows)));
chain.push(include.range.start_offset);
self.macro_candidates(
target,
chain,
path_conditional || visibility == Visibility::Unknown,
visited,
certain,
&mut collecting.reborrow(),
state,
None,
);
chain.pop();
}
}
fn fact_reach(
&self,
summary: &FileSummary,
verdicts: &mut HashMap<(u32, usize), Option<bool>>,
state: &Marked,
collecting: &mut Collecting<'_>,
guard: FactGuard,
offset: usize,
) -> FactReach {
match self.include_visibility(summary, verdicts, state, &mut *collecting, guard, offset) {
Visibility::Active => FactReach::Active,
Visibility::Inactive => FactReach::Inactive,
Visibility::Unknown => FactReach::Unknown,
}
}
fn include_visibility(
&self,
summary: &FileSummary,
verdicts: &mut HashMap<(u32, usize), Option<bool>>,
state: &Marked,
collecting: &mut Collecting<'_>,
guard: FactGuard,
offset: usize,
) -> Visibility {
let FactGuard::Region(region) = guard else {
return Visibility::Active;
};
if summary.guards.own_guard == Some(region) {
return Visibility::Active;
}
let mut unknown = false;
for at in summary.guards.conditions_of(region) {
let Some(branch) = summary
.guards
.region_at(at.region, offset)
.map(|region| region.active_branch)
else {
unknown = true;
continue;
};
let holds = match verdicts.get(&(at.region, branch)) {
Some(recorded) => *recorded,
None => {
let decided = match collecting.decided_at(
summary,
state,
at.region,
at.condition_at,
offset,
) {
Some(verdict) => verdict,
None => summary
.guards
.region_at(at.region, offset)
.and_then(|region| {
region.visibility(
&crate::index::environment::MacrosHere::from_walk(
state,
at.condition_at,
),
)
}),
};
verdicts.insert((at.region, branch), decided);
decided
}
};
match holds {
Some(true) => {}
Some(false) => {
return Visibility::Inactive;
}
None => unknown = true,
}
}
if unknown {
Visibility::Unknown
} else {
Visibility::Active
}
}
}
enum Collecting<'a> {
Name(&'a str, &'a mut Vec<MacroCandidate>),
Names(&'a mut HashSet<String>),
Visibility(&'a mut Seen),
Nothing,
}
#[derive(Debug, Clone)]
struct CachedWalk {
seen: std::sync::Arc<Seen>,
contributors: std::sync::Arc<Vec<String>>,
fingerprint: u64,
files: std::sync::Arc<Vec<(u32, IncludeVisibility)>>,
stamp: u64,
}
struct WalkClaim<'a> {
index: &'a ProjectIndex,
root: String,
}
impl Drop for WalkClaim<'_> {
fn drop(&mut self) {
self.index.a_walk_is_over(&self.root);
}
}
#[derive(Default, Debug)]
struct Seen {
visibility: HashMap<String, IncludeVisibility>,
through_an_import: HashSet<String>,
module_work: Vec<String>,
}
impl Seen {
fn new(root: &str) -> Seen {
Seen {
visibility: HashMap::from([(root.to_string(), IncludeVisibility::Unconditional)]),
through_an_import: HashSet::new(),
module_work: Vec::new(),
}
}
}
impl Collecting<'_> {
fn fact(
&mut self,
summary: &FileSummary,
chain: &[usize],
fact: &MacroFact,
path_conditional: bool,
region: FactReach,
) {
if let Collecting::Names(out) = self {
out.insert(fact.name.clone());
return;
}
let Collecting::Name(name, out) = self else {
return;
};
if fact.name != *name {
return;
}
let mut position = chain.to_vec();
position.push(fact.range.start_offset);
out.push(MacroCandidate {
position,
file: summary.path.clone(),
fact: fact.clone(),
path_conditional,
region,
});
}
fn reborrow(&mut self) -> Collecting<'_> {
match self {
Collecting::Name(name, out) => Collecting::Name(name, out),
Collecting::Names(out) => Collecting::Names(out),
Collecting::Visibility(seen) => Collecting::Visibility(seen),
Collecting::Nothing => Collecting::Nothing,
}
}
fn crossed(&mut self, target: &str, visibility: IncludeVisibility, through_an_import: bool) {
let Collecting::Visibility(seen) = self else {
return;
};
match seen.visibility.get(target) {
Some(known) if *known <= visibility => {}
_ => {
seen.visibility.insert(target.to_string(), visibility);
}
}
if through_an_import {
seen.through_an_import.insert(target.to_string());
}
}
fn reached_by_include(&mut self, target: &str) {
let Collecting::Visibility(seen) = self else {
return;
};
seen.through_an_import.remove(target);
}
fn crossed_a_module(&mut self, target: &str) {
let Collecting::Visibility(seen) = self else {
return;
};
seen.visibility
.entry(target.to_string())
.or_insert(IncludeVisibility::Unconditional);
if !seen.module_work.iter().any(|queued| queued == target) {
seen.module_work.push(target.to_string());
}
}
fn decided_at(
&mut self,
summary: &FileSummary,
state: &Marked,
region: u32,
condition_at: usize,
offset: usize,
) -> Option<Option<bool>> {
let Collecting::Visibility(seen) = self else {
return None;
};
let _ = seen;
if summary.guards.own_guard == Some(region) {
return Some(Some(true));
}
let asked = summary.guards.region_at(region, offset)?;
Some(
asked.visibility(&crate::index::environment::MacrosHere::from_walk(
state,
condition_at,
)),
)
}
}
fn apply_fact(state: &mut Marked, fact: &MacroFact, path_conditional: bool, reach: FactReach) {
if path_conditional || reach == FactReach::Unknown {
match (fact.settles_the_name, fact.kind) {
(true, crate::MacroKind::Definition) => state.define_name(&fact.name),
(true, crate::MacroKind::Undefinition) => state.undefine(&fact.name),
_ => state.mark_uncertain(&fact.name),
}
return;
}
match reach {
FactReach::Active => state.observe(fact),
FactReach::Inactive | FactReach::Unknown => {}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FactReach {
Active,
Inactive,
Unknown,
}
#[derive(Debug, Clone, Default)]
pub struct MacroEnvironment {
name: String,
candidates: Vec<MacroCandidate>,
}
impl MacroEnvironment {
pub fn at(&self, offset: usize) -> Known<&MacroCandidate> {
let in_force: Vec<&MacroCandidate> = self.in_force(offset).collect();
let best = last(
in_force
.iter()
.copied()
.filter(|candidate| !candidate.is_conditional()),
)
.or_else(|| last(in_force.iter().copied()));
let Some(best) = best else {
return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(
self.name.as_str(),
)));
};
if best.is_conditional() {
return Known::Unknown(UnknownReason::ConditionalCompilation);
}
self.as_answer(best)
}
pub fn is_a_macro_at(&self, offset: usize) -> Known<&MacroCandidate> {
let in_force: Vec<&MacroCandidate> = self.in_force(offset).collect();
let Some(best) = last(
in_force
.iter()
.copied()
.filter(|candidate| candidate.is_certain_about_the_name()),
) else {
return if in_force.is_empty() {
Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(
self.name.as_str(),
)))
} else {
Known::Unknown(UnknownReason::ConditionalCompilation)
};
};
if best.is_definition() {
return Known::Yes(best);
}
let overturned = in_force
.iter()
.any(|candidate| candidate.position > best.position && candidate.is_definition());
if overturned {
return Known::Unknown(UnknownReason::ConditionalCompilation);
}
Known::Unknown(UnknownReason::UndefinedHere(Box::from(self.name.as_str())))
}
fn in_force(&self, offset: usize) -> impl Iterator<Item = &MacroCandidate> {
self.candidates
.iter()
.filter(move |candidate| candidate.position[0] <= offset)
}
fn as_answer<'a>(&self, best: &'a MacroCandidate) -> Known<&'a MacroCandidate> {
if best.is_definition() {
return Known::Yes(best);
}
Known::Unknown(UnknownReason::UndefinedHere(Box::from(self.name.as_str())))
}
pub fn is_empty(&self) -> bool {
self.candidates.is_empty()
}
}
fn last<'a>(candidates: impl Iterator<Item = &'a MacroCandidate>) -> Option<&'a MacroCandidate> {
candidates.max_by(|one, other| one.position.cmp(&other.position))
}
#[derive(Debug, Clone)]
pub struct MacroCandidate {
position: Vec<usize>,
file: PathBuf,
fact: MacroFact,
path_conditional: bool,
region: FactReach,
}
impl MacroCandidate {
pub fn file(&self) -> &Path {
&self.file
}
pub fn fact(&self) -> &MacroFact {
&self.fact
}
pub fn is_definition(&self) -> bool {
self.fact.kind.is_definition()
}
pub fn is_conditional(&self) -> bool {
self.path_conditional || self.region == FactReach::Unknown
}
pub fn is_certain_about_the_name(&self) -> bool {
!self.path_conditional && (self.fact.settles_the_name || self.region == FactReach::Active)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VisibleDeclaration<'a> {
pub file: PathBuf,
pub fact: &'a DeclFact,
pub visibility: IncludeVisibility,
}
struct ProjectDeclaration {
file: PathBuf,
fact: DeclFact,
start_offset: usize,
}
impl ProjectDeclaration {
fn of(found: &VisibleDeclaration<'_>) -> ProjectDeclaration {
ProjectDeclaration {
file: found.file.clone(),
fact: found.fact.clone(),
start_offset: found.fact.name_range.start_offset,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct IndexedKind {
pub kind: DeclKind,
pub scope: Option<Box<str>>,
pub enumerator: bool,
pub template: bool,
}
impl IndexedKind {
pub(crate) fn of(found: &DeclFact) -> IndexedKind {
IndexedKind {
kind: found.kind,
scope: found.scope.clone().map(Box::from),
enumerator: found.kind == DeclKind::Variable
&& found.type_of.is_none()
&& found.scope.is_some(),
template: !found.parameters.is_empty(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectDefinition {
pub file: PathBuf,
pub fact: DeclFact,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectDefinitions {
pub found: Vec<ProjectDefinition>,
pub conditional: usize,
}
impl ProjectDefinitions {
pub fn one(found: ProjectDefinition) -> Self {
ProjectDefinitions {
found: vec![found],
conditional: 0,
}
}
pub fn is_one(&self) -> bool {
self.found.len() == 1
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MemberList {
pub members: Vec<ProjectMember>,
pub unlisted: Vec<UnlistedBase>,
}
impl MemberList {
pub fn own(&self) -> impl Iterator<Item = &ProjectMember> {
self.members.iter().filter(|member| member.depth == 0)
}
pub fn at_depth(&self, depth: usize) -> impl Iterator<Item = &ProjectMember> {
self.members
.iter()
.filter(move |member| member.depth == depth)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectMember {
pub file: PathBuf,
pub fact: DeclFact,
pub declared_in: String,
pub depth: usize,
pub ambiguous: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnlistedBase {
pub spelling: String,
pub reason: UnknownReason,
}
impl ProjectDefinition {
pub fn from_binding(
path: &Path,
binding: crate::Binding,
scope: Option<String>,
local: bool,
) -> Self {
ProjectDefinition {
file: path.to_path_buf(),
fact: DeclFact {
modifiers: crate::DeclModifiers::default(),
frees: 0,
reflection: None,
name: binding
.name
.identifier_text()
.unwrap_or_default()
.to_string(),
scope,
local,
in_namespace: None,
kind: crate::DeclKind::from_binding_kind(binding.kind),
definition: false,
type_of: None,
returns: None,
split_by_a_directive: false,
bases: Vec::new(),
parameters: Vec::new(),
constraints: Vec::new(),
requires_clause: None,
parameter_defaults: Vec::new(),
pattern: None,
parameter_list: None,
access: None,
exported: false,
range: binding.range,
name_range: binding.name_range,
clean: true,
guard: FactGuard::Unconditional,
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum IncludeVisibility {
Unconditional,
Conditional,
}
#[derive(Clone, Copy)]
enum Narrow<'q> {
Nothing,
Named(&'q [&'q str]),
Scoped(&'q str),
}
struct Hit<'a> {
rank: usize,
name: String,
qualified: String,
file: &'a Path,
posting: Posting,
fact: &'a DeclFact,
}
fn hit_order(one: &Hit<'_>, two: &Hit<'_>) -> std::cmp::Ordering {
one.rank
.cmp(&two.rank)
.then_with(|| one.name.cmp(&two.name))
.then_with(|| one.qualified.cmp(&two.qualified))
.then_with(|| one.file.cmp(two.file))
.then_with(|| one.posting.cmp(&two.posting))
}
fn sort_hits(hits: &mut [Hit<'_>]) {
hits.sort_by(hit_order);
}
fn matches(fact: &DeclFact, name: &str) -> bool {
if fact.local {
return false;
}
if fact.name.is_empty() {
return false;
}
if let Some(global) = name.strip_prefix("::") {
return fact.scope.is_none() && fact.name == global;
}
fact.qualified_name() == name || fact.name == name
}
fn include_targets(summary: &FileSummary) -> Vec<String> {
summary
.includes
.iter()
.filter_map(|include| include.resolved.as_ref())
.map(|path| normalize(path))
.collect()
}
fn normalize(path: &Path) -> String {
normalize_path(path, cfg!(windows))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectSymbol {
pub file: PathBuf,
pub fact: DeclFact,
}
fn rank_of(qualified: &str, name: &str, wanted: &str) -> Option<usize> {
let wanted = wanted.trim_start_matches("::").to_lowercase();
if wanted.is_empty() {
return None;
}
let query: Vec<&str> = wanted.split("::").collect();
if query.len() == 1 {
let name = name.to_lowercase();
if name == wanted {
return Some(0);
}
if name.starts_with(&wanted) {
return Some(1);
}
if name.contains(&wanted) {
return Some(2);
}
return None;
}
let segments: Vec<String> = qualified
.to_lowercase()
.split("::")
.map(str::to_string)
.collect();
if segments.len() < query.len() {
return None;
}
let tail = &segments[segments.len() - query.len()..];
let (last_asked, asked) = query.split_last()?;
let (last, rest) = tail.split_last()?;
if rest.iter().map(String::as_str).ne(asked.iter().copied()) {
return None;
}
if last == last_asked {
return Some(0);
}
if last.starts_with(last_asked) {
return Some(1);
}
None
}
fn the_same_declaration(one: &DeclFact, other: &DeclFact) -> bool {
one.name == other.name
&& one.scope == other.scope
&& one.local == other.local
&& one.kind == other.kind
&& one.type_of == other.type_of
&& one.returns == other.returns
&& one.bases == other.bases
&& one.parameters == other.parameters
&& one.parameter_list == other.parameter_list
}
fn the_same_declaration_in_one_file(one: &ProjectDeclaration, other: &ProjectDeclaration) -> bool {
if one.file != other.file || !the_same_declaration(&one.fact, &other.fact) {
return false;
}
match one.fact.kind {
DeclKind::Variable | DeclKind::Type => one.fact.type_of.is_some(),
DeclKind::Function => one.fact.parameter_list.is_some(),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::{IncludeVisibility, ProjectIndex};
use crate::cache::SummaryKey;
use crate::index::summarize;
use crate::symbol::{Known, UnknownReason};
use std::path::Path;
#[test]
fn a_member_named_like_its_class_does_not_hide_the_class() {
let index = index(&[
(
"/p/LSPHandle.h",
"class LSPHandle {\npublic:\n LSPHandle(int server);\n void RefreshDiagnostic();\n};\n",
),
(
"/p/LSPHandle.cpp",
"#include \"LSPHandle.h\"\nLSPHandle::LSPHandle(int server) {\n}\n",
),
]);
let found = index.definition("LSPHandle", Path::new("/p/LSPHandle.cpp"));
let Known::Yes(definition) = found else {
panic!("the class must resolve, not fall to its constructor: {found:?}");
};
assert_eq!(
definition.fact.kind,
crate::DeclKind::Type,
"the name `LSPHandle` resolved to {:?} in {}",
definition.fact.kind,
definition.file.display()
);
}
fn index(files: &[(&str, &str)]) -> ProjectIndex {
let mut index = ProjectIndex::new();
for (path, source) in files {
let mut summary = summarize(Path::new(path), source, SummaryKey::new(0, 0));
for include in &mut summary.includes {
include.resolved =
Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(summary);
}
index
}
#[test]
fn a_declaration_in_an_included_header_is_found() {
let index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
),
]);
let found = index.definition("Widget", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("the class in the included header must be found: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/widget.h"));
assert_eq!(definition.fact.name, "Widget");
}
#[test]
fn a_declaration_a_macro_makes_is_found_once_the_file_is_cooked() {
let files = [
(
"/p/decl.h",
"#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n",
),
("/p/api.h", "#include \"decl.h\"\nDECLARE_HANDLE(HWND);\n"),
];
let mut index = ProjectIndex::new();
let mut definitions = crate::MacroDefinitions::default();
for (path, source) in files {
let mut summary = summarize(Path::new(path), source, SummaryKey::new(0, 0));
for include in &mut summary.includes {
include.resolved =
Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
let _ = source;
index.insert(summary);
}
let api = Path::new("/p/api.h");
let source = files[1].1;
let before = index.definition("HWND__", api);
assert!(
matches!(before, Known::Unknown(_)),
"the raw reading cannot see a declaration inside a macro body: {before:?}"
);
let text_of = |wanted: &Path| {
files
.iter()
.find(|(path, _)| Path::new(path) == wanted)
.map(|(_, source)| *source)
.unwrap_or("")
};
let unit = crate::TranslationUnit::walk(
index.summary(api).expect("indexed"),
|wanted| {
index
.summary(wanted)
.map(|summary| (summary, text_of(wanted)))
},
&crate::Marked::default(),
&mut definitions,
false,
&crate::WalkCache::new(),
);
let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
let unit_definitions = unit.definitions();
let macros = crate::preprocess::cooked::FileMacros::new(
unit.environment_of(api).expect("the unit reaches api.h"),
&unit_definitions,
None,
true,
);
let rendered = crate::preprocess::cooked::cook_with(source, &tokens, ¯os).render();
let provider = crate::MemoryFiles::new();
let config = crate::CompilerConfig::default();
let indexer = crate::FileIndexer::new(&provider, &config);
let indexed = indexer.index_rendering(api, &rendered, SummaryKey::new(0, 0));
assert_eq!(indexed.mapped.dropped, 0, "every range landed in the file");
index.insert_cooked(api, indexed.into());
let after = index.definition("HWND__", api);
let Known::Yes(definition) = after else {
panic!("the cooked reading declares it: {after:?}");
};
assert_eq!(definition.file, api);
let written =
&source[definition.fact.range.start_offset..definition.fact.range.end_offset()];
assert!(
written.contains("DECLARE_HANDLE"),
"the declaration is reported at the invocation: {written:?}"
);
assert!(
matches!(index.definition("HWND", api), Known::Yes(_)),
"and the typedef with it: {:?}",
index.definition("HWND", api)
);
}
#[test]
fn a_declaration_both_readings_found_is_one_candidate() {
let source = "struct Plain { int size; };\n";
let mut index = index(&[("/p/a.h", source)]);
let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
let rendered = crate::preprocess::cooked::cook(source, &tokens).render();
let provider = crate::MemoryFiles::new();
let config = crate::CompilerConfig::default();
let indexer = crate::FileIndexer::new(&provider, &config);
let indexed =
indexer.index_rendering(Path::new("/p/a.h"), &rendered, SummaryKey::new(0, 0));
assert_eq!(indexed.mapped.dropped, 0);
index.insert_cooked(Path::new("/p/a.h"), indexed.into());
let found = index.definition("Plain", Path::new("/p/a.h"));
assert!(matches!(found, Known::Yes(_)), "one candidate: {found:?}");
}
fn cooked_reading_of(path: &str, source: &str) -> crate::CookedFile {
let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
let rendered = crate::preprocess::cooked::cook(source, &tokens).render();
let provider = crate::MemoryFiles::new();
let config = crate::CompilerConfig::default();
let indexer = crate::FileIndexer::new(&provider, &config);
indexer
.index_rendering(Path::new(path), &rendered, SummaryKey::new(0, 0))
.into()
}
#[test]
fn a_workspace_search_finds_symbols_across_the_project() {
let mut index = index(&[
(
"/p/widget.h",
"namespace ns {\nstruct Widget { int size; };\n}\n",
),
(
"/p/other.cpp",
"void f() {\n int widget_local;\n}\nstruct Widest { int y; };\n",
),
(
"/p/handle.h",
"#define DECLARE_HANDLE(name) struct name##__ { int unused; };\nDECLARE_HANDLE(HWND);\n",
),
]);
let names = |found: &[super::ProjectSymbol]| -> Vec<String> {
found
.iter()
.map(|symbol| symbol.fact.name.clone())
.collect()
};
let found = index.symbols_matching("wid", 100);
assert_eq!(
names(&found),
vec!["Widest", "Widget"],
"one rank, alphabetical by name: {found:?}"
);
assert_eq!(
found[1].fact.scope.as_deref(),
Some("ns"),
"and the fact says which scope it was written in: {found:?}"
);
let found = index.symbols_matching("widget", 100);
assert_eq!(names(&found), vec!["Widget"], "{found:?}");
let found = index.symbols_matching("idg", 100);
assert_eq!(
names(&found),
vec!["Widget"],
"a substring finds the name it is inside: {found:?}"
);
assert_eq!(
names(&index.symbols_matching("widget_local", 100)),
Vec::<String>::new(),
"a variable inside a body is not something the project has"
);
assert_eq!(
names(&index.symbols_matching("ns::widget", 100)),
vec!["Widget"]
);
assert_eq!(
names(&index.symbols_matching("Widget::si", 100)),
vec!["size"],
"a query with `::` is about a qualified name"
);
assert_eq!(index.symbols_matching("wid", 1).len(), 1);
index.insert_cooked(
Path::new("/p/handle.h"),
cooked_reading_of(
"/p/handle.h",
"#define DECLARE_HANDLE(name) struct name##__ { int unused; };\nDECLARE_HANDLE(HWND);",
),
);
assert!(
names(&index.symbols_matching("HWND__", 100)).contains(&"HWND__".to_string()),
"the macro-declared type is a symbol a compiler knows"
);
}
#[test]
fn re_indexing_different_text_takes_the_cooked_reading_with_it() {
let source = "struct Plain { int size; };\n";
let mut index = index(&[("/p/a.h", source)]);
index.insert_cooked(Path::new("/p/a.h"), cooked_reading_of("/p/a.h", source));
assert!(index.cooked_declarations(Path::new("/p/a.h")).is_some());
let same = summarize(Path::new("/p/a.h"), source, SummaryKey::new(0, 0));
index.insert(same);
assert!(
index.cooked_declarations(Path::new("/p/a.h")).is_some(),
"an unchanged file keeps its reading"
);
let changed = summarize(
Path::new("/p/a.h"),
"struct Other { int size; };\n",
SummaryKey::new(0, 0),
);
index.insert(changed);
assert!(
index.cooked_reading(Path::new("/p/a.h")).is_none(),
"the reading goes with the text it was built from"
);
}
#[test]
fn a_declaration_in_a_header_the_file_does_not_include_is_not_found() {
let index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
("/p/other.cpp", "void g() { }\n"),
]);
let found = index.definition("Widget", Path::new("/p/other.cpp"));
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"a name that is not in scope is not a definition: {found:?}"
);
}
#[test]
fn visibility_follows_a_chain_of_includes() {
let index = index(&[
("/p/deep.h", "struct Deep { int x; };\n"),
("/p/middle.h", "#include \"deep.h\"\n"),
(
"/p/main.cpp",
"#include \"middle.h\"\nvoid f() { Deep d; }\n",
),
]);
let found = index.definition("Deep", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("a transitively included declaration is visible: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/deep.h"));
}
#[test]
fn the_files_own_declaration_wins_over_an_included_one() {
let index = index(&[
("/p/widget.h", "struct Widget { int from_header; };\n"),
(
"/p/main.cpp",
"#include \"widget.h\"\nstruct Widget { int from_this_file; };\n",
),
]);
let found = index.definition("Widget", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("the local declaration wins: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/main.cpp"));
}
#[test]
fn a_name_declared_in_two_visible_headers_is_ambiguous_rather_than_guessed() {
let index = index(&[
("/p/one.h", "int count;\n"),
("/p/two.h", "int count;\n"),
(
"/p/main.cpp",
"#include \"one.h\"\n#include \"two.h\"\nvoid f() { count = 1; }\n",
),
]);
let found = index.definition("count", Path::new("/p/main.cpp"));
assert!(
matches!(found, Known::Unknown(UnknownReason::Ambiguous(_))),
"two declarations and nothing to choose between them: {found:?}"
);
}
#[test]
fn two_declarations_of_one_name_are_a_list_for_a_consumer_that_shows_one() {
let index = index(&[
("/p/one.h", "int count;\n"),
("/p/two.h", "int count;\n"),
(
"/p/main.cpp",
"#include \"one.h\"\n#include \"two.h\"\nvoid f() { count = 1; }\n",
),
]);
let Known::Yes(found) = index.definitions("count", Path::new("/p/main.cpp")) else {
panic!("two declarations, both of them answers");
};
assert_eq!(found.found.len(), 2);
assert_eq!(found.conditional, 0);
assert_eq!(
found.found[0].file,
Path::new("/p/one.h"),
"the order is imposed (by file, then offset), so a client's peek list cannot reorder itself between \
two identical requests"
);
assert_eq!(found.found[1].file, Path::new("/p/two.h"));
}
#[test]
fn a_bare_name_does_not_reach_a_class_member() {
let index = index(&[
(
"/p/name.h",
"struct Name {\n void printf(int i);\n};\nvoid Name::printf(int i) { }\n",
),
("/p/stdio.h", "void printf(const char* format, ...);\n"),
(
"/p/main.cpp",
"#include \"name.h\"\n#include \"stdio.h\"\nvoid f() { printf(\"x\"); }\n",
),
]);
let found = index.definitions_in_scope("printf", Path::new("/p/main.cpp"));
let Known::Yes(found) = found else {
panic!("the file can name the global `printf`: {found:?}");
};
assert_eq!(
found.found.len(),
1,
"one declaration, the only one an unqualified `printf` can denote: {:?}",
found
.found
.iter()
.map(|definition| definition.file.display().to_string())
.collect::<Vec<_>>()
);
assert_eq!(found.found[0].file, Path::new("/p/stdio.h"));
let Known::Yes(every) = index.definitions("printf", Path::new("/p/main.cpp")) else {
panic!("the index holds the spelling");
};
assert_eq!(
every.found.len(),
2,
"a member access whose object's type is unknown still asks this one"
);
let Known::Yes(qualified) =
index.definitions_in_scope("Name::printf", Path::new("/p/main.cpp"))
else {
panic!("a qualified name is a member's own question");
};
assert_eq!(
qualified.found.len(),
1,
"the member, addressed through its qualifier: {qualified:?}"
);
}
#[test]
fn an_overload_set_is_a_list_and_a_namespace_is_one_entity() {
let index = index(&[
(
"/p/lib.h",
"namespace ns {\n void f(int);\n void f(double);\n}\n",
),
("/p/other.h", "namespace ns {\n void f(char);\n}\n"),
(
"/p/main.cpp",
"#include \"lib.h\"\n#include \"other.h\"\nvoid h() { ns::f(1); }\n",
),
]);
let Known::Yes(found) = index.definitions("ns::f", Path::new("/p/main.cpp")) else {
panic!("an overload set is three declarations, not an ambiguity");
};
assert_eq!(found.found.len(), 3);
let Known::Yes(found) = index.definitions("ns", Path::new("/p/main.cpp")) else {
panic!("the namespace is declared in both headers");
};
assert_eq!(
found.found.len(),
1,
"one namespace, however many files reopen it: a peek list of fifty-eight entries answers a question \
nobody asked"
);
}
#[test]
fn one_function_declared_twice_is_one_entity_and_an_overload_is_two() {
let index = index(&[(
"/p/lib.h",
"namespace ns {\n void f(int);\n void f(int);\n void f(double);\n}\n",
)]);
let Known::Yes(found) = index.definitions("ns::f", Path::new("/p/lib.h")) else {
panic!("three declarations of `ns::f`, and two entities among them");
};
assert_eq!(
found.found.len(),
2,
"the twice-declared `(int)` is one entity; `(double)` is an overload: {found:?}"
);
}
#[test]
fn the_walk_that_carries_the_state_sees_what_asking_each_condition_saw() {
let index = index(&[
("/p/one.h", "#define ONE 1\n"),
("/p/two.h", "int count;\n"),
("/p/three.h", "int three;\n"),
(
"/p/main.cpp",
"#include \"one.h\"\n#ifdef FEATURE\n#include \"two.h\"\n#endif\n#include \"three.h\"\n",
),
("/p/four.h", "#include \"two.h\"\n"),
("/p/other.cpp", "#include \"four.h\"\n"),
]);
for root in ["/p/main.cpp", "/p/other.cpp"] {
let walked = index.visible_files(Path::new(root));
let asked = index.visible_files_by_asking_each_condition(Path::new(root));
let mut walked = walked.clone();
let mut asked = asked.clone();
walked.sort_by(|left, right| left.0.cmp(&right.0));
asked.sort_by(|left, right| left.0.cmp(&right.0));
assert_eq!(
walked, asked,
"the two walks disagree about {root}: the completion list is built from this set"
);
}
}
#[test]
fn a_declaration_behind_a_conditional_include_is_counted_not_offered() {
let index = index(&[
("/p/one.h", "int count;\n"),
("/p/two.h", "int count;\n"),
(
"/p/main.cpp",
"#include \"one.h\"\n#ifdef FEATURE\n#include \"two.h\"\n#endif\nvoid f() { count = 1; }\n",
),
]);
let Known::Yes(found) = index.definitions("count", Path::new("/p/main.cpp")) else {
panic!("the unguarded header declares it");
};
assert_eq!(found.found.len(), 1);
assert_eq!(found.found[0].file, Path::new("/p/one.h"));
assert_eq!(
found.conditional, 1,
"and the one that might also be there is counted, so the answer does not claim there is nothing else"
);
}
#[test]
fn an_include_inside_a_condition_that_is_decided_and_false_is_not_visible() {
let index = index(&[
("/p/arm.h", "int arm_intrinsic;\n"),
(
"/p/main.cpp",
"#if 0\n#include \"arm.h\"\n#endif\nvoid f() { }\n",
),
]);
let found = index.definition("arm_intrinsic", Path::new("/p/main.cpp"));
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"the branch was not taken, so the file is not in this translation unit at all: {found:?}"
);
}
#[test]
fn a_qualified_name_prefers_the_declaration_that_matches_it() {
let index = index(&[
("/p/a.h", "namespace a {\n struct Widget { int x; };\n}\n"),
("/p/b.h", "namespace b {\n struct Widget { int y; };\n}\n"),
(
"/p/main.cpp",
"#include \"a.h\"\n#include \"b.h\"\nvoid f() { a::Widget w; }\n",
),
]);
let found = index.definition("a::Widget", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("the qualified name must select one of them: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/a.h"));
assert_eq!(definition.fact.qualified_name(), "a::Widget");
}
#[test]
fn a_guarded_include_makes_the_answer_unknown() {
let index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
(
"/p/main.cpp",
"#if defined(USE_WIDGET)\n#include \"widget.h\"\n#endif\nvoid f() { Widget w; }\n",
),
]);
let found = index.definition("Widget", Path::new("/p/main.cpp"));
assert!(
matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
"a conditional include cannot be decided here: {found:?}"
);
}
#[test]
fn an_unconditional_include_beats_a_guarded_one() {
let index = index(&[
("/p/real.h", "struct Widget { int size; };\n"),
(
"/p/main.cpp",
"#include \"real.h\"\n#if defined(X)\n#include \"other.h\"\n#endif\nvoid f() { Widget w; }\n",
),
("/p/other.h", "struct Widget { int other; };\n"),
]);
let found = index.definition("Widget", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("the unconditional path wins: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/real.h"));
}
#[test]
fn a_file_that_includes_nothing_sees_only_itself() {
let index = index(&[("/p/a.cpp", "int count;\n"), ("/p/b.cpp", "int count;\n")]);
for path in ["/p/a.cpp", "/p/b.cpp"] {
let found = index.definition("count", Path::new(path));
let Known::Yes(definition) = found else {
panic!("{path} must find its own count: {found:?}");
};
assert_eq!(definition.file, Path::new(path));
}
}
#[test]
fn a_cycle_of_includes_does_not_hang_the_visibility_walk() {
let index = index(&[
("/p/a.h", "#include \"b.h\"\nstruct A { int x; };\n"),
("/p/b.h", "#include \"a.h\"\nstruct B { int y; };\n"),
("/p/main.cpp", "#include \"a.h\"\nvoid f() { B b; }\n"),
]);
let found = index.definition("B", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("a cycle must not stop a name being found: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/b.h"));
}
#[test]
fn the_reverse_edges_are_derived_from_the_summaries() {
let index = index(&[
("/p/header.h", "int x;\n"),
("/p/one.cpp", "#include \"header.h\"\n"),
("/p/two.cpp", "#include \"header.h\"\n"),
]);
let mut includers = index.includers_of(Path::new("/p/header.h"));
includers.sort();
assert_eq!(
includers,
[Path::new("/p/one.cpp"), Path::new("/p/two.cpp")],
"an edit to the header invalidates exactly these"
);
}
#[test]
fn reindexing_a_file_removes_the_edges_its_old_text_had() {
let mut index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
),
]);
assert!(index.includers_of(Path::new("/p/widget.h")).len() == 1);
let mut edited = summarize(
Path::new("/p/main.cpp"),
"void f() { }\n",
SummaryKey::new(1, 0),
);
for include in &mut edited.includes {
include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(edited);
assert!(
index.includers_of(Path::new("/p/widget.h")).is_empty(),
"the edge must go with the line that wrote it"
);
assert!(
matches!(
index.definition("Widget", Path::new("/p/main.cpp")),
Known::Unknown(_)
),
"and the name is no longer visible there"
);
}
#[test]
fn visibility_is_reported_so_a_caller_can_downgrade() {
let index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
("/p/main.cpp", "#include \"widget.h\"\n"),
]);
let found = index.files_declaring("Widget", Path::new("/p/main.cpp"));
assert_eq!(found.len(), 1);
assert_eq!(found[0].visibility, IncludeVisibility::Unconditional);
}
fn at(source: &str, needle: &str) -> usize {
source
.rfind(needle)
.unwrap_or_else(|| panic!("{needle:?} is not in {source:?}"))
}
fn analysed(
files: &[(&str, &str)],
from: &str,
source: &str,
) -> (ProjectIndex, cpp_parser::CppSyntaxTree) {
let (index, tree) = analysed_while_typing(files, from, source);
assert!(
tree.get_errors().is_empty(),
"the fixture must parse cleanly: {source:?}"
);
(index, tree)
}
fn analysed_while_typing(
files: &[(&str, &str)],
from: &str,
source: &str,
) -> (ProjectIndex, cpp_parser::CppSyntaxTree) {
let mut index = index(files);
let tree = cpp_parser::CppParser::parse(source, cpp_parser::ParserConfig::default());
let mut summary = summarize(Path::new(from), source, SummaryKey::new(0, 0));
for include in &mut summary.includes {
include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(summary);
(index, tree)
}
#[test]
fn a_local_declaration_is_answered_without_looking_in_the_index() {
let source = "#include \"widget.h\"\nvoid f() {\n int count = 0;\n count = 1;\n}\n";
let (index, tree) = analysed(&[("/p/widget.h", "int count;\n")], "/p/main.cpp", source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "count = 1;"),
);
let Known::Yes(definition) = found else {
panic!("the local must win: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/main.cpp"));
assert!(
definition.fact.range.start_offset > at(source, "void f"),
"the jump goes to the local, not to the header"
);
}
#[test]
fn another_files_local_is_never_the_answer() {
let source = "#include \"widget.h\"\nvoid f() {\n helper();\n}\n";
let (index, tree) = analysed(
&[(
"/p/widget.h",
"void g() {\n int helper = 0;\n}\nstruct Widget { int size; };\n",
)],
"/p/main.cpp",
source,
);
let header = index.summary(Path::new("/p/widget.h")).expect("indexed");
let helper = header
.declarations
.iter()
.find(|fact| fact.name == "helper")
.expect("the header declares `helper`");
assert!(helper.local, "declared inside `g`'s body");
assert_eq!(helper.scope, None, "…which is why the scope cannot say so");
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "helper();"),
);
assert!(
matches!(
found,
Known::Unknown(UnknownReason::NotDeclaredHere(_)) | Known::No
),
"the header's local is not a declaration of the name this file writes: {found:?}"
);
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n}\n";
let (index, tree) = analysed(
&[(
"/p/widget.h",
"void g() {\n int helper = 0;\n}\nstruct Widget { int size; };\n",
)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
let Known::Yes(definition) = found else {
panic!("`Widget` is at file scope in the header: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/widget.h"));
assert!(!definition.fact.local);
}
#[test]
fn a_call_resolves_through_the_return_type_of_a_header() {
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n w.inner().size = 1;\n}\n";
let (index, tree) = analysed(
&[(
"/p/widget.h",
"struct Inner {\n int size;\n};\nstruct Widget {\n Inner inner();\n};\n",
)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "size = 1;"),
);
let Known::Yes(definition) = found else {
panic!("`w.inner()` returns an `Inner`, which declares `size`: {found:?}");
};
assert_eq!(definition.fact.name, "size");
assert_eq!(
definition.file,
Path::new("/p/widget.h"),
"the member is in the header, like everything else on this chain"
);
}
#[test]
fn a_name_only_a_header_declares_is_found_through_the_index() {
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n}\n";
let (index, tree) = analysed(
&[("/p/widget.h", "struct Widget { int size; };\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
let Known::Yes(definition) = found else {
panic!("the header's class must be found: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/widget.h"));
assert_eq!(definition.fact.name, "Widget");
}
#[test]
fn a_qualified_name_resolves_into_an_included_header() {
let source = "#include \"a.h\"\nvoid f() {\n a::Widget w;\n}\n";
let (index, tree) = analysed(
&[("/p/a.h", "namespace a {\n struct Widget { int x; };\n}\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
let Known::Yes(definition) = found else {
panic!("the header's `a::Widget` must be found: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/a.h"));
assert_eq!(definition.fact.qualified_name(), "a::Widget");
}
#[test]
fn a_qualified_name_is_not_answered_by_a_same_named_declaration_elsewhere() {
let source = "#include \"b.h\"\nvoid f() {\n a::Widget w;\n}\n";
let (index, tree) = analysed(
&[("/p/b.h", "namespace b {\n struct Widget { int y; };\n}\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"`a::Widget` is not declared anywhere this file can see: {found:?}"
);
}
#[test]
fn a_global_spelling_does_not_match_a_namespaced_declaration() {
let source = "#include \"both.h\"\nvoid f() {\n ::Widget w;\n}\n";
let (index, tree) = analysed(
&[(
"/p/both.h",
"struct Widget { int global; };\nnamespace ns {\n struct Widget { int nested; };\n}\n",
)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
let Known::Yes(definition) = found else {
panic!("the global `Widget` is the one asked for: {found:?}");
};
assert_eq!(definition.fact.scope, None);
assert_eq!(definition.fact.name, "Widget");
}
fn member_of(
files: &[(&str, &str)],
from: &str,
source: &str,
needle: &str,
) -> Known<super::ProjectDefinition> {
let (index, tree) = analysed(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new(from),
at(source, needle),
)
}
#[test]
fn a_member_of_an_alias_resolves_through_it() {
let source = "struct Widget {\n int size;\n};\nusing Alias = Widget;\n\
void f() {\n Alias w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Alias` names `Widget`, so `size` is `Widget::size`: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
}
#[test]
fn a_member_of_the_standard_library_string_resolves_into_basic_string() {
let source = "namespace std {\n template<typename T> struct basic_string {\n int size;\n \
int find(int);\n };\n typedef basic_string<char> string;\n}\n\
void f() {\n std::string s;\n s.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`std::string::size` is `std::basic_string::size`: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(
member.fact.scope.as_deref(),
Some("std::basic_string"),
"the member is declared in the class the alias points at, and its scope says so"
);
}
#[test]
fn an_alias_written_with_using_resolves_the_same_way() {
let source = "namespace std {\n template<typename T> struct basic_string {\n int size;\n };\n \
using string = basic_string<char>;\n}\n\
void f() {\n std::string s;\n s.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the `using` form is the same declaration shape: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("std::basic_string"));
}
#[test]
fn an_alias_target_written_with_a_qualifier_is_taken_as_it_stands() {
let source = "namespace other {\n struct Thing {\n int size;\n };\n}\n\
namespace ns {\n using Alias = other::Thing;\n}\n\
void f() {\n ns::Alias t;\n t.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the qualified target is the class: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("other::Thing"));
}
#[test]
fn an_alias_to_an_alias_is_followed_to_the_class() {
let source = "struct Widget {\n int size;\n};\nusing B = Widget;\nusing A = B;\n\
void f() {\n A w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("two aliases deep is still a class at the end: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
}
#[test]
fn a_cycle_of_aliases_terminates_and_says_nothing_was_declared() {
let source = "using A = B;\nusing B = A;\nvoid f() {\n A w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(_)),
"a cycle of aliases names no class: {found:?}"
);
}
#[test]
fn an_alias_to_itself_terminates() {
let source = "using A = A;\nvoid f() {\n A w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(_)),
"`using A = A;` names no class: {found:?}"
);
}
#[test]
fn an_alias_whose_target_is_not_indexed_reports_the_target() {
let source = "using Alias = Widget;\nvoid f() {\n Alias w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Unknown(UnknownReason::NotDeclaredHere(written)) = found else {
panic!("the target is what was looked for: {found:?}");
};
assert_eq!(&*written, "Widget::size");
}
#[test]
fn an_alias_to_a_non_class_is_not_a_member_lookup() {
let source = "typedef int MyInt;\nvoid f() {\n MyInt x;\n x.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"`int` declares no members: {found:?}"
);
}
#[test]
fn a_function_pointer_typedef_records_the_whole_type() {
let source = "typedef void (*F)(int);\nvoid f() {\n F callback;\n callback();\n}\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let Known::Yes(fact) = index.definition("F", Path::new("/p/a.cpp")) else {
panic!("the alias is a fact")
};
assert_eq!(
fact.fact.type_of.as_deref(),
Some("void (*)(int)"),
"specifiers plus declarator minus the name"
);
let plain = "typedef basic_string<char> String;\n";
let (index, tree) = analysed(&[], "/p/b.cpp", plain);
let Known::Yes(fact) = index.definition("String", Path::new("/p/b.cpp")) else {
panic!("the alias is a fact")
};
assert_eq!(fact.fact.type_of.as_deref(), Some("basic_string<char>"));
let _ = (root, tree);
}
#[test]
fn a_member_list_of_an_alias_is_the_member_list_of_its_target() {
let source = "namespace std {\n template<typename T> struct basic_string {\n int size;\n \
int find(int);\n };\n typedef basic_string<char> string;\n}\n";
let list = members_of_class(&[], "/p/a.cpp", source, "std::string");
let Known::Yes(list) = list else {
panic!("the alias's target is a class with members: {list:?}");
};
assert!(
names(&list).contains(&"size") && names(&list).contains(&"find"),
"the members are `basic_string`'s: {:?}",
names(&list)
);
}
#[test]
fn a_member_access_resolves_through_the_objects_type() {
let source =
"struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Widget::size` is declared in this file: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
assert!(
member.fact.range.start_offset < at(source, "void f"),
"the jump goes to the member's declaration, not to the use"
);
}
#[test]
fn a_member_of_another_class_with_the_same_name_is_not_the_answer() {
let source = "struct Other {\n int size;\n};\nstruct Widget {\n int size;\n};\n\
void f() {\n Widget w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Widget::size` is the one the object names: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
assert!(
member.fact.range.start_offset > at(source, "struct Widget"),
"the jump lands in `Widget`, not in `Other`"
);
}
#[test]
fn a_member_access_reads_a_pointer_the_same_way() {
let source =
"struct Widget {\n int size;\n};\nvoid f() {\n Widget* p;\n p->size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the pointee's member is the answer: {found:?}");
};
assert_eq!(member.fact.name, "size");
}
#[test]
fn a_member_access_reaches_a_class_in_an_included_header() {
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n w.size = 1;\n}\n";
let (index, tree) = analysed(
&[("/p/widget.h", "struct Widget {\n int size;\n};\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "size = 1;"),
);
let Known::Yes(member) = found else {
panic!("the member declared in the header is the answer: {found:?}");
};
assert_eq!(member.file, Path::new("/p/widget.h"));
assert_eq!(member.fact.name, "size");
}
#[test]
fn a_member_access_through_a_qualified_type_resolves() {
let source = "namespace ns {\n struct Widget {\n int size;\n };\n}\n\
void f() {\n ns::Widget w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`ns::Widget::size` is in this file: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("ns::Widget"));
}
#[test]
fn a_member_of_a_class_that_does_not_have_it_is_not_declared_here() {
let source =
"struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.nope = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "nope = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"the class is known and the member is not in it: {found:?}"
);
}
#[test]
fn a_member_access_on_a_call_is_the_callees_return_type() {
let source = "struct Widget {\n int size;\n};\nWidget make();\n\
void f() {\n make().size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(definition) = found else {
panic!("`make()` returns a `Widget`, so `size` is its member: {found:?}");
};
assert_eq!(definition.fact.name, "size");
assert_eq!(definition.fact.type_of.as_deref(), Some("int"));
let constructed = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f() {\n Widget().size = 1;\n}\n",
"size = 1;",
);
assert!(
matches!(constructed, Known::Yes(_)),
"a temporary of a known class has the class's members: {constructed:?}"
);
}
#[test]
fn a_member_access_through_a_dereference_resolves() {
let through_a_call = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nWidget* make();\nvoid f() {\n (*make()).size = 1;\n}\n",
"size = 1;",
);
let Known::Yes(found) = through_a_call else {
panic!(
"`make()` returns a `Widget*`, so `(*make())` is a `Widget`: {through_a_call:?}"
);
};
assert_eq!(found.fact.name, "size");
let through_a_pointer = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f() {\n Widget* p;\n (*p).size = 1;\n}\n",
"size = 1;",
);
let Known::Yes(found) = through_a_pointer else {
panic!("`p` points at a `Widget`: {through_a_pointer:?}");
};
assert_eq!(found.fact.name, "size");
let through_a_parameter = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f(Widget* p) {\n (*p).size = 1;\n}\n",
"size = 1;",
);
let Known::Yes(found) = through_a_parameter else {
panic!("`p` points at a `Widget`: {through_a_parameter:?}");
};
assert_eq!(found.fact.name, "size");
let through_a_reference = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f() {\n Widget& r = w;\n (&r)->size = 1;\n}\n",
"size = 1;",
);
assert!(
matches!(through_a_reference, Known::Yes(_)),
"`&r` is a `Widget*`: {through_a_reference:?}"
);
}
#[test]
fn a_dereference_of_something_that_is_not_a_pointer_is_an_unknown_type() {
let source =
"struct Widget {\n int size;\n};\nvoid f() {\n int* q;\n (*q).size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
"an `int` is not a class, and saying so beats inventing one: {found:?}"
);
let vector = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\ntemplate<typename T> struct Box { T first; };\n\
void f() {\n Box<Widget> box;\n box[0].size = 1;\n}\n",
"size = 1;",
);
assert!(
matches!(vector, Known::Unknown(UnknownReason::UnknownType(_))),
"a class subscript needs the template instantiated: {vector:?}"
);
}
#[test]
fn a_member_access_through_a_subscript_of_an_array_resolves() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget arr[4];\n arr[0].size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(found) = found else {
panic!("`arr[0]` is a `Widget`: {found:?}");
};
assert_eq!(found.fact.name, "size");
let two_dimensional = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f() {\n Widget grid[2][3];\n grid[i][j].size = 1;\n}\n",
"size = 1;",
);
assert!(
matches!(two_dimensional, Known::Yes(_)),
"`grid[i][j]` is a `Widget`: {two_dimensional:?}"
);
}
#[test]
fn a_call_of_something_with_no_return_type_is_an_unknown_type() {
let source = "struct Widget {\n int size;\n};\nauto make() { return Widget{}; }\n\
void f() {\n make().size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(found) = found else {
panic!("`return Widget{{}}` states the type it returns: {found:?}");
};
assert_eq!(found.fact.name, "size");
for source in [
"struct Widget {\n int size;\n};\nWidget source();\n\
auto make() { return source(); }\nvoid f() {\n make().size = 1;\n}\n",
"struct Widget {\n int size;\n};\nauto make();\nvoid f() {\n make().size = 1;\n}\n",
] {
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
"the file does not state what this call has: {found:?}"
);
}
}
#[test]
fn a_member_access_on_an_unknown_object_is_an_unknown_type() {
let source = "void f() {\n widget.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
"nothing says what `widget` is: {found:?}"
);
}
#[test]
fn a_cursor_that_is_not_on_a_member_access_has_nothing_to_look_up() {
let source =
"struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "= 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"the cursor is not on a member name: {found:?}"
);
}
#[test]
fn a_nested_member_access_follows_the_types_down() {
let source = "struct Inner {\n int size;\n};\nstruct Outer {\n Inner b;\n};\n\
void f() {\n Outer a;\n a.b.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Inner::size` is what `a.b.size` names: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Inner"));
assert!(
member.fact.range.start_offset < at(source, "struct Outer"),
"the jump lands in `Inner`, not in `Outer`"
);
}
#[test]
fn a_nested_member_access_that_disagrees_with_the_outer_class_is_not_answered_by_it() {
let source = "struct Inner {\n int size;\n};\nstruct Outer {\n Inner b;\n int size;\n};\n\
void f() {\n Outer a;\n a.b.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the member of `a.b`'s type is the answer: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Inner"));
}
#[test]
fn this_resolves_to_the_enclosing_class() {
let source =
"struct Widget {\n int size;\n void grow() {\n this->size = 1;\n }\n};\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`this->size` is `Widget::size`: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
}
#[test]
fn this_resolves_to_the_nearest_class_when_classes_are_nested() {
let source = "struct Outer {\n int size;\n struct Inner {\n int size;\n void f() {\n \
this->size = 1;\n }\n };\n};\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`this` inside `Inner` is `Inner`: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Outer::Inner"));
}
#[test]
fn a_nested_access_propagates_why_the_inner_one_failed() {
let source = "struct Inner {\n int size;\n};\nstruct Outer {\n Inner b;\n};\n\
void f() {\n Outer a;\n a.nope.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"there is no `nope` to type, and that is the answer worth keeping: {found:?}"
);
}
#[test]
fn a_member_inherited_from_a_base_class_resolves() {
let source = "struct Base {\n int size;\n};\nstruct Derived : public Base {\n int other;\n};\n\
void f() {\n Derived d;\n d.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Base::size` is inherited by `Derived`: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Base"));
assert!(
member.fact.range.start_offset < at(source, "struct Derived"),
"the jump lands in the base, not in the derived class"
);
}
#[test]
fn a_member_of_the_class_itself_hides_one_in_a_base() {
let source = "struct Base {\n int size;\n};\nstruct Derived : public Base {\n int size;\n};\n\
void f() {\n Derived d;\n d.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the class's own member hides the one it inherits: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Derived"));
}
#[test]
fn a_member_inherited_through_another_base_resolves() {
let source = "struct Base {\n int size;\n};\nstruct Middle : public Base {\n int m;\n};\n\
struct Derived : public Middle {\n int d;\n};\n\
void f() {\n Derived x;\n x.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("a member two bases down is still inherited: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Base"));
}
#[test]
fn a_member_declared_in_two_bases_at_once_is_ambiguous_rather_than_picked() {
let source = "struct Left {\n int size;\n};\nstruct Right {\n int size;\n};\n\
struct Both : public Left, public Right {\n int own;\n};\n\
void f() {\n Both b;\n b.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::Ambiguous(_))),
"two bases declare it and nothing chooses: {found:?}"
);
}
#[test]
fn a_member_inherited_across_a_header_resolves() {
let source = "#include \"base.h\"\nstruct Derived : public Base {\n int d;\n};\n\
void f() {\n Derived x;\n x.size = 1;\n}\n";
let (index, tree) = analysed(
&[("/p/base.h", "struct Base {\n int size;\n};\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "size = 1;"),
);
let Known::Yes(member) = found else {
panic!("the inherited member is declared in the header: {found:?}");
};
assert_eq!(member.file, Path::new("/p/base.h"));
assert_eq!(member.fact.name, "size");
}
#[test]
fn a_member_nobody_declares_is_still_not_declared() {
let source = "struct Base {\n int size;\n};\nstruct Derived : public Base {\n int d;\n};\n\
void f() {\n Derived x;\n x.nope = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "nope = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"neither the class nor its base declares it: {found:?}"
);
}
#[test]
fn a_base_list_is_read_without_its_access_keywords() {
let source = "struct Base {\n int size;\n};\nstruct Derived : private virtual Base {\n int d;\n};\n\
void f() {\n Derived x;\n x.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the access and `virtual` are not part of the base's name: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Base"));
}
#[test]
fn a_base_that_inherits_from_itself_terminates() {
let source = "struct A : public B {\n int a;\n};\nstruct B : public A {\n int size;\n};\n\
void f() {\n A x;\n x.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("a cycle must not stop the member being found: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("B"));
}
#[test]
fn a_local_declaration_still_wins_when_the_header_also_has_the_name() {
let source = "#include \"widget.h\"\nint count = 0;\nvoid f() {\n count = 1;\n}\n";
let (index, tree) = analysed(
&[("/p/widget.h", "int count = 7;\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "count = 1;"),
);
let Known::Yes(definition) = found else {
panic!("the file's own declaration wins: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/main.cpp"));
}
fn members_of_class(
files: &[(&str, &str)],
from: &str,
source: &str,
class: &str,
) -> Known<super::MemberList> {
let (index, tree) = analysed(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
super::members_of(&index, &scopes, &root, Path::new(from), class)
}
fn names(list: &super::MemberList) -> Vec<&str> {
list.members
.iter()
.map(|member| member.fact.name.as_str())
.collect()
}
#[test]
fn an_anonymous_unions_members_belong_to_the_struct() {
let source = "struct point { int x; int y; };\n\
struct line {\n\
struct point from;\n\
union { long integer; double real; };\n\
char colour;\n\
};\n";
let found = members_of_class(&[], "/p/a.c", source, "line");
let Known::Yes(list) = found else {
panic!("`line` is declared here: {found:?}");
};
assert!(
names(&list).contains(&"integer"),
"the union is anonymous, so its members are `line`'s: {:?}",
names(&list)
);
assert!(
names(&list).contains(&"real"),
"and so is `real`: {:?}",
names(&list)
);
}
#[test]
fn a_class_declared_more_than_once_still_reports_the_bases_it_could_not_read() {
let source = "template <class E>\nstruct Stream : Base {\n int read;\n};\ntemplate struct Stream<char>;\n";
let found = members_of_class(
&[("/p/base.h", "struct Base { int eof; };\n")],
"/p/a.cpp",
source,
"Stream",
);
let Known::Yes(list) = found else {
panic!("`Stream` is declared here: {found:?}");
};
assert_eq!(names(&list), ["read"], "its own member is listed");
assert_eq!(
list.unlisted
.iter()
.map(|base| base.spelling.as_str())
.collect::<Vec<_>>(),
["Base"],
"and the base the walk could not follow is named, so the list does not claim completeness"
);
}
#[test]
fn a_class_lists_the_members_written_in_it() {
let source = "struct Widget {\n void grow();\n int size;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Widget");
let Known::Yes(list) = found else {
panic!("`Widget` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["grow", "size"]);
assert!(
list.unlisted.is_empty(),
"a class with no bases has nothing left unread: {:?}",
list.unlisted
);
let size = &list.members[1];
assert_eq!(size.declared_in, "Widget");
assert_eq!(size.depth, 0, "its own member, not an inherited one");
assert!(!size.ambiguous);
assert_eq!(size.file, Path::new("/p/a.cpp"));
assert_eq!(
size.fact.type_of.as_deref(),
Some("int"),
"the type a completion shows beside the name"
);
assert_eq!(
list.own().count(),
2,
"every member here is the class's own"
);
}
#[test]
fn a_derived_class_lists_its_own_members_before_the_ones_it_inherits() {
let source = "struct Base {\n int inherited_count;\n};\n\
struct Derived : public Base {\n int own_count;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in this file: {found:?}");
};
assert_eq!(
names(&list),
["own_count", "inherited_count"],
"the class's own members come first, and the inherited one is last"
);
assert_eq!(list.members[0].declared_in, "Derived");
assert_eq!(list.members[0].depth, 0);
assert_eq!(
list.members[1].declared_in, "Base",
"the member is the base's, not the derived class's"
);
assert_eq!(list.members[1].depth, 1);
assert_eq!(
list.members[1].fact.type_of.as_deref(),
Some("int"),
"and it carries its own declaration's type"
);
assert_eq!(list.at_depth(1).count(), 1);
}
#[test]
fn a_member_the_class_redeclares_hides_the_one_in_its_base() {
let source = "struct Base {\n int size;\n};\n\
struct Derived : public Base {\n double size;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in this file: {found:?}");
};
assert_eq!(
names(&list),
["size"],
"one `size`, and it is the derived class's"
);
assert_eq!(list.members[0].declared_in, "Derived");
assert_eq!(list.members[0].fact.type_of.as_deref(), Some("double"));
}
#[test]
fn a_name_two_bases_declare_is_listed_twice_and_marked_ambiguous() {
let source = "struct Left {\n int value;\n};\nstruct Right {\n int value;\n};\n\
struct Both : public Left, public Right {\n int own;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Both");
let Known::Yes(list) = found else {
panic!("`Both` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["own", "value", "value"]);
let values: Vec<&super::ProjectMember> = list
.members
.iter()
.filter(|member| member.fact.name == "value")
.collect();
assert_eq!(values.len(), 2, "both declarations survive into the list");
assert!(
values.iter().all(|member| member.ambiguous),
"both are contested: {values:?}"
);
let mut declaring: Vec<&str> = values
.iter()
.map(|member| member.declared_in.as_str())
.collect();
declaring.sort_unstable();
assert_eq!(declaring, ["Left", "Right"]);
assert!(
!list.members[0].ambiguous,
"`own` is declared once, in one class"
);
}
#[test]
fn a_destructor_hides_nothing_in_a_base_because_its_spelling_is_its_own() {
let source = "struct Base {\n virtual ~Base();\n int size;\n};\n\
struct Derived : public Base {\n virtual ~Derived();\n int d;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in this file: {found:?}");
};
let destructors: Vec<&super::ProjectMember> = list
.members
.iter()
.filter(|member| member.fact.name.starts_with('~'))
.collect();
assert_eq!(
destructors.len(),
2,
"both destructors are declarations that exist, and dropping one would be a silent omission: {:?}",
names(&list)
);
let mut classes: Vec<&str> = destructors
.iter()
.map(|member| member.declared_in.as_str())
.collect();
classes.sort_unstable();
assert_eq!(classes, ["Base", "Derived"]);
let mut spellings: Vec<&str> = destructors
.iter()
.map(|member| member.fact.name.as_str())
.collect();
spellings.sort_unstable();
assert_eq!(
spellings,
["~Base", "~Derived"],
"a destructor's name is the class it destroys, so the two are not one name"
);
assert!(
destructors.iter().all(|member| !member.ambiguous),
"two different spellings are not one contested name: {destructors:?}"
);
assert!(
list.members
.iter()
.any(|member| member.fact.name == "size" && member.declared_in == "Base"),
"and the named members still cross the inheritance boundary: {:?}",
names(&list)
);
}
#[test]
fn a_destructor_without_a_specifier_is_a_member() {
let source = "struct Derived {\n ~Derived();\n int d;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("the class must be found by its own name: {found:?}");
};
assert_eq!(names(&list), ["d", "~Derived"]);
}
#[test]
fn overloads_in_one_class_are_not_ambiguous() {
let source = "struct Widget {\n void f();\n void f(int);\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Widget");
let Known::Yes(list) = found else {
panic!("`Widget` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["f", "f"], "both overloads are listed");
assert!(
list.members.iter().all(|member| !member.ambiguous),
"one class declaring a name twice is an overload set, not an ambiguity: {:?}",
list.members
);
}
#[test]
fn a_cycle_of_bases_terminates_and_each_class_contributes_once() {
let source = "struct A : public B {\n int a_member;\n};\nstruct B : public A {\n int b_member;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "A");
let Known::Yes(list) = found else {
panic!("`A` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["a_member", "b_member"]);
assert_eq!(list.members[0].depth, 0);
assert_eq!(
list.members[1].depth, 1,
"`A` is reached again as `B`'s base and is not listed a second time"
);
}
#[test]
fn a_template_class_lists_the_members_it_was_written_with() {
let source = "template <typename T>\nstruct Holder {\n T value;\n int count;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Holder");
let Known::Yes(list) = found else {
panic!("`Holder` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["count", "value"]);
assert_eq!(
list.members[1].fact.type_of.as_deref(),
Some("T"),
"the parameter as written, not an instantiated type"
);
assert!(
!list.members.iter().any(|member| member.fact.name == "T"),
"the template parameter is declared in the parameter list, not in the class: {:?}",
names(&list)
);
}
#[test]
fn a_type_nothing_declares_has_no_member_list_rather_than_an_empty_one() {
let source = "void f() { }\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Nowhere");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"`Nowhere` is not a type this analysis has seen: {found:?}"
);
}
#[test]
fn a_class_that_is_empty_has_an_empty_member_list() {
let source = "struct Empty { };\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Empty");
let Known::Yes(list) = found else {
panic!("`Empty` is declared in this file and has no members: {found:?}");
};
assert!(list.members.is_empty());
}
#[test]
fn a_member_declared_in_a_nested_class_is_not_a_member_of_the_outer_one() {
let source = "struct Outer {\n struct Inner {\n int x;\n };\n int y;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Outer");
let Known::Yes(list) = found else {
panic!("`Outer` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["Inner", "y"]);
assert_eq!(list.members[0].fact.qualified_name(), "Outer::Inner");
}
#[test]
fn a_member_list_crosses_a_header_and_keeps_the_base_tagged() {
let source = "#include \"base.h\"\nstruct Derived : public Base {\n int d;\n};\n";
let (index, tree) = analysed(
&[("/p/base.h", "struct Base {\n int size;\n};\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::members_of(&index, &scopes, &root, Path::new("/p/main.cpp"), "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in the buffer: {found:?}");
};
assert_eq!(names(&list), ["d", "size"]);
assert_eq!(list.members[1].file, Path::new("/p/base.h"));
assert_eq!(list.members[1].declared_in, "Base");
}
#[test]
fn a_base_that_resolves_to_a_template_is_listed_without_instantiating_it() {
let source = "template <typename T>\nstruct Base {\n T size;\n};\n\
struct Derived : public Base<int> {\n int d;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["d", "size"]);
assert_eq!(
list.members[1].fact.type_of.as_deref(),
Some("int"),
"the base's parameter is substituted: {list:?}"
);
assert_eq!(list.members[1].declared_in, "Base<int>");
}
#[test]
fn a_base_nothing_declares_is_reported_as_a_gap_rather_than_dropped() {
let source = "#include \"missing.h\"\nstruct Derived : public Base {\n int d;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` itself is in the buffer: {found:?}");
};
assert_eq!(names(&list), ["d"], "what could be listed is listed");
assert_eq!(list.unlisted.len(), 1, "and what could not is named");
assert_eq!(list.unlisted[0].spelling, "Base");
assert!(
matches!(list.unlisted[0].reason, UnknownReason::NotDeclaredHere(_)),
"the reason has to say that the base is not here, not that the list ended: {:?}",
list.unlisted[0].reason
);
}
#[test]
fn a_base_of_a_class_in_a_namespace_is_looked_up_in_that_namespace() {
let lib = "namespace std {\nstruct _Tree {\n void find();\n};\nstruct map : _Tree {\n int count;\n};\n}\n";
let source = "#include \"lib.h\"\nstruct _Tree {\n void wrong();\n};\nvoid f() {\n std::map m;\n m.find();\n m.wrong();\n}\n";
let files: &[(&str, &str)] = &[("/p/lib.h", lib)];
let Known::Yes(list) = members_of_class(files, "/p/a.cpp", source, "std::map") else {
panic!("`std::map` is in the indexed header");
};
assert_eq!(
names(&list),
["count", "find"],
"`find` comes from the base, and `wrong` is not a member of anything this class inherits"
);
assert!(
list.unlisted.is_empty(),
"the base was found, so nothing here is a gap: {:?}",
list.unlisted
);
assert_eq!(
list.members[1].declared_in, "std::_Tree",
"the answer names the scope the base was found in, not the spelling the class wrote"
);
assert_eq!(list.members[1].depth, 1);
let found = member_of(files, "/p/a.cpp", source, "find();");
let Known::Yes(found) = found else {
panic!("`m.find` is `std::_Tree::find`: {found:?}");
};
assert_eq!(found.file, Path::new("/p/lib.h"));
assert_eq!(found.fact.qualified_name(), "std::_Tree::find");
assert!(
matches!(
member_of(files, "/p/a.cpp", source, "wrong();"),
Known::Unknown(UnknownReason::NotDeclaredHere(_))
),
"a base name that a nearer scope has does not fall through to the file-scope `_Tree`"
);
}
#[test]
fn a_type_spelled_from_the_global_name_space_lists_the_same_members() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n ::Widget w;\n}\n";
let found = members_of_class(&[], "/p/a.cpp", source, "::Widget");
let Known::Yes(list) = found else {
panic!("`::Widget` is the file-scope `Widget`: {found:?}");
};
assert_eq!(names(&list), ["size"]);
assert_eq!(list.members[0].declared_in, "Widget");
}
#[test]
fn a_member_added_to_a_base_appears_without_reindexing_the_derived_class() {
let a_header = "#include \"b.h\"\nstruct A : public B {\n int a_member;\n};\n";
let before = "struct B {\n int old_member;\n};\n";
let after = "struct B {\n int new_member;\n};\n";
let main = "#include \"a.h\"\n";
let mut index = index(&[
("/p/main.cpp", main),
("/p/a.h", a_header),
("/p/b.h", before),
]);
let tree = cpp_parser::CppParser::parse(main, cpp_parser::ParserConfig::default());
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let listed = |index: &ProjectIndex| match super::members_of(
index,
&scopes,
&root,
Path::new("/p/main.cpp"),
"A",
) {
Known::Yes(list) => list
.members
.iter()
.map(|member| member.fact.name.clone())
.collect::<Vec<_>>(),
other => panic!("`A` is declared in an included header: {other:?}"),
};
assert_eq!(listed(&index), ["a_member", "old_member"]);
let mut rebuilt = summarize(Path::new("/p/b.h"), after, SummaryKey::new(1, 0));
for include in &mut rebuilt.includes {
include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(rebuilt);
assert_eq!(
listed(&index),
["a_member", "new_member"],
"the derived class's members are read from its bases at query time, so the edit is seen without \
anything of `A`'s being rebuilt"
);
let a = index
.summary(Path::new("/p/a.h"))
.expect("`a.h` is indexed");
let a_members: Vec<&str> = a
.declarations
.iter()
.filter(|fact| fact.scope.as_deref() == Some("A"))
.map(|fact| fact.name.as_str())
.collect();
assert_eq!(
a_members,
["a_member"],
"a fact stores the spelling `B`, never the members `B` happens to have"
);
}
fn after(source: &str, needle: &str) -> usize {
source
.rfind(needle)
.unwrap_or_else(|| panic!("{needle:?} is not in {source:?}"))
+ needle.len()
}
fn completions_at(
files: &[(&str, &str)],
from: &str,
source: &str,
needle: &str,
) -> Known<super::MemberCompletions> {
let (index, tree) = analysed_while_typing(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
super::member_completions_at(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new(from),
after(source, needle),
)
}
#[test]
fn a_private_member_is_offered_inside_the_class_and_not_outside_it() {
let outside = "\
class Widget {
int hidden;
public:
int shown;
};
void f() {
Widget w;
w.
}
";
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", outside, "w.") else {
panic!("`w` is a `Widget`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert_eq!(
offered,
["shown"],
"`hidden` is private and the cursor is not in `Widget`"
);
assert_eq!(
found.hidden_by_access, 1,
"and the answer says how many it kept out"
);
let inside = "\
class Widget {
int hidden;
public:
int shown;
void grow(Widget& other) {
other.
}
};
";
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", inside, "other.") else {
panic!("`other` is a `Widget`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert_eq!(
offered,
["grow", "hidden", "shown"],
"inside the class both are nameable, so both are offered"
);
}
#[test]
fn a_member_defined_outside_its_class_keeps_its_access() {
let source = "\
class Widget {
int hidden;
public:
int shown;
void set(int value);
void grow(Widget& other);
};
void Widget::set(int value) {
hidden = value;
}
void Widget::grow(Widget& other) {
other.
}
void f(Widget& w) {
w.
}
";
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "other.") else {
panic!("`other` is a `Widget`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert!(
offered.contains(&"hidden"),
"the cursor is inside a member of `Widget`, so `hidden` is nameable there: {offered:?}"
);
assert!(
offered.contains(&"set") && offered.contains(&"shown") && offered.contains(&"grow"),
"and so is everything else the class declares: {offered:?}"
);
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "w.") else {
panic!("`w` is a `Widget`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert!(
!offered.contains(&"hidden"),
"and from outside the class the same member is not: {offered:?}"
);
}
#[test]
fn a_protected_member_is_offered_in_a_derived_class() {
let source = "\
class Base {
protected:
int guarded;
public:
int open;
};
class Derived : public Base {
void grow(Derived& other) {
other.
}
};
void f(Derived& d) {
d.
}
";
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "other.") else {
panic!("`other` is a `Derived`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert_eq!(
offered,
["grow", "guarded", "open"],
"`guarded` is protected and the cursor is in a class derived from the one that declares it"
);
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "d.") else {
panic!("`d` is a `Derived`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert_eq!(
offered,
["open"],
"and from a free function the same member is not nameable"
);
}
#[test]
fn a_member_access_with_nothing_typed_offers_the_types_members() {
let source = "struct Widget {\n int size;\n void grow();\n};\n\
void f() {\n Widget w;\n w.\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "w.");
let Known::Yes(completions) = found else {
panic!("`w` is a `Widget` declared two lines up: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(
completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect::<Vec<_>>(),
["grow", "size"]
);
assert_eq!(completions.prefix, "", "nothing of the name is written yet");
assert_eq!(
completions.member_range.start_offset,
after(source, "w."),
"the empty range sits just past the operator, which is where the name goes"
);
assert_eq!(completions.member_range.length, 0);
}
#[test]
fn a_half_typed_member_offers_the_same_members_and_names_the_prefix() {
let source = "struct Widget {\n int size;\n void grow();\n};\n\
void f() {\n Widget w;\n w.si\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "w.si");
let Known::Yes(completions) = found else {
panic!("the cursor is on the member being typed: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(completions.prefix, "si");
assert_eq!(
&source[completions.member_range.start_offset..completions.member_range.end_offset()],
"si",
"the range covers what is written, so replacing it does not leave a doubled name"
);
}
#[test]
fn a_pointer_member_access_offers_the_pointees_members() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget* p;\n p->\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "p->");
let Known::Yes(completions) = found else {
panic!("`Widget* p` is a pointer to a `Widget`: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(completions.members.members.len(), 1);
}
#[test]
fn a_completion_on_this_offers_the_enclosing_class_members() {
let source = "struct Widget {\n int size;\n void grow() {\n this->\n }\n};\n";
let found = completions_at(&[], "/p/a.cpp", source, "this->");
let Known::Yes(completions) = found else {
panic!("`this` is the enclosing `Widget`: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(
completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect::<Vec<_>>(),
["grow", "size"]
);
}
#[test]
fn the_members_offered_include_the_ones_the_bases_declare() {
let source = "struct Base {\n int inherited_size;\n};\n\
struct Derived : public Base {\n int own_size;\n};\n\
void f() {\n Derived d;\n d.\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "d.");
let Known::Yes(completions) = found else {
panic!("`d` is a `Derived`: {found:?}");
};
let listed: Vec<(&str, &str)> = completions
.members
.members
.iter()
.map(|member| (member.fact.name.as_str(), member.declared_in.as_str()))
.collect();
assert_eq!(
listed,
[("own_size", "Derived"), ("inherited_size", "Base")],
"the class's own member first, then the inherited one, tagged with where it is declared"
);
}
#[test]
fn the_members_offered_cross_a_header() {
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n w.\n}\n";
let (index, tree) = analysed_while_typing(
&[("/p/widget.h", "struct Widget {\n int size;\n};\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_completions_at(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
after(source, "w."),
);
let Known::Yes(completions) = found else {
panic!("the class is in the included header: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(
completions.members.members[0].file,
Path::new("/p/widget.h")
);
}
#[test]
fn a_completion_after_a_call_offers_what_the_call_returns() {
let source = "struct Widget {\n int size;\n void grow();\n};\nWidget make();\n\
void f() {\n make().\n}\n";
let Known::Yes(completions) = completions_at(&[], "/p/a.cpp", source, "make().") else {
panic!("`make()` returns a `Widget`");
};
assert_eq!(completions.class, "Widget");
assert_eq!(
completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect::<Vec<_>>(),
["grow", "size"]
);
}
#[test]
fn a_completion_after_a_dereference_offers_the_pointees_members() {
let source = "struct Widget {\n int size;\n};\nWidget* make();\n\
void f() {\n (*make()).\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "(*make()).");
let Known::Yes(completions) = found else {
panic!("`(*make())` is a `Widget`, so its members are the answer: {found:?}");
};
assert_eq!(completions.class, "Widget");
}
#[test]
fn a_completion_on_an_expression_with_no_type_offers_nothing_and_says_why() {
let source =
"struct Widget {\n int size;\n};\nvoid f() {\n Widget a;\n (a.size + a.size).\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "(a.size + a.size).");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
"an arithmetic expression's type is not read off a declaration: {found:?}"
);
}
#[test]
fn a_completion_on_an_object_of_an_unknown_type_offers_nothing() {
let source = "void f() {\n Nowhere w;\n w.\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "w.");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"`Nowhere` is a type nothing here declares: {found:?}"
);
let Known::Unknown(UnknownReason::NotDeclaredHere(name)) = found else {
unreachable!("just checked")
};
assert_eq!(
&*name, "Nowhere",
"and the reason names the type, not the object"
);
}
#[test]
fn a_cursor_that_is_not_on_a_member_access_offers_nothing() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "Widget w;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"a declaration is not a member access: {found:?}"
);
}
#[test]
fn a_cursor_on_the_object_asks_about_the_object() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.size;\n}\n";
let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_completions_at(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/a.cpp"),
at(source, "w.size"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"the cursor is on the object, before the operator: {found:?}"
);
}
#[test]
fn a_cursor_inside_a_name_filters_by_the_part_before_it() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.size;\n}\n";
let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let cursor = at(source, "w.size") + 2 + 2;
let found = super::member_completions_at(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/a.cpp"),
cursor,
);
let Known::Yes(completions) = found else {
panic!("the cursor is inside the member's name: {found:?}");
};
assert_eq!(completions.prefix, "si", "what has been typed so far");
assert_eq!(
&source[completions.member_range.start_offset..completions.member_range.end_offset()],
"size",
"and the whole name is what gets replaced"
);
}
#[test]
fn a_completed_member_access_still_answers_with_its_own_prefix() {
let source = "struct Widget {\n int size;\n void grow();\n};\n\
void f() {\n Widget w;\n w.size\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "w.size");
let Known::Yes(completions) = found else {
panic!("the cursor is at the end of `size`: {found:?}");
};
assert_eq!(completions.prefix, "size");
assert_eq!(
&source[completions.member_range.start_offset..completions.member_range.end_offset()],
"size"
);
}
#[test]
fn a_jump_on_a_member_that_is_not_written_yet_has_nothing_to_jump_to() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.\n}\n";
let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/a.cpp"),
after(source, "w."),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"there is no written name to resolve: {found:?}"
);
}
fn names_at(
files: &[(&str, &str)],
from: &str,
source: &str,
needle: &str,
) -> Known<super::NameCompletions> {
let (index, tree) = analysed_while_typing(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
super::name_completions_at(
&index,
&scopes,
&root,
Path::new(from),
after(source, needle),
)
}
fn names_at_blank(
files: &[(&str, &str)],
from: &str,
source: &str,
) -> Known<super::NameCompletions> {
let (index, tree) = analysed_while_typing(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let at = source
.find("void f()")
.and_then(|body| source[body..].find('{').map(|brace| body + brace + 1))
.expect("the fixture has a body");
super::name_completions_at(&index, &scopes, &root, Path::new(from), at)
}
#[track_caller]
fn offered(found: &Known<super::NameCompletions>) -> Vec<String> {
match found {
Known::Yes(completions) => completions
.names
.iter()
.map(|name| name.fact.name.clone())
.collect(),
other => panic!("expected names: {other:?}"),
}
}
#[test]
fn a_name_in_a_late_file_of_a_namespace_is_still_offered() {
let mut big = String::from("namespace ns {\n");
for index in 0..(super::MAX_COLLECTED_NAMES + 20) {
big.push_str(&format!(" int filler{index};\n"));
}
big.push_str("}\n");
let late = "namespace ns {\n int zebra;\n}\n";
let big_with_include = format!("#include \"late.h\"\n{big}");
let source = "#include \"big.h\"\nvoid f() {\n ns::\n}\n";
let files = [
("/p/big.h", big_with_include.as_str()),
("/p/late.h", late),
("/p/a.cpp", source),
];
let found = names_at(&files, "/p/a.cpp", source, "ns::");
let names = offered(&found);
assert!(
names.iter().any(|name| name == "zebra"),
"the name is declared in a file the cursor can see, and the list must not stop before it: \
{} names offered, none of them `zebra`",
names.len()
);
}
#[test]
fn the_members_of_a_class_template_reached_through_an_alias_are_offered() {
let header = "namespace ns {\n\
template <class _Ty>\n\
struct Basic {\n\
unsigned long size() const;\n\
_Ty* data();\n\
};\n\
using String = Basic<char>;\n\
}\n";
let source = "#include \"basic.h\"\nvoid f() {\n ns::String::\n}\n";
let files = [("/p/basic.h", header), ("/p/a.cpp", source)];
let found = names_at(&files, "/p/a.cpp", source, "ns::String::");
let names = offered(&found);
assert!(
names.iter().any(|name| name == "size") && names.iter().any(|name| name == "data"),
"`ns::String` is `ns::Basic<char>`, and its members are the answer: {names:?}"
);
}
#[test]
fn a_qualified_scope_offers_the_names_written_in_it() {
let source =
"namespace ns {\n struct Widget { };\n int helper();\n}\nvoid f() {\n ns::\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "ns::");
assert_eq!(
offered(&found),
["Widget", "helper"],
"sorted within the scope"
);
let Known::Yes(completions) = found else {
unreachable!("asserted above")
};
assert_eq!(completions.scope, "ns", "the scope as a lookup key");
assert_eq!(completions.prefix, "", "nothing of the name is typed yet");
assert_eq!(
completions.name_range.start_offset,
after(source, "ns::"),
"the empty range sits just past the `::`, where the name goes"
);
assert_eq!(completions.name_range.length, 0);
}
#[test]
fn a_half_typed_name_keeps_the_prefix_and_replaces_the_whole_segment() {
let source = "namespace ns {\n struct Widget { };\n}\nvoid f() {\n ns::Wid\n}\n";
let Known::Yes(completions) = names_at(&[], "/p/a.cpp", source, "ns::Wid") else {
panic!("the cursor is on the name being typed");
};
assert_eq!(completions.scope, "ns");
assert_eq!(completions.prefix, "Wid");
assert_eq!(
completions.name_range.start_offset,
at(source, "Wid"),
"the range is the written segment, not the point"
);
assert_eq!(completions.name_range.length, 3);
}
#[test]
fn a_class_scope_offers_its_members_and_the_ones_its_bases_declare() {
let source = "struct Base {\n typedef int size_type;\n};\n\
struct Derived : Base {\n typedef int value_type;\n};\n\
void f() {\n Derived::\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "Derived::");
assert_eq!(
offered(&found),
["value_type", "size_type"],
"the class's own names first, then the ones a base declares"
);
let Known::Yes(completions) = found else {
unreachable!("asserted above")
};
assert_eq!(completions.scope, "Derived");
assert_eq!(
completions
.names
.iter()
.map(|name| name.depth)
.collect::<Vec<_>>(),
[0, 1],
"the base's name is one step further out, which is the order lookup walks in"
);
}
#[test]
fn a_global_scope_offers_only_what_is_declared_at_file_scope() {
let source =
"int global;\nnamespace ns {\n int inner;\n}\nvoid f() {\n int local;\n ::\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "::");
assert_eq!(offered(&found), ["f", "global", "ns"]);
let Known::Yes(completions) = found else {
unreachable!("asserted above")
};
assert_eq!(completions.scope, "::", "the global name space, as spelled");
let names = offered(&Known::Yes(completions.clone()));
assert!(
!names.contains(&"inner".to_string()) && !names.contains(&"local".to_string()),
"a namespace member and a local are not in the global name space: {names:?}"
);
}
#[test]
fn a_bare_name_offers_the_scopes_the_cursor_is_inside_innermost_first() {
let source = "int at_file_scope;\nnamespace ns {\n int in_a_namespace;\n struct C {\n int member;\n \
void g() {\n int local;\n loc\n }\n };\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "loc");
assert_eq!(
offered(&found),
[
"local",
"g",
"member",
"C",
"in_a_namespace",
"at_file_scope",
"ns"
]
);
let Known::Yes(completions) = found else {
unreachable!("asserted above")
};
assert_eq!(completions.scope, "", "no qualifier was written");
assert_eq!(completions.prefix, "loc");
let depths: Vec<usize> = completions.names.iter().map(|name| name.depth).collect();
let mut sorted = depths.clone();
sorted.sort_unstable();
assert_eq!(depths, sorted, "nearer scopes come first");
assert_eq!(depths[0], 0, "the local is in the scope the cursor is in");
}
#[test]
fn another_files_local_is_not_offered_by_a_bare_name() {
let header = "/p/widget.h";
let declaration = "void g() {\n int __first = 0;\n int helper;\n}\nint global_name;\n";
let source = "#include \"widget.h\"\nvoid f() {\n int mine;\n min\n}\n";
let found = names_at(&[(header, declaration)], "/p/main.cpp", source, "min");
let names = offered(&found);
assert!(
names.contains(&"mine".to_string()),
"the local of *this* file is offered, from its own scopes: {names:?}"
);
assert!(
!names.contains(&"__first".to_string()) && !names.contains(&"helper".to_string()),
"another file's locals are not names this file can write: {names:?}"
);
let at_a_blank = names_at_blank(&[(header, declaration)], "/p/main.cpp", source);
let names = offered(&at_a_blank);
assert!(
names.contains(&"global_name".to_string()),
"…while a file-scope name in the same header is offered where nothing is typed: {names:?}"
);
}
#[test]
fn a_namespace_is_merged_across_the_buffer_and_the_header() {
let source =
"#include \"ns.h\"\nnamespace ns {\n int in_the_buffer;\n}\nvoid f() {\n ns::\n}\n";
let found = names_at(
&[("/p/ns.h", "namespace ns {\n int in_the_header;\n}\n")],
"/p/main.cpp",
source,
"ns::",
);
assert_eq!(offered(&found), ["in_the_buffer", "in_the_header"]);
}
#[test]
fn a_scope_nothing_declares_is_not_an_empty_list() {
let source = "void f() {\n nowhere::\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "nowhere::");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"nothing declares `nowhere`: {found:?}"
);
}
#[test]
fn a_cursor_where_a_name_can_be_written_offers_the_visible_names() {
let source = "struct Widget { int size; };\nvoid f() {\n Widget w;\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "Widget");
let Known::Yes(found) = found else {
panic!("a name can be written here: {found:?}");
};
let names: Vec<&str> = found
.names
.iter()
.map(|offered| offered.fact.name.as_str())
.collect();
assert!(
names.contains(&"Widget") && names.contains(&"f"),
"the names in scope: {names:?}"
);
assert_eq!(found.prefix, "Widget", "what is written filters the list");
assert_eq!(
found.name_range.length,
"Widget".len(),
"and the chosen name replaces it rather than being inserted beside it"
);
}
fn line_of(source: &str, offset: usize) -> usize {
source[..offset].matches('\n').count()
}
#[test]
fn a_macro_defined_above_its_use_resolves_to_the_define() {
let source = "#define MAX 1\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
let Known::Yes(found) = found else {
panic!("the define above the use is the answer: {found:?}");
};
assert_eq!(found.file, Path::new("/p/a.cpp"));
assert_eq!(found.fact.name, "MAX");
assert!(found.fact.kind.is_definition());
assert_eq!(
&source[found.fact.range.start_offset..found.fact.range.end_offset()],
"MAX",
"and the range is the name a user would be sent to"
);
}
#[test]
fn a_macro_defined_below_its_use_is_not_in_force_yet() {
let source = "int x = MAX;\n#define MAX 1\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"nothing above the use defines it: {found:?}"
);
}
#[test]
fn a_macro_in_an_included_header_resolves_into_that_header() {
let source = "#include \"config.h\"\nint x = FEATURE;\n";
let header = "#define FEATURE 1\n";
let (index, tree) = analysed(&[("/p/config.h", header)], "/p/main.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
let Known::Yes(found) = found else {
panic!("the header's define must be found: {found:?}");
};
assert_eq!(found.file, Path::new("/p/config.h"));
assert_eq!(line_of(header, found.fact.range.start_offset), 0);
}
#[test]
fn a_header_included_after_the_use_does_not_define_it_yet() {
let source = "int x = FEATURE;\n#include \"config.h\"\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"the include is below the use: {found:?}"
);
}
#[test]
fn the_later_of_two_headers_that_define_it_wins() {
let source = "#include \"one.h\"\n#include \"two.h\"\nint x = FLAG;\n";
let one = "#define FLAG 1\n";
let two = "#define FLAG 2\n";
let (index, tree) = analysed(
&[("/p/one.h", one), ("/p/two.h", two)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "FLAG;"));
let Known::Yes(found) = found else {
panic!("the last define gone past is the answer: {found:?}");
};
assert_eq!(found.file, Path::new("/p/two.h"));
}
#[test]
fn swapping_the_two_includes_swaps_the_answer() {
let source = "#include \"two.h\"\n#include \"one.h\"\nint x = FLAG;\n";
let one = "#define FLAG 1\n";
let two = "#define FLAG 2\n";
let (index, tree) = analysed(
&[("/p/one.h", one), ("/p/two.h", two)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "FLAG;"));
let Known::Yes(found) = found else {
panic!("order is the whole answer: {found:?}");
};
assert_eq!(found.file, Path::new("/p/one.h"));
}
#[test]
fn a_local_define_after_an_include_wins_over_the_header() {
let source = "#include \"config.h\"\n#define FEATURE 2\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
let Known::Yes(found) = found else {
panic!("the file's own later define is what is in force: {found:?}");
};
assert_eq!(found.file, Path::new("/p/main.cpp"));
}
#[test]
fn a_local_define_before_an_include_loses_to_the_header() {
let source = "#define FEATURE 2\n#include \"config.h\"\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
let Known::Yes(found) = found else {
panic!("the header was pasted after the local define: {found:?}");
};
assert_eq!(found.file, Path::new("/p/config.h"));
}
#[test]
fn a_nested_include_is_reached() {
let source = "#include \"middle.h\"\nint x = DEEP;\n";
let (index, tree) = analysed(
&[
("/p/middle.h", "#include \"leaf.h\"\n"),
("/p/leaf.h", "#define DEEP 1\n"),
],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "DEEP;"));
let Known::Yes(found) = found else {
panic!("a define two includes down is still in force: {found:?}");
};
assert_eq!(found.file, Path::new("/p/leaf.h"));
}
#[test]
fn an_undef_of_a_local_define_leaves_an_ordinary_identifier() {
let source = "#define MAX 1\n#undef MAX\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
assert!(
matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
"an `#undef` above the use settles it: {found:?}"
);
}
#[test]
fn an_undef_of_a_headers_define_also_counts() {
let source = "#include \"config.h\"\n#undef FEATURE\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
"the header's define is ended by the file's own `#undef`: {found:?}"
);
}
#[test]
fn a_define_after_an_undef_is_in_force_again() {
let source = "#define MAX 1\n#undef MAX\n#define MAX 2\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
let Known::Yes(found) = found else {
panic!("the last fact is a define: {found:?}");
};
assert_eq!(line_of(source, found.fact.range.start_offset), 2);
}
#[test]
fn a_define_inside_a_conditional_is_unknown_rather_than_guessed() {
let source = "#if defined(USE_MAX)\n#define MAX 1\n#endif\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
assert!(
matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
"whether that branch was taken is not knowable here: {found:?}"
);
}
#[test]
fn an_unconditional_define_beats_a_guarded_one_after_it() {
let source = "#define MAX 1\n#if defined(OTHER)\n#define MAX 3\n#endif\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
let Known::Yes(found) = found else {
panic!("the unconditional define is what is certain: {found:?}");
};
assert_eq!(line_of(source, found.fact.range.start_offset), 0);
}
#[test]
fn a_guarded_include_makes_the_answer_conditional() {
let source = "#if defined(USE_CONFIG)\n#include \"config.h\"\n#endif\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
"the only path to the define goes through an `#if`: {found:?}"
);
}
#[test]
fn a_name_no_one_defines_is_not_declared_here() {
let source = "int x = NOT_A_MACRO;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/a.cpp"),
at(source, "NOT_A_MACRO;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"the index is a subset of the translation unit, so this is not a definite no: {found:?}"
);
}
#[test]
fn a_cursor_that_is_not_on_a_name_has_nothing_to_look_up() {
let source = "#define MAX 1\nint x = MAX + 1;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "+ 1;"));
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"the cursor is on an operator: {found:?}"
);
}
#[test]
fn a_cycle_of_includes_terminates() {
let source = "#include \"a.h\"\nint x = SHARED;\n";
let (index, tree) = analysed(
&[
("/p/a.h", "#include \"b.h\"\n#define SHARED 1\n"),
("/p/b.h", "#include \"a.h\"\n"),
],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "SHARED;"),
);
let Known::Yes(found) = found else {
panic!("a cycle must not stop the define being found: {found:?}");
};
assert_eq!(found.file, Path::new("/p/a.h"));
}
#[test]
fn an_undef_in_a_header_is_reached_like_a_define() {
let source = "#include \"config.h\"\n#include \"cleanup.h\"\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[
("/p/config.h", "#define FEATURE 1\n"),
("/p/cleanup.h", "#undef FEATURE\n"),
],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
"the later header undefines it: {found:?}"
);
}
}
#[cfg(test)]
mod name_index_agrees_with_the_scan {
use super::*;
use crate::cache::SummaryKey;
use crate::index::summarize;
const WORDS: [&str; 6] = ["Widget", "size", "run", "Gadget", "count", "widest"];
struct Lcg(u64);
impl Lcg {
fn next(&mut self, below: usize) -> usize {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((self.0 >> 33) as usize) % below
}
}
fn source_of(number: usize, generator: &mut Lcg) -> String {
let mut text = String::new();
for _ in 0..generator.next(3) {
text.push_str(&format!(
"#include \"f{}.h\"\n",
generator.next(number.max(1))
));
}
text.push_str(&format!("#define DECL{number}(n) struct n {{ int v; }};\n"));
text.push_str(&format!("DECL{number}(Made{})\n", generator.next(4)));
text.push_str(&format!("namespace ns{} {{\n", generator.next(3)));
for _ in 0..1 + generator.next(3) {
let class = WORDS[generator.next(WORDS.len())];
let member = WORDS[generator.next(WORDS.len())];
text.push_str(&format!(
"struct {class} {{ int {member}; void {member}2(); }};\n"
));
}
text.push_str("}\n");
text.push_str(&format!("int {};\n", WORDS[generator.next(WORDS.len())]));
text.push_str(&format!(
"void fn{number}() {{ int {}; }}\n",
WORDS[generator.next(WORDS.len())]
));
text
}
fn file(index: &mut ProjectIndex, number: usize, source: &str) {
let path = format!("/p/f{number}.h");
let mut summary = summarize(Path::new(&path), source, SummaryKey::new(number as u64, 0));
for include in &mut summary.includes {
include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(summary);
}
fn cook(index: &mut ProjectIndex, number: usize, source: &str) {
let path = format!("/p/f{number}.h");
let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
let rendered = crate::preprocess::cooked::cook(source, &tokens).render();
let provider = crate::MemoryFiles::new();
let config = crate::CompilerConfig::default();
let indexed = crate::FileIndexer::new(&provider, &config).index_rendering(
Path::new(&path),
&rendered,
SummaryKey::new(number as u64, 0),
);
index.insert_cooked(Path::new(&path), indexed.into());
}
type Row = (PathBuf, String, Option<String>, usize, IncludeVisibility);
fn row(file: &Path, fact: &DeclFact, visibility: IncludeVisibility) -> Row {
(
file.to_path_buf(),
fact.name.clone(),
fact.scope.clone(),
fact.range.start_offset,
visibility,
)
}
fn scanned(index: &ProjectIndex, from: &Path, accepts: impl Fn(&DeclFact) -> bool) -> Vec<Row> {
let visible: HashMap<String, IncludeVisibility> =
index.visible_files(from).into_iter().collect();
let mut rows = Vec::new();
for summary in index.summaries() {
let Some(visibility) = visible.get(&normalize(&summary.path)).copied() else {
continue;
};
let raw: Vec<&DeclFact> = summary
.declarations
.iter()
.filter(|fact| accepts(fact))
.collect();
rows.extend(raw.iter().map(|fact| row(&summary.path, fact, visibility)));
for fact in index
.cooked_declarations(&summary.path)
.into_iter()
.flatten()
.filter(|fact| accepts(fact))
{
if !raw
.iter()
.any(|known| known.name == fact.name && known.kind == fact.kind)
{
rows.push(row(&summary.path, fact, visibility));
}
}
}
rows
}
fn rows(found: &[VisibleDeclaration<'_>]) -> Vec<Row> {
found
.iter()
.map(|found| row(&found.file, found.fact, found.visibility))
.collect()
}
fn symbols_by_scanning(
index: &ProjectIndex,
query: &str,
limit: usize,
) -> Vec<(PathBuf, String, Option<String>, usize)> {
let wanted = query.trim().to_lowercase();
let mut matches: Vec<(usize, String, String, PathBuf, &DeclFact)> = Vec::new();
for summary in index.summaries() {
let raw: Vec<&DeclFact> = summary
.declarations
.iter()
.filter(|fact| !fact.local)
.collect();
let fresh: Vec<&DeclFact> = index
.cooked_declarations(&summary.path)
.into_iter()
.flatten()
.filter(|fact| {
!fact.local
&& !raw
.iter()
.any(|known| known.name == fact.name && known.kind == fact.kind)
})
.collect();
for fact in raw.into_iter().chain(fresh) {
let qualified = fact.qualified_name();
let Some(rank) = rank_of(&qualified, &fact.name, &wanted) else {
continue;
};
let qualified = qualified.to_lowercase();
let name = match fact.name.is_empty() {
false => fact.name.to_lowercase(),
true => qualified
.rsplit("::")
.next()
.unwrap_or_default()
.to_string(),
};
matches.push((rank, name, qualified, summary.path.clone(), fact));
}
}
matches.sort_by(|one, two| {
one.0
.cmp(&two.0)
.then_with(|| one.1.cmp(&two.1))
.then_with(|| one.2.cmp(&two.2))
.then_with(|| one.3.cmp(&two.3))
});
matches
.into_iter()
.take(limit)
.map(|(_, _, _, file, fact)| {
(
file,
fact.name.clone(),
fact.scope.clone(),
fact.range.start_offset,
)
})
.collect()
}
fn check(index: &ProjectIndex, files: usize, step: &str) {
let asked_from: Vec<PathBuf> = (0..files)
.step_by(3)
.map(|n| PathBuf::from(format!("/p/f{n}.h")))
.collect();
for from in &asked_from {
for word in WORDS.iter().copied().chain([
"Made0",
"Made3",
"nothing",
"ns0::Widget",
"::size",
"ns1::Gadget",
]) {
assert_eq!(
rows(&index.files_declaring(word, from)),
scanned(index, from, |fact| matches(fact, word)),
"{step}: files_declaring({word:?}) from {from:?}"
);
}
for scope in [
"ns0",
"ns1",
"ns2",
"ns0::Widget",
"ns1::Gadget",
"ns2::size",
"nowhere",
] {
assert_eq!(
rows(&index.declarations_in(scope, from)),
scanned(index, from, |fact| fact.scope.as_deref() == Some(scope)),
"{step}: declarations_in({scope:?}) from {from:?}"
);
}
}
for query in [
"w",
"wid",
"Widget",
"size",
"ma",
"made",
"run2",
"ns0::wid",
"ns1::Gadget::si",
"Widget::",
"::widget",
"ns0::",
"zzz",
" count ",
"e",
] {
for limit in [1, 4, 1000] {
let found: Vec<_> = index
.symbols_matching(query, limit)
.into_iter()
.map(|symbol| {
(
symbol.file,
symbol.fact.name,
symbol.fact.scope,
symbol.fact.range.start_offset,
)
})
.collect();
assert_eq!(
found,
symbols_by_scanning(index, query, limit),
"{step}: symbols_matching({query:?}, {limit})"
);
}
}
let defining: Vec<PathBuf> = index
.summaries()
.filter(|summary| {
summary
.macros
.iter()
.any(|fact| fact.name == "DECL3" && fact.kind.is_definition())
})
.map(|summary| summary.path.clone())
.collect();
assert_eq!(
index.files_defining_macro("DECL3"),
defining,
"{step}: files_defining_macro"
);
}
#[test]
fn a_name_declared_everywhere_answers_the_first_hits_in_file_order() {
let mut index = ProjectIndex::new();
for number in 0..POPULAR_NAME + 50 {
file(
&mut index,
number,
&format!("struct C{number} {{ void run(); }};\n"),
);
}
let found = index.symbols_matching("run", 10);
assert_eq!(found.len(), 10);
assert_eq!(
found,
index.symbols_matching("run", 10),
"the same answer twice"
);
assert!(
found.iter().all(|symbol| {
let number: usize = symbol.file.to_string_lossy()[4..]
.trim_end_matches(".h")
.parse()
.unwrap();
number < 10
}),
"the cut takes the files in the order the index saw them: {found:?}"
);
}
#[test]
fn after_every_kind_of_edit() {
const FILES: usize = 24;
let mut generator = Lcg(7);
let mut sources: Vec<String> = Vec::new();
let mut index = ProjectIndex::new();
for number in 0..FILES {
sources.push(source_of(number, &mut generator));
file(&mut index, number, &sources[number]);
}
check(&index, FILES, "after building");
for number in (0..FILES).step_by(2) {
cook(&mut index, number, &sources[number]);
}
check(&index, FILES, "after cooking half of them");
assert!(
index.symbols_matching("widget", 1000).len() > 10,
"one name, many files and scopes"
);
assert!(
index
.symbols_matching("made", 1000)
.iter()
.any(|symbol| symbol.fact.name.starts_with("Made")),
"a name only the cooked reading declares"
);
assert!(
!index
.declarations_in("ns0", Path::new("/p/f21.h"))
.is_empty()
);
for number in [3, 4, 11] {
index.forget(Path::new(&format!("/p/f{number}.h")));
sources[number] = source_of(number + 100, &mut generator);
file(&mut index, number, &sources[number]);
}
check(&index, FILES, "after forgetting and re-reading three files");
let path = Path::new("/p/f6.h");
sources[6].push_str(
"int rekeyed;
",
);
let mut summary = summarize(path, &sources[6], SummaryKey::new(999, 0));
for include in &mut summary.includes {
include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(summary);
assert!(
index.cooked_declarations(path).is_none(),
"the reading described a different key"
);
check(&index, FILES, "after a re-key");
for number in [0, 2, 8] {
index.forget_cooked(Path::new(&format!("/p/f{number}.h")));
}
check(&index, FILES, "after forgetting three readings");
cook(&mut index, 8, &sources[8]);
cook(&mut index, 8, &sources[8]);
check(&index, FILES, "after cooking one twice");
for number in 0..FILES {
index.forget(Path::new(&format!("/p/f{number}.h")));
}
assert_eq!(
index.distinct_names(),
0,
"an index with no files has no names"
);
assert!(index.symbols_matching("w", 10).is_empty());
}
}
fn substituted_at_the_use(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
named: &NamedDeclaration,
type_of: Type,
) -> Type {
let arguments = written_template_arguments(expression);
if arguments.is_empty() {
return type_of;
}
let (names, _) = named.parameters_of(index, scopes, root, path);
if names.is_empty() {
return type_of;
}
let written_defaults = named.parameter_defaults_of(index, root);
let written_arguments: Vec<Type> = arguments.clone();
let mut defaults: Vec<Type> = Vec::with_capacity(written_defaults.len());
for default in &written_defaults {
if default.trim().is_empty() {
defaults.push(Type::builtin(""));
continue;
}
let parsed = parse_type_spelling(default);
defaults.push(
parsed.substituted(&crate::sema::types::TypeSubstitutions::new(
&names,
&written_arguments,
)),
);
}
let substitutions =
crate::sema::types::TypeSubstitutions::with_defaults(&names, &written_arguments, &defaults);
type_of.substituted(&substitutions)
}
fn folded_for_matching(argument: &str) -> String {
crate::sema::builtins::folded(argument)
}
fn the_alias_behind(
index: &ProjectIndex,
declaring: &Path,
written: &str,
) -> Option<(String, String)> {
let (head, rest) = written.split_once('<')?;
let inside = rest.trim_end().strip_suffix('>')?;
let Known::Yes(found) = index.definition(head.trim(), declaring) else {
return None;
};
if found.fact.kind != crate::DeclKind::Type {
return None;
}
let target = found.fact.type_of.as_deref()?;
let arguments = crate::sema::builtins::split_arguments(inside);
let substituted =
crate::sema::types::substituted_spelling(target, &found.fact.parameters, &arguments);
let substituted = substituted
.trim()
.trim_start_matches("typename ")
.trim()
.trim_start_matches("class ")
.trim();
let (named, member) = substituted.rsplit_once("::")?;
Some((named.trim().to_string(), member.trim().to_string()))
}
pub fn substituted_members(
index: &ProjectIndex,
from: &Path,
class: &str,
listed: Known<MemberList>,
) -> Known<MemberList> {
let Known::Yes(mut list) = listed else {
return listed;
};
let Some((base, arguments)) = split_template_arguments(class) else {
return Known::Yes(list);
};
let Some(declared) = index
.files_declaring(&base, from)
.into_iter()
.find(|declared| declared.fact.kind == crate::DeclKind::Type)
else {
return Known::Yes(list);
};
let mut names = declared.fact.parameters.clone();
if names.is_empty() {
return Known::Yes(list);
}
let mut arguments = arguments;
names.truncate(arguments.len());
arguments.truncate(names.len());
if names.is_empty() {
return Known::Yes(list);
}
let mut alias_names: Vec<String> = Vec::new();
let mut alias_targets: Vec<String> = Vec::new();
for member in list
.members
.iter()
.filter(|member| member.depth == 0 && member.fact.kind == crate::DeclKind::Type)
{
let Some(target) = member.fact.type_of.clone() else {
continue;
};
if target == member.fact.name {
continue;
}
alias_names.push(member.fact.name.clone());
alias_targets.push(target);
}
let declares_an_alias = |member: &ProjectMember| {
member.fact.kind == crate::DeclKind::Type && alias_names.contains(&member.fact.name)
};
for member in list
.members
.iter_mut()
.filter(|member| !declares_an_alias(member))
{
for spelling in [
&mut member.fact.parameter_list,
&mut member.fact.returns,
&mut member.fact.type_of,
]
.into_iter()
.flatten()
{
if !alias_names.is_empty() {
*spelling = crate::sema::types::substituted_spelling(
spelling,
&alias_names,
&alias_targets,
);
}
}
}
for member in &mut list.members {
for spelling in [
&mut member.fact.parameter_list,
&mut member.fact.returns,
&mut member.fact.type_of,
]
.into_iter()
.flatten()
{
*spelling = crate::sema::types::substituted_spelling(spelling, &names, &arguments);
}
}
Known::Yes(list)
}
fn split_template_arguments(spelling: &str) -> Option<(String, Vec<String>)> {
let spelling = spelling.trim();
let open = spelling.find('<')?;
let close = spelling.rfind('>')?;
if close < open || close + 1 != spelling.len() {
return None;
}
let base = spelling[..open].trim().to_string();
let mut arguments: Vec<String> = Vec::new();
let mut depth = 0i32;
let mut current = String::new();
for character in spelling[open + 1..close].chars() {
match character {
'<' | '(' | '[' => depth += 1,
'>' | ')' | ']' => depth -= 1,
',' if depth == 0 => {
arguments.push(current.trim().to_string());
current.clear();
continue;
}
_ => {}
}
current.push(character);
}
if !current.trim().is_empty() {
arguments.push(current.trim().to_string());
}
Some((base, arguments))
}
fn the_class_a_definition_belongs_to(
root: &cpp_parser::CppSyntaxNode,
offset: usize,
) -> Option<String> {
use cpp_parser::CppAstNode;
for declaration in root.descendants() {
let range = declaration.text_range();
if usize::from(range.start()) > offset || offset >= usize::from(range.end()) {
continue;
}
let Some(declaration) = cpp_parser::CppDeclaration::cast(declaration.clone()) else {
continue;
};
let Some((qualifier, _)) =
crate::sema::scopes::the_qualified_name_of_a_declaration(declaration.syntax())
else {
continue;
};
let before = qualifier.trim_end();
let start = before
.rfind(|character: char| {
!(character.is_alphanumeric() || matches!(character, '_' | ':'))
})
.map(|boundary| boundary + 1)
.unwrap_or(0);
let class = before[start..].trim();
if !class.is_empty() && !class.contains("::") {
return Some(class.to_string());
}
}
None
}
fn without_the_namespace(class: &str) -> String {
let mut depth = 0usize;
let mut boundary = 0usize;
let bytes = class.as_bytes();
let mut index = 0usize;
while index + 1 < bytes.len() {
match bytes[index] {
b'<' => depth += 1,
b'>' => depth = depth.saturating_sub(1),
b':' if depth == 0 && bytes[index + 1] == b':' => boundary = index + 2,
_ => {}
}
index += 1;
}
class[boundary.min(class.len())..].to_string()
}
fn is_a_parameter_name(name: &str) -> bool {
!name.is_empty()
&& !matches!(
name,
"class" | "typename" | "struct" | "union" | "enum" | "concept"
)
&& name
.chars()
.all(|character| character.is_alphanumeric() || character == '_')
}
fn lists_usable_parameter_names(names: &[String]) -> bool {
!names.is_empty()
&& names.iter().any(|name| !name.is_empty())
&& names
.iter()
.all(|name| name.is_empty() || is_a_parameter_name(name))
}
fn an_element_type_through_the_members(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
parameters: &[String],
arguments: &[String],
depth: usize,
) -> Option<String> {
if depth > 3 {
return None;
}
let Known::Yes(members) = members_of(index, scopes, root, path, class) else {
if crate::probes::inference() {
eprintln!("[inference] element_type: no member list for {class}");
}
return None;
};
for name in ["element_type", "value_type"] {
let Some(fact) = members
.members
.iter()
.filter(|member| member.fact.name == name)
.map(|member| &member.fact)
.find(|fact| fact.type_of.is_some())
else {
continue;
};
let Some(written) = fact.type_of.as_deref() else {
continue;
};
let substituted = crate::sema::types::substituted_spelling(written, parameters, arguments);
let target = base_type_name(&substituted).to_string();
if crate::probes::inference() {
eprintln!(
"[inference] element_type: {class}::{name} wrote {written:?} -> {substituted:?} -> {target:?}"
);
}
if !target.is_empty()
&& !parameters.iter().any(|parameter| parameter == &target)
&& target != base_type_name(class)
{
return Some(target);
}
}
for member in &members.members {
if member.fact.kind != crate::DeclKind::Type {
continue;
}
let Some(target) = member.fact.type_of.as_deref() else {
continue;
};
if base_type_name(target) == base_type_name(class) {
continue;
}
let bare_target = without_arguments(target.trim()).to_string();
let qualified = resolved_in_the_enclosing_scopes(index, scopes, path, class, &bare_target);
let qualified = resolve_aliases(index, scopes, root, path, &qualified);
if let Some(found) = an_element_type_through_the_members(
index,
scopes,
root,
path,
&qualified,
parameters,
arguments,
depth + 1,
) {
return Some(found);
}
}
for base in bases_of(index, scopes, root, path, class)
.value()
.unwrap_or_default()
{
let base = resolved_in_the_enclosing_scopes(index, scopes, path, class, base.trim());
let base = resolve_aliases(index, scopes, root, path, &base);
if let Some(found) = an_element_type_through_the_members(
index,
scopes,
root,
path,
&base,
parameters,
arguments,
depth + 1,
) {
return Some(found);
}
}
None
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct TableCost {
pub names: crate::index::names::NameIndexCost,
pub edges: usize,
pub edge_bytes: usize,
pub member_list_entries: usize,
pub member_lists: usize,
pub member_list_bytes: usize,
pub guard_entries: usize,
pub guard_bytes: usize,
pub visibility_entries: usize,
pub visibility_bytes: usize,
pub condition_entries: usize,
pub condition_bytes: usize,
pub path_bytes: usize,
}
impl TableCost {
pub fn total(&self) -> usize {
self.names.bytes
+ self.edge_bytes
+ self.member_list_bytes
+ self.guard_bytes
+ self.visibility_bytes
+ self.condition_bytes
+ self.path_bytes
}
}