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
// CERT C Rule: DCL08-C
// Properly encode relationships in constant definitions
//
// This rule checks that:
// 1. When constants have mathematical relationships, they should be encoded
// (e.g., OUT_STR_LEN = IN_STR_LEN + 2 instead of separate literals)
// 2. Constants should not encode false or impermanent relationships
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 Dcl08C;
impl CertRule for Dcl08C {
fn rule_id(&self) -> &'static str {
"DCL08-C"
}
fn description(&self) -> &'static str {
"Properly encode relationships in constant definitions"
}
fn severity(&self) -> Severity {
Severity::Low
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"DCL08-C"
}
fn check(&self, root_node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
// First pass: collect all enum constants across the entire file
let mut all_enum_constants = std::collections::HashMap::new();
self.collect_all_enum_constants(root_node, source, &mut all_enum_constants);
// Second pass: check each enum for violations
let mut cursor = root_node.walk();
self.check_node(
root_node,
source,
&mut violations,
&mut cursor,
&all_enum_constants,
);
violations
}
}
impl Dcl08C {
/// Collect all enum constant names across the entire file
fn collect_all_enum_constants(
&self,
node: &Node,
source: &str,
constants: &mut std::collections::HashMap<String, usize>,
) {
if node.kind() == "enum_specifier" {
if let Some(body) = node.child_by_field_name("body") {
let mut cursor = body.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "enumerator" {
if let Some(name_node) = child.child_by_field_name("name") {
let name = get_node_text(&name_node, source);
let line = name_node.start_position().row + 1;
constants.insert(name.to_string(), line);
}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
}
// Recurse into children
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
self.collect_all_enum_constants(&child, source, constants);
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn check_node(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
cursor: &mut tree_sitter::TreeCursor,
all_constants: &std::collections::HashMap<String, usize>,
) {
// Check if this is an enum declaration
if node.kind() == "enum_specifier" {
self.check_enum_specifier(node, source, violations, all_constants);
}
// Recursively check child nodes
if cursor.goto_first_child() {
loop {
let child = cursor.node();
self.check_node(&child, source, violations, cursor, all_constants);
if !cursor.goto_next_sibling() {
break;
}
}
cursor.goto_parent();
}
}
fn check_enum_specifier(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
all_constants: &std::collections::HashMap<String, usize>,
) {
// Get the enum body
let body = match node.child_by_field_name("body") {
Some(b) => b,
None => return,
};
// Collect all enumerator definitions
let mut enumerators = Vec::new();
let mut cursor = body.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "enumerator" {
enumerators.push(child);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
// Need at least 1 enumerator to check
if enumerators.is_empty() {
return;
}
// Check for potential missing relationships (same enum, literal values only)
self.check_missing_relationships(&enumerators, source, violations, all_constants);
}
fn check_missing_relationships(
&self,
enumerators: &[Node],
source: &str,
violations: &mut Vec<RuleViolation>,
all_constants: &std::collections::HashMap<String, usize>,
) {
// Collect enumerator info for THIS enum: name and value (if literal)
let mut enum_values = Vec::new();
let mut this_enum_names = std::collections::HashSet::new();
for enumerator in enumerators {
if let Some(name_node) = enumerator.child_by_field_name("name") {
let name = get_node_text(&name_node, source);
this_enum_names.insert(name.to_string());
// Check if there's a value
if let Some(value_node) = enumerator.child_by_field_name("value") {
let value_text = get_node_text(&value_node, source);
// Check if it's a simple numeric literal
if let Ok(value) = value_text.parse::<i64>() {
enum_values.push((name, value, name_node.start_position()));
} else if value_text.contains('+') || value_text.contains('-') {
// This is a reference with arithmetic
// Check if it references a constant from THIS enum (that's OK)
// or a constant from a DIFFERENT scope (that's potentially misleading)
let references_other_enum = all_constants.iter().any(|(enum_name, _)| {
value_text.contains(enum_name.as_str())
&& !this_enum_names.contains(enum_name)
});
if references_other_enum {
// References a constant from a different enum - potentially misleading
let position = name_node.start_position();
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
message: format!(
"Constant '{}' encodes a potentially misleading relationship: {}. \
If no permanent relationship exists, define constants independently.",
name, value_text
),
severity: self.severity(),
line: position.row + 1,
column: position.column + 1,
file_path: String::new(),
suggestion: Some(format!(
"Either define '{}' with its literal value or ensure the relationship with {} is permanent and accurate",
name, value_text
)),
requires_manual_review: Some(true),
});
}
}
}
}
}
// If all enumerators have explicit values AND there are 3 or more members, this is a
// protocol/register/command enum — the programmer deliberately assigned every value
// (e.g. wire-format spec, CAN command IDs). There is no implicit relationship to
// encode; skip the pair-offset check. 2-member enums like {IN_STR_LEN=18, OUT_STR_LEN=20}
// are the canonical DCL08-C example and are still checked.
if enum_values.len() == enumerators.len() && enumerators.len() >= 3 {
return;
}
// If all explicit values form a consecutive integer sequence (0,1,2,... or 1,2,3,...),
// this is just making enum numbering explicit — not an encoded relationship.
// Common patterns: {SUCCESS=0, FAIL=1}, {CHARGE=1, DISCHARGE=2}, {A=0, B=1, C=2}.
if enum_values.len() >= 2 {
let mut sorted_vals: Vec<i64> = enum_values.iter().map(|(_, v, _)| *v).collect();
sorted_vals.sort();
let is_consecutive = sorted_vals.windows(2).all(|w| w[1] == w[0] + 1);
if is_consecutive {
return;
}
}
// Check if any pair of values might have a relationship
// For noncompliant_1: IN_STR_LEN=18, OUT_STR_LEN=20 (20 = 18+2)
if enum_values.len() >= 2 {
// Check all pairs for simple arithmetic relationships
for i in 0..enum_values.len() {
for j in (i + 1)..enum_values.len() {
let (name1, val1, _) = &enum_values[i];
let (name2, val2, pos2) = &enum_values[j];
// Check if val2 could be expressed as val1 + offset
if val2 > val1 {
let offset = val2 - val1;
// Flag small offsets (like +2, +3) as potential relationships
if offset > 0 && offset <= 10 {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
message: format!(
"Constants '{}' and '{}' may have a relationship ({} = {} + {}). \
Consider encoding: {} = {} + {}",
name1, name2, val2, val1, offset, name2, name1, offset
),
severity: self.severity(),
line: pos2.row + 1,
column: pos2.column + 1,
file_path: String::new(),
suggestion: Some(format!(
"enum {{ {} = {}, {} = {} + {} }};",
name1, val1, name2, name1, offset
)),
requires_manual_review: Some(true),
});
}
}
}
}
}
}
#[allow(dead_code)]
fn contains_reference_with_arithmetic(
&self,
value_text: &str,
known_values: &[(&str, i64, tree_sitter::Point)],
) -> bool {
// Check if the value contains a reference to another enum constant plus arithmetic
for (name, _, _) in known_values {
if value_text.contains(name) && (value_text.contains('+') || value_text.contains('-')) {
return true;
}
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rule_id() {
let rule = Dcl08C;
assert_eq!(rule.rule_id(), "DCL08-C");
}
#[test]
fn test_severity() {
let rule = Dcl08C;
assert_eq!(rule.severity(), Severity::Low);
}
}