Skip to content

Commit 743b707

Browse files
committed
Rule 14.3: Support conditonal expressions
1 parent 235eede commit 743b707

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

c/misra/src/rules/RULE-14-3/ControllingExprInvariant.ql

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,23 @@ where
5757
)
5858
) and
5959
message = "Controlling expression in switch statement has invariant value."
60+
or
61+
exists(ConditionalExpr conditional |
62+
conditional.getCondition() = expr and
63+
(
64+
conditionAlwaysFalse(expr) or
65+
conditionAlwaysTrue(expr)
66+
)
67+
) and
68+
message = "Controlling expression in conditional statement has invariant value."
6069
) and
6170
// Exclude cases where the controlling expressions is affected by a macro, because they can appear
6271
// invariant in a particular invocation, but be variant between invocations.
63-
not expr.isAffectedByMacro()
72+
not (
73+
expr.isAffectedByMacro() and
74+
// Permit boolean literal macros
75+
not expr instanceof BooleanLiteral
76+
) and
77+
// Exclude template variables, because they can be instantiated with different values.
78+
not expr = any(TemplateVariable tv).getAnInstantiation().getAnAccess()
6479
select expr, message

c/misra/test/rules/RULE-14-3/ControllingExprInvariant.expected

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@
33
| test.c:16:9:16:13 | ... > ... | Controlling expression in if statement has invariant value. |
44
| test.c:20:20:20:24 | ... < ... | Controlling expression in loop statement has invariant value. |
55
| test.c:27:10:27:14 | ... < ... | Controlling expression in loop statement has invariant value. |
6+
| test.c:37:3:37:6 | 1 | Controlling expression in conditional statement has invariant value. |
7+
| test.c:38:3:38:3 | 1 | Controlling expression in conditional statement has invariant value. |

c/misra/test/rules/RULE-14-3/test.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,10 @@ void f3() {
3131
void f4() {
3232
do {
3333
} while (0u == 1u); // COMPLIANT - by exception 2
34+
}
35+
36+
void f5(bool b1) {
37+
true ? 1 : 2; // NON_COMPLIANT
38+
1 ? 1 : 2; // NON_COMPLIANT
39+
b1 ? 1 : 2; // COMPLIANT
3440
}

0 commit comments

Comments
 (0)