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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! FLP03-C: Detect and handle floating-point errors
//!
//! This rule addresses the detection and handling of errors occurring during
//! floating-point operations. Programmers often validate operands before operations
//! but neglect errors that occur during computation itself, which can result in
//! silent failures and unexpected arithmetic results.
//!
//! ## Floating-Point Errors to Detect:
//! - **Divide-by-zero**: Returns infinity rather than aborting
//! - **Inexact operations**: Loss of precision
//! - **Underflow**: Results too small to represent
//! - **Overflow**: Results too large for the data type
//! - **Invalid operations**: Conversions causing undefined values
//!
//! ## Examples:
//!
//! **Non-compliant:**
//! ```c
//! void fpOper_noErrorChecking(void) {
//!     double a = 1e-40, b, c = 0.1;
//!     float x = 0, y;
//!     y = a;           // Inexact and underflows - no error check
//!     b = y / x;       // Divide-by-zero - no error check
//!     c = sin(30) * a; // Inexact - no error check
//! }
//! ```
//!
//! **Compliant (using fenv.h):**
//! ```c
//! #include <fenv.h>
//! #pragma STDC FENV_ACCESS ON
//!
//! void fpOper_fenv(void) {
//!     double a = 1e-40, b, c = 0.1;
//!     float x = 0, y;
//!     int fpeRaised;
//!
//!     feclearexcept(FE_ALL_EXCEPT);
//!     y = a;
//!     fpeRaised = fetestexcept(FE_ALL_EXCEPT);
//!
//!     feclearexcept(FE_ALL_EXCEPT);
//!     b = y / x;
//!     fpeRaised = fetestexcept(FE_ALL_EXCEPT);
//! }
//! ```

use super::super::{CertRule, RuleViolation};
use crate::analyze::const_eval;
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use std::collections::HashSet;
use tree_sitter::Node;

pub struct Flp03C;

/// Analyzer that tracks floating-point variables
struct FpAnalyzer {
    float_vars: HashSet<String>,
}

impl FpAnalyzer {
    fn new() -> Self {
        Self {
            float_vars: HashSet::new(),
        }
    }

    /// Collect all floating-point variable declarations from the AST
    fn collect_float_vars(&mut self, node: &Node, source: &str) {
        if node.kind() == "declaration" {
            let decl_text = get_node_text(node, source);
            // Check if this is a float/double declaration
            if decl_text.starts_with("float")
                || decl_text.starts_with("double")
                || decl_text.contains(" float ")
                || decl_text.contains(" double ")
            {
                // Extract all identifiers from this declaration
                self.extract_identifiers_from_declaration(node, source);
            }
        }

        // Recursively process children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.collect_float_vars(&child, source);
            }
        }
    }

    fn extract_identifiers_from_declaration(&mut self, node: &Node, source: &str) {
        // Look for init_declarator or declarator nodes containing identifiers
        if node.kind() == "identifier" {
            // Verify parent is a declarator-type node (not type specifier)
            if let Some(parent) = node.parent() {
                let parent_kind = parent.kind();
                if parent_kind == "init_declarator"
                    || parent_kind == "declarator"
                    || parent_kind == "pointer_declarator"
                    || parent_kind == "array_declarator"
                {
                    let var_name = get_node_text(node, source).to_string();
                    self.float_vars.insert(var_name);
                }
            }
        }

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

    /// Check if an expression involves floating-point values or variables
    fn is_fp_expression(&self, node: &Node, source: &str) -> bool {
        let text = get_node_text(node, source);

        // Check for floating-point literals (contains decimal point or e notation)
        if text.contains('.') && !text.starts_with("/*") {
            return true;
        }

        // Precise scientific notation: digit before e/E, digit or sign after
        // Avoids matching 'e' in identifiers like "sizeof"
        let bytes = text.as_bytes();
        for i in 1..bytes.len().saturating_sub(1) {
            if bytes[i] == b'e' || bytes[i] == b'E' {
                let before = bytes[i - 1];
                let after = bytes[i + 1];
                if before.is_ascii_digit()
                    && (after.is_ascii_digit() || after == b'+' || after == b'-')
                {
                    return true;
                }
            }
        }

        // Check for floating-point type keywords
        if text.contains("float") || text.contains("double") {
            return true;
        }

        // Check if any identifier in this expression is a known float variable
        self.contains_float_identifier(node, source)
    }

    fn contains_float_identifier(&self, node: &Node, source: &str) -> bool {
        if node.kind() == "identifier" {
            let name = get_node_text(node, source);
            if self.float_vars.contains(name) {
                return true;
            }
        }

        // Recursively check children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if self.contains_float_identifier(&child, source) {
                    return true;
                }
            }
        }

        false
    }
}

impl Flp03C {
    #[allow(dead_code)]
    pub fn new() -> Self {
        Self
    }

    /// List of floating-point error checking functions from fenv.h
    const FENV_FUNCTIONS: &'static [&'static str] = &[
        "feclearexcept",
        "fetestexcept",
        "fegetexceptflag",
        "fesetexceptflag",
        "feraiseexcept",
    ];

    /// List of Windows-specific floating-point error checking functions
    const WINDOWS_FP_FUNCTIONS: &'static [&'static str] =
        &["_clearfp", "_statusfp", "_controlfp", "_fpieee_flt"];

    /// Check if a function name is a floating-point error checking function
    fn is_fp_error_check_function(&self, name: &str) -> bool {
        Self::FENV_FUNCTIONS.contains(&name) || Self::WINDOWS_FP_FUNCTIONS.contains(&name)
    }

    /// Check if a node contains floating-point error checking calls
    fn contains_fp_error_checking(&self, node: &Node, source: &str) -> bool {
        // Check this node
        if node.kind() == "call_expression" {
            if let Some(function) = node.child_by_field_name("function") {
                let func_name = get_node_text(&function, source);
                if self.is_fp_error_check_function(func_name) {
                    return true;
                }
            }
        }

        // Check for Windows SEH exception handling (_try/_except or __try/__except)
        // These are typically parsed as identifier nodes with the text "_try", "__try", etc.
        let node_text = get_node_text(node, source);
        if node_text.contains("_try")
            || node_text.contains("__try")
            || node_text.contains("_except")
            || node_text.contains("__except")
        {
            return true;
        }

        // Also check for _fpieee_flt which is Windows FP exception handling
        if node_text.contains("_fpieee_flt") || node_text.contains("unmask_fpsr") {
            return true;
        }

        // Recursively check children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if self.contains_fp_error_checking(&child, source) {
                    return true;
                }
            }
        }

        false
    }

    /// Check for floating-point division operations
    fn check_fp_division(
        &self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
        analyzer: &FpAnalyzer,
    ) {
        if node.kind() == "binary_expression" {
            // Check if this is a division operation
            let mut is_division = false;
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "/" {
                        is_division = true;
                        break;
                    }
                }
            }

            // Check each operand individually — at least one must be float
            let left_fp = node
                .child_by_field_name("left")
                .is_some_and(|l| analyzer.is_fp_expression(&l, source));
            let right_fp = node
                .child_by_field_name("right")
                .is_some_and(|r| analyzer.is_fp_expression(&r, source));
            if is_division && (left_fp || right_fp) {
                // Check if the division is inside a divide-by-zero guard
                if self.is_inside_division_guard(node, source) {
                    return;
                }

                // Check if the divisor is provably non-zero (all assignments
                // to it are non-zero constants). Catches goodG2B pattern:
                // `data = 2.0F; 100.0 / data;`
                if let Some(right) = node.child_by_field_name("right") {
                    if right.kind() == "identifier" {
                        let var_name = get_node_text(&right, source);
                        if Self::divisor_provably_nonzero_fp(node, var_name, source) {
                            return;
                        }
                    }
                }

                // Check if there's error checking in the containing function
                if let Some(containing_func) = self.find_containing_function(node) {
                    if !self.contains_fp_error_checking(&containing_func, source) {
                        violations.push(RuleViolation {
                            rule_id: self.rule_id().to_string(),
                            severity: self.severity(),
                            message: "Floating-point division without error checking (consider using feclearexcept/fetestexcept)".to_string(),
                            file_path: String::new(),
                            line: node.start_position().row + 1,
                            column: node.start_position().column + 1,
                            suggestion: Some(
                                "Use feclearexcept(FE_ALL_EXCEPT) before and fetestexcept(FE_ALL_EXCEPT) after floating-point operations".to_string()
                            ),
                            ..Default::default()
                        });
                    }
                }
            }
        }
    }

    /// Find the containing function definition for a given node
    fn find_containing_function<'a>(&self, node: &Node<'a>) -> Option<Node<'a>> {
        let mut current = Some(*node);
        while let Some(n) = current {
            if n.kind() == "function_definition" {
                return Some(n);
            }
            current = n.parent();
        }
        None
    }

    /// Check if a division node is inside a guard that protects against divide-by-zero.
    /// Recognizes patterns like:
    /// - `if (fabs(data) > 0.000001)` (magnitude check)
    /// - `if (data != 0)` or `if (data != 0.0)` (zero check)
    /// - `if (x > 0)` / `if (x < 0)` (sign check implies non-zero)
    fn is_inside_division_guard(&self, node: &Node, source: &str) -> bool {
        let mut current = node.parent();
        // Walk up to 15 ancestors looking for an enclosing if_statement
        let mut depth = 0;
        while let Some(n) = current {
            if depth > 15 {
                break;
            }
            if n.kind() == "if_statement" {
                if let Some(condition) = n.child_by_field_name("condition") {
                    let cond_text = get_node_text(&condition, source);
                    if Self::is_division_guard_condition(&cond_text) {
                        return true;
                    }
                }
            }
            current = n.parent();
            depth += 1;
        }
        false
    }

    /// Check if a condition text represents a divide-by-zero guard.
    fn is_division_guard_condition(cond_text: &str) -> bool {
        // fabs/fabsf/fabsl magnitude checks: fabs(x) > threshold
        if cond_text.contains("fabs") || cond_text.contains("fabsf") || cond_text.contains("fabsl")
        {
            if cond_text.contains('>') {
                return true;
            }
        }

        // != 0 or != 0.0 checks
        if (cond_text.contains("!= 0") || cond_text.contains("!=0")) && !cond_text.contains("== 0")
        {
            return true;
        }

        // Comparisons against zero that imply non-zero: > 0, < 0
        // But not >= 0 or <= 0 (those don't exclude zero)
        if (cond_text.contains("> 0") || cond_text.contains(">0"))
            && !cond_text.contains(">= 0")
            && !cond_text.contains(">=0")
        {
            return true;
        }
        if (cond_text.contains("< 0") || cond_text.contains("<0"))
            && !cond_text.contains("<= 0")
            && !cond_text.contains("<=0")
        {
            return true;
        }

        false
    }

    /// Check if the divisor variable is provably non-zero at the division point.
    /// Two strategies:
    /// 1. ALL assignments in the function are non-zero constants (catches `data=-1; data=7;`)
    /// 2. Constant-aware walk: track last assignment through feasible branches,
    ///    using file-scope constants to prune dead code (catches branched patterns
    ///    like `data=0.0F; if(STATIC_CONST_TRUE) { data=2.0F; } use(data);`)
    fn divisor_provably_nonzero_fp(div_node: &Node, var_name: &str, source: &str) -> bool {
        // Find containing function and translation unit root
        let mut current = Some(*div_node);
        let func = loop {
            match current {
                Some(n) if n.kind() == "function_definition" => break n,
                Some(n) => current = n.parent(),
                None => return false,
            }
        };
        let body = match func.child_by_field_name("body") {
            Some(b) => b,
            None => return false,
        };

        // Strategy 1: all assignments are non-zero
        let mut all_nonzero = true;
        let mut found_any = false;
        Self::check_all_assignments(&body, var_name, source, &mut all_nonzero, &mut found_any);
        if found_any && all_nonzero {
            return true;
        }

        // Strategy 2: constant-aware walk
        // Collect file-scope constants for condition resolution
        let root = {
            let mut n = func;
            while let Some(p) = n.parent() {
                n = p;
            }
            n
        };
        let constants = const_eval::collect_macro_constants(&root, source);
        let div_line = div_node.start_position().row;
        let last_val =
            Self::walk_scope_for_last_assignment(&body, var_name, source, div_line, &constants);
        if last_val == Some(true) {
            return true;
        }

        false
    }

    /// Walk a scope tracking the last assignment to `var_name` before `div_line`.
    /// For if-statements with constant conditions, only follows the feasible branch.
    /// Returns Some(true) if last reaching assignment is non-zero, Some(false) if zero,
    /// None if no assignment found.
    fn walk_scope_for_last_assignment(
        scope: &Node,
        var_name: &str,
        source: &str,
        div_line: usize,
        constants: &const_eval::MacroConstantMap,
    ) -> Option<bool> {
        let mut last_val: Option<bool> = None;
        for i in 0..scope.named_child_count() {
            let child = match scope.named_child(i) {
                Some(c) => c,
                None => continue,
            };
            if child.start_position().row >= div_line {
                break;
            }
            // Direct assignment
            if let Some(is_nz) = Self::get_assignment_value(&child, var_name, source) {
                last_val = Some(is_nz);
                continue;
            }
            // If-statement: resolve condition if possible
            if child.kind() == "if_statement" {
                if let Some(cond) = child.child_by_field_name("condition") {
                    let const_val = Self::eval_condition_const(&cond, source, constants);
                    match const_val {
                        Some(true) => {
                            // Only then-branch is feasible
                            if let Some(then_br) = child.child_by_field_name("consequence") {
                                if let Some(v) = Self::walk_scope_for_last_assignment(
                                    &then_br, var_name, source, div_line, constants,
                                ) {
                                    last_val = Some(v);
                                }
                            }
                        }
                        Some(false) => {
                            // Only else-branch is feasible
                            if let Some(else_br) = child.child_by_field_name("alternative") {
                                if let Some(v) = Self::walk_scope_for_last_assignment(
                                    &else_br, var_name, source, div_line, constants,
                                ) {
                                    last_val = Some(v);
                                }
                            }
                        }
                        None => {
                            // Unknown condition: conservatively don't update last_val
                            // (both branches are possible, can't guarantee which)
                        }
                    }
                }
                continue;
            }
            // Recurse into compound statements
            if child.kind() == "compound_statement" {
                if let Some(v) = Self::walk_scope_for_last_assignment(
                    &child, var_name, source, div_line, constants,
                ) {
                    last_val = Some(v);
                }
            }
        }
        last_val
    }

    /// Evaluate an if-condition as a constant boolean, using file-scope constants.
    fn eval_condition_const(
        cond: &Node,
        source: &str,
        constants: &const_eval::MacroConstantMap,
    ) -> Option<bool> {
        // Unwrap parenthesized_expression
        let inner = if cond.kind() == "parenthesized_expression" {
            cond.named_child(0).unwrap_or(*cond)
        } else {
            *cond
        };
        match inner.kind() {
            "number_literal" => {
                let text = get_node_text(&inner, source);
                text.parse::<i64>().ok().map(|n| n != 0)
            }
            "identifier" => {
                let name = get_node_text(&inner, source);
                constants.get(name).map(|&v| v != 0)
            }
            "true" => Some(true),
            "false" => Some(false),
            _ => None,
        }
    }

    /// Walk all assignments to var_name, tracking if all are non-zero.
    fn check_all_assignments(
        scope: &Node,
        var_name: &str,
        source: &str,
        all_nonzero: &mut bool,
        found_any: &mut bool,
    ) {
        for i in 0..scope.named_child_count() {
            let child = match scope.named_child(i) {
                Some(c) => c,
                None => continue,
            };
            if let Some(is_nz) = Self::get_assignment_value(&child, var_name, source) {
                *found_any = true;
                if !is_nz {
                    *all_nonzero = false;
                }
            } else {
                Self::check_all_assignments(&child, var_name, source, all_nonzero, found_any);
            }
        }
    }

    /// If `node` is a declaration or assignment to `var_name`, return Some(is_nonzero).
    fn get_assignment_value(node: &Node, var_name: &str, source: &str) -> Option<bool> {
        match node.kind() {
            "declaration" => {
                for j in 0..node.named_child_count() {
                    if let Some(gc) = node.named_child(j) {
                        if gc.kind() == "init_declarator" {
                            // Check if it's our variable
                            let has_var = (0..gc.named_child_count()).any(|k| {
                                gc.named_child(k).is_some_and(|n| {
                                    n.kind() == "identifier"
                                        && get_node_text(&n, source) == var_name
                                })
                            });
                            if has_var {
                                if let Some(val) = gc.named_child(gc.named_child_count() - 1) {
                                    if val.kind() != "identifier"
                                        || get_node_text(&val, source) != var_name
                                    {
                                        return Some(Self::is_nonzero_literal(&val, source));
                                    }
                                }
                            }
                        }
                    }
                }
                None
            }
            "expression_statement" => {
                let expr = node.named_child(0)?;
                if expr.kind() != "assignment_expression" {
                    return None;
                }
                let lhs = expr.child_by_field_name("left")?;
                if lhs.kind() == "identifier" && get_node_text(&lhs, source) == var_name {
                    let rhs = expr.child_by_field_name("right")?;
                    return Some(Self::is_nonzero_literal(&rhs, source));
                }
                None
            }
            _ => None,
        }
    }

    /// Check if a node is a non-zero numeric literal (int or float).
    fn is_nonzero_literal(node: &Node, source: &str) -> bool {
        match node.kind() {
            "number_literal" => {
                let text = get_node_text(node, source)
                    .trim_end_matches('f')
                    .trim_end_matches('F')
                    .trim_end_matches('l')
                    .trim_end_matches('L')
                    .to_string();
                if let Ok(v) = text.parse::<f64>() {
                    return v != 0.0;
                }
                if let Ok(v) = text.parse::<i64>() {
                    return v != 0;
                }
                false
            }
            "unary_expression" => {
                // Handle -(literal)
                if let Some(arg) = node.child_by_field_name("argument") {
                    Self::is_nonzero_literal(&arg, source)
                } else {
                    false
                }
            }
            "parenthesized_expression" => {
                if let Some(inner) = node.named_child(0) {
                    Self::is_nonzero_literal(&inner, source)
                } else {
                    false
                }
            }
            _ => false,
        }
    }
}

impl CertRule for Flp03C {
    fn rule_id(&self) -> &'static str {
        "FLP03-C"
    }

    fn description(&self) -> &'static str {
        "Detect and handle floating-point errors"
    }

    fn severity(&self) -> Severity {
        Severity::Low
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Recommendation
    }

    fn cert_id(&self) -> &'static str {
        "FLP03-C"
    }

    fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
        let mut violations = Vec::new();

        // First pass: collect all floating-point variable declarations
        let mut analyzer = FpAnalyzer::new();
        analyzer.collect_float_vars(node, source);

        // Second pass: check for violations
        self.check_node(node, source, &mut violations, &analyzer);
        violations
    }
}

impl Flp03C {
    fn check_node(
        &self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
        analyzer: &FpAnalyzer,
    ) {
        // Check for floating-point division without error checking
        if node.kind() == "binary_expression" {
            self.check_fp_division(node, source, violations, analyzer);
        }

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