use std::collections::{HashMap, HashSet};
use crate::preprocess::FilePreprocessing;
use crate::preprocess::directive::{Directive, DirectiveKind, SpannedDirective};
use crate::sema::symbol::{Binding, BindingKind, ScopeId, ScopeKind, ScopeTree};
use crate::summary::{
Access, ConditionalRegion, DeclFact, DeclKind, FactGuard, GuardBranch, MacroFact, MacroKind,
SummaryGuards,
};
use cpp_parser::CppSyntaxKind;
use cpp_parser::{CppSyntaxNode, SourceRange};
pub fn build_facts(
scopes: &ScopeTree,
preprocessing: &FilePreprocessing,
root: &CppSyntaxNode,
errors: &[SourceRange],
keep_locals: bool,
) -> (Vec<DeclFact>, SummaryGuards) {
let file = DeclarationFacts::new(scopes, preprocessing, root, errors, keep_locals);
file.build()
}
pub fn declared_type_of(root: &CppSyntaxNode, binding: &Binding) -> Option<String> {
declared_type_of_with(&DeclarationShapes::of(root), binding)
}
fn using_alias_target(shapes: &DeclarationShapes, name: cpp_parser::SourceRange) -> Option<String> {
let mut target = None;
shapes.on_the_path(name.start_offset, |shape| {
if shape.kind == CppSyntaxKind::UsingDecl
&& let Some(type_id) = &shape.type_id
{
let spelling = type_id.text().to_string().trim().to_string();
if !spelling.is_empty() {
target = Some(spelling);
}
}
});
target
}
fn reaches_the_name(node: &CppSyntaxNode, name: cpp_parser::SourceRange) -> bool {
let span = node.text_range();
usize::from(span.start()) <= name.start_offset && usize::from(span.end()) >= name.start_offset
}
pub(crate) fn declared_type_of_with(
shapes: &DeclarationShapes,
binding: &Binding,
) -> Option<String> {
if !matches!(
binding.kind,
BindingKind::Variable | BindingKind::Typedef | BindingKind::Alias
) {
return None;
}
let mut specifiers = None;
let mut declarator: Option<CppSyntaxNode> = None;
let name_is_a_parameter = shapes.names_a_parameter(binding.name_range.start_offset);
shapes.on_the_path(the_offset_to_descend_by(binding), |shape| {
if let Some(node) = &shape.specifiers {
specifiers = Some(node.clone());
}
if declarator.is_none()
&& let Some(node) = &shape.declarator
&& reaches_the_name(node, binding.name_range)
&& !(name_is_a_parameter && is_a_function_declarator(node))
{
declarator = Some(node.clone());
}
});
if let Some(target) = using_alias_target(shapes, binding.name_range) {
return Some(target);
}
let specifiers = specifiers?;
let the_declarator_holds_the_name = declarator
.as_ref()
.is_some_and(|node| reaches_the_name(node, binding.name_range));
let spelled = match binding.kind {
BindingKind::Typedef => None,
_ if the_declarator_holds_the_name => None,
_ => Some(binding.name.spelled()),
};
let found = crate::sema::types::type_of_declaration_named(
&specifiers,
declarator.as_ref(),
binding.name_range,
spelled.as_deref(),
matches!(binding.kind, BindingKind::Variable),
);
let written = found.to_string();
(!written.is_empty()).then_some(written)
}
pub(crate) fn declared_modifiers_with(
shapes: &DeclarationShapes,
binding: &Binding,
) -> crate::DeclModifiers {
let mut specifiers = None;
let mut declarator: Option<CppSyntaxNode> = None;
let name_is_a_parameter = shapes.names_a_parameter(the_offset_to_descend_by(binding));
shapes.on_the_path(the_offset_to_descend_by(binding), |shape| {
if let Some(node) = &shape.specifiers {
specifiers = Some(node.clone());
}
if declarator.is_none()
&& let Some(node) = &shape.declarator
&& reaches_the_name(node, binding.name_range)
&& !(name_is_a_parameter && is_a_function_declarator(node))
{
declarator = Some(node.clone());
}
});
let mut found = crate::DeclModifiers::default();
for node in [specifiers.as_ref(), declarator.as_ref()]
.into_iter()
.flatten()
{
found = found.union(modifiers_in(node));
}
if let Some(declarator) = declarator.as_ref() {
found = found.union(function_suffix_in(declarator));
}
if let Some(init) = declarator
.as_ref()
.and_then(|declarator| declarator.parent())
{
found = found.union(modifiers_in(&init));
}
if is_marked_maybe_unused(specifiers.as_ref(), declarator.as_ref()) {
found = found.union(crate::DeclModifiers::MAYBE_UNUSED);
}
found
}
fn function_suffix_in(declarator: &CppSyntaxNode) -> crate::DeclModifiers {
use cpp_parser::{CppAstNode, CppDeclarator, CppTokenKind};
let mut found = crate::DeclModifiers::default();
let Some(declarator_node) = CppDeclarator::cast(declarator.clone()) else {
return found;
};
let Some(parameter_list) = declarator_node.get_param_list() else {
return found;
};
let after_the_parameters = parameter_list.get_range().end();
for element in declarator_node.syntax().children_with_tokens() {
let Some(token) = element.into_token() else {
continue;
};
if token.text_range().start() < after_the_parameters {
continue;
}
match CppTokenKind::from(token.kind()) {
CppTokenKind::ConstKeyword => found = found.union(crate::DeclModifiers::CONST),
CppTokenKind::VolatileKeyword => found = found.union(crate::DeclModifiers::VOLATILE),
CppTokenKind::Ampersand => found = found.union(crate::DeclModifiers::LVALUE_REFERENCE),
CppTokenKind::LogicalAnd => found = found.union(crate::DeclModifiers::RVALUE_REFERENCE),
_ => {}
}
}
found
}
pub(crate) fn the_requires_clause_with(
shapes: &DeclarationShapes,
binding: &Binding,
) -> Option<String> {
let mut declarator: Option<CppSyntaxNode> = None;
shapes.on_the_path(the_offset_to_descend_by(binding), |shape| {
if let Some(node) = &shape.declarator
&& reaches_the_name(node, binding.name_range)
{
declarator = Some(node.clone());
}
});
use cpp_parser::{CppAstNode, CppInitDeclarator};
let parent = declarator.as_ref()?.parent()?;
let init = CppInitDeclarator::cast(parent)?;
let clause = init.get_requires_clause()?;
let text = clause.get_clause_text();
(!text.is_empty()).then_some(text)
}
fn is_marked_maybe_unused(
specifiers: Option<&CppSyntaxNode>,
declarator: Option<&CppSyntaxNode>,
) -> bool {
use cpp_parser::{CppAstNode, CppAttributeList, CppDeclSpecifierSeq};
if specifiers
.and_then(|node| CppDeclSpecifierSeq::cast(node.clone()))
.is_some_and(|specifiers| specifiers.has_attribute("maybe_unused"))
{
return true;
}
let Some(declaration) = specifiers.and_then(|node| node.parent()).or_else(|| {
declarator
.and_then(|node| node.parent())
.and_then(|node| node.parent())
}) else {
return false;
};
let mut before = cpp_parser::typed_previous_sibling::<CppAttributeList>(&declaration);
while let Some(list) = before {
if list.has_a_name("maybe_unused") {
return true;
}
before = cpp_parser::typed_previous_sibling::<CppAttributeList>(list.syntax());
}
false
}
fn is_a_function_declarator(declarator: &CppSyntaxNode) -> bool {
use cpp_parser::CppAstNode;
cpp_parser::CppDeclarator::cast(declarator.clone())
.is_some_and(|declarator| declarator.get_param_list().is_some())
}
fn modifiers_in(node: &CppSyntaxNode) -> crate::DeclModifiers {
use cpp_parser::CppAstNode;
let mut found = crate::DeclModifiers::default();
let mut stack: Vec<(CppSyntaxNode, bool)> = vec![(node.clone(), false)];
while let Some((current, in_a_parameter_list)) = stack.pop() {
for element in current.children_with_tokens() {
if let Some(token) = element.as_token().cloned() {
let word = token.text();
let bit = match word {
"virtual" => Some(crate::DeclModifiers::VIRTUAL),
"override" => Some(crate::DeclModifiers::OVERRIDE),
"final" => Some(crate::DeclModifiers::FINAL),
"constexpr" => Some(crate::DeclModifiers::CONSTEXPR),
"consteval" => Some(crate::DeclModifiers::CONSTEVAL),
"constinit" => Some(crate::DeclModifiers::CONSTINIT),
"static" => Some(crate::DeclModifiers::STATIC),
"inline" => Some(crate::DeclModifiers::INLINE),
"explicit" => Some(crate::DeclModifiers::EXPLICIT),
"maybe_unused" => Some(crate::DeclModifiers::MAYBE_UNUSED),
"nodiscard" => Some(crate::DeclModifiers::NODISCARD),
"delete" => Some(crate::DeclModifiers::DELETED),
"default" => Some(crate::DeclModifiers::DEFAULTED),
_ => None,
};
if let Some(bit) = bit {
found = found.union(bit);
}
if in_a_parameter_list
&& cpp_parser::CppTokenKind::from(token.kind())
== cpp_parser::CppTokenKind::Ellipsis
{
found = found.union(crate::DeclModifiers::VARIADIC);
}
continue;
}
let Some(child) = element.as_node().cloned() else {
continue;
};
if cpp_parser::CppClassBody::can_cast(child.kind().into())
|| cpp_parser::CppCompoundStat::can_cast(child.kind().into())
{
continue;
}
let child_is_a_parameter_list = cpp_parser::CppParamList::can_cast(child.kind().into());
stack.push((child, in_a_parameter_list || child_is_a_parameter_list));
}
}
found
}
fn the_offset_to_descend_by(binding: &Binding) -> usize {
if binding.name_range.length > 0 {
binding.name_range.start_offset
} else {
binding.range.start_offset
}
}
pub type TemplateParameters = (String, String, Option<String>);
#[derive(Default)]
pub struct DeclarationShapes {
shapes: Vec<Shape>,
roots: (u32, u32),
children: Vec<u32>,
templates: Vec<(
cpp_parser::SourceRange,
CppSyntaxNode,
std::sync::OnceLock<std::sync::Arc<Vec<TemplateParameters>>>,
)>,
parameter_lists: Vec<cpp_parser::SourceRange>,
}
struct Shape {
at: cpp_parser::SourceRange,
kind: CppSyntaxKind,
access: Option<Access>,
exported: bool,
specifiers: Option<CppSyntaxNode>,
trailing: Option<CppSyntaxNode>,
declarator: Option<CppSyntaxNode>,
type_id: Option<CppSyntaxNode>,
bases: Vec<CppSyntaxNode>,
pattern: Option<String>,
parent: Option<u32>,
children: (u32, u32),
}
impl DeclarationShapes {
fn template_at(&self, at: usize) -> Option<&std::sync::Arc<Vec<TemplateParameters>>> {
self.templates
.iter()
.rev()
.find(|(introduced, _, _)| {
introduced.start_offset <= at && at <= introduced.end_offset()
})
.map(|(_, list, parsed)| {
parsed.get_or_init(|| {
std::sync::Arc::new(crate::sema::types::template_parameters_with_defaults(list))
})
})
}
pub fn of(root: &CppSyntaxNode) -> Self {
use cpp_parser::CppAstNode;
let mut shapes: Vec<Shape> = Vec::new();
let mut chain: Vec<u32> = Vec::new();
let mut templates: Vec<(
cpp_parser::SourceRange,
CppSyntaxNode,
std::sync::OnceLock<std::sync::Arc<Vec<TemplateParameters>>>,
)> = Vec::new();
let mut bodies: Vec<(usize, Access)> = Vec::new();
let mut exports: Vec<usize> = Vec::new();
let mut parameter_lists: Vec<cpp_parser::SourceRange> = Vec::new();
for node in root.descendants() {
let at = cpp_parser::source_range(node.text_range());
if cpp_parser::CppParamList::can_cast(node.kind().into()) {
match parameter_lists.last_mut() {
Some(last)
if last.start_offset <= at.start_offset
&& at.end_offset() <= last.end_offset() => {}
_ => parameter_lists.push(at),
}
}
while chain
.last()
.is_some_and(|top| shapes[*top as usize].at.end_offset() <= at.start_offset)
{
chain.pop();
}
while bodies
.last()
.is_some_and(|(end, _)| *end <= at.start_offset)
{
bodies.pop();
}
while exports.last().is_some_and(|end| *end <= at.start_offset) {
exports.pop();
}
if begins_an_exported_region(&node) {
exports.push(at.end_offset());
}
let kind = CppSyntaxKind::from(node.kind());
if kind == CppSyntaxKind::ClassBody {
let default = node
.parent()
.and_then(cpp_parser::CppClassDef::cast)
.map_or(Access::Private, |class| {
if class.is_struct() || class.is_union() {
Access::Public
} else {
Access::Private
}
});
bodies.push((at.end_offset(), default));
} else if let Some((_, level)) = bodies.last_mut() {
match kind {
CppSyntaxKind::PublicAccess => *level = Access::Public,
CppSyntaxKind::ProtectedAccess => *level = Access::Protected,
CppSyntaxKind::PrivateAccess => *level = Access::Private,
_ => {}
}
}
if kind == CppSyntaxKind::TemplateDecl
&& let Some(list) =
cpp_parser::typed_children::<cpp_parser::CppTemplateParamList>(&node).next()
&& let Some(owner) = node.parent()
{
templates.push((
cpp_parser::source_range(owner.text_range()),
list.syntax().clone(),
std::sync::OnceLock::new(),
));
}
let read = children_a_question_reads(&node);
if read.is_empty() && !declares_a_shape(kind) {
continue;
}
let parent = chain.last().copied();
let pattern = match kind {
CppSyntaxKind::ClassDef | CppSyntaxKind::StructDef | CppSyntaxKind::UnionDef => {
written_class_pattern(&node)
}
_ => None,
};
shapes.push(Shape {
at,
kind,
pattern,
access: bodies.last().map(|(_, level)| *level),
exported: !exports.is_empty(),
specifiers: read.specifiers,
trailing: read.trailing,
declarator: read.declarator,
type_id: read.type_id,
bases: read.bases,
parent,
children: (0, 0),
});
chain.push(shapes.len() as u32 - 1);
}
let mut runs = vec![(0u32, 0u32); shapes.len() + 1];
for shape in &shapes {
runs[slot_of(shape.parent)].1 += 1;
}
let mut placed = 0u32;
let mut cursor = Vec::with_capacity(runs.len());
for run in runs.iter_mut() {
cursor.push(placed);
run.0 = placed;
placed += run.1;
}
let mut children = vec![0u32; placed as usize];
for (index, shape) in shapes.iter().enumerate() {
let slot = slot_of(shape.parent);
children[cursor[slot] as usize] = index as u32;
cursor[slot] += 1;
}
for (index, shape) in shapes.iter_mut().enumerate() {
shape.children = runs[index + 1];
}
DeclarationShapes {
shapes,
roots: runs[0],
children,
templates,
parameter_lists,
}
}
pub fn names_a_parameter(&self, offset: usize) -> bool {
let at = self
.parameter_lists
.partition_point(|range| range.start_offset <= offset);
let Some(index) = at.checked_sub(1) else {
return false;
};
offset < self.parameter_lists[index].end_offset()
}
pub fn len(&self) -> usize {
self.shapes.len()
}
pub fn access_at(&self, offset: usize) -> Option<Access> {
let mut found = None;
self.on_the_path(offset, |shape| found = shape.access);
found
}
pub fn specifiers_at(&self, offset: usize) -> Option<CppSyntaxNode> {
let mut found = None;
self.on_the_path(offset, |shape| {
if let Some(specifiers) = &shape.specifiers {
found = Some(specifiers.clone());
}
});
found
}
pub fn exported_at(&self, offset: usize) -> bool {
let mut found = false;
self.on_the_path(offset, |shape| found = shape.exported);
found
}
pub fn is_empty(&self) -> bool {
self.shapes.is_empty()
}
pub fn declaration_around(&self, name_range: SourceRange) -> Option<SourceRange> {
let mut innermost = None;
let mut template = None;
self.on_the_path(name_range.start_offset, |shape| {
if !contains(shape.at, name_range) {
return;
}
if shape.kind == cpp_parser::CppSyntaxKind::TemplateDecl {
template = Some(shape.at);
} else {
innermost = Some(shape.at);
}
});
template.or(innermost)
}
fn on_the_path(&self, offset: usize, mut visit: impl FnMut(&Shape)) {
let mut run = self.roots;
loop {
let candidates = &self.children[run.0 as usize..(run.0 + run.1) as usize];
let position = candidates
.partition_point(|index| self.shapes[*index as usize].at.start_offset <= offset);
let Some(&child) = position.checked_sub(1).and_then(|at| candidates.get(at)) else {
return;
};
let shape = &self.shapes[child as usize];
if shape.at.end_offset() <= offset {
return;
}
visit(shape);
run = shape.children;
}
}
}
fn slot_of(parent: Option<u32>) -> usize {
parent.map_or(0, |parent| parent as usize + 1)
}
struct ShapeChildren {
specifiers: Option<CppSyntaxNode>,
trailing: Option<CppSyntaxNode>,
declarator: Option<CppSyntaxNode>,
type_id: Option<CppSyntaxNode>,
bases: Vec<CppSyntaxNode>,
}
impl ShapeChildren {
fn is_empty(&self) -> bool {
self.specifiers.is_none()
&& self.trailing.is_none()
&& self.declarator.is_none()
&& self.type_id.is_none()
&& self.bases.is_empty()
}
}
fn children_a_question_reads(node: &CppSyntaxNode) -> ShapeChildren {
use cpp_parser::{
CppAstNode, CppBaseSpecifier, CppDeclSpecifierSeq, CppDeclarator, CppTrailingReturnType,
CppTypeId,
};
ShapeChildren {
specifiers: cpp_parser::typed_children::<CppDeclSpecifierSeq>(node)
.next()
.map(|child| child.syntax().clone()),
trailing: cpp_parser::typed_children::<CppTrailingReturnType>(node)
.next()
.map(|child| child.syntax().clone()),
declarator: cpp_parser::typed_children::<CppDeclarator>(node)
.next()
.map(|child| child.syntax().clone()),
type_id: cpp_parser::typed_children::<CppTypeId>(node)
.next()
.map(|child| child.syntax().clone()),
bases: cpp_parser::typed_children::<CppBaseSpecifier>(node)
.filter_map(|base| base.get_name())
.map(|name| name.syntax().clone())
.collect(),
}
}
fn declares_a_shape(kind: CppSyntaxKind) -> bool {
matches!(
kind,
CppSyntaxKind::UsingDecl
| CppSyntaxKind::TypedefDecl
| CppSyntaxKind::ClassDef
| CppSyntaxKind::StructDef
| CppSyntaxKind::UnionDef
| CppSyntaxKind::EnumDef
| CppSyntaxKind::NamespaceDecl
| CppSyntaxKind::ConceptDecl
)
}
fn declared_namespace_alias_target_with(root: &CppSyntaxNode, binding: &Binding) -> Option<String> {
if binding.kind != BindingKind::Namespace {
return None;
}
use cpp_parser::CppNamespaceDecl;
let token = cpp_parser::token_at(root, binding.name_range.start_offset)?;
let namespace = cpp_parser::typed_ancestors::<CppNamespaceDecl>(&token.parent()?).next()?;
if namespace.get_body().is_some() {
return None;
}
Some(namespace.get_name()?.get_qualified_name())
}
pub fn declared_alias_target(root: &CppSyntaxNode, binding: &Binding) -> Option<String> {
declared_alias_target_with(&DeclarationShapes::of(root), binding)
}
fn declared_alias_target_with(shapes: &DeclarationShapes, binding: &Binding) -> Option<String> {
if !matches!(binding.kind, BindingKind::Alias | BindingKind::Typedef) {
return None;
}
let mut declaration = None;
shapes.on_the_path(the_offset_to_descend_by(binding), |shape| {
if matches!(
shape.kind,
CppSyntaxKind::UsingDecl | CppSyntaxKind::TypedefDecl
) {
declaration = Some((
shape.kind,
shape.type_id.clone(),
shape.specifiers.clone(),
shape.declarator.clone(),
));
}
});
let (kind, type_id, specifiers, declarator) = declaration?;
if kind == CppSyntaxKind::UsingDecl {
return type_id
.as_ref()
.map(|target| target.text().to_string().trim().to_string())
.filter(|target| !target.is_empty());
}
let specifiers = specifiers.as_ref()?;
let declarator = declarator.as_ref();
if let Some(named) = the_class_a_typedef_body_names(specifiers, &binding.name.text()) {
return Some(named);
}
let Some(declarator) = declarator else {
let spelling = strip_declaration_specifiers(&specifiers.text().to_string());
return (!spelling.is_empty()).then_some(spelling);
};
let spelling = format!(
"{} {}",
strip_declaration_specifiers(&specifiers.text().to_string()),
without(
&declarator.text().to_string(),
declarator,
binding.name_range
)
);
let spelling = spelling.split_whitespace().collect::<Vec<_>>().join(" ");
(!spelling.is_empty()).then_some(spelling)
}
fn the_class_a_typedef_body_names(
specifiers: &CppSyntaxNode,
typedef_name: &str,
) -> Option<String> {
use cpp_parser::CppAstNode;
let body = specifiers.children().find(|child| {
let kind = CppSyntaxKind::from(child.kind());
cpp_parser::CppClassDef::can_cast(kind)
|| matches!(kind, CppSyntaxKind::EnumDef | CppSyntaxKind::EnumClassDef)
})?;
let tag = cpp_parser::typed_children::<cpp_parser::CppNameExpr>(&body)
.next()
.map(|name| cpp_parser::subtree_text_spaced(name.syntax()))
.filter(|written| !written.is_empty());
Some(tag.unwrap_or_else(|| typedef_name.trim().to_string()))
}
fn without(text: &str, node: &CppSyntaxNode, name: cpp_parser::SourceRange) -> String {
let start = usize::from(node.text_range().start());
let (from, to) = (
name.start_offset.saturating_sub(start),
name.end_offset().saturating_sub(start),
);
if from > to || to > text.len() || !text.is_char_boundary(from) || !text.is_char_boundary(to) {
return text.to_string();
}
format!("{}{}", &text[..from], &text[to..])
}
pub fn declared_returns_of(root: &CppSyntaxNode, binding: &Binding) -> Option<String> {
let written = declared_returns_of_with(&DeclarationShapes::of(root), binding);
if written.is_some() {
return written;
}
deduced_returns_of(root, binding)
}
pub fn deduced_returns_of_substituted(
root: &CppSyntaxNode,
binding: Binding,
substitutions: &crate::sema::types::TypeSubstitutions<'_>,
argument_types: &[crate::sema::types::Type],
) -> Option<String> {
if binding.kind != BindingKind::Function {
return None;
}
let declaration = declaration_of(root, &binding)?;
let body = body_of(&declaration)?;
let returns = returned_expressions_in(&body)
.into_iter()
.filter(|expression| a_branch_that_is_taken(expression, &body, substitutions))
.collect::<Vec<_>>();
if returns.is_empty() {
return None;
}
let mut agreed: Option<String> = None;
for expression in &returns {
let written =
type_a_return_states_with(expression, &declaration, substitutions, argument_types)?;
match &agreed {
None => agreed = Some(written),
Some(previous) if *previous == written => {}
Some(_) => return None,
}
}
agreed
}
fn a_branch_that_is_taken(
expression: &cpp_parser::CppExpr,
body: &cpp_parser::CppCompoundStat,
substitutions: &crate::sema::types::TypeSubstitutions<'_>,
) -> bool {
use cpp_parser::{CppAstNode, CppIfStat};
let body_range = body.get_range();
for condition in cpp_parser::typed_ancestors::<CppIfStat>(expression.syntax()) {
if !body_range.contains_range(condition.get_range()) {
break;
}
let Some(written) = constexpr_condition_of(&condition) else {
continue;
};
let Some(held) = evaluate_a_trait(&written, substitutions) else {
continue;
};
let in_the_else = condition.get_else_branch().is_some_and(|else_branch| {
expression.get_range().start() > else_branch.get_range().start()
});
if held == in_the_else {
return false;
}
}
true
}
fn constexpr_condition_of(statement: &cpp_parser::CppIfStat) -> Option<String> {
use cpp_parser::CppAstNode;
if !statement.is_constexpr() {
return None;
}
let inner = statement.get_condition()?.get_expr()?;
Some(cpp_parser::subtree_text_spaced(inner.syntax()))
}
fn evaluate_a_trait(
condition: &str,
substitutions: &crate::sema::types::TypeSubstitutions<'_>,
) -> Option<bool> {
let condition = condition.trim();
if let Some(rest) = condition.strip_prefix('!') {
return evaluate_a_trait(rest, substitutions).map(|held| !held);
}
if let Some((left, right)) = condition.split_once("&&") {
return match (
evaluate_a_trait(left, substitutions),
evaluate_a_trait(right, substitutions),
) {
(Some(false), _) | (_, Some(false)) => Some(false),
(Some(true), Some(true)) => Some(true),
_ => None,
};
}
if let Some((left, right)) = condition.split_once("||") {
return match (
evaluate_a_trait(left, substitutions),
evaluate_a_trait(right, substitutions),
) {
(Some(true), _) | (_, Some(true)) => Some(true),
(Some(false), Some(false)) => Some(false),
_ => None,
};
}
let (name, argument) = condition.split_once('<')?;
let argument = argument.trim_end().strip_suffix('>')?;
let (first, second) = match argument.split_once(',') {
Some((first, second)) => (first.trim(), Some(second.trim())),
None => (argument.trim(), None),
};
let first = substituted_spelling(first, substitutions);
match name.trim() {
"is_pointer_v" => Some(first.ends_with('*')),
"is_integral_v" => Some(matches!(
first.as_str(),
"bool"
| "char"
| "signed char"
| "unsigned char"
| "short"
| "unsigned short"
| "int"
| "unsigned int"
| "long"
| "unsigned long"
| "long long"
| "unsigned long long"
| "wchar_t"
| "char8_t"
| "char16_t"
| "char32_t"
| "size_t"
| "ptrdiff_t"
)),
"is_same_v" => {
let second = substituted_spelling(second?, substitutions);
Some(first == second)
}
_ => None,
}
}
fn substituted_spelling(
written: &str,
substitutions: &crate::sema::types::TypeSubstitutions<'_>,
) -> String {
let mut text = written.trim();
while let Some(inner) = text
.strip_prefix("decay_t<")
.and_then(|rest| rest.strip_suffix('>'))
{
text = inner.trim();
}
let replaced = substitutions.get(text).map(|argument| argument.to_string());
let text = replaced.as_deref().unwrap_or(text);
strip_reference_and_const(text)
}
fn strip_reference_and_const(written: &str) -> String {
let mut text = written.trim();
loop {
let trimmed = text.trim_end();
let without = trimmed
.strip_suffix("&&")
.or_else(|| trimmed.strip_suffix('&'));
match without {
Some(without) => text = without.trim_end(),
None => break,
}
}
let mut words: Vec<&str> = text.split_whitespace().collect();
while words
.first()
.is_some_and(|word| matches!(*word, "const" | "volatile"))
&& !words.iter().any(|word| word.contains('*'))
{
words.remove(0);
}
words.join(" ")
}
pub(crate) fn freed_parameters_of(root: &CppSyntaxNode, binding: &Binding) -> u64 {
if !matches!(
binding.kind,
BindingKind::Function | BindingKind::Constructor
) {
return 0;
}
use cpp_parser::CppAstNode;
let name_start = binding.name_range.start_offset;
let declaration = cpp_parser::typed_descendants::<cpp_parser::CppDeclaration>(root)
.filter(|declaration| {
let range = declaration.get_range();
usize::from(range.start()) <= name_start
&& name_start < usize::from(range.end())
&& declaration.get_body().is_some()
})
.max_by_key(|declaration| usize::from(declaration.get_range().start()));
let Some(declaration) = declaration else {
return 0;
};
let Some(body) = declaration.get_body() else {
return 0;
};
let parameters = the_parameter_names(declaration.syntax());
if parameters.is_empty() {
return 0;
}
let mut mask = 0u64;
scan_unconditional_statements(body.syntax(), ¶meters, &mut mask);
mask
}
fn fill_the_frees(root: &CppSyntaxNode, facts: &mut [crate::DeclFact]) {
if facts.is_empty() {
return;
}
let wanted: std::collections::HashSet<usize> = facts
.iter()
.filter(|fact| fact.kind == crate::DeclKind::Function)
.map(|fact| fact.name_range.start_offset)
.collect();
let mut bodies: std::collections::HashMap<usize, (CppSyntaxNode, Vec<String>)> =
std::collections::HashMap::with_capacity(wanted.len());
use cpp_parser::CppAstNode;
for node in cpp_parser::typed_descendants::<cpp_parser::CppDeclaration>(root) {
let Some(body) = node.get_body() else {
continue;
};
let Some(name) = node.get_name() else {
continue;
};
let name_start = usize::from(cpp_parser::CppAstToken::get_range(&name).start());
if !wanted.contains(&name_start) {
continue;
}
let parameters = the_parameter_names(node.syntax());
bodies.insert(name_start, (body.syntax().clone(), parameters));
}
for fact in facts {
if fact.kind != crate::DeclKind::Function {
continue;
}
let Some((body, parameters)) = bodies.get(&fact.name_range.start_offset) else {
continue;
};
if parameters.is_empty() {
continue;
}
let mut mask = 0u64;
scan_unconditional_statements(body, parameters, &mut mask);
fact.frees = mask;
}
}
fn fill_the_reflection(
root: &cpp_parser::CppSyntaxNode,
written: &str,
facts: &mut [crate::DeclFact],
) {
let mut annotations: std::collections::HashMap<usize, (&str, &str)> =
std::collections::HashMap::new();
use cpp_parser::CppAstNode;
for node in cpp_parser::typed_descendants::<cpp_parser::CppDeclaration>(root) {
let Some(name_start) = the_declaration_name_start(node.syntax()) else {
continue;
};
let start = usize::from(node.get_range().start());
let Some(annotation) =
the_annotation_before(written, start).or_else(|| the_annotation_at(written, start))
else {
continue;
};
annotations.insert(name_start, annotation);
}
for fact in facts {
if fact.reflection.is_some() {
continue;
}
if let Some((macro_name, arguments)) = annotations.get(&fact.name_range.start_offset) {
fact.reflection = Some(crate::summary::ReflectionFact {
macro_name: (*macro_name).to_string(),
specifiers: the_specifiers(arguments),
});
}
}
}
fn the_declaration_name_start(declaration: &cpp_parser::CppSyntaxNode) -> Option<usize> {
use cpp_parser::{CppAstNode, CppAstToken, CppDeclaration};
let declaration = CppDeclaration::cast(declaration.clone())?;
let name = declaration.get_name()?;
Some(usize::from(name.get_range().start()))
}
fn the_annotation_before(written: &str, at: usize) -> Option<(&str, &str)> {
let before = written.get(..at)?.trim_end();
if !before.ends_with(')') {
return None;
}
let bytes = before.as_bytes();
let mut depth = 0usize;
let mut index = bytes.len();
while index > 0 {
index -= 1;
match bytes[index] {
b')' => depth += 1,
b'(' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
}
if depth != 0 {
return None;
}
let head = before[..index].trim_end();
let start = head
.char_indices()
.rev()
.find(|(_, ch)| !(ch.is_alphanumeric() || *ch == '_'))
.map(|(offset, ch)| offset + ch.len_utf8())
.unwrap_or(0);
let macro_name = &head[start..];
if !matches!(
macro_name,
"UCLASS" | "USTRUCT" | "UENUM" | "UINTERFACE" | "UPROPERTY" | "UFUNCTION"
) {
return None;
}
Some((macro_name, &before[index + 1..before.len() - 1]))
}
fn the_annotation_at(written: &str, at: usize) -> Option<(&str, &str)> {
let rest = written.get(at..)?;
let open = rest.find('(')?;
let macro_name = rest[..open].trim_end();
if !matches!(
macro_name,
"UCLASS" | "USTRUCT" | "UENUM" | "UINTERFACE" | "UPROPERTY" | "UFUNCTION"
) {
return None;
}
let mut depth = 0usize;
let mut close = None;
for (index, character) in rest[open..].char_indices() {
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
close = Some(open + index);
break;
}
}
_ => {}
}
}
let close = close?;
Some((macro_name, &rest[open + 1..close]))
}
fn the_specifiers(arguments: &str) -> Vec<String> {
let mut specifiers = Vec::new();
let mut depth = 0usize;
let mut in_a_string = false;
let mut start = 0usize;
for (index, character) in arguments.char_indices() {
match character {
'"' => in_a_string = !in_a_string,
'(' | '[' | '{' if !in_a_string => depth += 1,
')' | ']' | '}' if !in_a_string => depth = depth.saturating_sub(1),
',' if depth == 0 && !in_a_string => {
let specifier = arguments[start..index].trim();
if !specifier.is_empty() {
specifiers.push(specifier.to_string());
}
start = index + 1;
}
_ => {}
}
}
let specifier = arguments[start..].trim();
if !specifier.is_empty() {
specifiers.push(specifier.to_string());
}
specifiers
}
fn the_parameters_of(scope: &CppSyntaxNode) -> Vec<cpp_parser::CppParam> {
use cpp_parser::{CppAstNode, CppDeclaration, CppLambdaExpr};
if let Some(declaration) = CppDeclaration::cast(scope.clone()) {
return declaration
.get_param_list()
.map(|list| list.get_params().collect())
.unwrap_or_default();
}
if let Some(lambda) = CppLambdaExpr::cast(scope.clone()) {
return lambda
.get_params()
.map(|list| list.get_params().collect())
.unwrap_or_default();
}
Vec::new()
}
fn the_declarations_in(scope: &CppSyntaxNode) -> Vec<cpp_parser::CppDeclaration> {
use cpp_parser::{CppAstNode, CppDeclaration, CppLambdaExpr};
let body = if let Some(lambda) = CppLambdaExpr::cast(scope.clone()) {
lambda.get_body()
} else {
CppDeclaration::cast(scope.clone()).and_then(|declaration| declaration.get_body())
};
let Some(body) = body else {
return Vec::new();
};
body.descendants::<CppDeclaration>()
.filter(|candidate| {
cpp_parser::typed_ancestors_until::<CppLambdaExpr>(candidate.syntax(), body.syntax())
.next()
.is_none()
})
.collect()
}
fn the_parameter_names(declaration: &CppSyntaxNode) -> Vec<String> {
the_parameters_of(declaration)
.into_iter()
.filter_map(|parameter| parameter.get_name_text())
.collect()
}
fn scan_unconditional_statements(node: &CppSyntaxNode, parameters: &[String], mask: &mut u64) {
use cpp_parser::{CppAstNode, CppStat};
for child in node.children() {
match CppStat::cast(child.clone()) {
Some(CppStat::CompoundStat(block)) => {
scan_unconditional_statements(block.syntax(), parameters, mask);
}
Some(CppStat::ExpressionStat(_) | CppStat::ReturnStat(_) | CppStat::Declaration(_)) => {
scan_for_a_free(&child, parameters, mask);
}
_ => {}
}
}
}
fn scan_for_a_free(node: &CppSyntaxNode, parameters: &[String], mask: &mut u64) {
use cpp_parser::{CppAstNode, CppExpr};
if let Some(expression) = CppExpr::cast(node.clone()) {
match &expression {
CppExpr::LambdaExpr(_) => return,
CppExpr::UnaryExpr(unary) => {
if unary.is_delete()
&& let Some(operand) = unary.get_operand()
&& let Some(name) = a_bare_name(operand.syntax())
&& let Some(index) = parameters.iter().position(|parameter| parameter == &name)
&& index < 64
{
*mask |= 1 << index;
}
}
CppExpr::CallExpr(call) => {
let name = call
.get_callee()
.and_then(|callee| the_last_identifier_of(callee.syntax()));
let frees_its_first_argument = match name.as_deref() {
Some("free") => true,
Some("destroy_at") => true,
_ => false,
};
if frees_its_first_argument
&& let Some(argument) = call.get_args().into_iter().next()
&& let Some(name) = a_bare_name(argument.syntax())
&& let Some(index) = parameters.iter().position(|parameter| parameter == &name)
&& index < 64
{
*mask |= 1 << index;
}
}
_ => {}
}
}
for child in node.children() {
scan_for_a_free(&child, parameters, mask);
}
}
fn a_bare_name(expression: &CppSyntaxNode) -> Option<String> {
use cpp_parser::{CppAstNode, CppNameExpr, CppUnaryExpr};
if let Some(name) = CppNameExpr::cast(expression.clone()) {
return name.get_name_text();
}
let unary = CppUnaryExpr::cast(expression.clone())?;
a_bare_name(unary.get_operand()?.syntax())
}
fn the_last_identifier_of(expression: &CppSyntaxNode) -> Option<String> {
use cpp_parser::{CppAstNode, CppCallExpr, CppMemberExpr, CppNameExpr};
if let Some(name) = CppNameExpr::cast(expression.clone()) {
return name
.get_last_name_token()
.map(|token| token.get_name_text().to_string());
}
if let Some(member) = CppMemberExpr::cast(expression.clone()) {
return member
.get_member_name()
.map(|token| token.get_name_text().to_string());
}
let call = CppCallExpr::cast(expression.clone())?;
let callee = call.get_callee()?;
the_last_identifier_of(callee.syntax())
}
fn deduced_returns_of(root: &CppSyntaxNode, binding: &Binding) -> Option<String> {
if binding.kind != BindingKind::Function {
return None;
}
let declaration = declaration_of(root, binding)?;
let body = body_of(&declaration)?;
let returns = returned_expressions_in(&body);
if returns.is_empty() {
return None;
}
let mut agreed: Option<String> = None;
for expression in &returns {
let written = type_a_return_states(expression, &declaration)?;
match &agreed {
None => agreed = Some(written),
Some(_) => return None,
}
}
agreed
}
fn body_of(declaration: &CppSyntaxNode) -> Option<cpp_parser::CppCompoundStat> {
use cpp_parser::{CppAstNode, CppDeclaration, CppLambdaExpr};
if let Some(declaration) = CppDeclaration::cast(declaration.clone()) {
return declaration.get_body();
}
CppLambdaExpr::cast(declaration.clone())?.get_body()
}
fn declaration_of(root: &CppSyntaxNode, binding: &Binding) -> Option<CppSyntaxNode> {
use cpp_parser::CppAstNode;
let token = cpp_parser::token_at(root, binding.name_range.start_offset)?;
token.parent_ancestors().find(|node| {
cpp_parser::CppDeclaration::can_cast(node.kind().into())
|| cpp_parser::CppSyntaxKind::from(node.kind())
== cpp_parser::CppSyntaxKind::FunctionDef
})
}
pub fn a_lambdas_return_type(
lambda: &CppSyntaxNode,
argument_types: &[crate::sema::types::Type],
) -> Option<String> {
use cpp_parser::{CppAstNode, CppLambdaExpr};
let lambda = CppLambdaExpr::cast(lambda.clone())?;
let body = lambda.get_body()?;
let parameters = the_parameters_of(lambda.syntax());
let receives_a_placeholder = parameters.iter().any(cpp_parser::CppParam::is_auto);
let placeholder_types = the_auto_parameters_with_their_arguments(¶meters, argument_types);
if receives_a_placeholder && placeholder_types.is_empty() {
return None;
}
let substitutions = crate::sema::types::TypeSubstitutions::new(&[], argument_types);
let mut agreed: Option<String> = None;
for statement in the_returns_of(&body, lambda.syntax()) {
let Some(expression) = statement.get_expr() else {
continue;
};
let written = match type_with_the_auto_parameters(&expression, &placeholder_types) {
Some(written) => written,
None => type_a_return_states_with(
&expression,
lambda.syntax(),
&substitutions,
argument_types,
)?,
};
match &agreed {
None => agreed = Some(written),
Some(previous) if *previous == written => {}
Some(_) => return None,
}
}
agreed
}
fn the_auto_parameters_with_their_arguments(
parameters: &[cpp_parser::CppParam],
argument_types: &[crate::sema::types::Type],
) -> Vec<(String, crate::sema::types::Type)> {
parameters
.iter()
.enumerate()
.filter(|(_, parameter)| parameter.is_auto())
.filter_map(|(at, parameter)| {
Some((parameter.get_name_text()?, argument_types.get(at)?.clone()))
})
.collect()
}
fn is_a_comparison(binary: &cpp_parser::CppBinaryExpr) -> bool {
matches!(
binary.get_operator_text().as_deref(),
Some("==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||")
)
}
fn is_a_literal_zero(expression: &cpp_parser::CppExpr) -> bool {
let cpp_parser::CppExpr::LiteralExpr(literal) = expression else {
return false;
};
literal.get_literal_text().is_some_and(|text| {
matches!(
text.trim(),
"0" | "0L" | "0U" | "0UL" | "0LL" | "0ULL" | "0u" | "0ul" | "0ll" | "0ull"
)
})
}
fn type_with_the_auto_parameters(
expression: &cpp_parser::CppExpr,
paired: &[(String, crate::sema::types::Type)],
) -> Option<String> {
use cpp_parser::{CppAstNode, CppExpr};
match expression {
CppExpr::ParenExpr(paren) => type_with_the_auto_parameters(&paren.get_expr()?, paired),
CppExpr::NameExpr(name) => {
let written = name.get_name_text()?;
paired
.iter()
.find(|(known, _)| *known == written)
.map(|(_, type_of)| type_of.to_string())
}
CppExpr::LiteralExpr(literal) => {
Some(literal_type(&literal.get_literal_text()?).to_string())
}
CppExpr::InitListExpr(list) => {
let head = list.get_constructed_type()?;
Some(cpp_parser::subtree_text_spaced(head.syntax()))
}
CppExpr::BinaryExpr(binary) => {
if is_a_comparison(binary) {
return Some("bool".to_string());
}
let left_type = type_with_the_auto_parameters(&binary.get_lhs()?, paired)?;
let right_type = type_with_the_auto_parameters(&binary.get_rhs()?, paired)?;
if left_type == right_type {
return Some(left_type);
}
let floating = |written: &str| written.contains("float") || written.contains("double");
match (floating(&left_type), floating(&right_type)) {
(true, true) => Some(if left_type.len() >= right_type.len() {
left_type
} else {
right_type
}),
(true, false) => Some(left_type),
(false, true) => Some(right_type),
(false, false) => None,
}
}
_ => None,
}
}
fn the_returns_of(
body: &cpp_parser::CppCompoundStat,
owner: &CppSyntaxNode,
) -> Vec<cpp_parser::CppReturnStat> {
use cpp_parser::{CppAstNode, CppDeclaration, CppLambdaExpr, CppReturnStat};
body.descendants::<CppReturnStat>()
.filter(|statement| {
cpp_parser::typed_ancestors_until::<CppLambdaExpr>(statement.syntax(), owner)
.next()
.is_none()
&& cpp_parser::typed_ancestors_until::<CppDeclaration>(statement.syntax(), owner)
.all(|declaration| declaration.get_body().is_none())
})
.collect()
}
fn returned_expressions_in(body: &cpp_parser::CppCompoundStat) -> Vec<cpp_parser::CppExpr> {
use cpp_parser::CppAstNode;
the_returns_of(body, body.syntax())
.into_iter()
.filter_map(|statement| statement.get_expr())
.collect()
}
pub(crate) fn the_widest_of(types: &[crate::sema::types::Type]) -> Option<String> {
let mut widest: Option<(u8, String)> = None;
for a_type in types {
let spelling = a_type.to_string();
let rank = match spelling.trim() {
"long double" => 6,
"double" => 5,
"float" => 4,
"unsigned long long" | "long long" | "long long int" | "unsigned long long int" => 3,
"unsigned long" | "long" | "long int" | "unsigned long int" | "signed long" => 2,
"bool" | "char" | "signed char" | "unsigned char" | "short" | "unsigned short"
| "int" | "unsigned" | "unsigned int" | "signed int" | "short int"
| "unsigned short int" | "signed short" | "signed short int" | "size_t"
| "std::size_t" | "ptrdiff_t" | "wchar_t" | "char8_t" | "char16_t" | "char32_t" => 1,
_ => return None,
};
match &widest {
Some((widest_rank, _)) if *widest_rank >= rank => {}
_ => widest = Some((rank, spelling.trim().to_string())),
}
}
let (rank, spelling) = widest?;
if rank == 1 && spelling != "size_t" && spelling != "std::size_t" && spelling != "ptrdiff_t" {
return Some("int".to_string());
}
Some(spelling)
}
fn a_data_member_type(expression: &CppSyntaxNode, declaration: &CppSyntaxNode) -> Option<String> {
use cpp_parser::{CppAstNode, CppClassBody, CppDeclaration, CppNameExpr};
const MOST_MEMBERS_AN_ACCESSOR_CLASS_HAS: usize = 64;
let name = CppNameExpr::cast(expression.clone())?.get_name_text()?;
let body = cpp_parser::typed_ancestors::<CppClassBody>(declaration).next()?;
for (seen, member) in body.children::<CppDeclaration>().enumerate() {
if seen >= MOST_MEMBERS_AN_ACCESSOR_CLASS_HAS {
return None;
}
if let Some(the_type) = member.get_type_text_of(&name) {
return Some(the_type);
}
}
None
}
fn type_a_return_states_with(
expression: &cpp_parser::CppExpr,
declaration: &CppSyntaxNode,
substitutions: &crate::sema::types::TypeSubstitutions<'_>,
argument_types: &[crate::sema::types::Type],
) -> Option<String> {
use cpp_parser::{CppAstNode, CppExpr};
match expression {
CppExpr::ParenExpr(paren) => type_a_return_states_with(
&paren.get_expr()?,
declaration,
substitutions,
argument_types,
),
CppExpr::NameExpr(name) => {
let written = parameter_type(name.syntax(), declaration)
.or_else(|| a_data_member_type(name.syntax(), declaration))
.or_else(|| a_local_variables_type(name.syntax(), declaration))
.or_else(|| a_captures_type(name.syntax()))?;
Some(substituted_spelling(&written, substitutions))
}
CppExpr::BinaryExpr(binary) => {
if binary.get_fold().is_some()
&& let Some(widest) = the_widest_of(argument_types)
{
return Some(widest);
}
if is_a_comparison(binary) {
return Some("bool".to_string());
}
let left_type = type_a_return_states_with(
&binary.get_lhs()?,
declaration,
substitutions,
argument_types,
)?;
let right_type = type_a_return_states_with(
&binary.get_rhs()?,
declaration,
substitutions,
argument_types,
)?;
if left_type == right_type {
return Some(left_type);
}
if matches!(binary.get_operator_text().as_deref(), Some("+" | "-")) {
if is_a_literal_zero(&binary.get_rhs()?) {
return Some(left_type);
}
if is_a_literal_zero(&binary.get_lhs()?) {
return Some(right_type);
}
}
None
}
_ => type_a_return_states(expression, declaration),
}
}
fn type_a_return_states(
expression: &cpp_parser::CppExpr,
declaration: &CppSyntaxNode,
) -> Option<String> {
use cpp_parser::{CppAstNode, CppExpr};
match expression {
CppExpr::CastExpr(cast) => {
let written = cast.get_type_id()?.get_type_text();
(!written.is_empty()).then_some(written)
}
CppExpr::InitListExpr(list) => {
let head = list.get_constructed_type()?;
let written = cpp_parser::subtree_text_spaced(head.syntax());
(!written.is_empty()).then_some(written)
}
CppExpr::LiteralExpr(literal) => {
Some(literal_type(&literal.get_literal_text()?).to_string())
}
CppExpr::NameExpr(name) => parameter_type(name.syntax(), declaration)
.or_else(|| a_data_member_type(name.syntax(), declaration))
.or_else(|| a_local_variables_type(name.syntax(), declaration))
.or_else(|| a_captures_type(name.syntax())),
CppExpr::BinaryExpr(binary) => {
if is_a_comparison(binary) {
return Some("bool".to_string());
}
let left_type = type_a_return_states(&binary.get_lhs()?, declaration)?;
let right_type = type_a_return_states(&binary.get_rhs()?, declaration)?;
if left_type == right_type {
return Some(left_type);
}
if matches!(binary.get_operator_text().as_deref(), Some("+" | "-")) {
if is_a_literal_zero(&binary.get_rhs()?) {
return Some(left_type);
}
if is_a_literal_zero(&binary.get_lhs()?) {
return Some(right_type);
}
}
None
}
_ => None,
}
}
fn literal_type(written: &str) -> &'static str {
let trimmed = written.trim();
if trimmed == "true" || trimmed == "false" {
return "bool";
}
if trimmed == "nullptr" {
return "nullptr_t";
}
if trimmed.starts_with('"') || trimmed.starts_with("'") {
return "const char*";
}
let looks_like_a_float = trimmed.contains('.')
|| (trimmed.contains('e') || trimmed.contains('E')) && !trimmed.starts_with("0x");
if looks_like_a_float {
return "double";
}
"int"
}
fn parameter_type(name: &CppSyntaxNode, declaration: &CppSyntaxNode) -> Option<String> {
use cpp_parser::{CppAstNode, CppNameExpr};
let written = CppNameExpr::cast(name.clone())?.get_name_text()?;
let parameter = the_parameters_of(declaration)
.into_iter()
.find(|parameter| parameter.get_name_text().as_deref() == Some(written.as_str()))?;
let the_type = parameter.get_type_text();
(!the_type.is_empty()).then_some(the_type)
}
fn a_captures_type(expression: &CppSyntaxNode) -> Option<String> {
use cpp_parser::{CppAstNode, CppDeclaration, CppLambdaExpr, CppNameExpr};
let written = CppNameExpr::cast(expression.clone())?.get_name_text()?;
let lambda = cpp_parser::typed_ancestors::<CppLambdaExpr>(expression).next()?;
let capture = lambda
.get_captures()?
.get_captures()
.find(|capture| capture.get_name_text().as_deref() == Some(written.as_str()))?;
let initializer = capture.get_initializer()?;
let enclosing = cpp_parser::typed_ancestors::<CppDeclaration>(lambda.syntax()).last()?;
type_a_return_states_with(
&initializer,
enclosing.syntax(),
&crate::sema::types::TypeSubstitutions::new(&[], &[]),
&[],
)
}
fn a_local_variables_type(
expression: &CppSyntaxNode,
declaration: &CppSyntaxNode,
) -> Option<String> {
use cpp_parser::{CppAstNode, CppNameExpr};
let name = CppNameExpr::cast(expression.clone())?;
let written = name.get_name_text()?;
let mut found: Option<String> = None;
for candidate in the_declarations_in(declaration) {
if candidate.get_range().end() > name.get_range().start() {
continue;
}
if !a_block_statement_encloses(candidate.syntax(), name.syntax()) {
continue;
}
if let Some(the_type) = candidate.get_type_text_of(&written) {
found = Some(the_type);
}
}
found
}
fn a_block_statement_encloses(declaration: &CppSyntaxNode, expression: &CppSyntaxNode) -> bool {
use cpp_parser::{CppAstNode, CppCompoundStat};
let Some(block) = cpp_parser::typed_ancestors::<CppCompoundStat>(declaration).next() else {
return true;
};
block.get_range().contains_range(expression.text_range())
}
pub(crate) fn declared_returns_of_in(
shapes: &DeclarationShapes,
root: &CppSyntaxNode,
binding: &Binding,
) -> Option<String> {
let written = declared_returns_of_with(shapes, binding);
if let Some(spelling) = written {
if binding.kind != BindingKind::OperatorFunction
|| an_operator_return_is_usable(root, binding, &spelling)
{
return Some(spelling);
}
return deduced_returns_of(root, binding);
}
deduced_returns_of(root, binding)
}
fn an_operator_return_is_usable(root: &CppSyntaxNode, binding: &Binding, spelling: &str) -> bool {
fn means_the_same_everywhere(kind: &crate::sema::types::Type) -> bool {
use crate::sema::types::Type;
match kind {
Type::Builtin { .. } => true,
Type::Named { name, arguments } => {
name.contains("::") && arguments.iter().all(means_the_same_everywhere)
}
Type::Pointer { to }
| Type::Qualified { of: to }
| Type::Reference { to, .. }
| Type::Array { of: to, .. } => means_the_same_everywhere(to),
_ => false,
}
}
if means_the_same_everywhere(&crate::sema::types::parse_type_spelling(spelling)) {
return true;
}
let Some(head) = crate::sema::types::parse_type_spelling(spelling)
.class_name()
.map(str::to_string)
else {
return true;
};
!the_enclosing_body_declares(root, binding, &head)
}
fn the_enclosing_body_declares(root: &CppSyntaxNode, binding: &Binding, name: &str) -> bool {
use cpp_parser::CppAstNode;
let Some(declaration) = declaration_of(root, binding) else {
return false;
};
let Some(body) = cpp_parser::typed_ancestors::<cpp_parser::CppClassBody>(&declaration).next()
else {
return false;
};
body.syntax()
.descendants()
.filter_map(cpp_parser::CppDeclaration::cast)
.filter(|declaration| {
matches!(
CppSyntaxKind::from(declaration.syntax().kind()),
CppSyntaxKind::UsingDecl | CppSyntaxKind::TypedefDecl
)
})
.any(|declaration| {
declaration
.get_name()
.is_some_and(|introduced| introduced.get_name_text() == name)
})
}
pub(crate) fn declared_returns_of_with(
shapes: &DeclarationShapes,
binding: &Binding,
) -> Option<String> {
let spelled = binding.name.text();
if let Some(target) = spelled.trim().strip_prefix("operator ").map(str::trim)
&& !target.is_empty()
{
return Some(target.to_string());
}
if !matches!(
binding.kind,
BindingKind::Function | BindingKind::OperatorFunction
) {
return None;
}
let mut specifiers = None;
let mut trailing = None;
let mut declarator = None;
shapes.on_the_path(the_offset_to_descend_by(binding), |shape| {
if let Some(node) = &shape.specifiers {
specifiers = Some(node.clone());
}
if let Some(node) = &shape.trailing
&& let Some(type_id) = cpp_parser::typed_children::<cpp_parser::CppTypeId>(node).next()
{
let spelling = type_id.get_type_text().trim().to_string();
if !spelling.is_empty() {
trailing = Some(spelling);
}
}
if declarator.is_none()
&& let Some(node) = &shape.declarator
{
declarator = Some(node.clone());
}
});
if let Some(trailing) = trailing {
let spelling = trailing.trim().to_string();
return (!spelling.is_empty()).then_some(spelling);
}
let before_the_name = declarator
.as_ref()
.map(|declarator| {
before(
&declarator.text().to_string(),
declarator,
binding.name_range,
)
})
.filter(|operators| {
operators
.chars()
.all(|c| c == '*' || c == '&' || c.is_whitespace())
})
.unwrap_or_default();
let specifiers = specifiers?;
let declared = binding.name.text();
let spelling = if specifiers.text().is_empty() {
String::new()
} else {
crate::sema::types::read_specifiers_named(
&specifiers,
Some(declared.as_str()),
cpp_parser::source_range(specifiers.text_range()),
)
.to_string()
};
let spelling = format!("{spelling} {before_the_name}");
let spelling = spelling.split_whitespace().collect::<Vec<_>>().join(" ");
if spelling == "auto" || spelling == "decltype(auto)" {
return None;
}
(!spelling.is_empty()).then_some(spelling)
}
fn before(text: &str, node: &CppSyntaxNode, name: cpp_parser::SourceRange) -> String {
if name.length == 0 {
return String::new();
}
let start = usize::from(node.text_range().start());
let to = name.start_offset.saturating_sub(start);
if to > text.len() || !text.is_char_boundary(to) {
return String::new();
}
text[..to].trim().to_string()
}
pub fn declared_access_at(root: &CppSyntaxNode, offset: usize) -> Option<Access> {
let token = cpp_parser::token_at(root, offset)?;
use cpp_parser::{
CppAccessSpecifier, CppAstNode, CppClassBody, CppClassDef, CppKind, CppTokenKind,
};
let body = cpp_parser::typed_ancestors::<CppClassBody>(&token.parent()?).next()?;
let default =
body.syntax()
.parent()
.and_then(CppClassDef::cast)
.map_or(Access::Private, |class| {
if class.is_struct() || class.is_union() {
Access::Public
} else {
Access::Private
}
});
let mut level = default;
for child in body.syntax().children() {
if usize::from(child.text_range().start()) >= offset {
break;
}
let Some(label) = CppAccessSpecifier::cast(child) else {
continue;
};
let Some(keyword) = label.get_keyword() else {
continue;
};
level = match keyword.get_keyword_kind() {
CppKind::Token(CppTokenKind::PublicKeyword) => Access::Public,
CppKind::Token(CppTokenKind::ProtectedKeyword) => Access::Protected,
CppKind::Token(CppTokenKind::PrivateKeyword) => Access::Private,
_ => continue,
};
}
Some(level)
}
pub fn declared_exported_at(root: &CppSyntaxNode, offset: usize) -> bool {
let Some(token) = cpp_parser::token_at(root, offset) else {
return false;
};
token
.parent_ancestors()
.any(|node| begins_an_exported_region(&node))
}
fn begins_an_exported_region(node: &CppSyntaxNode) -> bool {
if node.parent().is_none() {
return false;
}
let starts_with_export = cpp_parser::first_significant_token(node).is_some_and(|token| {
cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::ExportKeyword
});
if starts_with_export {
return true;
}
let mut previous = node.prev_sibling_or_token();
while let Some(element) = previous {
if let Some(token) = element.as_token() {
if cpp_parser::is_trivia(cpp_parser::CppTokenKind::from(token.kind())) {
previous = token.prev_sibling_or_token();
continue;
}
return cpp_parser::CppTokenKind::from(token.kind())
== cpp_parser::CppTokenKind::ExportKeyword;
}
return false;
}
false
}
pub fn parameter_list_at(root: &CppSyntaxNode, offset: usize) -> Option<String> {
let token = cpp_parser::token_at(root, offset)?;
use cpp_parser::CppAstNode;
let declarator =
cpp_parser::typed_ancestors::<cpp_parser::CppDeclarator>(&token.parent()?).next()?;
crate::inlay::parameter_list_text(declarator.syntax())
}
pub(crate) fn declared_parameters_with(
shapes: &DeclarationShapes,
binding: &Binding,
) -> Option<String> {
let mut found = None;
shapes.on_the_path(binding.name_range.start_offset, |shape| {
if let Some(declarator) = &shape.declarator
&& names_the_binding(declarator, binding.name_range.start_offset)
{
found = Some(declarator.clone());
}
});
crate::inlay::parameter_list_text(&found?)
}
fn names_the_binding(declarator: &CppSyntaxNode, offset: usize) -> bool {
use cpp_parser::CppAstNode;
let at = u32::try_from(offset).unwrap_or(u32::MAX);
cpp_parser::typed_children::<cpp_parser::CppNameExpr>(declarator).any(|name| {
let range = name.get_range();
u32::from(range.start()) <= at && at < u32::from(range.end())
})
}
pub fn declared_template_parameters_of(root: &CppSyntaxNode, binding: &Binding) -> Vec<String> {
declared_template_parameters_with(&DeclarationShapes::of(root), binding)
}
pub fn declared_parameter_defaults_of(root: &CppSyntaxNode, binding: &Binding) -> Vec<String> {
declared_parameter_defaults_with(&DeclarationShapes::of(root), binding)
}
pub(crate) fn declared_template_parameters_with(
shapes: &DeclarationShapes,
binding: &Binding,
) -> Vec<String> {
if !matches!(
binding.kind,
BindingKind::Class
| BindingKind::Function
| BindingKind::Constructor
| BindingKind::Destructor
| BindingKind::ConversionFunction
| BindingKind::OperatorFunction
| BindingKind::LiteralOperator
| BindingKind::Variable
| BindingKind::Alias
| BindingKind::Typedef
) {
return Vec::new();
}
let at = binding.name_range.start_offset;
match shapes.template_at(at) {
Some(shared) => shared.iter().map(|(name, _, _)| name.clone()).collect(),
None => Vec::new(),
}
}
fn declared_constraints_with(shapes: &DeclarationShapes, binding: &Binding) -> Vec<String> {
let at = binding.name_range.start_offset;
let Some(shared) = shapes.template_at(at) else {
return Vec::new();
};
let constrained: Vec<(String, String)> = shared
.iter()
.filter(|(_, constraint, _)| !constraint.is_empty())
.map(|(name, constraint, _)| (name.clone(), constraint.clone()))
.collect();
if constrained.is_empty() {
return Vec::new();
}
let mut declarator = None;
shapes.on_the_path(at, |shape| {
if let Some(found) = &shape.declarator {
declarator = Some(found.clone());
}
});
let Some(declarator) = declarator else {
return Vec::new();
};
use cpp_parser::CppAstNode;
let Some(declarator) = cpp_parser::CppDeclarator::cast(declarator) else {
return Vec::new();
};
let Some(list) = declarator.get_param_list() else {
return Vec::new();
};
let mut per_parameter = Vec::new();
for parameter in list.get_params() {
let written = parameter
.get_decl_specifiers()
.and_then(|specifiers| specifiers.get_type_name())
.and_then(|name| name.get_name_text());
let constraint = constrained
.iter()
.find(|(name, _)| written.as_deref() == Some(name.as_str()))
.map(|(_, constraint)| constraint.clone())
.unwrap_or_default();
per_parameter.push(constraint);
}
per_parameter
}
pub fn declared_bases_of(root: &CppSyntaxNode, binding: &Binding) -> Vec<String> {
declared_bases_of_with(&DeclarationShapes::of(root), binding)
}
pub(crate) fn declared_bases_of_with(shapes: &DeclarationShapes, binding: &Binding) -> Vec<String> {
use cpp_parser::CppAstNode;
if binding.kind != BindingKind::Class {
return Vec::new();
}
let mut owner = None;
shapes.on_the_path(the_offset_to_descend_by(binding), |shape| {
if cpp_parser::CppClassDef::can_cast(shape.kind) || shape.kind == CppSyntaxKind::EnumDef {
owner = Some(shape.bases.clone());
}
});
let Some(bases) = owner else {
return Vec::new();
};
bases
.iter()
.map(cpp_parser::subtree_text_spaced)
.filter(|name| !name.is_empty())
.collect()
}
const DECLARATION_SPECIFIERS: &[&str] = &[
"static",
"extern",
"inline",
"virtual",
"explicit",
"friend",
"mutable",
"register",
"thread_local",
"constexpr",
"consteval",
"constinit",
"typedef",
"const",
"volatile",
"struct",
"class",
"union",
"enum",
];
fn strip_declaration_specifiers(spelling: &str) -> String {
let mut rest = spelling.trim();
loop {
let Some(word) = rest.split_whitespace().next() else {
return String::new();
};
if !DECLARATION_SPECIFIERS.contains(&word) || word.len() == rest.len() {
return rest.trim().to_string();
}
rest = rest[word.len()..].trim_start();
}
}
fn fact_for(
root: &CppSyntaxNode,
shapes: &DeclarationShapes,
binding: &Binding,
scope: Option<String>,
local: bool,
in_namespace: Option<String>,
declarations: &Declarations<'_>,
) -> Option<DeclFact> {
let name = binding.name.text();
let (name, scope) = match name.rsplit_once("::") {
Some((qualifier, last)) if !local && !qualifier.is_empty() && !last.is_empty() => (
last.to_string(),
Some(qualifier.trim_start_matches("::").to_string()),
),
_ => (name, scope),
};
let split_by_a_directive = split_by_a_directive_with(shapes, binding);
let type_of = if split_by_a_directive {
None
} else {
declared_type_of_with(shapes, binding)
.or_else(|| declared_alias_target_with(shapes, binding))
.or_else(|| declared_namespace_alias_target_with(root, binding))
};
let returns = {
if split_by_a_directive {
None
} else {
declared_returns_of_with(shapes, binding)
.filter(|spelling| {
binding.kind != BindingKind::OperatorFunction
|| an_operator_return_is_usable(root, binding, spelling)
})
.or_else(|| deduced_returns_of(root, binding))
}
};
let bases = { declared_bases_of_with(shapes, binding) };
let parameters = { declared_template_parameters_with(shapes, binding) };
let constraints = { declared_constraints_with(shapes, binding) };
let parameter_defaults = { declared_parameter_defaults_with(shapes, binding) };
let access = shapes.access_at(the_offset_to_descend_by(binding));
let exported = shapes.exported_at(the_offset_to_descend_by(binding));
let parameter_list = match binding.kind {
BindingKind::Function
| BindingKind::Constructor
| BindingKind::Destructor
| BindingKind::ConversionFunction
| BindingKind::OperatorFunction
| BindingKind::LiteralOperator => declared_parameters_with(shapes, binding),
_ => None,
};
let parameter_list = parameter_list.or_else(|| {
if !matches!(
binding.kind,
BindingKind::Constructor | BindingKind::Destructor | BindingKind::ConversionFunction
) {
return None;
}
use cpp_parser::CppAstNode;
let token = cpp_parser::token_at(root, binding.range.start_offset)?;
let parent = token.parent()?;
let declaration = std::iter::once(parent.clone())
.chain(parent.ancestors())
.find(|node| cpp_parser::CppDeclaration::can_cast(node.kind().into()))?;
let declaration = cpp_parser::CppDeclaration::cast(declaration)?;
let list = declaration.get_param_list()?;
Some(list.syntax().text().to_string())
});
let in_namespace = if local { in_namespace } else { None };
let pattern = pattern_of(shapes, binding);
Some(DeclFact {
kind: DeclKind::from_binding_kind(binding.kind),
modifiers: declared_modifiers_with(shapes, binding),
requires_clause: the_requires_clause_with(shapes, binding),
frees: 0,
reflection: None,
name,
scope,
local,
in_namespace,
type_of,
returns,
split_by_a_directive,
bases,
parameters,
constraints,
parameter_defaults,
pattern,
parameter_list,
access,
exported,
range: binding.range,
name_range: binding.name_range,
clean: declarations.is_clean(binding.name_range, binding.range),
definition: declarations.declares_a_body(binding.name_range),
guard: FactGuard::Unconditional,
})
}
pub(crate) fn declared_parameter_defaults_with(
shapes: &DeclarationShapes,
binding: &Binding,
) -> Vec<String> {
let at = binding.name_range.start_offset;
if shapes.template_at(at).is_none() {
return Vec::new();
}
let Some(shared) = shapes.template_at(at) else {
return Vec::new();
};
if shared.iter().any(|(_, _, default)| default.is_some()) {
shared
.iter()
.map(|(_, _, default)| default.clone().unwrap_or_default())
.collect()
} else {
Default::default()
}
}
fn class_head_of(declaration: &CppSyntaxNode) -> String {
let mut head = String::new();
for child in declaration.children_with_tokens() {
if let Some(token) = child.as_token() {
head.push_str(token.text());
} else if let Some(node) = child.as_node() {
if node.first_token().is_some_and(|token| token.text() == "{") {
break;
}
head.push_str(&node.text().to_string());
}
if head.contains(['{', ';']) {
break;
}
}
head
}
pub(crate) fn pattern_of(shapes: &DeclarationShapes, binding: &Binding) -> Option<String> {
let mut found = None;
shapes.on_the_path(the_offset_to_descend_by(binding), |shape| {
if matches!(
shape.kind,
CppSyntaxKind::ClassDef | CppSyntaxKind::StructDef | CppSyntaxKind::UnionDef
) {
found = shape.pattern.clone();
}
});
found
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LocalReferences {
pub declared_at: u32,
pub uses: Vec<u32>,
}
pub fn local_references_of(scopes: &ScopeTree, root: &CppSyntaxNode) -> Vec<LocalReferences> {
let Some(file_scope) = scopes
.scopes()
.iter()
.position(|scope| scope.parent.is_none())
.map(ScopeId)
else {
return Vec::new();
};
let mut declared: HashSet<usize> = HashSet::new();
for scope in scopes.scopes() {
for binding in &scope.bindings {
declared.insert(binding.name_range.start_offset);
}
}
let mut found: HashMap<u32, Vec<u32>> = HashMap::new();
let mut by_name: HashMap<usize, HashMap<String, &Binding>> = HashMap::new();
for (index, scope) in scopes.scopes().iter().enumerate() {
let mut names: HashMap<String, &Binding> = HashMap::new();
for binding in &scope.bindings {
names.entry(binding.name.text()).or_insert(binding);
}
by_name.insert(index, names);
}
for element in root.descendants_with_tokens() {
let Some(token) = element.as_token() else {
continue;
};
if cpp_parser::CppTokenKind::from(token.kind()) != cpp_parser::CppTokenKind::Identifier {
continue;
}
let at = usize::from(token.text_range().start());
if declared.contains(&at) {
continue;
}
let name = token.text();
if name.is_empty() {
continue;
}
let Some(binding) = binding_for(scopes, &by_name, file_scope, at, name) else {
continue;
};
if !matches!(
scopes
.scope(binding.scope)
.map(|scope| scope.kind)
.unwrap_or(ScopeKind::TranslationUnit),
ScopeKind::Function | ScopeKind::Block | ScopeKind::Lambda
) {
continue;
}
found
.entry(binding.name_range.start_offset as u32)
.or_default()
.push(at as u32);
}
let mut references: Vec<LocalReferences> = found
.into_iter()
.map(|(declared_at, uses)| LocalReferences { declared_at, uses })
.collect();
references.sort_by_key(|entry| entry.declared_at);
references
}
fn binding_for<'a>(
scopes: &'a ScopeTree,
by_name: &HashMap<usize, HashMap<String, &'a Binding>>,
file_scope: ScopeId,
at: usize,
name: &str,
) -> Option<&'a Binding> {
let mut current = file_scope;
while let Some(child) = scopes.scope(current).and_then(|scope| {
scope.children.iter().copied().find(|child| {
scopes
.scope(*child)
.and_then(|scope| scope.range)
.is_some_and(|range| at >= range.start_offset && at < range.end_offset())
})
}) {
current = child;
}
let mut scope = Some(current);
while let Some(id) = scope {
let data = scopes.scope(id)?;
if let Some(binding) = by_name.get(&id.index()).and_then(|names| names.get(name)) {
return Some(binding);
}
scope = data.parent;
}
None
}
fn written_class_pattern(declaration: &CppSyntaxNode) -> Option<String> {
let text = class_head_of(declaration);
let head = text
.find(['{', ';'])
.map(|end| &text[..end])
.unwrap_or(&text[..]);
let mut at = 0usize;
let mut found = None;
for (index, _) in head.match_indices(|character: char| character.is_alphabetic()) {
if index < at {
continue;
}
let word = &head[index..];
let end = word
.find(|character: char| !character.is_alphanumeric() && character != '_')
.unwrap_or(word.len());
let word = &word[..end];
if matches!(word, "class" | "struct" | "union") {
found = Some(index + end);
}
at = index + end.max(1);
}
let after = &head[found?..];
let end = after.find([':', '{', ';']).unwrap_or(after.len());
let written = after[..end].trim();
written.contains('<').then(|| written.to_string())
}
fn enclosing_namespaces_of(scopes: &ScopeTree, from: ScopeId) -> Option<String> {
let mut segments: Vec<&str> = Vec::new();
for id in scopes.scope_chain(from) {
let Some(data) = scopes.scope(id) else {
continue;
};
if data.kind == ScopeKind::Namespace
&& let Some(name) = data.name.as_deref()
{
segments.push(name);
}
}
if segments.is_empty() {
return None;
}
segments.reverse();
segments.dedup();
Some(segments.join("::"))
}
struct Declarations<'a> {
by_start: Vec<(usize, usize, bool, bool)>, errors: &'a [SourceRange],
}
impl<'a> Declarations<'a> {
fn of(root: &CppSyntaxNode, errors: &'a [SourceRange]) -> Self {
let mut by_start: Vec<(usize, usize, bool, bool)> = Vec::new();
let mut bodies: Vec<(usize, usize)> = Vec::new();
for node in root.descendants() {
let kind = CppSyntaxKind::from(node.kind());
if matches!(kind, CppSyntaxKind::ClassBody | CppSyntaxKind::CompoundStat) {
let range = cpp_parser::source_range(node.text_range());
bodies.push((range.start_offset, range.end_offset()));
}
}
bodies.sort_unstable();
{
for node in root.descendants() {
let kind = CppSyntaxKind::from(node.kind());
if !crate::scopes::declaring_kinds().contains(&kind) {
continue;
}
let range = cpp_parser::source_range(node.text_range());
let start = bodies.partition_point(|(body, _)| *body < range.start_offset);
let has_body = bodies[start..]
.iter()
.take_while(|(body, _)| *body < range.end_offset())
.any(|(body, end)| *body >= range.start_offset && *end <= range.end_offset());
by_start.push((
range.start_offset,
range.end_offset(),
has_body,
errors.iter().any(|error| {
error.start_offset < range.end_offset()
&& range.start_offset < error.end_offset()
}),
));
}
}
by_start.sort_unstable_by_key(|(start, _, _, _)| *start);
Declarations { by_start, errors }
}
fn declares_a_body(&self, name_range: SourceRange) -> bool {
match self.innermost_at(name_range) {
Some((has_body, _)) => has_body,
None => false,
}
}
fn innermost_at(&self, name_range: SourceRange) -> Option<(bool, bool)> {
let at = self
.by_start
.partition_point(|(start, _, _, _)| *start <= name_range.start_offset);
for index in (0..at).rev() {
let (_, end, has_body, touched) = self.by_start[index];
if end > name_range.start_offset {
return Some((has_body, touched));
}
}
None
}
fn is_clean(&self, name_range: SourceRange, own_range: SourceRange) -> bool {
match self.innermost_at(name_range) {
Some((_, touched)) => !touched,
None => !self.errors.iter().any(|error| overlaps(*error, own_range)),
}
}
}
fn contains(outer: SourceRange, inner: SourceRange) -> bool {
outer.start_offset <= inner.start_offset && inner.end_offset() <= outer.end_offset()
}
fn overlaps(one: SourceRange, other: SourceRange) -> bool {
one.start_offset < other.end_offset() && other.start_offset < one.end_offset()
}
struct DeclarationFacts<'a> {
scopes: &'a ScopeTree,
preprocessing: &'a FilePreprocessing,
root: &'a CppSyntaxNode,
shapes: DeclarationShapes,
declarations: Declarations<'a>,
guards: SummaryGuards,
facts: Vec<DeclFact>,
keep_locals: bool,
}
impl<'a> DeclarationFacts<'a> {
fn new(
scopes: &'a ScopeTree,
preprocessing: &'a FilePreprocessing,
root: &'a CppSyntaxNode,
errors: &'a [SourceRange],
keep_locals: bool,
) -> Self {
DeclarationFacts {
keep_locals,
scopes,
preprocessing,
root,
shapes: {
let built = DeclarationShapes::of(root);
#[cfg(feature = "perf-probe")]
crate::perf::mark("shapes");
built
},
declarations: {
let built = Declarations::of(root, errors);
#[cfg(feature = "perf-probe")]
crate::perf::mark("declarations");
built
},
guards: SummaryGuards::default(),
facts: Vec::new(),
}
}
fn build(self) -> (Vec<DeclFact>, SummaryGuards) {
let DeclarationFacts {
keep_locals,
scopes,
preprocessing,
root,
shapes,
declarations,
mut guards,
mut facts,
} = self;
let rendered = root.text().to_string();
let walking = std::time::Instant::now();
for (index, scope) in scopes.scopes().iter().enumerate() {
let id = ScopeId(index);
if scope.kind == ScopeKind::TemplateParameters {
continue;
}
if scope.bindings.is_empty() {
continue;
}
let local = match scope.kind {
ScopeKind::Function | ScopeKind::Block | ScopeKind::Lambda => true,
_ => scopes.declares_a_local(id),
};
if local && !keep_locals {
continue;
}
let prefix = if local {
None
} else {
scopes.qualification_prefix_of(id)
};
let in_namespace = local.then(|| enclosing_namespaces_of(scopes, id)).flatten();
for binding in &scope.bindings {
if let Some(fact) = fact_for(
root,
&shapes,
binding,
prefix.clone(),
local,
in_namespace.clone(),
&declarations,
) {
facts.push(fact);
}
}
}
let walked = walking.elapsed();
#[cfg(feature = "perf-probe")]
crate::perf::mark("facts loop");
let qualifying = std::time::Instant::now();
let mut by_offset: std::collections::HashMap<usize, usize> =
std::collections::HashMap::with_capacity(facts.len());
for (at, fact) in facts.iter().enumerate() {
by_offset.entry(fact.name_range.start_offset).or_insert(at);
}
let qualified = qualified_declarations(root);
let qualified_count = qualified.len();
for (binding, scope, parameters) in qualified {
if let Some(&at) = by_offset.get(&binding.name_range.start_offset) {
let existing = &mut facts[at];
if existing.scope.is_none() {
existing.scope = Some(scope);
}
existing.range = binding.range;
continue;
}
if let Some(mut fact) = fact_for(
root,
&shapes,
&binding,
Some(scope),
false,
None,
&declarations,
) {
if fact.parameter_list.is_none() {
fact.parameter_list = parameters;
}
by_offset
.entry(fact.name_range.start_offset)
.or_insert(facts.len());
facts.push(fact);
}
}
facts.sort_by_key(|fact| fact.range.start_offset);
let freeing = std::time::Instant::now();
fill_the_frees(root, &mut facts);
let freed = freeing.elapsed();
#[cfg(feature = "perf-probe")]
crate::perf::mark("frees");
let reflecting = std::time::Instant::now();
fill_the_reflection(root, &rendered, &mut facts);
let reflected = reflecting.elapsed();
#[cfg(feature = "perf-probe")]
crate::perf::mark("reflection");
let mut targets: Vec<(&mut FactGuard, usize)> = facts
.iter_mut()
.map(|fact| (&mut fact.guard, fact.range.start_offset))
.collect();
let guarding = std::time::Instant::now();
assign_guards(&mut targets, preprocessing, &mut guards);
let guarded = guarding.elapsed();
#[cfg(feature = "perf-probe")]
crate::perf::mark("guards");
if crate::probes::units() {
eprintln!(
"[unit] scopes+facts {:>6.1} ms qualified {:.1} ms ({} declaration(s)) frees {:>6.1} ms \
reflection {:.1} ms guards {:.1} ms",
walked.as_secs_f64() * 1000.0,
qualifying.elapsed().as_secs_f64() * 1000.0,
qualified_count,
freed.as_secs_f64() * 1000.0,
reflected.as_secs_f64() * 1000.0,
guarded.as_secs_f64() * 1000.0
);
}
(facts, guards)
}
}
fn qualified_declarations(root: &CppSyntaxNode) -> Vec<(Binding, String, Option<String>)> {
use cpp_parser::{
CppAstNode, CppAstToken, CppCompoundStat, CppDeclaration, CppDeclarator, CppNameExpr,
};
let mut found = Vec::new();
for declaration in cpp_parser::typed_descendants::<CppDeclaration>(root) {
if cpp_parser::typed_ancestors::<CppCompoundStat>(declaration.syntax()).any(|compound| {
compound
.syntax()
.parent()
.is_none_or(|parent| !cpp_parser::CppNamespaceDecl::can_cast(parent.kind().into()))
}) {
continue;
}
let Some(declarator) = declaration
.get_init_declarator()
.and_then(|init| init.get_declarator())
.or_else(|| declaration.child::<CppDeclarator>())
else {
continue;
};
let names_itself = declarator.get_name().is_some();
let from_the_declarator = declarator
.child::<CppNameExpr>()
.filter(CppNameExpr::is_qualified);
let from_the_specifiers = (!names_itself)
.then(|| {
declaration.get_decl_specifiers().and_then(|specifiers| {
specifiers
.descendants::<CppNameExpr>()
.filter(CppNameExpr::is_qualified)
.last()
})
})
.flatten();
let name_node = match (from_the_declarator, from_the_specifiers) {
(Some(found), _) => found,
(None, Some(found)) => found,
(None, None) => continue,
};
let spelling = name_node.get_qualified_name();
let Some((qualifier, name)) = spelling.rsplit_once("::") else {
continue;
};
let qualifier = qualifier.trim();
let name = name.trim();
if qualifier.is_empty() || name.is_empty() {
continue;
}
let name_range = name_node
.get_identifier_token(name)
.map(|token| cpp_parser::source_range(token.get_range()))
.unwrap_or_else(|| cpp_parser::source_range(name_node.get_range()));
let has_parameters = declaration.get_param_list().is_some();
let class = qualifier.rsplit("::").next().unwrap_or(qualifier).trim();
let kind = if name.starts_with('~') {
crate::BindingKind::Destructor
} else if name.starts_with("operator") {
crate::BindingKind::OperatorFunction
} else if name == class {
crate::BindingKind::Constructor
} else if has_parameters {
crate::BindingKind::Function
} else {
crate::BindingKind::Variable
};
found.push((
Binding {
name: if let Some(rest) = name.strip_prefix('~') {
crate::Name::destructor(rest)
} else if let Some(symbol) = name.strip_prefix("operator") {
crate::Name::operator(symbol.trim())
} else {
crate::Name::identifier(name)
},
kind,
range: crate::scopes::without_trailing_trivia(declaration.syntax()),
name_range,
scope: ScopeId(0),
origin: None,
},
{
let mut namespaces: Vec<String> = cpp_parser::typed_ancestors::<
cpp_parser::CppNamespaceDecl,
>(declaration.syntax())
.filter_map(|namespace| namespace.get_name())
.map(|token| token.get_name_text().unwrap_or_default())
.collect();
namespaces.reverse();
if !qualifier.is_empty() {
namespaces.push(qualifier.to_string());
}
namespaces.join("::")
},
declaration
.get_param_list()
.map(|list| crate::inlay::tidy_list_text(&list.syntax().text().to_string()).0),
));
}
found
}
pub fn assign_guards(
facts: &mut [(&mut FactGuard, usize)],
preprocessing: &FilePreprocessing,
guards: &mut SummaryGuards,
) {
let mut conditionals = conditionals(preprocessing);
let regions = std::mem::take(&mut conditionals.regions);
let conditions = std::mem::take(&mut conditionals.conditionals);
let conditionals = conditionals.directives;
let mut open: Vec<usize> = Vec::new();
let mut cursor = 0usize;
for (guard, at) in facts.iter_mut() {
let at = *at;
while cursor < conditionals.len() && conditionals[cursor].observed_by <= at {
let region = conditionals[cursor];
match region.close {
false => open.push(region.index),
true => {
if let Some(position) = open.iter().rposition(|index| *index == region.index) {
open.truncate(position);
}
}
}
cursor += 1;
}
let innermost = open
.iter()
.rev()
.find(|index| regions[**index].start_offset <= at);
**guard = match innermost {
Some(index) => FactGuard::Region(*index as u32),
None => FactGuard::Unconditional,
};
}
guards.regions = regions;
guards.conditionals = conditions;
}
struct Conditionals {
directives: Vec<ConditionalDirective>,
regions: Vec<SourceRange>,
conditionals: Vec<ConditionalRegion>,
stray_closers: usize,
unclosed: usize,
}
#[derive(Debug, Clone, Copy)]
struct ConditionalDirective {
index: usize,
close: bool,
observed_by: usize,
}
type BranchFact = (usize, MacroKind);
enum BranchCondition {
NotDefined(Box<str>),
Defined(Box<str>),
Otherwise,
Other,
}
fn branch_condition(branch: &GuardBranch) -> BranchCondition {
match branch.kind {
DirectiveKind::Ifndef => {
BranchCondition::NotDefined(branch.condition.clone().unwrap_or_default())
}
DirectiveKind::Ifdef => {
BranchCondition::Defined(branch.condition.clone().unwrap_or_default())
}
DirectiveKind::Else => BranchCondition::Otherwise,
_ => named_condition(&branch.as_branch().tokens),
}
}
fn conditionals(preprocessing: &FilePreprocessing) -> Conditionals {
let mut found = Conditionals {
directives: Vec::new(),
regions: Vec::new(),
conditionals: Vec::new(),
stray_closers: 0,
unclosed: 0,
};
let mut open: Vec<usize> = Vec::new();
for spanned in &preprocessing.directives {
let kind = spanned.directive.kind();
if kind.opens_a_condition() {
let index = found.regions.len();
found.regions.push(condition_span(spanned));
found.conditionals.push(ConditionalRegion {
parent: open.last().map(|index| *index as u32),
branches: vec![conditional_branch(&spanned.directive, &spanned.range)],
decoded: std::sync::OnceLock::new(),
});
open.push(index);
found.directives.push(ConditionalDirective {
index,
close: false,
observed_by: spanned.range.end_offset(),
});
} else if kind.closes_a_condition() {
let Some(index) = open.last().copied() else {
found.stray_closers += 1;
continue;
};
close_branch(&mut found.conditionals, index, spanned.range.start_offset);
let closes = kind == DirectiveKind::Endif;
extend_region_to(&mut found.regions, index, spanned.range.end_offset());
if closes {
open.pop();
found.directives.push(ConditionalDirective {
index,
close: true,
observed_by: spanned.range.end_offset(),
});
} else {
open_branch(
&mut found.conditionals,
index,
&spanned.directive,
&spanned.range,
);
}
}
}
found.unclosed = open.len();
found
}
fn close_branch(conditionals: &mut [ConditionalRegion], region: usize, end: usize) {
let Some(branch) = conditionals
.get_mut(region)
.and_then(|conditional| conditional.branches.last_mut())
else {
return;
};
branch.body = SourceRange::new(
branch.body.start_offset,
end.saturating_sub(branch.body.start_offset),
);
}
fn open_branch(
conditionals: &mut [ConditionalRegion],
region: usize,
directive: &Directive,
range: &SourceRange,
) {
let Some(conditional) = conditionals.get_mut(region) else {
return;
};
conditional
.branches
.push(conditional_branch(directive, range));
}
fn conditional_branch(directive: &Directive, range: &SourceRange) -> GuardBranch {
GuardBranch {
kind: directive.kind(),
condition: match directive {
Directive::Conditional { condition, .. } => Some({
let mut spelling = String::new();
let mut previous_end = None;
for token in condition.iter() {
if previous_end.is_some_and(|end| end != token.range.start_offset) {
spelling.push(' ');
}
spelling.push_str(token.text());
previous_end = Some(token.range.end_offset());
}
spelling.into()
}),
Directive::Ifdef { name, .. } => Some(name.clone()),
_ => None,
},
body: SourceRange::new(range.end_offset(), 0),
range: *range,
}
}
fn named_condition(tokens: &[crate::token::Token]) -> BranchCondition {
let significant: Vec<&crate::token::Token> = tokens
.iter()
.filter(|token| !crate::token::is_trivia(token.kind))
.collect();
let rest = without_outer_parentheses(&significant);
let (negated, rest) = match rest.split_first() {
Some((first, rest)) if first.kind == cpp_parser::CppTokenKind::LogicalNot => (true, rest),
_ => (false, rest),
};
let Some((defined, rest)) = rest
.split_first()
.filter(|(token, _)| token.text() == "defined")
else {
return BranchCondition::Other;
};
let _ = defined;
let parenthesised = rest
.first()
.is_some_and(|token| token.kind == cpp_parser::CppTokenKind::LeftParen);
let rest = if parenthesised { &rest[1..] } else { rest };
let Some((name, rest)) = rest
.split_first()
.filter(|(token, _)| token.is_identifier())
else {
return BranchCondition::Other;
};
let rest = if parenthesised {
match rest.split_first() {
Some((close, rest)) if close.kind == cpp_parser::CppTokenKind::RightParen => rest,
_ => return BranchCondition::Other,
}
} else {
rest
};
if !rest.is_empty() {
return BranchCondition::Other;
}
if negated {
BranchCondition::NotDefined(name.text.as_str().into())
} else {
BranchCondition::Defined(name.text.as_str().into())
}
}
fn without_outer_parentheses<'a>(
tokens: &'a [&'a crate::token::Token],
) -> &'a [&'a crate::token::Token] {
let mut rest = tokens;
while rest.len() >= 2
&& rest[0].kind == cpp_parser::CppTokenKind::LeftParen
&& rest[rest.len() - 1].kind == cpp_parser::CppTokenKind::RightParen
{
let mut depth = 0isize;
let closes_at_the_end = rest.iter().enumerate().all(|(index, token)| {
match token.kind {
cpp_parser::CppTokenKind::LeftParen => depth += 1,
cpp_parser::CppTokenKind::RightParen => depth -= 1,
_ => {}
}
depth > 0 || index == rest.len() - 1
});
if !closes_at_the_end {
break;
}
rest = &rest[1..rest.len() - 1];
}
rest
}
pub fn mark_settling_macro_facts(
preprocessing: &FilePreprocessing,
own_guard: Option<usize>,
macros: &mut [MacroFact],
) {
if macros.is_empty() {
return;
}
let conditionals = conditionals(preprocessing);
if conditionals.conditionals.is_empty() {
return;
}
if conditionals.stray_closers > 0 || conditionals.unclosed > 0 {
return;
}
let mut last: HashMap<(usize, usize, &str), (MacroKind, usize)> = HashMap::new();
for (index, fact) in macros.iter().enumerate() {
let FactGuard::Region(region) = fact.guard else {
continue;
};
let Some(shape) = conditionals.conditionals.get(region as usize) else {
continue;
};
let Some(branch) = shape.branch_at(fact.range.start_offset) else {
continue;
};
last.insert(
(region as usize, branch, fact.name.as_str()),
(fact.kind, index),
);
}
let mut mentioned: HashMap<usize, HashMap<&str, Vec<BranchFact>>> = HashMap::new();
for (&(region, _, name), &(kind, index)) in &last {
mentioned
.entry(region)
.or_default()
.entry(name)
.or_default()
.push((index, kind));
}
let mut settles: HashMap<(usize, &str), bool> = HashMap::new();
let mut settling: Vec<usize> = Vec::new();
for (region, shape) in conditionals.conditionals.iter().enumerate() {
let Some(by_name) = mentioned.get(®ion) else {
continue;
};
for (name, in_branches) in by_name {
if in_branches.len() != shape.branches.len() {
continue;
}
let kind = in_branches[0].1;
if in_branches.iter().any(|(_, held)| *held != kind) {
continue;
}
let guaranteed = if shape.exhaustive() {
true
} else {
match shape.branches.as_slice() {
[one] => match branch_condition(one) {
BranchCondition::NotDefined(condition) => {
condition.as_ref() == *name && kind.is_definition()
}
BranchCondition::Defined(condition) => {
condition.as_ref() == *name && !kind.is_definition()
}
BranchCondition::Otherwise | BranchCondition::Other => false,
},
_ => false,
}
};
if !guaranteed {
continue;
}
let inherited = shape.parent.is_none_or(|parent| {
Some(parent as usize) == own_guard
|| settles
.get(&(parent as usize, name))
.copied()
.unwrap_or(false)
});
settles.insert((region, name), inherited);
if inherited {
settling.extend(in_branches.iter().map(|(index, _)| *index));
}
}
}
for index in settling {
macros[index].settles_the_name = true;
}
}
fn extend_region_to(regions: &mut [SourceRange], index: usize, end: usize) {
if let Some(region) = regions.get_mut(index) {
let start = region.start_offset;
let length = end.saturating_sub(start);
*region = SourceRange::new(start, length);
}
}
fn condition_span(spanned: &SpannedDirective) -> SourceRange {
match &spanned.directive {
Directive::Conditional { .. } | Directive::Ifdef { .. } => spanned.range,
_ => spanned.range,
}
}
pub fn by_name(facts: &[DeclFact]) -> HashMap<&str, Vec<&DeclFact>> {
let mut index: HashMap<&str, Vec<&DeclFact>> = HashMap::new();
for fact in facts {
index.entry(fact.name.as_str()).or_default().push(fact);
}
index
}
pub fn scope_of<'a>(scopes: &'a ScopeTree, fact: &DeclFact) -> Option<(ScopeId, &'a Binding)> {
let wanted = fact.scope.as_deref();
scopes
.scopes()
.iter()
.enumerate()
.find_map(|(index, scope)| {
if scope.name.as_deref() != wanted {
return None;
}
let binding = scope
.bindings
.iter()
.find(|binding| binding.name_range == fact.name_range)?;
Some((ScopeId(index), binding))
})
}
pub fn template_parameters_for<'a>(scopes: &'a ScopeTree, fact: &DeclFact) -> Vec<&'a str> {
let Some(scope) = scopes.scope_at(fact.range.start_offset) else {
return Vec::new();
};
let mut found: Vec<&str> = Vec::new();
for id in scopes.scope_chain(scope) {
let Some(data) = scopes.scope(id) else {
continue;
};
if data.kind != ScopeKind::TemplateParameters {
continue;
}
for binding in &data.bindings {
if binding.kind == BindingKind::TemplateParameter
&& let Some(name) = binding.name.identifier_text()
{
found.push(name);
}
}
}
found
}
pub fn split_by_a_directive_with(shapes: &DeclarationShapes, binding: &Binding) -> bool {
let Some(specifiers) = shapes.specifiers_at(the_offset_to_descend_by(binding)) else {
return false;
};
use cpp_parser::CppAstNode;
specifiers
.descendants()
.filter_map(cpp_parser::CppPreprocessorDirective::cast)
.any(|directive| {
let word = directive
.syntax()
.children_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| {
cpp_parser::CppTokenKind::from(token.kind()) != cpp_parser::CppTokenKind::Hash
})
.find(|token| !token.text().trim().is_empty());
let Some(word) = word else {
return false;
};
let word = word.text().to_string();
matches!(
word.as_str(),
"if" | "ifdef" | "ifndef" | "elif" | "else" | "endif"
)
})
}
#[cfg(test)]
mod tests {
use super::{build_facts, by_name, template_parameters_for};
use crate::preprocess::preprocess;
use crate::sema::scopes::build_scopes;
use crate::summary::DeclFact;
use crate::summary::{DeclKind, FactGuard};
use cpp_parser::{CppParser, ParserConfig};
#[test]
fn a_declaration_is_exported_only_where_export_reaches_it() {
let source = "export module m;\n\
export namespace ns { int inside(); }\n\
namespace ns { int outside(); }\n\
export int alone();\n\
int plain();\n";
let (facts, _) = facts(source);
let exported = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("{name} must be a fact"))
.exported
};
assert!(exported("inside"), "inside an exported namespace");
assert!(
!exported("outside"),
"the second namespace has no `export`, so a declaration in it is not exported"
);
assert!(exported("alone"), "`export int alone();`");
assert!(
!exported("plain"),
"and a declaration with no `export` above it"
);
}
#[test]
fn a_declaration_inside_a_template_can_name_its_parameters() {
let source = "template <class _Alloc>\n\
struct _Container {\n\
using value_type = typename _Alloc::value_type;\n\
};\n\
template <class _Ty> void take(_Ty value) { }\n";
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(tree.get_errors(), [], "the input must parse cleanly");
let root = tree.get_red_root();
let scopes = build_scopes(&root, &crate::NoMacroBodies);
let (facts, _) = build_facts(
&scopes,
&preprocess(source, tree.get_tokens()),
&root,
&[],
true,
);
let parameters_of = |name: &str| -> Vec<String> {
let fact = facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("{name} must be a fact"));
template_parameters_for(&scopes, fact)
.into_iter()
.map(str::to_string)
.collect()
};
assert_eq!(
parameters_of("value_type"),
vec!["_Alloc".to_string()],
"a member of a class template names the class's own parameter"
);
assert_eq!(
parameters_of("take"),
vec!["_Ty".to_string()],
"and a function template's parameter is in scope in its body, where the fact's `scope` is `None`"
);
assert!(
!parameters_of("_Container").contains(&"_Container".to_string()),
"the class's own name is not one of its parameters, so a type spelled `_Container` is not \
dependent. The list is not empty, and that is right rather than a leak: a template's parameters \
are in scope for the declaration that follows, **its own name included** — the note on \
`templated_declaration` says the name belongs to the enclosing scope, which is a statement about \
where the *binding* goes and not about what can be named. What the filter compares is the name, \
and `_Container` is not `_Alloc`: got {:?}",
parameters_of("_Container")
);
}
#[test]
fn an_alias_declares_a_fact_in_every_shape() {
let source = "using plain = int;\n\
namespace std {\n\
template <class _Alloc>\n\
using _Alloc_ptr_t = typename allocator_traits<_Alloc>::pointer;\n\
struct _Guard {\n\
using size_type = unsigned long long;\n\
using _Alty_traits = allocator_traits<int>;\n\
};\n\
}\n";
let (facts, _) = facts(source);
let everything: Vec<(String, DeclKind)> = facts
.iter()
.map(|fact| (fact.qualified_name(), fact.kind))
.collect();
let named = |name: &str| -> Option<String> {
facts
.iter()
.find(|fact| fact.name == name)
.map(DeclFact::qualified_name)
};
assert_eq!(
named("plain").as_deref(),
Some("plain"),
"a file-scope alias is a declaration: {everything:?}"
);
assert_eq!(
named("_Alloc_ptr_t").as_deref(),
Some("std::_Alloc_ptr_t"),
"a namespace-scope alias **template** is a declaration: {everything:?}"
);
assert_eq!(
named("size_type").as_deref(),
Some("std::_Guard::size_type"),
"a member alias to a concrete type is a declaration: {everything:?}"
);
assert_eq!(
named("_Alty_traits").as_deref(),
Some("std::_Guard::_Alty_traits"),
"a member alias to a **template-id** is a declaration — this is the shape that was missing, and \
`size_type` above is the control that says the member half works: {everything:?}"
);
}
#[test]
fn a_base_clause_survives_a_macro_before_the_name() {
let source = "struct Base { int b; };\n\
struct _Attr(\"x\") Widget : Base { int w; };\n\
struct Plain : Base { int p; };\n\
template <class _Alloc>\n\
struct _Attr(\"y\") Traits\n\
: conditional_t<true, Other<_Alloc>, Base> {};\n\
_EXPORT_STD template <class _Alloc>\n\
struct _Attr(\"z\") Exported\n\
: conditional_t<true, Other<_Alloc>, Base> {};\n\
template <class _Alloc>\n\
struct [[msvc::no_specializations(\"a\" \"b\")]] Attributed\n\
: conditional_t<true, Other<_Alloc>, Base> {};\n\
template <class _Alloc>\n\
struct [[msvc::no_specializations(\"Specializing this standard library template is forbidden by \" \"N5014 [allocator.traits.general]/1\")]] Bracketed\n\
: conditional_t<true, Other<_Alloc>, Base> {};\n\
namespace ns {\n\
template <class _Alloc>\n\
struct [[msvc::no_specializations(\"a\" \"b\")]] Nested\n\
: conditional_t<true, Other<_Alloc>, Base> {};\n\
}\n\
template <class _Alloc>\n\
struct [ [ msvc :: no_specializations ( \"a\" ) ] ] Spaced\n\
: conditional_t<true, Other<_Alloc>, Base> {};\n";
let (facts, _) = facts(source);
let bases_of = |name: &str| -> Vec<String> {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("{name} must be a fact"))
.bases
.clone()
};
assert_eq!(
bases_of("Widget"),
vec!["Base".to_string()],
"a macro between the keyword and the name does not change what the class derives from"
);
assert_eq!(
bases_of("Widget"),
bases_of("Plain"),
"…which is the same answer the plain spelling gives"
);
assert_eq!(
bases_of("Traits"),
vec!["conditional_t<true, Other<_Alloc>, Base>".to_string()],
"and the clause is kept **as written** — `conditional_t<…>` is not a class name, and turning it \
into one is not this layer's question"
);
assert_eq!(
bases_of("Exported"),
vec!["conditional_t<true, Other<_Alloc>, Base>".to_string()],
"a macro before `template` does not stop the class from being declared: {:?}",
facts
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
assert_eq!(
bases_of("Attributed"),
vec!["conditional_t<true, Other<_Alloc>, Base>".to_string()],
"an attribute between `struct` and the name does not stop the class from being declared: {:?}",
facts
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
assert_eq!(
bases_of("Bracketed"),
vec!["conditional_t<true, Other<_Alloc>, Base>".to_string()],
"the text inside the attribute's string does not change how the declaration is read: {:?}",
facts
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
assert_eq!(
bases_of("Nested"),
vec!["conditional_t<true, Other<_Alloc>, Base>".to_string()],
"a namespace around the declaration changes nothing about it: {:?}",
facts
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
assert_eq!(
bases_of("Spaced"),
vec!["conditional_t<true, Other<_Alloc>, Base>".to_string()],
"a space between the attribute's brackets does not change what the declaration is: {:?}",
facts
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
}
#[test]
fn an_alias_records_the_type_it_points_at() {
let source = "using A = basic_string<char>;\n\
typedef basic_string<char> B;\n\
typedef void (*F)(int);\n\
typedef int int32_t;\n";
let (facts, _) = facts(source);
let type_of = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("{name} must be a fact"))
.type_of
.clone()
};
assert_eq!(type_of("A").as_deref(), Some("basic_string<char>"));
assert_eq!(type_of("B").as_deref(), Some("basic_string<char>"));
assert_eq!(
type_of("F").as_deref(),
Some("void (*)(int)"),
"the specifiers plus the declarator with the alias's own name cut out"
);
assert_eq!(type_of("int32_t").as_deref(), Some("int"));
}
#[test]
fn a_member_whose_type_is_preceded_by_macros_is_named_by_its_declarator() {
let source = "struct S {\n _GLIBCXX_NODISCARD _GLIBCXX20_CONSTEXPR\n size_type\n size() const noexcept;\n};\n";
let (declared, _) = facts(source);
let names: Vec<&str> = declared.iter().map(|fact| fact.name.as_str()).collect();
assert!(
names.contains(&"size"),
"the member is named by its declarator: {names:?}"
);
assert!(
!names.contains(&"size_type")
|| names.iter().filter(|name| **name == "size_type").count() == 1,
"and no member is named after the type: {names:?}"
);
let defined = "struct S {\n#if FEATURE\n int a;\n#endif\n _GLIBCXX_NODISCARD _GLIBCXX20_CONSTEXPR\n size_type\n size() const noexcept\n { return 0; }\n};\n";
let (defined_facts, _) = facts(defined);
let names: Vec<&str> = defined_facts
.iter()
.map(|fact| fact.name.as_str())
.collect();
assert!(
names.contains(&"size"),
"an inline definition is named the same way as a declaration: {names:?}"
);
let suffix_macro = "struct S {\n _GLIBCXX_NODISCARD _GLIBCXX20_CONSTEXPR\n size_type\n size() const _GLIBCXX_NOEXCEPT\n { return 0; }\n};\n";
let (suffix_facts, _) = facts(suffix_macro);
let names: Vec<&str> = suffix_facts.iter().map(|fact| fact.name.as_str()).collect();
assert!(
names.contains(&"size"),
"a macro in the function-suffix position does not rename the member: {names:?}"
);
}
#[test]
fn a_class_records_no_type_of_its_own() {
let (facts, _) = facts("struct Widget { int size; };\nusing Alias = Widget;\n");
let widget = facts
.iter()
.find(|fact| fact.name == "Widget")
.expect("the class is a fact");
assert_eq!(widget.type_of, None);
assert_eq!(widget.kind, DeclKind::Type);
}
#[test]
fn a_qualified_name_with_template_arguments_declares_in_that_class() {
let source = "\
template <class T> class Box {
public:
int size;
void grow(int n);
struct Inner { int deep; };
};
void Box<int>::grow(int n) { size = n; }
int Box<int>::count = 0;
int Box<int>::Inner::deep = 0;
";
let (facts, _) = facts(source);
let scope_of = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("`{name}` must be a fact: {facts:?}"))
.scope
.clone()
};
assert_eq!(scope_of("grow").as_deref(), Some("Box"));
assert_eq!(
scope_of("count").as_deref(),
Some("Box"),
"`int Box<int>::count = 0;` is a member of `Box` — it used to declare nothing at all"
);
assert_eq!(
scope_of("deep").as_deref(),
Some("Box::Inner"),
"and a nested class's member is qualified by the *names*, without the template arguments"
);
assert!(
!facts.iter().any(|fact| fact.name.contains("::")),
"no fact is named with a qualifier"
);
}
fn facts(source: &str) -> (Vec<crate::summary::DeclFact>, crate::summary::SummaryGuards) {
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(tree.get_errors(), [], "the input must parse cleanly");
let root = tree.get_red_root();
build_facts(
&build_scopes(&root, &crate::NoMacroBodies),
&preprocess(source, tree.get_tokens()),
&root,
&[],
true,
)
}
#[test]
fn a_reflection_annotation_is_recorded_with_its_specifiers() {
let source = "\
UCLASS(Blueprintable, BlueprintType)
class MYGAME_API AMyActor
{
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = \"Game\")
bool bIsReady = false;
UFUNCTION(BlueprintCallable, meta=(DisplayName=\"Do It\", ToolTip=\"a, b\"))
void DoThing();
int32 NotAnnotated = 0;
};
";
let (facts, _) = facts(source);
let class = facts
.iter()
.find(|fact| fact.name == "AMyActor")
.expect("the class");
let reflection = class.reflection.clone().expect("UCLASS");
assert_eq!(reflection.macro_name, "UCLASS");
assert_eq!(
reflection.names().collect::<Vec<_>>(),
vec!["Blueprintable", "BlueprintType"]
);
let member = facts
.iter()
.find(|fact| fact.name == "bIsReady")
.expect("the member");
let reflection = member.reflection.clone().expect("UPROPERTY");
assert_eq!(reflection.macro_name, "UPROPERTY");
assert_eq!(
reflection.specifiers,
vec!["EditAnywhere", "BlueprintReadWrite", "Category = \"Game\"",]
);
assert_eq!(reflection.value_of("Category"), Some("\"Game\""));
let function = facts
.iter()
.find(|fact| fact.name == "DoThing")
.expect("the function");
let reflection = function.reflection.clone().expect("UFUNCTION");
assert_eq!(reflection.macro_name, "UFUNCTION");
assert_eq!(
reflection.specifiers,
vec![
"BlueprintCallable",
"meta=(DisplayName=\"Do It\", ToolTip=\"a, b\")",
],
"a value with commas in it is one specifier"
);
let plain = facts
.iter()
.find(|fact| fact.name == "NotAnnotated")
.expect("the plain member");
assert!(plain.reflection.is_none());
}
fn facts_of_a_broken_file(
source: &str,
) -> (Vec<crate::summary::DeclFact>, Vec<cpp_parser::SourceRange>) {
let tree = CppParser::parse(source, ParserConfig::default());
assert_ne!(
tree.get_errors(),
[],
"this fixture is meant to have errors: {source:?}"
);
let root = tree.get_red_root();
let errors: Vec<cpp_parser::SourceRange> = tree
.get_errors()
.iter()
.map(|error| cpp_parser::source_range(error.range))
.collect();
(
build_facts(
&build_scopes(&root, &crate::NoMacroBodies),
&preprocess(source, tree.get_tokens()),
&root,
&errors,
true,
)
.0,
errors,
)
}
fn qualified(source: &str) -> Vec<String> {
let (facts, _) = facts(source);
let mut names: Vec<String> = facts
.iter()
.map(|fact| match &fact.scope {
Some(scope) => format!("{scope}::{}", fact.name),
None => fact.name.clone(),
})
.collect();
names.sort();
names
}
#[test]
fn a_top_level_declaration_has_no_scope_prefix() {
assert_eq!(qualified("int count;\n"), ["count"]);
}
#[test]
fn a_member_is_qualified_by_its_class_and_its_namespaces() {
assert_eq!(
qualified("namespace ns { struct C { int member; void method(); }; }\n"),
["ns", "ns::C", "ns::C::member", "ns::C::method"]
);
}
#[test]
fn the_nested_namespace_spellings_agree() {
let compact = qualified("namespace a::b { struct C { int member; }; }\n");
let spelled = qualified("namespace a { namespace b { struct C { int member; }; } }\n");
assert_eq!(compact, spelled);
}
#[test]
fn a_function_body_does_not_qualify_its_locals() {
let names = qualified("namespace ns { void f() { int local = 0; } }\n");
assert!(
names.contains(&"local".to_string()),
"the local is declared and must be a fact: {names:?}"
);
assert!(
!names.iter().any(|name| name.contains("ns::f::")),
"a function body contributes no segment to a qualified name: {names:?}"
);
}
#[test]
fn facts_inside_a_conditional_carry_its_region() {
let source = "int outside;\n#if defined(A)\nint inside;\n#endif\nint after;\n";
let (facts, guards) = facts(source);
assert_eq!(guards.regions.len(), 1, "one `#if`, one region");
let guard_of = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("{name} must be a fact"))
.guard
};
assert_eq!(guard_of("outside"), FactGuard::Unconditional);
assert_eq!(guard_of("inside"), FactGuard::Region(0));
assert_eq!(
guard_of("after"),
FactGuard::Unconditional,
"the region is closed by its own `#endif`"
);
}
#[test]
fn a_declaration_inside_a_region_is_guarded_and_the_region_stays_open_until_endif() {
let source = "#if defined(A)\nint inside;\nint also_inside;\n#endif\nint after;\n";
let (facts, guards) = facts(source);
assert_eq!(guards.regions.len(), 1);
let guard_of = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("{name} must be a fact"))
.guard
};
assert_eq!(guard_of("inside"), FactGuard::Region(0));
assert_eq!(
guard_of("also_inside"),
FactGuard::Region(0),
"a second declaration in the same region interns to the same one"
);
assert_eq!(guard_of("after"), FactGuard::Unconditional);
}
#[test]
fn a_declaration_on_the_directive_line_is_not_a_fact() {
let source = "#if defined(A) int inside;\n#endif\nint outside;\n";
let (facts, guards) = facts(source);
assert_eq!(guards.regions.len(), 1, "the `#if` still opens a region");
assert!(
!facts.iter().any(|fact| fact.name == "inside"),
"the whole line is the directive's argument: {:?}",
facts.iter().map(|fact| &fact.name).collect::<Vec<_>>()
);
assert!(
facts.iter().any(|fact| fact.name == "outside"),
"and the declaration after the region is unaffected"
);
}
#[test]
fn nested_conditionals_give_the_innermost_region() {
let source = "#if defined(A)\nint outer;\n#if defined(B)\nint inner;\n#endif\n#endif\n";
let (facts, guards) = facts(source);
assert_eq!(guards.regions.len(), 2, "each `#if` is its own region");
let guard_of = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("{name} must be a fact"))
.guard
};
assert_ne!(guard_of("outer"), guard_of("inner"));
assert!(
matches!(guard_of("inner"), FactGuard::Region(_)),
"the inner declaration is guarded by the inner region"
);
}
#[test]
fn an_unbalanced_endif_does_not_swallow_the_rest_of_the_file() {
let source = "#endif\nint after;\n";
let (facts, guards) = facts(source);
assert!(guards.regions.is_empty(), "no region was opened");
assert_eq!(
facts
.iter()
.find(|fact| fact.name == "after")
.expect("the declaration is a fact")
.guard,
FactGuard::Unconditional
);
}
#[test]
fn the_by_name_view_groups_a_name_declared_twice() {
let (facts, _) = facts("void f();\nvoid f(int);\n");
let index = by_name(&facts);
assert_eq!(index.get("f").map(Vec::len), Some(2), "both overloads");
assert_eq!(index.get("g"), None, "a name no declaration mentions");
}
#[test]
fn a_declaration_kind_survives_the_walk() {
let (facts, _) = facts("struct C { int member; void method(); };\nnamespace ns { }\n");
let kind_of = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.map(|fact| fact.kind)
};
assert_eq!(kind_of("C"), Some(DeclKind::Type));
assert_eq!(kind_of("member"), Some(DeclKind::Variable));
assert_eq!(kind_of("method"), Some(DeclKind::Function));
assert_eq!(kind_of("ns"), Some(DeclKind::Namespace));
}
fn unclean(source: &str) -> Vec<String> {
let (facts, errors) = facts_of_a_broken_file(source);
assert!(!errors.is_empty(), "the fixture must have diagnostics");
facts
.iter()
.filter(|fact| !fact.clean)
.map(|fact| fact.name.clone())
.collect()
}
#[test]
fn a_file_that_parses_cleanly_is_clean() {
let (facts, _) = facts("struct S { int a; };\nint count;\nvoid f() { int local; }\n");
assert!(!facts.is_empty(), "the fixture declares something");
assert!(
facts.iter().all(|fact| fact.clean),
"with no diagnostics there is nothing to be unclean about: {:?}",
facts
.iter()
.filter(|fact| !fact.clean)
.map(|fact| fact.name.as_str())
.collect::<Vec<_>>()
);
}
#[test]
fn a_broken_declaration_leaves_the_rest_of_its_file_alone() {
let (facts, errors) = facts_of_a_broken_file("struct S { int a; };\nint b = ;\n");
assert_eq!(errors.len(), 1, "one error, in the second declaration");
assert_eq!(
facts
.iter()
.map(|fact| fact.name.as_str())
.collect::<Vec<_>>(),
["S", "a"],
"no fact for the declaration that failed"
);
assert!(
facts.iter().all(|fact| fact.clean),
"and the two that were read are untouched by the recovery"
);
}
#[test]
fn an_error_inside_a_declaration_is_reported_on_it() {
assert_eq!(unclean("namespace n { int bad = ; }\nint ok;\n"), ["n"]);
assert_eq!(unclean("void f() { int a = ; }\nint ok;\n"), ["f"]);
}
#[test]
fn only_the_innermost_declaration_is_touched() {
assert_eq!(
unclean("struct S { int a; void m() { int x = ; } };\nint ok;\n"),
["S", "m"]
);
}
#[test]
fn a_declaration_inside_a_function_body_is_local() {
let (facts, _) = facts(
"int global;\n\
namespace ns { int in_a_namespace; }\n\
struct C { int member; void method(); };\n\
void f(int parameter) {\n\
int local;\n\
{ int in_a_block; }\n\
struct Local { int inner; };\n\
}\n",
);
let local_of = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("`{name}` is declared in the fixture"))
.local
};
assert!(!local_of("global"), "file scope is reachable from outside");
assert!(!local_of("in_a_namespace"), "a namespace member too");
assert!(
!local_of("member"),
"a class body is not a function body, wherever the class is"
);
assert!(
!local_of("method"),
"and a member function's *declaration* is not its body"
);
assert!(
local_of("parameter"),
"a parameter is local to the function"
);
assert!(local_of("local"), "the case the field exists for");
assert!(local_of("in_a_block"), "a nested block is still inside it");
assert!(
local_of("inner"),
"and a class declared in there declares locals too"
);
}
#[test]
fn a_function_records_what_it_returns_and_nothing_else_does() {
let (facts, _) = facts(
"Widget make();\n\
Widget w;\n\
struct C { Widget member(); };\n\
static inline Widget decorated();\n\
auto trailing() -> Widget;\n\
auto deduced() { return Widget{}; }
auto unclearable() { return make(); }\n\
void plain();\n",
);
let of = |name: &str| {
facts
.iter()
.find(|fact| fact.name == name)
.unwrap_or_else(|| panic!("`{name}` is declared in the fixture"))
};
assert_eq!(of("make").returns.as_deref(), Some("Widget"));
assert_eq!(
of("make").type_of,
None,
"a function has no type of its own"
);
assert_eq!(
of("w").type_of.as_deref(),
Some("Widget"),
"…and a variable returns nothing"
);
assert_eq!(of("w").returns, None);
assert_eq!(
of("decorated").returns.as_deref(),
Some("Widget"),
"declaration specifiers are stripped, as they are from `type_of`"
);
assert_eq!(
of("trailing").returns.as_deref(),
Some("Widget"),
"a trailing return type wins — it is the one the file stated, and the specifiers say `auto`"
);
assert_eq!(
of("deduced").returns.as_deref(),
Some("Widget"),
"a construction in a `return` states the type it returns"
);
assert_eq!(
of("unclearable").returns,
None,
"a return this layer cannot type is still refused rather than guessed"
);
assert_eq!(of("plain").returns.as_deref(), Some("void"));
}
}
#[test]
fn an_annotation_after_a_multi_byte_character_is_read() {
let written = "// 3×UCLASS()\nclass Foo {};";
let at = written
.find("class Foo")
.expect("the declaration is written");
let found = the_annotation_before(written, at);
assert_eq!(
found.map(|(name, _)| name),
Some("UCLASS"),
"the annotation is found past a two-byte character"
);
}