use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use tree_sitter::Node;
pub struct Con41C;
impl CertRule for Con41C {
fn rule_id(&self) -> &'static str {
"CON41-C"
}
fn description(&self) -> &'static str {
"Wrap functions that can fail spuriously in a loop"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn cert_id(&self) -> &'static str {
"CON41-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.check_node(node, source, &mut violations);
violations
}
}
impl Con41C {
fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if node.kind() == "call_expression" {
if let Some(func) = node.child_by_field_name("function") {
let func_name = get_node_text(&func, source);
if matches!(
func_name,
"atomic_compare_exchange_weak" | "atomic_compare_exchange_weak_explicit"
) {
if !self.is_in_loop(node) {
let line = node.start_position().row + 1;
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Function '{}' can fail spuriously and must be wrapped in a loop (C11 7.17.7.4)",
func_name
),
file_path: String::new(),
line,
column: 0,
suggestion: Some(
format!("Wrap {} in a while/for/do-while loop to handle spurious failures", func_name)
),
..Default::default()
});
}
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_node(&child, source, violations);
}
}
}
fn is_in_loop(&self, node: &Node) -> bool {
let mut current = node.parent();
while let Some(parent) = current {
match parent.kind() {
"while_statement" | "for_statement" | "do_statement" => {
return true;
}
"function_definition" => {
return false;
}
_ => {
current = parent.parent();
}
}
}
false
}
}