Debian Codegraph @

gopls/internal/fuzzy/matcher.go

raw symbols SCIP
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package fuzzy implements a fuzzy matching algorithm.
6 package fuzzy
7
8 import (
9 "bytes"
10 "fmt"
11 )
12
13 const (
14 // MaxInputSize is the maximum size of the input scored against the fuzzy matcher. Longer inputs
15 // will be truncated to this size.
16 MaxInputSize = 127
17 // MaxPatternSize is the maximum size of the pattern used to construct the fuzzy matcher. Longer
18 // inputs are truncated to this size.
19 MaxPatternSize = 63
20 )
21
22 type scoreVal int
23
24 func (s scoreVal) val() int {
25 return int(s) >> 1
26 }
27
28 func (s scoreVal) prevK() int {
29 return int(s) & 1
30 }
31
32 func score(val int, prevK int /*0 or 1*/) scoreVal {
33 return scoreVal(val<<1 + prevK)
34 }
35
36 // Matcher implements a fuzzy matching algorithm for scoring candidates against a pattern.
37 // The matcher does not support parallel usage.
38 type Matcher struct {
39 pattern string
40 patternLower []byte // lower-case version of the pattern
41 patternShort []byte // first characters of the pattern
42 caseSensitive bool // set if the pattern is mix-cased
43
44 patternRoles []RuneRole // the role of each character in the pattern
45 roles []RuneRole // the role of each character in the tested string
46
47 scores [MaxInputSize + 1][MaxPatternSize + 1][2]scoreVal
48
49 scoreScale float32
50
51 lastCandidateLen int // in bytes
52 lastCandidateMatched bool
53
54 // Reusable buffers to avoid allocating for every candidate.
55 // - inputBuf stores the concatenated input chunks
56 // - lowerBuf stores the last candidate in lower-case
57 // - rolesBuf stores the calculated roles for each rune in the last
58 // candidate.
59 inputBuf [MaxInputSize]byte
60 lowerBuf [MaxInputSize]byte
61 rolesBuf [MaxInputSize]RuneRole
62 }
63
64 func (m *Matcher) String() string { return m.pattern }
65
66 func (m *Matcher) bestK(i, j int) int {
67 if m.scores[i][j][0].val() < m.scores[i][j][1].val() {
68 return 1
69 }
70 return 0
71 }
72
73 // NewMatcher returns a new fuzzy matcher for scoring candidates against the provided pattern.
74 func NewMatcher(pattern string) *Matcher {
75 if len(pattern) > MaxPatternSize {
76 pattern = pattern[:MaxPatternSize]
77 }
78
79 m := &Matcher{
80 pattern: pattern,
81 patternLower: toLower([]byte(pattern), nil),
82 }
83
84 for i, c := range m.patternLower {
85 if pattern[i] != c {
86 m.caseSensitive = true
87 break
88 }
89 }
90
91 if len(pattern) > 3 {
92 m.patternShort = m.patternLower[:3]
93 } else {
94 m.patternShort = m.patternLower
95 }
96
97 m.patternRoles = RuneRoles([]byte(pattern), nil)
98
99 if len(pattern) > 0 {
100 maxCharScore := 4
101 m.scoreScale = 1 / float32(maxCharScore*len(pattern))
102 }
103
104 return m
105 }
106
107 // Score returns the score returned by matching the candidate to the pattern.
108 // This is not designed for parallel use. Multiple candidates must be scored sequentially.
109 // Returns a score between 0 and 1 (0 - no match, 1 - perfect match).
110 func (m *Matcher) Score(candidate string) float32 {
111 return m.ScoreChunks([]string{candidate})
112 }
113
114 func (m *Matcher) ScoreChunks(chunks []string) float32 {
115 candidate := fromChunks(chunks, m.inputBuf[:])
116 if len(candidate) > MaxInputSize {
117 candidate = candidate[:MaxInputSize]
118 }
119 lower := toLower(candidate, m.lowerBuf[:])
120 m.lastCandidateLen = len(candidate)
121
122 if len(m.pattern) == 0 {
123 // Empty patterns perfectly match candidates.
124 return 1
125 }
126
127 if m.match(candidate, lower) {
128 sc := m.computeScore(candidate, lower)
129 if sc > minScore/2 && !m.poorMatch() {
130 m.lastCandidateMatched = true
131 if len(m.pattern) == len(candidate) {
132 // Perfect match.
133 return 1
134 }
135
136 if sc < 0 {
137 sc = 0
138 }
139 normalizedScore := min(float32(sc)*m.scoreScale, 1)
140
141 return normalizedScore
142 }
143 }
144
145 m.lastCandidateMatched = false
146 return 0
147 }
148
149 const minScore = -10000
150
151 // MatchedRanges returns matches ranges for the last scored string as a flattened array of
152 // [begin, end) byte offset pairs.
153 func (m *Matcher) MatchedRanges() []int {
154 if len(m.pattern) == 0 || !m.lastCandidateMatched {
155 return nil
156 }
157 i, j := m.lastCandidateLen, len(m.pattern)
158 if m.scores[i][j][0].val() < minScore/2 && m.scores[i][j][1].val() < minScore/2 {
159 return nil
160 }
161
162 var ret []int
163 k := m.bestK(i, j)
164 for i > 0 {
165 take := (k == 1)
166 k = m.scores[i][j][k].prevK()
167 if take {
168 if len(ret) == 0 || ret[len(ret)-1] != i {
169 ret = append(ret, i)
170 ret = append(ret, i-1)
171 } else {
172 ret[len(ret)-1] = i - 1
173 }
174 j--
175 }
176 i--
177 }
178 // Reverse slice.
179 for i := range len(ret) / 2 {
180 ret[i], ret[len(ret)-1-i] = ret[len(ret)-1-i], ret[i]
181 }
182 return ret
183 }
184
185 func (m *Matcher) match(candidate []byte, candidateLower []byte) bool {
186 i, j := 0, 0
187 for ; i < len(candidateLower) && j < len(m.patternLower); i++ {
188 if candidateLower[i] == m.patternLower[j] {
189 j++
190 }
191 }
192 if j != len(m.patternLower) {
193 return false
194 }
195
196 // The input passes the simple test against pattern, so it is time to classify its characters.
197 // Character roles are used below to find the last segment.
198 m.roles = RuneRoles(candidate, m.rolesBuf[:])
199
200 return true
201 }
202
203 func (m *Matcher) computeScore(candidate []byte, candidateLower []byte) int {
204 pattLen, candLen := len(m.pattern), len(candidate)
205
206 for j := 0; j <= len(m.pattern); j++ {
207 m.scores[0][j][0] = minScore << 1
208 m.scores[0][j][1] = minScore << 1
209 }
210 m.scores[0][0][0] = score(0, 0) // Start with 0.
211
212 segmentsLeft, lastSegStart := 1, 0
213 for i := range candLen {
214 if m.roles[i] == RSep {
215 segmentsLeft++
216 lastSegStart = i + 1
217 }
218 }
219
220 // A per-character bonus for a consecutive match.
221 consecutiveBonus := 2
222 wordIdx := 0 // Word count within segment.
223 for i := 1; i <= candLen; i++ {
224
225 role := m.roles[i-1]
226 isHead := role == RHead
227
228 if isHead {
229 wordIdx++
230 } else if role == RSep && segmentsLeft > 1 {
231 wordIdx = 0
232 segmentsLeft--
233 }
234
235 var skipPenalty int
236 if i == 1 || (i-1) == lastSegStart {
237 // Skipping the start of first or last segment.
238 skipPenalty++
239 }
240
241 for j := 0; j <= pattLen; j++ {
242 // By default, we don't have a match. Fill in the skip data.
243 m.scores[i][j][1] = minScore << 1
244
245 // Compute the skip score.
246 k := 0
247 if m.scores[i-1][j][0].val() < m.scores[i-1][j][1].val() {
248 k = 1
249 }
250
251 skipScore := m.scores[i-1][j][k].val()
252 // Do not penalize missing characters after the last matched segment.
253 if j != pattLen {
254 skipScore -= skipPenalty
255 }
256 m.scores[i][j][0] = score(skipScore, k)
257
258 if j == 0 || candidateLower[i-1] != m.patternLower[j-1] {
259 // Not a match.
260 continue
261 }
262 pRole := m.patternRoles[j-1]
263
264 if role == RTail && pRole == RHead {
265 if j > 1 {
266 // Not a match: a head in the pattern matches a tail character in the candidate.
267 continue
268 }
269 // Special treatment for the first character of the pattern. We allow
270 // matches in the middle of a word if they are long enough, at least
271 // min(3, pattern.length) characters.
272 if !bytes.HasPrefix(candidateLower[i-1:], m.patternShort) {
273 continue
274 }
275 }
276
277 // Compute the char score.
278 var charScore int
279 // Bonus: the char is in the candidate's last segment.
280 if segmentsLeft <= 1 {
281 charScore++
282 }
283
284 // Bonus: exact case match between pattern and candidate.
285 if candidate[i-1] == m.pattern[j-1] ||
286 // Bonus: candidate char is a head and pattern is all
287 // lowercase. There is no segmentation in an all lowercase
288 // pattern, so assume any char in pattern can be a head. Note
289 // that we are intentionally _not_ giving a bonus to a case
290 // insensitive match when the pattern is case sensitive.
291 role == RHead && !m.caseSensitive {
292 charScore++
293 }
294
295 // Penalty: pattern char is Head, candidate char is Tail.
296 if role == RTail && pRole == RHead {
297 charScore--
298 }
299 // Penalty: first pattern character matched in the middle of a word.
300 if j == 1 && role == RTail {
301 charScore -= 4
302 }
303
304 // Third dimension encodes whether there is a gap between the previous match and the current
305 // one.
306 for k := range 2 {
307 sc := m.scores[i-1][j-1][k].val() + charScore
308
309 isConsecutive := k == 1 || i-1 == 0 || i-1 == lastSegStart
310 if isConsecutive {
311 // Bonus: a consecutive match. First character match also gets a bonus to
312 // ensure prefix final match score normalizes to 1.0.
313 // Logically, this is a part of charScore, but we have to compute it here because it
314 // only applies for consecutive matches (k == 1).
315 sc += consecutiveBonus
316 }
317 if k == 0 {
318 // Penalty: Matching inside a segment (and previous char wasn't matched). Penalize for the lack
319 // of alignment.
320 if role == RTail || role == RUCTail {
321 sc -= 3
322 }
323 }
324
325 if sc > m.scores[i][j][1].val() {
326 m.scores[i][j][1] = score(sc, k)
327 }
328 }
329 }
330 }
331
332 result := m.scores[len(candidate)][len(m.pattern)][m.bestK(len(candidate), len(m.pattern))].val()
333
334 return result
335 }
336
337 // ScoreTable returns the score table computed for the provided candidate. Used only for debugging.
338 func (m *Matcher) ScoreTable(candidate string) string {
339 var buf bytes.Buffer
340
341 var line1, line2, separator bytes.Buffer
342 line1.WriteString("\t")
343 line2.WriteString("\t")
344 for j := range len(m.pattern) {
345 line1.WriteString(fmt.Sprintf("%c\t\t", m.pattern[j]))
346 separator.WriteString("----------------")
347 }
348
349 buf.WriteString(line1.String())
350 buf.WriteString("\n")
351 buf.WriteString(separator.String())
352 buf.WriteString("\n")
353
354 for i := 1; i <= len(candidate); i++ {
355 line1.Reset()
356 line2.Reset()
357
358 line1.WriteString(fmt.Sprintf("%c\t", candidate[i-1]))
359 line2.WriteString("\t")
360
361 for j := 1; j <= len(m.pattern); j++ {
362 line1.WriteString(fmt.Sprintf("M%6d(%c)\t", m.scores[i][j][0].val(), dir(m.scores[i][j][0].prevK())))
363 line2.WriteString(fmt.Sprintf("H%6d(%c)\t", m.scores[i][j][1].val(), dir(m.scores[i][j][1].prevK())))
364 }
365 buf.WriteString(line1.String())
366 buf.WriteString("\n")
367 buf.WriteString(line2.String())
368 buf.WriteString("\n")
369 buf.WriteString(separator.String())
370 buf.WriteString("\n")
371 }
372
373 return buf.String()
374 }
375
376 func dir(prevK int) rune {
377 if prevK == 0 {
378 return 'M'
379 }
380 return 'H'
381 }
382
383 func (m *Matcher) poorMatch() bool {
384 if len(m.pattern) < 2 {
385 return false
386 }
387
388 i, j := m.lastCandidateLen, len(m.pattern)
389 k := m.bestK(i, j)
390
391 var counter, len int
392 for i > 0 {
393 take := (k == 1)
394 k = m.scores[i][j][k].prevK()
395 if take {
396 len++
397 if k == 0 && len < 3 && m.roles[i-1] == RTail {
398 // Short match in the middle of a word
399 counter++
400 if counter > 1 {
401 return true
402 }
403 }
404 j--
405 } else {
406 len = 0
407 }
408 i--
409 }
410 return false
411 }
412
413 // BestMatch returns the name most similar to the
414 // pattern, using fuzzy matching, or the empty string.
415 func BestMatch(pattern string, names []string) string {
416 fuzz := NewMatcher(pattern)
417 best := ""
418 highScore := float32(0) // minimum score is 0 (no match)
419 for _, name := range names {
420 // TODO: Improve scoring algorithm.
421 score := fuzz.Score(name)
422 if score > highScore {
423 highScore = score
424 best = name
425 } else if score == 0 {
426 // Order matters in the fuzzy matching algorithm. If we find no match
427 // when matching the target to the identifier, try matching the identifier
428 // to the target.
429 revFuzz := NewMatcher(name)
430 revScore := revFuzz.Score(pattern)
431 if revScore > highScore {
432 highScore = revScore
433 best = name
434 }
435 }
436 }
437 return best
438 }