silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
use regex::Regex;
use std::sync::LazyLock;

/// A law id: nine Crockford symbols. That the first is a letter is `hash::is_crockford_id`,
/// so a hand-written id with a leading digit still parses and is refused by name.
pub const ID: &str = r"[0-9a-hjkmnp-z]{9}";

/// One span digest token: five Crockford symbols.
pub const DIGEST: &str = r"[0-9a-hjkmnp-z]{5}";

/// A project path: `.` for the workspace root, or `/`-joined segments that never open with a dot.
pub const PROJECTPATH: &str =
    r"(?:\.|[A-Za-z0-9_-][A-Za-z0-9._-]*(?:/[A-Za-z0-9_-][A-Za-z0-9._-]*)*)";

/// An id as a marker, an end or a mention writes it: case is ignored, and `i`, `l` and `o`
/// are read, since `normalise_id` maps them to `1`, `1` and `0` on capture.
pub const ID_READ: &str = r"(?i:[0-9a-tv-z]{9})";

/// A digest token as a marker writes it, read like `ID_READ`.
pub const DIGEST_READ: &str = r"(?i:[0-9a-tv-z]{5})";

/// What may follow an address or a digest on a marker line: whitespace, the close of the
/// comment, or the end of the line.
const ADDRESS_END: &str = r"(?:\s|\*/|-->|$)";

/// A byte order mark, which an editor may write before the first line: a marker after it still
/// opens its line.
const BOM: &str = r"\x{FEFF}?";

pub static MARKER_RE: LazyLock<Regex> = LazyLock::new(|| {
    // § xs2e8kj86@9wkvc
    Regex::new(&format!(
        r"(?m)^{BOM}\s*(?://|\{{/\*|/\*|#|--|<!--)\s*§\s*(?:({PROJECTPATH}):)?({ID_READ})(?:\.([a-z]+))?(?:@({DIGEST_READ}))?{ADDRESS_END}"
    ))
    .expect("marker regex")
});

pub static END_RE: LazyLock<Regex> = LazyLock::new(|| {
    // § rr512n5e2.b@7ktyf
    Regex::new(&format!(
        r"^{BOM}\s*(?://|\{{/\*|/\*|#|--|<!--)\s*§\s*end\s+(?:({PROJECTPATH}):)?({ID_READ})(?:\.([a-z]+))?{ADDRESS_END}"
    ))
    .expect("end regex")
});

/// One address of a `§ one` list with its digest, `{ID}` standing for the id form it reads.
const ENTRY: &str = r"(?:{PROJECTPATH}:)?{ID}(?:\.[a-z]+)?(?:@{DIGEST_READ})?";

fn entry(provisional: bool) -> String {
    let id = if provisional {
        format!(r"(?:{ID_READ}|\+[a-z0-9-]+)")
    } else {
        ID_READ.to_string()
    };
    ENTRY
        .replace("{PROJECTPATH}", PROJECTPATH)
        .replace("{DIGEST_READ}", DIGEST_READ)
        .replace("{ID}", &id)
}

/// The opening of a `§ one` marker, before its list.
const ONE_OPEN: &str = r"^\x{FEFF}?\s*(?://|\{/\*|/\*|#|--|<!--)\s*§\s*one\s+";

/// A `§ one` marker: a list of addresses, each with its own digest, that pins the statement or
/// member below it.
pub static ONE_RE: LazyLock<Regex> = LazyLock::new(|| {
    // § xs2e8kj86.h@7edjz
    let e = entry(false);
    Regex::new(&format!(r"{ONE_OPEN}({e}(?:\s*,\s*{e})*){ADDRESS_END}")).expect("one regex")
});

/// A `§ one` list whose entries may still be provisional `+name`s, which `fix` mints.
static ONE_ANY_RE: LazyLock<Regex> = LazyLock::new(|| {
    let e = entry(true);
    Regex::new(&format!(r"{ONE_OPEN}{e}(?:\s*,\s*{e})*{ADDRESS_END}")).expect("one any regex")
});

/// A comment that opens a `§ one` marker with an address-shaped token, so prose such as
/// `# § one of the cases` is no marker.
static ONE_LIKE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"{ONE_OPEN}(?:{PROJECTPATH}:)?(?:\+|(?i:[0-9a-z]{{9}})(?:[^A-Za-z0-9]|$))"
    ))
    .expect("one-like regex")
});

static ENTRY_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"(?:({PROJECTPATH}):)?({ID_READ})(?:\.([a-z]+))?(?:@({DIGEST_READ}))?"
    ))
    .expect("entry regex")
});

/// A comment that opens like a marker or an end, an id-shaped token followed by punctuation:
/// `# § c2ptr2t4v,b` is neither, and reading it as the law-grain marker it starts with would
/// pin the wrong address.
static MARKER_LIKE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"^{BOM}\s*(?://|\{{/\*|/\*|#|--|<!--)\s*§\s*(?:end\s+)?(?:{PROJECTPATH}:)?(?i:[0-9a-z]{{9}})[^\sA-Za-z0-9]"
    ))
    .expect("marker-like regex")
});

/// A comment that opens with `§` and an id-shaped token or a provisional `+name`, as a marker
/// or an end does.
static COMMENT_MARKER_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"^(?://|\{{/\*|/\*|#|--|<!--)\s*§\s*(?:end\s+|one\s+)?(?:{PROJECTPATH}:)?(?:\+[a-z0-9-]+|(?i:[0-9a-z]{{9}}))"
    ))
    .expect("comment marker regex")
});

/// A line that opens with a comment shaped as a marker, an end or a `§ one`: an id-shaped token
/// that ends where an id does, or a provisional `+name`.
static SHAPED_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"^{BOM}\s*(?://|\{{/\*|/\*|#|--|<!--)\s*§\s*(?:end\s+|one\s+)?(?:{PROJECTPATH}:)?(?:\+[a-z0-9-]+|(?i:[0-9a-z]{{9}})(?:[^A-Za-z0-9]|$))"
    ))
    .expect("shaped regex")
});

/// Whether the line opens with a comment shaped as a marker, an end or a `§ one`, well formed
/// or not.
pub fn shaped_as_marker(line: &str) -> bool {
    SHAPED_RE.is_match(line)
}

static WRAPPER_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"//|\{/\*|/\*|#|--|<!--").expect("wrapper regex"));

/// Whether the text of a comment opens as a marker or an end does.
pub fn opens_like_a_marker(comment: &str) -> bool {
    COMMENT_MARKER_RE.is_match(comment)
}

/// How a file holds a marker: code in a comment of its language, JSX also in the comment of an
/// expression container `{/* */}` among the children of an element, Markdown in an HTML
/// comment, and MDX, Markdown whose compiler refuses an HTML comment, in either or in `{/* */}`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Dialect {
    Code,
    Jsx,
    Markdown,
    Mdx,
}

impl Dialect {
    pub fn of(path: &std::path::Path) -> Self {
        match crate::span_lang::lang_for_path(path) {
            Some(lang) if lang.mdx => Dialect::Mdx,
            Some(lang) if lang.id == "markdown" => Dialect::Markdown,
            Some(lang) if matches!(lang.id, "tsx" | "javascript") => Dialect::Jsx,
            _ => Dialect::Code,
        }
    }

    pub fn is_markdown(self) -> bool {
        matches!(self, Dialect::Markdown | Dialect::Mdx)
    }

    /// Whether a marker or an end may open with `wrapper`, the comment that opens its line.
    pub fn opens_with(self, wrapper: &str) -> bool {
        // § xs2e8kj86.i@h7ps0
        match self {
            // In code `{/*` opens a JSX expression around a comment, not a comment.
            Dialect::Code => !wrapper.starts_with("{/*"),
            // § one xs2e8kj86.m@q30j9
            Dialect::Jsx => true,
            // A line that opens with `#` there is a heading.
            Dialect::Markdown => wrapper.starts_with("<!--"),
            Dialect::Mdx => wrapper.starts_with("<!--") || wrapper.starts_with("{/*"),
        }
    }
}

/// The 1-based lines where a comment that opens like a marker follows other text on its line,
/// read from the text alone: in markdown a comment of its dialect outside inline code and
/// fences, in any other file a marker wrapper outside the byte ranges of `literals`, its string
/// literals.
pub fn trailing_lines(dialect: Dialect, text: &str, literals: &[(usize, usize)]) -> Vec<usize> {
    let markdown = dialect.is_markdown();
    let fenced = fenced_lines(markdown, text);
    let mut out = Vec::new();
    let mut offset = 0;
    for (idx, line) in text.lines().enumerate() {
        let at = offset;
        offset += text[offset..]
            .find('\n')
            .map_or(text.len() - offset, |n| n + 1);
        if fenced[idx] || !line.contains('§') {
            continue;
        }
        let in_literal = |i: usize| literals.iter().any(|&(s, e)| s <= at + i && at + i < e);
        let line = if markdown {
            crate::parse::mask_inline_code(line)
        } else {
            line.to_string()
        };
        let trailing = WRAPPER_RE.find_iter(&line).any(|m| {
            // In code the comment of `{/*` opens after its brace, which is other text.
            let start = if !markdown && m.as_str() == "{/*" {
                m.start() + 1
            } else {
                m.start()
            };
            (!markdown || dialect.opens_with(m.as_str()))
                && !in_literal(start)
                && !line[..start]
                    .trim_start_matches('\u{feff}')
                    .trim()
                    .is_empty()
                && opens_like_a_marker(&line[start..])
        });
        if trailing {
            out.push(idx + 1);
        }
    }
    out
}

/// A line that opens like a marker or an end and is neither.
pub fn looks_like_a_marker(line: &str) -> bool {
    // § xs2e8kj86.b@g3xkk
    block_closed(line)
        && ((MARKER_LIKE_RE.is_match(line) && !MARKER_RE.is_match(line) && !END_RE.is_match(line))
            || (ONE_LIKE_RE.is_match(line) && !ONE_ANY_RE.is_match(line)))
}

/// Whether the line is a marker, a `§ one` list or an end.
pub fn is_pointer_line(line: &str) -> bool {
    MARKER_RE.is_match(line) || END_RE.is_match(line) || is_one(line)
}

/// Whether the line opens a `§ one` marker, its entries minted or still provisional.
pub fn opens_one(line: &str) -> bool {
    block_closed(line) && ONE_ANY_RE.is_match(line)
}

/// Whether the line is a `§ one` marker.
pub fn is_one(line: &str) -> bool {
    line.contains('§') && block_closed(line) && ONE_RE.is_match(line)
}

/// The 1-based lines of `text` that look like a marker or an end and are neither, outside a
/// fence and the lines no marker is read on.
pub fn malformed_lines(dialect: Dialect, text: &str) -> Vec<usize> {
    let unmarked = unmarked_lines(dialect, text);
    text.lines()
        .enumerate()
        .filter(|(idx, line)| !unmarked[*idx] && looks_like_a_marker(line))
        .map(|(idx, _)| idx + 1)
        .collect()
}

/// `line` with the id and digests of each marker or end it holds in canonical form, lowercase
/// with `i`, `l` and `o` read as Crockford digits.
pub fn canonical_line(line: &str) -> String {
    if is_one(line) {
        let mut out = line.to_string();
        for w in written(line).into_iter().rev() {
            for range in w.digest.into_iter().chain([w.id]) {
                out.replace_range(range.clone(), &crate::hash::normalise_id(&line[range]));
            }
        }
        return out;
    }
    let re: &Regex = if END_RE.is_match(line) {
        &END_RE
    } else {
        &MARKER_RE
    };
    let Some(caps) = re.captures(line).filter(|_| block_closed(line)) else {
        return line.to_string();
    };
    let mut out = line.to_string();
    for idx in (2..caps.len()).rev() {
        if idx == 3 {
            continue;
        }
        if let Some(m) = caps.get(idx) {
            out.replace_range(m.range(), &crate::hash::normalise_id(m.as_str()));
        }
    }
    out
}

/// Explicit span ends in one file. `pairs` maps a marker line to the line of the `end`
/// that closes it; `orphans` are `end` lines with no marker of their address above.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Ends {
    pub pairs: std::collections::BTreeMap<usize, usize>,
    pub orphans: Vec<(usize, String)>,
    /// `end` lines whose nearest marker of their address above is a `§ one` list.
    pub on_one: Vec<(usize, String)>,
}

#[cfg(test)]
pub fn explicit_ends(markdown: bool, text: &str) -> Ends {
    let dialect = if markdown {
        Dialect::Markdown
    } else {
        Dialect::Code
    };
    explicit_ends_in(&unmarked_lines(dialect, text), text)
}

/// The explicit ends of `text`, reading no marker and no end on a line `unmarked` holds.
pub fn explicit_ends_in(unmarked: &[bool], text: &str) -> Ends {
    // § rr512n5e2.b@9er9y
    let mut open: std::collections::HashMap<String, Vec<usize>> = std::collections::HashMap::new();
    let mut ends = Ends::default();
    let mut one = std::collections::HashSet::new();
    for (idx, line) in text.lines().enumerate() {
        if unmarked.get(idx).copied().unwrap_or(false) || !line.contains('§') {
            continue;
        }
        if let Some(c) = END_RE.captures(line).filter(|_| block_closed(line)) {
            let addr = MarkerAddr {
                project: c.get(1).map(|m| m.as_str().to_string()),
                id: crate::hash::normalise_id(&c[2]),
                letter: c.get(3).map(|m| m.as_str().to_string()),
                digest: None,
            }
            .display();
            match open.get_mut(&addr).and_then(Vec::pop) {
                // § one rr512n5e2.j@xackt
                Some(start) if one.contains(&start) => ends.on_one.push((idx, addr)),
                Some(start) => {
                    ends.pairs.insert(start, idx);
                }
                None => ends.orphans.push((idx, addr)),
            }
            continue;
        }
        if is_one(line) {
            one.insert(idx);
        }
        for addr in markers_in_line(line) {
            open.entry(addr.display()).or_default().push(idx);
        }
    }
    ends
}

#[derive(
    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub struct MarkerAddr {
    /// The project path of a qualified marker, `<projectpath>:<id>`. `None` is the current project.
    pub project: Option<String>,
    pub id: String,
    pub letter: Option<String>,
    pub digest: Option<String>,
}

impl MarkerAddr {
    /// The address without its digest, and the digest as written. `None` for a bare marker.
    pub fn split_digest(self) -> Option<(MarkerAddr, String)> {
        let digest = self.digest.clone()?;
        Some((
            MarkerAddr {
                digest: None,
                ..self
            },
            digest,
        ))
    }

    /// The address as written: `[<projectpath>:]<id>[.<letter>]`.
    pub fn display(&self) -> String {
        let local = match &self.letter {
            Some(letter) => format!("{}.{}", self.id, letter),
            None => self.id.clone(),
        };
        match &self.project {
            Some(project) => format!("{project}:{local}"),
            None => local,
        }
    }
}

/// The comment that opens a marker in a file of this extension, and what closes it. `None` for a
/// language whose line comment no marker wrapper is.
pub fn wrapper_for(path: &std::path::Path) -> Option<(&'static str, &'static str)> {
    // A file name alone picks these grammars, `Dockerfile` or `tsconfig.json`.
    match crate::span_lang::lang_for_path(path).map(|lang| lang.id) {
        Some("dockerfile") => return Some(("#", "")),
        Some("jsonc") => return Some(("//", "")),
        _ => {}
    }
    Some(match path.extension()?.to_str()? {
        "rs" | "ts" | "tsx" | "js" | "jsx" | "mjs" | "cjs" | "go" | "c" | "h" | "cc" | "cpp"
        | "hpp" | "java" | "kt" | "swift" | "cs" | "scala" | "dart" | "php" | "cedar"
        | "prisma" | "jsonc" | "json5" => ("//", ""),
        "py" | "sh" | "bash" | "zsh" | "rb" | "pl" | "r" | "yaml" | "yml" | "toml" | "hcl"
        | "tf" | "tfvars" | "nix" | "ex" | "exs" | "dockerfile" | "containerfile" => ("#", ""),
        "sql" | "lua" | "hs" => ("--", ""),
        "html" | "htm" | "xml" | "vue" | "svelte" => ("<!--", " -->"),
        "css" => ("/*", " */"),
        _ => return None,
    })
}

pub fn marker_from_caps(caps: regex::Captures<'_>) -> MarkerAddr {
    MarkerAddr {
        project: caps.get(1).map(|m| m.as_str().to_string()),
        id: crate::hash::normalise_id(&caps[2]),
        letter: caps.get(3).map(|m| m.as_str().to_string()),
        digest: caps.get(4).map(|m| crate::hash::normalise_id(m.as_str())),
    }
}

pub fn markers_in_line(line: &str) -> Vec<MarkerAddr> {
    written(line).into_iter().map(|w| w.addr).collect()
}

/// One address of a marker line as written: the bytes of its id, the byte where the address
/// ends, before any digest, and the bytes of its digest after `@`.
pub struct Written {
    pub addr: MarkerAddr,
    pub id: std::ops::Range<usize>,
    pub at: usize,
    pub digest: Option<std::ops::Range<usize>>,
}

/// Each address of a marker line, in the order it is written: one, or each of a `§ one` list.
pub fn written(line: &str) -> Vec<Written> {
    if !line.contains('§') || !block_closed(line) {
        return Vec::new();
    }
    let of = |caps: regex::Captures<'_>, offset: usize| {
        let id = caps.get(2).expect("id");
        Written {
            id: offset + id.start()..offset + id.end(),
            at: offset + caps.get(3).unwrap_or(id).end(),
            digest: caps.get(4).map(|m| offset + m.start()..offset + m.end()),
            addr: marker_from_caps(caps),
        }
    };
    if let Some(list) = ONE_RE.captures(line).and_then(|caps| caps.get(1)) {
        return ENTRY_RE
            .captures_iter(list.as_str())
            .map(|caps| of(caps, list.start()))
            .collect();
    }
    MARKER_RE
        .captures_iter(line)
        .map(|caps| of(caps, 0))
        .collect()
}

/// The entry of a marker line that `address` names, read as written or qualified by a project:
/// the one marker of a plain line, or that entry of a `§ one` list.
pub fn entry_for(line: &str, address: &str) -> Option<MarkerAddr> {
    let mut all = markers_in_line(line);
    if all.len() <= 1 {
        return all.pop();
    }
    all.into_iter().find(|pin| {
        let local = pin.display();
        address == local || address.ends_with(&format!(":{local}"))
    })
}

/// The `§ one` line without the entries `gone` names, `None` when no entry stays.
pub fn drop_from_one(line: &str, gone: impl Fn(&MarkerAddr) -> bool) -> Option<String> {
    let entries = written(line);
    let kept: Vec<&Written> = entries.iter().filter(|w| !gone(&w.addr)).collect();
    let (first, last) = (entries.first()?, entries.last()?);
    if kept.is_empty() {
        return None;
    }
    let start = first.id.start - first.addr.project.as_ref().map_or(0, |p| p.len() + 1);
    let end = last.digest.as_ref().map_or(last.at, |d| d.end);
    let text: Vec<String> = kept
        .iter()
        .map(|w| {
            let from = w.id.start - w.addr.project.as_ref().map_or(0, |p| p.len() + 1);
            line[from..w.digest.as_ref().map_or(w.at, |d| d.end)].to_string()
        })
        .collect();
    Some(format!(
        "{}{}{}",
        &line[..start],
        text.join(", "),
        &line[end..]
    ))
}

/// The address an explicit end line closes.
pub fn end_in_line(line: &str) -> Option<MarkerAddr> {
    let caps = END_RE.captures(line).filter(|_| block_closed(line))?;
    Some(MarkerAddr {
        project: caps.get(1).map(|m| m.as_str().to_string()),
        id: crate::hash::normalise_id(&caps[2]),
        letter: caps.get(3).map(|m| m.as_str().to_string()),
        digest: None,
    })
}

/// A `/* */` or `{/* */}` wrapper is a marker only when it closes on its own line, so a block
/// comment that runs on never turns its prose into a span.
fn block_closed(line: &str) -> bool {
    let line = line.trim_start_matches('\u{feff}').trim_start();
    line.strip_prefix("{/*")
        .or_else(|| line.strip_prefix("/*"))
        .is_none_or(|rest| rest.contains("*/"))
}

pub fn is_markdown(path: &std::path::Path) -> bool {
    // § xs2e8kj86.f@bwccd
    crate::span_lang::lang_for_path(path).is_some_and(|lang| lang.id == "markdown")
}

/// The 0-based lines of a markdown text inside a code fence, fence lines included, or inside
/// an indented code block. A text that is not markdown has none.
pub fn fenced_lines(markdown: bool, text: &str) -> Vec<bool> {
    if !markdown {
        return vec![false; text.lines().count()];
    }
    // The scan, the form checks and the code file of one markdown file each ask, on threads
    // of their own, and each answer is a parse.
    static FENCED: crate::par::Shared<Vec<bool>> = std::sync::OnceLock::new();
    crate::par::shared(&FENCED, blake3::hash(text.as_bytes()), || {
        markdown_fenced_lines(text)
    })
}

fn markdown_fenced_lines(text: &str) -> Vec<bool> {
    let lines: Vec<&str> = text.lines().collect();
    let mut out = crate::parse::fence_mask(&lines);
    for row in crate::span_lang::indented_code_lines(text) {
        if let Some(line) = out.get_mut(row) {
            *line = true;
        }
    }
    out
}

/// The 0-based lines of a text where no marker or end is read, though one may open like it:
/// in markdown a line inside a code fence, and a line whose comment its dialect does not read
/// a marker in, since `# § id` there is a heading, and in code a line that opens with `{/*`.
pub fn unmarked_lines(dialect: Dialect, text: &str) -> Vec<bool> {
    // § xs2e8kj86@684h3
    let mut out = fenced_lines(dialect.is_markdown(), text);
    for (idx, line) in text.lines().enumerate() {
        out[idx] |= !dialect.opens_with(line.trim_start_matches('\u{feff}').trim_start());
    }
    out
}

#[cfg(test)]
pub fn markers_in_text(text: &str) -> Vec<MarkerAddr> {
    text.lines().flat_map(markers_in_line).collect()
}

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

    #[test]
    fn marker_in_code_comment() {
        let line = format!("// § {}", "abcdefgh1");
        let hits = markers_in_line(&line);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].id, "abcdefgh1");
        assert!(hits[0].letter.is_none());
        assert!(hits[0].digest.is_none());
    }

    #[test]
    fn marker_with_clause_letter() {
        let line = "// § abcdefgh1.a";
        let hits = markers_in_line(line);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].id, "abcdefgh1");
        assert_eq!(hits[0].letter.as_deref(), Some("a"));
    }

    #[test]
    fn marker_with_pin() {
        let line = "// § abcdefgh1@k3n7q";
        let hits = markers_in_line(line);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].digest.as_deref(), Some("k3n7q"));
    }

    /// A digest is one five-character token: the two-token forms of earlier schemes, joined by
    /// `+` or written as ten characters, are no marker, and `check` fails them as malformed.
    #[test]
    fn a_digest_of_two_tokens_is_no_marker() {
        for line in ["// § abcdefgh1@k3n7q+m2p4s", "// § abcdefgh1@k3n7qm2p4s"] {
            assert!(markers_in_line(line).is_empty(), "{line}");
            assert!(looks_like_a_marker(line), "{line}");
        }
    }

    #[test]
    fn qualified_code_marker_carries_its_project() {
        let hits = markers_in_line("// § packages/billing:7k2m9x1ab.a@k3n7q");
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].project.as_deref(), Some("packages/billing"));
        assert_eq!(hits[0].id, "7k2m9x1ab");
        assert_eq!(hits[0].letter.as_deref(), Some("a"));
        assert_eq!(hits[0].digest.as_deref(), Some("k3n7q"));
        assert_eq!(hits[0].display(), "packages/billing:7k2m9x1ab.a");
    }

    #[test]
    fn root_project_qualifier_is_a_dot() {
        let hits = markers_in_line("# § .:7k2m9x1ab");
        assert_eq!(hits[0].project.as_deref(), Some("."));
        assert_eq!(hits[0].display(), ".:7k2m9x1ab");
    }

    #[test]
    fn qualified_doc_marker_and_end() {
        let hits = markers_in_line("<!-- § packages/billing:7k2m9x1ab.a -->");
        assert_eq!(hits[0].project.as_deref(), Some("packages/billing"));
        let ends = explicit_ends(
            false,
            "// § packages/billing:7k2m9x1ab.a\nx\n// § end packages/billing:7k2m9x1ab.a\n",
        );
        assert_eq!(ends.pairs.get(&0), Some(&2));
        assert!(ends.orphans.is_empty());
    }

    #[test]
    fn end_of_another_project_does_not_close_a_local_marker() {
        let ends = explicit_ends(
            false,
            "// § 7k2m9x1ab\n// § end packages/billing:7k2m9x1ab\n",
        );
        assert!(ends.pairs.is_empty());
        assert_eq!(
            ends.orphans,
            vec![(1, "packages/billing:7k2m9x1ab".to_string())]
        );
    }

    #[test]
    fn a_project_segment_never_opens_with_a_dot() {
        let hits = markers_in_line("// § ../x:7k2m9x1ab");
        assert!(hits.is_empty());
    }

    #[test]
    fn block_comment_marker_closes_on_its_line() {
        let id = "7k2m9x1ab";
        let hits = markers_in_line(&format!("  /* § {id}.a@k3n7q */"));
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].display(), format!("{id}.a"));
        assert_eq!(hits[0].digest.as_deref(), Some("k3n7q"));
        assert!(markers_in_line(&format!("/* § {id}.a")).is_empty());
        let ends = explicit_ends(false, &format!("/* § {id} */\nx\n/* § end {id} */\n"));
        assert_eq!(ends.pairs.get(&0), Some(&2));
        assert!(
            explicit_ends(false, &format!("/* § {id} */\n/* § end {id}\n"))
                .pairs
                .is_empty()
        );
    }

    #[test]
    fn a_one_marker_reads_each_address_of_its_list_with_its_own_digest() {
        let line = "    // § one c2ptr2t4v.b@q6q41, pkg:abcdefgh1, ABCDEFGH2@K3N7Q";
        assert!(is_one(line));
        let hits = markers_in_line(line);
        let shown: Vec<String> = hits.iter().map(MarkerAddr::display).collect();
        assert_eq!(shown, ["c2ptr2t4v.b", "pkg:abcdefgh1", "abcdefgh2"]);
        assert_eq!(hits[0].digest.as_deref(), Some("q6q41"));
        assert_eq!(hits[1].digest, None);
        assert_eq!(hits[2].digest.as_deref(), Some("k3n7q"));
        assert_eq!(
            canonical_line(line),
            "    // § one c2ptr2t4v.b@q6q41, pkg:abcdefgh1, abcdefgh2@k3n7q"
        );
        assert!(markers_in_line("<!-- § one c2ptr2t4v -->").len() == 1);
        assert!(!is_one("// § c2ptr2t4v"));
    }

    #[test]
    fn a_one_marker_that_breaks_its_list_is_malformed_and_prose_is_not() {
        for line in [
            "// § one c2ptr2t4v,,b",
            "// § one c2ptr2t4v, ",
            "// § one c2ptr2t4v; abcdefgh1",
        ] {
            assert!(markers_in_line(line).is_empty(), "{line}");
            assert!(looks_like_a_marker(line), "{line}");
        }
        assert!(!looks_like_a_marker("# § one of the cases"));
        assert!(!looks_like_a_marker("// § one +fee.a, c2ptr2t4v"));
        assert!(opens_one("// § one +fee.a, c2ptr2t4v"));
    }

    #[test]
    fn an_end_on_a_one_marker_pairs_with_nothing() {
        let ends = explicit_ends(false, "// § one c2ptr2t4v\nx\n// § end c2ptr2t4v\n");
        assert!(ends.pairs.is_empty());
        assert_eq!(ends.on_one, vec![(2, "c2ptr2t4v".to_string())]);
    }

    #[test]
    fn dropping_an_entry_keeps_the_others_as_written() {
        let line = "    // § one c2ptr2t4v.b@q6q41, pkg:abcdefgh1, abcdefgh2@k3n7q";
        let gone = |id: &'static str| move |a: &MarkerAddr| a.id == id;
        assert_eq!(
            drop_from_one(line, gone("abcdefgh1")).as_deref(),
            Some("    // § one c2ptr2t4v.b@q6q41, abcdefgh2@k3n7q")
        );
        assert_eq!(
            drop_from_one(line, gone("c2ptr2t4v")).as_deref(),
            Some("    // § one pkg:abcdefgh1, abcdefgh2@k3n7q")
        );
        assert_eq!(drop_from_one("// § one c2ptr2t4v", gone("c2ptr2t4v")), None);
    }

    #[test]
    fn marker_in_html_comment() {
        let line = format!("<!-- § {} -->", "xyzabcde1.b");
        let hits = markers_in_line(&line);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].display(), "xyzabcde1.b");
    }

    #[test]
    fn marker_in_mdx_comment() {
        let hits = markers_in_line("{/* § xyzabcde1.b@k3n7q */}");
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].display(), "xyzabcde1.b");
        assert_eq!(hits[0].digest.as_deref(), Some("k3n7q"));
        assert_eq!(markers_in_line("{/* § xyzabcde1*/}").len(), 1);
        assert!(markers_in_line("{/* § xyzabcde1").is_empty());
        assert!(looks_like_a_marker("{/* § xyzabcde1,b */}"));
        let text = "{/* § xyzabcde1 */}\nx\n{/* § end xyzabcde1 */}\n";
        let ends = explicit_ends_in(&unmarked_lines(Dialect::Mdx, text), text);
        assert_eq!(ends.pairs.get(&0), Some(&2));
    }

    /// MDX reads a marker in either comment, Markdown in an HTML comment alone, since
    /// `{/* */}` renders there as text, and code in neither `{/*` line.
    #[test]
    fn each_dialect_reads_its_own_comments() {
        let text = "{/* § xyzabcde1 */}\n<!-- § xyzabcde2 -->\n// § xyzabcde3\n";
        let read = |dialect| {
            let unmarked = unmarked_lines(dialect, text);
            text.lines()
                .zip(unmarked)
                .filter(|(_, unmarked)| !unmarked)
                .flat_map(|(line, _)| markers_in_line(line))
                .map(|m| m.id)
                .collect::<Vec<_>>()
        };
        assert_eq!(read(Dialect::Mdx), ["xyzabcde1", "xyzabcde2"]);
        assert_eq!(read(Dialect::Markdown), ["xyzabcde2"]);
        assert_eq!(read(Dialect::Code), ["xyzabcde2", "xyzabcde3"]);
        assert_eq!(
            trailing_lines(Dialect::Mdx, "Text {/* § xyzabcde1 */}\n", &[]),
            [1]
        );
        assert!(trailing_lines(Dialect::Markdown, "Text {/* § xyzabcde1 */}\n", &[]).is_empty());
        assert_eq!(
            trailing_lines(Dialect::Code, "{/* § xyzabcde1 */}\n", &[]),
            [1]
        );
        assert_eq!(
            Dialect::of(std::path::Path::new("docs/page.MDX")),
            Dialect::Mdx
        );
        assert_eq!(
            Dialect::of(std::path::Path::new("docs/page.md")),
            Dialect::Markdown
        );
    }

    #[test]
    fn a_marker_reads_case_and_crockford_homoglyphs() {
        let hits = markers_in_line("# § C2PTR2T4V.b@Q6Q41");
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].id, "c2ptr2t4v");
        assert_eq!(hits[0].digest.as_deref(), Some("q6q41"));
        let hits = markers_in_line("// § c2ptr2t4v.b@q6qIl");
        assert_eq!(hits[0].digest.as_deref(), Some("q6q11"));
        assert_eq!(markers_in_line("// § abcdefghO")[0].id, "abcdefgh0");
        let ends = explicit_ends(false, "// § ABCDEFGH1\nx\n// § end abcdefghl\n");
        assert_eq!(ends.pairs.get(&0), Some(&2));
    }

    #[test]
    fn an_address_ends_at_whitespace_or_the_comment_close() {
        for line in [
            "# § c2ptr2t4v,b",
            "# § c2ptr2t4v.+",
            "# § c2ptr2t4v.b,",
            "# § c2ptr2t4v@e1b8t,b",
            "// § end c2ptr2t4v,b",
        ] {
            assert!(markers_in_line(line).is_empty(), "{line}");
            assert!(looks_like_a_marker(line), "{line}");
        }
        assert!(
            explicit_ends(false, "// § c2ptr2t4v\n// § end c2ptr2t4v,b\n")
                .pairs
                .is_empty()
        );
        for line in [
            "# § c2ptr2t4v.b keeps a note",
            "/* § c2ptr2t4v.b*/",
            "<!-- § c2ptr2t4v.b-->",
            "# § c2ptr2t4v@e1b8t",
        ] {
            assert_eq!(markers_in_line(line).len(), 1, "{line}");
            assert!(!looks_like_a_marker(line), "{line}");
        }
        assert!(!looks_like_a_marker("# § documentation of the format"));
    }
}