use std::collections::{HashMap, HashSet};
use std::path::Path;
use cpp_parser::{CppTokenKind, SourceRange};
use crate::index::project::IndexedKind;
use crate::preprocess::directive::Directive;
use crate::sema::resolve::definition_at;
use crate::sema::symbol::{Binding, BindingKind, Known, ScopeId, ScopeKind, ScopeTree};
use cpp_parser::CppAstNode;
use crate::{DeclKind, FileView, ProjectIndex};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NameKind {
Namespace,
Type,
TypeParameter,
EnumMember,
Function,
Method,
Variable,
Property,
VariableTemplate,
Parameter,
Macro,
Keyword,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Provenance {
DeclaredHere,
Held,
Found,
Macro,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Name {
pub range: SourceRange,
pub kind: NameKind,
pub declaration: bool,
pub modifiers: Vec<NameModifier>,
pub provenance: Provenance,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NameModifier {
ReadOnly,
Static,
Deprecated,
}
pub fn classified_names(index: &ProjectIndex, view: &FileView) -> Vec<Name> {
let shapes: crate::sema::declarations::ShapeTable =
crate::sema::declarations::ShapeTable::new();
let types = crate::index::project::TypeMemo::default();
let declared = declarations_by_offset(view);
let parameters = parameter_offsets(view);
let macros = macro_names(view);
let invoked: std::collections::HashSet<usize> = {
let mut invoked = std::collections::HashSet::new();
let mut previous: Option<(usize, CppTokenKind)> = None;
for token in view.tree.get_tokens() {
if cpp_parser::is_trivia(token.kind) {
continue;
}
if token.kind == CppTokenKind::LeftParen
&& let Some((start, kind)) = previous
&& kind == CppTokenKind::Identifier
{
invoked.insert(start);
}
previous = Some((token.range.start_offset, token.kind));
}
invoked
};
let defined = definitions_of(view);
let members = member_kinds(index, view, &types, &shapes);
let qualified = qualified_names(view);
let mut held: HashMap<(&str, usize), Option<NameKind>> = HashMap::new();
let included_macros: std::cell::OnceCell<std::collections::HashSet<String>> =
std::cell::OnceCell::new();
let mut asked: HashMap<String, Option<NameKind>> = HashMap::new();
let mut out: Vec<Name> = Vec::new();
let qualified_heads: std::collections::HashSet<usize> = view
.root
.descendants()
.filter_map(cpp_parser::CppNameExpr::cast)
.flat_map(|name| {
let tokens: Vec<_> = name
.syntax()
.children_with_tokens()
.filter_map(|element| element.into_token())
.collect();
let mut heads = Vec::new();
for pair in tokens.windows(2) {
if pair[0].kind() == cpp_parser::CppTokenKind::Identifier.into()
&& pair[1].text() == "::"
{
heads.push(usize::from(pair[0].text_range().start()));
}
}
heads
})
.collect();
for token in view.tree.get_tokens() {
if token.kind != CppTokenKind::Identifier {
continue;
}
let range = token.range;
let Some(text) = view.get_token_text(range) else {
continue;
};
let at = range.start_offset;
let is_an_invoked_macro = invoked.contains(&at) && macros.contains_key(text);
if let Some(binding) = declared.get(&at)
&& !is_an_invoked_macro
&& let Some(kind) = kind_of_binding(
index,
binding,
view,
parameters.contains(&binding.name_range.start_offset),
&shapes,
)
{
out.push(Name {
range,
kind,
declaration: true,
modifiers: modifiers_of(view, at, kind, &shapes),
provenance: Provenance::DeclaredHere,
});
continue;
}
if let Some(define) = macros.get(text) {
out.push(Name {
range,
kind: NameKind::Macro,
declaration: define.start_offset == at,
modifiers: Vec::new(),
provenance: Provenance::Macro,
});
continue;
}
if let Some(kind) = members.get(&at) {
out.push(Name {
range,
kind: *kind,
declaration: false,
modifiers: modifiers_of(view, at, *kind, &shapes),
provenance: Provenance::Found,
});
continue;
}
let opens_a_qualified_name = qualified_heads.contains(&at);
let declared_here = !opens_a_qualified_name && defined.contains(text);
if declared_here {
let scope = view.scopes.scope_at(at).map_or(usize::MAX, |id| id.index());
let resolved = *held
.entry((text, scope))
.or_insert_with(|| match held_at(view, at) {
Held::InThisFile(binding) => kind_of_binding(
index,
&binding,
view,
parameters.contains(&binding.name_range.start_offset),
&shapes,
),
Held::NotHere => None,
});
if let Some(kind) = resolved {
out.push(Name {
range,
kind,
declaration: false,
modifiers: Vec::new(),
provenance: Provenance::Held,
});
continue;
}
}
if opens_a_qualified_name
&& defined.contains(text)
&& let Held::InThisFile(binding) = held_at(view, at)
&& matches!(
binding.kind,
BindingKind::Class
| BindingKind::Enum
| BindingKind::Alias
| BindingKind::Typedef
| BindingKind::Namespace
| BindingKind::TemplateParameter
)
&& let Some(kind) = kind_of_binding(index, &binding, view, false, &shapes)
{
out.push(Name {
range,
kind,
declaration: false,
modifiers: Vec::new(),
provenance: Provenance::Held,
});
continue;
}
let included = included_macros.get_or_init(|| index.macro_names_in_force(&view.path));
if included.contains(text) {
out.push(Name {
range,
kind: NameKind::Macro,
declaration: false,
modifiers: Vec::new(),
provenance: Provenance::Macro,
});
continue;
}
let written = qualified
.get(&at)
.cloned()
.unwrap_or_else(|| text.to_string());
let answer = asked.entry(written.clone()).or_insert_with(|| {
index
.kind_of(&written, &view.path)
.value()
.and_then(kind_of_index)
});
if let Some(kind) = answer {
out.push(Name {
range,
kind: *kind,
declaration: false,
modifiers: Vec::new(),
provenance: Provenance::Found,
});
}
}
out
}
fn declarations_by_offset(view: &FileView) -> HashMap<usize, &Binding> {
let mut map = HashMap::new();
for scope in view.scopes.scopes() {
for binding in &scope.bindings {
map.insert(binding.name_range.start_offset, binding);
}
}
map
}
enum Held {
InThisFile(Binding),
NotHere,
}
fn definitions_of(view: &FileView) -> HashSet<&str> {
view.scopes
.scopes()
.iter()
.flat_map(|scope| scope.bindings.iter())
.filter_map(|binding| binding.name.identifier_text())
.collect()
}
fn modifiers_of(
view: &FileView,
name_at: usize,
kind: NameKind,
shapes: &std::cell::OnceCell<crate::sema::declarations::DeclarationShapes>,
) -> Vec<NameModifier> {
if !matches!(
kind,
NameKind::Variable | NameKind::Parameter | NameKind::Method | NameKind::Function
) {
return Vec::new();
}
let shapes =
shapes.get_or_init(|| crate::sema::declarations::DeclarationShapes::of(&view.root));
let Some(specifiers) = shapes.specifiers_at(name_at) else {
return Vec::new();
};
let written = specifiers.text().to_string();
let words: Vec<&str> = written
.split(|character: char| !character.is_alphanumeric() && character != '_')
.filter(|word| !word.is_empty())
.collect();
let mut out = Vec::new();
if words
.iter()
.any(|word| matches!(*word, "const" | "constexpr" | "consteval"))
{
out.push(NameModifier::ReadOnly);
}
if words.contains(&"static") {
out.push(NameModifier::Static);
}
if written.contains("deprecated") {
out.push(NameModifier::Deprecated);
}
out
}
fn member_kinds(
index: &ProjectIndex,
view: &FileView,
memo: &crate::index::project::TypeMemo,
shapes: &crate::sema::declarations::ShapeTable,
) -> HashMap<usize, NameKind> {
fn writes_the_operator(node: &cpp_parser::CppSyntaxNode) -> bool {
node.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| matches!(token.text(), "." | "->"))
}
let mut kinds = HashMap::new();
for node in view.root.descendants().filter(|node| {
matches!(
cpp_parser::CppSyntaxKind::from(node.kind()),
cpp_parser::CppSyntaxKind::MemberExpr
| cpp_parser::CppSyntaxKind::ArrowExpr
| cpp_parser::CppSyntaxKind::IndexExpr
)
}) {
if !writes_the_operator(&node) {
continue;
}
let Some(access) = crate::sema::resolve::member_access_of(&node) else {
continue;
};
if access.member_range.length == 0 {
continue;
}
let found = crate::index::project::member_across_files_with(
memo,
shapes,
index,
&mut |_: &Path| None,
&view.scopes,
&view.root,
&view.path,
access.member_range.start_offset,
);
let Known::Yes(found) = found else {
continue;
};
let kind = match found.fact.kind {
DeclKind::Function if found.fact.scope.is_some() => NameKind::Method,
DeclKind::Function => NameKind::Function,
DeclKind::Variable if found.fact.scope.is_some() => NameKind::Property,
DeclKind::Variable => NameKind::Variable,
DeclKind::Type => NameKind::Type,
DeclKind::Namespace => NameKind::Namespace,
DeclKind::MacroLike => NameKind::Macro,
DeclKind::Other => continue,
};
kinds.insert(access.member_range.start_offset, kind);
}
kinds
}
fn held_at(view: &FileView, offset: usize) -> Held {
match definition_at(&view.scopes, &view.root, offset) {
Known::Yes(binding) => Held::InThisFile(binding),
_ => Held::NotHere,
}
}
fn in_a_class(scope: ScopeId, scopes: &ScopeTree) -> bool {
scopes.scope_chain(scope).into_iter().any(|id| {
scopes
.scope(id)
.is_some_and(|scope| scope.kind == ScopeKind::Class)
})
}
fn parameter_offsets(view: &FileView) -> HashSet<usize> {
let mut offsets = HashSet::new();
for list in view.root.descendants() {
if cpp_parser::CppSyntaxKind::from(list.kind()) != cpp_parser::CppSyntaxKind::ParameterList
{
continue;
}
for (_, declared) in crate::sema::scopes::parameters_of(&list) {
if let Some((_, name_range)) = declared {
offsets.insert(name_range.start_offset);
}
}
}
offsets
}
fn macro_names(view: &FileView) -> HashMap<String, SourceRange> {
let preprocessing = crate::preprocess(&view.source, view.tree.get_tokens());
let mut map = HashMap::new();
for spanned in &preprocessing.directives {
if let Directive::Define(define) = &spanned.directive
&& let Some(definition) = &define.macro_def
{
map.entry(definition.name.to_string())
.or_insert(definition.name_range);
}
}
map
}
fn qualified_names(view: &FileView) -> HashMap<usize, String> {
fn is_a_name_node(node: &cpp_parser::CppSyntaxNode) -> bool {
matches!(
cpp_parser::CppSyntaxKind::from(node.kind()),
cpp_parser::CppSyntaxKind::NameExpr | cpp_parser::CppSyntaxKind::IdentifierExpr
)
}
fn writes_a_qualifier(node: &cpp_parser::CppSyntaxNode) -> bool {
node.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| token.text() == "::")
}
let mut map = HashMap::new();
for node in view
.root
.descendants()
.filter(is_a_name_node)
.filter(writes_a_qualifier)
{
let mut written = String::new();
let mut global = false;
for element in node.children_with_tokens() {
let Some(token) = element.into_token() else {
continue;
};
match cpp_parser::CppTokenKind::from(token.kind()) {
cpp_parser::CppTokenKind::Identifier => {
if !written.is_empty() {
written.push_str("::");
}
written.push_str(token.text());
let at = usize::from(token.text_range().start());
map.insert(at, spell(global, &written));
}
cpp_parser::CppTokenKind::Scope if written.is_empty() => global = true,
_ => {}
}
}
}
map
}
fn spell(global: bool, written: &str) -> String {
if global {
format!("::{written}")
} else {
written.to_string()
}
}
fn denotes_a_function_pointer(index: &ProjectIndex, declaring: &Path, written: &str) -> bool {
let mut spelling = written.trim().to_string();
for _ in 0..4 {
if spelling.contains("(*") {
return true;
}
let Known::Yes(found) = index.definition(&spelling, declaring) else {
return false;
};
if found.fact.kind != DeclKind::Type {
return false;
}
let Some(target) = found.fact.type_of.as_deref() else {
return false;
};
let target = target.to_string();
if target == spelling {
return false;
}
spelling = target;
}
false
}
fn kind_of_binding(
index: &ProjectIndex,
binding: &Binding,
view: &FileView,
is_a_parameter: bool,
shapes: &crate::sema::declarations::ShapeTable,
) -> Option<NameKind> {
Some(match binding.kind {
BindingKind::Namespace => NameKind::Namespace,
BindingKind::Class | BindingKind::Enum | BindingKind::Alias | BindingKind::Typedef => {
NameKind::Type
}
BindingKind::TemplateParameter => NameKind::TypeParameter,
BindingKind::Enumerator => NameKind::EnumMember,
BindingKind::Constructor | BindingKind::Destructor => NameKind::Type,
BindingKind::Function
| BindingKind::ConversionFunction
| BindingKind::OperatorFunction
| BindingKind::LiteralOperator => {
if in_a_class(binding.scope, &view.scopes) {
NameKind::Method
} else {
NameKind::Function
}
}
BindingKind::Variable => {
if is_a_parameter {
NameKind::Parameter
} else if view
.scopes
.scope(binding.scope)
.is_some_and(|scope| scope.kind == crate::ScopeKind::Class)
{
NameKind::Property
} else if !crate::sema::declarations::declared_template_parameters_with(
crate::sema::declarations::shapes_from(shapes, &view.root),
binding,
)
.is_empty()
{
NameKind::VariableTemplate
} else if crate::sema::declarations::declared_type_of_with(
crate::sema::declarations::shapes_from(shapes, &view.root),
binding,
)
.is_some_and(|written| denotes_a_function_pointer(index, &view.path, &written))
{
NameKind::Function
} else {
NameKind::Variable
}
}
BindingKind::UsingDeclaration
| BindingKind::UsingDirective
| BindingKind::Label
| BindingKind::Other => return None,
})
}
pub(crate) fn kind_of_index(found: IndexedKind) -> Option<NameKind> {
Some(match found.kind {
DeclKind::Type => NameKind::Type,
DeclKind::Function if found.constructor => NameKind::Type,
DeclKind::Function if found.scope.is_some() => NameKind::Method,
DeclKind::Function => NameKind::Function,
DeclKind::Variable if found.enumerator => NameKind::EnumMember,
DeclKind::Variable if found.scope.is_some() => NameKind::Property,
DeclKind::Variable if found.template => NameKind::VariableTemplate,
DeclKind::Variable => NameKind::Variable,
DeclKind::Namespace => NameKind::Namespace,
DeclKind::MacroLike => NameKind::Macro,
DeclKind::Other => return None,
})
}