use crate::{
ast_context::AstContext,
config::Config,
rules::{Fix, Rule, Violation},
};
pub struct GErrorInit;
impl Rule for GErrorInit {
fn name(&self) -> &'static str {
"g_error_init"
}
fn description(&self) -> &'static str {
"Ensure GError* variables are initialized to NULL"
}
fn category(&self) -> crate::rules::Category {
crate::rules::Category::Correctness
}
fn fixable(&self) -> bool {
true
}
fn check_func_impl(
&self,
_ast_context: &AstContext,
_config: &Config,
func: &gobject_ast::top_level::FunctionDefItem,
file: &gobject_ast::FileModel,
violations: &mut Vec<Violation>,
) {
for stmt in &func.body_statements {
for decl in stmt.iter_declarations() {
self.check_declaration(file, decl, violations);
}
}
}
}
impl GErrorInit {
fn check_declaration(
&self,
file: &gobject_ast::FileModel,
decl: &gobject_ast::VariableDecl,
violations: &mut Vec<Violation>,
) {
if !decl.type_info.is_base_type("GError") || !decl.type_info.is_pointer() {
return;
}
let is_initialized_to_null = match &decl.initializer {
None => false,
Some(expr) if expr.is_null() || expr.is_zero() => true,
Some(_) => return,
};
if is_initialized_to_null {
return;
}
let insert_pos = decl.location.end_byte - 1;
let fix = Fix::new(insert_pos, insert_pos, " = NULL".to_string());
violations.push(self.violation_with_fix(
&file.path,
decl.location.line,
decl.location.column,
format!("GError *{} must be initialized to NULL", decl.name),
fix,
));
}
}