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 Pre11C;
impl Pre11C {
pub fn new() -> Self {
Self
}
fn check_macro_definition(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
let is_macro = node.kind() == "preproc_def" || node.kind() == "preproc_function_def";
if !is_macro {
return;
}
let value_node = match node.child_by_field_name("value") {
Some(v) => v,
None => return, };
let value_text = get_node_text(&value_node, source);
let trimmed = value_text.trim_end();
if trimmed.ends_with(';') {
let macro_name = if let Some(name_node) = node.child_by_field_name("name") {
get_node_text(&name_node, source)
} else {
"(unknown)"
};
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Macro '{}' definition ends with a semicolon. This can cause unexpected behavior when the macro is used.",
macro_name
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some(
"Remove the trailing semicolon from the macro definition. The semicolon should be added by the macro user, not in the definition.".to_string()
),
..Default::default()
});
}
}
}
impl CertRule for Pre11C {
fn rule_id(&self) -> &'static str {
"PRE11-C"
}
fn description(&self) -> &'static str {
"Do not conclude macro definitions with a semicolon"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn cert_id(&self) -> &'static str {
"PRE11-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.check_node(node, source, &mut violations);
violations
}
}
impl Pre11C {
fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
self.check_macro_definition(node, source, violations);
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_node(&child, source, violations);
}
}
}
}