Debian Codegraph @

src/algo/runeprefilter_test.go

raw
1 package algo
2
3 // Correctness tests for the rune-array prefilter (Step C).
4 //
5 // The prefilter may narrow the search scope but must never change a Result or
6 // its positions, and must never reject an item the general path would match.
7 // Each result is compared against the same code with the prefilter disabled.
8
9 import (
10 "math/rand"
11 "strings"
12 "testing"
13 "unicode"
14 "unicode/utf8"
15
16 "github.com/junegunn/fzf/src/util"
17 )
18
19 // foldForTest mirrors what Phase 2 does to a non-ASCII text rune: lowercase if
20 // uppercase, then normalize.
21 func foldForTest(r rune, normalize bool) rune {
22 if charClassOfNonAscii(r) == charUpper {
23 r = unicode.To(unicode.LowerCase, r)
24 }
25 if normalize {
26 r = normalizeRune(r)
27 }
28 return r
29 }
30
31 // The prefilter is only safe on items whose runes cannot become ASCII. This
32 // verifies util.MayFoldToAscii as a superset of the runes that actually can,
33 // over the whole Unicode range and both normalization modes. If normalize.go
34 // or the Go unicode tables change, this fails.
35 func TestMayFoldToAsciiIsSuperset(t *testing.T) {
36 missed := 0
37 for r := rune(utf8.RuneSelf); r <= unicode.MaxRune; r++ {
38 if r >= 0xD800 && r <= 0xDFFF {
39 continue
40 }
41 for _, normalize := range []bool{true, false} {
42 if foldForTest(r, normalize) < utf8.RuneSelf && !util.MayFoldToAscii(r) {
43 if missed++; missed < 10 {
44 t.Errorf("U+%04X folds to ASCII (normalize=%v) but MayFoldToAscii is false", r, normalize)
45 }
46 }
47 }
48 }
49 if missed > 0 {
50 t.Fatalf("%d runes fold to ASCII without being flagged", missed)
51 }
52 }
53
54 // Scripts that must stay unflagged, otherwise the prefilter never runs for
55 // them and Step C has no effect.
56 func TestMayFoldToAsciiExcludesMajorScripts(t *testing.T) {
57 for _, s := range []struct {
58 name string
59 lo, hi rune
60 }{
61 {"Cyrillic", 0x0400, 0x04FF}, {"Greek", 0x0370, 0x03FF}, {"Hebrew", 0x0590, 0x05FF},
62 {"Arabic", 0x0600, 0x06FF}, {"Thai", 0x0E00, 0x0E7F}, {"Devanagari", 0x0900, 0x097F},
63 {"CJK", 0x4E00, 0x9FFF}, {"Hangul", 0xAC00, 0xD7A3}, {"kana", 0x3040, 0x30FF},
64 {"box drawing", 0x2500, 0x257F}, {"emoji", 0x1F300, 0x1FAFF},
65 // These sit between the Latin blocks and were included in an earlier,
66 // wider grouping of foldableRanges. General Punctuation matters most:
67 // curly quotes, en and em dashes and the ellipsis are in it.
68 {"Greek Extended", 0x1F00, 0x1FFF}, {"General Punctuation", 0x2000, 0x206F},
69 {"Currency Symbols", 0x20A0, 0x20CF}, {"CJK Symbols", 0x3000, 0x303F},
70 } {
71 for r := s.lo; r <= s.hi; r++ {
72 if util.MayFoldToAscii(r) {
73 t.Errorf("%s U+%04X should not be flagged foldable", s.name, r)
74 break
75 }
76 }
77 }
78 }
79
80 // The byte-view scan must agree with the shipped reference scanners. The interesting inputs
81 // are runes whose low byte collides with the needle (U+0165 has low byte 'e')
82 // and runes sharing a lane offset, which the alignment and zero checks reject.
83 func TestIndexAsciiRuneMatchesReference(t *testing.T) {
84 rng := rand.New(rand.NewSource(3))
85 alphabet := []rune{'a', 'A', 'e', 'E', '/', '1', 0x0165, 0x00E9, 0x4E00, 0xD55C,
86 0x1F389, 0x0065 + 0x100, 0x0041 + 0x100, 0x2F65}
87 for trial := range 20000 {
88 n := rng.Intn(24)
89 runes := make([]rune, n)
90 for i := range runes {
91 runes[i] = alphabet[rng.Intn(len(alphabet))]
92 }
93 b := []byte{'a', 'e', 'A', 'E', '/', '1'}[rng.Intn(6)]
94 cs := rng.Intn(2) == 0
95 from := 0
96 if n > 0 {
97 from = rng.Intn(n)
98 }
99 if got, exp := indexAsciiRune(runes, cs, b, from), indexAsciiRuneRef(runes, cs, b, from); got != exp {
100 t.Fatalf("trial %d: indexAsciiRune(%U, cs=%v, %q, %d) = %d, expected %d", trial, runes, cs, b, from, got, exp)
101 }
102 if got, exp := lastIndexAsciiRune(runes, cs, b, from), lastIndexAsciiRuneRef(runes, cs, b, from); got != exp {
103 t.Fatalf("trial %d: lastIndexAsciiRune(%U, cs=%v, %q, %d) = %d, expected %d", trial, runes, cs, b, from, got, exp)
104 }
105 }
106 }
107
108 // Differential test: the prefilter must not change any Result or position.
109 // Corpora deliberately mix scripts that clear the foldable bit (CJK, Hangul,
110 // Cyrillic, emoji) with scripts that set it (accented Latin, fullwidth), so
111 // both the engaged and the bypassed path are exercised.
112 func TestRunePrefilterEquivalence(t *testing.T) {
113 t.Cleanup(func() { disableRunePrefilter = false })
114 rng := rand.New(rand.NewSource(4))
115 parts := []string{
116 "src", "util", "conf", "a", "e", "E", "A", "/", "_", "1", " ",
117 "漢字", "한글", "мир", "ελλ", "🎉", "café", "Müller", "naïve", "full",
118 "Å", "İ", "K", "ǰ", "ff",
119 }
120 patterns := []string{"a", "e", "conf", "src/util", "ae", "A", "E", "K", "k", "i", "//", "zz", "s l",
121 // non-ASCII patterns, the Step G path
122 "漢", "漢字", "한", "한글", "мир", "м", "ελλ", "🎉", "é", "ß", "Å", "İ", "f",
123 "漢a", "a漢", "한글/src", "🎉e"}
124
125 slab := util.MakeSlab(100*1024, 2048)
126 engaged, bypassed := 0, 0
127
128 for trial := range 30000 {
129 var sb strings.Builder
130 for range 1 + rng.Intn(8) {
131 sb.WriteString(parts[rng.Intn(len(parts))])
132 }
133 chars := util.ToChars([]byte(sb.String()))
134 if chars.IsBytes() {
135 continue
136 }
137 if chars.MayFoldToAscii() {
138 bypassed++
139 } else {
140 engaged++
141 }
142 pat := patterns[rng.Intn(len(patterns))]
143 cs := rng.Intn(2) == 0
144 if !cs {
145 pat = strings.ToLower(pat)
146 }
147 pattern := []rune(pat)
148 norm := rng.Intn(2) == 0
149 fwd := rng.Intn(2) == 0
150 wp := rng.Intn(2) == 0
151
152 disableRunePrefilter = true
153 expR, expP := FuzzyMatchV2(cs, norm, fwd, &chars, pattern, wp, slab)
154 disableRunePrefilter = false
155 gotR, gotP := FuzzyMatchV2(cs, norm, fwd, &chars, pattern, wp, slab)
156
157 if gotR != expR || !samePos(gotP, expP) {
158 t.Fatalf("trial %d: %q pattern=%q cs=%v norm=%v fwd=%v wp=%v\n prefilter on: %v %v\n prefilter off: %v %v",
159 trial, sb.String(), pat, cs, norm, fwd, wp, gotR, gotP, expR, expP)
160 }
161 }
162 disableRunePrefilter = false
163 t.Logf("prefilter engaged on %d items, bypassed on %d", engaged, bypassed)
164 if engaged == 0 || bypassed == 0 {
165 t.Fatalf("corpus did not exercise both paths (engaged=%d bypassed=%d)", engaged, bypassed)
166 }
167
168 // Equivalence alone would still hold if the prefilter never filtered
169 // anything, so confirm it both rejects and narrows.
170 rejected, narrowed := 0, 0
171 for range 5000 {
172 var sb strings.Builder
173 for range 1 + rng.Intn(8) {
174 sb.WriteString(parts[rng.Intn(len(parts))])
175 }
176 chars := util.ToChars([]byte(sb.String()))
177 if chars.IsBytes() || chars.MayFoldToAscii() {
178 continue
179 }
180 pattern := []rune(patterns[rng.Intn(len(patterns))])
181 lo, hi := asciiFuzzyIndex(&chars, pattern, false)
182 switch {
183 case lo < 0:
184 rejected++
185 case hi-lo < chars.Length():
186 narrowed++
187 }
188 }
189 t.Logf("prefilter rejected %d items, narrowed scope on %d", rejected, narrowed)
190 if rejected == 0 {
191 t.Fatal("prefilter never rejected an item, so equivalence proves nothing")
192 }
193 if narrowed == 0 {
194 t.Fatal("prefilter never narrowed the scope")
195 }
196 }
197
198 // FuzzyMatchV1 shares asciiFuzzyIndex, so it needs the same guarantee.
199 func TestRunePrefilterEquivalenceV1(t *testing.T) {
200 t.Cleanup(func() { disableRunePrefilter = false })
201 rng := rand.New(rand.NewSource(5))
202 parts := []string{"src", "conf", "a", "e", "/", "漢字", "한글", "мир", "café", "Å", "🎉"}
203 slab := util.MakeSlab(100*1024, 2048)
204 for trial := range 20000 {
205 var sb strings.Builder
206 for range 1 + rng.Intn(6) {
207 sb.WriteString(parts[rng.Intn(len(parts))])
208 }
209 chars := util.ToChars([]byte(sb.String()))
210 if chars.IsBytes() {
211 continue
212 }
213 pattern := []rune([]string{"a", "e", "conf", "src", "ae", "zz"}[rng.Intn(6)])
214 cs, norm, fwd, wp := rng.Intn(2) == 0, rng.Intn(2) == 0, rng.Intn(2) == 0, rng.Intn(2) == 0
215
216 disableRunePrefilter = true
217 expR, expP := FuzzyMatchV1(cs, norm, fwd, &chars, pattern, wp, slab)
218 disableRunePrefilter = false
219 gotR, gotP := FuzzyMatchV1(cs, norm, fwd, &chars, pattern, wp, slab)
220
221 if gotR != expR || !samePos(gotP, expP) {
222 t.Fatalf("trial %d: %q pattern=%q\n prefilter on: %v %v\n prefilter off: %v %v",
223 trial, sb.String(), string(pattern), gotR, gotP, expR, expP)
224 }
225 }
226 disableRunePrefilter = false
227 }
228
229 // normalizeRune skips the map when util.MayFoldToAscii rejects the rune. That
230 // is only sound if every key of the map is flagged, since a flagged-false rune
231 // is returned unchanged.
232 func TestNormalizedKeysAreFlagged(t *testing.T) {
233 for k := range normalized {
234 if !util.MayFoldToAscii(k) {
235 t.Errorf("normalized key U+%04X (%c) is not flagged by MayFoldToAscii", k, k)
236 }
237 }
238 }
239
240 // Guarding normalizeRune must not change what it returns, for any rune.
241 func TestNormalizeRuneUnchangedByGuard(t *testing.T) {
242 for r := rune(0); r <= unicode.MaxRune; r++ {
243 if r >= 0xD800 && r <= 0xDFFF {
244 continue
245 }
246 exp := r
247 if r >= 0x00C0 && r <= 0xFF61 {
248 if n := normalized[r]; n > 0 {
249 exp = n
250 }
251 }
252 if got := normalizeRune(r); got != exp {
253 t.Fatalf("normalizeRune(U+%04X) = U+%04X, expected U+%04X", r, got, exp)
254 }
255 }
256 }
257
258 // Step G lets non-ASCII pattern runes use the scan, but only when no other
259 // rune can transform into them. Being uncased is not sufficient: U+00DF has no
260 // simple uppercase yet U+1E9E lowercases onto it. This checks the guard against
261 // the full preimage relation over all of Unicode.
262 func TestRunePrefilterableGuardIsSound(t *testing.T) {
263 preimage := map[rune][]rune{}
264 for r := rune(0); r <= unicode.MaxRune; r++ {
265 if r >= 0xD800 && r <= 0xDFFF {
266 continue
267 }
268 if charClassOfNonAscii(r) == charUpper {
269 if l := unicode.To(unicode.LowerCase, r); l != r {
270 preimage[l] = append(preimage[l], r)
271 }
272 }
273 }
274
275 clean := util.ToChars([]byte("漢字")) // rune mode, fold bit clear
276 admitted, violations := 0, 0
277 for r := rune(utf8.RuneSelf); r <= unicode.MaxRune; r++ {
278 if r >= 0xD800 && r <= 0xDFFF {
279 continue
280 }
281 if !runePrefilterable(&clean, []rune{r}, false) {
282 continue
283 }
284 admitted++
285 if extra := preimage[r]; len(extra) > 0 {
286 violations++
287 if violations <= 5 {
288 t.Errorf("guard admits U+%04X but %U lowercases onto it", r, extra)
289 }
290 }
291 }
292 t.Logf("guard admits %d non-ASCII pattern runes, unsound for %d", admitted, violations)
293
294 // The scripts this step exists for must be fully admitted.
295 for _, s := range []struct {
296 name string
297 lo, hi rune
298 }{{"CJK", 0x4E00, 0x9FFF}, {"Hangul", 0xAC00, 0xD7A3}, {"kana", 0x3040, 0x30FF},
299 {"Thai", 0x0E00, 0x0E7F}, {"emoji", 0x1F300, 0x1FAFF}} {
300 for r := s.lo; r <= s.hi; r++ {
301 if !runePrefilterable(&clean, []rune{r}, false) {
302 t.Errorf("%s U+%04X should be admitted", s.name, r)
303 break
304 }
305 }
306 }
307 }
308
309 // The Step G path must actually run and reject, otherwise the equivalence
310 // test above proves nothing about non-ASCII patterns.
311 func TestNonAsciiPatternPrefilterEngages(t *testing.T) {
312 rng := rand.New(rand.NewSource(6))
313 parts := []string{"漢字", "한글", "src", "conf", "/", "мир", "🎉"}
314 engaged, rejected, narrowed, bypassed := 0, 0, 0, 0
315 for range 5000 {
316 var sb strings.Builder
317 for range 1 + rng.Intn(6) {
318 sb.WriteString(parts[rng.Intn(len(parts))])
319 }
320 chars := util.ToChars([]byte(sb.String()))
321 if chars.IsBytes() {
322 continue
323 }
324 pattern := []rune([]string{"漢", "漢字", "한글", "мир", "🎉", "é", "ß"}[rng.Intn(7)])
325 if !runePrefilterable(&chars, pattern, false) {
326 bypassed++
327 continue
328 }
329 engaged++
330 lo, hi := asciiFuzzyIndex(&chars, pattern, false)
331 switch {
332 case lo < 0:
333 rejected++
334 case hi-lo < chars.Length():
335 narrowed++
336 }
337 }
338 t.Logf("non-ASCII patterns: engaged %d, bypassed %d, rejected %d, narrowed %d",
339 engaged, bypassed, rejected, narrowed)
340 if engaged == 0 || rejected == 0 {
341 t.Fatalf("non-ASCII pattern path not exercised (engaged=%d rejected=%d)", engaged, rejected)
342 }
343 if bypassed == 0 {
344 t.Fatal("cased and foldable patterns should still bypass")
345 }
346 }
347
348 // indexRune picks which byte lane to scan, and is checked against the shipped
349 // reference scanners rather than a copy of them. Zero-low-byte runes (U+AE00) and
350 // runes whose lanes collide with common ASCII bytes are the cases that break a
351 // naive low-byte scan, so the alphabet includes both.
352 func TestIndexRuneMatchesReference(t *testing.T) {
353
354 alphabet := []rune{
355 'a', 'e', 'N', '/', 0x00,
356 0xAE00, 0xAC00, 0xD55C, // Hangul, low byte zero for U+AE00
357 0x4E00, 0x6587, 0x9FFF, // CJK, U+4E00 has zero low byte
358 0x3040, 0x0E00, // kana, Thai with zero low byte
359 0x1F389, 0x1F300, // emoji, 3 significant bytes
360 0x0100, 0x0165, 0x00E9, // low byte zero / ASCII-colliding lanes
361 }
362 rng := rand.New(rand.NewSource(7))
363 for trial := range 30000 {
364 n := rng.Intn(20)
365 runes := make([]rune, n)
366 for i := range runes {
367 runes[i] = alphabet[rng.Intn(len(alphabet))]
368 }
369 r := alphabet[rng.Intn(len(alphabet))]
370 from := 0
371 if n > 0 {
372 from = rng.Intn(n)
373 }
374 if got, exp := indexRune(runes, r, from), indexRuneRef(runes, r, from); got != exp {
375 t.Fatalf("trial %d: indexRune(%U, U+%04X, %d) = %d, expected %d", trial, runes, r, from, got, exp)
376 }
377 if got, exp := lastIndexRune(runes, r, from), lastIndexRuneRef(runes, r, from); got != exp {
378 t.Fatalf("trial %d: lastIndexRune(%U, U+%04X, %d) = %d, expected %d", trial, runes, r, from, got, exp)
379 }
380 }
381 }
382
383 // preparePattern mirrors what pattern.go guarantees the algo functions:
384 // lowercased when case-insensitive, normalized when normalize is on.
385 func preparePattern(pat string, caseSensitive, normalize bool) []rune {
386 if !caseSensitive {
387 pat = strings.ToLower(pat)
388 }
389 r := []rune(pat)
390 if normalize {
391 r = NormalizeRunes(r)
392 }
393 return r
394 }
395
396 // FuzzRunePrefilter drives arbitrary rune-mode input and arbitrary patterns
397 // through the prefilter and through the same code with it disabled, and
398 // requires identical Results and positions. The existing fast-path fuzzers
399 // only generate byte-mode input, so they never reach this path.
400 func FuzzRunePrefilter(f *testing.F) {
401 for _, in := range []string{
402 "한글/src/util.go", "漢字/conf", "café/binutils", "мир/test", "🎉/a",
403 "ABC.txt", "Ångström", "ǰ/ß/İ", "a漢b한c", "Āā",
404 } {
405 for _, p := range []string{"a", "conf", "漢", "한글", "мир", "ß", "É", "a漢"} {
406 f.Add(in, p)
407 }
408 }
409 slab := util.MakeSlab(200*1024, 4096)
410 f.Fuzz(func(t *testing.T, input, pat string) {
411 if len(input) > 512 || len(pat) == 0 || len(pat) > 32 {
412 return
413 }
414 chars := util.ToChars([]byte(input))
415 if chars.IsBytes() {
416 return // byte mode is covered by the existing fuzzers
417 }
418 for _, cs := range []bool{false, true} {
419 for _, norm := range []bool{false, true} {
420 p := preparePattern(pat, cs, norm)
421 if len(p) == 0 {
422 continue
423 }
424 for _, fwd := range []bool{true, false} {
425 for _, wp := range []bool{false, true} {
426 for _, fn := range []Algo{FuzzyMatchV2, FuzzyMatchV1, ExactMatchNaive} {
427 disableRunePrefilter = true
428 expR, expP := fn(cs, norm, fwd, &chars, p, wp, slab)
429 disableRunePrefilter = false
430 gotR, gotP := fn(cs, norm, fwd, &chars, p, wp, slab)
431 if gotR != expR || !samePos(gotP, expP) {
432 t.Fatalf("input=%q pattern=%q cs=%v norm=%v fwd=%v wp=%v\n prefilter on: %v %v\n prefilter off: %v %v",
433 input, pat, cs, norm, fwd, wp, gotR, gotP, expR, expP)
434 }
435 }
436 }
437 }
438 }
439 }
440 })
441 }
442
443 // RunesToChars can produce rune-mode Chars holding zero runes, which sends a
444 // nil pointer through unsafe.SliceData in runeBytes. ToChars cannot produce
445 // this (an empty input is byte mode), so it needs its own test.
446 func TestEmptyRuneModeChars(t *testing.T) {
447 t.Cleanup(func() { disableRunePrefilter = false })
448 slab := util.MakeSlab(100*1024, 2048)
449 for _, runes := range [][]rune{{}, nil, {'a'}, {0x4E00}} {
450 chars := util.RunesToChars(runes)
451 if chars.IsBytes() {
452 continue
453 }
454 for _, pat := range []string{"a", "漢", "ab"} {
455 p := []rune(pat)
456 for _, fn := range []Algo{FuzzyMatchV2, FuzzyMatchV1, ExactMatchNaive,
457 PrefixMatch, SuffixMatch, EqualMatch} {
458 disableRunePrefilter = true
459 expR, expP := fn(false, true, true, &chars, p, true, slab)
460 disableRunePrefilter = false
461 gotR, gotP := fn(false, true, true, &chars, p, true, slab)
462 if gotR != expR || !samePos(gotP, expP) {
463 t.Errorf("runes=%U pat=%q: prefilter on %v %v, off %v %v", runes, pat, gotR, gotP, expR, expP)
464 }
465 }
466 }
467 }
468 }
469
470 // MayFoldToAscii subtracts before bounds-checking, so a rune below the range
471 // (including a negative one, which utf8 decoding never produces but callers
472 // could construct) must not wrap into a false positive.
473 func TestMayFoldToAsciiOutOfRange(t *testing.T) {
474 for _, r := range []rune{-1, -0x10000, 0, 'a', 0x7F, 0xBF, 0xFF62, unicode.MaxRune, unicode.MaxRune + 1} {
475 if util.MayFoldToAscii(r) {
476 t.Errorf("MayFoldToAscii(%d) = true, expected false", r)
477 }
478 }
479 }