1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils;
use std::collections::HashMap;
use tree_sitter::Node;
pub struct Dcl01C;
impl CertRule for Dcl01C {
fn rule_id(&self) -> &'static str {
"DCL01-C"
}
fn description(&self) -> &'static str {
"Do not reuse variable names in subscopes"
}
fn severity(&self) -> Severity {
Severity::Low
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"DCL01-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
// Collect all variable declarations at this level and check for shadowing
check_scope_for_shadowing(
node,
source,
&HashMap::new(),
&mut violations,
self.rule_id(),
);
violations
}
}
/// Recursively check scopes for variable name shadowing
///
/// # Arguments
/// * `node` - Current AST node being checked
/// * `source` - Complete source code
/// * `outer_vars` - Map of variable names from outer scopes (name -> declaration location)
/// * `violations` - Vector to accumulate violations
/// * `rule_id` - Rule ID for violation reporting
fn check_scope_for_shadowing(
node: &Node,
source: &str,
outer_vars: &HashMap<String, (usize, usize)>,
violations: &mut Vec<RuleViolation>,
rule_id: &str,
) {
// Build a new scope with variables declared at this level
let mut current_scope = outer_vars.clone();
// Scan for declarations at this level
match node.kind() {
"translation_unit" => {
// File scope - collect all global declarations
let mut global_vars = HashMap::new();
collect_declarations_in_node(node, source, &mut global_vars);
// Check children with global scope
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "function_definition" {
check_scope_for_shadowing(
&child,
source,
&global_vars,
violations,
rule_id,
);
}
}
}
}
"function_definition" => {
// Function scope - collect parameters and check body
let params = extract_function_parameters(node, source);
for (param_name, line, col) in params {
if let Some((outer_line, outer_col)) = outer_vars.get(¶m_name) {
violations.push(RuleViolation {
rule_id: rule_id.to_string(),
severity: Severity::Low,
message: format!(
"Function parameter '{}' shadows variable from outer scope (line {}:{})",
param_name, outer_line, outer_col
),
file_path: String::new(),
line,
column: col,
suggestion: Some(format!(
"Rename parameter '{}' to avoid shadowing outer scope variable",
param_name
)),
..Default::default()
});
}
current_scope.insert(param_name, (line, col));
}
// Check function body
if let Some(body) = find_compound_statement(node) {
check_scope_for_shadowing(&body, source, ¤t_scope, violations, rule_id);
}
}
"compound_statement" => {
// Block scope - collect declarations in this block
let mut block_vars = HashMap::new();
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
// Check for variable declarations
if child.kind() == "declaration" {
let decls = extract_declarations(&child, source);
for (var_name, line, col) in decls {
// Check if this shadows an outer variable
if let Some((outer_line, outer_col)) = outer_vars.get(&var_name) {
violations.push(RuleViolation {
rule_id: rule_id.to_string(),
severity: Severity::Low,
message: format!(
"Variable '{}' shadows variable from outer scope (line {}:{})",
var_name, outer_line, outer_col
),
file_path: String::new(),
line,
column: col,
suggestion: Some(format!(
"Rename variable '{}' to avoid shadowing",
var_name
)),
..Default::default()
});
}
block_vars.insert(var_name, (line, col));
}
}
}
}
// Merge block variables into current scope
current_scope.extend(block_vars);
// Recursively check nested scopes
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
match child.kind() {
"compound_statement" | "for_statement" | "while_statement"
| "do_statement" | "if_statement" | "switch_statement" => {
check_scope_for_shadowing(
&child,
source,
¤t_scope,
violations,
rule_id,
);
}
_ => {}
}
}
}
}
"for_statement" => {
// For loop - check initializer for declarations
let mut loop_scope = current_scope.clone();
// Check for loop variable declarations in initializer
if let Some(init) = node.child_by_field_name("initializer") {
if init.kind() == "declaration" {
let decls = extract_declarations(&init, source);
for (var_name, line, col) in decls {
if let Some((outer_line, outer_col)) = outer_vars.get(&var_name) {
violations.push(RuleViolation {
rule_id: rule_id.to_string(),
severity: Severity::Low,
message: format!(
"Loop variable '{}' shadows variable from outer scope (line {}:{})",
var_name, outer_line, outer_col
),
file_path: String::new(),
line,
column: col,
suggestion: Some(format!(
"Rename loop variable '{}' to avoid shadowing",
var_name
)),
..Default::default()
});
}
loop_scope.insert(var_name, (line, col));
}
}
}
// Check loop body
if let Some(body) = node.child_by_field_name("body") {
check_scope_for_shadowing(&body, source, &loop_scope, violations, rule_id);
}
}
"while_statement" | "do_statement" => {
// While/do-while loop - check body
if let Some(body) = node.child_by_field_name("body") {
check_scope_for_shadowing(&body, source, ¤t_scope, violations, rule_id);
}
}
"if_statement" => {
// If statement - check consequence and alternative
if let Some(consequence) = node.child_by_field_name("consequence") {
check_scope_for_shadowing(
&consequence,
source,
¤t_scope,
violations,
rule_id,
);
}
if let Some(alternative) = node.child_by_field_name("alternative") {
check_scope_for_shadowing(
&alternative,
source,
¤t_scope,
violations,
rule_id,
);
}
}
"switch_statement" => {
// Switch statement - check body
if let Some(body) = node.child_by_field_name("body") {
check_scope_for_shadowing(&body, source, ¤t_scope, violations, rule_id);
}
}
_ => {
// For other nodes, recursively check children
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
check_scope_for_shadowing(&child, source, ¤t_scope, violations, rule_id);
}
}
}
}
}
/// Collect all variable declarations in a node (non-recursive)
fn collect_declarations_in_node(
node: &Node,
source: &str,
vars: &mut HashMap<String, (usize, usize)>,
) {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "declaration" {
let decls = extract_declarations(&child, source);
for (var_name, line, col) in decls {
vars.insert(var_name, (line, col));
}
}
}
}
}
/// Extract variable names from a declaration node
///
/// Returns: Vec<(variable_name, line_number, column_number)>
fn extract_declarations(decl_node: &Node, source: &str) -> Vec<(String, usize, usize)> {
let mut declarations = Vec::new();
// Look for declarators in the declaration
for i in 0..decl_node.child_count() {
if let Some(child) = decl_node.child(i) {
match child.kind() {
"init_declarator" => {
if let Some(declarator) = child.child_by_field_name("declarator") {
let var_name =
ast_utils::get_identifier_from_declarator(&declarator, source);
if !var_name.is_empty() {
let pos = declarator.start_position();
declarations.push((var_name, pos.row + 1, pos.column + 1));
}
}
}
"pointer_declarator" | "array_declarator" | "identifier" => {
let var_name = ast_utils::get_identifier_from_declarator(&child, source);
if !var_name.is_empty() {
let pos = child.start_position();
declarations.push((var_name, pos.row + 1, pos.column + 1));
}
}
_ => {}
}
}
}
declarations
}
/// Extract function parameters with their positions
///
/// Returns: Vec<(parameter_name, line_number, column_number)>
fn extract_function_parameters(func_node: &Node, source: &str) -> Vec<(String, usize, usize)> {
let mut parameters = Vec::new();
// Find the function_declarator
for i in 0..func_node.child_count() {
if let Some(child) = func_node.child(i) {
if child.kind() == "function_declarator" {
// Find parameter_list
for j in 0..child.child_count() {
if let Some(param_list) = child.child(j) {
if param_list.kind() == "parameter_list" {
// Extract each parameter
for k in 0..param_list.child_count() {
if let Some(param) = param_list.child(k) {
if param.kind() == "parameter_declaration" {
// Find the declarator in the parameter
for m in 0..param.child_count() {
if let Some(declarator) = param.child(m) {
if matches!(
declarator.kind(),
"identifier"
| "pointer_declarator"
| "array_declarator"
| "function_declarator"
) {
let param_name =
ast_utils::get_identifier_from_declarator(
&declarator,
source,
);
if !param_name.is_empty() {
let pos = declarator.start_position();
parameters.push((
param_name,
pos.row + 1,
pos.column + 1,
));
}
}
}
}
}
}
}
}
}
}
}
}
}
parameters
}
/// Find the compound_statement (body) of a function
fn find_compound_statement<'a>(func_node: &Node<'a>) -> Option<Node<'a>> {
for i in 0..func_node.child_count() {
if let Some(child) = func_node.child(i) {
if child.kind() == "compound_statement" {
return Some(child);
}
}
}
None
}