use std::path::Path;
use cpp_parser::SourceRange;
use crate::file::view::FileView;
use crate::{FileSummary, ProjectIndex};
pub mod access_invisible;
pub mod argument_count;
pub mod assign_type_check;
pub mod assignment_in_condition;
pub mod config;
pub mod diagnostic_code;
mod borrowed;
mod braces_around_statements;
pub mod concept_not_satisfied;
mod cstyle_cast;
mod dangling_field;
mod dangling_return;
mod else_after_return;
mod implicit_bool_conversion;
pub mod include_not_found;
mod macro_parentheses;
pub mod macro_redefined;
pub mod missing_return;
pub mod param_type_check;
pub mod redefinition;
pub mod return_type_mismatch;
mod simplify_boolean_expr;
pub mod syntax_error;
mod ue_generate_body;
mod ue_naming;
pub mod undefined_field;
pub mod undefined_name;
pub mod unnecessary_branch;
mod unreal;
pub mod unused;
mod use_after_free;
mod use_auto;
mod use_nullptr;
mod use_override;
pub use config::CheckConfig;
pub use diagnostic_code::{DiagnosticCode, RuleSeverity, RuleTag};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
pub range: SourceRange,
pub name: String,
pub code: DiagnosticCode,
pub message: String,
}
pub trait Check {
const CODES: &'static [DiagnosticCode];
fn check(context: &mut CheckContext<'_>);
}
pub fn run_check<T: Check>(context: &mut CheckContext<'_>) {
if context.is_c() && T::CODES.iter().all(|code| code.is_cpp_only()) {
return;
}
if !context.unreal && T::CODES.iter().all(|code| code.is_unreal_only()) {
return;
}
if T::CODES.iter().any(|code| context.config.is_enabled(*code)) {
if crate::probes::time_checks() {
let at = std::time::Instant::now();
T::check(context);
let took = at.elapsed();
if took.as_millis() > 0 {
eprintln!(
"[check] {:<32} {:>6} ms {}",
std::any::type_name::<T>()
.rsplit("::")
.next()
.unwrap_or("?"),
took.as_millis(),
context.path.display()
);
}
} else {
T::check(context);
}
}
}
pub struct CheckContext<'a> {
pub path: &'a Path,
pub summary: &'a FileSummary,
pub model: crate::sema::model::SemanticModel<'a>,
pub source: &'a str,
pub written: &'a str,
pub errors: &'a [cpp_parser::CppParseError],
pub view: &'a FileView,
pub config: CheckConfig,
pub language: cpp_parser::features::LanguageConfig,
pub unreal: bool,
findings: Vec<Finding>,
}
impl<'a> CheckContext<'a> {
pub fn new(
path: &'a Path,
summary: &'a FileSummary,
model: crate::sema::model::SemanticModel<'a>,
source: &'a str,
written: &'a str,
errors: &'a [cpp_parser::CppParseError],
view: &'a FileView,
config: CheckConfig,
language: cpp_parser::features::LanguageConfig,
unreal: bool,
) -> Self {
CheckContext {
path,
summary,
model,
source,
written,
errors,
config,
view,
language,
unreal,
findings: Vec::new(),
}
}
pub fn add(
&mut self,
code: DiagnosticCode,
range: SourceRange,
name: impl Into<String>,
message: impl Into<String>,
) {
let in_the_reading = range;
let range = self.in_the_file(range);
self.push(code, range, Some(in_the_reading), name, message);
}
pub fn add_in_the_file(
&mut self,
code: DiagnosticCode,
range: SourceRange,
name: impl Into<String>,
message: impl Into<String>,
) {
self.push(code, range, None, name, message);
}
pub fn node_text(&self, node: &cpp_parser::CppSyntaxNode) -> &'a str {
let range = cpp_parser::source_range(node.text_range());
self.source
.get(range.start_offset..range.end_offset())
.unwrap_or_default()
}
pub fn is_c(&self) -> bool {
self.language.family() == Some(cpp_parser::features::Family::C)
}
pub fn comments_and_literals(&self) -> Vec<SourceRange> {
let (tokens, _) = cpp_parser::lex(self.written, &cpp_parser::LexerConfig::default());
tokens
.into_iter()
.filter(|token| {
matches!(
token.kind,
cpp_parser::CppTokenKind::LineComment
| cpp_parser::CppTokenKind::BlockComment
| cpp_parser::CppTokenKind::StringLiteral
| cpp_parser::CppTokenKind::CharLiteral
)
})
.map(|token| token.range)
.collect()
}
pub fn in_a_comment_or_literal(&self, offset: usize, protected: &[SourceRange]) -> bool {
protected
.iter()
.any(|range| offset >= range.start_offset && offset < range.end_offset())
}
fn in_the_file(&self, range: SourceRange) -> SourceRange {
let Some(start) = self
.view
.file_offset_of(crate::file::coordinates::ReadingOffset::new(
range.start_offset,
))
else {
return range;
};
let end = self
.view
.file_offset_of_end(crate::file::coordinates::ReadingOffset::new(
range.end_offset(),
))
.unwrap_or(start);
SourceRange::new(start.get(), end.get().saturating_sub(start.get()))
}
fn push(
&mut self,
code: DiagnosticCode,
range: SourceRange,
in_the_reading: Option<SourceRange>,
name: impl Into<String>,
message: impl Into<String>,
) {
if !self.config.is_enabled(code) {
return;
}
if self.is_c() && code.is_cpp_only() {
return;
}
if let Some(in_the_reading) = in_the_reading
&& !self.view.was_written_here(in_the_reading)
{
return;
}
self.findings.push(Finding {
range,
name: name.into(),
code,
message: message.into(),
});
}
pub fn tree(&self) -> &cpp_parser::CppSyntaxNode {
self.model.tree()
}
pub fn scopes(&self) -> &crate::ScopeTree {
self.model.scopes()
}
pub fn index(&self) -> &ProjectIndex {
self.model.index()
}
pub fn root(&self) -> Option<cpp_parser::CppTranslationUnit> {
use cpp_parser::CppAstNode;
cpp_parser::CppTranslationUnit::cast(self.tree().clone())
}
pub fn type_of(
&self,
expression: &cpp_parser::CppSyntaxNode,
) -> crate::Known<(crate::sema::types::Type, std::path::PathBuf)> {
self.model.type_of(expression)
}
fn own_top_level_nodes(&self) -> Vec<cpp_parser::CppSyntaxNode> {
let root = self.tree().clone();
let mut kept = Vec::new();
for child in root.children() {
let range = cpp_parser::source_range(child.text_range());
if self.view.was_written_here(range) {
kept.push(child);
}
}
kept
}
pub fn own_syntax_nodes(&self) -> impl Iterator<Item = cpp_parser::CppSyntaxNode> + '_ {
self.own_top_level_nodes()
.into_iter()
.flat_map(|child| child.descendants())
}
pub fn own<T: cpp_parser::CppAstNode + 'static>(&self) -> impl Iterator<Item = T> + '_ {
self.own_syntax_nodes().filter_map(T::cast)
}
pub fn member_accesses(
&self,
) -> Vec<(
cpp_parser::CppSyntaxNode,
crate::sema::resolve::MemberAccess,
)> {
use cpp_parser::CppSyntaxKind;
self.own_syntax_nodes()
.filter(|node| {
matches!(
CppSyntaxKind::from(node.kind()),
CppSyntaxKind::IndexExpr | CppSyntaxKind::MemberExpr | CppSyntaxKind::ArrowExpr
)
})
.filter_map(|node| {
crate::sema::resolve::member_access_of(&node).map(|access| (node, access))
})
.collect()
}
pub fn own_tokens(&self) -> impl Iterator<Item = cpp_parser::CppTokenData> + '_ {
self.own_top_level_nodes()
.into_iter()
.flat_map(|child| child.descendants_with_tokens().collect::<Vec<_>>())
.filter_map(|element| element.into_token())
.map(|token| cpp_parser::CppTokenData {
kind: token.kind().into(),
range: cpp_parser::source_range(token.text_range()),
})
}
fn into_findings(mut self) -> Vec<Finding> {
self.findings
.sort_by_key(|finding| (finding.range.start_offset, finding.range.length));
self.findings
}
}
pub fn condition_of(statement: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSyntaxNode> {
use cpp_parser::CppAstNode;
cpp_parser::CppParenExpr::cast(statement.clone())
.is_some()
.then(|| statement.clone())
.or_else(|| {
statement
.children()
.find_map(|child| cpp_parser::CppParenExpr::cast(child).map(|p| p.syntax().clone()))
})
}
pub fn literal_condition_of(condition: &cpp_parser::CppSyntaxNode) -> Option<String> {
use cpp_parser::CppTokenKind;
let mut words = Vec::new();
for token in condition
.descendants_with_tokens()
.filter_map(|element| element.into_token())
{
match CppTokenKind::from(token.kind()) {
CppTokenKind::LeftParen
| CppTokenKind::RightParen
| CppTokenKind::Whitespace
| CppTokenKind::Newline => {}
CppTokenKind::TrueKeyword => words.push("true".to_string()),
CppTokenKind::FalseKeyword => words.push("false".to_string()),
_ => return None,
}
}
match words.as_slice() {
[word] => Some(word.clone()),
_ => None,
}
}
pub fn is_a_class_definition(node: &cpp_parser::CppSyntaxNode) -> bool {
use cpp_parser::CppAstNode;
cpp_parser::CppClassDef::cast(node.clone()).is_some()
}
pub fn is_a_function_definition(node: &cpp_parser::CppSyntaxNode) -> bool {
use cpp_parser::{CppAstNode, CppCompoundStat, CppDeclaration, CppParamList};
let Some(declaration) = CppDeclaration::cast(node.clone()) else {
return false;
};
let Some(body) = declaration.children::<CppCompoundStat>().next() else {
return false;
};
let body = span_of(body.syntax());
let Some(parameters) = declaration
.get_init_declarator()
.and_then(|declarator| declarator.get_declarator())
.and_then(|declarator| {
declarator
.syntax()
.descendants()
.find_map(CppParamList::cast)
})
.map(|parameters| span_of(parameters.syntax()))
else {
return false;
};
!contains(parameters, body) && parameters.0 < body.0
}
fn span_of(node: &cpp_parser::CppSyntaxNode) -> (usize, usize) {
let range = node.text_range();
(usize::from(range.start()), usize::from(range.end()))
}
fn contains(outer: (usize, usize), inner: (usize, usize)) -> bool {
outer.0 <= inner.0 && outer.1 >= inner.1
}
pub fn body_of(function: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSyntaxNode> {
use cpp_parser::{CppAstNode, CppCompoundStat, CppDeclaration};
CppDeclaration::cast(function.clone())?
.children::<CppCompoundStat>()
.next()
.map(|body| body.syntax().clone())
}
pub fn function_definitions(context: &CheckContext<'_>) -> Vec<cpp_parser::CppSyntaxNode> {
context
.own_syntax_nodes()
.filter(is_a_function_definition)
.collect()
}
const NOT_A_TYPE: &[&str] = &[
"constexpr",
"consteval",
"constinit",
"static",
"inline",
"virtual",
"explicit",
"friend",
"extern",
"mutable",
"register",
"thread_local",
"typedef",
];
pub struct FunctionHead {
pub returns: Option<String>,
pub name: String,
pub name_range: cpp_parser::SourceRange,
}
pub fn return_type_written_by(function: &cpp_parser::CppSyntaxNode) -> Option<String> {
function_head(function)?.returns
}
pub fn function_head(function: &cpp_parser::CppSyntaxNode) -> Option<FunctionHead> {
use cpp_parser::{CppAstNode, CppParamList};
let parameters = function.descendants().find_map(CppParamList::cast)?;
let open = usize::from(parameters.syntax().text_range().start());
let head: Vec<cpp_parser::CppSyntaxToken> = function
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| usize::from(token.text_range().end()) <= open)
.filter(|token| !cpp_parser::is_trivia(cpp_parser::CppTokenKind::from(token.kind())))
.collect();
let (name, name_range, name_starts_at) =
match head.iter().position(|token| token.text() == "operator") {
Some(at) => {
let last = head.last()?;
(
head[at..]
.iter()
.map(|token| token.text().to_string())
.collect::<String>(),
cpp_parser::source_range(head[at].text_range().cover(last.text_range())),
at,
)
}
None => {
let at = head.iter().rposition(|token| {
token.kind() == cpp_parser::CppTokenKind::Identifier.into()
})?;
let start = if at > 0 && head[at - 1].text() == "~" {
at - 1
} else {
at
};
(
head[start..=at]
.iter()
.map(|token| token.text().to_string())
.collect::<String>(),
cpp_parser::source_range(head[start].text_range().cover(head[at].text_range())),
start,
)
}
};
let before_the_name = &head[..name_starts_at];
let mut returns = String::new();
let mut previous_end: Option<usize> = None;
let own_text = function.text().to_string();
let function_starts = usize::from(function.text_range().start());
for token in before_the_name {
let range = token.text_range();
let (start, end) = (usize::from(range.start()), usize::from(range.end()));
if let Some(previous_end) = previous_end {
let gap = source_between(&own_text, function_starts, previous_end, start);
returns.push_str(gap);
}
returns.push_str(token.text());
previous_end = Some(end);
}
for specifier in NOT_A_TYPE {
returns = returns
.split(' ')
.filter(|word| word.trim() != *specifier)
.collect::<Vec<_>>()
.join(" ");
}
let returns = returns.trim().to_string();
let mut returns = returns.trim().to_string();
if returns.ends_with("::") {
returns = strip_trailing_scopes(&returns);
}
let returns = returns.trim().to_string();
let returns = if returns.is_empty()
|| name.starts_with('~')
|| name.starts_with("operator")
|| declares_the_enclosing_class_named(function, &name)
{
None
} else {
Some(returns)
};
Some(FunctionHead {
returns,
name,
name_range,
})
}
fn source_between(function_text: &str, function_starts: usize, from: usize, to: usize) -> &str {
let (from, to) = (
from.saturating_sub(function_starts),
to.saturating_sub(function_starts),
);
function_text.get(from..to).unwrap_or(" ")
}
fn strip_trailing_scopes(head: &str) -> String {
let mut head = head.trim_end().to_string();
while head.ends_with("::") {
head.truncate(head.len() - 2);
head = head.trim_end().to_string();
let word_starts = head
.rfind(|character: char| !(character.is_alphanumeric() || character == '_'))
.map(|at| at + 1)
.unwrap_or(0);
head.truncate(word_starts);
head = head.trim_end().to_string();
}
head
}
fn declares_the_enclosing_class_named(function: &cpp_parser::CppSyntaxNode, name: &str) -> bool {
use cpp_parser::CppSyntaxKind;
for ancestor in function.ancestors().skip(1) {
match CppSyntaxKind::from(ancestor.kind()) {
CppSyntaxKind::StructDef | CppSyntaxKind::ClassDef | CppSyntaxKind::UnionDef => {
let declared = ancestor
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::ClassBody)
.and_then(|body| {
ancestor
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.take_while(|token| {
token.text_range().end() <= body.text_range().start()
})
.filter(|token| {
token.kind() == cpp_parser::CppTokenKind::Identifier.into()
})
.last()
.map(|token| token.text().to_string())
});
return declared.as_deref() == Some(name.trim_start_matches('~'));
}
CppSyntaxKind::CompoundStat => return false,
_ => {}
}
}
false
}
pub fn spelling_of(node: &cpp_parser::CppSyntaxNode) -> Option<String> {
node.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| token.kind() == cpp_parser::CppTokenKind::Identifier.into())
.last()
.map(|token| token.text().to_string())
}
pub fn name_token_of(function: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSyntaxToken> {
use cpp_parser::{CppAstNode, CppParamList};
let parameters = function.descendants().find_map(CppParamList::cast)?;
let open = usize::from(parameters.syntax().text_range().start());
function
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| usize::from(token.text_range().end()) <= open)
.filter(|token| !cpp_parser::is_trivia(cpp_parser::CppTokenKind::from(token.kind())))
.filter(|token| token.kind() == cpp_parser::CppTokenKind::Identifier.into())
.last()
}
pub fn name_declared_by(function: &cpp_parser::CppSyntaxNode) -> Option<String> {
Some(function_head(function)?.name)
}
pub fn parameter_spellings_of(function: &cpp_parser::CppSyntaxNode) -> Vec<String> {
use cpp_parser::{CppAstNode, CppDeclaration, CppParam, CppParamList};
let Some(parameters) = CppDeclaration::cast(function.clone())
.and_then(|declaration| declaration.descendants::<CppParamList>().next())
else {
return Vec::new();
};
parameters
.children::<CppParam>()
.map(|parameter| parameter.syntax().text().to_string().trim().to_string())
.filter(|spelling| !spelling.is_empty())
.collect()
}
pub fn a_class_can_be_built_from(
context: &CheckContext<'_>,
class: &str,
value: &crate::sema::types::Type,
) -> Option<bool> {
if class.is_empty() {
return None;
}
if !value.is_arithmetic() {
return None;
}
let crate::Known::Yes(members) = context.model.own_members_of(class) else {
return None;
};
if members.is_empty() {
return None;
}
let mut constructors = 0usize;
for (_, fact) in &members {
let name = fact.name.as_str();
let is_a_constructor = name == class.rsplit("::").next().unwrap_or(class);
if name.starts_with("operator") {
return None;
}
if !is_a_constructor {
continue;
}
let Some(parameters) = fact.parameter_list.as_deref() else {
continue;
};
constructors += 1;
match parameters_that_could_accept(parameters, value) {
Some(true) => return Some(true),
None => return None,
Some(false) => {}
}
}
let _ = constructors;
Some(false)
}
fn parameters_that_could_accept(written: &str, value: &crate::sema::types::Type) -> Option<bool> {
if !value.is_arithmetic() {
return None;
}
let inner = written.trim().trim_start_matches('(').trim_end_matches(')');
let mut depth = 0i32;
let mut parameters: Vec<String> = Vec::new();
let mut current = String::new();
for character in inner.chars() {
match character {
'<' | '(' | '[' => depth += 1,
'>' | ')' | ']' => depth -= 1,
',' if depth == 0 => {
parameters.push(std::mem::take(&mut current));
continue;
}
_ => {}
}
current.push(character);
}
parameters.push(current);
if parameters.len() > 1 {
return if parameters.iter().any(|parameter| parameter.contains('=')) {
None
} else {
Some(false)
};
}
let mut any = false;
for parameter in parameters {
let Some(classified) = could_take_an_arithmetic_value(¶meter) else {
return None;
};
any = true;
if classified {
return Some(true);
}
}
any.then_some(false)
}
fn could_take_an_arithmetic_value(parameter: &str) -> Option<bool> {
let mut written = parameter.trim();
if let Some(at) = written.find('=') {
written = written[..at].trim();
}
if written.is_empty() || written == "..." || written.ends_with("...") {
return Some(written == "..." || written.ends_with("..."));
}
let words: Vec<&str> = written.split_whitespace().collect();
let (type_words, _name) = match words.as_slice() {
[] => return None,
[only] => (vec![*only], ""),
[rest @ .., last] => (rest.to_vec(), *last),
};
let type_written = type_words.join(" ");
let arithmetic = |word: &str| {
let word = word.trim_start_matches("const").trim();
matches!(
word,
"int"
| "long"
| "short"
| "char"
| "signed"
| "unsigned"
| "float"
| "double"
| "bool"
| "wchar_t"
| "char8_t"
| "char16_t"
| "char32_t"
| "size_t"
| "std::size_t"
| "ptrdiff_t"
| "int64_t"
| "uint64_t"
| "int32_t"
| "uint32_t"
| "std::int64_t"
| "std::uint64_t"
)
};
let behind_the_operator = type_written
.split(['*', '&'])
.next()
.unwrap_or_default()
.trim()
.trim_start_matches("const")
.trim();
let is_a_pointer_or_reference = type_written.contains('*') || type_written.contains('&');
if is_a_pointer_or_reference {
if type_written.contains('*') {
return Some(false);
}
return Some(arithmetic(behind_the_operator));
}
let bare = type_written.trim_start_matches("const").trim();
if arithmetic(bare) {
return Some(true);
}
let looks_like_a_template_parameter = bare.starts_with('_')
|| bare == "T"
|| bare.len() == 1
|| bare.starts_with("class ")
|| bare.starts_with("typename ");
if looks_like_a_template_parameter {
return None;
}
Some(false)
}
pub fn run(context: CheckContext<'_>) -> Vec<Finding> {
let mut context = context;
run_check::<include_not_found::IncludeNotFound>(&mut context);
run_check::<macro_redefined::MacroRedefined>(&mut context);
run_check::<macro_parentheses::MacroParentheses>(&mut context);
if !context.errors.is_empty() {
return std::mem::take(&mut context.findings);
}
run_check::<unused::Unused>(&mut context);
run_check::<braces_around_statements::BracesAroundStatements>(&mut context);
run_check::<use_nullptr::UseNullptr>(&mut context);
run_check::<concept_not_satisfied::ConceptNotSatisfied>(&mut context);
run_check::<use_override::UseOverride>(&mut context);
run_check::<simplify_boolean_expr::SimplifyBooleanExpr>(&mut context);
run_check::<else_after_return::ElseAfterReturn>(&mut context);
run_check::<cstyle_cast::CStyleCast>(&mut context);
run_check::<use_auto::UseAuto>(&mut context);
run_check::<implicit_bool_conversion::ImplicitBoolConversion>(&mut context);
run_check::<access_invisible::AccessInvisible>(&mut context);
run_check::<missing_return::MissingReturn>(&mut context);
run_check::<assignment_in_condition::AssignmentInCondition>(&mut context);
run_check::<unnecessary_branch::UnnecessaryBranch>(&mut context);
run_check::<undefined_field::UndefinedField>(&mut context);
run_check::<undefined_name::UndefinedName>(&mut context);
run_check::<redefinition::Redefinition>(&mut context);
run_check::<argument_count::ArgumentCount>(&mut context);
run_check::<param_type_check::ParamTypeCheck>(&mut context);
run_check::<assign_type_check::AssignTypeCheck>(&mut context);
run_check::<return_type_mismatch::ReturnTypeMismatch>(&mut context);
run_check::<dangling_return::DanglingReturn>(&mut context);
run_check::<dangling_field::DanglingField>(&mut context);
run_check::<use_after_free::UseAfterFree>(&mut context);
run_check::<ue_naming::UeNaming>(&mut context);
run_check::<ue_generate_body::UeGenerateBody>(&mut context);
if crate::probes::timing() {
let (ran, nanos) = context.model.inference_cost();
let (inferred, reused) = context.model.inference_stats();
eprintln!(
"[checks] inference: {ran} question(s) in {} ms ({inferred} computed, {reused} reused)",
nanos / 1_000_000
);
}
context.into_findings()
}
pub fn member_access_above(
node: &cpp_parser::CppSyntaxNode,
) -> Option<crate::sema::resolve::MemberAccess> {
let mut current = Some(node.clone());
for _ in 0..3 {
let node = current?;
if let Some(access) = crate::sema::resolve::member_access_of(&node) {
return Some(access);
}
current = node.parent();
}
None
}