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
//! Lit and FileCheck for Cargo test targets.
//!
//! # Test target
//!
//! Add a harness-free integration test to `Cargo.toml`:
//!
//! ```toml
//! [dev-dependencies]
//! litnik = "0.2"
//!
//! [[test]]
//! name = "lit"
//! path = "tests/lit.rs"
//! harness = false
//! ```
//!
//! Put the suite entry point in `tests/lit.rs`:
//!
//! ```rust,no_run
//! # #![allow(clippy::needless_doctest_main)]
//! fn main() {
//!     litnik::Suite::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/lit"))
//!         .suffix("mlir")
//!         .run_from_args();
//! }
//! ```
//!
//! `tests/lit/smoke.mlir`:
//!
//! ```text
//! // RUN: echo "answer = 42" | FileCheck %s
//! // CHECK: answer = 42
//! ```
//!
//! Run it with `cargo test --test lit`. Arguments after `--` are handled by the
//! test harness, including `--list` and name filters.
//!
//! # Choosing an entry point
//!
//! Use [`Suite`] in a harness-free Cargo test target. [`Suite::tool()`] binds a
//! compiler executable to the command name used in `RUN:` lines.
//! [`Suite::exec_root()`] places test working directories and `Output` trees
//! outside the source tree.
//!
//! If another harness owns listing or reporting, build a [`LitConfig`], discover
//! [`Test`] values through [`discovery`], and execute them through [`formats`].
//! That path preserves the exact [`ResultCode`] in each [`TestResult`].
//!
//! # Compatibility
//!
//! Suite configuration is expressed through [`Suite`] or [`LitConfig`]; Python
//! `lit.cfg` files are not evaluated. `RUN:` lines use Litnik's shell, and the
//! command name `FileCheck` selects the embedded checker.
//!
//! The [compatibility guide](https://github.com/kehrazy/litnik/blob/main/docs/compatibility.md)
//! documents supported directives, substitutions, shell syntax, FileCheck
//! options, and known differences from LLVM's tools.

#![warn(missing_docs)]

mod boolean_expression;
pub mod config;
pub mod discovery;
mod filecheck;
pub mod formats;
mod integrated;
mod runner;
mod shell;
mod substitution;
pub mod test;

pub use config::LitConfig;
pub use libtest_mimic::{Arguments, Conclusion};
pub use test::{ResultCode, Test, TestResult};

use std::path::PathBuf;

/// A Lit suite configured and run from one Rust test entry point.
///
/// Builder methods consume and return the suite, so configuration can be kept
/// in one expression. Methods that accept collections add values; scalar
/// methods replace the corresponding setting. Call [`Self::run_from_args()`]
/// from a harness-free Cargo integration test.
#[derive(Debug, Default)]
pub struct Suite {
    config: LitConfig,
}

impl Suite {
    /// Creates a suite whose source and execution roots start at `root`.
    ///
    /// Discovery is recursive. Add at least one suffix with [`Self::suffix()`];
    /// no suffixes are enabled initially. Set [`Self::exec_root()`] to keep
    /// generated `Output` directories outside the source tree. A suite with no
    /// matching files fails when it runs.
    ///
    /// 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 {
        Self {
            config: LitConfig::new(root),
        }
    }

    /// Replaces the source and discovery root.
    ///
    /// This clears a prior [`Self::source_root()`] override and retains the
    /// execution root and all other settings. 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.
    pub fn with_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.config.root = config::anchor_path(root.into());
        self.config.test_source_root = None;
        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 {
        self.config = self.config.tool(name, path);
        self
    }

    /// Adds one suffix used to select test files.
    ///
    /// A leading dot is optional. An empty suffix is ignored.
    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
        self.config = self.config.suffix(suffix);
        self
    }

    /// Adds test-file suffixes in iteration order.
    ///
    /// Each value follows [`Self::suffix()`] normalization.
    pub fn suffixes<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.config = self.config.suffixes(values);
        self
    }

    /// Excludes an exact file or directory base name from discovery.
    ///
    /// `Inputs`, `Output`, `.git`, and `.svn` are excluded independently of
    /// this setting.
    pub fn exclude(mut self, value: impl Into<String>) -> Self {
        self.config = self.config.exclude(value);
        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.config = self.config.excludes(values);
        self
    }

    /// Adds a regular-expression substitution for `RUN:` directives.
    ///
    /// Substitutions run in insertion order before built-in path forms. The
    /// replacement is literal text, so `$` does not expand capture groups. An
    /// invalid pattern makes each affected test `UNRESOLVED` during preparation.
    pub fn substitution(mut self, pattern: impl Into<String>, value: impl Into<String>) -> Self {
        self.config = self.config.substitution(pattern, value);
        self
    }

    /// Makes one exact feature name available to boolean test directives.
    pub fn feature(mut self, value: impl Into<String>) -> Self {
        self.config = self.config.feature(value);
        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.config = self.config.features(values);
        self
    }

    /// Sets one variable in the environment snapshot passed to test commands.
    ///
    /// The initial snapshot contains the Unicode variables visible when
    /// [`Self::new()`] created the suite.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.config = self.config.env(key, value);
        self
    }

    /// Sets the source root used for discovery and source-path substitutions.
    ///
    /// 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 source_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.config = self.config.source_root(root);
        self
    }

    /// Sets the root used for working directories and temporary files.
    ///
    /// The runner creates the required directories when a test executes. 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, root: impl Into<PathBuf>) -> Self {
        self.config = self.config.exec_root(root);
        self
    }

    /// Requires substitutions to stabilize within `value` additional passes.
    ///
    /// The runner always applies the initial substitution pass.
    pub fn recursive_expansion_limit(mut self, value: usize) -> Self {
        self.config = self.config.recursive_expansion_limit(Some(value));
        self
    }

    /// Sets the time limit for one complete test attempt, in seconds.
    ///
    /// The same deadline covers all `RUN:` lines 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, seconds: u64) -> Self {
        self.config = self.config.max_individual_test_time(seconds);
        self
    }

    /// Controls whether preparation succeeds without executing `RUN:` commands.
    ///
    /// When enabled, the runner reads 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.config = self.config.no_execute(value);
        self
    }

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

    /// Controls whether path substitutions use forward slashes.
    pub fn normalize_slashes(mut self, value: bool) -> Self {
        self.config = self.config.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.config = self.config.limit_to_features(values);
        self
    }

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

    /// Discovers the suite and runs it through `libtest-mimic`.
    ///
    /// A discovery error or zero matching files produces one failing entry
    /// named `litnik :: discovery`. `UNSUPPORTED`, `SKIPPED`, and `EXCLUDED`
    /// results become ignored harness entries. `XFAIL` and `FLAKYPASS` become
    /// successful entries because `libtest-mimic` has no custom success status.
    /// Use [`formats::run_shtest()`] when the exact [`TestResult::code`] is
    /// required.
    ///
    /// The returned [`Conclusion`] does not terminate the process.
    ///
    /// # Blocking
    ///
    /// This method performs synchronous filesystem access and waits for child
    /// processes. Independent tests can run in parallel through the harness.
    pub fn run(self, args: Arguments) -> Conclusion {
        let tests = match discovery::try_discover_tests(&self.config.root, &self.config) {
            Ok(tests) if !tests.is_empty() => tests,
            Ok(_) => {
                let root = self
                    .config
                    .test_source_root
                    .as_deref()
                    .unwrap_or(&self.config.root)
                    .display()
                    .to_string();
                let trial = libtest_mimic::Trial::test("litnik :: discovery", move || {
                    Err(format!("no tests discovered below '{root}'").into())
                });
                return libtest_mimic::run(&args, vec![trial]);
            }
            Err(error) => {
                let message = error.to_string();
                let trial = libtest_mimic::Trial::test("litnik :: discovery", move || {
                    Err(message.clone().into())
                });
                return libtest_mimic::run(&args, vec![trial]);
            }
        };

        let mut trials = Vec::with_capacity(tests.len());
        for mut test in tests {
            let config = self.config.clone();
            let name = test.get_full_name();
            trials.push(libtest_mimic::Trial::ignorable_test(name, move || {
                let result = formats::run_shtest(&mut test, &config);
                match result.code {
                    ResultCode::EXCLUDED | ResultCode::SKIPPED | ResultCode::UNSUPPORTED => {
                        Ok(libtest_mimic::Completion::Ignored {
                            reason: Some(result.code.label().to_string()),
                        })
                    }
                    code if code.is_failure() => {
                        let message =
                            format!("{} ({})\n{}", code.name(), code.label(), result.output);
                        Err(message.into())
                    }
                    _ => Ok(libtest_mimic::Completion::Completed),
                }
            }));
        }
        libtest_mimic::run(&args, trials)
    }

    /// Parses the process arguments, runs the suite, and exits with its status.
    ///
    /// This is the terminal call for a harness-free Cargo test target.
    pub fn run_from_args(self) -> ! {
        self.run(Arguments::from_args()).exit()
    }
}

#[cfg(test)]
mod tests {
    use libtest_mimic::Arguments;

    #[test]
    fn config_builder_is_chainable() {
        let suite = crate::Suite::new("/tmp")
            .tool("butcher-opt", "/bin/true")
            .suffix(".mlir")
            .feature("linux")
            .excludes(vec!["Ignore"])
            .test_retry_attempts(2)
            .limit_to_features(vec!["linux"]);

        let cfg = suite.config;
        assert!(cfg.tools.contains_key("butcher-opt"));
        assert!(cfg.suffixes.contains(".mlir"));
        assert!(cfg.available_features.contains("linux"));
    }

    #[test]
    fn suite_runs_with_empty_tests() {
        let suite = super::Suite::new(".").suffix(".does-not-exist");
        let args = Arguments::from_args();
        let _ = suite.run(args);
    }
}