Coverage Report

Created: 2026-11-10 14:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
src/strpbrk.c
Line
Count
Source
1
#include "prism/internal/strpbrk.h"
2
3
#include "prism/compiler/accel.h"
4
#include "prism/compiler/inline.h"
5
#include "prism/compiler/unused.h"
6
7
#include "prism/internal/assert.h"
8
#include "prism/internal/bit.h"
9
#include "prism/internal/diagnostic.h"
10
#include "prism/internal/encoding.h"
11
#include "prism/internal/parser.h"
12
13
#include <stdbool.h>
14
#include <string.h>
15
16
/**
17
 * Add an invalid multibyte character error to the parser.
18
 */
19
static PRISM_INLINE void
20
4.45k
pm_strpbrk_invalid_multibyte_character(pm_parser_t *parser, uint32_t start, uint32_t length) {
21
4.45k
    pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, start, length, PM_ERR_INVALID_MULTIBYTE_CHARACTER, parser->start[start]);
22
4.45k
}
23
24
/**
25
 * Set the explicit encoding for the parser to the current encoding.
26
 */
27
static PRISM_INLINE void
28
3.39k
pm_strpbrk_explicit_encoding_set(pm_parser_t *parser, uint32_t start, uint32_t length) {
29
3.39k
    if (parser->explicit_encoding != NULL) {
  Branch (29:9): [True: 2.47k, False: 920]
30
2.47k
        if (parser->explicit_encoding == parser->encoding) {
  Branch (30:13): [True: 2.46k, False: 13]
31
            // Okay, we already locked to this encoding.
32
2.46k
        } else 
if (13
parser->explicit_encoding == 13
PM_ENCODING_UTF_8_ENTRY13
) {
  Branch (32:20): [True: 13, False: 0]
33
            // Not okay, we already found a Unicode escape sequence and this
34
            // conflicts.
35
13
            pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, start, length, PM_ERR_MIXED_ENCODING, parser->encoding->name);
36
13
        } else {
37
            // Should not be anything else.
38
0
            PRISM_ASSERT(false && "unreachable");
  Branch (38:13): [Folded, False: 0]
  Branch (38:13): [True: 0, False: 0]
  Branch (38:13): [Folded, False: 0]
  Branch (38:13): [True: 0, False: 0]
39
0
        }
40
2.47k
    }
41
42
3.39k
    parser->explicit_encoding = parser->encoding;
43
3.39k
}
44
45
/**
46
 * Scan forward through ASCII bytes looking for a byte that is in the given
47
 * charset. Returns true if a match was found, storing its offset in *index.
48
 * Returns false if no match was found, storing the number of ASCII bytes
49
 * consumed in *index (so the caller can skip past them).
50
 *
51
 * All charset characters must be ASCII (< 0x80). The scanner stops at non-ASCII
52
 * bytes, returning control to the caller's encoding-aware loop.
53
 *
54
 * Up to three optimized implementations are selected at compile time, with a
55
 * no-op fallback for unsupported platforms:
56
 *   1. NEON — processes 16 bytes per iteration on aarch64.
57
 *   2. SSE2 — processes 16 bytes per iteration on x86-64.
58
 *   3. SWAR — little-endian fallback, processes 8 bytes per iteration.
59
 */
60
61
#if defined(PRISM_HAS_NEON) || defined(PRISM_HAS_SSE2) || defined(PRISM_HAS_SWAR)
62
63
/**
64
 * Update the cached strpbrk lookup tables if the charset has changed. The
65
 * parser caches the last charset's precomputed tables so that repeated calls
66
 * with the same breakpoints (the common case during string/regex/list lexing)
67
 * skip table construction entirely.
68
 *
69
 * Builds three structures:
70
 *   - low_lut/high_lut: nibble-based lookup tables for SIMD matching (NEON)
71
 *   - table: 256-bit bitmap for scalar fallback matching (all platforms)
72
 */
73
static PRISM_INLINE void
74
189k
pm_strpbrk_cache_update(pm_parser_t *parser, const uint8_t *charset) {
75
    // The cache key is the full charset buffer (PM_STRPBRK_CACHE_SIZE bytes).
76
    // Since it is always NUL-padded, a fixed-size comparison covers both
77
    // content and length.
78
189k
    if (memcmp(parser->strpbrk_cache.charset, charset, sizeof(parser->strpbrk_cache.charset)) == 0) 
return163k
;
  Branch (78:9): [True: 163k, False: 26.0k]
79
80
26.0k
    memset(parser->strpbrk_cache.low_lut, 0, sizeof(parser->strpbrk_cache.low_lut));
81
26.0k
    memset(parser->strpbrk_cache.high_lut, 0, sizeof(parser->strpbrk_cache.high_lut));
82
26.0k
    memset(parser->strpbrk_cache.table, 0, sizeof(parser->strpbrk_cache.table));
83
84
    // Always include NUL in the tables. The slow path uses strchr, which
85
    // always matches NUL (it finds the C string terminator), so NUL is
86
    // effectively always a breakpoint. Replicating that here lets the fast
87
    // scanner handle NUL at full speed instead of bailing to the slow path.
88
26.0k
    parser->strpbrk_cache.low_lut[0x00] |= (uint8_t) (1 << 0);
89
26.0k
    parser->strpbrk_cache.high_lut[0x00] = (uint8_t) (1 << 0);
90
26.0k
    parser->strpbrk_cache.table[0] |= (uint64_t) 1;
91
92
26.0k
    size_t charset_len = 0;
93
165k
    for (const uint8_t *c = charset; *c != '\0'; 
c++139k
) {
  Branch (93:38): [True: 139k, False: 26.0k]
94
139k
        parser->strpbrk_cache.low_lut[*c & 0x0F] |= (uint8_t) (1 << (*c >> 4));
95
139k
        parser->strpbrk_cache.high_lut[*c >> 4] = (uint8_t) (1 << (*c >> 4));
96
139k
        parser->strpbrk_cache.table[*c >> 6] |= (uint64_t) 1 << (*c & 0x3F);
97
139k
        charset_len++;
98
139k
    }
99
100
    // Store the new charset key, NUL-padded to the full buffer size.
101
26.0k
    memcpy(parser->strpbrk_cache.charset, charset, charset_len + 1);
102
26.0k
    memset(parser->strpbrk_cache.charset + charset_len + 1, 0, sizeof(parser->strpbrk_cache.charset) - charset_len - 1);
103
26.0k
}
104
105
#endif
106
107
#if defined(PRISM_HAS_NEON)
108
#include <arm_neon.h>
109
110
static PRISM_INLINE bool
111
189k
scan_strpbrk_ascii(pm_parser_t *parser, const uint8_t *source, size_t maximum, const uint8_t *charset, size_t *index) {
112
189k
    pm_strpbrk_cache_update(parser, charset);
113
114
189k
    uint8x16_t low_lut = vld1q_u8(parser->strpbrk_cache.low_lut);
115
189k
    uint8x16_t high_lut = vld1q_u8(parser->strpbrk_cache.high_lut);
116
189k
    uint8x16_t mask_0f = vdupq_n_u8(0x0F);
117
189k
    uint8x16_t mask_80 = vdupq_n_u8(0x80);
118
119
189k
    size_t idx = 0;
120
121
197k
    while (idx + 16 <= maximum) {
  Branch (121:12): [True: 184k, False: 13.1k]
122
184k
        uint8x16_t v = vld1q_u8(source + idx);
123
124
        // If any byte has the high bit set, we have non-ASCII data.
125
        // Return to let the caller's encoding-aware loop handle it.
126
184k
        if (vmaxvq_u8(vandq_u8(v, mask_80)) != 0) 
break20.6k
;
  Branch (126:13): [True: 20.6k, False: 163k]
127
128
163k
        uint8x16_t lo_class = vqtbl1q_u8(low_lut, vandq_u8(v, mask_0f));
129
163k
        uint8x16_t hi_class = vqtbl1q_u8(high_lut, vshrq_n_u8(v, 4));
130
163k
        uint8x16_t matched = vtstq_u8(lo_class, hi_class);
131
132
163k
        if (vmaxvq_u8(matched) == 0) {
  Branch (132:13): [True: 7.55k, False: 155k]
133
7.55k
            idx += 16;
134
7.55k
            continue;
135
7.55k
        }
136
137
        // Find the position of the first matching byte.
138
155k
        uint64_t lo64 = vgetq_lane_u64(vreinterpretq_u64_u8(matched), 0);
139
155k
        if (lo64 != 0) {
  Branch (139:13): [True: 143k, False: 12.8k]
140
143k
            *index = idx + pm_ctzll(lo64) / 8;
141
143k
            return true;
142
143k
        }
143
12.8k
        uint64_t hi64 = vgetq_lane_u64(vreinterpretq_u64_u8(matched), 1);
144
12.8k
        *index = idx + 8 + pm_ctzll(hi64) / 8;
145
12.8k
        return true;
146
155k
    }
147
148
    // Scalar tail for remaining < 16 ASCII bytes.
149
90.9k
    
while (33.7k
idx < maximum &&
source[idx] < 0x8090.4k
) {
  Branch (149:12): [True: 90.4k, False: 551]
  Branch (149:29): [True: 84.0k, False: 6.38k]
150
84.0k
        uint8_t byte = source[idx];
151
84.0k
        if (parser->strpbrk_cache.table[byte >> 6] & ((uint64_t) 1 << (byte & 0x3F))) {
  Branch (151:13): [True: 26.8k, False: 57.1k]
152
26.8k
            *index = idx;
153
26.8k
            return true;
154
26.8k
        }
155
57.1k
        idx++;
156
57.1k
    }
157
158
6.94k
    *index = idx;
159
6.94k
    return false;
160
33.7k
}
161
162
#elif defined(PRISM_HAS_SSE2)
163
#include <emmintrin.h>
164
165
static PRISM_INLINE bool
166
scan_strpbrk_ascii(pm_parser_t *parser, const uint8_t *source, size_t maximum, const uint8_t *charset, size_t *index) {
167
    pm_strpbrk_cache_update(parser, charset);
168
169
    /*
170
     * SSE2 has no byte shuffle, so the nibble lookup used by NEON is not
171
     * available. Instead, each charset byte is broadcast into its own vector
172
     * and compared against the input directly. Charsets are short, so this is
173
     * a handful of compares per 16 bytes.
174
     */
175
    __m128i needles[sizeof(parser->strpbrk_cache.charset)];
176
    size_t needles_size = 0;
177
178
    for (size_t i = 0; i < sizeof(parser->strpbrk_cache.charset) && parser->strpbrk_cache.charset[i] != '\0'; i++) {
179
        needles[needles_size++] = _mm_set1_epi8((char) parser->strpbrk_cache.charset[i]);
180
    }
181
182
    const __m128i zero = _mm_setzero_si128();
183
    size_t idx = 0;
184
185
    while (idx + 16 <= maximum) {
186
        __m128i v = _mm_loadu_si128((const __m128i *) (source + idx));
187
188
        /* If any byte has the high bit set, stop. */
189
        if (_mm_movemask_epi8(v) != 0) break;
190
191
        /* NUL is always a breakpoint, matching pm_strpbrk_cache_update. */
192
        __m128i matched = _mm_cmpeq_epi8(v, zero);
193
        for (size_t i = 0; i < needles_size; i++) {
194
            matched = _mm_or_si128(matched, _mm_cmpeq_epi8(v, needles[i]));
195
        }
196
197
        int mask = _mm_movemask_epi8(matched);
198
199
        if (mask == 0) {
200
            idx += 16;
201
            continue;
202
        }
203
204
        /* Find the first matching byte. */
205
        *index = idx + pm_ctzll((uint64_t) (mask & 0xFFFF));
206
        return true;
207
    }
208
209
    /* Scalar tail. */
210
    while (idx < maximum && source[idx] < 0x80) {
211
        uint8_t byte = source[idx];
212
        if (parser->strpbrk_cache.table[byte >> 6] & ((uint64_t) 1 << (byte & 0x3F))) {
213
            *index = idx;
214
            return true;
215
        }
216
        idx++;
217
    }
218
219
    *index = idx;
220
    return false;
221
}
222
223
#elif defined(PRISM_HAS_SWAR)
224
225
static PRISM_INLINE bool
226
scan_strpbrk_ascii(pm_parser_t *parser, const uint8_t *source, size_t maximum, const uint8_t *charset, size_t *index) {
227
    pm_strpbrk_cache_update(parser, charset);
228
229
    static const uint64_t highs = 0x8080808080808080ULL;
230
    size_t idx = 0;
231
232
    while (idx + 8 <= maximum) {
233
        uint64_t word;
234
        memcpy(&word, source + idx, 8);
235
236
        // Bail on any non-ASCII byte.
237
        if (word & highs) break;
238
239
        // Check each byte against the charset table.
240
        for (size_t j = 0; j < 8; j++) {
241
            uint8_t byte = source[idx + j];
242
            if (parser->strpbrk_cache.table[byte >> 6] & ((uint64_t) 1 << (byte & 0x3F))) {
243
                *index = idx + j;
244
                return true;
245
            }
246
        }
247
248
        idx += 8;
249
    }
250
251
    // Scalar tail.
252
    while (idx < maximum && source[idx] < 0x80) {
253
        uint8_t byte = source[idx];
254
        if (parser->strpbrk_cache.table[byte >> 6] & ((uint64_t) 1 << (byte & 0x3F))) {
255
            *index = idx;
256
            return true;
257
        }
258
        idx++;
259
    }
260
261
    *index = idx;
262
    return false;
263
}
264
265
#else
266
267
static PRISM_INLINE bool
268
scan_strpbrk_ascii(PRISM_UNUSED pm_parser_t *parser, PRISM_UNUSED const uint8_t *source, PRISM_UNUSED size_t maximum, PRISM_UNUSED const uint8_t *charset, size_t *index) {
269
    *index = 0;
270
    return false;
271
}
272
273
#endif
274
275
/**
276
 * This is the default path.
277
 */
278
static PRISM_INLINE const uint8_t *
279
5.29k
pm_strpbrk_utf8(pm_parser_t *parser, const uint8_t *source, const uint8_t *charset, size_t index, size_t maximum, bool validate) {
280
47.0k
    while (index < maximum) {
  Branch (280:12): [True: 46.3k, False: 700]
281
46.3k
        if (strchr((const char *) charset, source[index]) != NULL) {
  Branch (281:13): [True: 4.59k, False: 41.7k]
282
4.59k
            return source + index;
283
4.59k
        }
284
285
41.7k
        if (source[index] < 0x80) {
  Branch (285:13): [True: 33.2k, False: 8.54k]
286
33.2k
            index++;
287
33.2k
        } else {
288
8.54k
            size_t width = pm_encoding_utf_8_char_width(source + index, (ptrdiff_t) (maximum - index));
289
290
8.54k
            if (width > 0) {
  Branch (290:17): [True: 478, False: 8.06k]
291
478
                index += width;
292
8.06k
            } else if (!validate) {
  Branch (292:24): [True: 4.31k, False: 3.74k]
293
4.31k
                index++;
294
4.31k
            } else {
295
                // At this point we know we have an invalid multibyte character.
296
                // We'll walk forward as far as we can until we find the next
297
                // valid character so that we don't spam the user with a ton of
298
                // the same kind of error.
299
3.74k
                const size_t start = index;
300
301
8.98k
                do {
302
8.98k
                    index++;
303
8.98k
                } while (index < maximum && 
pm_encoding_utf_8_char_width(source + index, (ptrdiff_t) (maximum - index)) == 08.93k
);
  Branch (303:26): [True: 8.93k, False: 44]
  Branch (303:45): [True: 5.23k, False: 3.70k]
304
305
3.74k
                pm_strpbrk_invalid_multibyte_character(parser, (uint32_t) ((source + start) - parser->start), (uint32_t) (index - start));
306
3.74k
            }
307
8.54k
        }
308
41.7k
    }
309
310
700
    return NULL;
311
5.29k
}
312
313
/**
314
 * This is the path when the encoding is ASCII-8BIT.
315
 */
316
static PRISM_INLINE const uint8_t *
317
63
pm_strpbrk_ascii_8bit(pm_parser_t *parser, const uint8_t *source, const uint8_t *charset, size_t index, size_t maximum, bool validate) {
318
588
    while (index < maximum) {
  Branch (318:12): [True: 582, False: 6]
319
582
        if (strchr((const char *) charset, source[index]) != NULL) {
  Branch (319:13): [True: 57, False: 525]
320
57
            return source + index;
321
57
        }
322
323
525
        if (validate && source[index] >= 0x80) 
pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source - parser->start), 1)256
;
  Branch (323:13): [True: 525, False: 0]
  Branch (323:25): [True: 256, False: 269]
324
525
        index++;
325
525
    }
326
327
6
    return NULL;
328
63
}
329
330
/**
331
 * This is the slow path that does care about the encoding.
332
 */
333
static PRISM_INLINE const uint8_t *
334
986
pm_strpbrk_multi_byte(pm_parser_t *parser, const uint8_t *source, const uint8_t *charset, size_t index, size_t maximum, bool validate) {
335
986
    const pm_encoding_t *encoding = parser->encoding;
336
337
10.7k
    while (index < maximum) {
  Branch (337:12): [True: 10.6k, False: 91]
338
10.6k
        if (strchr((const char *) charset, source[index]) != NULL) {
  Branch (338:13): [True: 895, False: 9.78k]
339
895
            return source + index;
340
895
        }
341
342
9.78k
        if (source[index] < 0x80) {
  Branch (342:13): [True: 6.04k, False: 3.73k]
343
6.04k
            index++;
344
6.04k
        } else {
345
3.73k
            size_t width = encoding->char_width(source + index, (ptrdiff_t) (maximum - index));
346
3.73k
            if (validate) 
pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source - parser->start), (uint32_t) width)1.79k
;
  Branch (346:17): [True: 1.79k, False: 1.94k]
347
348
3.73k
            if (width > 0) {
  Branch (348:17): [True: 2.56k, False: 1.17k]
349
2.56k
                index += width;
350
2.56k
            } else 
if (1.17k
!validate1.17k
) {
  Branch (350:24): [True: 593, False: 579]
351
593
                index++;
352
593
            } else {
353
                // At this point we know we have an invalid multibyte character.
354
                // We'll walk forward as far as we can until we find the next
355
                // valid character so that we don't spam the user with a ton of
356
                // the same kind of error.
357
579
                const size_t start = index;
358
359
2.26k
                do {
360
2.26k
                    index++;
361
2.26k
                } while (index < maximum && 
encoding->char_width(source + index, (ptrdiff_t) (maximum - index)) == 02.20k
);
  Branch (361:26): [True: 2.20k, False: 65]
  Branch (361:45): [True: 1.68k, False: 514]
362
363
579
                pm_strpbrk_invalid_multibyte_character(parser, (uint32_t) ((source + start) - parser->start), (uint32_t) (index - start));
364
579
            }
365
3.73k
        }
366
9.78k
    }
367
368
91
    return NULL;
369
986
}
370
371
/**
372
 * This is the fast path that does not care about the encoding because we know
373
 * the encoding only supports single-byte characters.
374
 */
375
static PRISM_INLINE const uint8_t *
376
592
pm_strpbrk_single_byte(pm_parser_t *parser, const uint8_t *source, const uint8_t *charset, size_t index, size_t maximum, bool validate) {
377
592
    const pm_encoding_t *encoding = parser->encoding;
378
379
6.48k
    while (index < maximum) {
  Branch (379:12): [True: 6.45k, False: 25]
380
6.45k
        if (strchr((const char *) charset, source[index]) != NULL) {
  Branch (380:13): [True: 567, False: 5.88k]
381
567
            return source + index;
382
567
        }
383
384
5.88k
        if (source[index] < 0x80 || 
!validate2.14k
) {
  Branch (384:13): [True: 3.74k, False: 2.14k]
  Branch (384:37): [True: 801, False: 1.33k]
385
4.54k
            index++;
386
4.54k
        } else {
387
1.33k
            size_t width = encoding->char_width(source + index, (ptrdiff_t) (maximum - index));
388
1.33k
            pm_strpbrk_explicit_encoding_set(parser, (uint32_t) (source - parser->start), (uint32_t) width);
389
390
1.33k
            if (width > 0) {
  Branch (390:17): [True: 1.20k, False: 132]
391
1.20k
                index += width;
392
1.20k
            } else {
393
                // At this point we know we have an invalid multibyte character.
394
                // We'll walk forward as far as we can until we find the next
395
                // valid character so that we don't spam the user with a ton of
396
                // the same kind of error.
397
132
                const size_t start = index;
398
399
407
                do {
400
407
                    index++;
401
407
                } while (index < maximum && 
encoding->char_width(source + index, (ptrdiff_t) (maximum - index)) == 0404
);
  Branch (401:26): [True: 404, False: 3]
  Branch (401:45): [True: 275, False: 129]
402
403
132
                pm_strpbrk_invalid_multibyte_character(parser, (uint32_t) ((source + start) - parser->start), (uint32_t) (index - start));
404
132
            }
405
1.33k
        }
406
5.88k
    }
407
408
25
    return NULL;
409
592
}
410
411
/**
412
 * Here we have rolled our own version of strpbrk. The standard library strpbrk
413
 * has undefined behavior when the source string is not null-terminated. We want
414
 * to support strings that are not null-terminated because pm_parse does not
415
 * have the contract that the string is null-terminated. (This is desirable
416
 * because it means the extension can call pm_parse with the result of a call to
417
 * mmap).
418
 *
419
 * The standard library strpbrk also does not support passing a maximum length
420
 * to search. We want to support this for the reason mentioned above, but we
421
 * also don't want it to stop on null bytes. Ruby actually allows null bytes
422
 * within strings, comments, regular expressions, etc. So we need to be able to
423
 * skip past them.
424
 *
425
 * Finally, we want to support encodings wherein the charset could contain
426
 * characters that are trailing bytes of multi-byte characters. For example, in
427
 * Shift_JIS, the backslash character can be a trailing byte. In that case we
428
 * need to take a slower path and iterate one multi-byte character at a time.
429
 */
430
const uint8_t *
431
191k
pm_strpbrk(pm_parser_t *parser, const uint8_t *source, const uint8_t *charset, ptrdiff_t length, bool validate) {
432
191k
    if (length <= 0) 
return 2.12k
NULL2.12k
;
  Branch (432:9): [True: 2.12k, False: 189k]
433
434
189k
    size_t maximum = (size_t) length;
435
189k
    size_t index = 0;
436
189k
    if (scan_strpbrk_ascii(parser, source, maximum, charset, &index)) 
return source + index182k
;
  Branch (436:9): [True: 182k, False: 6.94k]
437
438
6.94k
    if (!parser->encoding_changed) {
  Branch (438:9): [True: 5.29k, False: 1.64k]
439
5.29k
        return pm_strpbrk_utf8(parser, source, charset, index, maximum, validate);
440
5.29k
    } else 
if (1.64k
parser->encoding == 1.64k
PM_ENCODING_ASCII_8BIT_ENTRY1.64k
) {
  Branch (440:16): [True: 63, False: 1.57k]
441
63
        return pm_strpbrk_ascii_8bit(parser, source, charset, index, maximum, validate);
442
1.57k
    } else if (parser->encoding->multibyte) {
  Branch (442:16): [True: 986, False: 592]
443
986
        return pm_strpbrk_multi_byte(parser, source, charset, index, maximum, validate);
444
986
    } else {
445
592
        return pm_strpbrk_single_byte(parser, source, charset, index, maximum, validate);
446
592
    }
447
6.94k
}