use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use std::collections::{HashMap, HashSet};
use tree_sitter::Node;
pub struct Int14C;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum OperationType {
Bitwise,
Arithmetic,
}
impl Int14C {
#[allow(dead_code)]
pub fn new() -> Self {
Self
}
fn is_bitwise_operator(&self, op: &str) -> bool {
matches!(op, "~" | "<<" | ">>" | "&" | "|" | "^")
}
fn is_arithmetic_operator(&self, op: &str) -> bool {
matches!(op, "+" | "-" | "*" | "/" | "%")
}
fn is_shift_operator(&self, op: &str) -> bool {
matches!(op, "<<" | ">>" | "<<=" | ">>=")
}
fn collect_signed_int_params(&self, node: &Node, source: &str) -> HashSet<String> {
let mut params = HashSet::new();
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "function_declarator" {
self.collect_params_from_declarator(&child, source, &mut params);
}
}
}
params
}
fn collect_params_from_declarator(
&self,
node: &Node,
source: &str,
params: &mut HashSet<String>,
) {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "parameter_list" {
self.collect_params_from_list(&child, source, params);
}
}
}
}
fn collect_params_from_list(&self, node: &Node, source: &str, params: &mut HashSet<String>) {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "parameter_declaration" {
let param_text = get_node_text(&child, source);
if (param_text.contains("int")
|| param_text.contains("short")
|| param_text.contains("long"))
&& !param_text.contains("unsigned")
{
if let Some(name) = self.extract_param_name(&child, source) {
params.insert(name);
}
}
}
}
}
}
fn extract_param_name(&self, node: &Node, source: &str) -> Option<String> {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "identifier" {
return Some(get_node_text(&child, source).to_string());
}
}
}
None
}
fn extract_variables(node: &Node, source: &str, vars: &mut HashSet<String>) {
if node.kind() == "identifier" {
let var_name = get_node_text(node, source).to_string();
vars.insert(var_name);
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
Self::extract_variables(&child, source, vars);
}
}
}
fn get_operator(&self, node: &Node, source: &str) -> Option<String> {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
let kind = child.kind();
if kind == "+"
|| kind == "-"
|| kind == "*"
|| kind == "/"
|| kind == "%"
|| kind == "<<"
|| kind == ">>"
|| kind == "&"
|| kind == "|"
|| kind == "^"
{
return Some(kind.to_string());
}
let text = get_node_text(&child, source);
if self.is_bitwise_operator(text) || self.is_arithmetic_operator(text) {
return Some(text.to_string());
}
}
}
None
}
fn check_function(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
let mut variable_operations: HashMap<String, HashSet<OperationType>> = HashMap::new();
let mut variable_locations: HashMap<String, (usize, usize)> = HashMap::new();
let signed_int_params = self.collect_signed_int_params(node, source);
let mut shift_operations: HashMap<String, (usize, usize)> = HashMap::new();
self.analyze_operations(
node,
source,
&mut variable_operations,
&mut variable_locations,
&signed_int_params,
&mut shift_operations,
);
for (var_name, operations) in variable_operations.iter() {
if var_name.len() == 2 {
continue;
}
if operations.contains(&OperationType::Bitwise)
&& operations.contains(&OperationType::Arithmetic)
{
let (line, column) = variable_locations.get(var_name).unwrap_or(&(0, 0));
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Variable '{}' used with both bitwise and arithmetic operations (reduces code readability)",
var_name
),
file_path: String::new(),
line: *line,
column: *column,
suggestion: Some(
"Use separate variables for bitwise and arithmetic operations, or refactor to use only arithmetic operators".to_string()
),
..Default::default()
});
}
}
for (var_name, (line, column)) in shift_operations.iter() {
if let Some(ops) = variable_operations.get(var_name) {
if ops.contains(&OperationType::Bitwise) && ops.contains(&OperationType::Arithmetic)
{
continue;
}
}
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Shift operation on signed integer '{}' may be used for arithmetic optimization (use explicit arithmetic instead)",
var_name
),
file_path: String::new(),
line: *line,
column: *column,
suggestion: Some(
"Use explicit arithmetic operations like * or / instead of shift operations on signed integers".to_string()
),
..Default::default()
});
}
}
fn analyze_operations(
&self,
node: &Node,
source: &str,
variable_operations: &mut HashMap<String, HashSet<OperationType>>,
variable_locations: &mut HashMap<String, (usize, usize)>,
signed_int_params: &HashSet<String>,
shift_operations: &mut HashMap<String, (usize, usize)>,
) {
if node.kind() == "binary_expression" {
if let Some(op) = self.get_operator(node, source) {
let op_type = if self.is_bitwise_operator(&op) {
Some(OperationType::Bitwise)
} else if self.is_arithmetic_operator(&op) {
Some(OperationType::Arithmetic)
} else {
None
};
if let Some(op_type) = op_type {
let mut vars = HashSet::new();
Self::extract_variables(node, source, &mut vars);
for var in vars.iter() {
variable_operations
.entry(var.clone())
.or_default()
.insert(op_type.clone());
if !variable_locations.contains_key(var) {
let line = node.start_position().row + 1;
let column = node.start_position().column + 1;
variable_locations.insert(var.clone(), (line, column));
}
}
if self.is_shift_operator(&op) {
for var in vars.iter() {
if signed_int_params.contains(var)
&& !shift_operations.contains_key(var)
{
let line = node.start_position().row + 1;
let column = node.start_position().column + 1;
shift_operations.insert(var.clone(), (line, column));
}
}
}
}
}
}
if node.kind() == "assignment_expression" {
if let Some(op_node) = node.child(1) {
let op_text = get_node_text(&op_node, source);
let op_type = if op_text == "+="
|| op_text == "-="
|| op_text == "*="
|| op_text == "/="
|| op_text == "%="
{
Some(OperationType::Arithmetic)
} else if op_text == "<<="
|| op_text == ">>="
|| op_text == "&="
|| op_text == "|="
|| op_text == "^="
{
Some(OperationType::Bitwise)
} else {
None
};
if let Some(op_type) = op_type {
if let Some(left) = node.child_by_field_name("left") {
if left.kind() == "identifier" {
let var = get_node_text(&left, source).to_string();
variable_operations
.entry(var.clone())
.or_default()
.insert(op_type);
if !variable_locations.contains_key(&var) {
let line = node.start_position().row + 1;
let column = node.start_position().column + 1;
variable_locations.insert(var.clone(), (line, column));
}
if self.is_shift_operator(op_text)
&& signed_int_params.contains(&var)
&& !shift_operations.contains_key(&var)
{
let line = node.start_position().row + 1;
let column = node.start_position().column + 1;
shift_operations.insert(var, (line, column));
}
}
}
}
}
}
if node.kind() == "unary_expression" {
if let Some(op_node) = node.child(0) {
if op_node.kind() == "~" {
let mut vars = HashSet::new();
if let Some(operand) = node.child(1) {
Self::extract_variables(&operand, source, &mut vars);
for var in vars {
variable_operations
.entry(var.clone())
.or_default()
.insert(OperationType::Bitwise);
variable_locations.entry(var).or_insert_with(|| {
let line = node.start_position().row + 1;
let column = node.start_position().column + 1;
(line, column)
});
}
}
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.analyze_operations(
&child,
source,
variable_operations,
variable_locations,
signed_int_params,
shift_operations,
);
}
}
}
}
impl CertRule for Int14C {
fn rule_id(&self) -> &'static str {
"INT14-C"
}
fn description(&self) -> &'static str {
"Avoid performing bitwise and arithmetic operations on the same data"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"INT14-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
if node.kind() == "function_definition" {
self.check_function(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
}
}