aboutsummaryrefslogtreecommitdiff
path: root/src/common/fuzzy.odin
blob: 822f37f94588d7900b18072767ae72ede20fb692 (plain)
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
package common

import "core:strings"
import "core:fmt"

/*
	Ported from https://github.com/llvm/llvm-project/blob/master/clang-tools-extra/clangd/FuzzyMatch.cpp
*/

max_pattern :: 63
max_word    :: 256

awful_score: int = -(1 << 13)
perfect_bonus :: 4
miss          :: 0
match         :: 1

FuzzyCharTypeSet :: u8

//do bitfield instead
FuzzyScoreInfo :: struct {
	score: int,
	prev:  int,
}

FuzzyCharRole :: enum (u8) {
	Unknown   = 0, // Stray control characters or impossible states.
	Tail      = 1, // Part of a word segment, but not the first character.
	Head      = 2, // The first character of a word segment.
	Separator = 3, // Punctuation characters that separate word segments.
}

FuzzyCharType :: enum (u8) {
	Empty       = 0, // Before-the-start and after-the-end (and control chars).
	Lower       = 1, // Lowercase letters, digits, and non-ASCII bytes.
	Upper       = 2, // Uppercase letters.
	Punctuation = 3, // ASCII punctuation (including Space)
}

FuzzyMatcher :: struct {
	pattern:          string,
	word:             string,
	lower_pattern:    string,
	lower_word:       string,
	scores:           [max_pattern + 1][max_word + 1][2]FuzzyScoreInfo,
	pattern_count:    int,
	pattern_type_set: FuzzyCharTypeSet,
	word_type_set:    FuzzyCharTypeSet,
	pattern_role:     [max_pattern]FuzzyCharRole,
	word_count:       int,
	score_scale:      f32,
	word_role:        [max_word]FuzzyCharRole,
}

//odinfmt: disable
char_roles: []u8 = {
	// clang-format off
	//         Curr= Empty Lower Upper Separ
	/*Prev=Empty */0x00,0xaa,0xaa,0xff, // At start, Lower|Upper->Head
	/*Prev=Lower */0x00,0x55,0xaa,0xff, // In word, Upper->Head;Lower->Tail
	/*Prev=Upper */0x00,0x55,0x59,0xff, // Ditto, but U(U)U->Tail
	/*Prev=Separ */0x00,0xaa,0xaa,0xff, // After separator, like at start
	// clang-format on
}

char_types: []u8 = {
	0x00,0x00,0x00,0x00, // Control characters
	0x00,0x00,0x00,0x00, // Control characters
	0xff,0xff,0xff,0xff, // Punctuation
	0x55,0x55,0xf5,0xff, // Numbers->Lower, more Punctuation.
	0xab,0xaa,0xaa,0xaa, // @ and A-O
	0xaa,0xaa,0xea,0xff, // P-Z, more Punctuation.
	0x57,0x55,0x55,0x55, // ` and a-o
	0x55,0x55,0xd5,0x3f, // p-z, Punctuation, DEL.
	0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55, // Bytes over 127 -> Lower.
	0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55, // (probably UTF-8).
	0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55,
	0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55,
}
//odinfmt: enable


make_fuzzy_matcher :: proc(pattern: string, allocator := context.temp_allocator) -> ^FuzzyMatcher {
	matcher := new(FuzzyMatcher, allocator)

	matcher.pattern_count = min(len(pattern), max_pattern)
	matcher.score_scale   = matcher.pattern_count > 0 ? 1 / cast(f32)(perfect_bonus * matcher.pattern_count) : 0
	matcher.pattern       = pattern[0:matcher.pattern_count]
	matcher.lower_pattern = strings.to_lower(matcher.pattern, context.temp_allocator)

	score_info_miss: FuzzyScoreInfo
	score_info_miss.score = 0
	score_info_miss.prev  = miss

	matcher.scores[0][0][miss] = score_info_miss

	score_info_match: FuzzyScoreInfo
	score_info_match.score = awful_score
	score_info_match.prev  = match

	matcher.scores[0][0][match] = score_info_match

	for p := 0; p < matcher.pattern_count; p += 1 {

		for w := 0; w < p; w += 1 {

			for a := 0; a < 2; a += 1 {
				score_info: FuzzyScoreInfo
				score_info.score        = awful_score
				score_info.prev         = miss
				matcher.scores[p][w][a] = score_info
				ref := matcher.pattern_role[:matcher.pattern_count]
				matcher.pattern_type_set = fuzzy_calculate_roles(matcher.pattern, &ref)
			}
		}
	}

	return matcher
}

fuzzy_to_acronym :: proc(word: string) -> (string, bool) {
	builder := strings.builder_make(context.temp_allocator)

	if len(word) <= 1 {
		return "", false
	}

	i         := 1
	last_char := word[0]

	strings.write_byte(&builder, last_char)

	for i < len(word) {

		if last_char == '_' {
			strings.write_byte(&builder, word[i])
		}

		last_char = word[i]

		i += 1
	}

	str := strings.to_string(builder)

	if len(str) <= 1 {
		return "", false
	}

	return str, true
}
//changed from bool to int because of a linux bug - 10.05.2021
fuzzy_match :: proc(matcher: ^FuzzyMatcher, word: string) -> (f32, int) {
	
	if !fuzzy_init(matcher, word) {
		return 0, 0
	}

	if matcher.pattern_count <= 0 {
		return 1, 1
	}

	if acronym, ok := fuzzy_to_acronym(word); ok {
		if acronym == matcher.pattern {
			return 20, 1
		}
	}

	fuzzy_build_graph(matcher)

	best := max(cast(int)matcher.scores[matcher.pattern_count][matcher.word_count][miss].score,
	   cast(int)matcher.scores[matcher.pattern_count][matcher.word_count][match].score)

	if fuzzy_is_awful(best) {
		return 0.0, 0
	}

	score := matcher.score_scale * min(perfect_bonus * cast(f32)matcher.pattern_count, cast(f32)max(0, best))

	if matcher.word_count == matcher.pattern_count {
		score *= 2
	}

	return score, 1
}

fuzzy_is_awful :: proc(s: int) -> bool {
	return s < awful_score / 2
}

fuzzy_calculate_roles :: proc(text: string, roles: ^[]FuzzyCharRole) -> FuzzyCharTypeSet {
	if len(text) != len(roles) {
		return 0
	}

	if len(text) == 0 {
		return 0
	}

	type: FuzzyCharType = cast(FuzzyCharType)fuzzy_packed_lookup(char_types, cast(uint)text[0])

	type_set: FuzzyCharTypeSet = cast(u8)(1 << cast(uint)type)

	types := type

	for i := 0; i < len(text) - 1; i += 1 {
		type = cast(FuzzyCharType)fuzzy_packed_lookup(char_types, cast(uint)text[i + 1])
		type_set |= 1 << cast(uint)type

		fuzzy_rotate(type, &types)

		roles[i] = cast(FuzzyCharRole)fuzzy_packed_lookup(char_roles, cast(uint)types)
	}

	fuzzy_rotate(.Empty, &types)

	roles[len(text) - 1] = cast(FuzzyCharRole)fuzzy_packed_lookup(char_roles, cast(uint)types)

	return type_set
}

fuzzy_rotate :: proc(t: FuzzyCharType, types: ^FuzzyCharType) {
	types^ = cast(FuzzyCharType)(((cast(uint)types^ << 2) | cast(uint)t) & 0x3f)
}

fuzzy_packed_lookup :: proc(data: $A/[]$T, i: uint) -> T {
	return (data[i >> 2] >> ((i & 3) * 2)) & 3
}

fuzzy_init :: proc(matcher: ^FuzzyMatcher, word: string) -> bool {
	matcher.word       = word
	matcher.word_count = min(max_word, len(matcher.word))

	if matcher.pattern_count > matcher.word_count {
		return false
	}

	if matcher.pattern_count == 0 {
		return true
	}

	matcher.lower_word = strings.to_lower(word, context.temp_allocator)

	w, p := 0, 0

	for ; p != matcher.pattern_count; w += 1 {
		if w == matcher.word_count {
			return false
		}

		if matcher.lower_word[w] == matcher.lower_pattern[p] {
			p += 1
		}
	}

	ref := matcher.word_role[:matcher.word_count]

	matcher.word_type_set = fuzzy_calculate_roles(word, &ref)

	return true
}

fuzzy_skip_penalty :: proc(matcher: ^FuzzyMatcher, w: int) -> int {
	if w == 0 { // Skipping the first character.
		return 3
	}

	if matcher.word_role[w] == .Head { // Skipping a segment.
		return 1
	}

	return 0
}

fuzzy_build_graph :: proc(matcher: ^FuzzyMatcher) {
	for w := 0; w < matcher.word_count; w += 1 {

		s: FuzzyScoreInfo

		score   := cast(int)matcher.scores[0][w][miss].score
		penalty := fuzzy_skip_penalty(matcher, w)
		sum     := score - penalty

		s.score = sum
		s.prev  = miss

		matcher.scores[0][w + 1][miss] = s

		s.score = awful_score
		s.prev  = miss

		matcher.scores[0][w + 1][match] = s
	}

	for p := 0; p < matcher.pattern_count; p += 1 {
		for w := p; w < matcher.word_count; w += 1 {
			score    := &matcher.scores[p + 1][w + 1]
			pre_miss := &matcher.scores[p + 1][w]

			match_miss_score := pre_miss[match].score
			miss_miss_score  := pre_miss[miss].score

			if p < matcher.pattern_count - 1 {
				match_miss_score -= fuzzy_skip_penalty(matcher, w)
				miss_miss_score  -= fuzzy_skip_penalty(matcher, w)
			}

			if match_miss_score > miss_miss_score {
				s: FuzzyScoreInfo
				s.score     = match_miss_score
				s.prev      = match
				score[miss] = s
			} else {
				s: FuzzyScoreInfo
				s.score     = miss_miss_score
				s.prev      = miss
				score[miss] = s
			}

			pre_match := &matcher.scores[p][w]

			match_match_score := fuzzy_allow_match(matcher, p, w, match) ? cast(int)pre_match[match].score + fuzzy_match_bonus(matcher, p, w, match) : awful_score

			miss_match_score := fuzzy_allow_match(matcher, p, w, miss) ? cast(int)pre_match[miss].score + fuzzy_match_bonus(matcher, p, w, miss) : awful_score

			if match_match_score > miss_match_score {
				s: FuzzyScoreInfo
				s.score      = match_match_score
				s.prev       = match
				score[match] = s
			} else {
				s: FuzzyScoreInfo
				s.score      = miss_match_score
				s.prev       = miss
				score[match] = s
			}
		}
	}
}

fuzzy_match_bonus :: proc(matcher: ^FuzzyMatcher, p: int, w: int, last: int) -> int {
	assert(matcher.lower_pattern[p] == matcher.lower_word[w])

	s := 1

	is_pattern_single_case := (cast(uint)matcher.pattern_type_set == 1 << cast(uint)FuzzyCharType.Lower)
	is_pattern_single_case |= (cast(uint)matcher.pattern_type_set == 1 << cast(uint)FuzzyCharType.Upper)

	// Bonus: case matches, or a Head in the pattern aligns with one in the word.
	// Single-case patterns lack segmentation signals and we assume any character
	// can be a head of a segment.
	if matcher.pattern[p] == matcher.word[w] ||
	(matcher.word_role[w] == FuzzyCharRole.Head &&
	(is_pattern_single_case || matcher.pattern_role[p] == FuzzyCharRole.Head)) {
		s += 1
		//fmt.println("match 1");
	}

	// Bonus: a consecutive match. First character match also gets a bonus to
	// ensure prefix final match score normalizes to 1.0.
	if w == 0 || last == match {
		s += 2
		//fmt.println("match 2");
	}

	// Penalty: matching inside a segment (and previous char wasn't matched).
	if matcher.word_role[w] == FuzzyCharRole.Tail && p > 0 && last == miss {
		s -= 3
		//fmt.println("match 3");
	}

	// Penalty: a Head in the pattern matches in the middle of a word segment.
	if matcher.pattern_role[p] == FuzzyCharRole.Head && matcher.word_role[w] == FuzzyCharRole.Tail {
		s -= 1
		//fmt.println("match 4");
	}

	// Penalty: matching the first pattern character in the middle of a segment.
	if p == 0 && matcher.word_role[w] == FuzzyCharRole.Tail {
		s -= 4
		//fmt.println("match 5");
	}

	assert(s <= perfect_bonus)

	return s
}

fuzzy_allow_match :: proc(matcher: ^FuzzyMatcher, p: int, w: int, last: int) -> bool {
	if matcher.lower_pattern[p] != matcher.lower_word[w] {
		return false
	}

	if last == miss {

		if matcher.word_role[w] == FuzzyCharRole.Tail && (matcher.word[w] == matcher.lower_word[w] ||
		0 >= (cast(uint)matcher.word_type_set & 1 << cast(uint)FuzzyCharType.Lower)) {
			return false
		}
	}

	return true
}