rllvm 0.4.2

A tool to build whole-program LLVM bitcode files
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! TOML-based configuration for rllvm.
//!
//! Configuration is loaded from `~/.rllvm/config.toml` by default, or from a path
//! specified via the `RLLVM_CONFIG` environment variable. The configuration stores
//! paths to LLVM tools (`clang`, `llvm-link`, etc.) and optional flags for bitcode
//! generation and linking.

use std::{
    env, fs,
    path::{Path, PathBuf},
    sync::OnceLock,
};

use serde::{Deserialize, Serialize};
use tracing::Level;

use crate::{
    constants::{
        BITCODE_ROOT_ENV_NAME, DEFAULT_CONF_FILEPATH_UNDER_HOME,
        DEFAULT_RLLVM_CONF_FILEPATH_ENV_NAME, HOME_ENV_NAME, LOG_LEVEL_ENV_NAME, LTO_MODE_ENV_NAME,
        RUSTC_ENV_NAME,
    },
    diagnostics::{check_version_compatibility, print_missing_tool_error},
    error::Error,
    lto::LtoMode,
    utils::{execute_llvm_config, find_llvm_config},
};

/// The cached outcome of loading the configuration.
///
/// The failure is stored as a message rather than as an [`Error`], because a
/// `OnceLock` hands out shared references and the error type is not `Clone` — every
/// caller needs its own owned error.
type ConfigResult = Result<RLLVMConfig, String>;

fn config_result_to_ref(result: &'static ConfigResult) -> Result<&'static RLLVMConfig, Error> {
    match result {
        Ok(config) => Ok(config),
        Err(message) => Err(Error::ConfigError(message.clone())),
    }
}

#[cfg(not(test))]
pub fn try_rllvm_config() -> Result<&'static RLLVMConfig, Error> {
    static RLLVM_CONFIG: OnceLock<ConfigResult> = OnceLock::new();
    config_result_to_ref(RLLVM_CONFIG.get_or_init(|| {
        RLLVMConfig::new().map_err(|err| format!("Failed to load rllvm configuration: {err}"))
    }))
}

/// Returns the global [`RLLVMConfig`] singleton (test variant).
///
/// Uses [`RLLVMConfig::try_default`] to infer configuration from the system.
#[cfg(test)]
pub fn try_rllvm_config() -> Result<&'static RLLVMConfig, Error> {
    static RLLVM_CONFIG: OnceLock<ConfigResult> = OnceLock::new();
    config_result_to_ref(RLLVM_CONFIG.get_or_init(|| {
        RLLVMConfig::try_default()
            .map_err(|err| format!("Failed to infer rllvm configuration: {err}"))
    }))
}

/// Returns the path the configuration is read from, and written to.
///
/// `$RLLVM_CONFIG` when set, otherwise `~/.rllvm/config.toml`.
///
/// Every component that needs to know where the configuration lives must go
/// through this. The path used to be decided in two places — here for reading
/// and in `rllvm-init` for writing — and they disagreed: `rllvm-init` hardcoded
/// the home path and ignored `RLLVM_CONFIG` entirely, so it could report writing
/// a configuration that nothing would ever read, while silently overwriting the
/// user's real one.
pub fn config_filepath() -> PathBuf {
    env::var(DEFAULT_RLLVM_CONF_FILEPATH_ENV_NAME).map_or_else(
        |_| {
            // Default config file
            PathBuf::from(env::var(HOME_ENV_NAME).unwrap_or("".into()))
                .join(DEFAULT_CONF_FILEPATH_UNDER_HOME)
        },
        // User-defined config file
        PathBuf::from,
    )
}

/// Configuration for rllvm, specifying LLVM tool paths and optional flags.
///
/// Typically loaded from `~/.rllvm/config.toml` via [`try_rllvm_config`], or
/// inferred from the system using [`RLLVMConfig::try_default`].
#[derive(Serialize, Deserialize, Debug)]
pub struct RLLVMConfig {
    /// The absolute filepath of `llvm-config`
    llvm_config_filepath: PathBuf,

    /// The absolute filepath of `clang`
    clang_filepath: PathBuf,

    /// The absolute filepath of `clang++`
    clangxx_filepath: PathBuf,

    /// The absolute filepath of `llvm-ar`
    llvm_ar_filepath: PathBuf,

    /// The absolute filepath of `llvm-link`
    llvm_link_filepath: PathBuf,

    /// The absolute filepath of `llvm-objcopy` (optional, currently unused)
    llvm_objcopy_filepath: Option<PathBuf>,

    /// The absolute filepath of `rustc` (optional; `which rustc` when unset)
    rustc_filepath: Option<PathBuf>,

    /// The absolute path of the directory that stores intermediate bitcode files
    bitcode_store_path: Option<PathBuf>,

    /// Extra user-provided linking flags for `llvm-link`
    llvm_link_flags: Option<Vec<String>>,

    /// Extra user-provided linking flags for link time optimization
    lto_ldflags: Option<Vec<String>>,

    /// Extra user-provided flags for bitcode generation, e.g., "-flto -fwhole-program-vtables"
    bitcode_generation_flags: Option<Vec<String>>,

    /// The configure only mode, which skips the bitcode generation (Default: false)
    is_configure_only: Option<bool>,

    /// Log level (Default: 0, print nothing)
    log_level: Option<u8>,

    /// Enable incremental bitcode caching (Default: false).
    /// Can also be enabled via `RLLVM_CACHE=1` environment variable.
    cache_enabled: Option<bool>,

    /// Root that embedded bitcode paths are recorded relative to (Default: none)
    bitcode_root: Option<PathBuf>,

    /// How to handle `-flto` builds: `marker`, `save-temps` or `skip`
    /// (Default: `marker`)
    lto_mode: Option<LtoMode>,

    /// Custom cache directory path (Default: `~/.rllvm/cache/`)
    cache_dir: Option<PathBuf>,
}

impl RLLVMConfig {
    /// Returns the path to `llvm-config`.
    pub fn llvm_config_filepath(&self) -> &PathBuf {
        &self.llvm_config_filepath
    }

    /// Returns the path to `clang`.
    pub fn clang_filepath(&self) -> &PathBuf {
        &self.clang_filepath
    }

    /// Returns the path to `clang++`.
    pub fn clangxx_filepath(&self) -> &PathBuf {
        &self.clangxx_filepath
    }

    /// Returns the path to `llvm-ar`.
    pub fn llvm_ar_filepath(&self) -> &PathBuf {
        &self.llvm_ar_filepath
    }

    /// Returns the path to `llvm-link`.
    pub fn llvm_link_filepath(&self) -> &PathBuf {
        &self.llvm_link_filepath
    }

    /// Returns the optional path to `llvm-objcopy`.
    pub fn llvm_objcopy_filepath(&self) -> Option<&PathBuf> {
        self.llvm_objcopy_filepath.as_ref()
    }

    /// Returns the optional bitcode store directory path.
    pub fn bitcode_store_path(&self) -> Option<&PathBuf> {
        self.bitcode_store_path.as_ref()
    }

    /// Returns the optional extra flags for `llvm-link`.
    pub fn llvm_link_flags(&self) -> Option<&Vec<String>> {
        self.llvm_link_flags.as_ref()
    }

    /// Returns the optional LTO link flags.
    pub fn lto_ldflags(&self) -> Option<&Vec<String>> {
        self.lto_ldflags.as_ref()
    }

    /// Returns the optional bitcode generation flags.
    pub fn bitcode_generation_flags(&self) -> Option<&Vec<String>> {
        self.bitcode_generation_flags.as_ref()
    }

    /// Returns whether configure-only mode is enabled (skips bitcode generation).
    pub fn is_configure_only(&self) -> bool {
        self.is_configure_only.unwrap_or_default()
    }

    /// Returns the configured log level.
    /// Returns the log level.
    ///
    /// `$RLLVM_LOG_LEVEL` wins over the configuration file. `rllvm-cc` layers
    /// `--rllvm-verbose` on top of both; `rllvm-rustc` has no such flag,
    /// because cargo owns its command line.
    pub fn log_level(&self) -> Level {
        let level = env::var(LOG_LEVEL_ENV_NAME)
            .ok()
            .and_then(|value| value.parse::<u8>().ok())
            .unwrap_or_else(|| self.log_level.unwrap_or_default());
        match level {
            0 => Level::ERROR,
            1 => Level::WARN,
            2 => Level::INFO,
            3 => Level::DEBUG,
            _ => Level::TRACE,
        }
    }

    /// Returns whether caching is enabled in the config.
    pub fn cache_enabled(&self) -> bool {
        self.cache_enabled.unwrap_or_default()
    }

    /// Returns the root that embedded bitcode paths are recorded relative to.
    ///
    /// `$RLLVM_BITCODE_ROOT` wins over the configuration file, so a build can opt
    /// into relocatable paths without editing a shared config.
    ///
    /// When unset, paths are recorded absolute, which is the historical
    /// behaviour and keeps existing objects readable.
    pub fn bitcode_root(&self) -> Option<PathBuf> {
        env::var(BITCODE_ROOT_ENV_NAME)
            .ok()
            .filter(|v| !v.is_empty())
            .map(PathBuf::from)
            .or_else(|| self.bitcode_root.clone())
    }

    /// Returns the configured `rustc`, if any.
    ///
    /// `$RLLVM_REAL_RUSTC` wins over the configuration file. Unset here and in
    /// the environment, the wrapper falls back to `rustc` on `PATH`.
    pub fn rustc_filepath(&self) -> Option<PathBuf> {
        env::var(RUSTC_ENV_NAME)
            .ok()
            .filter(|value| !value.is_empty())
            .map(PathBuf::from)
            .or_else(|| self.rustc_filepath.clone())
    }

    /// Returns the configured LTO mode.
    ///
    /// `$RLLVM_LTO_MODE` wins over the configuration file, so one build can
    /// switch modes without editing a config other builds share.
    ///
    /// An unrecognised value is an error rather than a fallback: silently
    /// producing a binary nothing can be extracted from is the bug #96 exists
    /// to fix.
    pub fn lto_mode(&self) -> Result<LtoMode, Error> {
        match env::var(LTO_MODE_ENV_NAME) {
            Ok(value) if !value.is_empty() => value.parse(),
            _ => Ok(self.lto_mode.unwrap_or_default()),
        }
    }

    /// Returns the optional custom cache directory path.
    pub fn cache_dir(&self) -> Option<&PathBuf> {
        self.cache_dir.as_ref()
    }
}

impl RLLVMConfig {
    /// Loads configuration from the config file.
    ///
    /// The file path is determined by the `RLLVM_CONFIG` environment variable,
    /// falling back to `~/.rllvm/config.toml`.
    pub fn new() -> Result<Self, Error> {
        Self::load_path(config_filepath())
    }

    fn load_path<P>(config_filepath: P) -> Result<Self, Error>
    where
        P: AsRef<Path> + std::fmt::Debug,
    {
        let config_filepath = config_filepath.as_ref();

        // An existing file is parsed; otherwise the configuration is inferred
        // from the LLVM installation and written out for next time.
        //
        // This is deliberately not `confy::load_path`, which reaches for
        // `Default` to create a missing file. Inferring a configuration can
        // fail (no `llvm-config` on the system), and `Default` has no way to
        // report that other than panicking — on the very first run, at that.
        let mut config = if Self::config_file_has_content(config_filepath) {
            Self::parse_file(config_filepath)?
        } else {
            let inferred = Self::try_default()?;
            inferred.write_to(config_filepath)?;
            inferred
        };

        config.validate_tool_paths();

        if let Some(bitcode_store_path) = &config.bitcode_store_path {
            // Check if the bitcode store path is absolute or not
            if !bitcode_store_path.is_absolute() {
                // Not absolute
                tracing::warn!(
                    "Ignore the bitcode store path, as it is not absolute: {:?}",
                    bitcode_store_path
                );
                config.bitcode_store_path = None;
            } else {
                // Further check if the directory exists
                if !bitcode_store_path.exists() {
                    // Not exist, then create it
                    tracing::info!(
                        "Create the directory for the bitcode store: {:?}",
                        bitcode_store_path
                    );
                    fs::create_dir_all(bitcode_store_path).map_err(|err| {
                        tracing::error!(
                            "Failed to create the bitcode store directory: err={}",
                            err
                        );
                        err
                    })?;
                } else {
                    // Finally, check if this is a directory
                    if !bitcode_store_path.is_dir() {
                        // Not a directory
                        tracing::warn!(
                            "Ignore the bitcode store path, as it is not a directory: {:?}",
                            bitcode_store_path
                        );
                        config.bitcode_store_path = None;
                    }
                }
            }
        }

        Ok(config)
    }
}

impl RLLVMConfig {
    /// Returns `true` if the path names a file with something in it.
    ///
    /// An empty file is treated as absent, matching how a partially written or
    /// truncated config would otherwise fail to parse.
    fn config_file_has_content(config_filepath: &Path) -> bool {
        fs::metadata(config_filepath).is_ok_and(|meta| meta.is_file() && meta.len() > 0)
    }

    /// Parse a configuration file from disk.
    fn parse_file(config_filepath: &Path) -> Result<Self, Error> {
        let contents = fs::read_to_string(config_filepath).map_err(|err| {
            tracing::error!(
                "Failed to read configuration: config_filepath={:?}, err={}",
                config_filepath,
                err
            );
            Error::ConfigError(format!(
                "Failed to read configuration from {config_filepath:?}: {err}"
            ))
        })?;

        toml::from_str(&contents).map_err(|err| {
            tracing::error!(
                "Failed to parse configuration: config_filepath={:?}, err={}",
                config_filepath,
                err
            );
            Error::ConfigError(format!(
                "Failed to parse configuration from {config_filepath:?}: {err}"
            ))
        })
    }

    /// Serialize this configuration to the given path, creating parent
    /// directories as needed.
    fn write_to(&self, config_filepath: &Path) -> Result<(), Error> {
        if let Some(parent_dir) = config_filepath.parent()
            && !parent_dir.as_os_str().is_empty()
        {
            fs::create_dir_all(parent_dir)?;
        }

        let contents = toml::to_string_pretty(self).map_err(|err| {
            Error::ConfigError(format!("Failed to serialize the configuration: {err}"))
        })?;
        fs::write(config_filepath, contents).map_err(|err| {
            tracing::error!(
                "Failed to write configuration: config_filepath={:?}, err={}",
                config_filepath,
                err
            );
            err
        })?;

        tracing::info!("Wrote inferred configuration to {:?}", config_filepath);
        Ok(())
    }
}

impl RLLVMConfig {
    /// Checks that configured tool paths exist on disk, printing colored errors for each missing tool.
    fn validate_tool_paths(&self) {
        let tools: &[(&str, &Path)] = &[
            ("llvm-config", &self.llvm_config_filepath),
            ("clang", &self.clang_filepath),
            ("clang++", &self.clangxx_filepath),
            ("llvm-ar", &self.llvm_ar_filepath),
            ("llvm-link", &self.llvm_link_filepath),
        ];

        for (name, path) in tools {
            if !path.exists() {
                print_missing_tool_error(name, Some(path));
            }
        }

        // `llvm-objcopy` is optional: no code path invokes it today, so a stale
        // or absent entry must not be reported as an error.
        if let Some(llvm_objcopy_filepath) = &self.llvm_objcopy_filepath
            && !llvm_objcopy_filepath.exists()
        {
            tracing::debug!(
                "Configured `llvm-objcopy` does not exist: {:?}",
                llvm_objcopy_filepath
            );
        }

        // Check version compatibility between clang and LLVM tools
        if self.clang_filepath.exists() && self.llvm_config_filepath.exists() {
            check_version_compatibility(&self.clang_filepath, &self.llvm_config_filepath);
        }
    }

    /// Infers configuration by discovering LLVM tools on the system.
    ///
    /// Uses [`find_llvm_config`](crate::utils::find_llvm_config) to locate
    /// `llvm-config`, then derives all other tool paths from `llvm-config --bindir`.
    pub fn try_default() -> Result<Self, Error> {
        tracing::info!("Infer rllvm configurations ...");

        // Find `llvm-config`
        let llvm_config_filepath = find_llvm_config().inspect_err(|_| {
            print_missing_tool_error("llvm-config", None);
        })?;
        tracing::info!("- llvm-config: {:?}", llvm_config_filepath);

        // Obtain LLVM version
        match execute_llvm_config(&llvm_config_filepath, &["--version"]) {
            Ok(llvm_version) => tracing::info!("- LLVM version: {}", llvm_version),
            Err(err) => tracing::warn!("- LLVM version: (unknown, err={:?})", err),
        }

        let llvm_bindir = PathBuf::from(
            execute_llvm_config(&llvm_config_filepath, &["--bindir"]).map_err(|err| {
                tracing::error!("Failed to execute `llvm-config --bindir`: {:?}", err);
                err
            })?,
        );

        // Find `clang`
        let clang_filepath = llvm_bindir.join("clang");

        // Find `clang++`
        let clangxx_filepath = llvm_bindir.join("clang++");

        // Find `llvm-ar`
        let llvm_ar_filepath = llvm_bindir.join("llvm-ar");

        // Find `llvm-link`
        let llvm_link_filepath = llvm_bindir.join("llvm-link");

        // Find `llvm-objcopy`, which is optional: it is recorded when present,
        // but nothing invokes it, so its absence must not fail the inference.
        let llvm_objcopy_filepath = llvm_bindir.join("llvm-objcopy");
        let llvm_objcopy_filepath = if llvm_objcopy_filepath.exists() {
            Some(llvm_objcopy_filepath)
        } else {
            tracing::debug!("- llvm-objcopy: (not found in {:?})", llvm_bindir);
            None
        };

        let llvm_bin_tools: &[(&str, &PathBuf)] = &[
            ("clang", &clang_filepath),
            ("clang++", &clangxx_filepath),
            ("llvm-ar", &llvm_ar_filepath),
            ("llvm-link", &llvm_link_filepath),
        ];
        for (name, filepath) in llvm_bin_tools {
            if !filepath.exists() {
                print_missing_tool_error(name, Some(filepath));
                return Err(Error::MissingFile(format!("{filepath:?}")));
            }
        }

        // Check version compatibility between clang and LLVM tools
        check_version_compatibility(&clang_filepath, &llvm_config_filepath);

        Ok(Self {
            llvm_config_filepath,
            clang_filepath,
            clangxx_filepath,
            llvm_ar_filepath,
            llvm_link_filepath,
            llvm_objcopy_filepath,
            // Not inferred: rustc is not an LLVM tool and need not be
            // installed. The wrapper falls back to `rustc` on `PATH`.
            rustc_filepath: None,
            bitcode_store_path: None,
            llvm_link_flags: None,
            lto_ldflags: None,
            lto_mode: None,
            bitcode_generation_flags: None,
            is_configure_only: None,
            log_level: None,
            bitcode_root: None,
            cache_enabled: None,
            cache_dir: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lto::LtoMode;

    /// Writes a config file containing the required tool paths plus `extra`,
    /// returning the owning temporary directory, its path, and the inferred
    /// configuration the paths came from.
    fn write_config(extra: &str) -> (tempfile::TempDir, PathBuf, RLLVMConfig) {
        let inferred = RLLVMConfig::try_default().expect("Failed to infer the LLVM tool paths");
        let contents = format!(
            "llvm_config_filepath = '{}'\n\
             clang_filepath = '{}'\n\
             clangxx_filepath = '{}'\n\
             llvm_ar_filepath = '{}'\n\
             llvm_link_filepath = '{}'\n\
             {}",
            inferred.llvm_config_filepath().display(),
            inferred.clang_filepath().display(),
            inferred.clangxx_filepath().display(),
            inferred.llvm_ar_filepath().display(),
            inferred.llvm_link_filepath().display(),
            extra,
        );

        let dir = tempfile::tempdir().expect("Failed to create a temporary directory");
        let config_filepath = dir.path().join("config.toml");
        fs::write(&config_filepath, contents).expect("Failed to write the test config file");
        (dir, config_filepath, inferred)
    }

    #[test]
    fn bitcode_store_path_relative_is_ignored() {
        let (_dir, config_filepath, _) = write_config("bitcode_store_path = 'relative/dir'\n");
        let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");
        assert!(
            config.bitcode_store_path().is_none(),
            "a relative bitcode store path must be ignored"
        );
    }

    #[test]
    fn bitcode_store_path_absolute_is_created_when_missing() {
        let dir = tempfile::tempdir().unwrap();
        let store = dir.path().join("store").join("nested");
        assert!(!store.exists());

        let (_cfg_dir, config_filepath, _) =
            write_config(&format!("bitcode_store_path = '{}'\n", store.display()));
        let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");

        assert_eq!(config.bitcode_store_path(), Some(&store));
        assert!(store.is_dir(), "the store directory was not created");
    }

    #[test]
    fn bitcode_store_path_pointing_at_a_file_is_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let not_a_dir = dir.path().join("a_file");
        fs::write(&not_a_dir, b"x").unwrap();

        let (_cfg_dir, config_filepath, _) =
            write_config(&format!("bitcode_store_path = '{}'\n", not_a_dir.display()));
        let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");

        assert!(
            config.bitcode_store_path().is_none(),
            "a store path that is not a directory must be ignored"
        );
    }

    #[test]
    fn bitcode_store_path_existing_directory_is_kept() {
        let dir = tempfile::tempdir().unwrap();
        let store = dir.path().join("store");
        fs::create_dir_all(&store).unwrap();

        let (_cfg_dir, config_filepath, _) =
            write_config(&format!("bitcode_store_path = '{}'\n", store.display()));
        let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");
        assert_eq!(config.bitcode_store_path(), Some(&store));
    }

    #[test]
    fn missing_config_file_is_written_from_inferred_values() {
        let dir = tempfile::tempdir().unwrap();
        let config_filepath = dir.path().join("nested").join("config.toml");
        assert!(!config_filepath.exists());

        let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");

        assert!(
            config_filepath.exists(),
            "first run must write the inferred config"
        );
        assert!(config.clang_filepath().exists());
    }

    #[test]
    fn optional_flag_accessors_round_trip() {
        let (_dir, config_filepath, _) = write_config(
            "llvm_link_flags = ['-v']\n\
             lto_ldflags = ['-flto']\n\
             bitcode_generation_flags = ['-g']\n\
             is_configure_only = true\n\
             cache_enabled = true\n\
             log_level = 3\n",
        );
        let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");

        assert_eq!(config.llvm_link_flags(), Some(&vec!["-v".to_string()]));
        assert_eq!(config.lto_ldflags(), Some(&vec!["-flto".to_string()]));
        assert_eq!(
            config.bitcode_generation_flags(),
            Some(&vec!["-g".to_string()])
        );
        assert!(config.is_configure_only());
        assert!(config.cache_enabled());
        assert_eq!(config.log_level(), Level::DEBUG);
    }

    #[test]
    fn log_level_mapping_covers_every_value() {
        for (value, expected) in [
            (0u8, Level::ERROR),
            (1, Level::WARN),
            (2, Level::INFO),
            (3, Level::DEBUG),
            (4, Level::TRACE),
            (9, Level::TRACE),
        ] {
            let (_dir, config_filepath, _) = write_config(&format!("log_level = {value}\n"));
            let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");
            assert_eq!(config.log_level(), expected, "log_level = {value}");
        }
    }

    #[test]
    fn load_config_without_llvm_objcopy_filepath() {
        let (_dir, config_filepath, inferred) = write_config("");

        let config = RLLVMConfig::load_path(&config_filepath)
            .expect("A config without `llvm_objcopy_filepath` should load");

        assert!(config.llvm_objcopy_filepath().is_none());
        assert_eq!(config.clang_filepath(), inferred.clang_filepath());
        assert_eq!(config.llvm_link_filepath(), inferred.llvm_link_filepath());
    }

    #[test]
    fn lto_mode_is_read_from_the_config_file() {
        let (_dir, config_filepath, _) = write_config("lto_mode = 'save-temps'\n");
        let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");

        assert_eq!(config.lto_mode().unwrap(), LtoMode::SaveTemps);
    }

    #[test]
    fn lto_mode_defaults_to_marker_when_absent() {
        let (_dir, config_filepath, _) = write_config("log_level = 0\n");
        let config = RLLVMConfig::load_path(&config_filepath).expect("load failed");

        assert_eq!(config.lto_mode().unwrap(), LtoMode::Marker);
    }

    #[test]
    fn load_config_with_llvm_objcopy_filepath() {
        // Existing config files still set the key; they must keep loading.
        let llvm_objcopy_filepath = RLLVMConfig::try_default()
            .expect("Failed to infer the LLVM tool paths")
            .llvm_objcopy_filepath()
            .cloned()
            .unwrap_or_else(|| PathBuf::from("llvm-objcopy"));
        let (_dir, config_filepath, _inferred) = write_config(&format!(
            "llvm_objcopy_filepath = '{}'\n",
            llvm_objcopy_filepath.display()
        ));

        let config = RLLVMConfig::load_path(&config_filepath)
            .expect("A config with `llvm_objcopy_filepath` should load");

        assert_eq!(config.llvm_objcopy_filepath(), Some(&llvm_objcopy_filepath));
    }
}