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
use std::{
    collections::{HashMap, HashSet},
    path::{Path, PathBuf},
    process::Command,
};

use anyhow::{Context, Result};
use serde::Deserialize;

/// Raw meson introspection data
#[derive(Debug, Default, Deserialize)]
#[allow(dead_code)]
struct MesonData {
    #[serde(default)]
    pub benchmarks: Vec<Benchmark>,
    #[serde(default)]
    pub buildoptions: Vec<BuildOption>,
    #[serde(default)]
    pub buildsystem_files: Vec<String>,
    #[serde(default)]
    pub compilers: HashMap<String, HashMap<String, Compiler>>,
    #[serde(default)]
    pub dependencies: Vec<Dependency>,
    #[serde(default)]
    pub install_plan: HashMap<String, HashMap<String, InstallPlan>>,
    #[serde(default)]
    pub installed: HashMap<String, String>,
    #[serde(default)]
    pub machines: HashMap<String, MachineInfo>,
    #[serde(default)]
    pub projectinfo: Option<ProjectInfo>,
    #[serde(default)]
    pub targets: Vec<Target>,
    #[serde(default)]
    pub tests: Vec<Test>,
}

/// Represents the full output of `meson introspect --all` with pre-computed
/// caches
#[derive(Debug)]
pub struct MesonIntrospection {
    /// Path to the meson build directory
    build_dir: PathBuf,

    /// Raw meson data
    #[allow(dead_code)]
    data: MesonData,

    /// Pre-computed set of GIR-introspected headers
    introspected_headers: HashSet<PathBuf>,

    /// Pre-computed set of installed headers
    installed_headers: HashSet<PathBuf>,
}

#[derive(Debug, Deserialize)]
pub struct Benchmark {
    pub name: String,
    pub suite: Vec<String>,
    pub cmd: Vec<String>,
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default)]
    pub depends: Vec<String>,
    pub workdir: Option<String>,
    pub timeout: u32,
    pub protocol: String,
    pub priority: i32,
}

#[derive(Debug, Deserialize)]
pub struct BuildOption {
    pub name: String,
    #[serde(rename = "type")]
    pub option_type: String,
    pub value: serde_json::Value,
    pub section: String,
    pub machine: String,
    pub description: String,
    #[serde(default)]
    pub choices: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct Compiler {
    pub id: String,
    #[serde(default)]
    pub exelist: Vec<String>,
    #[serde(default)]
    pub linker_exelist: Vec<String>,
    #[serde(default)]
    pub file_suffixes: Vec<String>,
    #[serde(default)]
    pub default_suffix: Option<String>,
    pub version: String,
    pub full_version: String,
    #[serde(default)]
    pub linker_id: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Dependency {
    pub name: String,
    #[serde(rename = "type")]
    pub dep_type: String,
    pub version: String,
    #[serde(default)]
    pub compile_args: Vec<String>,
    #[serde(default)]
    pub link_args: Vec<String>,
    #[serde(default)]
    pub include_directories: Vec<String>,
    #[serde(default)]
    pub sources: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct InstallPlan {
    pub destination: String,
    #[serde(default)]
    pub tag: Option<String>,
    #[serde(default)]
    pub subproject: Option<String>,
    #[serde(default)]
    pub install_rpath: Option<String>,
    #[serde(default)]
    pub exclude_dirs: Vec<String>,
    #[serde(default)]
    pub exclude_files: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct MachineInfo {
    pub system: String,
    pub cpu_family: String,
    pub cpu: String,
    pub endian: String,
}

#[derive(Debug, Deserialize)]
pub struct ProjectInfo {
    pub version: String,
    pub descriptive_name: String,
    #[serde(default)]
    pub license: Vec<String>,
    #[serde(default)]
    pub subprojects: Vec<SubprojectInfo>,
}

#[derive(Debug, Deserialize)]
pub struct SubprojectInfo {
    pub name: String,
    pub version: String,
    pub descriptive_name: String,
}

#[derive(Debug, Deserialize)]
pub struct Target {
    pub name: String,
    pub id: String,
    #[serde(rename = "type")]
    pub target_type: String,
    pub defined_in: String,
    pub filename: Vec<String>,
    pub build_by_default: bool,
    #[serde(default)]
    pub target_sources: Vec<TargetSource>,
    #[serde(default)]
    pub dependencies: Vec<String>,
    #[serde(default)]
    pub subproject: Option<String>,
    pub installed: bool,
}

#[derive(Debug, Deserialize)]
pub struct TargetSource {
    #[serde(default)]
    pub language: Option<String>,
    #[serde(default)]
    pub compiler: Vec<String>,
    #[serde(default)]
    pub parameters: Vec<String>,
    #[serde(default)]
    pub sources: Vec<String>,
    #[serde(default)]
    pub generated_sources: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct Test {
    pub name: String,
    pub suite: Vec<String>,
    pub cmd: Vec<String>,
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default)]
    pub depends: Vec<String>,
    pub workdir: Option<String>,
    pub timeout: u32,
    pub protocol: String,
    pub priority: i32,
}

/// Find the meson build directory by looking for meson-info/meson-info.json
/// Searches in:
/// 1. User-specified build_dir from config
/// 2. Common build directory names (build/, builddir/, _build/)
/// 3. Any directory containing meson-info/
fn find_build_dir(project_root: &Path, config_build_dir: Option<&str>) -> Option<PathBuf> {
    // 1. Check user-specified build_dir
    if let Some(dir) = config_build_dir {
        let path = project_root.join(dir);
        if is_build_dir(&path) {
            return Some(path);
        }
    }

    // 2. Check common build directory names
    for name in &["build", "builddir", "_build"] {
        let path = project_root.join(name);
        if is_build_dir(&path) {
            return Some(path);
        }
    }

    // 3. Search for any directory containing meson-info/
    if let Ok(entries) = std::fs::read_dir(project_root) {
        for entry in entries.filter_map(std::result::Result::ok) {
            let path = entry.path();
            if path.is_dir() && is_build_dir(&path) {
                return Some(path);
            }
        }
    }

    None
}

/// Check if a directory is a valid meson build directory
fn is_build_dir(path: &Path) -> bool {
    path.join("meson-info").join("meson-info.json").exists()
}

impl MesonIntrospection {
    /// Create a mock MesonIntrospection for testing with specified headers
    #[doc(hidden)]
    pub fn mock(
        introspected_headers: HashSet<PathBuf>,
        installed_headers: HashSet<PathBuf>,
    ) -> Self {
        Self {
            build_dir: PathBuf::from("/mock/build"),
            data: MesonData::default(),
            introspected_headers,
            installed_headers,
        }
    }

    /// Create MesonIntrospection by finding the build directory and running
    /// `meson introspect --all` Returns None if no build directory is found
    pub fn new(project_root: &Path, config_build_dir: Option<&str>) -> Result<Option<Self>> {
        // Find build directory
        let Some(build_dir) = find_build_dir(project_root, config_build_dir) else {
            return Ok(None);
        };

        // Run meson introspect --all
        let output = Command::new("meson")
            .arg("introspect")
            .arg(&build_dir)
            .arg("--all")
            .output()
            .context("Failed to run meson introspect (is meson installed?)")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("meson introspect --all failed: {}", stderr);
        }

        // Parse JSON output
        let stdout = String::from_utf8(output.stdout)
            .context("meson introspect output is not valid UTF-8")?;

        let data: MesonData = serde_json::from_str(&stdout)
            .context("Failed to parse meson introspect JSON output")?;

        // Pre-compute introspected headers
        let introspected_headers = Self::compute_introspected_headers(&data, &build_dir)?;

        // Pre-compute installed headers
        let installed_headers = Self::compute_installed_headers(&data);

        Ok(Some(Self {
            build_dir,
            data,
            introspected_headers,
            installed_headers,
        }))
    }

    /// Compute headers scanned by g-ir-scanner (GObject introspection headers)
    fn compute_introspected_headers(
        data: &MesonData,
        _build_dir: &Path,
    ) -> Result<HashSet<PathBuf>> {
        let mut headers = HashSet::new();

        // Find all targets that produce .gir files
        for target in &data.targets {
            // Check if this target produces a .gir file
            let produces_gir = target.filename.iter().any(|f| f.ends_with(".gir"));
            if !produces_gir {
                continue;
            }

            // Look for --filelist argument in g-ir-scanner command
            for source in &target.target_sources {
                for arg in &source.compiler {
                    if let Some(filelist_path) = arg.strip_prefix("--filelist=") {
                        // Read the filelist and extract .h files
                        let content = std::fs::read_to_string(filelist_path)
                            .context(format!("Failed to read GIR filelist: {}", filelist_path))?;

                        for line in content.lines() {
                            let line = line.trim();
                            if line.ends_with(".h") {
                                headers.insert(PathBuf::from(line));
                            }
                        }
                    }
                }
            }
        }

        Ok(headers)
    }

    /// Compute installed header files (all headers that will be installed)
    fn compute_installed_headers(data: &MesonData) -> HashSet<PathBuf> {
        let mut headers = HashSet::new();
        for source_path in data.installed.keys() {
            if source_path.ends_with(".h") {
                headers.insert(PathBuf::from(source_path));
            }
        }
        headers
    }

    /// Get headers scanned by g-ir-scanner (GObject introspection headers)
    pub fn get_introspected_headers(&self) -> &HashSet<PathBuf> {
        &self.introspected_headers
    }

    /// Get installed header files (all headers that will be installed)
    pub fn get_installed_headers(&self) -> &HashSet<PathBuf> {
        &self.installed_headers
    }
}

/// Compiler information extracted from compile_commands.json
#[derive(Debug, Clone)]
pub struct CompilerInfo {
    /// Compiler executable (e.g., "cc", "gcc", "/usr/bin/clang")
    pub compiler: String,
    /// Compilation flags (-I, -D, etc.)
    pub flags: Vec<String>,
}

/// Entry in compile_commands.json (standard format used by CMake, Meson, etc.)
#[derive(Debug, Deserialize)]
struct CompileCommand {
    /// Build directory
    directory: String,
    /// Full compilation command
    command: String,
    /// Source file path (relative to directory)
    file: String,
}

impl MesonIntrospection {
    /// Load compile_commands.json and build a map from source file →
    /// CompilerInfo
    pub fn load_compiler_map(&self) -> Result<HashMap<PathBuf, CompilerInfo>> {
        let compile_commands_path = self.build_dir.join("compile_commands.json");
        if !compile_commands_path.exists() {
            anyhow::bail!(
                "compile_commands.json not found in {}",
                self.build_dir.display()
            );
        }

        let content = std::fs::read_to_string(&compile_commands_path)
            .context("Failed to read compile_commands.json")?;

        let commands: Vec<CompileCommand> =
            serde_json::from_str(&content).context("Failed to parse compile_commands.json")?;

        let mut map = HashMap::new();

        for cmd in commands {
            let (compiler, flags) = Self::parse_compile_command(&cmd.command);

            // Resolve file path (may be relative to build directory)
            let file_path = if Path::new(&cmd.file).is_absolute() {
                PathBuf::from(&cmd.file)
            } else {
                PathBuf::from(&cmd.directory).join(&cmd.file)
            };

            // Canonicalize to get absolute path
            let file_path = file_path
                .canonicalize()
                .unwrap_or_else(|_| file_path.clone());

            map.insert(file_path, CompilerInfo { compiler, flags });
        }

        tracing::debug!("Loaded {} entries from compile_commands.json", map.len());

        Ok(map)
    }

    /// Parse a compilation command string to extract compiler and flags
    fn parse_compile_command(command: &str) -> (String, Vec<String>) {
        let parts: Vec<&str> = command.split_whitespace().collect();
        if parts.is_empty() {
            return ("cc".to_string(), Vec::new());
        }

        // First part is compiler (skip ccache if present)
        let (compiler_idx, compiler) = if parts[0] == "ccache" && parts.len() > 1 {
            (1, parts[1].to_string())
        } else {
            (0, parts[0].to_string())
        };

        // Extract flags (skip compiler, -o, -c, -MF, -MQ, -MD and their arguments, and
        // the input file)
        let mut flags = Vec::new();
        let mut i = compiler_idx + 1;

        while i < parts.len() {
            let flag = parts[i];

            // Skip output-related flags and their arguments
            if flag == "-o" || flag == "-MF" || flag == "-MQ" {
                i += 2; // Skip flag and its argument
                continue;
            }

            // Skip standalone flags
            if flag == "-c" || flag == "-MD" {
                i += 1;
                continue;
            }

            // Skip the input file (last .c file)
            if flag.ends_with(".c") && i == parts.len() - 1 {
                break;
            }

            flags.push(flag.to_string());
            i += 1;
        }

        (compiler, flags)
    }
}