snappea 0.1.0

The P modeling language in Rust: emit events from your application and check them against P specs in tests, plus the `snappea` checker
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
//! The environment the commands run in: console, file system, clock and entropy.
//!
//! Commands never touch `std::fs`, `std::time` or `std::process` directly so that the crate
//! also runs in a browser. [`MemHost`] is an in-memory implementation for tests and wasm;
//! `snappea::cli` supplies a native one.

use std::collections::BTreeMap;
use std::io;
use std::path::{Component, Path, PathBuf};

pub use crate::checker::observe_inputs::{LiveRead, LiveSource};

/// Console stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stream {
    Out,
    Err,
}

/// Console colors upstream uses (`ConsoleColor`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
    Red,
    Yellow,
    Cyan,
}

/// Everything the commands need from their environment. File system methods behave like
/// their `std::fs` namesakes unless documented otherwise.
pub trait Host {
    /// Writes console text (no newline added).
    fn write(&mut self, stream: Stream, text: &str, color: Option<Color>);
    /// Reads one complete stdin line, or `None` at EOF. Live observe hosts override this.
    fn read_stdin_line(&self) -> io::Result<Option<String>> {
        Err(io::Error::new(io::ErrorKind::Unsupported, "stdin is unavailable on this host"))
    }
    /// The current directory (absolute).
    fn cwd(&self) -> PathBuf;
    fn read_to_string(&self, path: &Path) -> io::Result<String>;
    /// Creates or replaces a file, creating its parent directories first.
    fn write_file(&mut self, path: &Path, contents: &str) -> io::Result<()>;
    fn is_file(&self, path: &Path) -> bool;
    fn is_dir(&self, path: &Path) -> bool;
    /// Entries (full paths) of a directory, sorted.
    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>>;
    fn create_dir_all(&mut self, path: &Path) -> io::Result<()>;
    fn remove_dir_all(&mut self, path: &Path) -> io::Result<()>;
    /// Removes a file. The default reports it unsupported.
    fn remove_file(&mut self, path: &Path) -> io::Result<()> {
        Err(io::Error::new(io::ErrorKind::Unsupported, format!("cannot remove '{}' on this host", path.display())))
    }
    fn rename(&mut self, from: &Path, to: &Path) -> io::Result<()>;
    /// Seconds since an arbitrary fixed point (for elapsed-time reporting).
    fn now(&self) -> f64;
    /// Peak memory use of the process in gigabytes, or 0 if unknown.
    fn max_memory_gb(&self) -> f64;
    /// A fresh random seed (used when `--seed` is not given).
    fn random_seed(&mut self) -> u32;
    /// Seconds since the Unix epoch (wall-clock time, for timestamped names), or 0 if unknown.
    fn unix_time(&self) -> f64;
    /// Threads for checking schedules in parallel; `None` (the default) when the host has
    /// none, and checks then run a single worker.
    fn threads(&self) -> Option<Threads> {
        None
    }
    /// Opens live observation inputs (`--live`). The default reads them one after another,
    /// stdin through [`Host::read_stdin_line`] and files to their current end; hosts that
    /// can wait on several streams at once override it.
    fn open_live(&self, inputs: &[LiveInput]) -> Box<dyn LiveSource + '_> {
        Box::new(SequentialLive { host: self, inputs: inputs.to_vec(), current: 0, lines: None })
    }
}

/// One `--live` input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LiveInput {
    /// `-`: standard input.
    Stdin,
    /// A file, named pipe or other readable path (absolute).
    Path(PathBuf),
}

/// [`Host::open_live`]'s default: each input in turn, to its end.
struct SequentialLive<'a, H: Host + ?Sized> {
    host: &'a H,
    inputs: Vec<LiveInput>,
    current: usize,
    /// The remaining lines of the current file input.
    lines: Option<std::vec::IntoIter<String>>,
}

impl<H: Host + ?Sized> LiveSource for SequentialLive<'_, H> {
    fn next(&mut self) -> LiveRead {
        let input = self.current;
        let line = match self.inputs.get(input) {
            None => return LiveRead::End { input },
            Some(LiveInput::Stdin) => self.host.read_stdin_line(),
            Some(LiveInput::Path(p)) => {
                if self.lines.is_none() {
                    match self.host.read_to_string(p) {
                        Ok(text) => {
                            let lines: Vec<String> = text.lines().map(String::from).collect();
                            self.lines = Some(lines.into_iter());
                        }
                        Err(e) => return LiveRead::Error { input, error: e.to_string() },
                    }
                }
                Ok(self.lines.as_mut().and_then(|l| l.next()))
            }
        };
        match line {
            Ok(Some(line)) => LiveRead::Line { input, line },
            Ok(None) => {
                self.current += 1;
                self.lines = None;
                LiveRead::End { input }
            }
            Err(e) => LiveRead::Error { input, error: e.to_string() },
        }
    }
}

/// Work for a thread of [`Threads::run`].
pub type Job<'a> = Box<dyn FnOnce() + Send + 'a>;

/// A host's threads (see [`Host::threads`]).
#[derive(Debug, Clone, Copy)]
pub struct Threads {
    /// How many workers `snappea check` uses by default (one per CPU core).
    pub available: usize,
    /// Runs each job on its own thread and `main` on the calling thread; returns once all
    /// have finished.
    pub run: for<'a> fn(jobs: Vec<Job<'a>>, main: &mut (dyn FnMut() + 'a)),
}

/// A command stopped after reporting the problem on the console; holds the exit code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Exit(pub i32);

/// Prints `Error: {msg}` on stderr; returns exit code 1.
pub(crate) fn report_and_exit(host: &mut dyn Host, msg: &str) -> Exit {
    host.write(Stream::Err, "Error: ", Some(Color::Red));
    host.write(Stream::Err, msg, Some(Color::Yellow));
    host.write(Stream::Err, "\n", None);
    Exit(1)
}

/// Writes an output file the command has announced (`..... Writing {path}`), `path` being
/// relative to the current directory or absolute. A failure is reported as
/// `Error: Could not write file ...` with exit code 1.
pub(crate) fn write_output(host: &mut dyn Host, path: &str, contents: &str) -> Result<(), Exit> {
    let full = full_path(&host.cwd(), Path::new(path));
    host.write_file(&full, contents)
        .map_err(|e| report_and_exit(host, &format!("Could not write file '{}': {}", path, e)))
}

/// Convenience console helpers.
pub trait HostExt: Host {
    fn out_line(&mut self, s: &str) {
        self.write(Stream::Out, s, None);
        self.write(Stream::Out, "\n", None);
    }
    fn out_colored_line(&mut self, s: &str, c: Color) {
        self.write(Stream::Out, s, Some(c));
        self.write(Stream::Out, "\n", None);
    }
}

impl<T: Host + ?Sized> HostExt for T {}

/// A host that holds back console output, to show it (or its errors) only if needed.
#[cfg(feature = "cli")]
pub(crate) struct Buffered<'a> {
    pub inner: &'a mut dyn Host,
    pub out: Vec<(Stream, String, Option<Color>)>,
}

#[cfg(feature = "cli")]
impl<'a> Buffered<'a> {
    pub fn new(inner: &'a mut dyn Host) -> Self {
        Buffered { inner, out: Vec::new() }
    }

    /// The text written to stderr so far.
    pub fn errors(&self) -> String {
        self.out.iter().filter(|(s, ..)| *s == Stream::Err).map(|(_, t, _)| t.as_str()).collect()
    }
}

#[cfg(feature = "cli")]
impl Host for Buffered<'_> {
    fn write(&mut self, stream: Stream, text: &str, color: Option<Color>) {
        self.out.push((stream, text.to_string(), color));
    }
    fn cwd(&self) -> PathBuf {
        self.inner.cwd()
    }
    fn read_to_string(&self, path: &Path) -> io::Result<String> {
        self.inner.read_to_string(path)
    }
    fn write_file(&mut self, path: &Path, contents: &str) -> io::Result<()> {
        self.inner.write_file(path, contents)
    }
    fn is_file(&self, path: &Path) -> bool {
        self.inner.is_file(path)
    }
    fn is_dir(&self, path: &Path) -> bool {
        self.inner.is_dir(path)
    }
    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
        self.inner.read_dir(path)
    }
    fn create_dir_all(&mut self, path: &Path) -> io::Result<()> {
        self.inner.create_dir_all(path)
    }
    fn remove_dir_all(&mut self, path: &Path) -> io::Result<()> {
        self.inner.remove_dir_all(path)
    }
    fn remove_file(&mut self, path: &Path) -> io::Result<()> {
        self.inner.remove_file(path)
    }
    fn rename(&mut self, from: &Path, to: &Path) -> io::Result<()> {
        self.inner.rename(from, to)
    }
    fn now(&self) -> f64 {
        self.inner.now()
    }
    fn max_memory_gb(&self) -> f64 {
        self.inner.max_memory_gb()
    }
    fn random_seed(&mut self) -> u32 {
        self.inner.random_seed()
    }
    fn unix_time(&self) -> f64 {
        self.inner.unix_time()
    }
    fn threads(&self) -> Option<Threads> {
        self.inner.threads()
    }
}

/// A host that shows only warnings and errors: stderr, and the stdout text the commands
/// color (upstream's console colors every warning and error, never progress). Plain stdout
/// text is dropped, unless `quiet` is off.
#[cfg(feature = "cli")]
pub(crate) struct Quiet<'a> {
    pub inner: &'a mut dyn Host,
    pub quiet: bool,
    /// The last stdout text was shown, so the newline ending it is too.
    shown: bool,
}

#[cfg(feature = "cli")]
impl<'a> Quiet<'a> {
    pub fn new(inner: &'a mut dyn Host, quiet: bool) -> Self {
        Quiet { inner, quiet, shown: false }
    }
}

#[cfg(feature = "cli")]
impl Host for Quiet<'_> {
    fn write(&mut self, stream: Stream, text: &str, color: Option<Color>) {
        if stream == Stream::Err || !self.quiet {
            return self.inner.write(stream, text, color);
        }
        if color.is_some() || (self.shown && text == "\n") {
            self.shown = true;
            self.inner.write(stream, text, color);
        } else {
            self.shown = false;
        }
    }
    fn read_stdin_line(&self) -> io::Result<Option<String>> {
        self.inner.read_stdin_line()
    }
    fn cwd(&self) -> PathBuf {
        self.inner.cwd()
    }
    fn read_to_string(&self, path: &Path) -> io::Result<String> {
        self.inner.read_to_string(path)
    }
    fn write_file(&mut self, path: &Path, contents: &str) -> io::Result<()> {
        self.inner.write_file(path, contents)
    }
    fn is_file(&self, path: &Path) -> bool {
        self.inner.is_file(path)
    }
    fn is_dir(&self, path: &Path) -> bool {
        self.inner.is_dir(path)
    }
    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
        self.inner.read_dir(path)
    }
    fn create_dir_all(&mut self, path: &Path) -> io::Result<()> {
        self.inner.create_dir_all(path)
    }
    fn remove_dir_all(&mut self, path: &Path) -> io::Result<()> {
        self.inner.remove_dir_all(path)
    }
    fn remove_file(&mut self, path: &Path) -> io::Result<()> {
        self.inner.remove_file(path)
    }
    fn rename(&mut self, from: &Path, to: &Path) -> io::Result<()> {
        self.inner.rename(from, to)
    }
    fn now(&self) -> f64 {
        self.inner.now()
    }
    fn max_memory_gb(&self) -> f64 {
        self.inner.max_memory_gb()
    }
    fn random_seed(&mut self) -> u32 {
        self.inner.random_seed()
    }
    fn unix_time(&self) -> f64 {
        self.inner.unix_time()
    }
    fn threads(&self) -> Option<Threads> {
        self.inner.threads()
    }
    fn open_live(&self, inputs: &[LiveInput]) -> Box<dyn LiveSource + '_> {
        self.inner.open_live(inputs)
    }
}

/// A host's file system, for expanding log paths and globs.
#[cfg(feature = "cli")]
pub(crate) struct HostFiles<'a>(pub &'a dyn Host);

#[cfg(feature = "cli")]
impl crate::checker::observe_inputs::LogFiles for HostFiles<'_> {
    fn is_file(&self, path: &Path) -> bool {
        self.0.is_file(path)
    }
    fn is_dir(&self, path: &Path) -> bool {
        self.0.is_dir(path)
    }
    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
        self.0.read_dir(path)
    }
    fn read_to_string(&self, path: &Path) -> io::Result<String> {
        self.0.read_to_string(path)
    }
}

/// `Path.GetFullPath`: makes `p` absolute against `cwd` and resolves `.`/`..` lexically.
pub fn full_path(cwd: &Path, p: &Path) -> PathBuf {
    let joined = if p.is_absolute() { p.to_path_buf() } else { cwd.join(p) };
    normalize(&joined)
}

/// Lexically resolves `.` and `..` components.
pub fn normalize(p: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for c in p.components() {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                out.pop();
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// `Path.GetRelativePath(from, to)` for absolute, normalized paths.
pub fn relative_path(from: &Path, to: &Path) -> String {
    let f: Vec<_> = from.components().collect();
    let t: Vec<_> = to.components().collect();
    let common = f.iter().zip(t.iter()).take_while(|(a, b)| a == b).count();
    if common == 0 {
        return to.to_string_lossy().to_string();
    }
    let mut parts: Vec<String> = Vec::new();
    for _ in common..f.len() {
        parts.push("..".into());
    }
    for c in &t[common..] {
        parts.push(c.as_os_str().to_string_lossy().to_string());
    }
    if parts.is_empty() {
        ".".into()
    } else {
        parts.join("/")
    }
}

/// Whether a file name is hidden the way .NET reports it on Unix (leading dot).
pub fn is_hidden(p: &Path) -> bool {
    p.file_name().and_then(|n| n.to_str()).map(|n| n.starts_with('.')).unwrap_or(false)
}

#[derive(Debug, Clone)]
enum Node {
    Dir,
    File(String),
}

/// An in-memory host: a virtual file system plus captured console output. Memory use and
/// wall-clock time read as 0.
#[derive(Debug, Clone)]
pub struct MemHost {
    nodes: BTreeMap<PathBuf, Node>,
    pub cwd: PathBuf,
    pub stdout: String,
    pub stderr: String,
    /// [`Host::now`]; always 0 by default.
    pub clock: fn() -> f64,
    /// [`Host::random_seed`].
    pub seed: u32,
    /// [`Host::threads`]; `None` by default.
    pub threads: Option<Threads>,
}

impl Default for MemHost {
    fn default() -> Self {
        MemHost::new("/work")
    }
}

impl MemHost {
    pub fn new(cwd: &str) -> MemHost {
        let mut h = MemHost {
            nodes: BTreeMap::new(),
            cwd: PathBuf::from(cwd),
            stdout: String::new(),
            stderr: String::new(),
            clock: || 0.0,
            seed: 0,
            threads: None,
        };
        h.create_dir_all(Path::new(cwd)).expect("an empty file system has no files in the way");
        h
    }

    fn abs(&self, p: &Path) -> PathBuf {
        full_path(&self.cwd, p)
    }

    /// Adds a file (creating parent directories), path relative to the cwd or absolute.
    ///
    /// # Panics
    ///
    /// If the file cannot be written (a directory is in the way, or a file where a parent
    /// directory should be).
    pub fn add_file(&mut self, path: &str, contents: &str) {
        if let Err(e) = self.write_file(Path::new(path), contents) {
            panic!("cannot add {}: {}", path, e);
        }
    }

    /// All files under `dir` (absolute paths).
    pub fn files_under(&self, dir: &str) -> Vec<PathBuf> {
        let d = self.abs(Path::new(dir));
        self.nodes
            .iter()
            .filter(|(p, n)| matches!(n, Node::File(_)) && p.starts_with(&d))
            .map(|(p, _)| p.clone())
            .collect()
    }
}

fn not_found(p: &Path) -> io::Error {
    io::Error::new(io::ErrorKind::NotFound, format!("Could not find a part of the path '{}'.", p.display()))
}

fn is_a_directory(p: &Path) -> io::Error {
    io::Error::other(format!("Is a directory: '{}'", p.display()))
}

fn not_a_directory(p: &Path) -> io::Error {
    io::Error::other(format!("Not a directory: '{}'", p.display()))
}

impl Host for MemHost {
    fn write(&mut self, stream: Stream, text: &str, _color: Option<Color>) {
        match stream {
            Stream::Out => self.stdout.push_str(text),
            Stream::Err => self.stderr.push_str(text),
        }
    }

    fn cwd(&self) -> PathBuf {
        self.cwd.clone()
    }

    fn read_to_string(&self, path: &Path) -> io::Result<String> {
        match self.nodes.get(&self.abs(path)) {
            Some(Node::File(s)) => Ok(s.clone()),
            Some(Node::Dir) => Err(is_a_directory(path)),
            None => Err(not_found(path)),
        }
    }

    fn write_file(&mut self, path: &Path, contents: &str) -> io::Result<()> {
        let p = self.abs(path);
        if let Some(Node::Dir) = self.nodes.get(&p) {
            return Err(is_a_directory(path));
        }
        if let Some(parent) = p.parent() {
            self.create_dir_all(parent)?;
        }
        self.nodes.insert(p, Node::File(contents.to_string()));
        Ok(())
    }

    fn is_file(&self, path: &Path) -> bool {
        matches!(self.nodes.get(&self.abs(path)), Some(Node::File(_)))
    }

    fn is_dir(&self, path: &Path) -> bool {
        matches!(self.nodes.get(&self.abs(path)), Some(Node::Dir))
    }

    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
        let d = self.abs(path);
        if !self.is_dir(&d) {
            return Err(not_found(path));
        }
        Ok(self.nodes.keys().filter(|p| p.parent() == Some(d.as_path())).cloned().collect())
    }

    fn create_dir_all(&mut self, path: &Path) -> io::Result<()> {
        let p = self.abs(path);
        let mut cur = PathBuf::new();
        for c in p.components() {
            cur.push(c.as_os_str());
            if let Some(Node::File(_)) = self.nodes.get(&cur) {
                return Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("File exists: '{}'", cur.display())));
            }
            self.nodes.entry(cur.clone()).or_insert(Node::Dir);
        }
        Ok(())
    }

    fn remove_dir_all(&mut self, path: &Path) -> io::Result<()> {
        let p = self.abs(path);
        match self.nodes.get(&p) {
            Some(Node::Dir) => {
                self.nodes.retain(|k, _| !k.starts_with(&p));
                Ok(())
            }
            Some(Node::File(_)) => Err(not_a_directory(path)),
            None => Err(not_found(path)),
        }
    }

    fn remove_file(&mut self, path: &Path) -> io::Result<()> {
        let p = self.abs(path);
        match self.nodes.get(&p) {
            Some(Node::File(_)) => {
                self.nodes.remove(&p);
                Ok(())
            }
            Some(Node::Dir) => Err(is_a_directory(path)),
            None => Err(not_found(path)),
        }
    }

    fn rename(&mut self, from: &Path, to: &Path) -> io::Result<()> {
        let f = self.abs(from);
        let t = self.abs(to);
        if !self.nodes.contains_key(&f) {
            return Err(not_found(from));
        }
        let moved: Vec<(PathBuf, Node)> =
            self.nodes.iter().filter(|(k, _)| k.starts_with(&f)).map(|(k, v)| (k.clone(), v.clone())).collect();
        self.nodes.retain(|k, _| !k.starts_with(&f));
        for (k, v) in moved {
            let rel = k.strip_prefix(&f).unwrap().to_path_buf();
            let dest = if rel.as_os_str().is_empty() { t.clone() } else { t.join(rel) };
            self.nodes.insert(dest, v);
        }
        Ok(())
    }

    fn now(&self) -> f64 {
        (self.clock)()
    }

    fn max_memory_gb(&self) -> f64 {
        0.0
    }

    fn random_seed(&mut self) -> u32 {
        self.seed
    }

    fn unix_time(&self) -> f64 {
        0.0
    }

    fn threads(&self) -> Option<Threads> {
        self.threads
    }
}