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 Exp13C;
impl CertRule for Exp13C {
fn rule_id(&self) -> &'static str {
"EXP13-C"
}
fn description(&self) -> &'static str {
"Treat relational and equality operators as if they were nonassociative"
}
fn severity(&self) -> Severity {
Severity::Low
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"EXP13-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
if node.kind() == "binary_expression" {
if let Some(operator_node) = node.child_by_field_name("operator") {
let operator = get_node_text(&operator_node, source);
if is_relational_or_equality_operator(operator) {
if let Some(left) = node.child_by_field_name("left") {
if contains_relational_or_equality(&left, source) {
report_violation(node, source, &mut violations);
}
}
if let Some(right) = node.child_by_field_name("right") {
if contains_relational_or_equality(&right, source) {
report_violation(node, source, &mut violations);
}
}
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
violations.extend(self.check(&child, source));
}
}
violations
}
}
fn is_relational_or_equality_operator(op: &str) -> bool {
matches!(op, "<" | ">" | "<=" | ">=" | "==" | "!=")
}
fn contains_relational_or_equality(node: &Node, source: &str) -> bool {
match node.kind() {
"binary_expression" => {
if let Some(operator_node) = node.child_by_field_name("operator") {
let operator = get_node_text(&operator_node, source);
is_relational_or_equality_operator(operator)
} else {
false
}
}
"parenthesized_expression" => {
false
}
_ => false,
}
}
fn report_violation(node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
let start_point = node.start_position();
let node_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: "EXP13-C".to_string(),
severity: Severity::Low,
message: format!(
"Chained relational or equality operators should use explicit logical operators: '{}'",
node_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some(
"Use explicit logical operators (&&, ||) to clarify intent: e.g., (a < b) && (b < c)"
.to_string(),
),
..Default::default()
});
}