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],
) -> (Vec<DeclFact>, SummaryGuards) {
let file = DeclarationFacts::new(scopes, preprocessing, root, errors);
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
&& node
.children()
.any(|inner| CppSyntaxKind::from(inner.kind()) == CppSyntaxKind::ParameterList))
{
declarator = Some(node.clone());
}
});
if let Some(target) = using_alias_target(shapes, binding.name_range) {
return Some(target);
}
let specifiers = specifiers?;
let spelled = match binding.kind {
BindingKind::Typedef => None,
_ => Some(binding.name.text()),
};
let found = crate::sema::types::type_of_declaration_named(
&specifiers,
declarator.as_ref(),
binding.name_range,
spelled.as_deref(),
);
let written = found.to_string();
(!written.is_empty()).then_some(written)
}
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 struct DeclarationShapes {
shapes: Vec<Shape>,
roots: (u32, u32),
children: Vec<u32>,
templates: Vec<(cpp_parser::SourceRange, CppSyntaxNode)>,
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 {
pub fn of(root: &CppSyntaxNode) -> Self {
let mut shapes: Vec<Shape> = Vec::new();
let mut chain: Vec<u32> = Vec::new();
let mut templates: Vec<(cpp_parser::SourceRange, CppSyntaxNode)> = 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 CppSyntaxKind::from(node.kind()) == CppSyntaxKind::ParameterList {
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 = match node.parent().map(|owner| CppSyntaxKind::from(owner.kind())) {
Some(CppSyntaxKind::StructDef | CppSyntaxKind::UnionDef) => Access::Public,
_ => 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) = node.children().find(|child| {
CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TemplateParameterList
})
&& let Some(owner) = node.parent()
{
templates.push((cpp_parser::source_range(owner.text_range()), list.clone()));
}
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 {
let mut read = ShapeChildren {
specifiers: None,
trailing: None,
declarator: None,
type_id: None,
bases: Vec::new(),
};
for child in node.children() {
match CppSyntaxKind::from(child.kind()) {
CppSyntaxKind::DeclSpecifierSeq if read.specifiers.is_none() => {
read.specifiers = Some(child)
}
CppSyntaxKind::TrailingReturnType if read.trailing.is_none() => {
read.trailing = Some(child)
}
CppSyntaxKind::Declarator if read.declarator.is_none() => read.declarator = Some(child),
CppSyntaxKind::TypeId if read.type_id.is_none() => read.type_id = Some(child),
CppSyntaxKind::BaseSpecifier => read.bases.extend(
child
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::NameExpr),
),
_ => {}
}
}
read
}
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
)
}
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> {
let body = specifiers.children().find(|child| {
matches!(
CppSyntaxKind::from(child.kind()),
CppSyntaxKind::ClassDef
| CppSyntaxKind::StructDef
| CppSyntaxKind::UnionDef
| CppSyntaxKind::EnumDef
| CppSyntaxKind::EnumClassDef
)
})?;
let tag = body
.children()
.filter(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::NameExpr)
.map(|child| child.text().to_string().trim().to_string())
.find(|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<'_>,
) -> 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)?;
match &agreed {
None => agreed = Some(written),
Some(previous) if *previous == written => {}
Some(_) => return None,
}
}
agreed
}
fn a_branch_that_is_taken(
expression: &CppSyntaxNode,
body: &CppSyntaxNode,
substitutions: &crate::sema::types::TypeSubstitutions<'_>,
) -> bool {
let mut conditions: Vec<CppSyntaxNode> = body
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::IfStat)
.filter(|node| {
let range = node.text_range();
range.start() <= expression.text_range().start()
&& expression.text_range().end() <= range.end()
})
.collect();
conditions.sort_by_key(|node| node.text_range().len());
for condition in conditions {
let Some(written) = constexpr_condition_of(&condition) else {
continue;
};
let Some(held) = evaluate_a_trait(&written, substitutions) else {
continue;
};
let in_the_else = else_offset_of(&condition)
.is_some_and(|at| usize::from(expression.text_range().start()) > at);
if held == in_the_else {
return false;
}
}
true
}
fn else_offset_of(statement: &CppSyntaxNode) -> Option<usize> {
statement
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.find(|token| token.text() == "else")
.map(|token| usize::from(token.text_range().start()))
}
fn constexpr_condition_of(statement: &CppSyntaxNode) -> Option<String> {
let text = statement.text().to_string();
let at = text.find("constexpr")?;
let rest = &text[at + "constexpr".len()..];
let open = rest.find('(')?;
let mut depth = 0usize;
for (index, character) in rest[open..].char_indices() {
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(rest[open + 1..open + index].to_string());
}
}
_ => {}
}
}
None
}
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(" ")
}
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<CppSyntaxNode> {
declaration
.descendants()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::CompoundStat)
}
fn declaration_of(root: &CppSyntaxNode, binding: &Binding) -> Option<CppSyntaxNode> {
let token = cpp_parser::token_at(root, binding.name_range.start_offset)?;
token.parent_ancestors().find(|node| {
matches!(
CppSyntaxKind::from(node.kind()),
CppSyntaxKind::Declaration | CppSyntaxKind::FunctionDef
)
})
}
fn returned_expressions_in(body: &CppSyntaxNode) -> Vec<CppSyntaxNode> {
let mut found = Vec::new();
for statement in body.descendants() {
if CppSyntaxKind::from(statement.kind()) != CppSyntaxKind::ReturnStat {
continue;
}
if statement.ancestors().any(|node| {
matches!(
CppSyntaxKind::from(node.kind()),
CppSyntaxKind::LambdaExpr | CppSyntaxKind::FunctionDef
)
}) {
continue;
}
if let Some(expression) = statement.children().last() {
found.push(expression);
}
}
found
}
fn type_a_return_states_with(
expression: &CppSyntaxNode,
declaration: &CppSyntaxNode,
substitutions: &crate::sema::types::TypeSubstitutions<'_>,
) -> Option<String> {
match CppSyntaxKind::from(expression.kind()) {
CppSyntaxKind::NameExpr | CppSyntaxKind::IdentifierExpr => {
let written = parameter_type(expression, declaration)?;
Some(substituted_spelling(&written, substitutions))
}
CppSyntaxKind::BinaryExpr => {
let operands: Vec<CppSyntaxNode> = expression.children().collect();
let comparison = expression
.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| {
matches!(
token.text(),
"==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||"
)
});
if comparison {
return Some("bool".to_string());
}
let (left, right) = (operands.first()?, operands.last()?);
let left_type = type_a_return_states_with(left, declaration, substitutions)?;
let right_type = type_a_return_states_with(right, declaration, substitutions)?;
if left_type == right_type {
return Some(left_type);
}
let literal_zero = |operand: &CppSyntaxNode| {
CppSyntaxKind::from(operand.kind()) == CppSyntaxKind::LiteralExpr
&& matches!(
operand.text().to_string().trim(),
"0" | "0L" | "0U" | "0UL" | "0LL" | "0ULL"
)
};
if matches!(operator_of(expression).as_deref(), Some("+" | "-")) {
if literal_zero(right) {
return Some(left_type);
}
if literal_zero(left) {
return Some(right_type);
}
}
None
}
_ => type_a_return_states(expression, declaration),
}
}
fn type_a_return_states(expression: &CppSyntaxNode, declaration: &CppSyntaxNode) -> Option<String> {
match CppSyntaxKind::from(expression.kind()) {
CppSyntaxKind::CastExpr => {
let target = expression
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TypeId)?;
let written = target.text().to_string().trim().to_string();
(!written.is_empty()).then_some(written)
}
CppSyntaxKind::LiteralExpr => {
Some(literal_type(&expression.text().to_string()).to_string())
}
CppSyntaxKind::NameExpr | CppSyntaxKind::IdentifierExpr => {
parameter_type(expression, declaration)
}
CppSyntaxKind::BinaryExpr => {
let operands: Vec<CppSyntaxNode> = expression.children().collect();
let comparison = expression
.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| {
matches!(
token.text(),
"==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||"
)
});
if comparison {
return Some("bool".to_string());
}
let (left, right) = (operands.first()?, operands.last()?);
let left_type = type_a_return_states(left, declaration)?;
let right_type = type_a_return_states(right, declaration)?;
if left_type == right_type {
return Some(left_type);
}
let literal_zero = |operand: &CppSyntaxNode| {
CppSyntaxKind::from(operand.kind()) == CppSyntaxKind::LiteralExpr
&& matches!(
operand.text().to_string().trim(),
"0" | "0L" | "0U" | "0UL" | "0LL" | "0ULL" | "0u" | "0ul" | "0ll" | "0ull"
)
};
if matches!(operator_of(expression).as_deref(), Some("+" | "-")) {
if literal_zero(right) {
return Some(left_type);
}
if literal_zero(left) {
return Some(right_type);
}
}
None
}
_ => None,
}
}
fn operator_of(expression: &CppSyntaxNode) -> Option<String> {
expression
.children_with_tokens()
.filter_map(|element| element.into_token())
.map(|token| token.text().to_string())
.find(|text| {
!text.trim().is_empty()
&& text
.chars()
.all(|character| !character.is_alphanumeric() && character != '_')
})
}
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> {
let written = name.text().to_string();
let written = written.trim();
let parameter = declaration.descendants().find(|node| {
if CppSyntaxKind::from(node.kind()) != CppSyntaxKind::Parameter {
return false;
}
node.descendants().any(|child| {
matches!(
CppSyntaxKind::from(child.kind()),
CppSyntaxKind::Declarator | CppSyntaxKind::NameExpr
) && child.text().to_string().trim() == written
})
})?;
let whole = parameter.text().to_string();
let whole = whole.trim();
let at = whole.rfind(written)?;
let the_type = whole[..at].trim();
(!the_type.is_empty()).then(|| the_type.to_string())
}
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 {
let Some(declaration) = declaration_of(root, binding) else {
return false;
};
let Some(body) = declaration
.ancestors()
.find(|node| matches!(CppSyntaxKind::from(node.kind()), CppSyntaxKind::ClassBody))
else {
return false;
};
body.descendants()
.filter(|node| matches!(CppSyntaxKind::from(node.kind()), CppSyntaxKind::Declaration))
.any(|node| {
let text = node.text().to_string();
let text = text.trim();
let alias = if let Some(rest) = text.strip_prefix("using ") {
rest.split(|c: char| !(c.is_alphanumeric() || c == '_'))
.next()
.unwrap_or_default()
.to_string()
} else if text.starts_with("typedef ") {
let before_the_semicolon = text.trim_end_matches(';');
before_the_semicolon
.rsplit(|c: char| !(c.is_alphanumeric() || c == '_'))
.next()
.unwrap_or_default()
.to_string()
} else {
return false;
};
alias == 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) = node
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TypeId)
{
let spelling = type_id.text().to_string().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().to_string().trim().is_empty() {
String::new()
} else {
crate::sema::types::read_specifiers_named(&specifiers, Some(declared.as_str())).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)?;
let body = token
.parent_ancestors()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::ClassBody)?;
let default = match body.parent().map(|owner| CppSyntaxKind::from(owner.kind())) {
Some(CppSyntaxKind::StructDef | CppSyntaxKind::UnionDef) => Access::Public,
_ => Access::Private,
};
let mut level = default;
for child in body.children() {
if usize::from(child.text_range().start()) >= offset {
break;
}
level = match CppSyntaxKind::from(child.kind()) {
CppSyntaxKind::PublicAccess => Access::Public,
CppSyntaxKind::ProtectedAccess => Access::Protected,
CppSyntaxKind::PrivateAccess => 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 = node
.children_with_tokens()
.find_map(|element| element.into_token())
.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)?;
let declarator = token
.parent_ancestors()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Declarator)?;
crate::inlay::parameter_list_text(&declarator)
}
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 {
let at = u32::try_from(offset).unwrap_or(u32::MAX);
declarator.children().any(|child| {
matches!(CppSyntaxKind::from(child.kind()), CppSyntaxKind::NameExpr)
&& u32::from(child.text_range().start()) <= at
&& at < u32::from(child.text_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;
shapes
.templates
.iter()
.rev()
.find(|(introduced, _)| introduced.start_offset <= at && at <= introduced.end_offset())
.map(|(_, list)| crate::sema::types::template_parameter_names(list))
.unwrap_or_default()
}
fn declared_constraints_with(shapes: &DeclarationShapes, binding: &Binding) -> Vec<String> {
let at = binding.name_range.start_offset;
let Some((_, head)) = shapes
.templates
.iter()
.rev()
.find(|(introduced, _)| introduced.start_offset <= at && at <= introduced.end_offset())
else {
return Vec::new();
};
let constrained: Vec<(String, String)> = crate::sema::types::template_parameters_in(head)
.into_iter()
.filter(|(_, constraint)| !constraint.is_empty())
.collect();
if constrained.is_empty() {
return Vec::new();
}
let mut found = None;
shapes.on_the_path(at, |shape| {
if let Some(declarator) = &shape.declarator {
found = Some(declarator.clone());
}
});
let Some(declarator) = found else {
return Vec::new();
};
let Some(list) = declarator
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::ParameterList)
else {
return Vec::new();
};
let mut per_parameter = Vec::new();
for parameter in list.children() {
if CppSyntaxKind::from(parameter.kind()) != CppSyntaxKind::Parameter {
continue;
}
let written = parameter.text().to_string();
let constraint = constrained
.iter()
.find(|(name, _)| mentions_the_word(&written, name))
.map(|(_, constraint)| constraint.clone())
.unwrap_or_default();
per_parameter.push(constraint);
}
per_parameter
}
fn mentions_the_word(spelling: &str, word: &str) -> bool {
let mut rest = spelling;
while let Some(at) = rest.find(word) {
let before = rest[..at].chars().next_back();
let after = rest[at + word.len()..].chars().next();
let before_is_a_word =
before.is_some_and(|character| character.is_alphanumeric() || character == '_');
let after_is_a_word =
after.is_some_and(|character| character.is_alphanumeric() || character == '_');
if !before_is_a_word && !after_is_a_word {
return true;
}
rest = &rest[at + word.len()..];
}
false
}
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> {
if binding.kind != BindingKind::Class {
return Vec::new();
}
let mut owner = None;
shapes.on_the_path(the_offset_to_descend_by(binding), |shape| {
if matches!(
shape.kind,
CppSyntaxKind::ClassDef | CppSyntaxKind::StructDef | CppSyntaxKind::EnumDef
) {
owner = Some(shape.bases.clone());
}
});
let Some(bases) = owner else {
return Vec::new();
};
bases
.iter()
.map(|name| name.text().to_string().trim().to_string())
.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 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))
};
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 in_namespace = if local { in_namespace } else { None };
let pattern = pattern_of(shapes, binding);
Some(DeclFact {
kind: DeclKind::from_binding_kind(binding.kind),
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),
guard: FactGuard::Unconditional,
})
}
pub(crate) fn declared_parameter_defaults_with(
shapes: &DeclarationShapes,
binding: &Binding,
) -> Vec<String> {
if declared_template_parameters_with(shapes, binding).is_empty() {
return Vec::new();
}
let at = binding.name_range.start_offset;
let Some((_, head)) = shapes
.templates
.iter()
.rev()
.find(|(introduced, _)| introduced.start_offset <= at && at <= introduced.end_offset())
else {
return Vec::new();
};
let defaults = crate::sema::types::template_parameter_defaults(head);
if defaults.iter().any(|default| !default.is_empty()) {
defaults
} 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();
Some(segments.join("::"))
}
struct Declared {
range: cpp_parser::SourceRange,
touched: bool,
}
struct Declarations<'a> {
nodes: Vec<Declared>,
errors: &'a [SourceRange],
}
impl<'a> Declarations<'a> {
fn of(root: &CppSyntaxNode, errors: &'a [SourceRange]) -> Self {
let mut nodes = Vec::new();
if !errors.is_empty() {
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());
nodes.push(Declared {
range,
touched: errors.iter().any(|error| {
error.start_offset < range.end_offset()
&& range.start_offset < error.end_offset()
}),
});
}
nodes.sort_by_key(|declared| declared.range.length);
}
Declarations { nodes, errors }
}
fn is_clean(&self, name_range: SourceRange, own_range: SourceRange) -> bool {
match self
.nodes
.iter()
.find(|declared| contains(declared.range, name_range))
{
Some(declared) => !declared.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>,
}
impl<'a> DeclarationFacts<'a> {
fn new(
scopes: &'a ScopeTree,
preprocessing: &'a FilePreprocessing,
root: &'a CppSyntaxNode,
errors: &'a [SourceRange],
) -> Self {
DeclarationFacts {
scopes,
preprocessing,
root,
shapes: { DeclarationShapes::of(root) },
declarations: Declarations::of(root, errors),
guards: SummaryGuards::default(),
facts: Vec::new(),
}
}
fn build(self) -> (Vec<DeclFact>, SummaryGuards) {
let DeclarationFacts {
scopes,
preprocessing,
root,
shapes,
declarations,
mut guards,
mut facts,
} = self;
for (index, scope) in scopes.scopes().iter().enumerate() {
let id = ScopeId(index);
if scope.kind == ScopeKind::TemplateParameters {
continue;
}
let (prefix, local) = match scope.kind {
ScopeKind::Function | ScopeKind::Block | ScopeKind::Lambda => (None, true),
_ => (
scopes.qualification_prefix_of(id),
scopes.declares_a_local(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);
}
}
}
for (binding, scope, parameters) in qualified_declarations(root) {
if let Some(existing) = facts
.iter_mut()
.find(|fact| fact.name_range.start_offset == binding.name_range.start_offset)
{
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;
}
facts.push(fact);
}
}
facts.sort_by_key(|fact| fact.range.start_offset);
let mut targets: Vec<(&mut FactGuard, usize)> = facts
.iter_mut()
.map(|fact| (&mut fact.guard, fact.range.start_offset))
.collect();
assign_guards(&mut targets, preprocessing, &mut guards);
(facts, guards)
}
}
fn qualified_declarations(root: &CppSyntaxNode) -> Vec<(Binding, String, Option<String>)> {
let mut found = Vec::new();
for node in root.descendants() {
if !matches!(
CppSyntaxKind::from(node.kind()),
CppSyntaxKind::Declaration | CppSyntaxKind::FunctionDef
) {
continue;
}
if node.ancestors().any(|ancestor| {
matches!(
CppSyntaxKind::from(ancestor.kind()),
CppSyntaxKind::CompoundStat
)
}) {
continue;
}
let Some(declarator) = node.children().find(|child| {
matches!(
CppSyntaxKind::from(child.kind()),
CppSyntaxKind::InitDeclarator | CppSyntaxKind::Declarator
)
}) else {
continue;
};
let outer = declarator
.children()
.find(|child| matches!(CppSyntaxKind::from(child.kind()), CppSyntaxKind::Declarator))
.unwrap_or_else(|| declarator.clone());
let names_itself = outer
.children()
.any(|child| matches!(CppSyntaxKind::from(child.kind()), CppSyntaxKind::NameExpr));
let from_the_declarator = outer
.children()
.find(|child| {
matches!(CppSyntaxKind::from(child.kind()), CppSyntaxKind::NameExpr)
&& child.text().to_string().contains("::")
})
.map(|name| (name, true));
let from_the_specifiers = (!names_itself)
.then(|| {
node.children()
.find(|child| {
matches!(
CppSyntaxKind::from(child.kind()),
CppSyntaxKind::DeclSpecifierSeq
)
})
.and_then(|specifiers| {
specifiers
.descendants()
.filter(|child| {
matches!(CppSyntaxKind::from(child.kind()), CppSyntaxKind::NameExpr)
&& child.text().to_string().contains("::")
})
.last()
})
})
.flatten()
.map(|name| (name, false));
let (name_node, _from_declarator) = match (from_the_declarator, from_the_specifiers) {
(Some(found), _) => found,
(None, Some(found)) => found,
(None, None) => continue,
};
let spelling = name_node.text().to_string();
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
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| {
cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::Identifier
&& token.text() == name
})
.last()
.map(|token| cpp_parser::source_range(token.text_range()))
.unwrap_or_else(|| cpp_parser::source_range(name_node.text_range()));
let has_parameters = node.descendants().any(|child| {
matches!(
CppSyntaxKind::from(child.kind()),
CppSyntaxKind::ParameterList
)
});
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(&node),
name_range,
scope: ScopeId(0),
origin: None,
},
qualifier.to_string(),
node.children()
.filter(|child| {
!matches!(
CppSyntaxKind::from(child.kind()),
CppSyntaxKind::CompoundStat
)
})
.find_map(|child| {
child
.descendants()
.find(|child| {
matches!(
CppSyntaxKind::from(child.kind()),
CppSyntaxKind::ParameterList
)
})
.map(|list| crate::inlay::tidy_list_text(&list.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.clone())
} else {
BranchCondition::Defined(name.text.clone())
}
}
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 {
shapes
.specifiers_at(the_offset_to_descend_by(binding))
.map(|node| node.text().to_string())
.is_some_and(|text| {
text.lines().any(|line| {
let Some(directive) = line.trim_start().strip_prefix('#') else {
return false;
};
let word: &str = directive
.trim_start()
.split(|character: char| !character.is_ascii_alphanumeric())
.next()
.unwrap_or_default();
matches!(word, "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, &[]);
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,
&[],
)
}
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,
)
.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{}; }\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,
None,
"a deduced `auto` is not a class anything can be looked up in"
);
assert_eq!(of("plain").returns.as_deref(), Some("void"));
}
}