reflex-search 2.3.0

A local-first, structure-aware code search engine for AI agents
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
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
//! Line-based pre-filtering to detect comments and string literals
//!
//! This module provides language-specific filters that analyze lines of code
//! to determine if a pattern match occurs inside a comment or string literal.
//! This enables us to skip files where ALL matches are in non-code contexts,
//! avoiding expensive tree-sitter parsing when possible.
//!
//! # Performance Impact
//!
//! Pre-filtering can reduce tree-sitter parsing workload by 2-5x:
//! - Pattern "mb_" in Linux kernel: 2,500 files → ~500 files to parse
//! - Expected speedup: 38s → ~1-2s for symbol queries
//!
//! # Design Philosophy
//!
//! - **Conservative**: Only skip files when 100% certain ALL matches are in comments/strings
//! - **Language-specific**: Each language has its own comment/string syntax rules
//! - **Line-based**: Fast heuristic analysis without full parsing
//! - **No false negatives**: Never skip files with valid code matches
//!
//! # How a line is read
//!
//! One left-to-right scan per question ([`region_at`]). It knows each language's
//! comments, strings, raw strings, char literals and string interpolation, so the
//! `//` of `"https://…"` is part of a string, not the start of a comment, and
//! `${call()}` inside a template literal is code. Through 2.2.0 each filter found the
//! first `//` or `#` on the line wherever it was, and dropped every match after it.
//!
//! A line is read without the lines around it, so two cases count as code (the match
//! is kept): a string that does not close on this line (it may be the end of a string
//! that began earlier), and the inside of a block comment that began on an earlier line.
//!
//! [`FileRegions`] reads a whole file with the same steps, so it also knows those two
//! cases. It refuses a file whose scan does not end in code; callers then use the line.

use crate::models::Language;

/// Trait for language-specific line filtering
pub trait LineFilter {
    /// Check if a position in a line is inside a comment
    ///
    /// # Arguments
    /// * `line` - The full line of text
    /// * `pattern_pos` - Byte position where the pattern starts (0-indexed)
    ///
    /// # Returns
    /// `true` if the pattern is definitely inside a comment, `false` otherwise
    fn is_in_comment(&self, line: &str, pattern_pos: usize) -> bool;

    /// Check if a position in a line is inside a string literal
    ///
    /// # Arguments
    /// * `line` - The full line of text
    /// * `pattern_pos` - Byte position where the pattern starts (0-indexed)
    ///
    /// # Returns
    /// `true` if the pattern is definitely inside a string literal, `false` otherwise
    fn is_in_string(&self, line: &str, pattern_pos: usize) -> bool;

    /// Check if a position in a line is inside a comment or a string literal, with
    /// one scan of the line instead of two.
    fn is_in_comment_or_string(&self, line: &str, pattern_pos: usize) -> bool {
        self.is_in_comment(line, pattern_pos) || self.is_in_string(line, pattern_pos)
    }
}

/// Get a LineFilter for a specific language
pub fn get_filter(lang: Language) -> Option<Box<dyn LineFilter>> {
    Some(Box::new(SyntaxFilter(syntax_of(lang)?)))
}

/// The comment and string rules for `lang`, `None` when it has none.
fn syntax_of(lang: Language) -> Option<Syntax> {
    let syntax = match lang {
        Language::Rust => Syntax::Rust,
        Language::C | Language::Cpp => Syntax::C,
        Language::Go => Syntax::Go,
        Language::Java => Syntax::Java,
        // Vue and Svelte: JS/TS in <script> sections; templates read the same way.
        Language::JavaScript | Language::TypeScript | Language::Vue | Language::Svelte => {
            Syntax::JavaScript
        }
        Language::Python => Syntax::Python,
        Language::Ruby => Syntax::Ruby,
        Language::PHP => Syntax::Php,
        Language::CSharp => Syntax::CSharp,
        Language::Kotlin => Syntax::Kotlin,
        Language::Zig => Syntax::Zig,
        // No filter for the text tier: "inside a string literal" is not a meaningful
        // idea in markdown or YAML, and guessing would drop real matches.
        Language::Text
        | Language::Lock
        | Language::Generated
        | Language::Swift
        | Language::Unknown => return None,
    };
    Some(syntax)
}

/// The comments and string literals of one whole file, so a block comment or a string
/// that spans lines is known (the line filter reads each line alone).
pub struct FileRegions {
    text: String,
    /// Sorted, disjoint byte ranges of `text` that are comment or string.
    non_code: Vec<std::ops::Range<usize>>,
    /// Byte offset of the start of each line.
    line_starts: Vec<usize>,
}

impl FileRegions {
    /// Scan `text`. `None` when `lang` has no rules, or when the scan does not end in
    /// code: an unclosed string or block comment, or a newline in a string that cannot
    /// hold one. A wrong scan would hide the rest of the file, so such a file is left
    /// to the line filter.
    pub fn new(lang: Language, text: String) -> Option<Self> {
        let non_code = non_code_ranges(syntax_of(lang)?, text.as_bytes())?;
        let line_starts = std::iter::once(0)
            .chain(text.match_indices('\n').map(|(i, _)| i + 1))
            .collect();
        Some(FileRegions {
            text,
            non_code,
            line_starts,
        })
    }

    /// Whether every occurrence of `pattern` on line `line` (1-based) is in a comment
    /// or a string; with `whole_word`, only occurrences that are a whole identifier
    /// count (`async_op` in `async_op_span` is not one). `Some(false)` when one is in
    /// code or none is found (keep the match); `None` when the line's text is not
    /// `expected` (the file changed), or no such line.
    pub fn line_is_non_code(
        &self,
        line: usize,
        expected: &str,
        pattern: &str,
        whole_word: bool,
    ) -> Option<bool> {
        let start = *self.line_starts.get(line.checked_sub(1)?)?;
        let end = self
            .line_starts
            .get(line)
            .map_or(self.text.len(), |&next| next - 1);
        let text = &self.text[start..end];
        // The engine shortens a long line's preview around the match, with `…` at a
        // cut end, so the line need only contain what is left.
        let expected = expected.trim().trim_matches('…').trim();
        if expected.is_empty() || !text.contains(expected) {
            return None;
        }
        let mut found = false;
        let b = text.as_bytes();
        for (at, _) in text.match_indices(pattern) {
            let end = at + pattern.len();
            if whole_word
                && (at > 0 && is_ident(b[at - 1]) || b.get(end).is_some_and(|&c| is_ident(c)))
            {
                continue;
            }
            found = true;
            if !self.is_non_code(start + at) {
                return Some(false);
            }
        }
        Some(found)
    }

    fn is_non_code(&self, pos: usize) -> bool {
        let i = self.non_code.partition_point(|r| r.end <= pos);
        self.non_code.get(i).is_some_and(|r| r.start <= pos)
    }
}

/// Whether a string of `kind` may hold a newline. Where the language forbids it, a
/// newline means the scan went wrong.
fn multiline_string(syntax: Syntax, kind: StrKind) -> bool {
    match kind.close {
        Close::Triple(_) | Close::RustRaw(_) | Close::CppRaw(..) => true,
        Close::Byte(b'`') => true,
        Close::Byte(_) => {
            kind.doubled_quote || matches!(syntax, Syntax::Rust | Syntax::Ruby | Syntax::Php)
        }
    }
}

/// The comment and string ranges of a whole file (see [`FileRegions::new`]), with the
/// steps [`region_at`] takes on one line.
fn non_code_ranges(syntax: Syntax, b: &[u8]) -> Option<Vec<std::ops::Range<usize>>> {
    let line_end = |i: usize| {
        b[i..]
            .iter()
            .position(|&c| c == b'\n')
            .map_or(b.len(), |n| i + n)
    };
    let mut out = Vec::new();
    let mut stack: Vec<Frame> = Vec::new();
    // Start of the string text since its opener or the last interpolation.
    let mut seg = 0;
    let mut i = 0;
    while i < b.len() {
        match stack.last().copied() {
            Some(Frame::Str(kind)) => {
                if b[i] == b'\n' && !multiline_string(syntax, kind) {
                    return None;
                }
                match string_step(b, i, kind) {
                    StrStep::Skip(n) => i += n,
                    StrStep::Close(n) => {
                        i += n;
                        out.push(seg..i);
                        stack.pop();
                    }
                    StrStep::Interp(n) => {
                        i += n;
                        out.push(seg..i);
                        stack.push(Frame::Interp(0));
                    }
                    StrStep::CodeSpan(end) => {
                        out.push(seg..i);
                        i = end;
                        seg = i;
                    }
                }
            }
            top => match code_step(syntax, b, i) {
                CodeStep::LineComment => {
                    let end = line_end(i);
                    out.push(i..end);
                    i = end;
                }
                CodeStep::Span(end, region) => {
                    let end = if syntax == Syntax::Zig && b[i] == b'\\' {
                        line_end(i) // a Zig `\\` string is the rest of the line
                    } else {
                        end
                    };
                    let text = &b[i..end];
                    if b[i] == b'/' && region == Region::Str && text.contains(&b'\n') {
                        i += 1; // a "regex" across lines is a division
                        continue;
                    }
                    if region == Region::Comment && !text.ends_with(b"*/") {
                        return None; // unclosed block comment
                    }
                    if region != Region::Code {
                        out.push(i..end);
                    }
                    i = end;
                }
                CodeStep::Open(n, kind) => {
                    seg = i;
                    stack.push(Frame::Str(kind));
                    i += n;
                }
                CodeStep::Byte => {
                    if let Some(Frame::Interp(depth)) = top {
                        match b[i] {
                            b'{' => *stack.last_mut().unwrap() = Frame::Interp(depth + 1),
                            b'}' if depth == 0 => {
                                stack.pop();
                                i += 1;
                                seg = i;
                                continue;
                            }
                            b'}' => *stack.last_mut().unwrap() = Frame::Interp(depth - 1),
                            _ => {}
                        }
                    }
                    i += 1;
                }
            },
        }
    }
    stack.is_empty().then_some(out)
}

/// The comment and string rules of one language family.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Syntax {
    Rust,
    /// C and C++ (C++ raw strings `R"x(…)x"` and digit separators `1'000` included).
    C,
    Go,
    Java,
    /// JavaScript, TypeScript, Vue and Svelte.
    JavaScript,
    Python,
    Ruby,
    Php,
    CSharp,
    Kotlin,
    Zig,
}

impl Syntax {
    fn slash_comments(self) -> bool {
        !matches!(self, Syntax::Python | Syntax::Ruby)
    }

    fn hash_comments(self) -> bool {
        matches!(self, Syntax::Python | Syntax::Ruby | Syntax::Php)
    }

    fn block_comments(self) -> bool {
        !matches!(self, Syntax::Python | Syntax::Ruby | Syntax::Zig)
    }

    fn nested_block_comments(self) -> bool {
        matches!(self, Syntax::Rust | Syntax::Kotlin)
    }

    /// `'x'` is a char literal; elsewhere `'` delimits a string.
    fn char_literals(self) -> bool {
        matches!(
            self,
            Syntax::Rust
                | Syntax::C
                | Syntax::Go
                | Syntax::Java
                | Syntax::CSharp
                | Syntax::Kotlin
                | Syntax::Zig
        )
    }
}

struct SyntaxFilter(Syntax);

impl LineFilter for SyntaxFilter {
    fn is_in_comment(&self, line: &str, pattern_pos: usize) -> bool {
        region_at(self.0, line, pattern_pos) == Region::Comment
    }

    fn is_in_string(&self, line: &str, pattern_pos: usize) -> bool {
        region_at(self.0, line, pattern_pos) == Region::Str
    }

    fn is_in_comment_or_string(&self, line: &str, pattern_pos: usize) -> bool {
        region_at(self.0, line, pattern_pos) != Region::Code
    }
}

/// What a position of a line is, as far as the line alone can tell.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Region {
    /// Code, or not known (the conservative answer).
    Code,
    Comment,
    Str,
}

#[derive(Debug, Clone, Copy)]
enum Frame {
    Str(StrKind),
    /// Code inside a string (`${…}`, `#{…}`, `{…}`), with its open `{` count.
    Interp(u32),
}

#[derive(Debug, Clone, Copy)]
struct StrKind {
    close: Close,
    /// `\` escapes the next byte.
    backslash: bool,
    /// `""` is an escaped quote (C# verbatim strings).
    doubled_quote: bool,
    interp: Interp,
}

#[derive(Debug, Clone, Copy)]
enum Close {
    /// One delimiter byte: `"`, `'` or a backtick.
    Byte(u8),
    /// Three delimiter bytes: `"""` or `'''`.
    Triple(u8),
    /// Rust raw string: `"` and this many `#`.
    RustRaw(usize),
    /// C++ raw string: `)`, the delimiter at `line[start..end]`, `"`.
    CppRaw(usize, usize),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Interp {
    None,
    /// `${…}` (JavaScript template literals).
    DollarBrace,
    /// `${…}` and `$name` (Kotlin).
    Kotlin,
    /// `{…}`, with `{{` and `}}` as literal braces (Python f-strings, C# `$"…"`).
    Brace,
    /// `#{…}` (Ruby).
    HashBrace,
    /// `{$…}` and `$name->prop` (PHP).
    Php,
}

impl StrKind {
    fn plain(quote: u8) -> Self {
        StrKind {
            close: Close::Byte(quote),
            backslash: true,
            doubled_quote: false,
            interp: Interp::None,
        }
    }

    fn raw(close: Close) -> Self {
        StrKind {
            close,
            backslash: false,
            doubled_quote: false,
            interp: Interp::None,
        }
    }

    fn with_interp(self, interp: Interp) -> Self {
        StrKind { interp, ..self }
    }
}

enum CodeStep {
    /// A line comment starts here: the rest of the line is a comment.
    LineComment,
    /// `[i, end)` is one token of this region (block comment, char literal, regex).
    Span(usize, Region),
    /// A string opens with an opener of this many bytes.
    Open(usize, StrKind),
    Byte,
}

enum StrStep {
    Skip(usize),
    /// The string closes with a delimiter of this many bytes.
    Close(usize),
    /// An interpolation opens with an opener of this many bytes.
    Interp(usize),
    /// `[i, end)` is code inside the string (`$name`).
    CodeSpan(usize),
}

/// Classify byte `pos` of `line`.
fn region_at(syntax: Syntax, line: &str, pos: usize) -> Region {
    let b = line.as_bytes();
    let mut stack: Vec<Frame> = Vec::new();
    // Set once the scan reaches `pos` inside a string: that string's depth on `stack`.
    // The answer is `Str` only if that string closes on this line.
    let mut open_at: Option<usize> = None;
    let mut i = 0;

    loop {
        if open_at.is_none() && i >= pos {
            match stack.last() {
                Some(Frame::Str(_)) => open_at = Some(stack.len()),
                _ => return Region::Code,
            }
        }
        if i >= b.len() {
            // The string that holds `pos` does not close on this line.
            return Region::Code;
        }
        let reached = open_at.is_some();

        match stack.last().copied() {
            Some(Frame::Str(kind)) => match string_step(b, i, kind) {
                StrStep::Skip(n) => i += n,
                StrStep::Close(n) => {
                    stack.pop();
                    i += n;
                    if open_at.is_some_and(|depth| stack.len() < depth) {
                        return Region::Str;
                    }
                }
                StrStep::Interp(n) => {
                    stack.push(Frame::Interp(0));
                    i += n;
                }
                StrStep::CodeSpan(end) => {
                    if !reached && pos < end {
                        return Region::Code;
                    }
                    i = end;
                }
            },
            top => match code_step(syntax, b, i) {
                CodeStep::LineComment => {
                    // Not reached: `pos` lies after the comment start.
                    return if reached {
                        Region::Code
                    } else {
                        Region::Comment
                    };
                }
                CodeStep::Span(end, region) => {
                    if !reached && pos < end {
                        return region;
                    }
                    i = end;
                }
                CodeStep::Open(n, kind) => {
                    if !reached && pos < i + n {
                        return Region::Code;
                    }
                    stack.push(Frame::Str(kind));
                    i += n;
                }
                CodeStep::Byte => {
                    if let Some(Frame::Interp(depth)) = top {
                        match b[i] {
                            b'{' => *stack.last_mut().unwrap() = Frame::Interp(depth + 1),
                            b'}' if depth == 0 => {
                                stack.pop();
                            }
                            b'}' => *stack.last_mut().unwrap() = Frame::Interp(depth - 1),
                            _ => {}
                        }
                    }
                    i += 1;
                }
            },
        }
    }
}

/// One step of the scan in code at `b[i]`.
fn code_step(syntax: Syntax, b: &[u8], i: usize) -> CodeStep {
    let next = b.get(i + 1).copied();
    match b[i] {
        b'/' if next == Some(b'/') && syntax.slash_comments() => CodeStep::LineComment,
        b'/' if next == Some(b'*') && syntax.block_comments() => {
            CodeStep::Span(block_comment_end(syntax, b, i), Region::Comment)
        }
        b'/' if syntax == Syntax::JavaScript && regex_can_start(b, i) => match regex_end(b, i) {
            Some(end) => CodeStep::Span(end, Region::Str),
            None => CodeStep::Byte,
        },
        // PHP 8 attributes (`#[Route(…)]`) are code.
        b'#' if syntax.hash_comments() && !(syntax == Syntax::Php && next == Some(b'[')) => {
            CodeStep::LineComment
        }
        // Zig multiline string literal: the rest of the line is the string.
        b'\\' if syntax == Syntax::Zig && next == Some(b'\\') => {
            CodeStep::Span(b.len(), Region::Str)
        }
        b'\'' if syntax.char_literals() => match char_literal_end(b, i) {
            Some(end) => CodeStep::Span(end, Region::Str),
            None => CodeStep::Byte,
        },
        b'"' | b'\'' | b'`' => match open_string(syntax, b, i) {
            Some((n, kind)) => CodeStep::Open(n, kind),
            None => CodeStep::Byte,
        },
        _ => CodeStep::Byte,
    }
}

/// The string that a quote at `b[i]` opens, and the length of its opener. A prefix
/// before the quote (`r#`, `f`, `@$`, `R`) was already read as code; it is looked
/// up behind the quote.
fn open_string(syntax: Syntax, b: &[u8], i: usize) -> Option<(usize, StrKind)> {
    let q = b[i];
    let triple = b.get(i..i + 3) == Some(&[q, q, q][..]);
    match syntax {
        Syntax::Rust => (q == b'"').then(|| (1, rust_string(b, i))),
        Syntax::C => (q == b'"').then(|| cpp_string(b, i)),
        Syntax::Go => match q {
            b'"' => Some((1, StrKind::plain(q))),
            b'`' => Some((1, StrKind::raw(Close::Byte(q)))),
            _ => None,
        },
        Syntax::Java | Syntax::Zig => match q {
            b'"' if triple && syntax == Syntax::Java => Some((
                3,
                StrKind {
                    close: Close::Triple(q),
                    ..StrKind::plain(q)
                },
            )),
            b'"' => Some((1, StrKind::plain(q))),
            _ => None,
        },
        Syntax::JavaScript => match q {
            b'`' => Some((1, StrKind::plain(q).with_interp(Interp::DollarBrace))),
            _ => Some((1, StrKind::plain(q))),
        },
        Syntax::Python => {
            if q == b'`' {
                return None;
            }
            // Prefixes: r, b, f, u, t and two-letter mixes (rb, fr, …).
            let prefix = ident_run_before(b, i);
            let f_string = prefix.len() <= 2
                && prefix.iter().all(|c| b"rRbBfFuUtT".contains(c))
                && prefix.iter().any(|c| b"fFtT".contains(c));
            let kind = if triple {
                StrKind {
                    close: Close::Triple(q),
                    ..StrKind::plain(q)
                }
            } else {
                StrKind::plain(q)
            };
            let kind = if f_string {
                kind.with_interp(Interp::Brace)
            } else {
                kind
            };
            Some((if triple { 3 } else { 1 }, kind))
        }
        Syntax::Ruby => match q {
            b'\'' => Some((1, StrKind::plain(q))),
            _ => Some((1, StrKind::plain(q).with_interp(Interp::HashBrace))),
        },
        Syntax::Php => match q {
            b'\'' => Some((1, StrKind::plain(q))),
            _ => Some((1, StrKind::plain(q).with_interp(Interp::Php))),
        },
        Syntax::CSharp => {
            if q != b'"' {
                return None;
            }
            let mut j = i;
            while j > 0 && matches!(b[j - 1], b'@' | b'$') {
                j -= 1;
            }
            let prefix = &b[j..i];
            let interp = if prefix.contains(&b'$') {
                Interp::Brace
            } else {
                Interp::None
            };
            if prefix.contains(&b'@') {
                // Verbatim: `\` is a plain byte, `""` is a quote.
                return Some((
                    1,
                    StrKind {
                        close: Close::Byte(q),
                        backslash: false,
                        doubled_quote: true,
                        interp,
                    },
                ));
            }
            if triple {
                // C# 11 raw string literal.
                return Some((3, StrKind::raw(Close::Triple(q)).with_interp(interp)));
            }
            Some((1, StrKind::plain(q).with_interp(interp)))
        }
        Syntax::Kotlin => match q {
            b'"' if triple => Some((
                3,
                StrKind::raw(Close::Triple(q)).with_interp(Interp::Kotlin),
            )),
            b'"' => Some((1, StrKind::plain(q).with_interp(Interp::Kotlin))),
            _ => None,
        },
    }
}

/// `"…"`, `b"…"`, or a raw string `r"…"`, `r#"…"#`, `br##"…"##`.
fn rust_string(b: &[u8], i: usize) -> StrKind {
    let mut j = i;
    while j > 0 && b[j - 1] == b'#' {
        j -= 1;
    }
    let hashes = i - j;
    let prefix = ident_run_before(b, j);
    if matches!(prefix, b"r" | b"br" | b"cr") {
        StrKind::raw(Close::RustRaw(hashes))
    } else {
        StrKind::plain(b'"')
    }
}

/// `"…"`, or a C++ raw string `R"delim(…)delim"` (also `LR`, `uR`, `UR`, `u8R`).
fn cpp_string(b: &[u8], i: usize) -> (usize, StrKind) {
    let prefix = ident_run_before(b, i);
    if matches!(prefix, b"R" | b"LR" | b"uR" | b"UR" | b"u8R") {
        let start = i + 1;
        let delim_len = b[start..]
            .iter()
            .take(17)
            .position(|&c| c == b'(')
            .filter(|&n| {
                b[start..start + n]
                    .iter()
                    .all(|c| !c.is_ascii_whitespace() && !b")\\\"".contains(c))
            });
        if let Some(n) = delim_len {
            let end = start + n;
            return (end + 1 - i, StrKind::raw(Close::CppRaw(start, end)));
        }
    }
    (1, StrKind::plain(b'"'))
}

/// One step of the scan inside a string at `b[i]`.
fn string_step(b: &[u8], i: usize, kind: StrKind) -> StrStep {
    let c = b[i];
    let next = b.get(i + 1).copied();
    if kind.backslash && c == b'\\' {
        return StrStep::Skip(2);
    }
    if kind.doubled_quote && c == b'"' && next == Some(b'"') {
        return StrStep::Skip(2);
    }
    if let Some(n) = closes(kind.close, b, i) {
        return StrStep::Close(n);
    }
    match (kind.interp, c, next) {
        (Interp::DollarBrace | Interp::Kotlin, b'$', Some(b'{')) => StrStep::Interp(2),
        (Interp::Kotlin, b'$', Some(n)) if is_ident_start(n) => {
            StrStep::CodeSpan(ident_end(b, i + 1))
        }
        (Interp::Brace, b'{', Some(b'{')) | (Interp::Brace, b'}', Some(b'}')) => StrStep::Skip(2),
        (Interp::Brace, b'{', _) => StrStep::Interp(1),
        (Interp::HashBrace, b'#', Some(b'{')) => StrStep::Interp(2),
        (Interp::Php, b'{', Some(b'$')) => StrStep::Interp(1),
        (Interp::Php, b'$', Some(n)) if is_ident_start(n) => {
            let mut end = ident_end(b, i + 1);
            while b[end..].starts_with(b"->") && b.get(end + 2).is_some_and(|&c| is_ident_start(c))
            {
                end = ident_end(b, end + 2);
            }
            StrStep::CodeSpan(end)
        }
        _ => StrStep::Skip(1),
    }
}

/// The length of the closing delimiter at `b[i]`, if one is there.
fn closes(close: Close, b: &[u8], i: usize) -> Option<usize> {
    let rest = &b[i..];
    match close {
        Close::Byte(q) => (rest[0] == q).then_some(1),
        Close::Triple(q) => rest.starts_with(&[q, q, q]).then_some(3),
        Close::RustRaw(hashes) => {
            (rest[0] == b'"' && rest.len() > hashes && rest[1..=hashes].iter().all(|&c| c == b'#'))
                .then_some(1 + hashes)
        }
        Close::CppRaw(start, end) => {
            let delim = &b[start..end];
            (rest[0] == b')'
                && rest[1..].starts_with(delim)
                && rest.get(1 + delim.len()) == Some(&b'"'))
            .then_some(2 + delim.len())
        }
    }
}

/// The end of the block comment that starts at `b[i]` (`/*`), or the line's end.
fn block_comment_end(syntax: Syntax, b: &[u8], i: usize) -> usize {
    let nested = syntax.nested_block_comments();
    let mut depth = 1;
    let mut j = i + 2;
    while j < b.len() {
        if b[j..].starts_with(b"*/") {
            depth -= 1;
            j += 2;
            if depth == 0 {
                return j;
            }
        } else if nested && b[j..].starts_with(b"/*") {
            depth += 1;
            j += 2;
        } else {
            j += 1;
        }
    }
    b.len()
}

/// The end of a char literal that starts at `b[i]` (`'`): one character, or one escape
/// (`'\n'`, `'\''`, `'\u{1F600}'`). `None` for a Rust lifetime or label (`'a`), a C++
/// digit separator (`1'000`) or anything longer, which stay code.
fn char_literal_end(b: &[u8], i: usize) -> Option<usize> {
    let body = i + 1;
    match *b.get(body)? {
        b'\\' => {
            let from = body + 2;
            let close = b.get(from..)?.iter().take(10).position(|&c| c == b'\'')?;
            Some(from + close + 1)
        }
        b'\'' => None,
        c => {
            let end = body + utf8_len(c);
            (b.get(end) == Some(&b'\'')).then_some(end + 1)
        }
    }
}

/// Whether a `/` at `b[i]` starts a JavaScript regex literal rather than a division:
/// the usual rule, by the token before it.
fn regex_can_start(b: &[u8], i: usize) -> bool {
    let mut j = i;
    while j > 0 && b[j - 1].is_ascii_whitespace() {
        j -= 1;
    }
    if j == 0 {
        return true;
    }
    let c = b[j - 1];
    if is_ident(c) || c == b'$' {
        return matches!(
            ident_run_before(b, j),
            b"return"
                | b"typeof"
                | b"instanceof"
                | b"in"
                | b"of"
                | b"new"
                | b"delete"
                | b"void"
                | b"throw"
                | b"case"
                | b"do"
                | b"else"
                | b"yield"
                | b"await"
        );
    }
    b"(,=:[!&|?{};+-*%<>~^".contains(&c)
}

/// The end of the regex literal that starts at `b[i]`, if it closes on this line.
fn regex_end(b: &[u8], i: usize) -> Option<usize> {
    let mut in_class = false;
    let mut j = i + 1;
    while j < b.len() {
        match b[j] {
            b'\\' => j += 1,
            b'[' => in_class = true,
            b']' => in_class = false,
            b'/' if !in_class => return Some(j + 1),
            _ => {}
        }
        j += 1;
    }
    None
}

fn is_ident(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == b'_' || c >= 0x80
}

fn is_ident_start(c: u8) -> bool {
    c.is_ascii_alphabetic() || c == b'_' || c >= 0x80
}

/// The identifier bytes that end just before `b[i]`.
fn ident_run_before(b: &[u8], i: usize) -> &[u8] {
    let mut j = i;
    while j > 0 && is_ident(b[j - 1]) {
        j -= 1;
    }
    &b[j..i]
}

fn ident_end(b: &[u8], start: usize) -> usize {
    let mut j = start;
    while j < b.len() && is_ident(b[j]) {
        j += 1;
    }
    j
}

/// The byte length of the UTF-8 character that starts with `c`.
fn utf8_len(c: u8) -> usize {
    match c {
        0xF0.. => 4,
        0xE0.. => 3,
        0xC0.. => 2,
        _ => 1,
    }
}

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

    const TARGET: &str = "call_the_target";

    fn filter(lang: Language) -> Box<dyn LineFilter> {
        get_filter(lang).expect("a filter")
    }

    /// The region of the first `call_the_target` on `line`.
    fn region(lang: Language, line: &str) -> Region {
        let pos = line.find(TARGET).expect("the target is on the line");
        let f = filter(lang);
        match (f.is_in_comment(line, pos), f.is_in_string(line, pos)) {
            (true, false) => Region::Comment,
            (false, true) => Region::Str,
            (false, false) => Region::Code,
            (true, true) => panic!("both a comment and a string: {line}"),
        }
    }

    fn assert_regions(lang: Language, cases: &[(&str, Region)]) {
        for (line, want) in cases {
            assert_eq!(region(lang, line), *want, "{lang:?}: {line}");
            let pos = line.find(TARGET).unwrap();
            assert_eq!(
                filter(lang).is_in_comment_or_string(line, pos),
                *want != Region::Code,
                "{lang:?} one-scan answer: {line}"
            );
        }
    }

    use Region::{Code, Comment, Str};

    // ========================================================================
    // Rust Tests
    // ========================================================================

    #[test]
    fn test_rust_single_line_comment() {
        let filter = filter(Language::Rust);
        let line = "let x = 5; // extract_symbols here";
        assert!(filter.is_in_comment(line, 15)); // "extract" is in comment
        assert!(!filter.is_in_comment(line, 4)); // "x" is not in comment
    }

    #[test]
    fn test_rust_multiline_comment() {
        let filter = filter(Language::Rust);
        let line = "let x = /* extract_symbols */ 5;";
        assert!(filter.is_in_comment(line, 11)); // "extract" is in comment
        assert!(!filter.is_in_comment(line, 30)); // "5" is not in comment
    }

    #[test]
    fn test_rust_string_literal() {
        let filter = filter(Language::Rust);
        let line = r#"let s = "extract_symbols";"#;
        assert!(filter.is_in_string(line, 9)); // "extract" is in string
        assert!(!filter.is_in_string(line, 27)); // after string
    }

    #[test]
    fn test_rust_raw_string() {
        let filter = filter(Language::Rust);
        let line = r#"let s = r"extract_symbols";"#;
        assert!(filter.is_in_string(line, 10)); // "extract" is in raw string
    }

    #[test]
    fn test_rust_raw_string_with_hashes() {
        let filter = filter(Language::Rust);
        let line = r###"let s = r#"extract_symbols"#;"###;
        assert!(filter.is_in_string(line, 11)); // "extract" is in raw string
    }

    #[test]
    fn test_rust_escaped_quote() {
        let filter = filter(Language::Rust);
        let line = r#"let s = "before \" extract_symbols after";"#;
        assert!(filter.is_in_string(line, 15)); // "extract" is in string
    }

    #[test]
    fn rust_comment_markers_inside_strings_are_not_comments() {
        assert_regions(
            Language::Rust,
            &[
                (
                    r#"let url = "https://example.com/api"; call_the_target();"#,
                    Code,
                ),
                (r#"let g = "src/*.rs"; call_the_target();"#, Code),
                (r#"let s = "//"; // call_the_target"#, Comment),
                (r##"let s = r#"a "// b"#; call_the_target();"##, Code),
                (r#"let s = "a \"//\" b"; call_the_target();"#, Code),
            ],
        );
    }

    #[test]
    fn rust_char_literals_and_lifetimes() {
        assert_regions(
            Language::Rust,
            &[
                (r#"let q = '"'; call_the_target("x");"#, Code),
                (r#"let q = '\''; call_the_target("x");"#, Code),
                (r#"let q = b'"'; call_the_target("x");"#, Code),
                (r#"fn f<'a>(x: &'a str) { call_the_target("x") }"#, Code),
                (r#"'outer: loop { call_the_target("x") }"#, Code),
                ("let r#type = 1; call_the_target();", Code),
            ],
        );
    }

    #[test]
    fn rust_nested_block_comments() {
        assert_regions(
            Language::Rust,
            &[
                ("/* a /* b */ call_the_target */ x", Comment),
                ("/* a /* b */ c */ call_the_target()", Code),
            ],
        );
    }

    #[test]
    fn a_string_that_does_not_close_on_the_line_is_not_known() {
        // The end of a string that began on an earlier line, then code.
        assert_regions(Language::Rust, &[(r#"    ", call_the_target);"#, Code)]);
        // The start of a string that ends on a later line: also kept.
        assert_regions(Language::Rust, &[(r#"let s = "call_the_target"#, Code)]);
        // A block comment that does not close on the line is still a comment.
        assert_regions(Language::Rust, &[("x(); /* call_the_target", Comment)]);
    }

    // ========================================================================
    // C / C++ Tests
    // ========================================================================

    #[test]
    fn c_strings_char_literals_and_raw_strings() {
        assert_regions(
            Language::C,
            &[
                (r#"printf("/* not a comment */"); call_the_target();"#, Code),
                (r#"puts("http://x"); call_the_target();"#, Code),
                (r#"char c = '"'; call_the_target();"#, Code),
                ("int x = 1; // call_the_target", Comment),
                ("int x = /* call_the_target */ 1;", Comment),
            ],
        );
        assert_regions(
            Language::Cpp,
            &[
                (r#"auto s = R"x(call_the_target)x";"#, Str),
                (r#"auto s = R"x(a )" // b)x"; call_the_target();"#, Code),
                (r#"auto s = u8R"(//)"; call_the_target();"#, Code),
                ("int n = 1'000'000; call_the_target('a');", Code),
                ("int n = 1'000; call_the_target('a');", Code),
            ],
        );
    }

    // ========================================================================
    // Go Tests
    // ========================================================================

    #[test]
    fn test_go_raw_string() {
        let filter = filter(Language::Go);
        let line = "s := `extract_symbols`";
        assert!(filter.is_in_string(line, 6));
    }

    #[test]
    fn go_comment_markers_inside_strings_are_not_comments() {
        assert_regions(
            Language::Go,
            &[
                ("s := `//` + call_the_target()", Code),
                (r#"u := "https://x"; call_the_target()"#, Code),
                (r#"r := '"'; call_the_target()"#, Code),
                ("x := 1 // call_the_target", Comment),
            ],
        );
    }

    // ========================================================================
    // Java Tests
    // ========================================================================

    #[test]
    fn java_strings_and_comments() {
        assert_regions(
            Language::Java,
            &[
                (r#"String u = "https://x"; call_the_target();"#, Code),
                (r#"String s = "call_the_target";"#, Str),
                (r#"char c = '"'; call_the_target();"#, Code),
                ("/** call_the_target */", Comment),
            ],
        );
    }

    // ========================================================================
    // JavaScript Tests
    // ========================================================================

    #[test]
    fn test_js_single_line_comment() {
        let filter = filter(Language::JavaScript);
        let line = "let x = 5; // extract_symbols here";
        assert!(filter.is_in_comment(line, 15));
        assert!(!filter.is_in_comment(line, 4));
    }

    #[test]
    fn test_js_string_double_quote() {
        let filter = filter(Language::JavaScript);
        let line = r#"let s = "extract_symbols";"#;
        assert!(filter.is_in_string(line, 9));
        assert!(!filter.is_in_string(line, 27));
    }

    #[test]
    fn test_js_string_single_quote() {
        let filter = filter(Language::JavaScript);
        let line = "let s = 'extract_symbols';";
        assert!(filter.is_in_string(line, 9));
    }

    #[test]
    fn test_js_template_literal() {
        let filter = filter(Language::JavaScript);
        let line = "let s = `extract_symbols`;";
        assert!(filter.is_in_string(line, 9));
    }

    #[test]
    fn js_comment_markers_inside_strings_are_not_comments() {
        assert_regions(
            Language::JavaScript,
            &[
                (r#"const u = "https://x"; call_the_target(u);"#, Code),
                ("const u = 'http://x', v = call_the_target();", Code),
                // Minified: one early URL used to hide every later match.
                (
                    r#"var a="https://cdn.x/y.js",b=1;function f(){return call_the_target(a)}"#,
                    Code,
                ),
            ],
        );
    }

    #[test]
    fn js_template_interpolation_is_code() {
        assert_regions(
            Language::JavaScript,
            &[
                ("const s = `${call_the_target(user)}`;", Code),
                ("const s = `a ${x} call_the_target`;", Str),
                ("const s = `a ${ {k: 1}.k } call_the_target`;", Str),
                ("const s = `${`${call_the_target()}`}`;", Code),
                ("const s = `${'}'} call_the_target`;", Str),
            ],
        );
    }

    #[test]
    fn js_regex_literals() {
        assert_regions(
            Language::JavaScript,
            &[
                (r"const re = /^https?:\/\//; call_the_target(re);", Code),
                (r#"if (/"/.test(s)) call_the_target("x");"#, Code),
                (r"s.replace(/[/]/g, '-'); call_the_target();", Code),
                ("const n = a / b; // call_the_target", Comment),
                ("const n = a / b / call_the_target;", Code),
                ("return /call_the_target/.test(s);", Str),
            ],
        );
    }

    #[test]
    fn typescript_vue_and_svelte_read_like_javascript() {
        for lang in [Language::TypeScript, Language::Vue, Language::Svelte] {
            assert_regions(
                lang,
                &[
                    (r#"const u = "https://x"; call_the_target(u);"#, Code),
                    ("// call_the_target", Comment),
                ],
            );
        }
    }

    // ========================================================================
    // Python Tests
    // ========================================================================

    #[test]
    fn test_python_comment() {
        let filter = filter(Language::Python);
        let line = "x = 5  # extract_symbols here";
        assert!(filter.is_in_comment(line, 9));
        assert!(!filter.is_in_comment(line, 0));
    }

    #[test]
    fn test_python_string() {
        let filter = filter(Language::Python);
        let line = r#"s = "extract_symbols""#;
        assert!(filter.is_in_string(line, 5));
    }

    #[test]
    fn test_python_triple_quote() {
        let filter = filter(Language::Python);
        let line = r#"s = """extract_symbols""""#;
        assert!(filter.is_in_string(line, 7));
    }

    #[test]
    fn python_hash_inside_strings_is_not_a_comment() {
        assert_regions(
            Language::Python,
            &[
                (r##"color = "#fff"; call_the_target(color)"##, Code),
                ("tag = '#x'; call_the_target()", Code),
                (r##"s = """# a""" + call_the_target()"##, Code),
                ("x = 1  # call_the_target", Comment),
            ],
        );
    }

    #[test]
    fn python_f_string_interpolation_is_code() {
        assert_regions(
            Language::Python,
            &[
                (r#"s = f"{call_the_target()}""#, Code),
                (r#"s = rf"{call_the_target()}""#, Code),
                (r#"s = f"call_the_target {x}""#, Str),
                (r#"s = f"{{call_the_target}}""#, Str),
                (r#"s = r"{call_the_target}""#, Str),
            ],
        );
    }

    // ========================================================================
    // Ruby Tests
    // ========================================================================

    #[test]
    fn ruby_strings_comments_and_interpolation() {
        assert_regions(
            Language::Ruby,
            &[
                (r##"color = "#fff"; call_the_target"##, Code),
                (r##"s = "#{call_the_target}""##, Code),
                (r##"s = '#{call_the_target}'"##, Str),
                ("x = 1 # call_the_target", Comment),
            ],
        );
    }

    // ========================================================================
    // PHP Tests
    // ========================================================================

    #[test]
    fn php_strings_comments_attributes_and_interpolation() {
        assert_regions(
            Language::PHP,
            &[
                (r#"$u = "https://x"; call_the_target();"#, Code),
                (r##"$c = "#fff"; call_the_target();"##, Code),
                ("#[Route('/x')] function call_the_target() {}", Code),
                ("# call_the_target", Comment),
                ("// call_the_target", Comment),
                (r#"$s = "{$o->call_the_target()}";"#, Code),
                (r#"$s = "$call_the_target";"#, Code),
                (r#"$s = "$o->call_the_target";"#, Code),
                (r#"$s = '$call_the_target';"#, Str),
            ],
        );
    }

    // ========================================================================
    // C# Tests
    // ========================================================================

    #[test]
    fn test_csharp_verbatim_string() {
        let filter = filter(Language::CSharp);
        let line = r#"string s = @"extract_symbols";"#;
        assert!(filter.is_in_string(line, 13));
    }

    #[test]
    fn test_csharp_verbatim_escaped_quote() {
        let filter = filter(Language::CSharp);
        let line = r#"string s = @"before "" extract_symbols after";"#;
        assert!(filter.is_in_string(line, 19));
    }

    #[test]
    fn csharp_verbatim_and_interpolated_strings() {
        assert_regions(
            Language::CSharp,
            &[
                (r#"var p = @"C:\dir\"; call_the_target();"#, Code),
                (r#"var u = "https://x"; call_the_target();"#, Code),
                (r#"var s = $"{call_the_target()}";"#, Code),
                (r#"var s = $@"{call_the_target()}";"#, Code),
                (r#"var s = $"{{call_the_target}}";"#, Str),
                (r#"char c = '"'; call_the_target();"#, Code),
            ],
        );
    }

    // ========================================================================
    // Kotlin Tests
    // ========================================================================

    #[test]
    fn kotlin_string_templates() {
        assert_regions(
            Language::Kotlin,
            &[
                (r#"val s = "Hello $call_the_target""#, Code),
                (r#"val s = "${call_the_target()}""#, Code),
                (r#"val s = "call_the_target""#, Str),
                (r#"val s = """a "// b""" + call_the_target()"#, Code),
                (r#"val u = "https://x"; call_the_target()"#, Code),
            ],
        );
    }

    // ========================================================================
    // Zig Tests
    // ========================================================================

    #[test]
    fn zig_strings_and_multiline_literals() {
        assert_regions(
            Language::Zig,
            &[
                (r#"const u = "https://x"; call_the_target();"#, Code),
                (r"    \\ call_the_target", Str),
                ("// call_the_target", Comment),
            ],
        );
    }

    #[test]
    fn non_ascii_text_before_the_pattern() {
        assert_regions(
            Language::Rust,
            &[
                (r#"let s = "héllo //"; call_the_target();"#, Code),
                ("let c = 'é'; call_the_target();", Code),
                ("// héllo call_the_target", Comment),
            ],
        );
    }

    #[test]
    fn text_tiers_have_no_filter() {
        for lang in [
            Language::Text,
            Language::Lock,
            Language::Generated,
            Language::Swift,
            Language::Unknown,
        ] {
            assert!(get_filter(lang).is_none(), "{lang:?}");
        }
    }

    /// Line `n` (1-based) of `text`, for `line_is_non_code`'s check.
    fn nth(text: &str, n: usize) -> &str {
        text.lines().nth(n - 1).unwrap()
    }

    fn non_code(lang: Language, text: &str, line: usize) -> Option<bool> {
        let regions = FileRegions::new(lang, text.to_string())?;
        regions.line_is_non_code(line, nth(text, line), "target", true)
    }

    #[test]
    fn file_regions_know_comments_and_strings_across_lines() {
        let rust = "/*! Docs:\n * the target here\n */\nfn f() {\n    let s = \"one\n    target two\";\n    let r = r#\"\n target\n\"#;\n    target(s, '\\'', 'x');\n}\n";
        assert_eq!(
            non_code(Language::Rust, rust, 2),
            Some(true),
            "block comment"
        );
        assert_eq!(
            non_code(Language::Rust, rust, 6),
            Some(true),
            "multi-line string"
        );
        assert_eq!(non_code(Language::Rust, rust, 8), Some(true), "raw string");
        assert_eq!(non_code(Language::Rust, rust, 10), Some(false), "code");

        let py = "x = \"\"\"\ntarget\n\"\"\"\ntarget()  # target\n";
        assert_eq!(non_code(Language::Python, py, 2), Some(true));
        assert_eq!(non_code(Language::Python, py, 4), Some(false));

        let js = "const a = `\n${target()} target\n`;\nconst b = `\ntarget\n`;\n";
        assert_eq!(
            non_code(Language::JavaScript, js, 2),
            Some(false),
            "interpolation is code"
        );
        assert_eq!(non_code(Language::JavaScript, js, 5), Some(true));
    }

    #[test]
    fn file_regions_refuse_a_scan_that_does_not_end_in_code() {
        // Unclosed block comment and string: the rest of the file would be hidden.
        assert!(FileRegions::new(Language::Rust, "fn f() {}\n/* target\n".into()).is_none());
        assert!(FileRegions::new(Language::Rust, "let s = \"target\n".into()).is_none());
        // A newline inside a Python '…' string means the scan went wrong.
        assert!(FileRegions::new(Language::Python, "s = 'a\ntarget = 1\n'\n".into()).is_none());
        // No rules for the text tier.
        assert!(FileRegions::new(Language::Text, "target\n".into()).is_none());
    }

    #[test]
    fn file_regions_check_the_line_text() {
        let regions = FileRegions::new(Language::Rust, "fn target() {}\n".into()).unwrap();
        assert_eq!(
            regions.line_is_non_code(1, "fn target() {}", "target", true),
            Some(false)
        );
        assert_eq!(
            regions.line_is_non_code(1, "something else", "target", true),
            None
        );
        assert_eq!(
            regions.line_is_non_code(1, "fn target(…", "target", true),
            Some(false)
        );
        assert_eq!(
            regions.line_is_non_code(9, "fn target() {}", "target", true),
            None
        );
        assert_eq!(
            regions.line_is_non_code(1, "fn target() {}", "absent", true),
            Some(false)
        );

        // Whole identifiers: the code hit `target_span` does not keep a comment-only line.
        let text = "let target_span = 1; // target\n";
        let regions = FileRegions::new(Language::Rust, text.into()).unwrap();
        let line = text.trim_end();
        assert_eq!(
            regions.line_is_non_code(1, line, "target", true),
            Some(true)
        );
        assert_eq!(
            regions.line_is_non_code(1, line, "target", false),
            Some(false)
        );
    }
}