haz-domain 0.2.0

Shared domain types for the haz task runner (identifiers, paths, errors).
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! Task references: the textual form used to identify one or more
//! tasks across the workspace.
//!
//! Six syntactic forms exist (per `REF-002`..`REF-005`, `REF-008`):
//!
//! - `~:<task>`: same-project reference,
//! - `<project>:<task>`: project reference,
//! - `^:<task>`: fan-out reference,
//! - `^~:<task>`: sibling-fan-out reference,
//! - `[<tag>]:<task>`: tag reference,
//! - `[<tag>]~:<task>`: sibling-tag reference.
//!
//! The sibling-modifier forms (`^~:` and `[<tag>]~:`) exclude the
//! bearing project from the otherwise-included fan-out resolution.
//!
//! Each name component (project, tag, task) is a validated
//! identifier per [`crate::name`]. Parsing checks only syntactic
//! validity (`REF-001`..`REF-008`); resolution against the
//! workspace happens later.

use std::fmt;

use snafu::{ResultExt, Snafu, ensure};

use crate::name::{NameError, ProjectName, TagName, TaskName};

/// Which name component of a task reference failed validation.
///
/// Used as a field of [`TaskRefError::InvalidName`] so a single
/// variant covers `REF-001` violations across all four reference
/// forms without sacrificing diagnostic detail.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NameComponent {
    /// The project name in a [`TaskRef::Project`] reference.
    Project,
    /// The tag name in a [`TaskRef::Tag`] reference.
    Tag,
    /// The task name in any reference form.
    Task,
}

impl fmt::Display for NameComponent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            NameComponent::Project => "project",
            NameComponent::Tag => "tag",
            NameComponent::Task => "task",
        };
        f.write_str(s)
    }
}

/// Error produced when parsing a [`TaskRef`].
///
/// Each variant maps to either the grammar (`REF-002`..`REF-006`)
/// or to identifier inheritance (`REF-001`).
#[derive(Debug, Clone, PartialEq, Eq, Snafu)]
pub enum TaskRefError {
    /// Violates the grammar: the input is empty.
    #[snafu(display("task reference is empty"))]
    EmptyInput,

    /// Violates `REF-006` for the project-reference form: the input
    /// has no leading sigil and contains no `:` separator.
    #[snafu(display("task reference has no `:` separator"))]
    MissingColon,

    /// Violates the grammar for the tag-reference form (`REF-005` /
    /// `REF-006`): the input begins with `[` but is missing the
    /// closing `]` or the `:` that must follow it.
    #[snafu(display("tag reference malformed: missing `]` or `:` after `]`"))]
    MalformedTagBrackets,

    /// Violates `REF-001`: a name component fails the identifier
    /// rules `ID-001`..`ID-003`.
    #[snafu(display("invalid {component} name: {source}"))]
    InvalidName {
        /// Which component (project, tag, or task) failed.
        component: NameComponent,
        /// The underlying identifier error.
        source: NameError,
    },
}

/// A validated task reference.
///
/// Construction is via [`TaskRef::parse`]. The [`fmt::Display`]
/// implementation produces a string that round-trips through
/// [`TaskRef::parse`].
///
/// # Examples
///
/// ```
/// use haz_domain::task_ref::TaskRef;
///
/// let r = TaskRef::parse("~:compile").unwrap();
/// assert_eq!(r.to_string(), "~:compile");
///
/// let r = TaskRef::parse("[typescript]:compile").unwrap();
/// assert_eq!(r.to_string(), "[typescript]:compile");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TaskRef {
    /// `~:<task>`. Resolves within the bearing project (`REF-002`).
    SameProject(TaskName),
    /// `<project>:<task>`. Resolves to a task in the named project
    /// (`REF-003`).
    Project(ProjectName, TaskName),
    /// `^:<task>`. Resolves to every task with this name across the
    /// workspace, including the bearing project (`REF-004`).
    FanOut(TaskName),
    /// `^~:<task>`. Resolves to every task with this name across the
    /// workspace *except the bearing project* (`REF-008`).
    SiblingFanOut(TaskName),
    /// `[<tag>]:<task>`. Resolves to every task with this name
    /// whose project carries the named tag, including the bearing
    /// project (`REF-005`).
    Tag(TagName, TaskName),
    /// `[<tag>]~:<task>`. Resolves to every task with this name
    /// whose project carries the named tag, *excluding the bearing
    /// project* even if it carries the named tag (`REF-008`).
    SiblingTag(TagName, TaskName),
}

impl TaskRef {
    /// Parse `s` as a [`TaskRef`].
    ///
    /// Dispatch follows `REF-006`: at most three characters of
    /// lookahead for `^`-prefixed forms, plus scanning past the
    /// closing `]` for tag forms.
    ///
    /// # Errors
    ///
    /// Returns a [`TaskRefError`] when `s` violates the grammar
    /// (`REF-002`..`REF-006`, `REF-008`) or when any name component
    /// violates the identifier rules (`REF-001`, delegating to
    /// `ID-001`..`ID-003`):
    ///
    /// - [`TaskRefError::EmptyInput`] if `s` is the empty string.
    /// - [`TaskRefError::MissingColon`] if `s` is a project
    ///   reference with no `:` separator.
    /// - [`TaskRefError::MalformedTagBrackets`] if `s` begins with
    ///   `[` but is not a well-formed `[<tag>]:<task>` or
    ///   `[<tag>]~:<task>`.
    /// - [`TaskRefError::InvalidName`] if any name component is
    ///   not a valid identifier.
    ///
    /// # Examples
    ///
    /// ```
    /// use haz_domain::task_ref::TaskRef;
    ///
    /// assert!(TaskRef::parse("~:compile").is_ok());
    /// assert!(TaskRef::parse("lib_core:compile").is_ok());
    /// assert!(TaskRef::parse("^:compile").is_ok());
    /// assert!(TaskRef::parse("^~:compile").is_ok());
    /// assert!(TaskRef::parse("[typescript]:compile").is_ok());
    /// assert!(TaskRef::parse("[typescript]~:compile").is_ok());
    ///
    /// assert!(TaskRef::parse("").is_err());
    /// assert!(TaskRef::parse("compile").is_err());
    /// assert!(TaskRef::parse("[tag]compile").is_err());
    /// assert!(TaskRef::parse("[tag]~compile").is_err());
    /// ```
    pub fn parse(s: &str) -> Result<Self, TaskRefError> {
        ensure!(!s.is_empty(), EmptyInputSnafu);

        if let Some(rest) = s.strip_prefix("~:") {
            let task = TaskName::try_new(rest).context(InvalidNameSnafu {
                component: NameComponent::Task,
            })?;
            return Ok(TaskRef::SameProject(task));
        }

        // The sibling-fan-out form `^~:` must be tested before the
        // plain fan-out form `^:` (longer prefix wins).
        if let Some(rest) = s.strip_prefix("^~:") {
            let task = TaskName::try_new(rest).context(InvalidNameSnafu {
                component: NameComponent::Task,
            })?;
            return Ok(TaskRef::SiblingFanOut(task));
        }

        if let Some(rest) = s.strip_prefix("^:") {
            let task = TaskName::try_new(rest).context(InvalidNameSnafu {
                component: NameComponent::Task,
            })?;
            return Ok(TaskRef::FanOut(task));
        }

        if let Some(rest) = s.strip_prefix('[') {
            let close_idx = rest.find(']').ok_or(TaskRefError::MalformedTagBrackets)?;
            let (tag_str, after_close) = rest.split_at(close_idx);
            let after_bracket = &after_close[']'.len_utf8()..];

            // The character(s) following `]` decide between the
            // plain tag form `:` and the sibling-tag form `~:`.
            // The sibling-tag form must be tested first (longer
            // prefix wins).
            let (task_str, is_sibling) = if let Some(rest) = after_bracket.strip_prefix("~:") {
                (rest, true)
            } else if let Some(rest) = after_bracket.strip_prefix(':') {
                (rest, false)
            } else {
                return Err(TaskRefError::MalformedTagBrackets);
            };

            let tag = TagName::try_new(tag_str).context(InvalidNameSnafu {
                component: NameComponent::Tag,
            })?;
            let task = TaskName::try_new(task_str).context(InvalidNameSnafu {
                component: NameComponent::Task,
            })?;
            return Ok(if is_sibling {
                TaskRef::SiblingTag(tag, task)
            } else {
                TaskRef::Tag(tag, task)
            });
        }

        // Default: project reference `<project>:<task>` (REF-006).
        let colon_idx = s.find(':').ok_or(TaskRefError::MissingColon)?;
        let (proj_str, after_colon) = s.split_at(colon_idx);
        let task_str = &after_colon[':'.len_utf8()..];
        let project = ProjectName::try_new(proj_str).context(InvalidNameSnafu {
            component: NameComponent::Project,
        })?;
        let task = TaskName::try_new(task_str).context(InvalidNameSnafu {
            component: NameComponent::Task,
        })?;
        Ok(TaskRef::Project(project, task))
    }

    /// `true` if this is a same-project reference (`~:<task>`).
    #[must_use]
    pub fn is_same_project(&self) -> bool {
        matches!(self, TaskRef::SameProject(_))
    }

    /// `true` if this is a project reference (`<project>:<task>`).
    #[must_use]
    pub fn is_project(&self) -> bool {
        matches!(self, TaskRef::Project(_, _))
    }

    /// `true` if this is a fan-out reference (`^:<task>`).
    #[must_use]
    pub fn is_fan_out(&self) -> bool {
        matches!(self, TaskRef::FanOut(_))
    }

    /// `true` if this is a sibling-fan-out reference (`^~:<task>`).
    #[must_use]
    pub fn is_sibling_fan_out(&self) -> bool {
        matches!(self, TaskRef::SiblingFanOut(_))
    }

    /// `true` if this is a tag reference (`[<tag>]:<task>`).
    #[must_use]
    pub fn is_tag(&self) -> bool {
        matches!(self, TaskRef::Tag(_, _))
    }

    /// `true` if this is a sibling-tag reference (`[<tag>]~:<task>`).
    #[must_use]
    pub fn is_sibling_tag(&self) -> bool {
        matches!(self, TaskRef::SiblingTag(_, _))
    }
}

impl fmt::Display for TaskRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TaskRef::SameProject(task) => write!(f, "~:{task}"),
            TaskRef::Project(project, task) => write!(f, "{project}:{task}"),
            TaskRef::FanOut(task) => write!(f, "^:{task}"),
            TaskRef::SiblingFanOut(task) => write!(f, "^~:{task}"),
            TaskRef::Tag(tag, task) => write!(f, "[{tag}]:{task}"),
            TaskRef::SiblingTag(tag, task) => write!(f, "[{tag}]~:{task}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::name::NameError;
    use crate::task_ref::{NameComponent, TaskRef, TaskRefError};

    // REF-001: identifier inheritance. A few representative
    // violations across the four forms.

    #[test]
    fn ref_001_rejects_invalid_project_name() {
        assert!(matches!(
            TaskRef::parse("lib core:compile"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Project,
                source: NameError::InvalidChar { c: ' ' },
            })
        ));
    }

    #[test]
    fn ref_001_rejects_invalid_tag_name() {
        assert!(matches!(
            TaskRef::parse("[a b]:compile"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Tag,
                source: NameError::InvalidChar { c: ' ' },
            })
        ));
    }

    #[test]
    fn ref_001_rejects_invalid_task_name() {
        assert!(matches!(
            TaskRef::parse("~:foo bar"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::InvalidChar { c: ' ' },
            })
        ));
    }

    #[test]
    fn ref_001_rejects_empty_project_name() {
        assert!(matches!(
            TaskRef::parse(":compile"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Project,
                source: NameError::Empty,
            })
        ));
    }

    #[test]
    fn ref_001_rejects_empty_tag_name() {
        assert!(matches!(
            TaskRef::parse("[]:compile"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Tag,
                source: NameError::Empty,
            })
        ));
    }

    #[test]
    fn ref_001_rejects_empty_task_in_same_project() {
        assert!(matches!(
            TaskRef::parse("~:"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::Empty,
            })
        ));
    }

    #[test]
    fn ref_001_rejects_empty_task_in_fan_out() {
        assert!(matches!(
            TaskRef::parse("^:"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::Empty,
            })
        ));
    }

    #[test]
    fn ref_001_rejects_empty_task_in_project() {
        assert!(matches!(
            TaskRef::parse("lib:"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::Empty,
            })
        ));
    }

    #[test]
    fn ref_001_rejects_empty_task_in_tag() {
        assert!(matches!(
            TaskRef::parse("[typescript]:"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::Empty,
            })
        ));
    }

    // REF-002: same-project reference.

    #[test]
    fn ref_002_parses_same_project() {
        let r = TaskRef::parse("~:compile").unwrap();
        assert!(r.is_same_project());
        assert_eq!(r.to_string(), "~:compile");
    }

    #[test]
    fn ref_002_parses_same_project_with_underscore_and_dash() {
        let r = TaskRef::parse("~:test_unit-1").unwrap();
        assert!(matches!(r, TaskRef::SameProject(_)));
    }

    // REF-003: project reference.

    #[test]
    fn ref_003_parses_project() {
        let r = TaskRef::parse("lib_core:compile").unwrap();
        assert!(r.is_project());
        assert_eq!(r.to_string(), "lib_core:compile");
    }

    #[test]
    fn ref_003_parses_project_with_dash() {
        let r = TaskRef::parse("web-frontend:bundle").unwrap();
        assert!(matches!(r, TaskRef::Project(_, _)));
    }

    // REF-004: fan-out reference.

    #[test]
    fn ref_004_parses_fan_out() {
        let r = TaskRef::parse("^:compile").unwrap();
        assert!(r.is_fan_out());
        assert_eq!(r.to_string(), "^:compile");
    }

    // REF-005: tag reference.

    #[test]
    fn ref_005_parses_tag() {
        let r = TaskRef::parse("[typescript]:compile").unwrap();
        assert!(r.is_tag());
        assert_eq!(r.to_string(), "[typescript]:compile");
    }

    #[test]
    fn ref_005_parses_tag_with_dash() {
        let r = TaskRef::parse("[release]:publish").unwrap();
        assert!(matches!(r, TaskRef::Tag(_, _)));
    }

    // REF-008: sibling-fan-out and sibling-tag references.

    #[test]
    fn ref_008_parses_sibling_fan_out() {
        let r = TaskRef::parse("^~:compile").unwrap();
        assert!(r.is_sibling_fan_out());
        assert_eq!(r.to_string(), "^~:compile");
    }

    #[test]
    fn ref_008_parses_sibling_fan_out_with_underscore_and_dash() {
        let r = TaskRef::parse("^~:test_unit-1").unwrap();
        assert!(matches!(r, TaskRef::SiblingFanOut(_)));
    }

    #[test]
    fn ref_008_parses_sibling_tag() {
        let r = TaskRef::parse("[typescript]~:compile").unwrap();
        assert!(r.is_sibling_tag());
        assert_eq!(r.to_string(), "[typescript]~:compile");
    }

    #[test]
    fn ref_008_parses_sibling_tag_with_dash() {
        let r = TaskRef::parse("[release]~:publish").unwrap();
        assert!(matches!(r, TaskRef::SiblingTag(_, _)));
    }

    #[test]
    fn ref_008_rejects_empty_task_in_sibling_fan_out() {
        assert!(matches!(
            TaskRef::parse("^~:"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::Empty,
            })
        ));
    }

    #[test]
    fn ref_008_rejects_empty_task_in_sibling_tag() {
        assert!(matches!(
            TaskRef::parse("[typescript]~:"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::Empty,
            })
        ));
    }

    #[test]
    fn ref_008_rejects_invalid_task_in_sibling_fan_out() {
        assert!(matches!(
            TaskRef::parse("^~:foo bar"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::InvalidChar { c: ' ' },
            })
        ));
    }

    #[test]
    fn ref_008_rejects_invalid_tag_in_sibling_tag() {
        assert!(matches!(
            TaskRef::parse("[a b]~:compile"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Tag,
                source: NameError::InvalidChar { c: ' ' },
            })
        ));
    }

    #[test]
    fn ref_008_rejects_empty_tag_in_sibling_tag() {
        assert!(matches!(
            TaskRef::parse("[]~:compile"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Tag,
                source: NameError::Empty,
            })
        ));
    }

    // REF-006: dispatch by leading characters.

    #[test]
    fn ref_006_dispatch_same_project() {
        // `~:` always wins, even when the rest looks tag-like
        // (which would also fail ID-001 anyway).
        let r = TaskRef::parse("~:compile").unwrap();
        assert!(r.is_same_project());
    }

    #[test]
    fn ref_006_dispatch_fan_out() {
        let r = TaskRef::parse("^:compile").unwrap();
        assert!(r.is_fan_out());
    }

    #[test]
    fn ref_006_dispatch_sibling_fan_out() {
        // `^~:` must beat `^:` (longer prefix wins).
        let r = TaskRef::parse("^~:compile").unwrap();
        assert!(r.is_sibling_fan_out());
    }

    #[test]
    fn ref_006_dispatch_tag() {
        let r = TaskRef::parse("[t]:compile").unwrap();
        assert!(r.is_tag());
    }

    #[test]
    fn ref_006_dispatch_sibling_tag() {
        // The `~:` after `]` must beat the bare `:` (longer prefix
        // wins).
        let r = TaskRef::parse("[t]~:compile").unwrap();
        assert!(r.is_sibling_tag());
    }

    #[test]
    fn ref_006_dispatch_project_default() {
        let r = TaskRef::parse("p:t").unwrap();
        assert!(r.is_project());
    }

    #[test]
    fn ref_006_rejects_tilde_without_colon() {
        // `~compile` has no `:` at all; it falls through to the
        // project-reference branch which then fails MissingColon.
        assert!(matches!(
            TaskRef::parse("~compile"),
            Err(TaskRefError::MissingColon)
        ));
    }

    #[test]
    fn ref_006_rejects_caret_without_colon() {
        assert!(matches!(
            TaskRef::parse("^compile"),
            Err(TaskRefError::MissingColon)
        ));
    }

    #[test]
    fn ref_006_rejects_tag_missing_close_bracket() {
        assert!(matches!(
            TaskRef::parse("[tag"),
            Err(TaskRefError::MalformedTagBrackets)
        ));
    }

    #[test]
    fn ref_006_rejects_tag_missing_colon_after_close() {
        assert!(matches!(
            TaskRef::parse("[tag]compile"),
            Err(TaskRefError::MalformedTagBrackets)
        ));
    }

    #[test]
    fn ref_006_rejects_sibling_fan_out_without_colon() {
        // `^~compile` has no `:` after `^~`; falls through to the
        // project-reference branch and fails MissingColon.
        assert!(matches!(
            TaskRef::parse("^~compile"),
            Err(TaskRefError::MissingColon)
        ));
    }

    #[test]
    fn ref_006_rejects_sibling_tag_without_colon() {
        // `[tag]~compile` has `~` after `]` but no `:` after it;
        // neither `~:` nor `:` strip-prefix matches, so it falls
        // through to MalformedTagBrackets.
        assert!(matches!(
            TaskRef::parse("[tag]~compile"),
            Err(TaskRefError::MalformedTagBrackets)
        ));
    }

    #[test]
    fn ref_006_rejects_sibling_tag_bare_tilde_after_close() {
        // `[tag]~` ends right after `~`; no `:` follows.
        assert!(matches!(
            TaskRef::parse("[tag]~"),
            Err(TaskRefError::MalformedTagBrackets)
        ));
    }

    #[test]
    fn ref_006_rejects_tilde_suffix_on_project_name() {
        // `lib~:compile` is not a sibling form; `~` is not in the
        // identifier alphabet, so the project-name validation
        // rejects it.
        assert!(matches!(
            TaskRef::parse("lib~:compile"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Project,
                source: NameError::InvalidChar { c: '~' },
            })
        ));
    }

    #[test]
    fn ref_006_rejects_no_colon_at_all() {
        assert!(matches!(
            TaskRef::parse("compile"),
            Err(TaskRefError::MissingColon)
        ));
    }

    #[test]
    fn ref_006_rejects_empty_input() {
        assert!(matches!(TaskRef::parse(""), Err(TaskRefError::EmptyInput)));
    }

    // REF-007: no whitespace, no extras. Inherited from ID-001
    // for chars inside identifier slots; checked here for the
    // characters directly after a sigil.

    #[test]
    fn ref_007_rejects_space_after_same_project_sigil() {
        // `~: foo` keeps the leading space inside what would be
        // the task name, which then fails ID-001.
        assert!(matches!(
            TaskRef::parse("~: foo"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::InvalidLeadingChar { c: ' ' },
            })
        ));
    }

    #[test]
    fn ref_007_rejects_non_ascii_in_task() {
        // U+00E9 (LATIN SMALL LETTER E WITH ACUTE) is not ASCII.
        assert!(matches!(
            TaskRef::parse("~:caf\u{00E9}"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Task,
                source: NameError::InvalidChar { c: '\u{00E9}' },
            })
        ));
    }

    #[test]
    fn ref_007_rejects_tab_in_project() {
        assert!(matches!(
            TaskRef::parse("lib\tcore:compile"),
            Err(TaskRefError::InvalidName {
                component: NameComponent::Project,
                source: NameError::InvalidChar { c: '\t' },
            })
        ));
    }

    // Round-trip parse -> Display -> parse.

    #[test]
    fn round_trip_same_project() {
        let original = "~:compile";
        let r = TaskRef::parse(original).unwrap();
        assert_eq!(r.to_string(), original);
        assert_eq!(TaskRef::parse(&r.to_string()).unwrap(), r);
    }

    #[test]
    fn round_trip_project() {
        let original = "lib_core:compile";
        let r = TaskRef::parse(original).unwrap();
        assert_eq!(r.to_string(), original);
        assert_eq!(TaskRef::parse(&r.to_string()).unwrap(), r);
    }

    #[test]
    fn round_trip_fan_out() {
        let original = "^:test";
        let r = TaskRef::parse(original).unwrap();
        assert_eq!(r.to_string(), original);
        assert_eq!(TaskRef::parse(&r.to_string()).unwrap(), r);
    }

    #[test]
    fn round_trip_tag() {
        let original = "[typescript]:compile";
        let r = TaskRef::parse(original).unwrap();
        assert_eq!(r.to_string(), original);
        assert_eq!(TaskRef::parse(&r.to_string()).unwrap(), r);
    }

    #[test]
    fn round_trip_sibling_fan_out() {
        let original = "^~:test";
        let r = TaskRef::parse(original).unwrap();
        assert_eq!(r.to_string(), original);
        assert_eq!(TaskRef::parse(&r.to_string()).unwrap(), r);
    }

    #[test]
    fn round_trip_sibling_tag() {
        let original = "[typescript]~:compile";
        let r = TaskRef::parse(original).unwrap();
        assert_eq!(r.to_string(), original);
        assert_eq!(TaskRef::parse(&r.to_string()).unwrap(), r);
    }

    // Properties: every reference produced by the six valid
    // strategies parses, displays back to itself, and is recognised
    // by the right `is_*` predicate.

    use proptest::prelude::*;

    fn name_strategy() -> impl Strategy<Value = String> {
        "[A-Za-z0-9][A-Za-z0-9_-]{0,15}"
    }

    proptest! {
        #[test]
        fn prop_same_project_round_trips(task in name_strategy()) {
            let s = format!("~:{task}");
            let r = TaskRef::parse(&s).unwrap();
            prop_assert!(r.is_same_project());
            prop_assert_eq!(r.to_string(), s);
        }

        #[test]
        fn prop_project_round_trips(
            project in name_strategy(),
            task in name_strategy(),
        ) {
            let s = format!("{project}:{task}");
            let r = TaskRef::parse(&s).unwrap();
            prop_assert!(r.is_project());
            prop_assert_eq!(r.to_string(), s);
        }

        #[test]
        fn prop_fan_out_round_trips(task in name_strategy()) {
            let s = format!("^:{task}");
            let r = TaskRef::parse(&s).unwrap();
            prop_assert!(r.is_fan_out());
            prop_assert_eq!(r.to_string(), s);
        }

        #[test]
        fn prop_sibling_fan_out_round_trips(task in name_strategy()) {
            let s = format!("^~:{task}");
            let r = TaskRef::parse(&s).unwrap();
            prop_assert!(r.is_sibling_fan_out());
            prop_assert_eq!(r.to_string(), s);
        }

        #[test]
        fn prop_tag_round_trips(
            tag in name_strategy(),
            task in name_strategy(),
        ) {
            let s = format!("[{tag}]:{task}");
            let r = TaskRef::parse(&s).unwrap();
            prop_assert!(r.is_tag());
            prop_assert_eq!(r.to_string(), s);
        }

        #[test]
        fn prop_sibling_tag_round_trips(
            tag in name_strategy(),
            task in name_strategy(),
        ) {
            let s = format!("[{tag}]~:{task}");
            let r = TaskRef::parse(&s).unwrap();
            prop_assert!(r.is_sibling_tag());
            prop_assert_eq!(r.to_string(), s);
        }
    }
}