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 Dcl20C;
impl Dcl20C {
#[allow(dead_code)]
pub fn new() -> Self {
Dcl20C
}
fn check_node<'a>(
&self,
node: &Node<'a>,
source: &'a str,
violations: &mut Vec<RuleViolation>,
) {
if node.kind() == "declaration" {
self.check_declaration_for_function(&node, source, violations);
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_node(&child, source, violations);
}
}
}
fn check_function_declarator<'a>(
&self,
declarator: &Node<'a>,
source: &'a str,
violations: &mut Vec<RuleViolation>,
) {
if declarator.kind() == "function_declarator" {
if let Some(params) = declarator.child_by_field_name("parameters") {
if self.has_empty_parameters(¶ms, source) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
line: params.start_position().row + 1,
column: params.start_position().column + 1,
message: "Function has empty parameter list () - should explicitly specify (void) to indicate no arguments".to_string(),
severity: self.severity(),
file_path: String::new(),
suggestion: Some("Change () to (void) to explicitly indicate function takes no arguments".to_string()),
requires_manual_review: None,
});
}
}
} else {
for i in 0..declarator.child_count() {
if let Some(child) = declarator.child(i) {
self.check_function_declarator(&child, source, violations);
}
}
}
}
fn check_declaration_for_function<'a>(
&self,
decl: &Node<'a>,
source: &'a str,
violations: &mut Vec<RuleViolation>,
) {
for i in 0..decl.child_count() {
if let Some(child) = decl.child(i) {
if child.kind() == "function_declarator" || child.kind() == "init_declarator" {
self.check_function_declarator(&child, source, violations);
}
}
}
}
fn has_empty_parameters<'a>(&self, params: &Node<'a>, source: &'a str) -> bool {
let params_text = get_node_text(params, source).trim();
if params_text == "()" {
return true;
}
let mut has_params = false;
for i in 0..params.child_count() {
if let Some(child) = params.child(i) {
if child.kind() == "parameter_declaration" {
has_params = true;
let param_text = get_node_text(&child, source).trim();
if param_text == "void" {
return false; }
} else if child.kind() == "type_identifier" {
let type_text = get_node_text(&child, source).trim();
if type_text == "void" {
return false; }
}
}
}
if !has_params {
return !params_text.contains("void");
}
false
}
}
impl CertRule for Dcl20C {
fn rule_id(&self) -> &'static str {
"DCL20-C"
}
fn description(&self) -> &'static str {
"Explicitly specify void when a function accepts no arguments"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"DCL20-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.check_node(node, source, &mut violations);
violations
}
}