sqc 0.4.13

Software Code Quality - CERT C compliance checker
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! INT14-C: Avoid performing bitwise and arithmetic operations on the same data
//!
//! This rule addresses performing bitwise and arithmetic operations on the same data.
//! Bitwise operations are frequently used on arithmetic values as premature optimization,
//! which reduces code readability and obscures programmer intent.
//!
//! ## Bitwise operators:
//! - Unary: `~` (bitwise NOT)
//! - Binary: `<<` `>>` (shift), `&` `|` `^` (bitwise AND/OR/XOR)
//!
//! ## Non-compliant examples:
//!
//! **Left shift misuse:**
//! ```c
//! int compute(int x) {
//!     int y = x << 2;  // Bitwise shift
//!     x += y + 1;      // Arithmetic operation
//!     return x;        // Computes 5x + 1 via bit manipulation
//! }
//! ```
//!
//! **Right shift division:**
//! ```c
//! int compute(int x) {
//!     x >>= 2;  // Bitwise shift (implementation-dependent for negatives)
//!     return x; // Attempts division by 4
//! }
//! ```
//!
//! ## Compliant solutions:
//! ```c
//! int compute(int x) {
//!     return 5 * x + 1;  // Clear mathematical intent
//! }
//!
//! int compute(int x) {
//!     return x / 4;  // Explicit division
//! }
//! ```

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
    }

    /// Check if an operator is a bitwise operator
    fn is_bitwise_operator(&self, op: &str) -> bool {
        matches!(op, "~" | "<<" | ">>" | "&" | "|" | "^")
    }

    /// Check if an operator is an arithmetic operator
    fn is_arithmetic_operator(&self, op: &str) -> bool {
        matches!(op, "+" | "-" | "*" | "/" | "%")
    }

    /// Check if an operator is a shift operator (subset of bitwise often misused for arithmetic)
    fn is_shift_operator(&self, op: &str) -> bool {
        matches!(op, "<<" | ">>" | "<<=" | ">>=")
    }

    /// Collect signed integer parameters from a function
    fn collect_signed_int_params(&self, node: &Node, source: &str) -> HashSet<String> {
        let mut params = HashSet::new();

        // Look for function_declarator within function_definition
        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>,
    ) {
        // Look for parameter_list
        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);
                    // Check for signed integer types (int, short, long, signed)
                    // Exclude unsigned types
                    if (param_text.contains("int")
                        || param_text.contains("short")
                        || param_text.contains("long"))
                        && !param_text.contains("unsigned")
                    {
                        // Extract parameter name
                        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
    }

    /// Extract variable names used in an expression
    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);
        }

        // Recursively check children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                Self::extract_variables(&child, source, vars);
            }
        }
    }

    /// Get the operator from a binary expression
    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());
                }
                // Handle named operators
                let text = get_node_text(&child, source);
                if self.is_bitwise_operator(text) || self.is_arithmetic_operator(text) {
                    return Some(text.to_string());
                }
            }
        }
        None
    }

    /// Check a function definition for mixed bitwise/arithmetic operations
    fn check_function(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
        // Track which variables have been used with which operation types
        let mut variable_operations: HashMap<String, HashSet<OperationType>> = HashMap::new();

        // Track line numbers for first occurrence
        let mut variable_locations: HashMap<String, (usize, usize)> = HashMap::new();

        // Collect signed integer parameters
        let signed_int_params = self.collect_signed_int_params(node, source);

        // Track shift operations on signed integer parameters
        let mut shift_operations: HashMap<String, (usize, usize)> = HashMap::new();

        // Recursively analyze all operations in the function
        self.analyze_operations(
            node,
            source,
            &mut variable_operations,
            &mut variable_locations,
            &signed_int_params,
            &mut shift_operations,
        );

        // Check for variables that have both bitwise and arithmetic operations.
        // Skip exactly-2-char variable names like `bi` — these are loop counter/index
        // variables where mixed bitwise+arithmetic is standard embedded pattern
        // (e.g., bit position calculated as `pos + bi`, then used in `1u << bi`).
        // Single-char names like `x` are NOT skipped — they could be function parameters.
        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()
                });
            }
        }

        // Flag shift operations on signed integer parameters (often used for arithmetic optimization)
        for (var_name, (line, column)) in shift_operations.iter() {
            // Skip if already flagged for mixed operations
            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()
            });
        }
    }

    /// Recursively analyze operations on variables
    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)>,
    ) {
        // Check binary expressions
        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 {
                    // Extract variables from this expression
                    let mut vars = HashSet::new();
                    Self::extract_variables(node, source, &mut vars);

                    // Record operation type for each variable
                    for var in vars.iter() {
                        variable_operations
                            .entry(var.clone())
                            .or_default()
                            .insert(op_type.clone());

                        // Record first location if not already recorded
                        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));
                        }
                    }

                    // Track shift operations on signed integer parameters
                    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));
                            }
                        }
                    }
                }
            }
        }

        // Check compound assignment expressions (e.g., x += 1, x <<= 2)
        if node.kind() == "assignment_expression" {
            if let Some(op_node) = node.child(1) {
                let op_text = get_node_text(&op_node, source);

                // Check for compound assignment operators
                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 {
                    // Extract the left-hand variable
                    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);

                            // Record first location if not already recorded
                            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));
                            }

                            // Track shift compound assignments on signed int params
                            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));
                            }
                        }
                    }
                }
            }
        }

        // Check unary expressions (e.g., ~x)
        if node.kind() == "unary_expression" {
            if let Some(op_node) = node.child(0) {
                if op_node.kind() == "~" {
                    // Extract variables from the operand
                    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);

                            // Record first location if not already recorded
                            variable_locations.entry(var).or_insert_with(|| {
                                let line = node.start_position().row + 1;
                                let column = node.start_position().column + 1;
                                (line, column)
                            });
                        }
                    }
                }
            }
        }

        // Recursively check child nodes
        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();

        // Check function definitions
        if node.kind() == "function_definition" {
            self.check_function(node, source, &mut violations);
        }

        // Recursively check child nodes
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                violations.extend(self.check(&child, source));
            }
        }

        violations
    }
}