litnik 0.2.1

An embedded Lit and FileCheck runner for compiler test suites.
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
//! Complete suite configuration for low-level discovery and execution.
//!
//! Most Cargo test targets can use [`crate::Suite`]. Use [`LitConfig`] when
//! calling [`crate::discovery`] or [`crate::formats`] directly.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// Configuration shared by discovery and every test in one Lit suite.
///
/// Builder methods consume and return the configuration. Collection methods add
/// values; scalar methods replace the corresponding setting. [`Self::new()`]
/// snapshots the process environment. Relative roots and tool paths are
/// resolved against the process working directory when their builder method is
/// called.
///
/// [`Default`] is equivalent to `LitConfig::new(".")`.
///
/// # Example
///
/// ```
/// let config = litnik::LitConfig::new("tests/lit")
///     .suite_name("optimizer")
///     .suffix("mlir")
///     .tool("example-opt", "target/debug/example-opt")
///     .feature("registered-target");
///
/// assert!(config.registered_tool("example-opt").is_some());
/// ```
#[derive(Debug, Clone)]
pub struct LitConfig {
    pub(crate) name: String,
    pub(crate) root: PathBuf,
    pub(crate) tools: HashMap<String, RegisteredTool>,
    pub(crate) suffixes: HashSet<String>,
    pub(crate) exclusions: HashSet<String>,
    pub(crate) substitutions: Vec<(String, String)>,
    pub(crate) environment: HashMap<String, String>,
    pub(crate) available_features: HashSet<String>,
    pub(crate) pipefail: bool,
    pub(crate) recursive_expansion_limit: Option<usize>,
    pub(crate) limit_to_features: HashSet<String>,
    pub(crate) max_individual_test_time_seconds: Option<u64>,
    pub(crate) no_execute: bool,
    pub(crate) normalize_slashes: bool,
    pub(crate) test_source_root: Option<PathBuf>,
    pub(crate) test_exec_root: Option<PathBuf>,
    pub(crate) default_substitutions: Vec<(String, String)>,
    pub(crate) test_retry_attempts: usize,
}

#[derive(Debug, Clone)]
pub(crate) struct RegisteredTool {
    path: PathBuf,
    #[cfg(test)]
    utf8: Option<String>,
}

impl LitConfig {
    /// Creates configuration whose source and execution roots start at `root`.
    ///
    /// The initial environment is a snapshot of the current process environment.
    /// Tests inherit that snapshot unless [`Self::env()`] replaces a value. No
    /// test suffixes or features are enabled. Pipefail is enabled, command
    /// execution is enabled, and retries and time limits are disabled.
    ///
    /// A relative root is resolved against the process working directory when
    /// this method is called.
    ///
    /// # Panics
    ///
    /// Panics if `root` is relative and the process working directory is not
    /// available, or if a process environment variable is not valid Unicode.
    pub fn new(root: impl Into<PathBuf>) -> Self {
        let root = anchor_path(root.into());

        Self {
            name: "litnik".into(),
            root,
            tools: HashMap::new(),
            suffixes: HashSet::new(),
            exclusions: HashSet::new(),
            substitutions: Vec::new(),
            environment: std::env::vars().collect(),
            available_features: HashSet::new(),
            pipefail: true,
            recursive_expansion_limit: None,
            limit_to_features: HashSet::new(),
            max_individual_test_time_seconds: None,
            no_execute: false,
            normalize_slashes: false,
            test_source_root: None,
            test_exec_root: None,
            default_substitutions: Vec::new(),
            test_retry_attempts: 0,
        }
    }

    /// Sets the name used in the harness identifier `name :: relative-path`.
    pub fn suite_name(mut self, value: impl Into<String>) -> Self {
        self.name = value.into();
        self
    }

    /// Registers an executable under an exact `RUN:` command name.
    ///
    /// A later registration replaces the path for the same name. Registered
    /// tools take precedence over `PATH`; the embedded `FileCheck` command takes
    /// precedence over a tool registered with that name. A relative path is
    /// resolved against the process working directory when this method is
    /// called.
    ///
    /// # Panics
    ///
    /// Panics if `path` is relative and the process working directory is not
    /// available.
    pub fn tool(mut self, name: impl Into<String>, path: impl Into<PathBuf>) -> Self {
        let name = name.into();
        let path = anchor_path(path.into());
        #[cfg(test)]
        let utf8 = path.to_str().map(ToOwned::to_owned);
        self.tools.insert(
            name,
            RegisteredTool {
                path,
                #[cfg(test)]
                utf8,
            },
        );
        self
    }

    /// Adds one suffix used to select test files.
    ///
    /// A missing leading dot is added. An empty suffix is ignored.
    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
        let suffix = suffix.into();
        if !suffix.is_empty() {
            self.suffixes.insert(if suffix.starts_with('.') {
                suffix
            } else {
                format!(".{suffix}")
            });
        }
        self
    }

    /// Adds test-file suffixes in iteration order.
    ///
    /// This method applies the same normalization as [`Self::suffix()`] to each
    /// value.
    pub fn suffixes<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for value in values {
            self = self.suffix(value);
        }
        self
    }

    /// Excludes a file or directory whose base name exactly equals `value`.
    ///
    /// `Inputs`, `Output`, `.git`, and `.svn` are excluded independently of
    /// this setting.
    pub fn exclude(mut self, value: impl Into<String>) -> Self {
        self.exclusions.insert(value.into());
        self
    }

    /// Adds exact file or directory base names to the discovery exclusions.
    pub fn excludes<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.exclusions.extend(values.into_iter().map(Into::into));
        self
    }

    /// Adds a regular-expression substitution for `RUN:` directives.
    ///
    /// Substitutions run in insertion order before the default and built-in
    /// forms. The replacement is literal text, so `$` does not expand capture
    /// groups. Patterns are compiled while each test is prepared; an invalid
    /// pattern makes the test `UNRESOLVED`.
    pub fn substitution(mut self, pattern: impl Into<String>, value: impl Into<String>) -> Self {
        self.substitutions.push((pattern.into(), value.into()));
        self
    }

    /// Adds regular-expression substitutions in iteration order.
    ///
    /// Each pair follows [`Self::substitution()`] semantics.
    pub fn substitutions<I, K, V>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.substitutions
            .extend(values.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }

    /// Adds a base substitution after suite substitutions and before built-ins.
    ///
    /// Use [`Self::substitution()`] for suite-specific substitutions. This
    /// method exists for integrations that assemble a base configuration.
    pub fn default_substitution(
        mut self,
        pattern: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        self.default_substitutions
            .push((pattern.into(), value.into()));
        self
    }

    /// Adds base substitutions in iteration order.
    ///
    /// Each pair follows [`Self::default_substitution()`] semantics.
    pub fn default_substitutions<I, K, V>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.default_substitutions
            .extend(values.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }

    /// Makes one exact feature name available to boolean test directives.
    pub fn feature(mut self, value: impl Into<String>) -> Self {
        self.available_features.insert(value.into());
        self
    }

    /// Makes each supplied feature name available to boolean test directives.
    pub fn features<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.available_features
            .extend(values.into_iter().map(Into::into));
        self
    }

    /// Sets one variable in the environment snapshot passed to test commands.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.environment.insert(key.into(), value.into());
        self
    }

    /// Sets the source root used for discovery and source-path substitutions.
    ///
    /// This setting takes precedence over the root passed to discovery. When no
    /// execution root is set, it also becomes the execution root. A relative
    /// path is resolved against the process working directory when this method
    /// is called.
    ///
    /// # Panics
    ///
    /// Panics if the root is relative and the process working directory is not
    /// available.
    pub fn source_root(mut self, value: impl Into<PathBuf>) -> Self {
        self.test_source_root = Some(anchor_path(value.into()));
        self
    }

    /// Sets the root used for test working directories and temporary files.
    ///
    /// The directory is created when a test runs. The source tree is used when
    /// no execution root is set. A relative root is resolved against the
    /// process working directory when this method is called.
    ///
    /// # Panics
    ///
    /// Panics if the root is relative and the process working directory is not
    /// available.
    pub fn exec_root(mut self, value: impl Into<PathBuf>) -> Self {
        self.test_exec_root = Some(anchor_path(value.into()));
        self
    }

    /// Sets the maximum number of recursive substitution passes.
    ///
    /// The runner always applies one pass. `None` stops there. `Some(limit)`
    /// requires expansion to stabilize within `limit` additional passes.
    pub fn recursive_expansion_limit(mut self, value: Option<usize>) -> Self {
        self.recursive_expansion_limit = value;
        self
    }

    /// Sets the time limit for one complete test attempt, in seconds.
    ///
    /// The same deadline covers every `RUN:` line in the attempt. Zero disables
    /// the limit. The runner stops child processes at the deadline but cannot
    /// interrupt an embedded command while it runs.
    pub fn max_individual_test_time(mut self, secs: u64) -> Self {
        self.max_individual_test_time_seconds = (secs != 0).then_some(secs);
        self
    }

    /// Controls whether preparation succeeds without executing `RUN:` commands.
    ///
    /// When enabled, the runner reads integrated directives, evaluates feature
    /// conditions, and applies substitutions. A test that passes preparation
    /// receives `PASS`, or `XPASS` when an `XFAIL:` condition is active, with
    /// the rendered commands. The runner does not parse or execute those
    /// commands.
    pub fn no_execute(mut self, value: bool) -> Self {
        self.no_execute = value;
        self
    }

    /// Controls whether a non-final failed stage fails its pipeline.
    ///
    /// Pipefail is enabled when configuration is created.
    pub fn with_pipefail(mut self, value: bool) -> Self {
        self.pipefail = value;
        self
    }

    /// Controls whether path substitutions use forward slashes.
    pub fn normalize_slashes(mut self, value: bool) -> Self {
        self.normalize_slashes = value;
        self
    }

    /// Restricts execution to tests that depend on at least one listed feature.
    ///
    /// A selected test must satisfy all of its `REQUIRES:` expressions, and at
    /// least one expression must become false when the listed features are
    /// removed. Other tests receive `UNSUPPORTED`.
    pub fn limit_to_features<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.limit_to_features = values.into_iter().map(Into::into).collect();
        self
    }

    /// Sets the number of retries after an initial `FAIL` result.
    ///
    /// `TIMEOUT` and `UNRESOLVED` results are not retried. A test-level
    /// `ALLOW_RETRIES:` directive replaces this setting.
    pub fn test_retry_attempts(mut self, attempts: usize) -> Self {
        self.test_retry_attempts = attempts;
        self
    }

    #[cfg(test)]
    pub(crate) fn tool_path(&self, name: &str) -> Option<&String> {
        self.tools.get(name)?.utf8.as_ref()
    }

    /// Returns the registered executable for the exact command `name`.
    pub fn registered_tool(&self, name: &str) -> Option<&Path> {
        self.tools.get(name).map(|tool| tool.path.as_path())
    }

    pub(crate) fn to_test_config(&self) -> crate::test::TestConfig {
        crate::test::TestConfig {
            name: self.name.clone(),
            suffixes: self.suffixes.clone(),
            exclusions: self.exclusions.clone(),
            substitutions: self.substitutions.clone(),
            default_substitutions: self.default_substitutions.clone(),
            available_features: self.available_features.clone(),
            normalize_slashes: self.normalize_slashes,
            pipefail: self.pipefail,
            recursive_expansion_limit: self.recursive_expansion_limit,
            limit_to_features: self.limit_to_features.clone(),
            max_individual_test_time: self
                .max_individual_test_time_seconds
                .map(std::time::Duration::from_secs),
            environment: self.environment.clone(),
            test_retry_attempts: self.test_retry_attempts,
            tools: self
                .tools
                .iter()
                .map(|(name, tool)| (name.clone(), tool.path.clone()))
                .collect(),
        }
    }

    #[cfg(test)]
    pub(crate) fn use_external_shell(self, _value: bool) -> Self {
        self
    }
}

pub(crate) fn anchor_path(path: PathBuf) -> PathBuf {
    if path.is_absolute() {
        path
    } else {
        std::env::current_dir()
            .expect("cannot anchor a relative path without a process working directory")
            .join(path)
    }
}

impl Default for LitConfig {
    fn default() -> Self {
        Self::new(".")
    }
}

#[cfg(test)]
mod tests {
    use super::LitConfig;

    #[test]
    fn builder_roundtrip() {
        let cfg = LitConfig::new("/tmp/root")
            .suite_name("x")
            .suffix(".mlir")
            .exclude("Inputs")
            .tool("clang", "/bin/clang")
            .feature("linux");
        assert_eq!(cfg.name, "x");
        assert!(cfg.suffixes.contains(".mlir"));
        assert!(cfg.exclusions.contains("Inputs"));
        assert_eq!(cfg.tool_path("clang"), Some(&"/bin/clang".to_string()));
        assert!(cfg.available_features.contains("linux"));
    }
}