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
use std::{path::Path, sync::LazyLock};
use gobject_ast::model::{Include, PreprocessorDirective, TopLevelItem};
use crate::{
ast_context::AstContext,
config::Config,
rules::{ConfigOption, Fix, Rule, Violation},
};
pub struct IncludeOrder;
impl Rule for IncludeOrder {
fn name(&self) -> &'static str {
"include_order"
}
fn description(&self) -> &'static str {
"Enforce consistent include ordering: config header (configurable), associated header, standard C/POSIX headers, system headers, project headers"
}
fn category(&self) -> crate::rules::Category {
crate::rules::Category::Style
}
fn fixable(&self) -> bool {
true
}
fn config_options(&self) -> &'static [ConfigOption] {
static OPTIONS: LazyLock<Vec<ConfigOption>> = LazyLock::new(|| {
vec![ConfigOption {
name: "config_header",
option_type: "string",
default_value: "\"config.h\"",
example_value: "\"myproject-config.h\"",
description: "Name of the config header file",
}]
});
&OPTIONS
}
fn check_all(
&self,
ast_context: &AstContext,
config: &Config,
violations: &mut Vec<Violation>,
) {
let config_header = config
.get_rule_config(self.name())
.and_then(|rc| rc.options.get("config_header"))
.and_then(|v| v.as_str())
.unwrap_or("config.h");
for (path, file) in ast_context.iter_all_files() {
self.check_include_groups(&file.top_level_items, path, config_header, violations);
}
}
}
impl IncludeOrder {
/// Check include ordering at each level of the tree structure
/// All includes at the same level (outside conditionals) are sorted
/// together
fn check_include_groups(
&self,
items: &[TopLevelItem],
file_path: &Path,
config_header: &str,
violations: &mut Vec<Violation>,
) {
// Collect all top-level includes
let mut top_level_includes = Vec::new();
for item in items {
match item {
TopLevelItem::Preprocessor(PreprocessorDirective::Include {
path,
is_system,
location,
}) => {
top_level_includes.push(Include {
path: path.clone(),
is_system: *is_system,
location: location.clone(),
});
}
TopLevelItem::Preprocessor(PreprocessorDirective::Conditional { body, .. }) => {
// Recursively check includes within the conditional block
self.check_include_groups(body, file_path, config_header, violations);
}
_ => {}
}
}
// Check and fix all top-level includes as one group
if !top_level_includes.is_empty() {
self.check_and_fix_group_scattered(
&top_level_includes,
file_path,
config_header,
violations,
);
}
}
/// Check and fix scattered includes (may be separated by #ifdef blocks)
/// All includes should be sorted and moved to be consecutive at the start
fn check_and_fix_group_scattered(
&self,
includes: &[Include],
file_path: &Path,
config_header: &str,
violations: &mut Vec<Violation>,
) {
if includes.is_empty() {
return;
}
// Step 1: Compute expected vs actual order
let expected_order = self.compute_expected_order(file_path, includes, config_header);
let current_order: Vec<_> = includes.iter().map(|inc| &inc.path).collect();
if expected_order == current_order {
return; // Already in correct order
}
// Step 2: Gather information about the include block
let first_inc = &includes[0];
let last_inc = includes
.iter()
.max_by_key(|inc| inc.location.end_byte)
.unwrap();
// Step 3: Determine spacing after the last include (to preserve it)
// The last include's end_byte points right after its newline
let trailing_newlines = last_inc.location.count_trailing_newlines();
// Step 4: Generate sorted includes with preserved trailing spacing
let sorted_text = self.generate_sorted_includes_text(
&expected_order,
includes,
file_path,
config_header,
trailing_newlines,
);
// Step 5: Build fixes
let mut fixes = Vec::new();
// Replace first include with all sorted includes (including trailing newlines)
// Also consume any blank lines immediately after the first include
let first_end = first_inc.location.end_byte + first_inc.location.count_trailing_newlines();
fixes.push(Fix::new(
first_inc.location.start_byte,
first_end,
sorted_text,
));
// Delete all other includes
// Consume any blank lines immediately after each deleted include
for inc in includes.iter().skip(1) {
let end = inc.location.end_byte + inc.location.count_trailing_newlines();
fixes.push(Fix::delete(inc.location.start_byte, end));
}
violations.push(self.violation_with_fixes(
file_path,
first_inc.location.line,
1,
format!(
"Includes are not in the correct order. Expected: {} (if present), associated header, standard C headers, system headers (<>), project headers (\"\") (all alphabetically sorted within each group, blank line between groups)",
config_header
),
fixes,
));
}
/// Generate the text for sorted includes with proper grouping
fn generate_sorted_includes_text(
&self,
expected_order: &[&str],
includes: &[Include],
file_path: &Path,
config_header: &str,
trailing_newlines: usize,
) -> String {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IncludeGroup {
Config,
Associated,
StandardC,
System,
Project,
}
let grouped_includes: Vec<(&&str, IncludeGroup)> = expected_order
.iter()
.map(|path| {
let group = if *path == config_header {
IncludeGroup::Config
} else if self.is_associated_header(path, file_path) {
IncludeGroup::Associated
} else {
let original = includes.iter().find(|inc| inc.path == *path).unwrap();
if original.is_system && self.is_standard_c_header(path) {
IncludeGroup::StandardC
} else if original.is_system {
IncludeGroup::System
} else {
IncludeGroup::Project
}
};
(path, group)
})
.collect();
let mut result = String::new();
let mut last_group: Option<IncludeGroup> = None;
for (path, group) in grouped_includes {
// Add blank line between groups
if let Some(prev_group) = last_group
&& prev_group != group
{
result.push('\n');
}
last_group = Some(group);
let original = includes.iter().find(|inc| inc.path == *path).unwrap();
let bracket = if original.is_system {
("<", ">")
} else {
("\"", "\"")
};
result.push_str(&format!("#include {}{}{}\n", bracket.0, path, bracket.1));
}
// Add trailing newlines to preserve original spacing
for _ in 0..trailing_newlines {
result.push('\n');
}
result
}
/// Compute the expected order of includes
fn compute_expected_order<'a>(
&self,
file_path: &Path,
includes: &'a [Include],
config_header: &str,
) -> Vec<&'a str> {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum IncludeGroup {
Config = 0, // config.h must be first
Associated = 1, // foo.c -> foo.h
StandardC = 2, // <stdio.h>, <math.h>, etc.
System = 3, // <glib.h>, <gtk/gtk.h>, etc.
Project = 4, // "..."
}
let mut grouped: Vec<(&Include, IncludeGroup)> = includes
.iter()
.map(|inc| {
let group = if inc.path == config_header {
IncludeGroup::Config
} else if self.is_associated_header(&inc.path, file_path) {
IncludeGroup::Associated
} else if inc.is_system && self.is_standard_c_header(&inc.path) {
IncludeGroup::StandardC
} else if inc.is_system {
IncludeGroup::System
} else {
IncludeGroup::Project
};
(inc, group)
})
.collect();
// Sort by group first, then alphabetically within each group
grouped.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.path.cmp(&b.0.path)));
grouped.iter().map(|(inc, _)| inc.path.as_str()).collect()
}
/// Check if a header is a standard C or POSIX header
fn is_standard_c_header(&self, path: &str) -> bool {
// Standard C library headers
if matches!(
path,
"assert.h"
| "complex.h"
| "ctype.h"
| "errno.h"
| "fenv.h"
| "float.h"
| "inttypes.h"
| "iso646.h"
| "limits.h"
| "locale.h"
| "math.h"
| "setjmp.h"
| "signal.h"
| "stdalign.h"
| "stdarg.h"
| "stdatomic.h"
| "stdbool.h"
| "stddef.h"
| "stdint.h"
| "stdio.h"
| "stdlib.h"
| "stdnoreturn.h"
| "string.h"
| "tgmath.h"
| "threads.h"
| "time.h"
| "uchar.h"
| "wchar.h"
| "wctype.h"
) {
return true;
}
// POSIX headers
if matches!(
path,
"aio.h"
| "arpa/inet.h"
| "dirent.h"
| "dlfcn.h"
| "fcntl.h"
| "fmtmsg.h"
| "fnmatch.h"
| "ftw.h"
| "glob.h"
| "grp.h"
| "iconv.h"
| "langinfo.h"
| "libgen.h"
| "monetary.h"
| "mqueue.h"
| "ndbm.h"
| "net/if.h"
| "netdb.h"
| "netinet/in.h"
| "netinet/tcp.h"
| "nl_types.h"
| "poll.h"
| "pthread.h"
| "pwd.h"
| "regex.h"
| "sched.h"
| "search.h"
| "semaphore.h"
| "spawn.h"
| "strings.h"
| "stropts.h"
| "sys/ipc.h"
| "sys/mman.h"
| "sys/msg.h"
| "sys/resource.h"
| "sys/select.h"
| "sys/sem.h"
| "sys/shm.h"
| "sys/socket.h"
| "sys/stat.h"
| "sys/statvfs.h"
| "sys/time.h"
| "sys/times.h"
| "sys/types.h"
| "sys/uio.h"
| "sys/un.h"
| "sys/utsname.h"
| "sys/wait.h"
| "sysexits.h"
| "syslog.h"
| "tar.h"
| "termios.h"
| "trace.h"
| "ulimit.h"
| "unistd.h"
| "utime.h"
| "utmpx.h"
| "wordexp.h"
) {
return true;
}
false
}
/// Get all possible associated headers for a C file
/// Returns the basenames to check (without directory prefix)
/// foo.c -> ["foo.h", "foo-private.h", "fooprivate.h"]
fn get_associated_header_basenames(&self, file_path: &Path) -> Vec<String> {
if file_path.extension() != Some(std::ffi::OsStr::new("c")) {
return Vec::new();
}
let Some(stem) = file_path.file_stem().and_then(|s| s.to_str()) else {
return Vec::new();
};
vec![
format!("{}.h", stem), // foo.c -> foo.h
format!("{}-private.h", stem), // foo.c -> foo-private.h
format!("{}private.h", stem), // foo.c -> fooprivate.h
]
}
/// Check if an include path is an associated header for the given file
/// Checks the basename of the include, so "meta-test/meta-test-monitor.h"
/// matches for "meta-test-monitor.c"
fn is_associated_header(&self, include_path: &str, file_path: &Path) -> bool {
let basenames = self.get_associated_header_basenames(file_path);
// Extract basename from include path (part after last '/')
let include_basename = include_path.rsplit('/').next().unwrap_or(include_path);
basenames.iter().any(|pattern| pattern == include_basename)
}
}