flow-span 0.1.0-rc.5

Source positions, source files, the identifier interner, and the places in a run.
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
//! Places in a run (`history.md`, *Identity*; `runs.md`, *Places in a run*):
//! a run's id, a task's path, a call's id and a moment in one task.
//!
//! A run's id is 128 bits written as 32 lowercase hexadecimal digits. The
//! other three share one grammar:
//!
//! ```text
//! [p<segment>:]<task>[#<count>[+<steps>]]
//! task = root ( /<spawn> )*
//! ```
//!
//! A [`TaskPath`] is the task alone. A [`CallRef`] adds the call's count and
//! may carry its segment. A [`Moment`] adds the count of calls answered and
//! the steps since. A segment, a spawn and a call's count are numbers from
//! 1, while a moment's count and steps are numbers from 0. Every number is
//! written in decimal with no sign and no leading zero and fits in 64 bits.
//! Segment 0, the run's first, has no prefix. Each type reads exactly the
//! text its `Display` writes, so a place is checked once, where text becomes
//! one, and is a place from then on.

use std::fmt;
use std::num::NonZeroU64;
use std::str::FromStr;

/// How many digits a run id has.
const DIGITS: usize = 32;

/// How many of its digits a run id is shown to a person with
/// (`guides/cli.md`).
const SHOWN: usize = 12;

/// The count `n`, which counts from 1: a spawn's or a call's, as a test
/// writes it.
///
/// # Panics
///
/// When `n` is 0.
#[cfg(any(test, feature = "test-support"))]
#[must_use]
pub fn count(n: u64) -> NonZeroU64 {
    NonZeroU64::new(n).expect("a count from 1")
}

/// A run's id: 128 bits, written as exactly 32 lowercase hexadecimal digits.
/// Text becomes one only through [`RunId::parse`], so an id read from a
/// history, a frame or a command line that has any other form is refused
/// where it is read. Ids order as their written digits do. It keeps its
/// digits beside its bits, so it is `Copy` and lends them as text without
/// allocating.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RunId {
    bits: u128,
    digits: [u8; DIGITS],
}

impl RunId {
    /// The run id `text` is.
    ///
    /// # Errors
    ///
    /// A [`ParsePlaceError`] when `text` is not exactly 32 lowercase
    /// hexadecimal digits.
    pub fn parse(text: &str) -> Result<RunId, ParsePlaceError> {
        let digits =
            text.len() == DIGITS && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
        match u128::from_str_radix(text, 16) {
            Ok(bits) if digits => Ok(RunId::of(bits)),
            _ => Err(ParsePlaceError::new(PlaceKind::Run, text)),
        }
    }

    /// The id made of `bits`, as a minted id is written.
    #[must_use]
    pub fn from_bits(bits: [u8; 16]) -> RunId {
        RunId::of(u128::from_be_bytes(bits))
    }

    /// Its 16 bits, most significant byte first, as [`RunId::from_bits`]
    /// reads them.
    #[must_use]
    pub fn bits(&self) -> [u8; 16] {
        self.bits.to_be_bytes()
    }

    /// The id of `bits`, its digits written once.
    fn of(bits: u128) -> RunId {
        const HEX: &[u8; 16] = b"0123456789abcdef";
        let mut digits = [0_u8; DIGITS];
        for (place, digit) in digits.iter_mut().enumerate() {
            let shift = 4 * (DIGITS - 1 - place);
            *digit = HEX[usize::from(u8::try_from((bits >> shift) & 0xf).unwrap_or(0))];
        }
        RunId { bits, digits }
    }

    /// The id whose digits are `n` written in hexadecimal and padded with
    /// zeros: a fixed id for tests, never a minted one.
    #[cfg(any(test, feature = "test-support"))]
    #[must_use]
    pub fn example(n: u128) -> RunId {
        RunId::of(n)
    }

    /// Its 32 digits.
    ///
    /// # Panics
    ///
    /// Never: an id's digits are written from `0-9a-f` alone.
    #[must_use]
    pub fn as_str(&self) -> &str {
        std::str::from_utf8(&self.digits).expect("a run id's digits are ASCII")
    }

    /// Its first 12 digits, as it is shown to a person.
    #[must_use]
    pub fn shown(&self) -> &str {
        &self.as_str()[..SHOWN]
    }
}

impl fmt::Display for RunId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl fmt::Debug for RunId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "RunId({self})")
    }
}

/// Which task a call came from: its parent's path plus the parent's count of
/// spawns at the moment it was spawned (`history.md`, *Identity*).
///
/// The root task's path is empty and is written `root`; its first child is
/// `root/1`. Counters never restart: a task spawned after a checkpoint has
/// the path a replay from fact 1 gives it.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct TaskPath {
    counts: Vec<NonZeroU64>,
}

impl TaskPath {
    /// The root task.
    #[must_use]
    pub fn root() -> TaskPath {
        TaskPath::new(Vec::new())
    }

    /// The task whose spawn counts from the root down are `counts`.
    #[must_use]
    pub fn new(counts: Vec<NonZeroU64>) -> TaskPath {
        TaskPath { counts }
    }

    /// The task this one spawned as its `count`th spawn.
    #[must_use]
    pub fn child(&self, count: NonZeroU64) -> TaskPath {
        let mut counts = self.counts.clone();
        counts.push(count);
        TaskPath::new(counts)
    }

    /// The spawn counts from the root down, empty for the root.
    #[must_use]
    pub fn counts(&self) -> &[NonZeroU64] {
        &self.counts
    }

    /// The task path `text` writes: `root`, then `/` and a spawn count any
    /// number of times.
    ///
    /// # Errors
    ///
    /// A [`ParsePlaceError`] when `text` is any other text.
    pub fn parse(text: &str) -> Result<TaskPath, ParsePlaceError> {
        match Written::read(text) {
            Some(Written {
                segment: None,
                task,
                count: None,
            }) => Ok(task),
            _ => Err(ParsePlaceError::new(PlaceKind::Task, text)),
        }
    }
}

impl fmt::Display for TaskPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("root")?;
        for count in &self.counts {
            write!(f, "/{count}")?;
        }
        Ok(())
    }
}

/// A Tool call's id (`history.md`, *Identity*): the segment it was first
/// recorded in, its task and the task's count of Tool calls, written
/// `root/1#4` in the first segment and `p1:root/1#4` in the second.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CallRef {
    segment: u64,
    task: TaskPath,
    index: NonZeroU64,
}

impl CallRef {
    /// The call `index` of `task`, first recorded in `segment`, 0 for the
    /// run's first.
    #[must_use]
    pub fn new(segment: u64, task: TaskPath, index: NonZeroU64) -> CallRef {
        CallRef {
            segment,
            task,
            index,
        }
    }

    /// The call `index` of `task` in the run's first segment: a call's
    /// position.
    #[must_use]
    pub fn first(task: TaskPath, index: NonZeroU64) -> CallRef {
        CallRef::new(0, task, index)
    }

    /// The call id `text` writes: an optional segment `pK:`, a task path,
    /// `#`, then the task's count of Tool calls.
    ///
    /// # Errors
    ///
    /// A [`ParsePlaceError`] when `text` is any other text.
    pub fn parse(text: &str) -> Result<CallRef, ParsePlaceError> {
        let refused = || ParsePlaceError::new(PlaceKind::Call, text);
        match Written::read(text).ok_or_else(refused)? {
            Written {
                segment,
                task,
                count: Some((index, None)),
            } => Ok(CallRef::new(
                segment.map_or(0, NonZeroU64::get),
                task,
                NonZeroU64::new(index).ok_or_else(refused)?,
            )),
            Written { .. } => Err(refused()),
        }
    }

    /// The segment the call was first recorded in, 0 for the run's first.
    #[must_use]
    pub fn segment(&self) -> u64 {
        self.segment
    }

    /// The task that made the call.
    #[must_use]
    pub fn task(&self) -> &TaskPath {
        &self.task
    }

    /// The task's count of Tool calls, this one included: 1 for its first.
    #[must_use]
    pub fn index(&self) -> NonZeroU64 {
        self.index
    }

    /// The call's position: its task and count, in the first segment.
    #[must_use]
    pub fn position(&self) -> CallRef {
        CallRef::first(self.task.clone(), self.index)
    }
}

impl fmt::Display for CallRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_segment(f, self.segment)?;
        write!(f, "{}#{}", self.task, self.index)
    }
}

impl fmt::Debug for CallRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "CallRef({self})")
    }
}

/// A place in one task's evaluation (`runs.md`, *Places in a run*): the
/// segment whose program is evaluating, the task, the count of its calls
/// whose answers were handed to it, and the steps it has taken since,
/// written `root/2#4+17` or `p1:root#4+5`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Moment {
    /// The segment, 0 for the run's first.
    pub segment: u64,
    /// The task.
    pub task: TaskPath,
    /// The index of its last call whose answer was handed to it; 0 before
    /// its first.
    pub call: u64,
    /// Its steps since: 0 is the call's own step, or the task's start.
    pub steps: u64,
}

impl Moment {
    /// The moment `text` writes: a call's id whose count may be 0, `+`,
    /// then the steps.
    ///
    /// # Errors
    ///
    /// A [`ParsePlaceError`] when `text` is any other text.
    pub fn parse(text: &str) -> Result<Moment, ParsePlaceError> {
        match Written::read(text) {
            Some(Written {
                segment,
                task,
                count: Some((call, Some(steps))),
            }) => Ok(Moment {
                segment: segment.map_or(0, NonZeroU64::get),
                task,
                call,
                steps,
            }),
            _ => Err(ParsePlaceError::new(PlaceKind::Moment, text)),
        }
    }
}

impl fmt::Display for Moment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_segment(f, self.segment)?;
        write!(f, "{}#{}+{}", self.task, self.call, self.steps)
    }
}

/// A segment's prefix: `pK:` for segment `K` after the first, nothing for
/// the first.
fn write_segment(f: &mut fmt::Formatter<'_>, segment: u64) -> fmt::Result {
    if segment > 0 {
        write!(f, "p{segment}:")?;
    }
    Ok(())
}

/// The parts of the grammar a text writes, each read once.
struct Written {
    /// The segment its `pK:` prefix names, if it has one.
    segment: Option<NonZeroU64>,
    /// The task.
    task: TaskPath,
    /// The number after `#`, and the steps after `+`, if written.
    count: Option<(u64, Option<u64>)>,
}

impl Written {
    /// The parts `text` writes, or `None` when it follows no part of the
    /// grammar.
    fn read(text: &str) -> Option<Written> {
        let (segment, rest) = match text.strip_prefix('p') {
            Some(prefixed) => {
                let (segment, rest) = prefixed.split_once(':')?;
                (Some(NonZeroU64::new(number(segment)?)?), rest)
            }
            None => (None, text),
        };
        let (task, count) = match rest.split_once('#') {
            Some((task, count)) => (task, Some(count)),
            None => (rest, None),
        };
        let counts = match task.strip_prefix("root")? {
            "" => Vec::new(),
            spawns => spawns
                .strip_prefix('/')?
                .split('/')
                .map(|count| NonZeroU64::new(number(count)?))
                .collect::<Option<_>>()?,
        };
        let count = match count {
            None => None,
            Some(count) => Some(match count.split_once('+') {
                None => (number(count)?, None),
                Some((count, steps)) => (number(count)?, Some(number(steps)?)),
            }),
        };
        Some(Written {
            segment,
            task: TaskPath::new(counts),
            count,
        })
    }
}

/// The number `text` writes in decimal with no sign and no leading zero,
/// within 64 bits.
fn number(text: &str) -> Option<u64> {
    let n: u64 = text.parse().ok()?;
    (n.to_string() == text).then_some(n)
}

/// What a text was read as.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PlaceKind {
    /// A [`RunId`].
    Run,
    /// A [`TaskPath`].
    Task,
    /// A [`CallRef`].
    Call,
    /// A [`Moment`].
    Moment,
}

impl PlaceKind {
    /// What the kind is and how it is written.
    const fn written(self) -> &'static str {
        match self {
            PlaceKind::Run => "a run id: an id is 32 lowercase hexadecimal digits",
            PlaceKind::Task => "a task id, such as root or root/2/1",
            PlaceKind::Call => "a call id, such as root#1, root/2#3 or p1:root#6",
            PlaceKind::Moment => "a moment, such as root#0+3, root/2#4+17 or p1:root#4+5",
        }
    }
}

/// Text that is not the place it was read as, as it was given.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ParsePlaceError {
    kind: PlaceKind,
    text: String,
}

impl ParsePlaceError {
    fn new(kind: PlaceKind, text: &str) -> ParsePlaceError {
        ParsePlaceError {
            kind,
            text: text.to_owned(),
        }
    }

    /// What the text was read as.
    #[must_use]
    pub fn kind(&self) -> PlaceKind {
        self.kind
    }

    /// The text, as it was given.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }
}

impl fmt::Display for ParsePlaceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "`{}` is not {}",
            self.text.escape_debug(),
            self.kind.written()
        )
    }
}

impl std::error::Error for ParsePlaceError {}

/// `FromStr` through the type's `parse`, and serde as the text its
/// `Display` writes: one form for each place, read and written.
macro_rules! written_as_text {
    ($($place:ty),+) => {$(
        impl FromStr for $place {
            type Err = ParsePlaceError;

            fn from_str(text: &str) -> Result<$place, ParsePlaceError> {
                <$place>::parse(text)
            }
        }

        impl serde::Serialize for $place {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.collect_str(self)
            }
        }

        impl<'de> serde::Deserialize<'de> for $place {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<$place, D::Error> {
                let text = String::deserialize(deserializer)?;
                <$place>::parse(&text).map_err(serde::de::Error::custom)
            }
        }
    )+};
}

written_as_text!(RunId, TaskPath, CallRef, Moment);

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests;