use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils;
use std::collections::HashSet;
use tree_sitter::Node;
pub struct Dcl17C;
impl CertRule for Dcl17C {
fn rule_id(&self) -> &'static str {
"DCL17-C"
}
fn description(&self) -> &'static str {
"Beware of miscompiled volatile-qualified variables"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"DCL17-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
if node.kind() != "translation_unit" {
return violations;
}
let volatile_vars = collect_volatile_variables(node, source);
find_direct_volatile_accesses(node, source, &volatile_vars, &mut violations);
find_kr_style_functions(node, source, &mut violations);
violations
}
}
fn collect_volatile_variables<'a>(root: &Node, source: &'a str) -> HashSet<&'a str> {
let mut volatile_vars = HashSet::new();
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
if child.kind() == "declaration" {
if has_volatile_qualifier(&child, source) {
collect_declarator_names(&child, source, &mut volatile_vars);
}
}
}
volatile_vars
}
fn has_volatile_qualifier(decl_node: &Node, source: &str) -> bool {
let mut cursor = decl_node.walk();
for child in decl_node.children(&mut cursor) {
if child.kind() == "type_qualifier" {
let text = ast_utils::get_node_text(&child, source);
if text == "volatile" {
return true;
}
}
if child.kind() == "storage_class_specifier" || child.kind() == "primitive_type" {
if has_volatile_qualifier(&child, source) {
return true;
}
}
}
false
}
fn collect_declarator_names<'a>(decl_node: &Node, source: &'a str, names: &mut HashSet<&'a str>) {
let mut cursor = decl_node.walk();
for child in decl_node.children(&mut cursor) {
match child.kind() {
"init_declarator" => {
if let Some(declarator) = child.child_by_field_name("declarator") {
if let Some(name) = extract_identifier_name(&declarator, source) {
names.insert(name);
}
}
}
"identifier" => {
let name = ast_utils::get_node_text(&child, source);
names.insert(name);
}
"pointer_declarator" => {
if let Some(name) = extract_identifier_name(&child, source) {
names.insert(name);
}
}
_ => {}
}
}
}
fn extract_identifier_name<'a>(declarator: &Node, source: &'a str) -> Option<&'a str> {
match declarator.kind() {
"identifier" => Some(ast_utils::get_node_text(declarator, source)),
"pointer_declarator" | "array_declarator" | "function_declarator" => {
if let Some(child_declarator) = declarator.child_by_field_name("declarator") {
extract_identifier_name(&child_declarator, source)
} else {
let mut cursor = declarator.walk();
for child in declarator.children(&mut cursor) {
if child.kind() == "identifier" {
return Some(ast_utils::get_node_text(&child, source));
}
if let Some(name) = extract_identifier_name(&child, source) {
return Some(name);
}
}
None
}
}
_ => None,
}
}
fn find_direct_volatile_accesses(
node: &Node,
source: &str,
volatile_vars: &HashSet<&str>,
violations: &mut Vec<RuleViolation>,
) {
if node.kind() == "identifier" {
let var_name = ast_utils::get_node_text(node, source);
if volatile_vars.contains(var_name) {
if is_direct_access(node, source) {
if is_simple_volatile_access(node) {
} else {
let start_point = node.start_position();
violations.push(RuleViolation {
rule_id: "DCL17-C".to_string(),
severity: Severity::Medium,
message: format!(
"Direct access to volatile variable '{}' may be miscompiled. Wrap volatile accesses in functions",
var_name
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some(
"Use wrapper functions: int vol_read(volatile int *p) { return *p; }".to_string()
),
..Default::default()
});
}
}
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
find_direct_volatile_accesses(&child, source, volatile_vars, violations);
}
}
fn is_simple_volatile_access(node: &Node) -> bool {
if let Some(parent) = node.parent() {
match parent.kind() {
"assignment_expression" => {
return true;
}
"init_declarator" => return true,
"return_statement" => return true,
"parenthesized_expression" => {
if let Some(grandparent) = parent.parent() {
if matches!(
grandparent.kind(),
"if_statement" | "while_statement" | "for_statement"
) {
return true;
}
}
}
"argument_list" => return true,
_ => {}
}
}
false
}
fn is_direct_access(node: &Node, _source: &str) -> bool {
let mut current = node.parent();
while let Some(parent) = current {
match parent.kind() {
"unary_expression" => {
if let Some(operator) = parent.child_by_field_name("operator") {
if operator.kind() == "&" {
if let Some(grandparent) = parent.parent() {
if grandparent.kind() == "argument_list" {
return false;
}
}
}
}
current = parent.parent();
}
"call_expression" => {
if let Some(function) = parent.child_by_field_name("function") {
if is_ancestor_of(&function, node) {
return true;
}
}
return false;
}
"assignment_expression"
| "update_expression"
| "binary_expression"
| "init_declarator"
| "return_statement"
| "for_statement"
| "while_statement"
| "if_statement"
| "switch_statement" => {
return true;
}
"pointer_expression" => {
if let Some(argument) = parent.child_by_field_name("argument") {
if argument.kind() == "call_expression" {
return false;
}
}
current = parent.parent();
}
_ => {
current = parent.parent();
}
}
}
false
}
fn is_ancestor_of(ancestor: &Node, descendant: &Node) -> bool {
let mut current = Some(*descendant);
while let Some(node) = current {
if node.id() == ancestor.id() {
return true;
}
current = node.parent();
}
false
}
fn find_kr_style_functions(root: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
let mut cursor = root.walk();
for child in root.children(&mut cursor) {
match child.kind() {
"declaration" => {
check_empty_param_list_decl(&child, source, violations);
}
"function_definition" => {
check_kr_style_definition(&child, source, violations);
}
_ => {}
}
}
}
fn check_empty_param_list_decl(decl: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
let mut decl_cursor = decl.walk();
for child in decl.children(&mut decl_cursor) {
if child.kind() == "function_declarator" {
if let Some(params) = child.child_by_field_name("parameters") {
if is_empty_param_list(¶ms) {
let func_name = if let Some(id) = child.child_by_field_name("declarator") {
ast_utils::get_node_text(&id, source)
} else {
find_func_name_in_declarator(&child, source)
};
violations.push(RuleViolation {
rule_id: "DCL17-C".to_string(),
severity: Severity::Medium,
message: format!(
"Function '{}' declared with empty parameter list (K&R style). \
Use '(void)' for functions that accept no arguments.",
func_name
),
file_path: String::new(),
line: child.start_position().row + 1,
column: child.start_position().column + 1,
suggestion: Some(format!(
"Change '{}()' to '{}(void)' to declare a proper prototype",
func_name, func_name,
)),
..Default::default()
});
}
}
}
}
}
fn find_func_name_in_declarator<'a>(func_decl: &Node<'a>, source: &'a str) -> &'a str {
for i in 0..func_decl.child_count() {
if let Some(child) = func_decl.child(i) {
if child.kind() == "identifier" {
return ast_utils::get_node_text(&child, source);
}
}
}
"unknown"
}
fn is_empty_param_list(params: &Node) -> bool {
let mut cursor = params.walk();
for child in params.children(&mut cursor) {
if child.kind() == "parameter_declaration" {
return false;
}
if child.kind() == "identifier" {
return false;
}
}
true
}
fn check_kr_style_definition(func_def: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
let mut has_kr_params = false;
let mut func_name = "unknown";
let mut cursor = func_def.walk();
for child in func_def.children(&mut cursor) {
if child.kind() == "function_declarator" {
func_name = find_func_name_in_declarator(&child, source);
}
if child.kind() == "declaration" {
has_kr_params = true;
}
}
if has_kr_params {
violations.push(RuleViolation {
rule_id: "DCL17-C".to_string(),
severity: Severity::Medium,
message: format!(
"Function '{}' uses K&R-style (old-style) parameter declarations. \
Use modern prototype syntax.",
func_name,
),
file_path: String::new(),
line: func_def.start_position().row + 1,
column: func_def.start_position().column + 1,
suggestion: Some(
"Rewrite using prototype syntax: void func(int x) instead of void func(x) int x;"
.to_string(),
),
..Default::default()
});
}
}