gobject-linter 0.1.2

A fast tree-sitter-based linter for GObject/C code
Documentation
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
use std::{collections::HashMap, fmt, fs, path::Path};

use anyhow::{Context, Result};
use clap::ValueEnum;
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::{Deserialize, de};

use crate::{for_each_rule, rules::*};

#[derive(Default, Debug, Clone, Copy, ValueEnum, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum OutputFormat {
    /// Human-readable colorized output (default)
    #[default]
    Text,
    /// JSON format
    Json,
    /// SARIF JSON format for GitHub Code Scanning, VS Code, etc.
    Sarif,
    /// GCC-compatible format for Emacs, Vim, and other tools
    Gcc,
    /// Gitlab specific Code Quality Report
    GitlabCodequality,
}

/// Parse a GLib version string like "2.76" into (major, minor)
pub fn parse_glib_version(version: &str) -> Option<(u32, u32)> {
    let parts: Vec<&str> = version.split('.').collect();
    if parts.len() != 2 {
        return None;
    }
    let major = parts[0].parse::<u32>().ok()?;
    let minor = parts[1].parse::<u32>().ok()?;
    Some((major, minor))
}

/// Deserialize GLib version from string to (major, minor) tuple
fn deserialize_glib_version<'de, D>(deserializer: D) -> Result<Option<(u32, u32)>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let version_str: Option<String> = Option::deserialize(deserializer)?;

    match version_str {
        Some(s) => parse_glib_version(&s).map(Some).ok_or_else(|| {
            de::Error::custom(format!(
                "Invalid GLib version format: '{}'. Expected format: 'major.minor' (e.g., '2.76')",
                s
            ))
        }),
        None => Ok(None),
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Style {
    #[serde(default = "default_true")]
    pub space_before_paren: bool,
}

impl Default for Style {
    fn default() -> Self {
        Self {
            space_before_paren: true,
        }
    }
}

impl Style {
    pub fn format_call(&self, func: &str, args: &[&str]) -> String {
        let sep = if self.space_before_paren { " (" } else { "(" };
        let mut s =
            String::with_capacity(func.len() + 2 + args.iter().map(|a| a.len() + 2).sum::<usize>());
        s.push_str(func);
        s.push_str(sep);
        for (i, arg) in args.iter().enumerate() {
            if i > 0 {
                s.push_str(", ");
            }
            s.push_str(arg);
        }
        s.push(')');
        s
    }

    pub fn format_call_stmt(&self, func: &str, args: &[&str]) -> String {
        let mut s = self.format_call(func, args);
        s.push(';');
        s
    }

    pub fn format_addr_call(&self, func: &str, var: &str, extra_args: &[&str]) -> String {
        let sep = if self.space_before_paren { " (" } else { "(" };
        let mut s = String::with_capacity(
            func.len() + 4 + var.len() + extra_args.iter().map(|a| a.len() + 2).sum::<usize>(),
        );
        s.push_str(func);
        s.push_str(sep);
        s.push('&');
        s.push_str(var);
        for arg in extra_args {
            s.push_str(", ");
            s.push_str(arg);
        }
        s.push(')');
        s
    }

    pub fn format_addr_call_stmt(&self, func: &str, var: &str, extra_args: &[&str]) -> String {
        let mut s = self.format_addr_call(func, var, extra_args);
        s.push(';');
        s
    }
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub style: Style,

    #[serde(default)]
    pub rules: RulesConfig,

    #[serde(default)]
    pub ignore: Vec<String>,

    /// Minimum supported GLib version as (major, minor)
    /// Rules requiring newer GLib versions will be automatically disabled
    #[serde(default, deserialize_with = "deserialize_glib_version")]
    pub min_glib_version: Option<(u32, u32)>,

    /// Target MSVC-compatible code
    #[serde(default)]
    pub msvc_compatible: bool,

    /// Output format
    pub format: Option<OutputFormat>,

    /// Editor URL format for clickable links
    /// Available placeholders: {path}, {line}, {column}
    /// Examples:
    ///   VSCode: "vscode://file{path}:{line}:{column}"
    ///   IntelliJ: "idea://open?file={path}&line={line}"
    ///   Sublime: "subl://open?url=file://{path}&line={line}&column={column}"
    pub editor_url: Option<String>,

    /// Build directory for meson introspection (used for dead code analysis)
    /// If not specified, will search for common build directories (build/,
    /// builddir/, _build/)
    pub build_dir: Option<String>,

    /// Default severity level for all non-opt-in rules.
    /// Opt-in rules always default to "ignore" regardless of this setting.
    /// Per-rule `level` settings override this.
    pub default_level: Option<RuleLevel>,
}

/// Rule severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RuleLevel {
    /// Report as error and exit with failure code
    Error,
    /// Report as warning but don't fail
    Warn,
    /// Disabled/ignored
    Ignore,
}

impl RuleLevel {
    pub fn is_enabled(&self) -> bool {
        !matches!(self, Self::Ignore)
    }

    pub fn is_error(&self) -> bool {
        matches!(self, Self::Error)
    }

    pub fn is_warn(&self) -> bool {
        matches!(self, Self::Warn)
    }
}

/// Per-rule configuration
#[derive(Debug, Default, Clone)]
pub struct RuleConfig {
    /// Explicitly configured level, or None if the user never set it.
    /// None is resolved at runtime: opt-in rules default to Ignore, others to
    /// Warn.
    pub level: Option<RuleLevel>,
    pub ignore: Vec<String>,
    /// Rule-specific options (e.g., config_header for include_order)
    pub options: HashMap<String, toml::Value>,
}

impl<'de> Deserialize<'de> for RuleConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct RuleConfigVisitor;

        impl<'de> serde::de::Visitor<'de> for RuleConfigVisitor {
            type Value = RuleConfig;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter
                    .write_str("a boolean, \"error\"/\"warn\"/\"ignore\", or a RuleConfig struct")
            }

            fn visit_bool<E>(self, value: bool) -> Result<RuleConfig, E>
            where
                E: de::Error,
            {
                Ok(RuleConfig {
                    level: Some(if value {
                        RuleLevel::Error
                    } else {
                        RuleLevel::Ignore
                    }),
                    ignore: Vec::new(),
                    options: HashMap::new(),
                })
            }

            fn visit_str<E>(self, value: &str) -> Result<RuleConfig, E>
            where
                E: de::Error,
            {
                let level = match value {
                    "error" => RuleLevel::Error,
                    "warn" => RuleLevel::Warn,
                    "ignore" => RuleLevel::Ignore,
                    _ => {
                        return Err(de::Error::unknown_variant(
                            value,
                            &["error", "warn", "ignore"],
                        ));
                    }
                };
                Ok(RuleConfig {
                    level: Some(level),
                    ignore: Vec::new(),
                    options: HashMap::new(),
                })
            }

            fn visit_map<M>(self, mut map: M) -> Result<RuleConfig, M::Error>
            where
                M: serde::de::MapAccess<'de>,
            {
                let mut level: Option<RuleLevel> = None;
                let mut ignore = None;
                let mut options = HashMap::new();

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "level" => {
                            if level.is_some() {
                                return Err(de::Error::duplicate_field("level"));
                            }
                            let level_str: String = map.next_value()?;
                            level = Some(match level_str.as_str() {
                                "error" => RuleLevel::Error,
                                "warn" => RuleLevel::Warn,
                                "ignore" => RuleLevel::Ignore,
                                _ => {
                                    return Err(de::Error::unknown_variant(
                                        &level_str,
                                        &["error", "warn", "ignore"],
                                    ));
                                }
                            });
                        }
                        "ignore" => {
                            if ignore.is_some() {
                                return Err(de::Error::duplicate_field("ignore"));
                            }
                            ignore = Some(map.next_value()?);
                        }
                        _ => {
                            // Capture unknown fields as rule-specific options
                            let value: toml::Value = map.next_value()?;
                            options.insert(key, value);
                        }
                    }
                }

                Ok(RuleConfig {
                    level, // None when not set
                    ignore: ignore.unwrap_or_default(),
                    options,
                })
            }
        }

        deserializer.deserialize_any(RuleConfigVisitor)
    }
}

macro_rules! impl_rules_config {
    ($(($config_field:ident, $rule_type:ident)),* $(,)?) => {
        #[derive(Debug, Clone, Deserialize, Default)]
        pub struct RulesConfig {
            $(
                #[serde(default)]
                pub $config_field: RuleConfig,
            )*
        }
    };
}

for_each_rule!(impl_rules_config);

impl Config {
    pub fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            // Return default config if file doesn't exist
            return Ok(Self::default());
        }

        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;

        let config: Self = toml::from_str(&content)
            .with_context(|| format!("Failed to parse config file: {}", path.display()))?;

        Ok(config)
    }

    pub fn build_ignore_matcher(&self) -> Result<GlobSet> {
        let mut builder = GlobSetBuilder::new();

        for pattern in &self.ignore {
            let glob = Glob::new(pattern)
                .with_context(|| format!("Invalid ignore pattern: {}", pattern))?;
            builder.add(glob);
        }

        builder.build().context("Failed to build ignore matcher")
    }

    /// Build an ignore matcher for a specific rule, combining global and
    /// per-rule ignores
    pub fn build_rule_ignore_matcher(&self, rule_config: &RuleConfig) -> Result<GlobSet> {
        let mut builder = GlobSetBuilder::new();

        // Add global ignore patterns
        for pattern in &self.ignore {
            let glob = Glob::new(pattern)
                .with_context(|| format!("Invalid ignore pattern: {}", pattern))?;
            builder.add(glob);
        }

        // Add per-rule ignore patterns
        for pattern in &rule_config.ignore {
            let glob = Glob::new(pattern)
                .with_context(|| format!("Invalid ignore pattern: {}", pattern))?;
            builder.add(glob);
        }

        builder.build().context("Failed to build ignore matcher")
    }

    /// Get reference to a rule config by field name
    pub fn get_rule_config(&self, field_name: &str) -> Option<&RuleConfig> {
        macro_rules! impl_get_rule_config {
            ($(($config_field:ident, $rule_type:ident)),* $(,)?) => {
                match field_name {
                    $(
                        stringify!($config_field) => Some(&self.rules.$config_field),
                    )*
                    _ => None,
                }
            };
        }

        for_each_rule!(impl_get_rule_config)
    }

    /// Get mutable reference to a rule config by field name
    pub fn get_rule_config_mut(&mut self, field_name: &str) -> Option<&mut RuleConfig> {
        macro_rules! impl_get_rule_config_mut {
            ($(($config_field:ident, $rule_type:ident)),* $(,)?) => {
                match field_name {
                    $(
                        stringify!($config_field) => Some(&mut self.rules.$config_field),
                    )*
                    _ => None,
                }
            };
        }

        for_each_rule!(impl_get_rule_config_mut)
    }

    pub fn get_string_list(&self, rule_name: &str, key: &str) -> Vec<String> {
        self.get_rule_config(rule_name)
            .and_then(|rc| rc.options.get(key))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Enable only specific rules, disabling all others
    pub fn enable_only_rules(&mut self, rule_names: &[String]) -> Result<()> {
        // First, validate that all provided rule names exist
        let valid_rules: Vec<&str> = {
            macro_rules! collect_rule_names {
                ($(($config_field:ident, $rule_type:ident)),* $(,)?) => {
                    vec![$(stringify!($config_field)),*]
                };
            }
            for_each_rule!(collect_rule_names)
        };

        for rule_name in rule_names {
            if !valid_rules.contains(&rule_name.as_str()) {
                anyhow::bail!("Unknown rule: {}", rule_name);
            }
        }

        // Now enable only the specified rules
        macro_rules! impl_enable_only_rules {
            ($(($config_field:ident, $rule_type:ident)),* $(,)?) => {
                {
                    $(
                        self.rules.$config_field.level = Some(if rule_names.iter().any(|r| r == stringify!($config_field)) {
                            RuleLevel::Error
                        } else {
                            RuleLevel::Ignore
                        });
                    )*
                }
            };
        }

        for_each_rule!(impl_enable_only_rules);
        Ok(())
    }

    /// Disable specific rules (all others remain enabled according to config)
    pub fn disable_rules(&mut self, rule_names: &[String]) -> Result<()> {
        // First, validate that all provided rule names exist
        let valid_rules: Vec<&str> = {
            macro_rules! collect_rule_names {
                ($(($config_field:ident, $rule_type:ident)),* $(,)?) => {
                    vec![$(stringify!($config_field)),*]
                };
            }
            for_each_rule!(collect_rule_names)
        };

        for rule_name in rule_names {
            if !valid_rules.contains(&rule_name.as_str()) {
                anyhow::bail!("Unknown rule: {}", rule_name);
            }
        }

        // Now disable the specified rules
        macro_rules! impl_disable_rules {
            ($(($config_field:ident, $rule_type:ident)),* $(,)?) => {
                {
                    $(
                        if rule_names.iter().any(|r| r == stringify!($config_field)) {
                            self.rules.$config_field.level = Some(RuleLevel::Ignore);
                        }
                    )*
                }
            };
        }

        for_each_rule!(impl_disable_rules);
        Ok(())
    }

    /// Filter rules by category, disabling all others
    pub fn filter_by_category(&mut self, category: Category) -> Result<()> {
        macro_rules! impl_filter_by_category {
            ($(($config_field:ident, $rule_type:ident)),* $(,)?) => {
                {
                    $(
                        self.rules.$config_field.level = Some(if $rule_type.category() == category {
                            RuleLevel::Error
                        } else {
                            RuleLevel::Ignore
                        });
                    )*
                }
            };
        }

        for_each_rule!(impl_filter_by_category);
        Ok(())
    }
}