silcrow 0.1.0

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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
use std::path::Path;
use unicode_normalization::UnicodeNormalization;

use crate::span_lang;

const ISSUES: &str = "https://github.com/zifeo/silcrow/issues";

pub fn language_label(ext: &str) -> String {
    match ext {
        "go" => "Go".into(),
        "java" => "Java".into(),
        "kt" | "kts" => "Kotlin".into(),
        "c" | "h" => "C".into(),
        "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" => "C++".into(),
        "rb" => "Ruby".into(),
        "cedar" => "Cedar".into(),
        other => format!(".{other}"),
    }
}

/// The warning for a file whose extension has no tested grammar: its pins are coarse, so it
/// names the languages that pin a construct and where to ask for one more.
pub fn notice(path: &Path, ext: &str) -> String {
    // § k6rfj5k37.e@gbvmg
    let lang = language_label(ext);
    let title = format!("Add tested grammar: {lang}");
    let search = format!("{ISSUES}?q={}", query_encode(&format!("is:issue {title}")));
    let new = format!("{ISSUES}/new?title={}", query_encode(&title));
    let tested: Vec<String> = span_lang::PINNED
        .iter()
        .map(|lang| {
            let exts: Vec<String> = lang.extensions.iter().map(|e| format!(".{e}")).collect();
            format!("{} ({})", lang.id, exts.join(", "))
        })
        .collect();
    format!(
        "{}: `{lang}` has no tested grammar, so its pins use a fallback heuristic. Each span runs to the end of the file, or to its `§ end` line, so a pin is coarse and will drift often. Tested languages: {}. Search existing requests: {search}  Request support: {new}",
        path.display(),
        tested.join(", ")
    )
}

fn query_encode(input: &str) -> String {
    let mut out = String::new();
    for b in input.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' => out.push(b as char),
            b' ' => out.push('+'),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

#[cfg(test)]
pub fn mint(
    ext: &str,
    source: &str,
    start_line: usize,
    end_line: usize,
    punch: &[(usize, usize)],
) -> String {
    mint_clause(ext, source, start_line, end_line, punch, "")
}

pub fn mint_clause(
    ext: &str,
    source: &str,
    start_line: usize,
    end_line: usize,
    punch: &[(usize, usize)],
    clause: &str,
) -> String {
    // § d1bc2zca5.a@5j89y
    let stream = prepare(ext, source, start_line, end_line, punch);
    span_lang::encode_digest(&format!("{stream}\n§{clause}"))
}

/// Whether the span from `start_line` to before `end_line` holds nothing but comments and
/// whitespace. Nested spans count: their statements are written inside it.
/// Whether the lines `start_line..end_line` hold nothing once comments and the spans `nested` in
/// them are cut out, each to a hole token.
pub fn is_empty(
    ext: &str,
    source: &str,
    (start_line, end_line): (usize, usize),
    nested: &[(usize, usize)],
) -> bool {
    // § rr512n5e2.d@vnhrw
    // silcrow:follow
    prepare(ext, source, start_line, end_line, nested).is_empty()
}

fn prepare(
    ext: &str,
    source: &str,
    start_line: usize,
    end_line: usize,
    punch: &[(usize, usize)],
) -> String {
    // § k6rfj5k37.e@3pzgx
    let mut kept = String::new();
    let mut holes = vec![false; punch.len()];
    for (idx, line) in source.lines().enumerate() {
        let line_no = idx + 1;
        if line_no < start_line || line_no >= end_line {
            continue;
        }
        if let Some(at) = punched_line(line_no, punch) {
            // § rr512n5e2.c@m3d2q
            if !std::mem::replace(&mut holes[at], true) {
                kept.push_str(HOLE);
                kept.push('\n');
            }
            continue;
        }
        kept.push_str(line);
        kept.push('\n');
    }
    // With no grammar to say a trailing separator is formatting, it is a byte of the span.
    let stripped = strip_comments(&kept, ext);
    let nfc: String = stripped.nfc().collect();
    let mut words: Vec<&str> = nfc
        .split([' ', '\t', '\n', '\r', '\x0c'])
        .filter(|word| !word.is_empty())
        .collect();
    // A hole nothing of the span follows writes nothing, as in a tested grammar.
    while words.last() == Some(&HOLE) {
        words.pop();
    }
    words.join(" ")
}

const HOLE: &str = "\u{1}hole";

/// The index of the first punched range that holds `line`.
fn punched_line(line: usize, punch: &[(usize, usize)]) -> Option<usize> {
    punch
        .iter()
        .position(|(start, end)| line >= *start && line < *end)
}

/// The comment forms of a language with no tested grammar.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Comment {
    /// `//` to the end of the line.
    Line,
    /// `/* */`.
    Block,
    /// `#` to the end of the line, at the start of a line or after whitespace.
    Hash,
    /// `--` to the end of the line, at the start of a line or after whitespace, and followed
    /// by whitespace or the end of the line, so an operator such as `-->` or `n--` stays code.
    DashDash,
    /// `<!-- -->`.
    Html,
    /// A Lua long comment, `--[[ ]]` or `--[==[ ]==]`.
    LuaLong,
}

/// The comments the fallback strips for a file extension. An extension the table does not
/// name strips nothing: a wrapper its language does not use may be code there, as `#define`
/// in C, `n--` in Go or `//` in Nix, its merge operator.
fn comment_syntax(ext: &str) -> &'static [Comment] {
    // § k6rfj5k37.e@ak1e6
    use Comment::*;
    match ext {
        "go" | "java" | "kt" | "kts" | "c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx"
        | "cs" | "swift" | "scala" | "sc" | "dart" | "groovy" | "gradle" | "proto" | "sol"
        | "php" | "m" | "mm" | "v" | "sv" => &[Line, Block],
        "cedar" => &[Line],
        "rb" | "pl" | "pm" | "r" | "yaml" | "yml" | "toml" | "cmake" | "ex" | "exs" | "jl"
        | "ps1" | "psm1" | "tcl" | "awk" | "zsh" | "fish" | "ksh" | "mk" | "nim" | "cr"
        | "coffee" => &[Hash],
        "nix" => &[Hash, Block],
        "lua" => &[LuaLong, DashDash],
        "sql" | "hs" | "elm" | "ada" | "adb" | "ads" | "vhd" | "vhdl" => &[DashDash],
        "xml" | "svg" | "xhtml" | "xsl" | "xslt" | "plist" => &[Html],
        _ => &[],
    }
}

/// The string literals of a language beyond the single, double and backtick quotes every
/// extension reads.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Literal {
    /// `""" """`, which spans lines, and in which a backslash escapes the next character.
    TripleDouble,
    /// `''' '''`, which spans lines, and in which a backslash escapes the next character.
    TripleSingle,
    /// `""" """` with no escapes: a backslash is a byte.
    RawTripleDouble,
    /// `''' '''` with no escapes, a TOML multi-line literal string.
    RawTripleSingle,
    /// A C# verbatim string, `@"..."`, `$@"..."` or `@$"..."`, in which `""` is a quote and a
    /// backslash is a byte.
    CsVerbatim,
    /// A Lua long string, `[[ ]]` or `[==[ ]==]`.
    LuaLong,
    /// A C++ raw string, `R"delim( )delim"`, with an optional `u8`, `u`, `U` or `L` prefix.
    CppRaw,
    /// A Nix indented string, `'' ''`, in which `'''`, `''$` and `''\` escape.
    NixIndented,
}

fn literal_syntax(ext: &str) -> &'static [Literal] {
    // § k6rfj5k37.e@qqgjm
    use Literal::*;
    match ext {
        "groovy" | "gradle" | "dart" | "ex" | "exs" | "coffee" => &[TripleDouble, TripleSingle],
        "toml" => &[TripleDouble, RawTripleSingle],
        "java" | "swift" | "jl" | "elm" => &[TripleDouble],
        "kt" | "kts" | "scala" | "sc" | "nim" => &[RawTripleDouble],
        "cs" => &[RawTripleDouble, CsVerbatim],
        "lua" => &[LuaLong],
        "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" | "h" => &[CppRaw],
        "nix" => &[NixIndented],
        _ => &[],
    }
}

/// The input with its comments stripped.
fn strip_comments(input: &str, ext: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for (piece, start, end) in pieces(ext, input) {
        if piece != Piece::Comment {
            out.push_str(&input[start..end]);
        }
    }
    out
}

/// The byte ranges of the string literals of `text`, as the fallback reads them.
pub fn literal_ranges(ext: &str, text: &str) -> Vec<(usize, usize)> {
    pieces(ext, text)
        .into_iter()
        .filter(|(piece, _, _)| *piece == Piece::Literal)
        .map(|(_, start, end)| (start, end))
        .collect()
}

/// The 0-based lines of `text` that open inside a string literal of the file's language, as
/// the fallback reads it: a `§` there is a value, not a marker.
pub fn literal_lines(ext: &str, text: &str) -> Vec<bool> {
    let mut out = vec![false; text.lines().count()];
    let mut line = 0;
    let mut at = 0;
    for (piece, start, end) in pieces(ext, text) {
        for (rel, _) in text[at..end].match_indices('\n') {
            line += 1;
            let opens = at + rel + 1;
            if piece == Piece::Literal && opens > start && opens < end && line < out.len() {
                out[line] = true;
            }
        }
        at = end;
    }
    out
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Piece {
    Code,
    Comment,
    Literal,
}

/// The input cut into code, comments and string literals, in order, as the tables read the
/// language of `ext`. A line comment ends before its line break, which stays code.
fn pieces(ext: &str, input: &str) -> Vec<(Piece, usize, usize)> {
    let syntax = comment_syntax(ext);
    let literal = literal_syntax(ext);
    let mut out: Vec<(Piece, usize, usize)> = Vec::new();
    let mut push = |piece: Piece, start: usize, end: usize| match out.last_mut() {
        Some((Piece::Code, _, e)) if piece == Piece::Code && *e == start => *e = end,
        _ => out.push((piece, start, end)),
    };
    let after_space = |i: usize| {
        input[..i]
            .chars()
            .next_back()
            .is_none_or(char::is_whitespace)
    };
    let mut i = 0;
    while i < input.len() {
        let rest = &input[i..];
        // § k6rfj5k37.e@y369e
        // A line that reads as a comment in most languages keeps its apostrophes out of any
        // string where the table names no comment, though it stays code.
        let comment_like = syntax.is_empty()
            && (rest.starts_with("//") || rest.starts_with('#') || rest.starts_with("-- "))
            && input[..i]
                .rsplit('\n')
                .next()
                .is_none_or(|before| before.trim().is_empty());
        if comment_like {
            let end = rest.find('\n').map_or(input.len(), |rel| i + rel);
            push(Piece::Code, i, end);
            i = end;
            continue;
        }
        // § end k6rfj5k37.e
        if let Some(len) = literal_len(literal, input, i) {
            push(Piece::Literal, i, i + len);
            i += len;
            continue;
        }
        let lua_long = syntax.contains(&Comment::LuaLong)
            && rest.starts_with("--")
            && after_space(i)
            && long_bracket(&rest[2..]).is_some();
        if lua_long {
            let len = 2 + long_bracket_len(&rest[2..]);
            push(Piece::Comment, i, i + len);
            i += len;
            continue;
        }
        let block = if syntax.contains(&Comment::Html) && rest.starts_with("<!--") {
            Some(("<!--", "-->"))
        } else if syntax.contains(&Comment::Block) && rest.starts_with("/*") {
            Some(("/*", "*/"))
        } else {
            None
        };
        if let Some((open, close)) = block {
            let end = input[i + open.len()..]
                .find(close)
                .map_or(input.len(), |rel| i + open.len() + rel + close.len());
            push(Piece::Comment, i, end);
            i = end;
            continue;
        }
        let dash_dash = rest.starts_with("--")
            && after_space(i)
            && rest[2..].chars().next().is_none_or(char::is_whitespace);
        // A Go directive, `//go:build` or `// +build`, decides what compiles: it is code.
        let directive = ext == "go"
            && input[..i].chars().next_back().is_none_or(|c| c == '\n')
            && (rest.starts_with("//go:") || rest.starts_with("// +build"));
        let line = (syntax.contains(&Comment::Line) && rest.starts_with("//") && !directive)
            || (syntax.contains(&Comment::Hash) && rest.starts_with('#') && after_space(i))
            || (syntax.contains(&Comment::DashDash) && dash_dash);
        if line {
            let end = rest.find('\n').map_or(input.len(), |rel| i + rel);
            push(Piece::Comment, i, end);
            i = end;
            continue;
        }
        let ch = rest.chars().next().expect("non-empty rest");
        if matches!(ch, '"' | '\'' | '`') {
            let len = quoted_len(ext, rest, ch);
            push(Piece::Literal, i, i + len);
            i += len;
            continue;
        }
        push(Piece::Code, i, i + ch.len_utf8());
        i += ch.len_utf8();
    }
    out
}

/// Bytes of the literal of `syntax` that opens at `at` in `input`, delimiters included. One
/// that never closes runs to the end of the input.
fn literal_len(syntax: &[Literal], input: &str, at: usize) -> Option<usize> {
    let rest = &input[at..];
    syntax.iter().find_map(|form| match form {
        Literal::TripleDouble => triple_len(rest, b'"', true),
        Literal::TripleSingle => triple_len(rest, b'\'', true),
        Literal::RawTripleDouble => triple_len(rest, b'"', false),
        Literal::RawTripleSingle => triple_len(rest, b'\'', false),
        Literal::CsVerbatim => cs_verbatim_len(rest),
        Literal::LuaLong => long_bracket(rest).map(|_| long_bracket_len(rest)),
        Literal::CppRaw => cpp_raw_len(input, at),
        Literal::NixIndented => rest.starts_with("''").then(|| nix_indented_len(rest)),
    })
}

/// Bytes of the triple-quoted literal of `quote` that opens `rest`, a backslash escaping the
/// next byte when the form `escapes`. A run of quotes at the close ends it at the last three.
fn triple_len(rest: &str, quote: u8, escapes: bool) -> Option<usize> {
    let bytes = rest.as_bytes();
    if !bytes.starts_with(&[quote; 3]) {
        return None;
    }
    let mut i = 3;
    while i + 3 <= bytes.len() {
        if escapes && bytes[i] == b'\\' {
            i += 2;
            continue;
        }
        if bytes[i..i + 3] == [quote; 3] {
            let end = i + 3;
            return Some(end + bytes[end..].iter().take_while(|&&b| b == quote).count());
        }
        i += 1;
    }
    Some(rest.len())
}

/// Bytes of the C# verbatim string that opens `rest`, up to the `"` that no other `"`
/// follows.
fn cs_verbatim_len(rest: &str) -> Option<usize> {
    let prefix = ["@\"", "$@\"", "@$\""]
        .into_iter()
        .find(|p| rest.starts_with(p))?;
    let bytes = rest.as_bytes();
    let mut i = prefix.len();
    while i < bytes.len() {
        if bytes[i] == b'"' {
            if bytes.get(i + 1) == Some(&b'"') {
                i += 2;
                continue;
            }
            return Some(i + 1);
        }
        i += 1;
    }
    Some(rest.len())
}

/// The level of the Lua long bracket that opens `rest`, `[[` being 0 and `[==[` 2.
fn long_bracket(rest: &str) -> Option<usize> {
    let level = rest
        .strip_prefix('[')?
        .bytes()
        .take_while(|&b| b == b'=')
        .count();
    (rest.as_bytes().get(1 + level) == Some(&b'[')).then_some(level)
}

/// Bytes of the Lua long bracket that opens `rest`, up to its close of the same level.
fn long_bracket_len(rest: &str) -> usize {
    let level = long_bracket(rest).unwrap_or(0);
    let close = format!("]{}]", "=".repeat(level));
    let open = level + 2;
    rest[open..]
        .find(&close)
        .map_or(rest.len(), |rel| open + rel + close.len())
}

/// Bytes of the C++ raw string that opens at `at`, its prefix included: `R"` after nothing
/// that continues an identifier, or after a `u8`, `u`, `U` or `L` prefix, then a delimiter of
/// at most sixteen characters, `(`, and the close `)delim"`.
fn cpp_raw_len(input: &str, at: usize) -> Option<usize> {
    let ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
    if input[..at].chars().next_back().is_some_and(ident) {
        return None;
    }
    let rest = &input[at..];
    let prefix = ["u8R\"", "uR\"", "UR\"", "LR\"", "R\""]
        .into_iter()
        .find(|p| rest.starts_with(p))?;
    let body = &rest[prefix.len()..];
    let open = body.find('(')?;
    let delim = &body[..open];
    if delim.len() > 16 || delim.contains([' ', ')', '\\', '\n', '\t', '"']) {
        return None;
    }
    let close = format!("){delim}\"");
    let from = prefix.len() + open + 1;
    Some(
        rest[from..]
            .find(&close)
            .map_or(rest.len(), |rel| from + rel + close.len()),
    )
}

/// Bytes of the Nix indented string that opens `rest`, up to the `''` that closes it.
fn nix_indented_len(rest: &str) -> usize {
    let bytes = rest.as_bytes();
    let mut i = 2;
    while i + 1 < bytes.len() {
        if bytes[i] == b'\'' && bytes[i + 1] == b'\'' {
            match bytes.get(i + 2) {
                Some(b'\'' | b'$') => i += 3,
                Some(b'\\') => i += 4,
                _ => return i + 2,
            }
            continue;
        }
        i += 1;
    }
    rest.len()
}

/// How the single and double quotes of a language read: those whose strings run over lines,
/// and those in which a backslash is a byte.
struct Quotes {
    lines: &'static [char],
    raw: &'static [char],
}

/// The quotes of a language with no tested grammar, `None` where the table does not know its
/// string rules: a quote whose meaning depends on where it stands, as in YAML or XML, a dialect
/// that decides what a backslash does, as in SQL, or an extension several languages share.
fn quote_rules(ext: &str) -> Option<Quotes> {
    // § k6rfj5k37.e@ra0gz
    let (lines, raw): (&[char], &[char]) = match ext {
        "go" | "java" | "kt" | "kts" | "c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx"
        | "cs" | "swift" | "scala" | "sc" | "dart" | "groovy" | "gradle" | "proto" | "sol"
        | "mm" | "sv" | "awk" | "nim" | "hs" | "elm" | "ada" | "adb" | "ads" | "vhd" | "vhdl"
        | "lua" | "mk" | "cedar" => (&[], &[]),
        "toml" => (&[], &['\'']),
        "rb" | "pl" | "pm" | "r" | "php" | "ex" | "exs" | "fish" | "coffee" => (&['"', '\''], &[]),
        "zsh" | "ksh" => (&['"', '\''], &['\'']),
        "jl" | "cr" | "nix" | "cmake" => (&['"'], &[]),
        _ => return None,
    };
    Some(Quotes { lines, raw })
}

/// Bytes of the string literal that opens `rest` with `quote`, both quotes included. A
/// backslash escapes the next character, but in a Go backtick string or a quote the language
/// reads raw. A string its language closes on its line closes at the end of the line when its
/// quote never comes, so an apostrophe in prose does not swallow the file. A backtick string,
/// one its language runs over lines, and any string of a language whose rules are unknown,
/// runs to its quote, which keeps every byte it may hold.
fn quoted_len(ext: &str, rest: &str, quote: char) -> usize {
    // § k6rfj5k37.e@df838
    let rules = quote_rules(ext);
    let escapes =
        !(ext == "go" && quote == '`') && rules.as_ref().is_none_or(|q| !q.raw.contains(&quote));
    let lines = quote == '`' || rules.as_ref().is_none_or(|q| q.lines.contains(&quote));
    let mut chars = rest.char_indices().skip(1);
    while let Some((at, c)) = chars.next() {
        match c {
            '\\' if escapes => {
                chars.next();
            }
            '\n' if !lines => return at,
            c if c == quote => return at + c.len_utf8(),
            _ => {}
        }
    }
    rest.len()
}

/// The 1-based lines of `text` that open like a marker inside a string literal of a language
/// whose string rules the fallback does not know: neither a marker nor a value can be read
/// there, so `check` fails them.
pub fn undecided_lines(ext: &str, text: &str) -> Vec<usize> {
    // § xs2e8kj86.g@d9pwf
    if quote_rules(ext).is_some() || !text.contains('§') {
        return Vec::new();
    }
    literal_lines(ext, text)
        .into_iter()
        .zip(text.lines())
        .enumerate()
        .filter(|(_, (literal, line))| {
            *literal && crate::marker::opens_like_a_marker(line.trim_start())
        })
        .map(|(idx, _)| idx + 1)
        .collect()
}

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

    fn token(body: &str) -> String {
        token_in("go", body)
    }

    #[test]
    fn an_apostrophe_in_a_line_comment_opens_no_string() {
        let text = "// Staff can't read drafts.\npermit (principal, action, resource)\n// § abcdefgh1\nwhen { resource.owner == \"it's\" };\n";
        for ext in ["cedar", "xyz"] {
            assert_eq!(literal_lines(ext, text), vec![false; 4], "{ext}");
            assert!(undecided_lines(ext, text).is_empty(), "{ext}");
        }
        assert_ne!(
            token_in("cedar", text),
            token_in("cedar", &text.replace("\"it's\"", "\"its\""))
        );
        assert_eq!(
            token_in("cedar", text),
            token_in(
                "cedar",
                &text.replace("// Staff can't read drafts.", "// Other prose.")
            )
        );
    }

    fn token_in(ext: &str, body: &str) -> String {
        mint(ext, body, 1, body.lines().count() + 1, &[])
    }

    #[test]
    fn the_readme_language_table_and_fallback_warning_match_the_tested_grammars() {
        let readme =
            std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md"))
                .unwrap();
        let section = readme
            .split("\n## Languages\n")
            .nth(1)
            .and_then(|rest| rest.split("\n## ").next())
            .expect("README has a Languages section");
        let rows: Vec<(String, Vec<String>)> = section
            .lines()
            .filter(|line| line.starts_with("| ") && !line.starts_with("| Language"))
            .filter(|line| !line.starts_with("| ---"))
            .map(|line| {
                let cells: Vec<&str> = line.trim_matches('|').split('|').map(str::trim).collect();
                let grammar = cells[0].split(',').next().unwrap().to_lowercase();
                let exts = cells[1]
                    .split(", ")
                    .map(|e| e.trim_matches('`').trim_start_matches('.').to_string())
                    .collect();
                (grammar, exts)
            })
            .collect();
        let pinned: Vec<(String, Vec<String>)> = span_lang::PINNED
            .iter()
            .map(|lang| {
                let exts = lang.extensions.iter().map(|e| e.to_string()).collect();
                (lang.id.to_string(), exts)
            })
            .collect();
        assert_eq!(rows, pinned);
        let warning = format!("WRN {}", notice(Path::new("svc/pay.go"), "go"));
        assert!(
            section.lines().any(|line| line == warning),
            "the README fallback warning reads otherwise than:\n{warning}"
        );
    }

    #[test]
    fn a_trailing_separator_is_a_byte_of_a_fallback_span() {
        assert_ne!(token("f(\"a, )\");\n"), token("f(\"a)\");\n"));
        assert_ne!(token("f(a, b,\n);\n"), token("f(a, b);\n"));
        assert_ne!(token_in("jl", "t = (1,)\n"), token_in("jl", "t = (1)\n"));
        assert_ne!(token_in("hs", "u = (,)\n"), token_in("hs", "u = ()\n"));
        assert_eq!(
            token_in("jl", "t = (1,  )\n"),
            token_in("jl", "t = (1, )\n")
        );
        assert_eq!(token("f(a,\n  b);\n"), token("f(a, b);\n"));
    }

    #[test]
    fn only_ascii_whitespace_collapses() {
        assert_ne!(token("p(\"a\u{a0}b\")\n"), token("p(\"a b\")\n"));
        assert_ne!(token("p(\"a\u{3000}b\")\n"), token("p(\"a b\")\n"));
        assert_eq!(token("p(\"a \t\x0c b\")\n"), token("p(\"a b\")\n"));
    }

    #[test]
    fn a_multi_line_string_is_a_literal() {
        let toml = |q: &str, word: &str| format!("s = {q}\n# {word}\n{q}\n");
        for q in ["\"\"\"", "'''"] {
            assert_ne!(
                token_in("toml", &toml(q, "allow")),
                token_in("toml", &toml(q, "deny"))
            );
            assert_eq!(
                literal_lines("toml", &toml(q, "§ abcdefgh1")),
                [false, true, true]
            );
        }
        assert_eq!(
            token_in("toml", "p = '''C:\\''' # one\nq = 'C:\\' # one\n"),
            token_in("toml", "p = '''C:\\''' # two\nq = 'C:\\' # two\n")
        );
        let rb = |word: &str| format!("s = \"a\n# {word}\nb\" # note\n");
        assert_ne!(token_in("rb", &rb("allow")), token_in("rb", &rb("deny")));
        assert_eq!(
            token_in("rb", "s = \"a\nb\" # one\n"),
            token_in("rb", "s = \"a\nb\" # two\n")
        );
        assert_eq!(literal_lines("rb", &rb("§ abcdefgh1")), [false, true, true]);
        assert_eq!(
            literal_lines("go", "s := \"a\n// § abcdefgh1\n"),
            [false, false]
        );
    }

    #[test]
    fn a_marker_where_the_string_rules_are_unknown_is_undecided() {
        let open = "a = 'x\n# § abcdefgh1\n'\n";
        assert_eq!(literal_lines("conf", open), [false, true, true]);
        assert_eq!(undecided_lines("conf", open), [2]);
        assert_eq!(undecided_lines("yaml", open), [2]);
        assert!(undecided_lines("rb", open).is_empty());
        assert!(undecided_lines("conf", "a = 'x'\n# § abcdefgh1\n").is_empty());
    }

    #[test]
    fn comments_and_whitespace_do_not_move() {
        let clean = "save(x);\n";
        assert_eq!(token(clean), token("save(x); // line\n"));
        assert_eq!(token(clean), token("save(x); /* block */\n"));
        assert_eq!(token_in("rb", clean), token_in("rb", "save(x); # hash\n"));
        assert_eq!(
            token_in("sql", clean),
            token_in("sql", "save(x); -- dash\n")
        );
        assert_eq!(
            token_in("xml", clean),
            token_in("xml", "save(x); <!-- html -->\n")
        );
        assert_eq!(token(clean), token("save(x);   \n"));
        assert_eq!(token("save(  x  );\n"), token("save( x );\n"));
    }

    #[test]
    fn a_go_directive_is_code() {
        assert_ne!(
            token("//go:build linux\npackage a\n"),
            token("//go:build darwin\npackage a\n")
        );
        assert_ne!(token("//go:generate a\npackage a\n"), token("package a\n"));
        assert_ne!(
            token("// +build a\npackage a\n"),
            token("// +build b\npackage a\n")
        );
        assert_eq!(token("// note\npackage a\n"), token("package a\n"));
    }

    #[test]
    fn a_wrapper_the_language_does_not_use_is_code() {
        assert_ne!(
            token_in("c", "#define LIMIT 10\n"),
            token_in("c", "#define LIMIT 1000\n")
        );
        assert_ne!(
            token("for n--; n > 0; {charge()}\n"),
            token("for n--; n > 0; {refund()}\n")
        );
        assert_ne!(
            token_in("yaml", "run: x --dry-run\n"),
            token_in("yaml", "run: x --force\n")
        );
        assert_ne!(
            token_in("pl", "print $#a;\n"),
            token_in("pl", "print $#b;\n")
        );
        assert_ne!(token_in("hs", "a --> b\n"), token_in("hs", "a --> c\n"));
        assert_ne!(
            token_in("conf", "a = 1 # x\n"),
            token_in("conf", "a = 1 # y\n")
        );
    }

    #[test]
    fn nfc_normalizes() {
        let nfd = "cafe\u{0301}\n";
        let nfc = "caf\u{e9}\n";
        assert_eq!(token(nfd), token(nfc));
    }

    #[test]
    fn body_change_moves() {
        assert_ne!(token("save(x);\n"), token("save(x + 1);\n"));
    }

    #[test]
    fn a_fallback_pin_is_one_token() {
        assert_eq!(mint_clause("go", "save(x);\n", 1, 2, &[], "").len(), 5);
    }

    #[test]
    fn notice_links_github_search_and_new_issue() {
        let n = notice(Path::new("main.go"), "go");
        assert!(n.contains("fallback heuristic"), "{n}");
        assert!(n.contains("runs to the end of the file"), "{n}");
        assert!(n.contains("or to its `§ end` line"), "{n}");
        assert!(n.contains("rust (.rs)"), "{n}");
        assert!(n.contains("github.com/zifeo/silcrow/issues?q="), "{n}");
        assert!(n.contains("issues/new?title="), "{n}");
        assert!(n.contains("Add+tested+grammar"), "{n}");
        assert!(n.contains("Go"), "{n}");
    }

    #[test]
    fn punch_drops_inner_span() {
        let src = "aaa\ninner\nbbb\n";
        let full = mint("go", src, 1, 4, &[]);
        let punched = mint("go", src, 1, 4, &[(2, 3)]);
        assert_ne!(full, punched);
        assert_ne!(
            punched,
            mint("go", "aaa\nbbb\n", 1, 3, &[]),
            "the hole is a token"
        );
        assert_eq!(punched, mint("go", "aaa\nother\nbbb\n", 1, 4, &[(2, 3)]));
        assert_ne!(punched, mint("go", "inner\naaa\nbbb\n", 1, 4, &[(1, 2)]));
    }

    #[test]
    fn per_language_literals_and_operators_are_code() {
        assert_ne!(
            token_in("nix", "cfg // { enable = true; }\n"),
            token_in("nix", "cfg // { enable = false; }\n")
        );
        assert_eq!(
            token_in("nix", "x = 1; # one\n/* two */\n"),
            token_in("nix", "x = 1;\n")
        );
        assert_ne!(
            token_in("nix", "s = ''\n  # a\n'';\n"),
            token_in("nix", "s = ''\n  # b\n'';\n")
        );
        assert_ne!(
            token_in("kt", "val u = \"\"\"\nhttps://pay.example.com/v1\n\"\"\"\n"),
            token_in("kt", "val u = \"\"\"\nhttps://pay.example.com/v2\n\"\"\"\n")
        );
        assert_ne!(
            token_in("lua", "local s = [[\n-- allow\n]]\n"),
            token_in("lua", "local s = [[\n-- deny\n]]\n")
        );
        assert_ne!(
            token_in("lua", "local s = [==[\n]] -- allow\n]==]\n"),
            token_in("lua", "local s = [==[\n]] -- deny\n]==]\n")
        );
        assert_eq!(
            token_in("lua", "--[[ one\ntwo ]]\nx = 1\n"),
            token_in("lua", "x = 1\n")
        );
        assert_ne!(
            token_in("cpp", "auto s = R\"x(\n// allow\n)x\";\n"),
            token_in("cpp", "auto s = R\"x(\n// deny\n)x\";\n")
        );
        assert_eq!(token_in("cpp", "f(); // one\n"), token_in("cpp", "f();\n"));
    }

    #[test]
    fn a_crlf_file_hashes_as_its_lf_form() {
        let src = "u := `a\nb`\ns := \"\"\"\nc\n\"\"\" // d\n";
        assert_eq!(token(src), token(&src.replace('\n', "\r\n")));
        assert_eq!(
            token_in("kt", src),
            token_in("kt", &src.replace('\n', "\r\n"))
        );
    }

    #[test]
    fn a_raw_string_ends_at_its_quote_whatever_precedes_it() {
        let go = |host: &str| format!("d := `C:\\`\nu := `https://{host}/v1`\n");
        assert_ne!(
            token(&go("pay.example.com")),
            token(&go("evil.example.net"))
        );
        let kt = |host: &str| {
            format!("val d = \"\"\"C:\\\"\"\"\nval u = \"\"\"https://{host}/v1\"\"\"\n")
        };
        assert_ne!(
            token_in("kt", &kt("pay.example.com")),
            token_in("kt", &kt("evil.example.net"))
        );
        let cs = |host: &str| format!("var d = @\"C:\\\";\nvar u = \"https://{host}/v1\";\n");
        assert_ne!(
            token_in("cs", &cs("pay.example.com")),
            token_in("cs", &cs("evil.example.net"))
        );
        assert_ne!(
            token_in("cs", "f(@\"a\"\" // x\");\n"),
            token_in("cs", "f(@\"a\"\" // y\");\n")
        );
        let java = |host: &str| {
            format!("var s = \"\"\"\n  a \\\"\"\" b\n  https://{host}/v1\n  \"\"\";\n")
        };
        assert_ne!(
            token_in("java", &java("pay.example.com")),
            token_in("java", &java("evil.example.net"))
        );
        assert_eq!(
            literal_lines("go", "d := `C:\\`\n// § abcdefgh1\n"),
            [false, false]
        );
    }

    #[test]
    fn a_line_inside_a_multi_line_literal_is_named() {
        let kt = "val a = 1\nval s = \"\"\"\n// § abcdefgh1\n\"\"\"\n// § abcdefgh2\n";
        assert_eq!(literal_lines("kt", kt), [false, false, true, true, false]);
        let go = "x := `\n// § abcdefgh1\n`\n";
        assert_eq!(literal_lines("go", go), [false, true, true]);
        assert_eq!(
            literal_lines("go", "a // `\n// § abcdefgh1\n"),
            [false, false]
        );
    }

    #[test]
    fn comment_wrappers_inside_strings_are_kept() {
        assert_ne!(
            token("post(\"https://pay.example.com/v1/retry\")\n"),
            token("post(\"https://pay.example.com/v2/charge-anyway\")\n")
        );
        assert_ne!(
            token_in("sql", "q('a -- b')\n"),
            token_in("sql", "q('a -- c')\n")
        );
        assert_ne!(
            token_in("rb", "p(`x # y`)\n"),
            token_in("rb", "p(`x # z`)\n")
        );
        assert_ne!(token("p(\"\\\" // a\")\n"), token("p(\"\\\" // b\")\n"));
        assert_eq!(token("p(\"a\") // one\n"), token("p(\"a\") // two\n"));
        assert_eq!(
            token_in("rb", "p(\"it's\") # one\n"),
            token_in("rb", "p(\"it's\") # two\n")
        );
    }
}