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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
//! Go CFG builder implementation
use crate::ast::FunctionNode;
use crate::cfg::{Cfg, NodeId, NodeKind};
use crate::language::cfg_builder::CfgBuilder;
use crate::language::tree_sitter_utils::{
find_child_by_kind, find_function_by_start, with_cached_go_tree,
};
use tree_sitter::Node;
/// Go CFG builder
///
/// Builds control flow graphs from Go function bodies parsed with tree-sitter.
pub struct GoCfgBuilder;
impl CfgBuilder for GoCfgBuilder {
fn build(&self, function: &FunctionNode) -> Cfg {
let (_body_node_id, source) = function.body.as_go();
let result = with_cached_go_tree(source, |root| {
let func_node = find_function_by_start(
root,
function.span.start,
&["function_declaration", "method_declaration"],
)?;
let body_node = find_child_by_kind(func_node, "block")?;
let mut builder = GoCfgBuilderState::new();
builder.build_from_block(&body_node, source);
Some(builder.cfg)
});
result.unwrap_or_else(|| {
let mut cfg = Cfg::new();
cfg.add_edge(cfg.entry, cfg.exit);
cfg
})
}
}
/// Internal builder state for constructing the CFG
struct GoCfgBuilderState {
cfg: Cfg,
current_node: Option<NodeId>,
/// Stack of loop/switch/select contexts for break/continue
loop_stack: Vec<LoopContext>,
/// Label attached to the next loop/switch/select statement visited, if any
pending_label: Option<String>,
}
struct LoopContext {
/// Lazily created: `None` until something actually needs to jump here
/// (a `break`, a case falling through, or a no-default fallback edge).
/// A `for` loop's own header->join "exit" edge always creates it eagerly
/// since that path is unconditional, so it's only ever lazy for
/// switch/select, where every case may terminate control flow itself
/// (e.g. `return` in every case), leaving the join node unneeded.
break_target: Option<NodeId>,
/// `None` for switch/select contexts, which do not accept `continue`
continue_target: Option<NodeId>,
/// Label naming this construct, for labeled break/continue
label: Option<String>,
}
impl GoCfgBuilderState {
fn new() -> Self {
let cfg = Cfg::new();
let entry = cfg.entry;
GoCfgBuilderState {
cfg,
current_node: Some(entry),
loop_stack: Vec::new(),
pending_label: None,
}
}
/// Get or lazily create the break target for the loop/switch/select
/// context at `idx` in `loop_stack`.
fn get_or_create_break_target(&mut self, idx: usize) -> NodeId {
if let Some(ctx) = self.loop_stack.get(idx) {
if let Some(id) = ctx.break_target {
return id;
}
}
let id = self.cfg.add_node(NodeKind::Join);
if let Some(ctx) = self.loop_stack.get_mut(idx) {
ctx.break_target = Some(id);
}
id
}
/// Visit every named child of `node` in order, dispatching each through
/// `visit_node`. Shared by `build_from_block` (a function/if/for body) and
/// the `statement_list` dispatch arm below (the wrapper tree-sitter-go
/// puts around every multi-statement body), so the walk-and-dispatch loop
/// isn't duplicated between them.
fn visit_children(&mut self, node: &Node, source: &str) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
// Skip braces and other structural nodes
if child.is_named() {
self.visit_node(&child, source);
}
}
}
/// Visit one case body shared by `visit_switch` and `visit_select`: build
/// the case's start node off `condition_node`, walk its body, and connect
/// its end to the enclosing switch/select's join (unless the case body
/// itself already terminated control flow, e.g. `return`/`break`).
/// `case`'s own kind (`expression_case`/`type_case`/`default_case` for a
/// switch, `communication_case`/`default_case` for a select) is the
/// caller's concern, not this helper's — a case is a case once the
/// caller has already decided to visit it.
fn visit_case(&mut self, case: &Node, condition_node: NodeId, idx: usize, source: &str) {
let case_start = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(condition_node, case_start);
self.current_node = Some(case_start);
// `:` is a punctuation token, already excluded by `visit_children`'s
// `is_named()` check like every other unnamed token.
self.visit_children(case, source);
if let Some(case_end) = self.current_node {
if case_end != self.cfg.exit {
let join_node = self.get_or_create_break_target(idx);
self.cfg.add_edge(case_end, join_node);
}
}
}
/// Build CFG from a block node
fn build_from_block(&mut self, block: &Node, source: &str) {
self.visit_children(block, source);
// Connect last node to exit
if let Some(last_node) = self.current_node {
if last_node != self.cfg.exit {
let has_exit_edge = self
.cfg
.edges
.iter()
.any(|e| e.from == last_node && e.to == self.cfg.exit);
if !has_exit_edge {
self.cfg.add_edge(last_node, self.cfg.exit);
}
}
}
}
/// Visit a tree-sitter node and build CFG
fn visit_node(&mut self, node: &Node, source: &str) {
match node.kind() {
"if_statement" => self.visit_if(node, source),
"for_statement" => self.visit_for(node, source),
"switch_statement" | "expression_switch_statement" => self.visit_switch(node, source),
"type_switch_statement" => self.visit_type_switch(node, source),
"select_statement" => self.visit_select(node, source),
"return_statement" => self.visit_return(node),
"break_statement" => self.visit_break(node, source),
"continue_statement" => self.visit_continue(node, source),
"goto_statement" => self.visit_goto(),
"labeled_statement" => self.visit_labeled(node, source),
"defer_statement" => self.visit_defer(node),
"go_statement" => self.visit_go_statement(node),
"expression_statement" => self.visit_expression_statement(node, source),
"block" => self.build_from_block(node, source),
// tree-sitter-go wraps every sequence of statements (a
// function/if/for block body, a switch/select case body, etc.)
// in a statement_list node. Without flattening it via
// `visit_children`, every statement inside would be treated as
// one opaque, un-dispatched node - collapsing entire multi-
// statement blocks into a single generic statement and silently
// skipping any if/for/switch/etc. nested inside.
"statement_list" => self.visit_children(node, source),
_ => {
// Regular statement - add node and continue
self.visit_simple_statement();
}
}
}
/// A bare expression statement is a `panic(...)` call or an ordinary
/// statement; distinguishing the two is real decision logic, not
/// dispatch, so it lives here rather than inline in `visit_node`'s match.
fn visit_expression_statement(&mut self, node: &Node, source: &str) {
if is_panic_call(node, source) {
self.visit_panic();
} else {
self.visit_simple_statement();
}
}
fn visit_simple_statement(&mut self) {
if let Some(from_node) = self.current_node {
let stmt_node = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(from_node, stmt_node);
self.current_node = Some(stmt_node);
}
}
fn visit_if(&mut self, node: &Node, source: &str) {
let from_node = self.current_node.expect("Current node should exist");
// Condition node
let condition_node = self.cfg.add_node(NodeKind::Condition);
self.cfg.add_edge(from_node, condition_node);
// Then branch (consequence block)
let then_start = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(condition_node, then_start);
if let Some(consequence) = find_child_by_kind(*node, "block") {
self.current_node = Some(then_start);
self.build_from_block(&consequence, source);
}
let then_end = self.current_node.unwrap_or(then_start);
// Else branch (alternative)
let join_node = self.cfg.add_node(NodeKind::Join);
if let Some(alternative) = find_child_by_field(*node, "alternative") {
let else_start = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(condition_node, else_start);
self.current_node = Some(else_start);
self.visit_node(&alternative, source);
let else_end = self.current_node.unwrap_or(else_start);
if then_end != self.cfg.exit {
self.cfg.add_edge(then_end, join_node);
}
if else_end != self.cfg.exit {
self.cfg.add_edge(else_end, join_node);
}
} else {
// No else branch - condition can go directly to join
self.cfg.add_edge(condition_node, join_node);
if then_end != self.cfg.exit {
self.cfg.add_edge(then_end, join_node);
}
}
self.current_node = Some(join_node);
}
fn visit_for(&mut self, node: &Node, source: &str) {
let from_node = self.current_node.expect("Current node should exist");
// Loop header
let loop_header = self.cfg.add_node(NodeKind::LoopHeader);
self.cfg.add_edge(from_node, loop_header);
// Loop body
let body_start = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(loop_header, body_start);
// Push loop context for break/continue. The join node is created
// lazily below via get_or_create_break_target, but a `for` loop's
// header always has an unconditional "exit" edge to it (the loop
// condition can always be false, or there is none), so it will
// always end up created.
let label = self.pending_label.take();
self.loop_stack.push(LoopContext {
break_target: None,
continue_target: Some(loop_header),
label,
});
// Visit loop body
if let Some(body) = find_child_by_kind(*node, "block") {
self.current_node = Some(body_start);
self.build_from_block(&body, source);
// Back edge to loop header
if let Some(body_end) = self.current_node {
if body_end != self.cfg.exit {
self.cfg.add_edge(body_end, loop_header);
}
}
}
// Exit condition from loop header
let idx = self.loop_stack.len() - 1;
let join_node = self.get_or_create_break_target(idx);
self.cfg.add_edge(loop_header, join_node);
// Pop loop context
self.loop_stack.pop();
self.current_node = Some(join_node);
}
fn visit_switch(&mut self, node: &Node, source: &str) {
let from_node = self.current_node.expect("Current node should exist");
// Switch condition
let condition_node = self.cfg.add_node(NodeKind::Condition);
self.cfg.add_edge(from_node, condition_node);
// Push break context (switch/select break independently of any
// enclosing loop; `continue` is not valid here, so continue_target
// is None and unlabeled continue skips over this context). The join
// node itself is created lazily: if every case terminates control
// flow (e.g. `return` in every case) and there's a default (so no
// fallback-to-join edge is added either), nothing ever needs a join
// node, and creating one eagerly would leave it unreachable.
let idx = self.loop_stack.len();
let label = self.pending_label.take();
self.loop_stack.push(LoopContext {
break_target: None,
continue_target: None,
label,
});
// Visit each case. Regular switches use "expression_case"; type
// switches (switch x.(type) { case T: ... }) use "type_case".
let mut has_default = false;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
let kind = child.kind();
if is_switch_case_kind(kind) {
has_default |= kind == "default_case";
self.visit_case(&child, condition_node, idx, source);
}
}
// If there's no default case, no case is guaranteed to match, so the
// switch can fall through directly to join. When a default exists,
// one case always executes, so this edge would be spurious.
if !has_default {
let join_node = self.get_or_create_break_target(idx);
self.cfg.add_edge(condition_node, join_node);
}
let ctx = self.loop_stack.pop().expect("pushed switch context above");
self.current_node = ctx.break_target;
}
fn visit_type_switch(&mut self, node: &Node, source: &str) {
// Type switches work similar to regular switches
self.visit_switch(node, source);
}
fn visit_select(&mut self, node: &Node, source: &str) {
let from_node = self.current_node.expect("Current node should exist");
// Select condition (non-deterministic choice)
let condition_node = self.cfg.add_node(NodeKind::Condition);
self.cfg.add_edge(from_node, condition_node);
// Push break context (select break independently of any enclosing
// loop; `continue` is not valid here). The join node is created
// lazily: if every case terminates control flow (e.g. `return` in
// every case), nothing ever needs a join node, and creating one
// eagerly would leave it unreachable.
let idx = self.loop_stack.len();
let label = self.pending_label.take();
self.loop_stack.push(LoopContext {
break_target: None,
continue_target: None,
label,
});
// Visit each communication case
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if matches!(child.kind(), "communication_case" | "default_case") {
self.visit_case(&child, condition_node, idx, source);
}
}
let ctx = self.loop_stack.pop().expect("pushed select context above");
self.current_node = ctx.break_target;
}
fn visit_return(&mut self, _node: &Node) {
if let Some(from_node) = self.current_node {
let return_node = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(from_node, return_node);
self.cfg.add_edge(return_node, self.cfg.exit);
self.current_node = None; // Dead code after return
}
}
fn visit_break(&mut self, node: &Node, source: &str) {
if let Some(from_node) = self.current_node {
let label = find_label_text(node, source);
let idx = match &label {
Some(label) => self
.loop_stack
.iter()
.rposition(|ctx| ctx.label.as_deref() == Some(label.as_str())),
None => {
if self.loop_stack.is_empty() {
None
} else {
Some(self.loop_stack.len() - 1)
}
}
};
if let Some(idx) = idx {
let target = self.get_or_create_break_target(idx);
let break_node = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(from_node, break_node);
self.cfg.add_edge(break_node, target);
self.current_node = None; // Dead code after break
}
}
}
fn visit_continue(&mut self, node: &Node, source: &str) {
if let Some(from_node) = self.current_node {
let label = find_label_text(node, source);
// `continue` only targets an enclosing `for` loop; switch/select
// contexts (continue_target: None) are transparent to it.
let target = match &label {
Some(label) => self
.loop_stack
.iter()
.rev()
.find(|ctx| ctx.label.as_deref() == Some(label.as_str()))
.and_then(|ctx| ctx.continue_target),
None => self
.loop_stack
.iter()
.rev()
.find_map(|ctx| ctx.continue_target),
};
if let Some(target) = target {
let continue_node = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(from_node, continue_node);
self.cfg.add_edge(continue_node, target);
self.current_node = None; // Dead code after continue
}
}
}
fn visit_goto(&mut self) {
if let Some(from_node) = self.current_node {
// goto is a branch: +1 CC, then control leaves this path.
// We don't track named jump targets (matches the C builder's
// approximation), so it is modeled as an edge straight to exit.
let goto_node = self.cfg.add_node(NodeKind::Condition);
self.cfg.add_edge(from_node, goto_node);
self.cfg.add_edge(goto_node, self.cfg.exit);
self.current_node = None;
}
}
fn visit_labeled(&mut self, node: &Node, source: &str) {
// A label is a jump target reachable via goto. Always create a node
// for it so dead code after a goto/return/break doesn't panic.
let label_node = self.cfg.add_node(NodeKind::Statement);
if let Some(from) = self.current_node {
self.cfg.add_edge(from, label_node);
} else {
self.cfg.add_edge(self.cfg.entry, label_node);
}
self.current_node = Some(label_node);
// Record the label so the following loop/switch/select statement
// can be targeted by a labeled break/continue.
self.pending_label = find_label_text(node, source);
// Visit the labeled statement itself (skip the label_name child)
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.is_named() && child.kind() != "label_name" {
self.visit_node(&child, source);
break;
}
}
self.pending_label = None;
}
fn visit_defer(&mut self, _node: &Node) {
// Defer statements are executed, but don't affect control flow
// They're counted as non-structured exits in metrics
self.visit_simple_statement();
}
fn visit_go_statement(&mut self, _node: &Node) {
// Go statements spawn goroutines but don't affect control flow
// They're counted in fan-out metrics
self.visit_simple_statement();
}
fn visit_panic(&mut self) {
if let Some(from_node) = self.current_node {
let panic_node = self.cfg.add_node(NodeKind::Statement);
self.cfg.add_edge(from_node, panic_node);
self.cfg.add_edge(panic_node, self.cfg.exit);
self.current_node = None; // Dead code after panic
}
}
}
/// Find a child node by field name
fn find_child_by_field<'a>(node: Node<'a>, field: &str) -> Option<Node<'a>> {
node.child_by_field_name(field)
}
/// Extract the label name text from a labeled/break/continue statement node,
/// if it has a `label_name` child.
fn find_label_text(node: &Node, source: &str) -> Option<String> {
find_child_by_kind(*node, "label_name")
.map(|n| source[n.start_byte()..n.end_byte()].to_string())
}
/// True for switch/type-switch case node kinds (`switch x { ... }` and
/// `switch x.(type) { ... }` share `default_case`; only `expression_case` vs.
/// `type_case` differs between them).
/// Whether a tree-sitter-go node kind is a `switch` case arm
/// (`expression_case`/`type_case`/`default_case`). Used by `visit_switch` and
/// `visit_type_switch` to filter case children before handing them to
/// `visit_case`; select's `communication_case` is a distinct kind and isn't
/// covered here.
fn is_switch_case_kind(kind: &str) -> bool {
matches!(kind, "expression_case" | "type_case" | "default_case")
}
/// Check if a node is a panic() call
fn is_panic_call(node: &Node, source: &str) -> bool {
// Check if this is a call_expression where the function is "panic"
if let Some(call_expr) = find_child_by_kind(*node, "call_expression") {
if let Some(func) = find_child_by_kind(call_expr, "identifier") {
let func_text = &source[func.start_byte()..func.end_byte()];
return func_text == "panic";
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::{FunctionId, FunctionNode};
use crate::language::parser::LanguageParser;
use crate::language::{FunctionBody, SourceSpan};
fn make_test_go_function(source: &str) -> FunctionNode {
FunctionNode {
id: FunctionId {
file_index: 0,
local_index: 0,
},
name: Some("test".to_string()),
span: SourceSpan::new(0, source.len(), 1, 1, 0),
body: FunctionBody::Go {
body_node: 0,
source: source.to_string(),
},
suppression_reason: None,
}
}
#[test]
fn test_go_cfg_builder_simple() {
let source = r#"
package main
func test() {
x := 1
}
"#;
let function = make_test_go_function(source);
let builder = GoCfgBuilder;
let cfg = builder.build(&function);
// Should have entry, statement, exit
assert!(cfg.node_count() >= 2);
}
#[test]
fn test_go_cfg_builder_if() {
let source = r#"
package main
func test(x int) {
if x > 0 {
println("positive")
}
}
"#;
// Parse to find the actual function start position
use crate::language::GoParser;
let parser = GoParser::new().unwrap();
let module = parser.parse(source, "test.go").unwrap();
let functions = module.discover_functions(0, source);
assert_eq!(functions.len(), 1);
let function = &functions[0];
let builder = GoCfgBuilder;
let cfg = builder.build(function);
// Should have at least entry and exit
// Full CFG would be: entry, condition, then, join, exit (5 nodes)
// But we verify it's more than just entry->exit (2 nodes)
assert!(
cfg.node_count() >= 3,
"Expected at least 3 nodes for if statement, got {}",
cfg.node_count()
);
assert!(
cfg.edge_count() >= 2,
"Expected at least 2 edges, got {}",
cfg.edge_count()
);
}
#[test]
fn test_go_cfg_builder_for() {
let source = r#"
package main
func test() {
for i := 0; i < 10; i++ {
println(i)
}
}
"#;
// Parse to find the actual function start position
use crate::language::GoParser;
let parser = GoParser::new().unwrap();
let module = parser.parse(source, "test.go").unwrap();
let functions = module.discover_functions(0, source);
assert_eq!(functions.len(), 1);
let function = &functions[0];
let builder = GoCfgBuilder;
let cfg = builder.build(function);
// Should have at least entry and exit
// Full CFG would be: entry, loop header, body, join, exit (5 nodes)
// But we verify it's more than just entry->exit (2 nodes)
assert!(
cfg.node_count() >= 3,
"Expected at least 3 nodes for for loop, got {}",
cfg.node_count()
);
assert!(
cfg.edge_count() >= 2,
"Expected at least 2 edges, got {}",
cfg.edge_count()
);
}
/// Parse `source`, find the first declared function, and build its CFG.
fn build_cfg(source: &str) -> Cfg {
use crate::language::GoParser;
let parser = GoParser::new().unwrap();
let module = parser.parse(source, "test.go").unwrap();
let functions = module.discover_functions(0, source);
assert_eq!(functions.len(), 1, "expected exactly one function");
let builder = GoCfgBuilder;
builder.build(&functions[0])
}
// ---- go statements (goroutines) ----
#[test]
fn test_go_statement_simple() {
let source = r#"
package main
func test() {
go doWork()
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
// go statement is a fork, not a branch: entry -> stmt -> exit, no CC increase
assert!(cfg.node_count() >= 2);
}
#[test]
fn test_go_statement_with_closure_body_not_walked() {
// The goroutine body (containing an if) must not be walked into as
// part of the enclosing function's control flow - it executes
// concurrently, not inline.
let source = r#"
package main
func test(x int) {
go func() {
if x > 0 {
doWork()
}
}()
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
// No Condition node should be produced from the closure's inner `if`,
// since the goroutine body is not part of this function's CFG.
let condition_count = cfg
.nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Condition))
.count();
assert_eq!(
condition_count, 0,
"goroutine body should not be walked into"
);
}
#[test]
fn test_multiple_go_statements_sequential() {
let source = r#"
package main
func test() {
go doWork()
go doOtherWork()
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
assert!(cfg.node_count() >= 3);
}
// ---- defer statements ----
#[test]
fn test_defer_statement_simple() {
let source = r#"
package main
func test() {
defer cleanup()
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
// defer does not fork or branch: no Condition node produced
let condition_count = cfg
.nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Condition))
.count();
assert_eq!(condition_count, 0);
}
#[test]
fn test_defer_does_not_execute_inline() {
// A defer followed by more statements should behave as ordinary
// sequential flow: defer doesn't jump or terminate the block.
let source = r#"
package main
func test() {
defer cleanup()
doWork()
doMore()
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
// entry -> defer_stmt -> doWork -> doMore -> exit: linear chain
assert_eq!(cfg.node_count(), 5);
assert_eq!(cfg.edge_count(), 4);
}
#[test]
fn test_multiple_defers() {
let source = r#"
package main
func test() {
defer cleanup()
defer cleanup()
defer cleanup()
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
assert!(cfg.node_count() >= 4);
}
// ---- select statements ----
#[test]
fn test_select_statement_branches_like_switch() {
let source = r#"
package main
func test(ch1 chan int, ch2 chan int) {
select {
case <-ch1:
doA()
case <-ch2:
doB()
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
// Each communication_case should be reachable from a shared
// Condition node (the select), and both should reach a join.
let condition_count = cfg
.nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Condition))
.count();
assert_eq!(condition_count, 1, "select should add one Condition node");
}
#[test]
fn test_select_with_default() {
let source = r#"
package main
func test(ch chan int) {
select {
case v := <-ch:
_ = v
default:
doB()
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
assert!(cfg.node_count() >= 4);
}
#[test]
fn test_select_in_loop_break_targets_select_not_loop() {
// An unlabeled `break` inside a select's case must exit the select,
// not the enclosing `for` loop.
let source = r#"
package main
func test(ch chan int) {
for {
select {
case <-ch:
break
default:
doB()
}
doAfterSelect()
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
// doAfterSelect() must still be reachable (break only exits the
// select, so the loop body continues past it).
let stmt_count = cfg
.nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Statement))
.count();
// entry-adjacent statements: select cases (2) + break + doB + doAfterSelect >= 4
assert!(stmt_count >= 4, "got {} statement nodes", stmt_count);
}
// ---- type switches ----
#[test]
fn test_type_switch_visits_every_case() {
// Regression: type_case nodes (used by `switch x.(type)`) were
// previously not recognized by the switch visitor (only
// expression_case/default_case were), so non-default cases were
// silently skipped rather than contributing to the CFG.
let source = r#"
package main
func test(x interface{}) {
switch x.(type) {
case int:
doInt()
case string:
doString()
default:
doOther()
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
let stmt_count = cfg
.nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Statement))
.count();
// At least 3 case-start nodes + 3 case-body statement nodes = 6.
// (Before the fix, only the default_case was recognized, so the
// int/string type_case branches were silently dropped.)
assert!(
stmt_count >= 6,
"all three type_case/default_case branches should be visited, got {} statement nodes",
stmt_count
);
}
#[test]
fn test_type_switch_without_default_has_fallthrough_edge() {
let source = r#"
package main
func test(x interface{}) {
switch x.(type) {
case int:
doInt()
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
// No default: the switch condition must have a direct edge to join
// representing "no case matched".
assert!(cfg.node_count() >= 4);
}
// ---- switch default-case fallthrough edge ----
#[test]
fn test_switch_with_default_has_no_spurious_fallthrough_edge() {
// Regression: the switch visitor used to unconditionally add a
// condition -> join edge even when a default case exists, even
// though a default case guarantees some case always executes.
let with_default = r#"
package main
func test(x int) {
switch x {
case 1:
doA()
default:
doB()
}
}
"#;
let without_default = r#"
package main
func test(x int) {
switch x {
case 1:
doA()
}
}
"#;
let cfg_with = build_cfg(with_default);
let cfg_without = build_cfg(without_default);
cfg_with.validate().unwrap();
cfg_without.validate().unwrap();
assert!(
!has_condition_to_join_edge(&cfg_with),
"switch with a default case must not have a direct \
condition -> join fallthrough edge, since a case always matches"
);
assert!(
has_condition_to_join_edge(&cfg_without),
"switch without a default case must have a direct \
condition -> join fallthrough edge for the no-match path"
);
}
/// True if the CFG has an edge directly from a Condition node to a Join node.
fn has_condition_to_join_edge(cfg: &Cfg) -> bool {
let kind_of = |id: NodeId| cfg.nodes.iter().find(|n| n.id == id).map(|n| n.kind);
cfg.edges.iter().any(|e| {
matches!(kind_of(e.from), Some(NodeKind::Condition))
&& matches!(kind_of(e.to), Some(NodeKind::Join))
})
}
// ---- labeled break/continue ----
#[test]
fn test_labeled_continue_targets_outer_loop() {
let source = r#"
package main
func test() {
Outer:
for i := 0; i < 10; i++ {
for j := 0; j < 10; j++ {
if j == 5 {
continue Outer
}
}
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
assert!(cfg.node_count() >= 5);
}
#[test]
fn test_labeled_break_targets_outer_loop() {
let source = r#"
package main
func test() {
Outer:
for i := 0; i < 10; i++ {
for j := 0; j < 10; j++ {
if j == 5 {
break Outer
}
}
doAfterOuterLoop()
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
assert!(cfg.node_count() >= 6);
}
#[test]
fn test_labeled_break_from_switch_in_loop() {
let source = r#"
package main
func test(x int) {
Loop:
for i := 0; i < 10; i++ {
switch x {
case 1:
break Loop
default:
doB()
}
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
assert!(cfg.node_count() >= 5);
}
#[test]
fn test_unlabeled_break_in_switch_does_not_break_outer_loop() {
// Regression: switch/select never pushed their own break context,
// so an unlabeled `break` inside a switch nested in a loop was
// silently dropped instead of exiting only the switch.
let source = r#"
package main
func test(x int) {
for i := 0; i < 10; i++ {
switch x {
case 1:
break
default:
doB()
}
doAfterSwitch()
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
let stmt_count = cfg
.nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Statement))
.count();
// doAfterSwitch() must be present and reachable in the CFG.
assert!(stmt_count >= 5, "got {} statement nodes", stmt_count);
}
// ---- goto / labeled statements ----
#[test]
fn test_goto_statement_terminates_current_path() {
let source = r#"
package main
func test(x int) {
if x < 0 {
goto Done
}
doWork()
Done:
return
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
let condition_count = cfg
.nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Condition))
.count();
// if-condition + goto-as-branch = 2 Condition nodes
assert_eq!(condition_count, 2);
}
#[test]
fn test_labeled_statement_wrapping_loop_is_walked() {
// Regression: labeled_statement previously matched the catch-all
// branch, which added a single generic Statement node instead of
// descending into the labeled loop - completely dropping the
// loop's own control flow from the CFG.
let source = r#"
package main
func test() {
Loop:
for i := 0; i < 10; i++ {
if i == 5 {
break Loop
}
}
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
let condition_count = cfg
.nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Condition))
.count();
assert!(
condition_count >= 1,
"labeled for-loop's inner `if` must still be walked, got {} Condition nodes",
condition_count
);
}
#[test]
fn test_label_after_goto_does_not_panic() {
// Dead code (after goto) reaching a label must not panic when
// building the CFG.
let source = r#"
package main
func test(x int) {
goto Done
doUnreachable()
Done:
doWork()
}
"#;
let cfg = build_cfg(source);
cfg.validate().unwrap();
}
#[test]
fn test_is_switch_case_kind() {
assert!(is_switch_case_kind("expression_case"));
assert!(is_switch_case_kind("type_case"));
assert!(is_switch_case_kind("default_case"));
// select's case kind is distinct and must not be treated as a switch case.
assert!(!is_switch_case_kind("communication_case"));
assert!(!is_switch_case_kind("block"));
}
#[test]
fn test_visit_expression_statement_panic_call_marks_dead_code() {
// visit_panic (unlike visit_simple_statement) sets current_node to
// None, so statements after a bare panic() call must be elided from
// the CFG entirely rather than turned into unreachable nodes.
let panic_source = r#"
package main
func test() {
doA()
panic("boom")
doB()
doC()
}
"#;
let plain_source = r#"
package main
func test() {
doA()
doB()
doC()
}
"#;
let panic_cfg = build_cfg(panic_source);
let plain_cfg = build_cfg(plain_source);
panic_cfg.validate().unwrap();
plain_cfg.validate().unwrap();
assert_eq!(
panic_cfg.node_count(),
4, // entry, doA, panic, exit — doB/doC are dead code
"statements after panic() must not become CFG nodes"
);
assert_eq!(
plain_cfg.node_count(),
5, // entry, doA, doB, doC, exit — all reachable
"an ordinary call sequence keeps every statement reachable"
);
}
}