-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfzf-native-module.c
More file actions
8826 lines (8168 loc) · 336 KB
/
Copy pathfzf-native-module.c
File metadata and controls
8826 lines (8168 loc) · 336 KB
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
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* strdup is POSIX (not C11); Linux glibc hides it under c11 without this. */
#if defined(__linux__) && !defined(_POSIX_C_SOURCE)
# define _POSIX_C_SOURCE 200809L
#endif
#include <assert.h>
#include <ctype.h>
#include <stdalign.h>
#include <stdbool.h>
#include <stdint.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include "emacs-module.h"
#include "fzf.h"
#include "fzf-additions.h"
#include "fzf-private.h"
#include "fzf-simd-prefilter.h"
#include "utf8proc-2.10.0/utf8proc.h"
#include <stdio.h>
#include <stdarg.h>
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
#include <stdatomic.h>
#include <pthread.h>
// for sysconf(_SC_NPROCESSORS_ONLN);
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <poll.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
/* Block all signals on the current thread. Worker threads call this on
entry so async signals (SIGCHLD, SIGIO, ...) only ever land on Emacs's
main thread. Otherwise Emacs's signal handler forwards via pthread_kill,
which can recursively lock an os_unfair_lock if it fires while the worker
is inside libsystem code — observed crash on macOS. Synchronous faults
(SIGSEGV/etc.) are delivered by the kernel regardless of mask. */
#if defined(FZF_NATIVE_CTEST)
static inline void fzf_block_all_signals(void) {}
#else
static inline void fzf_block_all_signals(void) {
sigset_t s;
sigfillset(&s);
pthread_sigmask(SIG_BLOCK, &s, NULL);
}
#endif
/* A forked producer must not inherit Emacs's thread signal mask or ignored
termination dispositions. Otherwise stop can successfully send SIGTERM
while the child remains alive indefinitely. */
static inline void fzf_prepare_forked_child_signals(void) {
sigset_t empty;
sigemptyset(&empty);
sigprocmask(SIG_SETMASK, &empty, NULL);
struct sigaction action;
memset(&action, 0, sizeof action);
action.sa_handler = SIG_DFL;
sigemptyset(&action.sa_mask);
sigaction(SIGTERM, &action, NULL);
sigaction(SIGINT, &action, NULL);
sigaction(SIGQUIT, &action, NULL);
sigaction(SIGHUP, &action, NULL);
}
#else
/* Non-POSIX (Windows): no signals to block, worker entry calls become no-ops. */
static inline void fzf_block_all_signals(void) {}
#endif
#ifdef _WIN32
/* emacs-module.h declares emacs_module_init before this translation unit can
add __declspec(dllexport), and MSVC rejects a differently decorated
definition. The Windows target exports the two ABI symbols with the module
definition file instead. */
# define EXPORT
#elif defined(__GNUC__) || defined(__clang__)
# define EXPORT __attribute__((visibility("default")))
#else
# define EXPORT
#endif
/* Compile-time logging gate. Build with FZF_NATIVE_DEBUG=1 to enable
file logging; otherwise fzf_log() is a no-op macro and all call-site
args are discarded by the preprocessor (zero runtime cost). */
#ifdef FZF_NATIVE_DEBUG
static FILE *fzf_log_file = NULL;
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
static pthread_mutex_t fzf_log_mu = PTHREAD_MUTEX_INITIALIZER;
#endif
static void fzf_log(const char *format, ...) {
if (!fzf_log_file) return;
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
pthread_mutex_lock(&fzf_log_mu);
#endif
time_t now = time(NULL);
struct tm *t = localtime(&now);
char tstr[64];
strftime(tstr, sizeof(tstr), "%Y-%m-%d %H:%M:%S", t);
fprintf(fzf_log_file, "[%s] ", tstr);
va_list args;
va_start(args, format);
vfprintf(fzf_log_file, format, args);
va_end(args);
fflush(fzf_log_file);
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
pthread_mutex_unlock(&fzf_log_mu);
#endif
}
#else
#define fzf_log(...) ((void)0)
#endif
static struct emacs_runtime *global_rt;
/** See https://wambold.com/Martin/writings/alignof.html */
#define ALIGNOF(type) offsetof (struct { char c; type member; }, member)
/** MSVC does not recognize __attribute__((unused)), so define it away. */
#ifdef _MSC_VER
#define UNUSED(x) x
#else
#define UNUSED(x) __attribute__((unused)) x
#endif
#ifdef _WIN32
typedef long ssize_t;
#endif
#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
#define BATCH_SIZE 2048
#ifndef ASYNC_BATCH_WINDOW
#define ASYNC_BATCH_WINDOW 64
#endif
#define ASYNC_WORKER_LIMIT 64
#define BATCH_CACHE_BUCKETS 4096
#define BATCH_CACHE_QUERY_BUCKETS 4096
#define BATCH_CACHE_MAX_QUERIES 4096
#define BATCH_CACHE_SOURCE_SCAN_LIMIT 256
#define BATCH_CACHE_SPARSE_LIMIT 128
/* Turn the fallible POSIX CPU-count probe into a bounded worker count.
WORK_ITEMS == 0 means that no per-call work cap applies (the persistent
async pool case). A zero or negative probe must still run one worker;
casting it directly to unsigned can otherwise mean zero workers or a huge
allocation. */
static unsigned fzf_worker_count(long detected_cpus, size_t work_items) {
unsigned count = detected_cpus > 0
? detected_cpus > ASYNC_WORKER_LIMIT
? ASYNC_WORKER_LIMIT
: (unsigned)detected_cpus
: 1;
if (work_items > 0 && work_items < count)
count = (unsigned)work_items;
return count;
}
/* Increment when any public native-module contract requires matching Elisp.
This covers batch APIs on every platform and interactive APIs on POSIX. */
#define FZF_NATIVE_ABI 2
/* Retain the C-test and POSIX compatibility name for the session API. */
#define FZF_NATIVE_SESSION_ABI FZF_NATIVE_ABI
EXPORT
int plugin_is_GPL_compatible;
emacs_value Qnil, Qlistofzero, Fcons, Flist, Qt;
emacs_value Fhashtablep, Fmessage, Fvectorp, Fconsp, Fcdr, Fcar, Fvconcat;
emacs_value Ffunctionp, Fsymbolp, Fsymbolname, Flength, Fnth, Fprinc, Freverse;
emacs_value Qcompletion_score, Fput_text_property, Qzero, Qone;
emacs_value Fcopy_sequence, Fsetcar, Faset, Fmultibyte_string_p;
emacs_value Fencode_coding_string, Qutf_8;
emacs_value Qface, Qcompletions_common_part;
emacs_value Fremove_text_properties, Qface_nil_plist;
emacs_value Fsymbol_value;
/* Cached defcustom name symbols — interned once at init, looked up via
`defcustom_value' on each read. The values themselves stay dynamic
so user `setq' / `customize-set-variable' is respected. */
emacs_value Qsym_score_scheme, Qsym_case_mode, Qsym_fuzzy;
emacs_value Qsym_normalize, Qsym_search_direction;
emacs_value Qsym_batch_highlight, Qsym_async_highlight;
emacs_value Qsym_max_line_length, Qsym_async_cache_size;
emacs_value Qsym_async_cache_bytes;
emacs_value Qsym_async_batch_cache_bytes, Qsym_filter_only_min_pool;
emacs_value Qsym_filter_only_length, Qsym_filter_only_logic;
emacs_value Qsym_shell_file_name, Qsym_shell_command_switch, Qsym_exec_path;
emacs_value Qsym_process_environment;
emacs_value Qsym_highlight_fn;
/* Cached value symbols for `type-of' comparisons and signal/error names. */
emacs_value Qvector, Qstring, Qdefault, Qpath, Qhistory, Qignore, Qrespect;
emacs_value Qauto, Qforward, Qbackward;
emacs_value Qor, Qand;
emacs_value Qstringp, Qwrong_type_argument, Qerror;
typedef void (*fzf_native_finalizer_fn)(void *);
static void slab_finalize(void *object);
static void async_session_finalize(void *object);
static void async_signal_error(emacs_env *env, const char *message) {
emacs_value msg = env->make_string(env, message,
(ptrdiff_t)strlen(message));
env->non_local_exit_signal(env, Qerror,
env->funcall(env, Flist, 1, &msg));
}
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
static void async_signal_posix_error(emacs_env *env, const char *operation,
int error_number) {
char message[256];
snprintf(message, sizeof message, "fzf-native: %s failed: %s",
operation, strerror(error_number > 0 ? error_number : EIO));
async_signal_error(env, message);
}
#endif
/* Emacs user pointers carry no C type information in their payload. Check
the registered finalizer before casting so a slab cannot be interpreted as
an AsyncSession (or vice versa). Cross-kind pointers previously exposed
fabricated metadata and could send teardown through arbitrary memory. */
static void *fzf_native_typed_user_ptr(
emacs_env *env, emacs_value value,
fzf_native_finalizer_fn expected_finalizer,
const char *expected_name) {
void *ptr = env->get_user_ptr(env, value);
if (env->non_local_exit_check(env) != emacs_funcall_exit_return)
return NULL;
fzf_native_finalizer_fn actual_finalizer =
env->get_user_finalizer(env, value);
if (env->non_local_exit_check(env) != emacs_funcall_exit_return)
return NULL;
if (actual_finalizer != expected_finalizer) {
char message[128];
snprintf(message, sizeof message,
"fzf-native: expected %s", expected_name);
async_signal_error(env, message);
return NULL;
}
return ptr;
}
/** An Emacs string made accessible by copying. */
struct Str { char *b; size_t len; };
static bool str_has_embedded_nul(struct Str value) {
return value.b && memchr(value.b, '\0', value.len) != NULL;
}
/* Validate the bounded candidate and classify it in one pass. The matcher
otherwise scans the same immutable bytes once for strlen and once for
ASCII classification after this module has already scanned them for NUL. */
static bool str_analyze_candidate(struct Str value, bool *input_is_ascii) {
const unsigned char *ptr = (const unsigned char *)value.b;
size_t len = value.len;
bool ascii = true;
const uint64_t ones = UINT64_C(0x0101010101010101);
const uint64_t highs = UINT64_C(0x8080808080808080);
if (!ptr) {
*input_is_ascii = true;
return len == 0;
}
while (len >= sizeof(uint64_t)) {
uint64_t word;
memcpy(&word, ptr, sizeof word);
if ((word - ones) & ~word & highs) return false;
if (word & highs) ascii = false;
ptr += sizeof word;
len -= sizeof word;
}
while (len-- > 0) {
unsigned char byte = *ptr++;
if (byte == 0) return false;
if (byte & 0x80) ascii = false;
}
*input_is_ascii = ascii;
return true;
}
static bool reject_embedded_nul(emacs_env *env, struct Str value,
const char *what) {
if (!str_has_embedded_nul(value)) return false;
char message[128];
snprintf(message, sizeof message,
"fzf-native: embedded NUL in %s is not supported", what);
async_signal_error(env, message);
return true;
}
static bool bytes_are_valid_utf8(const char *bytes, size_t length) {
size_t offset = 0;
while (offset < length) {
utf8proc_int32_t codepoint = 0;
utf8proc_ssize_t width = utf8proc_iterate(
(const utf8proc_uint8_t *)bytes + offset,
(utf8proc_ssize_t)(length - offset), &codepoint);
if (width <= 0) return false;
offset += (size_t)width;
}
return true;
}
/* Count Emacs-style characters (Unicode codepoints) in UTF-8 data. Invalid
bytes count as one character each so byte-junk inputs always make progress
and retain the module's existing best-effort behavior. */
static size_t utf8_character_count(const char *str, size_t byte_len) {
size_t byte_pos = 0;
size_t char_count = 0;
while (byte_pos < byte_len) {
utf8proc_int32_t codepoint;
utf8proc_ssize_t width = utf8proc_iterate(
(const utf8proc_uint8_t *)(str + byte_pos),
(utf8proc_ssize_t)(byte_len - byte_pos), &codepoint);
byte_pos += width > 0 ? (size_t)width : 1;
char_count++;
}
return char_count;
}
/* Return the byte length of the first CHAR_LIMIT codepoints without splitting
a valid UTF-8 sequence. Invalid bytes count as one codepoint. */
static size_t utf8_prefix_byte_length(const char *str, size_t byte_len,
size_t char_limit) {
size_t byte_pos = 0;
size_t char_count = 0;
while (byte_pos < byte_len && char_count < char_limit) {
utf8proc_int32_t codepoint;
utf8proc_ssize_t width = utf8proc_iterate(
(const utf8proc_uint8_t *)(str + byte_pos),
(utf8proc_ssize_t)(byte_len - byte_pos), &codepoint);
byte_pos += width > 0 ? (size_t)width : 1;
char_count++;
}
return byte_pos;
}
/** Module userdata that gets allocated once at initialization. */
struct Data {
unsigned max_workers;
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
pthread_t threads[];
#endif
};
/** Intrusive linked list of bump allocation blocks. */
struct Bump {
struct Bump *next;
char *cursor, *limit, b[];
};
#ifdef FZF_NATIVE_CTEST
static _Atomic bool copy_test_fail_bump_allocation;
static _Atomic size_t bump_test_live_blocks;
#endif
static void bump_free(struct Bump *head) {
while (head) {
struct Bump *next = head->next;
#ifdef FZF_NATIVE_CTEST
atomic_fetch_sub_explicit(
&bump_test_live_blocks, 1, memory_order_relaxed);
#endif
free(head);
head = next;
}
}
/** Copies the Emacs string to make its contents accessible.
Probes the required buffer size with a NULL-buf call first, then either
copies into remaining bump space (if it fits) or allocates a new block.
Avoids the opportunistic "try inline, catch memory-buffer-too-small,
retry" pattern: that signal is now caught by CATCHER_ALL_DEBUGGABLE
on Emacs 31+, which invokes `debug' before the module handler can
convert it to a pending exit -- so with `debug-on-error' on, the
silent retry pops the debugger. */
static struct Str copy_valid_emacs_string(emacs_env *env, struct Bump **bump, emacs_value value) {
ptrdiff_t len;
if (!env->copy_string_contents(env, value, NULL, &len)) {
/* Length probe failed (e.g., unicode-string-p on an invalid unibyte
string). Leave the pending exit set so the caller can try the
encode-coding-string fallback. */
return (struct Str) { 0 };
}
char *buf;
if (*bump && (*bump)->limit - (*bump)->cursor >= len) {
/* Fits in current bump. Copy inline. */
buf = (*bump)->cursor;
} else {
/* Need a new bump. Grow at least 2x the current head, and at least
enough to fit this string plus alignment slack. */
size_t capacity = *bump ? 2 * (size_t)((*bump)->limit - (*bump)->b) : 2048;
if (capacity < (size_t) len) capacity = len + alignof(uint64_t) - 1;
struct Bump *new = NULL;
#ifdef FZF_NATIVE_CTEST
bool force_allocation_failure = atomic_exchange_explicit(
©_test_fail_bump_allocation, false, memory_order_acq_rel);
#else
bool force_allocation_failure = false;
#endif
if (force_allocation_failure ||
!(new = malloc(sizeof *new + capacity)))
return (struct Str) { 0 };
#ifdef FZF_NATIVE_CTEST
atomic_fetch_add_explicit(
&bump_test_live_blocks, 1, memory_order_relaxed);
#endif
*new = (struct Bump) { .next = *bump, .cursor = new->b, .limit = new->b + capacity };
*bump = new;
buf = new->cursor;
}
if (!env->copy_string_contents(env, value, buf, &len)) {
/* Rare: state changed between probe and copy (e.g. string mutated).
Clear any pending exit and drop the candidate. */
if (env->non_local_exit_check(env) != emacs_funcall_exit_return)
env->non_local_exit_clear(env);
return (struct Str) { 0 };
}
(*bump)->cursor = (char *) (((uintptr_t) (*bump)->cursor + len
+ alignof(uint64_t) - 1) & ~(alignof(uint64_t) - 1));
return (struct Str) { buf, len - 1 };
}
/**
* Like copy_emacs_string, but if the direct copy fails (e.g. because VALUE is
* an invalid unibyte string that Emacs's module API refuses to hand out via
* copy_string_contents, signaling `unicode-string-p'), fall back to encoding
* VALUE through `encode-coding-string' with UTF-8 and retry. This lets us
* accept arbitrary multibyte and byte-junk candidates without aborting the
* whole batch. The original VALUE is never mutated; the encoding happens on a
* fresh Emacs string that we then copy into the bump. Returns a zero Str if
* even the coerced copy fails, in which case callers should skip the
* candidate.
*/
static struct Str copy_emacs_string(emacs_env *env, struct Bump **bump,
emacs_value value) {
struct Str s = copy_valid_emacs_string(env, bump, value);
if (s.b) return s;
/* Only a direct-copy signal justifies representation conversion. A bump
allocation failure leaves no pending exit; treating that as an encoding
failure used to recurse forever while the allocator kept returning NULL. */
if (env->non_local_exit_check(env) == emacs_funcall_exit_return)
return (struct Str) { 0 };
env->non_local_exit_clear(env);
emacs_value encode_args[] = { value, Qutf_8, Qt };
emacs_value encoded = env->funcall(env, Fencode_coding_string, 3, encode_args);
if (env->non_local_exit_check(env) != emacs_funcall_exit_return) {
env->non_local_exit_clear(env);
return (struct Str) { 0 };
}
/* The encoded value is the one and only fallback. Do not recurse if its
copy also fails: a second conversion cannot make progress and can turn a
runtime failure into unbounded recursion. */
s = copy_valid_emacs_string(env, bump, encoded);
if (!s.b && env->non_local_exit_check(env) != emacs_funcall_exit_return) {
env->non_local_exit_clear(env);
}
return s;
}
typedef struct {
uint16_t score;
uint16_t first;
uint16_t second;
} FzfRankKeys;
static bool fzf_rank_is_space(utf8proc_int32_t codepoint) {
return (codepoint >= 0x09 && codepoint <= 0x0d) ||
codepoint == 0x20 || codepoint == 0x85 || codepoint == 0xa0 ||
codepoint == 0x1680 ||
(codepoint >= 0x2000 && codepoint <= 0x200a) ||
codepoint == 0x2028 || codepoint == 0x2029 ||
codepoint == 0x202f || codepoint == 0x205f ||
codepoint == 0x3000;
}
static uint16_t fzf_rank_u16(size_t value) {
return value > UINT16_MAX ? UINT16_MAX : (uint16_t)value;
}
static uint16_t fzf_rank_score(int64_t score) {
if (score <= 0) return 0;
return score > UINT16_MAX ? UINT16_MAX : (uint16_t)score;
}
static uint64_t fzf_rank_sort_key(FzfRankKeys rank) {
return ((uint64_t)(UINT16_MAX - rank.score) << 32) |
((uint64_t)rank.first << 16) | (uint64_t)rank.second;
}
/* Each scheme uses an upper portion of the packed rank key. LSD sorting can
skip the lower bytes that are constant for the scheme: history has only
score, default adds one secondary key, and path uses all three keys. */
static unsigned fzf_rank_radix_first_pass(fzf_score_scheme_t scheme) {
if (scheme == FZF_SCORE_SCHEME_HISTORY) return 4;
if (scheme == FZF_SCORE_SCHEME_DEFAULT) return 2;
return 0;
}
/* Build the non-score sort keys used by pinned fzf. Default ranks by the
Unicode-trimmed character count. Path ranks by the distance from the last
slash or backslash, then by that count. History has no extra key. */
static FzfRankKeys fzf_rank_keys_preclassified(
const char *text, size_t text_len, bool input_is_ascii,
const fzf_score_bounds_t *bounds, fzf_score_scheme_t scheme) {
FzfRankKeys keys = {0};
keys.score = fzf_rank_score(bounds ? bounds->raw_score : 0);
if (scheme == FZF_SCORE_SCHEME_HISTORY) return keys;
/* For ASCII, rune indexes are byte indexes and fzf's Unicode trim length
is the byte span after removing ASCII whitespace at the two edges. */
if (input_is_ascii) {
size_t first = 0, end = text_len;
while (first < end &&
fzf_rank_is_space((unsigned char)text[first]))
first++;
while (end > first &&
fzf_rank_is_space((unsigned char)text[end - 1]))
end--;
size_t trim_length = end - first;
if (scheme == FZF_SCORE_SCHEME_DEFAULT) {
keys.first = fzf_rank_u16(trim_length);
return keys;
}
ptrdiff_t last_delimiter = -1;
for (size_t i = text_len; i > 0; i--) {
if (text[i - 1] == '/' || text[i - 1] == '\\') {
last_delimiter = (ptrdiff_t)(i - 1);
break;
}
}
keys.first = UINT16_MAX;
if (bounds && bounds->valid && bounds->min_begin >= 0 &&
last_delimiter <= bounds->min_begin) {
size_t distance = (size_t)((ptrdiff_t)bounds->min_begin -
last_delimiter);
keys.first = fzf_rank_u16(distance);
}
keys.second = fzf_rank_u16(trim_length);
return keys;
}
size_t offset = 0, rune_index = 0;
size_t first_nonspace = SIZE_MAX, last_nonspace = 0;
ptrdiff_t last_delimiter = -1;
while (offset < text_len) {
utf8proc_int32_t codepoint = 0;
utf8proc_ssize_t width = utf8proc_iterate(
(const utf8proc_uint8_t *)text + offset,
(utf8proc_ssize_t)(text_len - offset), &codepoint);
if (width <= 0) {
codepoint = (unsigned char)text[offset];
width = 1;
}
if (!fzf_rank_is_space(codepoint)) {
if (first_nonspace == SIZE_MAX) first_nonspace = rune_index;
last_nonspace = rune_index;
}
if (codepoint == '/' || codepoint == '\\')
last_delimiter = (ptrdiff_t)rune_index;
offset += (size_t)width;
rune_index++;
}
size_t trim_length = first_nonspace == SIZE_MAX
? 0 : last_nonspace - first_nonspace + 1;
if (scheme == FZF_SCORE_SCHEME_DEFAULT) {
keys.first = fzf_rank_u16(trim_length);
} else if (scheme == FZF_SCORE_SCHEME_PATH) {
keys.first = UINT16_MAX;
if (bounds && bounds->valid && bounds->min_begin >= 0 &&
last_delimiter <= bounds->min_begin) {
size_t distance = (size_t)((ptrdiff_t)bounds->min_begin -
last_delimiter);
keys.first = fzf_rank_u16(distance);
}
keys.second = fzf_rank_u16(trim_length);
}
return keys;
}
/* A single positive term has the same public and raw scores unless the
public scorer clamps a non-positive raw score to the match sentinel 1.
Path ranking always needs match bounds. */
static bool fzf_rank_can_reuse_public_score(
const fzf_pattern_t *pattern, fzf_score_scheme_t scheme) {
return scheme != FZF_SCORE_SCHEME_PATH && pattern &&
pattern->size == 1 && pattern->ptr[0]->size == 1 &&
!pattern->ptr[0]->ptr[0].inv;
}
static int fzf_score_and_rank(
const char *text, size_t text_len, bool input_is_ascii,
fzf_pattern_t *pattern, fzf_slab_t *slab,
fzf_score_scheme_t scheme, bool can_reuse_public_score,
FzfRankKeys *rank) {
fzf_score_bounds_t bounds = {0};
int score;
if (can_reuse_public_score) {
score = fzf_get_score_bytes_preclassified(
text, text_len, input_is_ascii, pattern, slab);
if (score == 1) {
/* One is ambiguous: it can be a real raw score or the clamped value
of a valid non-positive v1 match. Re-score only this rare case. */
score = fzf_get_score_with_bounds_bytes_preclassified(
text, text_len, input_is_ascii, pattern, slab, &bounds);
} else {
bounds.raw_score = score;
}
} else {
score = fzf_get_score_with_bounds_bytes_preclassified(
text, text_len, input_is_ascii, pattern, slab, &bounds);
}
if (score > 0 && rank)
*rank = fzf_rank_keys_preclassified(
text, text_len, input_is_ascii, &bounds, scheme);
return score;
}
struct Candidate {
emacs_value value;
struct Str s;
int score;
FzfRankKeys rank;
size_t idx;
};
static int candidate_order(const struct Candidate *left,
const struct Candidate *right) {
uint16_t left_score = left->rank.score;
uint16_t right_score = right->rank.score;
if (left_score != right_score) return left_score > right_score ? -1 : 1;
if (left->rank.first != right->rank.first)
return left->rank.first < right->rank.first ? -1 : 1;
if (left->rank.second != right->rank.second)
return left->rank.second < right->rank.second ? -1 : 1;
if (left->idx != right->idx) return left->idx < right->idx ? -1 : 1;
return 0;
}
static int cmp_candidate(const void *a, const void *b) {
return candidate_order(a, b);
}
static void insertion_sort_candidates(struct Candidate *xs, size_t n) {
for (size_t i = 1; i < n; i++) {
struct Candidate candidate = xs[i];
size_t j = i;
while (j > 0 && candidate_order(&xs[j - 1], &candidate) > 0) {
xs[j] = xs[j - 1];
j--;
}
xs[j] = candidate;
}
}
/* Stable radix sort of xs[0..n-1] by the packed fzf rank key. The input is
in producer order, so an exact key tie already has the final index order.
Allocation failure uses the same total comparator through qsort. */
static void counting_sort_candidates(struct Candidate *xs, size_t n,
fzf_score_scheme_t scheme) {
if (n <= 1) return;
/* Avoid the radix scratch allocation for tiny inputs. */
if (n < 64) { insertion_sort_candidates(xs, n); return; }
unsigned first_pass = fzf_rank_radix_first_pass(scheme);
uint64_t first_key = fzf_rank_sort_key(xs[0].rank);
uint64_t varying_bits = 0;
for (size_t i = 1; i < n; i++)
varying_bits |= fzf_rank_sort_key(xs[i].rank) ^ first_key;
varying_bits &= UINT64_MAX << (first_pass * 8);
if (varying_bits == 0) return;
struct Candidate *out = malloc(n * sizeof *out);
if (!out) { qsort(xs, n, sizeof *xs, cmp_candidate); return; }
unsigned active_passes[6];
size_t active_count = 0;
size_t counts[6][256];
for (unsigned pass = first_pass; pass < 6; pass++) {
if ((varying_bits & (UINT64_C(0xff) << (pass * 8))) != 0) {
active_passes[active_count] = pass;
memset(counts[active_count], 0, sizeof counts[active_count]);
active_count++;
}
}
if (active_count == 2) {
unsigned first_shift = active_passes[0] * 8;
unsigned second_shift = active_passes[1] * 8;
for (size_t i = 0; i < n; i++) {
uint64_t key = fzf_rank_sort_key(xs[i].rank);
counts[0][(key >> first_shift) & 0xff]++;
counts[1][(key >> second_shift) & 0xff]++;
}
} else {
for (size_t i = 0; i < n; i++) {
uint64_t key = fzf_rank_sort_key(xs[i].rank);
for (size_t active = 0; active < active_count; active++) {
unsigned shift = active_passes[active] * 8;
counts[active][(key >> shift) & 0xff]++;
}
}
}
struct Candidate *src = xs, *dst = out;
for (size_t active = 0; active < active_count; active++) {
unsigned pass = active_passes[active];
unsigned shift = pass * 8;
size_t offset[256];
offset[0] = 0;
for (size_t i = 1; i < 256; i++)
offset[i] = offset[i - 1] + counts[active][i - 1];
for (size_t i = 0; i < n; i++) {
size_t byte = (fzf_rank_sort_key(src[i].rank) >> shift) & 0xff;
dst[offset[byte]++] = src[i];
}
struct Candidate *swap = src;
src = dst;
dst = swap;
}
if (src != xs) memcpy(xs, src, n * sizeof *xs);
free(out);
}
struct Batch {
unsigned len;
struct Candidate xs[BATCH_SIZE];
};
struct Shared {
fzf_pattern_t *pattern;
struct Batch *const batches;
fzf_score_scheme_t score_scheme;
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
_Atomic ssize_t remaining;
#else
ssize_t remaining;
#endif
/* When true, workers call `fzf_has_match' (cheap boolean) instead of
`fzf_get_score' and assign score=1 to survivors. The caller skips
ranked sorting to keep input order. */
bool filter_only;
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
_Atomic bool allocation_failed;
_Atomic bool embedded_nul;
#else
/* Windows executes this worker synchronously on the calling thread. MSVC's
C11 mode does not implement `_Atomic', so no synchronization is needed. */
bool allocation_failed;
bool embedded_nul;
#endif
};
static bool shared_allocation_failed(struct Shared *shared) {
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
return atomic_load_explicit(&shared->allocation_failed,
memory_order_relaxed);
#else
return shared->allocation_failed;
#endif
}
static void shared_set_allocation_failed(struct Shared *shared) {
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
atomic_store_explicit(&shared->allocation_failed, true,
memory_order_relaxed);
#else
shared->allocation_failed = true;
#endif
}
static bool shared_embedded_nul(struct Shared *shared) {
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
return atomic_load_explicit(&shared->embedded_nul, memory_order_relaxed);
#else
return shared->embedded_nul;
#endif
}
static void shared_set_embedded_nul(struct Shared *shared) {
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
atomic_store_explicit(&shared->embedded_nul, true, memory_order_relaxed);
#else
shared->embedded_nul = true;
#endif
}
static bool shared_worker_should_stop(struct Shared *shared) {
return shared_allocation_failed(shared);
}
// Most of the threading lifted from https://github.com/axelf4/hotfuzz
static void *worker_routine(void *ptr) {
fzf_block_all_signals();
/* printf("-----\nStarting Worker Routine\n-----\n"); */
struct Shared *shared = ptr;
// Create a one-time use slab.
fzf_slab_t *slab = fzf_make_default_slab();
if (!slab || !fzf_slab_set_score_scheme(slab, shared->score_scheme)) {
shared_set_allocation_failed(shared);
fzf_free_slab(slab);
return NULL;
}
fzf_pattern_t *pattern = shared->pattern;
bool filter_only = shared->filter_only;
bool can_reuse_public_score =
fzf_rank_can_reuse_public_score(pattern, shared->score_scheme);
ssize_t batch_idx;
#ifdef _WIN32
while ((batch_idx = --shared->remaining) >= 0) {
#endif
// Atomic fetch-and-decrement for shared->remaining
// --shared->remaining would return the decremented value whereas
// atomic_fetch_sub_explicit returns the original value before decrement.
// So, use batch_idx - 1 when handling the idx.
#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)
while ((batch_idx = atomic_fetch_sub_explicit(&shared->remaining,
1,
memory_order_seq_cst) - 1) >= 0) {
#endif
struct Batch *batch = shared->batches + batch_idx;
unsigned n = 0;
bool invalid_candidate = false;
/* A peer OOM is terminal. Check once per immutable batch so the
exceptional cross-worker stop does not add an atomic load and branch
to every ordinary candidate. The worker that observes its own OOM
still stops immediately below; peers finish at most one 2048-row
batch before seeing the shared failure. */
if (shared_worker_should_stop(shared))
break;
if (pattern) {
for (unsigned i = 0; i < batch->len; ++i) {
struct Candidate x = batch->xs[i];
bool input_is_ascii;
/* Validate candidate bytes on the worker that already owns this
batch. NUL is an invalid-input exception: publish it with a
write-only relaxed flag and stop only this worker. Other workers
may finish, but ordinary candidates pay no shared-state read. */
if (!str_analyze_candidate(x.s, &input_is_ascii)) {
shared_set_embedded_nul(shared);
invalid_candidate = true;
break;
}
/* You can get the score/position for as many items as you want */
FzfRankKeys rank = {0};
int score = filter_only
? (fzf_has_match_bytes_preclassified(
x.s.b, x.s.len, input_is_ascii, pattern, slab) ? 1 : 0)
: fzf_score_and_rank(
x.s.b, x.s.len, input_is_ascii, pattern, slab,
shared->score_scheme, can_reuse_public_score, &rank);
if (fzf_allocation_failed()) {
shared_set_allocation_failed(shared);
break;
}
if (score > 0) {
/* printf("Str: %s # = %d | i = %d, batch->len = %d, batch_idx = %zd\n", */
/* x.s.b, score, i, batch->len, batch_idx); */
x.score = score;
if (!filter_only) x.rank = rank;
batch->xs[n++] = x;
}
}
}
batch->len = n;
if (invalid_candidate)
break;
}
// Free one-time use slab.
fzf_free_slab(slab);
/* printf("-----\nEnding Worker Routine\n-----\n"); */
return NULL;
}
/* Per-call scratch for `dispatch_highlight_runs'. Sized at the start of a
score / highlight-all / async-candidates call to the maximum possible
position count (the query length); reused across every top-N candidate
in that call to avoid per-candidate malloc/free churn.
`runs` is split into two halves: starts in [0, capacity), ends in
[capacity, 2*capacity). `vargs` holds 2*capacity emacs_values
(alternating start-val/end-val) for the `vector' funcall. */
typedef struct {
size_t *starts;
size_t *ends;
emacs_value *vargs;
size_t capacity; /* max positions; 0 means uninitialized */
} HlScratch;
static bool hl_scratch_init(HlScratch *s, size_t max_pos) {
s->capacity = 0;
s->starts = NULL; s->ends = NULL; s->vargs = NULL;
if (max_pos == 0) return true;
s->starts = (size_t *)malloc(max_pos * sizeof(size_t));
s->ends = (size_t *)malloc(max_pos * sizeof(size_t));
s->vargs = (emacs_value *)malloc(max_pos * 2 * sizeof(emacs_value));
if (!s->starts || !s->ends || !s->vargs) {
free(s->starts); free(s->ends); free(s->vargs);
s->starts = NULL; s->ends = NULL; s->vargs = NULL;
return false;
}
s->capacity = max_pos;
return true;
}
static void hl_scratch_free(HlScratch *s) {
free(s->starts);
free(s->ends);
free(s->vargs);
s->starts = NULL; s->ends = NULL; s->vargs = NULL;
s->capacity = 0;
}
/* NOTE: upstream main carried a `runs_byte_to_char' helper here that converted
fzf's byte-offset positions to character offsets, because upstream fzf.c
returns byte positions. This fork's UTF-8 fzf.c instead returns character
offsets directly (see `dispatch_highlight_runs'), so that conversion was
removed to avoid double-converting multibyte candidates. */
/* Dispatch fzf positions on CSTR to HOOK as offsets in STR's representation.
POS->data[] is fzf's descending character-offset list; consolidated
into ascending contiguous runs, mapped back to byte offsets when STR is
unibyte, packed into
[s0 e0 s1 e1 …] vector, and passed as (funcall HOOK STR positions).
A NULL/empty POS is dispatched as an empty vector so the hook can remove
highlights left by an earlier matching policy. It means "no positive
highlight positions", not "no match": inverse-only matches and genuine
misses both produce it. No-op only when HOOK is nil.
SCRATCH provides reusable buffers sized at the start of the score call;
when NULL or undersized, falls back to a per-call malloc/free pair. */
static void dispatch_highlight_runs(emacs_env *env, const char *cstr,
fzf_position_t *pos,
emacs_value str, emacs_value hook,
HlScratch *scratch) {
if (env->eq(env, hook, Qnil)) return;
if (!pos || pos->size == 0) {
emacs_value positions = env->funcall(env, Qvector, 0, NULL);
if (env->non_local_exit_check(env) != emacs_funcall_exit_return) {
env->non_local_exit_clear(env);
return;
}
/* The hook owns highlight mutation, including clear-only handling. */
env->funcall(env, hook, 2, (emacs_value[]){ str, positions });
if (env->non_local_exit_check(env) != emacs_funcall_exit_return) {
env->non_local_exit_clear(env);
}
return;
}
size_t plen = pos->size;
size_t *starts;
size_t *ends;
emacs_value *vargs;
bool need_free = false;
if (scratch && plen <= scratch->capacity) {
starts = scratch->starts;
ends = scratch->ends;
vargs = scratch->vargs;
} else {
starts = (size_t *)malloc(plen * sizeof(size_t));
ends = (size_t *)malloc(plen * sizeof(size_t));
vargs = (emacs_value *)malloc(plen * 2 * sizeof(emacs_value));
if (!starts || !ends || !vargs) {
free(starts); free(ends); free(vargs); return;
}
need_free = true;
}
/* Group ascending positions (fzf emits descending; we walk j = plen-2..0
against an ascending pos->data, with pos->data[plen-1] as the
smallest seed) into contiguous [start, end+1) runs. */
size_t n_runs = 0;
size_t cs = pos->data[plen - 1];
size_t ce = cs;
for (ptrdiff_t j = (ptrdiff_t)plen - 2; j >= 0; j--) {
size_t p = pos->data[j];
if (p == ce + 1) { ce = p; continue; }