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
//! MSC12-C: Detect and remove code that has no effect or is never executed
//!
//! Detects several patterns of dead or no-effect code:
//! 1. Expression statements with no side effects (e.g., `a == b;`, `a + b;`, `5;`)
//! 2. Duplicate conditions in if/else-if chains
//! 3. Redundant sub-expressions in logical operators (`a == b && a == b`)
//! 4. Meaningless `continue` at end of loop body
//! 5. Empty control flow bodies (if/else/for/while with empty `{}`)
//! 6. Stray semicolons (`;` as a statement)
//! 7. Empty function bodies
use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use tree_sitter::Node;
pub struct Msc12C;
impl Msc12C {
pub fn new() -> Self {
Self
}
fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
match node.kind() {
"expression_statement" => {
self.check_no_effect_expression(node, source, violations);
}
"if_statement" => {
self.check_duplicate_conditions(node, source, violations);
self.check_empty_control_flow(node, source, violations);
}
"for_statement" | "while_statement" | "do_statement" => {
self.check_meaningless_continue(node, source, violations);
self.check_empty_control_flow(node, source, violations);
}
"function_definition" => {
self.check_empty_function(node, source, violations);
}
"compound_statement" => {
self.check_empty_standalone_block(node, source, violations);
}
"switch_statement" => {
self.check_empty_switch_case(node, source, violations);
}
"assignment_expression" => {
self.check_self_assignment(node, source, violations);
}
_ => {}
}
// Check for redundant logical sub-expressions in various contexts
if node.kind() == "binary_expression" {
self.check_redundant_logical(node, source, violations);
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_node(&child, source, violations);
}
}
}
/// Check for expression statements that have no side effects.
/// Patterns: `a == b;`, `a != b;`, `a + b;`, `5;`, `;`
fn check_no_effect_expression(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
// Get the expression child (skip the trailing `;`)
let expr = match node.child(0) {
Some(e) if e.kind() != ";" => e,
_ => {
// Stray semicolon: expression_statement with only ";"
// Skip if inside a for statement (empty for(;;) components are valid)
if let Some(parent) = node.parent() {
if parent.kind() == "for_statement" {
return;
}
}
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Stray semicolon has no effect.".to_string(),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Remove the unnecessary semicolon".to_string()),
..Default::default()
});
return;
}
};
// Skip macro invocations — they may have side effects we can't see
if expr.kind() == "call_expression" {
return;
}
// Cast-to-void is intentional suppression: (void)x;
if expr.kind() == "cast_expression" {
let type_text = expr
.child_by_field_name("type")
.map(|t| get_node_text(&t, source))
.unwrap_or_default();
if type_text.trim() == "void" {
return;
}
}
// Comma expressions — last sub-expression determines effect
if expr.kind() == "comma_expression" {
return;
}
match expr.kind() {
// Pure comparison used as a statement: a == b; a != b; a < b; etc.
"binary_expression" => {
if let Some(op_node) = expr.child_by_field_name("operator") {
let op = get_node_text(&op_node, source);
match op.trim() {
"==" | "!=" | "<" | ">" | "<=" | ">=" => {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Comparison '{}' used as a statement has no effect. \
Did you mean '=' (assignment)?",
op
),
file_path: String::new(),
line: expr.start_position().row + 1,
column: expr.start_position().column + 1,
suggestion: Some(
"Use '=' for assignment, or remove this statement".to_string(),
),
..Default::default()
});
}
// Arithmetic without assignment: a + b; a - b; a * b;
"+" | "-" | "*" | "/" | "%" => {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Arithmetic expression '{}' used as a statement has no effect. \
The result is discarded.",
get_node_text(&expr, source).trim()
),
file_path: String::new(),
line: expr.start_position().row + 1,
column: expr.start_position().column + 1,
suggestion: Some(
"Assign the result to a variable or remove this statement"
.to_string(),
),
..Default::default()
});
}
// Bitwise/shift without assignment: x >> 3; x & mask;
">>" | "<<" | "&" | "|" | "^" => {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Expression '{}' used as a statement has no effect. \
The result is discarded.",
get_node_text(&expr, source).trim()
),
file_path: String::new(),
line: expr.start_position().row + 1,
column: expr.start_position().column + 1,
suggestion: Some(
"Assign the result to a variable or remove this statement"
.to_string(),
),
..Default::default()
});
}
_ => {}
}
}
}
// Pointer dereference as statement with no assignment: *p++;
// tree-sitter parses `*p++` as pointer_expression(update_expression)
// The dereference result is discarded.
"pointer_expression" => {
// *p++ — the dereference is discarded, only p is incremented
// But (*p)++ is an update_expression at the top level — that has effect
let text = get_node_text(&expr, source);
let trimmed = text.trim();
if trimmed.starts_with('*') {
// Check if the inner expression is an update (p++) — dereference is wasted
if let Some(inner) = expr.child_by_field_name("argument") {
if inner.kind() == "update_expression" {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Dereference of post-incremented pointer has no effect. \
'*p++' dereferences then discards the value; \
only the pointer is advanced."
.to_string(),
file_path: String::new(),
line: expr.start_position().row + 1,
column: expr.start_position().column + 1,
suggestion: Some(
"Use '(*p)++' to increment the pointed-to value, \
or '++p' / 'p++' to just advance the pointer"
.to_string(),
),
..Default::default()
});
}
}
}
}
// Bare literal as statement: `5;`, `"hello";`, `'c';`
"number_literal" | "string_literal" | "char_literal" => {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Literal '{}' used as a statement has no effect.",
get_node_text(&expr, source).trim()
),
file_path: String::new(),
line: expr.start_position().row + 1,
column: expr.start_position().column + 1,
suggestion: Some("Remove this statement or use its value".to_string()),
..Default::default()
});
}
// Bare identifier or field expression as statement: `x;` or `s.field;`
"identifier" | "field_expression" => {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Expression '{}' used as a statement has no effect.",
get_node_text(&expr, source).trim()
),
file_path: String::new(),
line: expr.start_position().row + 1,
column: expr.start_position().column + 1,
suggestion: Some("Remove this statement or use its value".to_string()),
..Default::default()
});
}
_ => {}
}
}
/// Check for duplicate conditions in if/else-if chains.
/// `if (x == 1) ... else if (x == 1) ...` — second branch is dead code.
fn check_duplicate_conditions(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
// Collect all conditions in the if/else-if chain
let mut conditions: Vec<(String, Node)> = Vec::new();
let mut current = Some(*node);
while let Some(if_node) = current {
if if_node.kind() != "if_statement" {
break;
}
if let Some(cond) = if_node.child_by_field_name("condition") {
let cond_text = get_node_text(&cond, source);
let trimmed = cond_text.trim().to_string();
// Skip conditions with function calls — they may have side effects
// (e.g., getc() advances the stream, so identical text != identical result)
if self.contains_call(&cond) {
conditions.push((trimmed, cond));
current = if_node.child_by_field_name("alternative").and_then(|alt| {
if alt.kind() == "else_clause" {
(0..alt.child_count()).find_map(|i| {
let c = alt.child(i)?;
if c.kind() == "if_statement" {
Some(c)
} else {
None
}
})
} else if alt.kind() == "if_statement" {
Some(alt)
} else {
None
}
});
continue;
}
// Check for duplicate against earlier conditions
for (prev_text, _) in &conditions {
if *prev_text == trimmed {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Duplicate condition '{}' in if/else-if chain. \
The second branch is dead code.",
trimmed
),
file_path: String::new(),
line: cond.start_position().row + 1,
column: cond.start_position().column + 1,
suggestion: Some(
"Check for the correct condition or remove the dead branch"
.to_string(),
),
..Default::default()
});
break;
}
}
conditions.push((trimmed, cond));
}
// Follow else-if chain
current = if_node.child_by_field_name("alternative").and_then(|alt| {
if alt.kind() == "else_clause" {
// The if_statement inside the else clause
(0..alt.child_count()).find_map(|i| {
let c = alt.child(i)?;
if c.kind() == "if_statement" {
Some(c)
} else {
None
}
})
} else if alt.kind() == "if_statement" {
Some(alt)
} else {
None
}
});
}
}
/// Check for redundant sub-expressions in logical operators.
/// `a == b && a == b` — second operand is always the same as the first.
fn check_redundant_logical(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
if node.kind() != "binary_expression" {
return;
}
let op = match node.child_by_field_name("operator") {
Some(o) => get_node_text(&o, source),
None => return,
};
if op.trim() != "&&" && op.trim() != "||" {
return;
}
let left = match node.child_by_field_name("left") {
Some(l) => l,
None => return,
};
let right = match node.child_by_field_name("right") {
Some(r) => r,
None => return,
};
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
if left_text.trim() == right_text.trim() {
// Skip if the expression contains function calls (side effects)
if self.contains_call(&left) {
return;
}
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"Redundant sub-expression in '{}' operator. \
Both sides are identical: '{}'.",
op.trim(),
left_text.trim()
),
file_path: String::new(),
line: right.start_position().row + 1,
column: right.start_position().column + 1,
suggestion: Some("Remove the duplicate sub-expression".to_string()),
..Default::default()
});
}
}
/// Check for meaningless `continue` at the end of a loop body.
fn check_meaningless_continue(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
let body = match node.child_by_field_name("body") {
Some(b) if b.kind() == "compound_statement" => b,
_ => return,
};
// Find the last non-brace statement
let mut last_stmt = None;
for i in 0..body.child_count() {
if let Some(child) = body.child(i) {
if child.kind() != "{" && child.kind() != "}" && child.kind() != "comment" {
last_stmt = Some(child);
}
}
}
if let Some(stmt) = last_stmt {
if stmt.kind() == "continue_statement" {
let _ = source; // already used above
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Unconditional 'continue' at end of loop body has no effect. \
The loop would continue anyway."
.to_string(),
file_path: String::new(),
line: stmt.start_position().row + 1,
column: stmt.start_position().column + 1,
suggestion: Some("Remove the unnecessary 'continue' statement".to_string()),
..Default::default()
});
}
}
}
/// Check for empty control flow bodies: if/else/for/while with empty `{}`
fn check_empty_control_flow(
&self,
node: &Node,
_source: &str,
violations: &mut Vec<RuleViolation>,
) {
match node.kind() {
"if_statement" => {
// Check if the consequence (then-branch) is empty
if let Some(consequence) = node.child_by_field_name("consequence") {
if self.is_empty_body(&consequence) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Empty if statement body has no effect.".to_string(),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some(
"Add code to the if body or remove the empty branch".to_string(),
),
..Default::default()
});
}
}
// Check if the else clause has an empty body
if let Some(alt) = node.child_by_field_name("alternative") {
if alt.kind() == "else_clause" {
// Find the body inside the else clause (skip "else" keyword)
for i in 0..alt.child_count() {
if let Some(child) = alt.child(i) {
if child.kind() == "compound_statement"
&& self.is_empty_body(&child)
{
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Empty else statement body has no effect."
.to_string(),
file_path: String::new(),
line: alt.start_position().row + 1,
column: alt.start_position().column + 1,
suggestion: Some(
"Add code to the else body or remove the empty branch"
.to_string(),
),
..Default::default()
});
}
}
}
}
}
}
"for_statement" | "while_statement" | "do_statement" => {
if let Some(body) = node.child_by_field_name("body") {
if self.is_empty_body(&body) {
let kind = node.kind().replace("_statement", "");
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!("Empty {} loop body has no effect.", kind),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some(format!(
"Add code to the {} body or remove the empty loop",
kind
)),
..Default::default()
});
}
}
}
_ => {}
}
}
/// Check for function definitions with empty bodies
fn check_empty_function(
&self,
node: &Node,
_source: &str,
violations: &mut Vec<RuleViolation>,
) {
if let Some(body) = node.child_by_field_name("body") {
if self.is_empty_body(&body) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Empty function body has no effect.".to_string(),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Add code to the function or remove it if unused".to_string()),
..Default::default()
});
}
}
}
/// Check for standalone empty blocks `{ }` inside function bodies
fn check_empty_standalone_block(
&self,
node: &Node,
_source: &str,
violations: &mut Vec<RuleViolation>,
) {
// Only flag standalone blocks (parent is another compound_statement)
// Skip function bodies, if/else/for/while/do bodies (handled elsewhere)
if let Some(parent) = node.parent() {
let pk = parent.kind();
if pk != "compound_statement" && pk != "case_statement" && pk != "labeled_statement" {
return;
}
} else {
return;
}
if self.is_empty_body(node) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Empty code block has no effect.".to_string(),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Add code to the block or remove it".to_string()),
..Default::default()
});
}
}
/// Check for switch cases that only contain `break` (no real code)
fn check_empty_switch_case(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
// Find all case_statement children inside the switch body
if let Some(body) = node.child_by_field_name("body") {
for i in 0..body.child_count() {
if let Some(case_node) = body.child(i) {
if case_node.kind() == "case_statement" {
// Check if the case only has: "case" expr ":" break_statement
let mut has_real_code = false;
for j in 0..case_node.child_count() {
if let Some(child) = case_node.child(j) {
let kind = child.kind();
if kind != "case"
&& kind != ":"
&& kind != "break_statement"
&& kind != "comment"
&& kind != "{"
&& kind != "}"
&& !kind.starts_with("number_literal")
&& !kind.starts_with("char_literal")
{
// Skip the case value expression
if child.prev_named_sibling().is_none()
|| child.prev_named_sibling().map(|s| s.kind())
== Some("case")
{
continue;
}
has_real_code = true;
break;
}
}
}
if !has_real_code {
let _ = source;
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: "Empty case statement has no effect.".to_string(),
file_path: String::new(),
line: case_node.start_position().row + 1,
column: case_node.start_position().column + 1,
suggestion: Some("Add code to the case or remove it".to_string()),
..Default::default()
});
}
}
}
}
}
}
/// Check for self-assignment: `x = x;`
fn check_self_assignment(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
let left = match node.child_by_field_name("left") {
Some(l) => l,
None => return,
};
let right = match node.child_by_field_name("right") {
Some(r) => r,
None => return,
};
// Only check plain `=` assignment, not compound (+=, etc.)
if let Some(op) = node.child_by_field_name("operator") {
if get_node_text(&op, source) != "=" {
return;
}
}
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
if left_text.trim() == right_text.trim() && !left_text.trim().is_empty() {
// Skip if contains function calls (side effects in getter)
if self.contains_call(&right) {
return;
}
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!("Self-assignment '{}' has no effect.", left_text.trim()),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some(
"Remove the self-assignment or assign a different value".to_string(),
),
..Default::default()
});
}
}
/// Returns true if a compound_statement contains no meaningful statements
fn is_empty_body(&self, node: &Node) -> bool {
if node.kind() != "compound_statement" {
return false;
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
let kind = child.kind();
if kind != "{" && kind != "}" && kind != "comment" {
return false;
}
}
}
true
}
/// Returns true if the node or any descendant is a call_expression.
fn contains_call(&self, node: &Node) -> bool {
if node.kind() == "call_expression" {
return true;
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if self.contains_call(&child) {
return true;
}
}
}
false
}
}
impl CertRule for Msc12C {
fn rule_id(&self) -> &'static str {
"MSC12-C"
}
fn description(&self) -> &'static str {
"Detect and remove code that has no effect or is never executed"
}
fn severity(&self) -> Severity {
Severity::Low
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"MSC12-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.check_node(node, source, &mut violations);
violations
}
}