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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Control-flow graph construction from tree-sitter AST.
#![allow(dead_code)]
//!
//! Builds a lightweight CFG from C function bodies. Each basic block contains
//! a sequence of statements with a single entry and single exit. Edges represent
//! control flow between blocks (fallthrough, branches, back edges, returns).

use super::const_eval::MacroConstantMap;
use std::collections::HashMap;
use tree_sitter::Node;

/// Unique identifier for a basic block within a function CFG.
pub type BlockId = usize;

/// A basic block: a straight-line sequence of statements.
#[derive(Debug, Clone)]
pub struct BasicBlock {
    pub id: BlockId,
    /// Byte ranges of statements in this block (start, end).
    pub statements: Vec<(usize, usize)>,
    /// Overall byte range of this block.
    pub byte_range: (usize, usize),
    /// Byte range of the condition expression (for if/while/for/do-while blocks).
    /// Used by null-state analysis to extract edge refinement info.
    pub condition_range: Option<(usize, usize)>,
}

/// Edge types in the control-flow graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CfgEdge {
    /// Sequential fallthrough to the next block.
    Fallthrough,
    /// True branch of an if/while/for condition.
    TrueBranch,
    /// False branch of an if/while/for condition.
    FalseBranch,
    /// Back edge from loop body to loop header.
    BackEdge,
    /// Return from function (edge to exit block).
    Return,
    /// Break out of a loop.
    Break,
    /// Continue to loop header.
    Continue,
    /// Goto jump to a labeled statement.
    Goto,
}

/// A control-flow graph for a single function.
#[derive(Debug, Clone)]
pub struct FunctionCfg {
    pub blocks: Vec<BasicBlock>,
    pub edges: Vec<(BlockId, BlockId, CfgEdge)>,
    pub entry: BlockId,
    pub exits: Vec<BlockId>,
    /// Source code for the function (for extracting text).
    function_start_byte: usize,
}

impl FunctionCfg {
    /// Get successors of a block.
    pub fn successors(&self, block_id: BlockId) -> Vec<(BlockId, &CfgEdge)> {
        self.edges
            .iter()
            .filter(|(from, _, _)| *from == block_id)
            .map(|(_, to, edge)| (*to, edge))
            .collect()
    }

    /// Get predecessors of a block.
    pub fn predecessors(&self, block_id: BlockId) -> Vec<(BlockId, &CfgEdge)> {
        self.edges
            .iter()
            .filter(|(_, to, _)| *to == block_id)
            .map(|(from, _, edge)| (*from, edge))
            .collect()
    }

    /// Get the number of blocks.
    pub fn block_count(&self) -> usize {
        self.blocks.len()
    }

    /// Get a block by ID.
    pub fn get_block(&self, id: BlockId) -> Option<&BasicBlock> {
        self.blocks.get(id)
    }
}

/// Builder for constructing a CFG from a function's compound_statement body.
struct CfgBuilder {
    blocks: Vec<BasicBlock>,
    edges: Vec<(BlockId, BlockId, CfgEdge)>,
    current_block: BlockId,
    /// Stack of (loop_header, loop_exit) for break/continue targets.
    loop_stack: Vec<(BlockId, BlockId)>,
    /// Label name → block ID mapping for goto edge wiring.
    label_blocks: HashMap<String, BlockId>,
    /// Pending goto edges: (source_block, label_name) to wire after all labels are seen.
    pending_gotos: Vec<(BlockId, String)>,
    function_start_byte: usize,
    /// File-level constants (static const int, #define) for condition evaluation.
    constants: MacroConstantMap,
}

impl CfgBuilder {
    fn new(function_start_byte: usize, constants: MacroConstantMap) -> Self {
        let entry_block = BasicBlock {
            id: 0,
            statements: Vec::new(),
            byte_range: (0, 0),
            condition_range: None,
        };
        CfgBuilder {
            blocks: vec![entry_block],
            edges: Vec::new(),
            current_block: 0,
            loop_stack: Vec::new(),
            label_blocks: HashMap::new(),
            pending_gotos: Vec::new(),
            function_start_byte,
            constants,
        }
    }

    fn new_block(&mut self) -> BlockId {
        let id = self.blocks.len();
        self.blocks.push(BasicBlock {
            id,
            statements: Vec::new(),
            byte_range: (0, 0),
            condition_range: None,
        });
        id
    }

    fn add_edge(&mut self, from: BlockId, to: BlockId, kind: CfgEdge) {
        // Avoid duplicate edges
        if !self
            .edges
            .iter()
            .any(|(f, t, k)| *f == from && *t == to && *k == kind)
        {
            self.edges.push((from, to, kind));
        }
    }

    fn add_statement(&mut self, start: usize, end: usize) {
        if let Some(block) = self.blocks.get_mut(self.current_block) {
            block.statements.push((start, end));
            if block.byte_range.0 == 0 || start < block.byte_range.0 {
                block.byte_range.0 = start;
            }
            if end > block.byte_range.1 {
                block.byte_range.1 = end;
            }
        }
    }

    fn build_from_compound_statement<'a>(&mut self, node: &Node<'a>, source: &str) {
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "{" | "}" => continue,
                    _ => self.process_statement(&child, source),
                }
            }
        }
    }

    fn process_statement<'a>(&mut self, node: &Node<'a>, source: &str) {
        match node.kind() {
            "if_statement" => self.process_if(node, source),
            "while_statement" => self.process_while(node, source),
            "for_statement" => self.process_for(node, source),
            "do_statement" => self.process_do_while(node, source),
            "switch_statement" => {
                // Treat switch as a single statement for now
                self.add_statement(node.start_byte(), node.end_byte());
            }
            "return_statement" => {
                self.add_statement(node.start_byte(), node.end_byte());
                let exit_block = self.new_block();
                self.add_edge(self.current_block, exit_block, CfgEdge::Return);
                self.current_block = self.new_block(); // Unreachable block after return
            }
            "break_statement" => {
                self.add_statement(node.start_byte(), node.end_byte());
                if let Some(&(_, loop_exit)) = self.loop_stack.last() {
                    self.add_edge(self.current_block, loop_exit, CfgEdge::Break);
                }
                self.current_block = self.new_block(); // Unreachable block after break
            }
            "continue_statement" => {
                self.add_statement(node.start_byte(), node.end_byte());
                if let Some(&(loop_header, _)) = self.loop_stack.last() {
                    self.add_edge(self.current_block, loop_header, CfgEdge::Continue);
                }
                self.current_block = self.new_block(); // Unreachable block after continue
            }
            "goto_statement" => {
                self.add_statement(node.start_byte(), node.end_byte());
                // Extract label name and record for deferred edge wiring
                for i in 0..node.child_count() {
                    if let Some(child) = node.child(i) {
                        if child.kind() == "statement_identifier" || child.kind() == "identifier" {
                            if let Ok(label) = child.utf8_text(source.as_bytes()) {
                                self.pending_gotos
                                    .push((self.current_block, label.to_string()));
                            }
                        }
                    }
                }
                self.current_block = self.new_block(); // Unreachable block after goto
            }
            "compound_statement" => {
                self.build_from_compound_statement(node, source);
            }
            "labeled_statement" => {
                // Start a new block at the label — goto edges target this block
                let label_block = self.new_block();
                self.add_edge(self.current_block, label_block, CfgEdge::Fallthrough);
                self.current_block = label_block;

                // Record label name → block mapping
                for i in 0..node.child_count() {
                    if let Some(child) = node.child(i) {
                        if child.kind() == "identifier" || child.kind() == "statement_identifier" {
                            if let Ok(label) = child.utf8_text(source.as_bytes()) {
                                self.label_blocks.insert(label.to_string(), label_block);
                            }
                        }
                    }
                }

                // Process the labeled statement's body
                for i in 0..node.child_count() {
                    if let Some(child) = node.child(i) {
                        if child.kind() != ":"
                            && child.kind() != "identifier"
                            && child.kind() != "statement_identifier"
                        {
                            self.process_statement(&child, source);
                        }
                    }
                }
            }
            _ => {
                // Regular statement: add to current block
                self.add_statement(node.start_byte(), node.end_byte());
            }
        }
    }

    fn process_if<'a>(&mut self, node: &Node<'a>, source: &str) {
        // Add the condition to the current block and check for constant value
        let const_val = if let Some(condition) = node.child_by_field_name("condition") {
            self.add_statement(condition.start_byte(), condition.end_byte());
            if let Some(block) = self.blocks.get_mut(self.current_block) {
                block.condition_range = Some((condition.start_byte(), condition.end_byte()));
            }
            evaluate_constant_condition(&condition, source, &self.constants)
        } else {
            None
        };

        let condition_block = self.current_block;
        let then_block = self.new_block();
        let join_block = self.new_block();

        // True branch — skip if condition is constant false
        if const_val != Some(false) {
            self.add_edge(condition_block, then_block, CfgEdge::TrueBranch);
            self.current_block = then_block;

            if let Some(consequence) = node.child_by_field_name("consequence") {
                self.process_statement(&consequence, source);
            }
            self.add_edge(self.current_block, join_block, CfgEdge::Fallthrough);
        }

        // False branch — skip if condition is constant true
        if const_val != Some(true) {
            if let Some(alternative) = node.child_by_field_name("alternative") {
                let else_block = self.new_block();
                self.add_edge(condition_block, else_block, CfgEdge::FalseBranch);
                self.current_block = else_block;

                // else_clause has a child that is the actual statement
                for i in 0..alternative.child_count() {
                    if let Some(child) = alternative.child(i) {
                        if child.kind() != "else" {
                            self.process_statement(&child, source);
                        }
                    }
                }
                self.add_edge(self.current_block, join_block, CfgEdge::Fallthrough);
            } else {
                self.add_edge(condition_block, join_block, CfgEdge::FalseBranch);
            }
        }

        // If condition is constant, ensure join block is reachable from exactly one side.
        // When the constant makes one branch dead AND there's no else, connect directly.
        if const_val == Some(false) && node.child_by_field_name("alternative").is_none() {
            self.add_edge(condition_block, join_block, CfgEdge::Fallthrough);
        }

        self.current_block = join_block;
    }

    fn process_while<'a>(&mut self, node: &Node<'a>, source: &str) {
        let header_block = self.new_block();
        self.add_edge(self.current_block, header_block, CfgEdge::Fallthrough);

        // Add condition to header block
        self.current_block = header_block;
        let const_val = if let Some(condition) = node.child_by_field_name("condition") {
            self.add_statement(condition.start_byte(), condition.end_byte());
            if let Some(block) = self.blocks.get_mut(header_block) {
                block.condition_range = Some((condition.start_byte(), condition.end_byte()));
            }
            evaluate_constant_condition(&condition, source, &self.constants)
        } else {
            None
        };

        let body_block = self.new_block();
        let exit_block = self.new_block();

        self.add_edge(header_block, body_block, CfgEdge::TrueBranch);
        // Skip FalseBranch for while(1) — the loop never exits via condition.
        // Exit is only reachable via break edges from the body.
        if const_val != Some(true) {
            self.add_edge(header_block, exit_block, CfgEdge::FalseBranch);
        }

        // Process body
        self.loop_stack.push((header_block, exit_block));
        self.current_block = body_block;
        if let Some(body) = node.child_by_field_name("body") {
            self.process_statement(&body, source);
        }
        self.add_edge(self.current_block, header_block, CfgEdge::BackEdge);
        self.loop_stack.pop();

        self.current_block = exit_block;
    }

    fn process_for<'a>(&mut self, node: &Node<'a>, source: &str) {
        // Initializer in current block
        if let Some(initializer) = node.child_by_field_name("initializer") {
            self.add_statement(initializer.start_byte(), initializer.end_byte());
        }

        let header_block = self.new_block();
        self.add_edge(self.current_block, header_block, CfgEdge::Fallthrough);

        // Condition in header block — for(;;) has no condition (always-true)
        self.current_block = header_block;
        let const_val = if let Some(condition) = node.child_by_field_name("condition") {
            self.add_statement(condition.start_byte(), condition.end_byte());
            if let Some(block) = self.blocks.get_mut(header_block) {
                block.condition_range = Some((condition.start_byte(), condition.end_byte()));
            }
            evaluate_constant_condition(&condition, source, &self.constants)
        } else {
            // No condition = for(;;) = always true
            Some(true)
        };

        let body_block = self.new_block();
        let update_block = self.new_block();
        let exit_block = self.new_block();

        self.add_edge(header_block, body_block, CfgEdge::TrueBranch);
        // Skip FalseBranch for for(;;) or for(;1;) — loop only exits via break
        if const_val != Some(true) {
            self.add_edge(header_block, exit_block, CfgEdge::FalseBranch);
        }

        // Process body
        self.loop_stack.push((update_block, exit_block));
        self.current_block = body_block;
        if let Some(body) = node.child_by_field_name("body") {
            self.process_statement(&body, source);
        }
        self.add_edge(self.current_block, update_block, CfgEdge::Fallthrough);
        self.loop_stack.pop();

        // Update expression
        self.current_block = update_block;
        if let Some(update) = node.child_by_field_name("update") {
            self.add_statement(update.start_byte(), update.end_byte());
        }
        self.add_edge(update_block, header_block, CfgEdge::BackEdge);

        self.current_block = exit_block;
    }

    fn process_do_while<'a>(&mut self, node: &Node<'a>, source: &str) {
        let body_block = self.new_block();
        self.add_edge(self.current_block, body_block, CfgEdge::Fallthrough);

        let exit_block = self.new_block();

        // Process body first (do-while executes body before checking condition)
        self.loop_stack.push((body_block, exit_block));
        self.current_block = body_block;
        if let Some(body) = node.child_by_field_name("body") {
            self.process_statement(&body, source);
        }
        self.loop_stack.pop();

        // Condition block
        let cond_block = self.new_block();
        self.add_edge(self.current_block, cond_block, CfgEdge::Fallthrough);
        self.current_block = cond_block;

        if let Some(condition) = node.child_by_field_name("condition") {
            self.add_statement(condition.start_byte(), condition.end_byte());
            if let Some(block) = self.blocks.get_mut(cond_block) {
                block.condition_range = Some((condition.start_byte(), condition.end_byte()));
            }
        }

        self.add_edge(cond_block, body_block, CfgEdge::BackEdge);
        self.add_edge(cond_block, exit_block, CfgEdge::FalseBranch);

        self.current_block = exit_block;
    }

    fn build(mut self) -> FunctionCfg {
        // Wire pending goto edges now that all labels have been seen
        let goto_edges: Vec<(BlockId, BlockId)> = self
            .pending_gotos
            .iter()
            .filter_map(|(src, label)| self.label_blocks.get(label).map(|&tgt| (*src, tgt)))
            .collect();
        for (src, tgt) in goto_edges {
            self.add_edge(src, tgt, CfgEdge::Goto);
        }

        // Find exit blocks (blocks with Return edges, or the last block if it has no successors)
        let mut exits: Vec<BlockId> = self
            .edges
            .iter()
            .filter(|(_, _, kind)| *kind == CfgEdge::Return)
            .map(|(from, _, _)| *from)
            .collect();

        // Also include terminal blocks (those in Return edges as targets)
        let return_targets: Vec<BlockId> = self
            .edges
            .iter()
            .filter(|(_, _, kind)| *kind == CfgEdge::Return)
            .map(|(_, to, _)| *to)
            .collect();
        exits.extend(return_targets);

        // If no explicit returns, the last block is an implicit exit
        if exits.is_empty() && !self.blocks.is_empty() {
            exits.push(self.blocks.len() - 1);
        }

        exits.sort();
        exits.dedup();

        FunctionCfg {
            blocks: self.blocks,
            edges: self.edges,
            entry: 0,
            exits,
            function_start_byte: self.function_start_byte,
        }
    }
}

/// Evaluate whether a condition node is a compile-time constant.
/// Returns `Some(true)` for truthy constants (non-zero integer, `true`),
/// `Some(false)` for `0` / `false`, and `None` for non-constant expressions.
fn evaluate_constant_condition(
    condition: &Node,
    source: &str,
    constants: &MacroConstantMap,
) -> Option<bool> {
    // The condition field of an if/while is a parenthesized_expression in C.
    let inner = unwrap_parens_cfg(condition);
    match inner.kind() {
        "number_literal" => {
            let text = inner.utf8_text(source.as_bytes()).ok()?;
            let trimmed = text.trim();
            if trimmed == "0" {
                Some(false)
            } else {
                // Accept any integer literal that isn't 0 as truthy
                trimmed.parse::<i64>().ok().map(|n| n != 0)
            }
        }
        "true" => Some(true),
        "false" => Some(false),
        // Resolve identifiers via file-level constants (static const int, #define).
        // E.g., `static const int STATIC_CONST_TRUE = 1;` → if(STATIC_CONST_TRUE) is truthy.
        "identifier" => {
            let name = inner.utf8_text(source.as_bytes()).ok()?;
            constants.get(name).map(|&v| v != 0)
        }
        // Handle constant comparisons: 5==5, 5!=5, etc.
        "binary_expression" => {
            let left = inner.child_by_field_name("left")?;
            let operator = inner.child_by_field_name("operator")?;
            let right = inner.child_by_field_name("right")?;
            let left = unwrap_parens_cfg(&left);
            let right = unwrap_parens_cfg(&right);

            // Resolve each operand: number literal or identifier via constants
            let lv = resolve_constant_operand(&left, source, constants)?;
            let rv = resolve_constant_operand(&right, source, constants)?;

            let op = operator.utf8_text(source.as_bytes()).ok()?;
            match op.trim() {
                "==" => Some(lv == rv),
                "!=" => Some(lv != rv),
                "<" => Some(lv < rv),
                ">" => Some(lv > rv),
                "<=" => Some(lv <= rv),
                ">=" => Some(lv >= rv),
                _ => None,
            }
        }
        _ => None,
    }
}

/// Resolve a single operand node to an i64 value (number literal or constant identifier).
fn resolve_constant_operand(
    node: &Node,
    source: &str,
    constants: &MacroConstantMap,
) -> Option<i64> {
    match node.kind() {
        "number_literal" => {
            let text = node.utf8_text(source.as_bytes()).ok()?.trim().to_string();
            text.parse::<i64>().ok()
        }
        "identifier" => {
            let name = node.utf8_text(source.as_bytes()).ok()?;
            constants.get(name).copied()
        }
        _ => None,
    }
}

/// Unwrap parenthesized_expression nodes for CFG condition evaluation.
fn unwrap_parens_cfg<'a>(node: &'a Node<'a>) -> Node<'a> {
    let mut n = *node;
    while n.kind() == "parenthesized_expression" {
        if let Some(inner) = n.child(1) {
            n = inner;
        } else {
            break;
        }
    }
    n
}

/// Build a CFG from a function_definition node.
/// Returns None if the node is not a function_definition or has no body.
pub fn build_function_cfg(func_node: &Node, source: &str) -> Option<FunctionCfg> {
    build_function_cfg_with_constants(func_node, source, &MacroConstantMap::new())
}

/// Build a CFG with file-level constant resolution (static const int, #define).
/// This enables dead-branch pruning for patterns like `if(STATIC_CONST_TRUE)`.
pub fn build_function_cfg_with_constants(
    func_node: &Node,
    source: &str,
    constants: &MacroConstantMap,
) -> Option<FunctionCfg> {
    if func_node.kind() != "function_definition" {
        return None;
    }

    let body = func_node.child_by_field_name("body")?;
    if body.kind() != "compound_statement" {
        return None;
    }

    let mut builder = CfgBuilder::new(func_node.start_byte(), constants.clone());
    builder.build_from_compound_statement(&body, source);
    Some(builder.build())
}

/// Extract the function name from a function_definition node.
pub fn get_function_name<'a>(func_node: &Node<'a>, source: &'a str) -> Option<&'a str> {
    let declarator = func_node.child_by_field_name("declarator")?;
    extract_name_from_declarator(&declarator, source)
}

fn extract_name_from_declarator<'a>(node: &Node<'a>, source: &'a str) -> Option<&'a str> {
    match node.kind() {
        "identifier" => node.utf8_text(source.as_bytes()).ok(),
        "function_declarator" | "pointer_declarator" => {
            let inner = node.child_by_field_name("declarator")?;
            extract_name_from_declarator(&inner, source)
        }
        _ => {
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "identifier" {
                        return child.utf8_text(source.as_bytes()).ok();
                    }
                }
            }
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse_and_build_cfg(code: &str) -> Option<FunctionCfg> {
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&tree_sitter_c::language()).unwrap();
        let tree = parser.parse(code, None).unwrap();
        let root = tree.root_node();

        // Find the function_definition
        for i in 0..root.child_count() {
            if let Some(child) = root.child(i) {
                if child.kind() == "function_definition" {
                    return build_function_cfg(&child, code);
                }
            }
        }
        None
    }

    #[test]
    fn test_simple_function() {
        let code = r#"
        void foo() {
            int x = 1;
            int y = 2;
        }
        "#;
        let cfg = parse_and_build_cfg(code).unwrap();
        assert!(cfg.block_count() >= 1);
        assert_eq!(cfg.entry, 0);
    }

    #[test]
    fn test_if_else() {
        let code = r#"
        void foo(int x) {
            if (x > 0) {
                x = 1;
            } else {
                x = 2;
            }
            x = 3;
        }
        "#;
        let cfg = parse_and_build_cfg(code).unwrap();
        // Should have: entry, then-block, else-block, join-block (minimum)
        assert!(cfg.block_count() >= 4);
        // Should have true and false branch edges
        let has_true = cfg.edges.iter().any(|(_, _, e)| *e == CfgEdge::TrueBranch);
        let has_false = cfg.edges.iter().any(|(_, _, e)| *e == CfgEdge::FalseBranch);
        assert!(has_true);
        assert!(has_false);
    }

    #[test]
    fn test_while_loop() {
        let code = r#"
        void foo(int n) {
            int i = 0;
            while (i < n) {
                i++;
            }
        }
        "#;
        let cfg = parse_and_build_cfg(code).unwrap();
        // Should have a back edge
        let has_back = cfg.edges.iter().any(|(_, _, e)| *e == CfgEdge::BackEdge);
        assert!(has_back);
    }

    #[test]
    fn test_for_loop() {
        let code = r#"
        void foo() {
            for (int i = 0; i < 10; i++) {
                int x = i;
            }
        }
        "#;
        let cfg = parse_and_build_cfg(code).unwrap();
        let has_back = cfg.edges.iter().any(|(_, _, e)| *e == CfgEdge::BackEdge);
        assert!(has_back);
    }

    #[test]
    fn test_return_creates_exit() {
        let code = r#"
        int foo(int x) {
            if (x < 0) {
                return -1;
            }
            return x;
        }
        "#;
        let cfg = parse_and_build_cfg(code).unwrap();
        let return_count = cfg
            .edges
            .iter()
            .filter(|(_, _, e)| *e == CfgEdge::Return)
            .count();
        assert!(return_count >= 2);
    }

    #[test]
    fn test_goto_edges() {
        let code = r#"
        void foo(int x) {
            if (x < 0) goto skip;
            int y = 42;
            skip:
            use(y);
        }
        "#;
        let cfg = parse_and_build_cfg(code).unwrap();
        let has_goto = cfg.edges.iter().any(|(_, _, e)| *e == CfgEdge::Goto);
        assert!(has_goto, "Should have a goto edge");
        // The label should create a new block
        assert!(
            cfg.block_count() >= 4,
            "goto+label should create at least 4 blocks"
        );
    }

    #[test]
    fn test_break_continue() {
        let code = r#"
        void foo(int n) {
            for (int i = 0; i < n; i++) {
                if (i == 5) break;
                if (i == 3) continue;
            }
        }
        "#;
        let cfg = parse_and_build_cfg(code).unwrap();
        let has_break = cfg.edges.iter().any(|(_, _, e)| *e == CfgEdge::Break);
        let has_continue = cfg.edges.iter().any(|(_, _, e)| *e == CfgEdge::Continue);
        assert!(has_break);
        assert!(has_continue);
    }
}