Ruby 4.1.0dev (2026-12-01 revision 79c2996ab7df465f236529156e07834647308733)
re.c (79c2996ab7df465f236529156e07834647308733)
1/**********************************************************************
2
3 re.c -
4
5 $Author$
6 created at: Mon Aug 9 18:24:49 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <ctype.h>
15
16#include "encindex.h"
17#include "hrtime.h"
18#include "internal.h"
19#include "internal/bignum.h"
20#include "internal/encoding.h"
21#include "internal/error.h"
22#include "internal/gc.h"
23#include "internal/hash.h"
24#include "internal/imemo.h"
25#include "internal/re.h"
26#include "internal/string.h"
27#include "internal/object.h"
28#include "internal/ractor.h"
29#include "internal/variable.h"
30#include "regint.h"
31#include "ruby/atomic.h"
32#include "ruby/encoding.h"
33#include "ruby/re.h"
34#include "ruby/util.h"
35#include "ractor_core.h"
36
38 struct RRegexp re;
39 struct re_pattern_buffer pattern; /* a.k.a. OnigRegexType, defined in onigmo.h */
40};
41
42/* Flags of RRegexp
43 *
44 * 4: KCODE_FIXED
45 * The regexp has "fixed encoding", meaning it can't be match against any ASCII-compatible string.
46 * 5: RREGEXP_INITIALIZED
47 * The regexp has been fully initialized and can be used.
48 * 6: REG_ENCODING_NONE
49 * The regexp has no encoding. Means the `n` modifier was used.
50 * 10-16: ENCODING
51 * Stores the encoding of the regexp.
52 */
53
54#define KCODE_FIXED FL_USER4
55#define REG_ENCODING_NONE FL_USER6
56
57/* Flags of RMatch
58 *
59 * 0: MATCH_BUSY
60 * The match is currently in use or may have escaped and can no longer be recycled.
61 * 1: RMATCH_ONIG
62 * TBD.
63 */
64
65#define MATCH_BUSY FL_USER0
66
67VALUE rb_eRegexpError, rb_eRegexpTimeoutError;
68
69typedef char onig_errmsg_buffer[ONIG_MAX_ERROR_MESSAGE_LEN];
70#define errcpy(err, msg) strlcpy((err), (msg), ONIG_MAX_ERROR_MESSAGE_LEN)
71
72#if 'a' == 97 /* it's ascii */
73static const char casetable[] = {
74 '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
75 '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
76 '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
77 '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
78 /* ' ' '!' '"' '#' '$' '%' '&' ''' */
79 '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
80 /* '(' ')' '*' '+' ',' '-' '.' '/' */
81 '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
82 /* '0' '1' '2' '3' '4' '5' '6' '7' */
83 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
84 /* '8' '9' ':' ';' '<' '=' '>' '?' */
85 '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
86 /* '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' */
87 '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
88 /* 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' */
89 '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
90 /* 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' */
91 '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
92 /* 'X' 'Y' 'Z' '[' '\' ']' '^' '_' */
93 '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
94 /* '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' */
95 '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
96 /* 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' */
97 '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
98 /* 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' */
99 '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
100 /* 'x' 'y' 'z' '{' '|' '}' '~' */
101 '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
102 '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
103 '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
104 '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
105 '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
106 '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
107 '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
108 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
109 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
110 '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
111 '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
112 '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
113 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
114 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
115 '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
116 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
117 '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
118};
119#else
120# error >>> "You lose. You will need a translation table for your character set." <<<
121#endif
122
123// The process-global timeout for regexp matching
124rb_hrtime_t rb_reg_match_time_limit = 0;
125
126int
127rb_memcicmp(const void *x, const void *y, rb_len_t len)
128{
129 const unsigned char *p1 = x, *p2 = y;
130 int tmp;
131
132 while (len--) {
133 if ((tmp = casetable[(unsigned)*p1++] - casetable[(unsigned)*p2++]))
134 return tmp;
135 }
136 return 0;
137}
138
139#if defined(HAVE_MEMMEM) && !defined(__APPLE__)
140static inline rb_len_t
141rb_memsearch_ss(const unsigned char *xs, rb_len_t m, const unsigned char *ys, rb_len_t n)
142{
143 const unsigned char *y;
144
145 if ((y = memmem(ys, n, xs, m)) != NULL)
146 return y - ys;
147 else
148 return -1;
149}
150#else
151static inline rb_len_t
152rb_memsearch_ss(const unsigned char *xs, rb_len_t m, const unsigned char *ys, rb_len_t n)
153{
154 const unsigned char *x = xs, *xe = xs + m;
155 const unsigned char *y = ys, *ye = ys + n;
156#define VALUE_MAX ((VALUE)~(VALUE)0)
157 VALUE hx, hy, mask = VALUE_MAX >> ((SIZEOF_VALUE - m) * CHAR_BIT);
158
159 if (m > SIZEOF_VALUE)
160 rb_bug("!!too long pattern string!!");
161
162 if (!(y = memchr(y, *x, n - m + 1)))
163 return -1;
164
165 /* Prepare hash value */
166 for (hx = *x++, hy = *y++; x < xe; ++x, ++y) {
167 hx <<= CHAR_BIT;
168 hy <<= CHAR_BIT;
169 hx |= *x;
170 hy |= *y;
171 }
172 /* Searching */
173 while (hx != hy) {
174 if (y == ye)
175 return -1;
176 hy <<= CHAR_BIT;
177 hy |= *y;
178 hy &= mask;
179 y++;
180 }
181 return y - ys - m;
182}
183#endif
184
185static inline rb_len_t
186rb_memsearch_qs(const unsigned char *xs, rb_len_t m, const unsigned char *ys, rb_len_t n)
187{
188 const unsigned char *x = xs, *xe = xs + m;
189 const unsigned char *y = ys;
190 VALUE i, qstable[256];
191
192 /* Preprocessing */
193 for (i = 0; i < 256; ++i)
194 qstable[i] = m + 1;
195 for (; x < xe; ++x)
196 qstable[*x] = xe - x;
197 /* Searching */
198 for (; y + m <= ys + n; y += *(qstable + y[m])) {
199 if (*xs == *y && memcmp(xs, y, m) == 0)
200 return y - ys;
201 }
202 return -1;
203}
204
205static inline unsigned int
206rb_memsearch_qs_utf8_hash(const unsigned char *x, const unsigned char *e)
207{
208 register const unsigned int mix = 8353;
209 register unsigned int h = *x;
210 if (h < 0xC0) {
211 return h + 256;
212 }
213 else if (e - x < (h < 0xE0 ? 2 : h < 0xF0 ? 3 : 4)) {
214 return h + 256;
215 }
216 else if (h < 0xE0) {
217 h *= mix;
218 h += x[1];
219 }
220 else if (h < 0xF0) {
221 h *= mix;
222 h += x[1];
223 h *= mix;
224 h += x[2];
225 }
226 else if (h < 0xF5) {
227 h *= mix;
228 h += x[1];
229 h *= mix;
230 h += x[2];
231 h *= mix;
232 h += x[3];
233 }
234 else {
235 return h + 256;
236 }
237 return (unsigned char)h;
238}
239
240static inline rb_len_t
241rb_memsearch_qs_utf8(const unsigned char *xs, rb_len_t m, const unsigned char *ys, rb_len_t n)
242{
243 const unsigned char *x = xs, *xe = xs + m;
244 const unsigned char *y = ys;
245 VALUE i, qstable[512];
246
247 /* Preprocessing */
248 for (i = 0; i < 512; ++i) {
249 qstable[i] = m + 1;
250 }
251 for (; x < xe; ++x) {
252 qstable[rb_memsearch_qs_utf8_hash(x, xe)] = xe - x;
253 }
254 /* Searching */
255 for (; y + m <= ys + n; y += qstable[rb_memsearch_qs_utf8_hash(y+m, ys+n)]) {
256 if (*xs == *y && memcmp(xs, y, m) == 0)
257 return y - ys;
258 }
259 return -1;
260}
261
262static inline rb_len_t
263rb_memsearch_with_char_size(const unsigned char *xs, rb_len_t m, const unsigned char *ys, rb_len_t n, int char_size)
264{
265 const unsigned char *x = xs, x0 = *xs, *y = ys;
266
267 for (n -= m; n >= 0; n -= char_size, y += char_size) {
268 if (x0 == *y && memcmp(x+1, y+1, m-1) == 0)
269 return y - ys;
270 }
271 return -1;
272}
273
274static inline rb_len_t
275rb_memsearch_wchar(const unsigned char *xs, rb_len_t m, const unsigned char *ys, rb_len_t n)
276{
277 return rb_memsearch_with_char_size(xs, m, ys, n, 2);
278}
279
280static inline rb_len_t
281rb_memsearch_qchar(const unsigned char *xs, rb_len_t m, const unsigned char *ys, rb_len_t n)
282{
283 return rb_memsearch_with_char_size(xs, m, ys, n, 4);
284}
285
287rb_memsearch(const void *x0, rb_len_t m, const void *y0, rb_len_t n, rb_encoding *enc)
288{
289 const unsigned char *x = x0, *y = y0;
290
291 if (m > n) return -1;
292 else if (m == n) {
293 return memcmp(x0, y0, m) == 0 ? 0 : -1;
294 }
295 else if (m < 1) {
296 return 0;
297 }
298 else if (m == 1) {
299 const unsigned char *ys = memchr(y, *x, n);
300
301 if (ys)
302 return ys - y;
303 else
304 return -1;
305 }
306 else if (LIKELY(rb_enc_mbminlen(enc) == 1)) {
307 if (m <= SIZEOF_VALUE) {
308 return rb_memsearch_ss(x0, m, y0, n);
309 }
310 else if (enc == rb_utf8_encoding()){
311 return rb_memsearch_qs_utf8(x0, m, y0, n);
312 }
313 }
314 else if (LIKELY(rb_enc_mbminlen(enc) == 2)) {
315 return rb_memsearch_wchar(x0, m, y0, n);
316 }
317 else if (LIKELY(rb_enc_mbminlen(enc) == 4)) {
318 return rb_memsearch_qchar(x0, m, y0, n);
319 }
320 return rb_memsearch_qs(x0, m, y0, n);
321}
322
323static int
324char_to_option(int c)
325{
326 int val;
327
328 switch (c) {
329 case 'i':
330 val = ONIG_OPTION_IGNORECASE;
331 break;
332 case 'x':
333 val = ONIG_OPTION_EXTEND;
334 break;
335 case 'm':
336 val = ONIG_OPTION_MULTILINE;
337 break;
338 default:
339 val = 0;
340 break;
341 }
342 return val;
343}
344
345enum { OPTBUF_SIZE = 4 };
346
347static char *
348option_to_str(char str[OPTBUF_SIZE], int options)
349{
350 char *p = str;
351 if (options & ONIG_OPTION_MULTILINE) *p++ = 'm';
352 if (options & ONIG_OPTION_IGNORECASE) *p++ = 'i';
353 if (options & ONIG_OPTION_EXTEND) *p++ = 'x';
354 *p = 0;
355 return str;
356}
357
358extern int
359rb_char_to_option_kcode(int c, int *option, int *kcode)
360{
361 *option = 0;
362
363 switch (c) {
364 case 'n':
365 *kcode = rb_ascii8bit_encindex();
366 return (*option = ARG_ENCODING_NONE);
367 case 'e':
368 *kcode = ENCINDEX_EUC_JP;
369 break;
370 case 's':
371 *kcode = ENCINDEX_Windows_31J;
372 break;
373 case 'u':
374 *kcode = rb_utf8_encindex();
375 break;
376 default:
377 *kcode = -1;
378 return (*option = char_to_option(c));
379 }
380 *option = ARG_ENCODING_FIXED;
381 return 1;
382}
383
384static bool
385reg_initialized_p(VALUE re)
386{
387 return FL_TEST_RAW(re, RREGEXP_INITIALIZED) && RREGEXP_SRC(re) && RREGEXP_SRC_PTR(re);
388}
389
390static void
391rb_reg_check(VALUE re)
392{
393 if (!reg_initialized_p(re)) {
394 rb_raise(rb_eTypeError, "uninitialized Regexp");
395 }
396}
397
398static void
399rb_reg_expr_str(VALUE str, const char *s, rb_len_t len,
400 rb_encoding *enc, rb_encoding *resenc, int term)
401{
402 const char *p, *pend;
403 int cr = ENC_CODERANGE_UNKNOWN;
404 int need_escape = 0;
405 int c, clen;
406
407 p = s; pend = p + len;
408 rb_str_coderange_scan_restartable(p, pend, enc, &cr);
409 if (rb_enc_asciicompat(enc) && ENC_CODERANGE_CLEAN_P(cr)) {
410 while (p < pend) {
411 c = rb_enc_ascget(p, pend, &clen, enc);
412 if (c == -1) {
413 if (enc == resenc) {
414 p += mbclen(p, pend, enc);
415 }
416 else {
417 need_escape = 1;
418 break;
419 }
420 }
421 else if (c != term && rb_enc_isprint(c, enc)) {
422 p += clen;
423 }
424 else {
425 need_escape = 1;
426 break;
427 }
428 }
429 }
430 else {
431 need_escape = 1;
432 }
433
434 if (!need_escape) {
435 rb_str_buf_cat(str, s, len);
436 }
437 else {
438 int unicode_p = rb_enc_unicode_p(enc);
439 p = s;
440 while (p<pend) {
441 c = rb_enc_ascget(p, pend, &clen, enc);
442 if (c == '\\' && p+clen < pend) {
443 int n = clen + mbclen(p+clen, pend, enc);
444 rb_str_buf_cat(str, p, n);
445 p += n;
446 continue;
447 }
448 else if (c == -1) {
449 clen = rb_enc_precise_mbclen(p, pend, enc);
450 if (!MBCLEN_CHARFOUND_P(clen)) {
451 c = (unsigned char)*p;
452 clen = 1;
453 goto hex;
454 }
455 if (resenc) {
456 unsigned int c = rb_enc_mbc_to_codepoint(p, pend, enc);
457 rb_str_buf_cat_escaped_char(str, c, unicode_p);
458 }
459 else {
460 clen = MBCLEN_CHARFOUND_LEN(clen);
461 rb_str_buf_cat(str, p, clen);
462 }
463 }
464 else if (c == term) {
465 char c = '\\';
466 rb_str_buf_cat(str, &c, 1);
467 rb_str_buf_cat(str, p, clen);
468 }
469 else if (rb_enc_isprint(c, enc)) {
470 rb_str_buf_cat(str, p, clen);
471 }
472 else if (!rb_enc_isspace(c, enc)) {
473 char b[8];
474
475 hex:
476 snprintf(b, sizeof(b), "\\x%02X", c);
477 rb_str_buf_cat(str, b, 4);
478 }
479 else {
480 rb_str_buf_cat(str, p, clen);
481 }
482 p += clen;
483 }
484 }
485}
486
487static VALUE
488rb_reg_desc(VALUE re)
489{
490 rb_encoding *enc = rb_enc_get(re);
491 VALUE str = rb_str_buf_new2("/");
492 rb_encoding *resenc = rb_default_internal_encoding();
493 if (resenc == NULL) resenc = rb_default_external_encoding();
494
495 if (re && rb_enc_asciicompat(enc)) {
496 rb_enc_copy(str, re);
497 }
498 else {
499 rb_enc_associate(str, rb_usascii_encoding());
500 }
501
502 VALUE src_str = RREGEXP_SRC(re);
503 rb_reg_expr_str(str, RSTRING_PTR(src_str), RSTRING_LEN(src_str), enc, resenc, '/');
504 RB_GC_GUARD(src_str);
505
506 rb_str_buf_cat2(str, "/");
507 if (re) {
508 char opts[OPTBUF_SIZE];
509 rb_reg_check(re);
510 if (*option_to_str(opts, RREGEXP_PTR(re)->options))
511 rb_str_buf_cat2(str, opts);
512 if (RBASIC(re)->flags & REG_ENCODING_NONE)
513 rb_str_buf_cat2(str, "n");
514 }
515 return str;
516}
517
518
519/*
520 * call-seq:
521 * source -> string
522 *
523 * Returns the original string of +self+:
524 *
525 * /ab+c/ix.source # => "ab+c"
526 *
527 * Regexp escape sequences are retained:
528 *
529 * /\x20\+/.source # => "\\x20\\+"
530 *
531 * Lexer escape characters are not retained:
532 *
533 * /\//.source # => "/"
534 *
535 */
536
537static VALUE
538rb_reg_source(VALUE re)
539{
540 VALUE str;
541
542 rb_reg_check(re);
543 str = rb_str_dup(RREGEXP_SRC(re));
544 return str;
545}
546
547/*
548 * call-seq:
549 * inspect -> string
550 *
551 * Returns a nicely-formatted string representation of +self+:
552 *
553 * /ab+c/ix.inspect # => "/ab+c/ix"
554 *
555 * Related: Regexp#to_s.
556 */
557
558static VALUE
559rb_reg_inspect(VALUE re)
560{
561 if (!reg_initialized_p(re)) {
562 return rb_any_to_s(re);
563 }
564 return rb_reg_desc(re);
565}
566
567static VALUE rb_reg_str_with_term(VALUE re, int term);
568
569/*
570 * call-seq:
571 * to_s -> string
572 *
573 * Returns a string showing the options and string of +self+:
574 *
575 * r0 = /ab+c/ix
576 * s0 = r0.to_s # => "(?ix-m:ab+c)"
577 *
578 * The returned string may be used as an argument to Regexp.new,
579 * or as interpolated text for a
580 * {Regexp interpolation}[rdoc-ref:Regexp@Interpolation+Mode]:
581 *
582 * r1 = Regexp.new(s0) # => /(?ix-m:ab+c)/
583 * r2 = /#{s0}/ # => /(?ix-m:ab+c)/
584 *
585 * Note that +r1+ and +r2+ are not equal to +r0+
586 * because their original strings are different:
587 *
588 * r0 == r1 # => false
589 * r0.source # => "ab+c"
590 * r1.source # => "(?ix-m:ab+c)"
591 *
592 * Related: Regexp#inspect.
593 *
594 */
595
596static VALUE
597rb_reg_to_s(VALUE re)
598{
599 return rb_reg_str_with_term(re, '/');
600}
601
602/*
603 * Onigmo must not be left by a non-local exit (an exception, a throw or
604 * Thread#kill): that leaks what it has allocated (the parse tree, the match
605 * stack, the match cache). While re.c runs Onigmo (between reg_onig_begin()
606 * and reg_onig_end()), what the interrupts raise in the matcher is caught and
607 * raised again after Onigmo has returned, and the warnings of the parser
608 * (Warning.warn may raise) are kept and emitted after the compilation. The
609 * other users of Onigmo (C extensions) and the platforms without thread-local
610 * variables get the former behavior.
611 */
612#ifdef ONIG_THREAD_LOCAL
613static ONIG_THREAD_LOCAL int reg_onig_depth;
614static ONIG_THREAD_LOCAL int reg_onig_interrupt_state;
615static ONIG_THREAD_LOCAL struct {
616 char *buf; /* the messages, each terminated by NUL */
617 size_t len, capa;
618 const char *sourcefile;
619 int sourceline;
620} reg_onig_warnings;
621#endif
622
623static inline void
624reg_onig_begin(void)
625{
626#ifdef ONIG_THREAD_LOCAL
627 reg_onig_depth++;
628#endif
629}
630
631static inline void
632reg_onig_end(void)
633{
634#ifdef ONIG_THREAD_LOCAL
635 reg_onig_depth--;
636#endif
637}
638
639static VALUE
640reg_check_ints_i(VALUE _)
641{
643 return Qnil;
644}
645
646/* Called periodically by the matcher (CHECK_INTERRUPT_IN_MATCH_AT). Returns
647 * nonzero when an interrupt raised; the matcher then frees what it holds and
648 * returns ONIGERR_INTERRUPTED, and reg_onig_raise_interrupt() raises again. */
649int
650rb_reg_check_ints(void)
651{
652#ifdef ONIG_THREAD_LOCAL
653 if (reg_onig_depth > 0) {
654 int depth = reg_onig_depth, state;
655
656 if (!RUBY_VM_INTERRUPTED_ANY(GET_EC())) return 0;
657 /* The interrupts may run Ruby code (e.g. a trap handler), which may
658 * use Onigmo in turn. */
659 reg_onig_depth = 0;
660 rb_protect(reg_check_ints_i, Qnil, &state);
661 reg_onig_depth = depth;
662 if (state) {
663 reg_onig_interrupt_state = state;
664 return 1;
665 }
666 return 0;
667 }
668#endif
670 return 0;
671}
672
673NORETURN(static void reg_onig_raise_interrupt(void));
674static void
675reg_onig_raise_interrupt(void)
676{
677#ifdef ONIG_THREAD_LOCAL
678 int state = reg_onig_interrupt_state;
679 reg_onig_interrupt_state = 0;
680 rb_jump_tag(state);
681#else
683#endif
684}
685
686static void
687reg_warn_now(const char *sourcefile, int sourceline, const char *msg)
688{
690 if (sourcefile == NULL)
691 rb_warn("%s", msg);
692 else
693 rb_compile_warn(sourcefile, sourceline, "%s", msg);
694}
695
696/* Called by the parser for each warning. */
697void
698rb_reg_warn(const char *sourcefile, int sourceline, const char *msg)
699{
700#ifdef ONIG_THREAD_LOCAL
701 if (reg_onig_depth > 0) {
702 size_t n = strlen(msg) + 1;
703
704 if (reg_onig_warnings.capa - reg_onig_warnings.len < n) {
705 size_t capa = reg_onig_warnings.capa * 2 + n;
706 /* not ruby_xrealloc(), which raises */
707 char *buf = realloc(reg_onig_warnings.buf, capa);
708 if (!buf) return;
709 reg_onig_warnings.buf = buf;
710 reg_onig_warnings.capa = capa;
711 }
712 memcpy(reg_onig_warnings.buf + reg_onig_warnings.len, msg, n);
713 reg_onig_warnings.len += n;
714 reg_onig_warnings.sourcefile = sourcefile;
715 reg_onig_warnings.sourceline = sourceline;
716 return;
717 }
718#endif
719 reg_warn_now(sourcefile, sourceline, msg);
720}
721
722/* Emits the warnings kept while compiling. */
723static void
724reg_warn_kept(void)
725{
726#ifdef ONIG_THREAD_LOCAL
727 if (reg_onig_warnings.len == 0) return;
728
729 const char *sourcefile = reg_onig_warnings.sourcefile;
730 int sourceline = reg_onig_warnings.sourceline;
731 VALUE msgs = rb_ary_new();
732 const char *p = reg_onig_warnings.buf, *e = p + reg_onig_warnings.len;
733
734 for (; p < e; p += strlen(p) + 1) {
736 }
737 free(reg_onig_warnings.buf);
738 reg_onig_warnings.buf = NULL;
739 reg_onig_warnings.len = reg_onig_warnings.capa = 0;
740
741 for (long i = 0; i < RARRAY_LEN(msgs); i++) {
742 reg_warn_now(sourcefile, sourceline, RSTRING_PTR(RARRAY_AREF(msgs, i)));
743 }
744 RB_GC_GUARD(msgs);
745#endif
746}
747
748static void
749reg_warn_discard(void)
750{
751#ifdef ONIG_THREAD_LOCAL
752 free(reg_onig_warnings.buf);
753 reg_onig_warnings.buf = NULL;
754 reg_onig_warnings.len = reg_onig_warnings.capa = 0;
755#endif
756}
757
758static VALUE
759reg_warn_kept_i(VALUE _)
760{
761 reg_warn_kept();
762 return Qnil;
763}
764
765static VALUE
766rb_reg_preprocess(const char *p, const char *end, rb_encoding *enc,
767 rb_encoding **fixed_enc, onig_errmsg_buffer err, int options);
768
769static VALUE
770rb_reg_str_with_term(VALUE re, int term)
771{
772 int options, opt;
773 const int embeddable = ONIG_OPTION_MULTILINE|ONIG_OPTION_IGNORECASE|ONIG_OPTION_EXTEND;
774 VALUE str = rb_str_buf_new2("(?");
775 char optbuf[OPTBUF_SIZE + 1]; /* for '-' */
776 rb_encoding *enc = rb_enc_get(re);
777
778 rb_reg_check(re);
779
780 rb_enc_copy(str, re);
781 options = RREGEXP_PTR(re)->options;
782 VALUE src_str = RREGEXP_SRC(re);
783 const UChar *ptr = (UChar *)RSTRING_PTR(src_str);
784 rb_len_t len = RSTRING_LEN(src_str);
785 again:
786 if (len >= 4 && ptr[0] == '(' && ptr[1] == '?' && rb_enc_asciicompat(enc)) {
787 int err = 1;
788 ptr += 2;
789 if ((len -= 2) > 0) {
790 do {
791 opt = char_to_option((int )*ptr);
792 if (opt != 0) {
793 options |= opt;
794 }
795 else {
796 break;
797 }
798 ++ptr;
799 } while (--len > 0);
800 }
801 if (len > 1 && *ptr == '-') {
802 ++ptr;
803 --len;
804 do {
805 opt = char_to_option((int )*ptr);
806 if (opt != 0) {
807 options &= ~opt;
808 }
809 else {
810 break;
811 }
812 ++ptr;
813 } while (--len > 0);
814 }
815 if (*ptr == ')') {
816 --len;
817 ++ptr;
818 goto again;
819 }
820 if (*ptr == ':' && ptr[len-1] == ')') {
821 Regexp *rp;
822 VALUE verbose = ruby_verbose;
823 rb_encoding *fixed_enc = 0;
824 onig_errmsg_buffer errmsg = "";
825 VALUE unescaped;
826
827 ++ptr;
828 len -= 2;
829 unescaped = rb_reg_preprocess((const char *)ptr, (const char *)ptr + len,
830 enc, &fixed_enc, errmsg, options);
831 if (!NIL_P(unescaped) && (!fixed_enc || fixed_enc == enc)) {
833 reg_onig_begin();
834 err = onig_new(&rp, (UChar *)RSTRING_PTR(unescaped),
835 (UChar *)RSTRING_END(unescaped), options,
836 enc, OnigDefaultSyntax, NULL);
837 reg_onig_end();
838 onig_free(rp);
839 ruby_verbose = verbose;
840 reg_warn_discard();
841 RB_GC_GUARD(unescaped);
842 }
843 }
844 if (err) {
845 options = RREGEXP_PTR(re)->options;
846 ptr = (UChar*)RREGEXP_SRC_PTR(re);
847 len = RREGEXP_SRC_LEN(re);
848 }
849 }
850
851 if (*option_to_str(optbuf, options)) rb_str_buf_cat2(str, optbuf);
852
853 if ((options & embeddable) != embeddable) {
854 optbuf[0] = '-';
855 option_to_str(optbuf + 1, ~options);
856 rb_str_buf_cat2(str, optbuf);
857 }
858
859 rb_str_buf_cat2(str, ":");
860 if (rb_enc_asciicompat(enc)) {
861 rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term);
862 rb_str_buf_cat2(str, ")");
863 }
864 else {
865 const char *s, *e;
866 char *paren;
867 ptrdiff_t n;
868 rb_str_buf_cat2(str, ")");
869 rb_enc_associate(str, rb_usascii_encoding());
870 str = rb_str_encode(str, rb_enc_from_encoding(enc), 0, Qnil);
871
872 /* backup encoded ")" to paren */
873 s = RSTRING_PTR(str);
874 e = RSTRING_END(str);
875 s = rb_enc_left_char_head(s, e-1, e, enc);
876 n = e - s;
877 paren = ALLOCA_N(char, n);
878 memcpy(paren, s, n);
879 rb_str_resize(str, RSTRING_LEN(str) - n);
880
881 rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term);
882 rb_str_buf_cat(str, paren, n);
883 }
884 rb_enc_copy(str, re);
885
886 RB_GC_GUARD(src_str);
887
888 return str;
889}
890
891NORETURN(static void rb_reg_raise(const char *err, VALUE re));
892
893static void
894rb_reg_raise(const char *err, VALUE re)
895{
896 VALUE desc = rb_reg_desc(re);
897
898 rb_raise(rb_eRegexpError, "%s: %"PRIsVALUE, err, desc);
899}
900
901static VALUE
902rb_enc_reg_error_desc(const char *s, rb_len_t len, rb_encoding *enc, int options, const char *err)
903{
904 char opts[OPTBUF_SIZE + 1]; /* for '/' */
905 VALUE desc = rb_str_buf_new2(err);
906 rb_encoding *resenc = rb_default_internal_encoding();
907 if (resenc == NULL) resenc = rb_default_external_encoding();
908
909 rb_enc_associate(desc, enc);
910 rb_str_buf_cat2(desc, ": /");
911 rb_reg_expr_str(desc, s, len, enc, resenc, '/');
912 opts[0] = '/';
913 option_to_str(opts + 1, options);
914 rb_str_buf_cat2(desc, opts);
915 return rb_exc_new3(rb_eRegexpError, desc);
916}
917
918NORETURN(static void rb_enc_reg_raise(const char *s, rb_len_t len, rb_encoding *enc, int options, const char *err));
919
920static void
921rb_enc_reg_raise(const char *s, rb_len_t len, rb_encoding *enc, int options, const char *err)
922{
923 rb_exc_raise(rb_enc_reg_error_desc(s, len, enc, options, err));
924}
925
926static VALUE
927rb_reg_error_desc(VALUE str, int options, const char *err)
928{
929 return rb_enc_reg_error_desc(RSTRING_PTR(str), RSTRING_LEN(str),
930 rb_enc_get(str), options, err);
931}
932
933NORETURN(static void rb_reg_raise_str(VALUE str, int options, const char *err));
934
935static void
936rb_reg_raise_str(VALUE str, int options, const char *err)
937{
938 rb_exc_raise(rb_reg_error_desc(str, options, err));
939}
940
941
942/*
943 * call-seq:
944 * casefold?-> true or false
945 *
946 * Returns +true+ if the case-insensitivity flag in +self+ is set,
947 * +false+ otherwise:
948 *
949 * /a/.casefold? # => false
950 * /a/i.casefold? # => true
951 * /(?i:a)/.casefold? # => false
952 *
953 */
954
955static VALUE
956rb_reg_casefold_p(VALUE re)
957{
958 rb_reg_check(re);
959 return RBOOL(RREGEXP_PTR(re)->options & ONIG_OPTION_IGNORECASE);
960}
961
962
963/*
964 * call-seq:
965 * options -> integer
966 *
967 * Returns an integer whose bits show the options set in +self+.
968 *
969 * The option bits are:
970 *
971 * Regexp::IGNORECASE # => 1
972 * Regexp::EXTENDED # => 2
973 * Regexp::MULTILINE # => 4
974 *
975 * Examples:
976 *
977 * /foo/.options # => 0
978 * /foo/i.options # => 1
979 * /foo/x.options # => 2
980 * /foo/m.options # => 4
981 * /foo/mix.options # => 7
982 *
983 * Note that additional bits may be set in the returned integer;
984 * these are maintained internally in +self+, are ignored if passed
985 * to Regexp.new, and may be ignored by the caller:
986 *
987 * Returns the set of bits corresponding to the options used when
988 * creating this regexp (see Regexp::new for details). Note that
989 * additional bits may be set in the returned options: these are used
990 * internally by the regular expression code. These extra bits are
991 * ignored if the options are passed to Regexp::new:
992 *
993 * r = /\xa1\xa2/e # => /\xa1\xa2/
994 * r.source # => "\\xa1\\xa2"
995 * r.options # => 16
996 * Regexp.new(r.source, r.options) # => /\xa1\xa2/
997 *
998 */
999
1000static VALUE
1001rb_reg_options_m(VALUE re)
1002{
1003 int options = rb_reg_options(re);
1004 return INT2NUM(options);
1005}
1006
1007static int
1008reg_names_iter(const OnigUChar *name, const OnigUChar *name_end,
1009 int back_num, int *back_refs, OnigRegex regex, void *arg)
1010{
1011 VALUE ary = (VALUE)arg;
1012 rb_ary_push(ary, rb_enc_str_new((const char *)name, name_end-name, regex->enc));
1013 return 0;
1014}
1015
1016/*
1017 * call-seq:
1018 * names -> array_of_names
1019 *
1020 * Returns an array of names of captures
1021 * (see {Named Captures}[rdoc-ref:Regexp@Named+Captures]):
1022 *
1023 * /(?<foo>.)(?<bar>.)(?<baz>.)/.names # => ["foo", "bar", "baz"]
1024 * /(?<foo>.)(?<foo>.)/.names # => ["foo"]
1025 * /(.)(.)/.names # => []
1026 *
1027 */
1028
1029static VALUE
1030rb_reg_names(VALUE re)
1031{
1032 VALUE ary;
1033 rb_reg_check(re);
1034 ary = rb_ary_new_capa(onig_number_of_names(RREGEXP_PTR(re)));
1035 onig_foreach_name(RREGEXP_PTR(re), reg_names_iter, (void*)ary);
1036 return ary;
1037}
1038
1039static int
1040reg_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end,
1041 int back_num, int *back_refs, OnigRegex regex, void *arg)
1042{
1043 VALUE hash = (VALUE)arg;
1044 VALUE ary = rb_ary_new2(back_num);
1045 int i;
1046
1047 for (i = 0; i < back_num; i++)
1048 rb_ary_store(ary, i, INT2NUM(back_refs[i]));
1049
1050 rb_hash_aset(hash, rb_str_new((const char*)name, name_end-name),ary);
1051
1052 return 0;
1053}
1054
1055/*
1056 * call-seq:
1057 * named_captures -> hash
1058 *
1059 * Returns a hash representing named captures of +self+
1060 * (see {Named Captures}[rdoc-ref:Regexp@Named+Captures]):
1061 *
1062 * - Each key is the name of a named capture.
1063 * - Each value is an array of integer indexes for that named capture.
1064 *
1065 * Examples:
1066 *
1067 * /(?<foo>.)(?<bar>.)/.named_captures # => {"foo"=>[1], "bar"=>[2]}
1068 * /(?<foo>.)(?<foo>.)/.named_captures # => {"foo"=>[1, 2]}
1069 * /(.)(.)/.named_captures # => {}
1070 *
1071 */
1072
1073static VALUE
1074rb_reg_named_captures(VALUE re)
1075{
1076 regex_t *reg = (rb_reg_check(re), RREGEXP_PTR(re));
1077 VALUE hash = rb_hash_new_capa(onig_number_of_names(reg));
1078 onig_foreach_name(reg, reg_named_captures_iter, (void*)hash);
1079 return hash;
1080}
1081
1082static int
1083onig_new_with_source(regex_t* reg, const UChar* pattern, const UChar* pattern_end,
1084 OnigOptionType option, OnigEncoding enc, const OnigSyntaxType* syntax,
1085 OnigErrorInfo* einfo, const char *sourcefile, int sourceline)
1086{
1087 int r;
1088
1089 if (IS_NULL(reg)) return ONIGERR_MEMORY;
1090
1091 r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
1092 if (r) goto err;
1093
1094 r = onig_compile_ruby(reg, pattern, pattern_end, einfo, sourcefile, sourceline);
1095 if (r) {
1096 err:
1097 onig_free_body(reg);
1098 }
1099 return r;
1100}
1101
1102static bool
1103make_regexp(Regexp *rp, const char *s, rb_len_t len, rb_encoding *enc, int flags, onig_errmsg_buffer err,
1104 const char *sourcefile, int sourceline)
1105{
1106 int r;
1107 OnigErrorInfo einfo;
1108
1109 /* Handle escaped characters first. */
1110
1111 /* Build a copy of the string (in dest) with the
1112 escaped characters translated, and generate the regex
1113 from that.
1114 */
1115
1116 /* the caller emits the warnings (reg_warn_kept()) */
1117 reg_onig_begin();
1118 r = onig_new_with_source(rp, (UChar*)s, (UChar*)(s + len), flags,
1119 enc, OnigDefaultSyntax, &einfo, sourcefile, sourceline);
1120 reg_onig_end();
1121 if (r) {
1122 onig_error_code_to_str((UChar*)err, r, &einfo);
1123 return false;
1124 }
1125 return true;
1126}
1127
1128
1129/*
1130 * Document-class: MatchData
1131 *
1132 * :markup: markdown
1133 *
1134 * Ruby [matcher methods][matcher methods] create \MatchData objects.
1135 *
1136 * A \MatchData object contains the detailed result of a match, including:
1137 *
1138 * - The target string used for the match.
1139 * - The Regexp used for the match.
1140 * - The matched substring.
1141 * - The substring preceding the matched substring.
1142 * - The substring following the matched substring.
1143 * - Captured substrings.
1144 *
1145 * ## In Brief
1146 *
1147 * ```ruby
1148 * # Basics.
1149 * s = 'https://docs.ruby-lang.org/en/2.5.0/MatchData.html'
1150 * m = s.match(/(\d\.?)+/) # => #<MatchData "2.5.0" 1:"0">
1151 * m.string # => "https://docs.ruby-lang.org/en/2.5.0/MatchData.html"
1152 * m.regexp # => /(\d\.?)+/
1153 * m[0] # => "2.5.0" # Matched substring.
1154 * m.pre_match # => "https://docs.ruby-lang.org/en/"
1155 * m.post_match # => "/MatchData.html"
1156 *
1157 * # Unnamed (numbered) captures.
1158 * m = "2025-12-25".match(/(\d{4})-(\d{2})-(\d{2})/)
1159 * # => #<MatchData "2025-12-25" 1:"2025" 2:"12" 3:"25">
1160 * m[0] # => "2025-12-25" # Entire matched substring.
1161 * m[1] # => "2025" # First captured substring.
1162 * m[2] # => "12" # Second captured substring.
1163 * m[3] # => "25" # Third captured substring.
1164 * m[4] # => nil # No more captured substrings.
1165 *
1166 * # Named captures.
1167 * m = "2025-12-25".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
1168 * m[:year] # "2025"
1169 * m[:month] # "12"
1170 * m[:day] # "25"
1171 * # Also available by numbers.
1172 * m[0] # => "2025-12-25"
1173 * m[1] # => "2025"
1174 * m[:nosuch] # Raises IndexError: undefined group name reference: nosuch.
1175 * ```
1176 *
1177 * ## Matcher Methods
1178 *
1179 * Each of these methods creates a \MatchData object,
1180 * updates the [matcher global variables][matcher global variables],
1181 * and returns the \MatchData object:
1182 *
1183 * - Regexp#match.
1184 * - String#match.
1185 * - Symbol#match.
1186 *
1187 * Each of these methods creates a \MatchData object,
1188 * updates the [matcher global variables][matcher global variables],
1189 * but _does not_ return the \MatchData object;
1190 * the \MatchData object is available in global variable `$~`:
1191 *
1192 * - Regexp#=~
1193 * - String#=~
1194 * - String#gsub
1195 * - String#gsub!
1196 * - String#scan
1197 * - String#sub
1198 * - String#sub!
1199 * - Symbol#=~
1200 *
1201 * Each of these methods, when called with a Regexp argument,
1202 * creates a \MatchData object,
1203 * updates the [matcher global variables][matcher global variables],
1204 * but _does not_ return the \MatchData object;
1205 * the \MatchData object is available in global variable `$~`:
1206 *
1207 * - String#index
1208 * - String#partition
1209 * - String#rindex
1210 * - String#rpartition
1211 * - String#slice
1212 * - String#slice!
1213 * - String#split
1214 *
1215 * ## Match-Related Methods
1216 *
1217 * Each of these predicate methods performs a "fast match,"
1218 * returning whether a match was found,
1219 * but _not_ creating a \MatchData object,
1220 * and _not_ setting [matcher global variables][matcher global variables]:
1221 *
1222 * - Regexp#match?
1223 * - String#match?
1224 * - Symbol#match?
1225 *
1226 * This method return the \MatchData object resulting from the most recent match:
1227 *
1228 * - Regexp::last_match.
1229 *
1230 * [matcher methods]: rdoc-ref:MatchData@Matcher+Methods
1231 * [matcher global variables]: rdoc-ref:Regexp@Global+Variables
1232 *
1233 *
1234 * ## What's Here
1235 *
1236 * First, what's elsewhere. Class \MatchData:
1237 *
1238 * - Inherits from {class Object}[rdoc-ref:Object@Whats-Here].
1239 *
1240 * Here, class \MatchData provides methods that are useful for:
1241 *
1242 * ### General Methods
1243 *
1244 * - #== (aliased as #eql?): returns whether `self` and another object are equal.
1245 * - #hash: returns the integer hash value for `self`.
1246 * - #inspect: returns a string representation of `self`.
1247 * - #post_match: returns the substring that follows the matched string.
1248 * - #pre_match: returns the substring that precedes the matched string.
1249 * - #regexp: returns the Regexp used to produce `self`.
1250 * - #size (aliased as #length): returns the size of the array of matched substrings.
1251 * - #string: returns the string used to produce `self`.
1252 * - #to_a: returns the array of matched substrings.
1253 * - #to_s: returns a string representation of `self`.
1254 *
1255 * ### Capture Methods
1256 *
1257 * Each of these methods returns information about all captures:
1258 *
1259 * - #captures (aliased as #deconstruct): returns an array of the captured substrings.
1260 * - #named_captures: returns a hash of the named captures.
1261 * - #names: returns an array of the capture names.
1262 *
1263 * Each of these methods returns information about one capture,
1264 * which may be specified by its integer index or by its name (if it is a named capture):
1265 *
1266 * - #[]: returns a matched substring or an array of matched substrings
1267 * for the given arguments.
1268 * - #begin: returns the character offset of the beginning of the capture.
1269 * - #bytebegin: returns the byte offset of the beginning of the capture.
1270 * - #byteend: returns the byte offset of the end of the capture.
1271 * - #byteoffset: returns the byte offsets of the beginning and end of the capture.
1272 * - #deconstruct_keys: returns a hash of the names and values for the given names.
1273 * - #end: returns the character offset of the end of the capture.
1274 * - #integer_at: returns the value of the capture, converted to an integer.
1275 * - #match: returns the matched substring for the capture.
1276 * - #match_length: returns the length (in characters) of the matched substring for the capture.
1277 * - #offset: returns the begin and end offsets for the capture.
1278 * - #values_at: returns a matched substring or an array of matched substrings
1279 * for the given arguments.
1280 *
1281 */
1282
1284
1285static VALUE
1286match_alloc_n(VALUE klass, int num_regs)
1287{
1288 int capa = num_regs * 2;
1289 size_t alloc_size = offsetof(struct RMatch, as) + sizeof(OnigPosition) * capa;
1290 if (alloc_size < sizeof(struct RMatch)) {
1291 alloc_size = sizeof(struct RMatch);
1292 }
1293
1294 VALUE flags = T_MATCH;
1295 if (!rb_gc_size_allocatable_p(alloc_size)) {
1296 alloc_size = sizeof(struct RMatch);
1297 flags |= RMATCH_ONIG;
1298 capa = 0;
1299 }
1300
1301 NEWOBJ_OF(match, struct RMatch, klass, flags, alloc_size);
1302 memset(((char *)match) + sizeof(struct RBasic), 0, alloc_size - sizeof(struct RBasic));
1303 match->capa = capa;
1304 return (VALUE)match;
1305}
1306
1307static VALUE
1308match_alloc(VALUE klass)
1309{
1310 return match_alloc_n(klass, 0);
1311}
1312
1313int
1314rb_reg_region_copy(struct re_registers *to, const struct re_registers *from)
1315{
1316 onig_region_copy(to, (OnigRegion *)from);
1317 if (to->allocated) return 0;
1318 rb_gc();
1319 onig_region_copy(to, (OnigRegion *)from);
1320 if (to->allocated) return 0;
1321 return ONIGERR_MEMORY;
1322}
1323
1324static void
1325match_to_onig(VALUE match, int num_regs, const OnigPosition *src_beg, const OnigPosition *src_end)
1326{
1327 struct RMatch *rm = RMATCH(match);
1328 struct re_registers tmp = {0};
1329 if (onig_region_resize(&tmp, num_regs)) {
1330 rb_memerror();
1331 }
1332 memcpy(tmp.beg, src_beg, num_regs * sizeof(OnigPosition));
1333 memcpy(tmp.end, src_end, num_regs * sizeof(OnigPosition));
1334 rm->as.onig = tmp;
1335 FL_SET_RAW(match, RMATCH_ONIG);
1336}
1337
1338void
1339rb_match_ensure_onig(VALUE match)
1340{
1341 if (FL_TEST_RAW(match, RMATCH_ONIG)) return;
1342 struct RMatch *rm = RMATCH(match);
1343 int n = rm->num_regs;
1344 match_to_onig(match, n, &rm->as.embed[0], &rm->as.embed[n]);
1345}
1346
1347/* Replace `match`'s registers with a copy of (num_regs, beg, end). If the
1348 * data does not fit in the embed form, the match is evicted to onig form.
1349 * Raises on OOM. */
1350static void
1351match_set_regs(VALUE match, int num_regs, const OnigPosition *beg, const OnigPosition *end)
1352{
1353 struct RMatch *rm = RMATCH(match);
1354
1355 if (FL_TEST_RAW(match, RMATCH_ONIG)) {
1356 if (onig_region_resize(&rm->as.onig, num_regs)) {
1357 rb_memerror();
1358 }
1359 memcpy(rm->as.onig.beg, beg, num_regs * sizeof(OnigPosition));
1360 memcpy(rm->as.onig.end, end, num_regs * sizeof(OnigPosition));
1361 }
1362 else if (num_regs * 2 <= rm->capa) {
1363 memcpy(&rm->as.embed[0], beg, num_regs * sizeof(OnigPosition));
1364 memcpy(&rm->as.embed[num_regs], end, num_regs * sizeof(OnigPosition));
1365 }
1366 else {
1367 match_to_onig(match, num_regs, beg, end);
1368 }
1369 rm->num_regs = num_regs;
1370}
1371
1372static void
1373match_reuse(VALUE match)
1374{
1375 struct RMatch *rm = RMATCH(match);
1376 if (FL_TEST_RAW(match, RMATCH_ONIG)) {
1377 onig_region_free(&rm->as.onig, 0);
1378 memset(&rm->as.onig, 0, sizeof(rm->as.onig));
1379 FL_UNSET_RAW(match, RMATCH_ONIG);
1380 }
1381 if (rm->char_offset) {
1382 ruby_xfree(rm->char_offset);
1383 rm->char_offset = NULL;
1385 }
1386}
1387/* Helpers for carrying a MatchData to another objspace via Ractor#send(move:). The match's
1388 * registers are written out to an onig-independent blob so the original malloc'd area can be
1389 * freed, leaving an empty shell behind, and rebuilt from the blob on the receiving side. */
1390void *
1391rb_match_blob_dump(VALUE match, VALUE *regexp_out, VALUE *str_out, int *num_regs_out, bool release_source)
1392{
1393 struct RMatch *rm = RMATCH(match);
1394 int n = rm->num_regs;
1395 *regexp_out = rm->regexp;
1396 *str_out = rm->str;
1397 *num_regs_out = n;
1398
1399 OnigPosition *blob = ALLOC_N(OnigPosition, n ? 2 * n : 1);
1400 const OnigPosition *beg = RMATCH_BEG_PTR(match);
1401 const OnigPosition *end = RMATCH_END_PTR(match);
1402 for (int i = 0; i < n; i++) {
1403 blob[2 * i] = beg[i];
1404 blob[2 * i + 1] = end[i];
1405 }
1406
1407 /* A copy leaves the source usable; only a move takes its internals apart. */
1408 if (release_source) {
1409 match_reuse(match);
1410 }
1411 return blob;
1412}
1413
1414VALUE
1415rb_match_blob_alloc(VALUE klass, int num_regs)
1416{
1417 return match_alloc_n(klass, num_regs);
1418}
1419
1420void
1421rb_match_blob_load(VALUE match, VALUE regexp, VALUE str, int num_regs, const void *blob_)
1422{
1423 const OnigPosition *blob = blob_;
1424 struct RMatch *rm = RMATCH(match);
1425 RB_OBJ_WRITE(match, &rm->str, str);
1426 RB_OBJ_WRITE(match, &rm->regexp, regexp);
1427
1428 OnigPosition *beg = ALLOC_N(OnigPosition, num_regs ? num_regs : 1);
1429 OnigPosition *end = ALLOC_N(OnigPosition, num_regs ? num_regs : 1);
1430 for (int i = 0; i < num_regs; i++) {
1431 beg[i] = blob[2 * i];
1432 end[i] = blob[2 * i + 1];
1433 }
1434 match_set_regs(match, num_regs, beg, end);
1435 ruby_xfree(beg);
1436 ruby_xfree(end);
1437}
1438
1439void
1440rb_match_blob_free(void *blob)
1441{
1442 ruby_xfree(blob);
1443}
1444
1445typedef struct {
1446 rb_len_t byte_pos;
1447 rb_len_t char_pos;
1448} pair_t;
1449
1450static int
1451pair_byte_cmp(const void *pair1, const void *pair2)
1452{
1453 rb_len_t diff = ((pair_t*)pair1)->byte_pos - ((pair_t*)pair2)->byte_pos;
1454#if SIZEOF_RB_LEN_T > SIZEOF_INT
1455 return diff ? diff > 0 ? 1 : -1 : 0;
1456#else
1457 return (int)diff;
1458#endif
1459}
1460
1461/* A shareable MatchData is read by several Ractors at once, so the offsets are
1462 * built privately and published with a CAS; char_offset is NULL until then. */
1463static const struct rmatch_offset *
1464match_char_offsets(VALUE match)
1465{
1466 struct RMatch *rm = RMATCH(match);
1467 struct rmatch_offset *offsets = RUBY_ATOMIC_PTR_LOAD(rm->char_offset);
1468 struct rmatch_offset *published;
1469 int i, num_regs, num_pos;
1470 rb_len_t c;
1471 char *s, *p, *q;
1472 rb_encoding *enc;
1473 pair_t *pairs;
1474 VALUE pairs_obj = Qnil;
1475
1476 if (offsets) return offsets;
1477
1478 num_regs = RMATCH_NREGS(match);
1479 enc = rb_enc_get(RMATCH(match)->str);
1480
1481 if (rb_enc_mbmaxlen(enc) == 1) {
1482 offsets = ALLOC_N(struct rmatch_offset, num_regs);
1483 for (i = 0; i < num_regs; i++) {
1484 offsets[i].beg = RMATCH_BEG(match, i);
1485 offsets[i].end = RMATCH_END(match, i);
1486 }
1487 goto publish;
1488 }
1489
1490 pairs = RB_ALLOCV_N(pair_t, pairs_obj, num_regs * 2);
1491 num_pos = 0;
1492 for (i = 0; i < num_regs; i++) {
1493 if (RMATCH_BEG(match, i) < 0)
1494 continue;
1495 pairs[num_pos++].byte_pos = RMATCH_BEG(match, i);
1496 pairs[num_pos++].byte_pos = RMATCH_END(match, i);
1497 }
1498 qsort(pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1499
1500 s = p = RSTRING_PTR(RMATCH(match)->str);
1501 c = 0;
1502 for (i = 0; i < num_pos; i++) {
1503 q = s + pairs[i].byte_pos;
1504 c += rb_enc_strlen(p, q, enc);
1505 pairs[i].char_pos = c;
1506 p = q;
1507 }
1508
1509 offsets = ALLOC_N(struct rmatch_offset, num_regs);
1510 for (i = 0; i < num_regs; i++) {
1511 pair_t key, *found;
1512 if (RMATCH_BEG(match, i) < 0) {
1513 offsets[i].beg = -1;
1514 offsets[i].end = -1;
1515 continue;
1516 }
1517
1518 key.byte_pos = RMATCH_BEG(match, i);
1519 found = bsearch(&key, pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1520 offsets[i].beg = found->char_pos;
1521
1522 key.byte_pos = RMATCH_END(match, i);
1523 found = bsearch(&key, pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1524 offsets[i].end = found->char_pos;
1525 }
1526
1527 RB_ALLOCV_END(pairs_obj);
1528
1529 publish:
1530 published = RUBY_ATOMIC_PTR_CAS(rm->char_offset, NULL, offsets);
1531 if (published) {
1532 SIZED_FREE_N(offsets, num_regs);
1533 return published;
1534 }
1535 rm->char_offset_num_allocated = num_regs;
1536 return offsets;
1537}
1538
1539static VALUE
1540match_check(VALUE match)
1541{
1542 if (!RMATCH(match)->regexp) {
1543 rb_raise(rb_eTypeError, "uninitialized MatchData");
1544 }
1545 return match;
1546}
1547
1548/* :nodoc: */
1549VALUE
1550rb_match_init_copy(VALUE obj, VALUE orig)
1551{
1552 struct RMatch *rm = RMATCH(obj);
1553
1554 if (!OBJ_INIT_COPY(obj, orig)) return obj;
1555
1556 RB_OBJ_WRITE(obj, &rm->str, RMATCH(orig)->str);
1557 RB_OBJ_WRITE(obj, &rm->regexp, RMATCH(orig)->regexp);
1558
1559 match_set_regs(obj, RMATCH_NREGS(orig), RMATCH_BEG_PTR(orig), RMATCH_END_PTR(orig));
1560
1561 const struct rmatch_offset *orig_offsets = RUBY_ATOMIC_PTR_LOAD(RMATCH(orig)->char_offset);
1562 if (orig_offsets) {
1563 if (rm->char_offset_num_allocated < rm->num_regs) {
1564 SIZED_REALLOC_N(rm->char_offset, struct rmatch_offset, rm->num_regs, rm->char_offset_num_allocated);
1566 }
1567 MEMCPY(rm->char_offset, orig_offsets, struct rmatch_offset, rm->num_regs);
1568 RB_GC_GUARD(orig);
1569 }
1570
1571 return obj;
1572}
1573
1574
1575/*
1576 * :markup: markdown
1577 *
1578 * call-seq:
1579 * regexp -> regexp
1580 *
1581 * Returns the Regexp that produced the match:
1582 *
1583 * ```ruby
1584 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1585 * match = '2026-12-25'.match(regexp)
1586 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
1587 * match.regexp
1588 * # => /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1589 * ```
1590 *
1591 */
1592
1593static VALUE
1594match_regexp(VALUE match)
1595{
1596 VALUE regexp;
1597 match_check(match);
1598 regexp = RMATCH(match)->regexp;
1599 if (NIL_P(regexp)) {
1600 VALUE str = rb_reg_nth_match(0, match);
1601 regexp = rb_reg_regcomp(rb_reg_quote(str));
1602 if (RB_OBJ_SHAREABLE_P(match)) {
1603 return regexp;
1604 }
1605 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, regexp);
1606 }
1607 return regexp;
1608}
1609
1610/*
1611 * :markup: markdown
1612 *
1613 * call-seq:
1614 * names -> array_of_strings
1615 *
1616 * Returns an array containing the capture names:
1617 *
1618 * ```ruby
1619 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1620 * match = '2026-12-25'.match(regexp)
1621 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
1622 * match.names # => ["year", "month", "day"]
1623 * ```
1624 *
1625 */
1626
1627static VALUE
1628match_names(VALUE match)
1629{
1630 match_check(match);
1631 if (NIL_P(RMATCH(match)->regexp))
1632 return rb_ary_new_capa(0);
1633 return rb_reg_names(RMATCH(match)->regexp);
1634}
1635
1636/*
1637 * :markup: markdown
1638
1639 * call-seq:
1640 * size -> integer
1641 *
1642 * Returns size of the match array:
1643 *
1644 * ```ruby
1645 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1646 * match = '2026-12-25'.match(regexp)
1647 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
1648 * match.size # => 4
1649 * ```
1650 *
1651 */
1652
1653static VALUE
1654match_size(VALUE match)
1655{
1656 match_check(match);
1657 return INT2FIX(RMATCH_NREGS(match));
1658}
1659
1660static int match_name_to_backref_number(VALUE match, VALUE name);
1661NORETURN(static void name_to_backref_error(VALUE name));
1662
1663static void
1664name_to_backref_error(VALUE name)
1665{
1666 rb_raise(rb_eIndexError, "undefined group name reference: % "PRIsVALUE,
1667 name);
1668}
1669
1670static void
1671backref_number_check(VALUE match, int i)
1672{
1673 if (i < 0 || RMATCH_NREGS(match) <= i)
1674 rb_raise(rb_eIndexError, "index %d out of matches", i);
1675}
1676
1677static int
1678match_backref_number(VALUE match, VALUE backref)
1679{
1680 int num;
1681
1682 match_check(match);
1683 if (SYMBOL_P(backref)) {
1684 backref = rb_sym2str(backref);
1685 }
1686 else if (!RB_TYPE_P(backref, T_STRING)) {
1687 return NUM2INT(backref);
1688 }
1689
1690 num = match_name_to_backref_number(match, backref);
1691
1692 if (num < 1) {
1693 name_to_backref_error(backref);
1694 }
1695
1696 return num;
1697}
1698
1699int
1701{
1702 return match_backref_number(match, backref);
1703}
1704
1705/*
1706 * :markup: markdown
1707 *
1708 * call-seq:
1709 * offset(n) -> [begin_offset, end_offset]
1710 * offset(name) -> [begin_offset, end_offset]
1711 *
1712 * Returns the offsets (in characters) of the beginning (#begin value)
1713 * and end (#end value) of the specified match.
1714 *
1715 * With non-negative integer argument `n` given,
1716 * returns the character offsets for the `n`th match:
1717 *
1718 * ```ruby
1719 * regexp = /(\d{4})-(\d{2})-(\d{2})/
1720 * match = '2026-12-25'.match(regexp)
1721 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
1722 * match[0] # => "2026-12-25"
1723 * match.offset(0) # => [0, 10]
1724 * match[2] # => "12"
1725 * match.offset(2) # => [5, 7]
1726 * match.offset(4) # Raises IndexError: index 4 out of matches.
1727 *
1728 * match = /(ん)(に)(ち)/.match('こんにちは')
1729 * # => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
1730 * match[0] # => "んにち"
1731 * match.offset(0) # => [1, 4]
1732 * match[2] # => "に"
1733 * match.offset(2) # => [2, 3]
1734 * match.offset(4) # Raises IndexError: index 4 out of matches.
1735 * ```
1736 *
1737 * With string or symbol argument `name` given,
1738 * returns the offsets for the named match:
1739 *
1740 * ```ruby
1741 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1742 * match = '2026-12-25'.match(regexp)
1743 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
1744 * match[:year] # => "2026"
1745 * match.offset(:year) # => [0, 4]
1746 * match['day'] # => "25"
1747 * match.offset('day') # => [8, 10]
1748 * match.offset(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
1749 * ```
1750 *
1751 */
1752
1753static VALUE
1754match_offset(VALUE match, VALUE n)
1755{
1756 int i = match_backref_number(match, n);
1757
1758 match_check(match);
1759 backref_number_check(match, i);
1760
1761 if (RMATCH_BEG(match, i) < 0)
1762 return rb_assoc_new(Qnil, Qnil);
1763
1764 const struct rmatch_offset *ofs = &match_char_offsets(match)[i];
1765 return rb_assoc_new(LEN2NUM(ofs->beg), LEN2NUM(ofs->end));
1766}
1767
1768/*
1769 * :markup: markdown
1770 *
1771 * call-seq:
1772 * byteoffset(object) -> [bytebegin, byteend]
1773 *
1774 * Returns the offsets (in bytes) of the beginning and end of the specified match.
1775 *
1776 * With argument `object` given as a non-negative integer argument `n` given,
1777 * returns the offsets of the `n`th match:
1778 *
1779 * ```ruby
1780 * regexp = /(\d{4})-(\d{2})-(\d{2})/
1781 * match = '2026-12-25'.match(regexp)
1782 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
1783 * match[1] # => "2026"
1784 * match.byteoffset(1) # => [0, 4]
1785 * match[3] # => "25"
1786 * match.byteoffset(3) # => [8, 10]
1787 * match.byteoffset(10) # Raises IndexError: index 10 out of matches.
1788 *
1789 * match = /(ん)(に)(ち)/.match('こんにちは')
1790 * # => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
1791 * match[1] # => "ん"
1792 * match.byteoffset(1) # => [3, 6] # Byte offsets.
1793 * match.offset(1) # => [1, 2] # Character offsets.
1794 * ```
1795 *
1796 * With argument `object` given as a string or symbol argument `name`,
1797 * returns the offsets of the named match:
1798 *
1799 * ```ruby
1800 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1801 * match = '2026-12-25'.match(regexp)
1802 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
1803 * match[:year] # => "2026"
1804 * match.byteoffset(:year) # => [0, 4]
1805 * match.byteoffset('day') # => [8, 10]
1806 * ```
1807 *
1808 *
1809 * Related: MatchData#offset.
1810 *
1811 */
1812
1813static VALUE
1814match_byteoffset(VALUE match, VALUE n)
1815{
1816 int i = match_backref_number(match, n);
1817
1818 match_check(match);
1819 backref_number_check(match, i);
1820
1821 if (RMATCH_BEG(match, i) < 0)
1822 return rb_assoc_new(Qnil, Qnil);
1823 return rb_assoc_new(LEN2NUM(RMATCH_BEG(match, i)), LEN2NUM(RMATCH_END(match, i)));
1824}
1825
1826
1827/*
1828 * :markup: markdown
1829 *
1830 * call-seq:
1831 * bytebegin(n) -> integer
1832 * bytebegin(name) -> integer
1833 *
1834 * Returns the offset (in bytes) of the beginning of the specified match.
1835 *
1836 * With non-negative integer argument `n` given,
1837 * returns the offset of the beginning of the `n`th match:
1838 *
1839 * ```ruby
1840 * regexp = /(\d{4})-(\d{2})-(\d{2})/
1841 * match = '2026-12-25'.match(regexp)
1842 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
1843 * match[0] # => "2026-12-25"
1844 * match.bytebegin(0) # => 0
1845 * match[2] # => "12"
1846 * match.bytebegin(2) # => 5
1847 * match.bytebegin(20) # Raises IndexError: index 20 out of matches.
1848 *
1849 * match = /(ん)(に)(ち)/.match('こんにちは')
1850 * # => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
1851 * match[2] # => "に"
1852 * match.bytebegin(2) # => 6 # Byte offset.
1853 * match.begin(2) # => 2 # Character offset.
1854 * ```
1855 *
1856 * With string or symbol argument `name` given,
1857 * returns the offset of the beginning for the named match:
1858 *
1859 * ```ruby
1860 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1861 * match = '2026-12-25'.match(regexp)
1862 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
1863 * match[:month] # => "12"
1864 * match.bytebegin(:month) # => 5
1865 * match.bytebegin('day') # => 8
1866 * ```
1867 *
1868 * Related: MatchData#begin.
1869 *
1870 */
1871
1872static VALUE
1873match_bytebegin(VALUE match, VALUE n)
1874{
1875 int i = match_backref_number(match, n);
1876
1877 match_check(match);
1878 backref_number_check(match, i);
1879
1880 if (RMATCH_BEG(match, i) < 0)
1881 return Qnil;
1882 return LEN2NUM(RMATCH_BEG(match, i));
1883}
1884
1885
1886/*
1887 * :markup: markdown
1888 *
1889 * call-seq:
1890 * byteend(n) -> integer
1891 * byteend(name) -> integer
1892 *
1893 * Returns the offset (in bytes) of the end of the specified match.
1894 *
1895 * When non-negative integer argument `n` is given,
1896 * returns the offset of the end of the `n`th match:
1897 *
1898 * ```ruby
1899 * regexp = /(\d{4})-(\d{2})-(\d{2})/
1900 * match = '2026-12-25'.match(regexp)
1901 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
1902 * match[1] # => "2026"
1903 * match.byteend(1) # => 4
1904 * match[3] # => "25"
1905 * match.byteend(3) # => 10
1906 * match.byteend(4) # Raises IndexError: index 4 out of matches.
1907 *
1908 * match = /(ん)(に)(ち)/.match('こんにちは')
1909 * # => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
1910 * match[1] # => "ん"
1911 * match.byteend(1) # => 6 # Byte offset.
1912 * match.end(1) # => 2 # Character offset.
1913 * ```
1914 *
1915 * When string or symbol argument `name` is given,
1916 * returns the offset of the end for the named match:
1917 *
1918 * ```ruby
1919 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1920 * match = '2026-12-25'.match(regexp)
1921 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
1922 * match[:year] # => "2026"
1923 * match.byteend(:year) # => 4
1924 * match['day'] # => "25"
1925 * match.byteend('day') # => 10
1926 * ```
1927 *
1928 * Related: MatchData#bytebegin.
1929 *
1930 */
1931
1932static VALUE
1933match_byteend(VALUE match, VALUE n)
1934{
1935 int i = match_backref_number(match, n);
1936
1937 match_check(match);
1938 backref_number_check(match, i);
1939
1940 if (RMATCH_BEG(match, i) < 0)
1941 return Qnil;
1942 return LEN2NUM(RMATCH_END(match, i));
1943}
1944
1945
1946/*
1947 * :markup: markdown
1948 *
1949 * call-seq:
1950 * begin(n) -> integer
1951 * begin(name) -> integer
1952 *
1953 * Returns the offset (in characters) of the beginning of the specified match.
1954 *
1955 * With non-negative integer argument `n` given,
1956 * returns the character offset of the beginning of the `n`th match:
1957 *
1958 * ```ruby
1959 * regexp = /(\d{4})-(\d{2})-(\d{2})/
1960 * match = '2026-12-25'.match(regexp)
1961 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
1962 * match[0] # => "2026-12-25"
1963 * match.begin(0) # => 0
1964 * match[3] # => "25"
1965 * match.begin(3) # => 8
1966 * match.begin(10) # Raises IndexError: index 10 out of matches.
1967 *
1968 * match = /(ん)(に)(ち)/.match('こんにちは')
1969 * # => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
1970 * match[2] # => "に"
1971 * match.begin(2) # => 2 # Character offset.
1972 * match.bytebegin(2) # => 6 # Byte offset.
1973 * ```
1974 *
1975 * With string or symbol argument `name` given,
1976 * returns the offset of the beginning for the named match:
1977 *
1978 * ```ruby
1979 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
1980 * match = '2026-12-25'.match(regexp)
1981 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
1982 * match[:year] # => "2026"
1983 * match.begin(:year) # => 0
1984 * match.begin('month') # => 5
1985 * ```
1986 *
1987 * Related: MatchData#bytebegin.
1988 *
1989 */
1990
1991static VALUE
1992match_begin(VALUE match, VALUE n)
1993{
1994 int i = match_backref_number(match, n);
1995
1996 match_check(match);
1997 backref_number_check(match, i);
1998
1999 if (RMATCH_BEG(match, i) < 0)
2000 return Qnil;
2001
2002 return LEN2NUM(match_char_offsets(match)[i].beg);
2003}
2004
2005
2006/*
2007 * :markup: markdown
2008 *
2009 * call-seq:
2010 * end(n) -> integer
2011 * end(name) -> integer
2012 *
2013 * Returns the offset (in characters) of the end of the specified match.
2014 *
2015 * With non-negative integer argument `n` given,
2016 * returns the character offset of the end of the `n`th match:
2017 *
2018 * ```ruby
2019 * regexp = /(\d{4})-(\d{2})-(\d{2})/
2020 * match = '2026-12-25'.match(regexp)
2021 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
2022 * match[0] # => "2026-12-25"
2023 * match.end(0) # => 10
2024 * match[3] # => "25"
2025 * match.end(3) # => 10
2026 * match.end(10) # Raises IndexError: index 10 out of matches.
2027 *
2028 * match = /(ん)(に)(ち)/.match('こんにちは')
2029 * # => #<MatchData "んにち" 1:"ん" 2:"に" 3:"ち">
2030 * match[2] # => "に"
2031 * match.end(2) # => 3 # Character offset.
2032 * match.byteend(2) # => 9 # Byte offset.
2033 * ```
2034 *
2035 * With string or symbol argument `name` given, returns the offset of the end for the named match:
2036 *
2037 * ```ruby
2038 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
2039 * match = '2026-12-25'.match(regexp)
2040 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
2041 * match[:year] # => "2026"
2042 * match.end(:year) # => 4
2043 * match.end('month') # => 7
2044 * ```
2045 *
2046 * Related: MatchData#byteend.
2047 *
2048 */
2049
2050static VALUE
2051match_end(VALUE match, VALUE n)
2052{
2053 int i = match_backref_number(match, n);
2054
2055 match_check(match);
2056 backref_number_check(match, i);
2057
2058 if (RMATCH_BEG(match, i) < 0)
2059 return Qnil;
2060
2061 return LEN2NUM(match_char_offsets(match)[i].end);
2062}
2063
2064/*
2065 * :markup: markdown
2066 *
2067 * call-seq:
2068 * match(n) -> string or nil
2069 * match(name) -> string or nil
2070 *
2071 * Returns the matched substring corresponding to the given argument.
2072 *
2073 * With non-negative integer argument `n` given,
2074 * returns the matched substring for the `n`th match:
2075 *
2076 * ```ruby
2077 * regexp = /(\d{4})-(\d{2})-(\d{2})/
2078 * match = '2026-12-25'.match(regexp)
2079 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
2080 * match.match(0) # => "2026-12-25"
2081 * match.match(1) # => "2026"
2082 * match.match(2) # => "12"
2083 * match.match(3) # => "25"
2084 * match.match(4) # Raises IndexError: index 4 out of matches.
2085 * ```
2086 *
2087 * Except for `n == 0`, these same values are available
2088 * in [Regexp global variables][regexp global variables]:
2089 *
2090 * ```ruby
2091 * $0 # Returns the name of the current program.
2092 * $1 # => "2026"
2093 * $2 # => "12"
2094 * $3 # => "25"
2095 * $4 # => nil
2096 * ```
2097 *
2098 * Returns `nil` for an optional capture that had no match:
2099 *
2100 * ```ruby
2101 * match = /(\d+)(?:-(\d+))?/.match('123')
2102 * # => #<MatchData "123" 1:"123" 2:nil>
2103 * match.match(0) # => "123"
2104 * match.match(1) # => "123"
2105 * match.match(2) # => nil
2106 * ```
2107 *
2108 * With string or symbol argument `name` given,
2109 * returns the matched substring for the given name:
2110 *
2111 * ```ruby
2112 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
2113 * match = '2026-12-25'.match(regexp)
2114 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
2115 * match.match(:year) # => "2026"
2116 * match.match('day') # => "25"
2117 * match.match(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
2118 * ```
2119 *
2120 * Returns `nil` for a named capture that had no match:
2121 *
2122 * ```ruby
2123 * match = /(?<year>\d{4})(?:-(?<month>\d{2}))?/.match('2026')
2124 * # => #<MatchData "2026" year:"2026" month:nil>
2125 * match.match(:year) # => "2026"
2126 * match.match(:month) # => nil
2127 * ```
2128 *
2129 * [regexp global variables]: rdoc-ref:Regexp@Global+Variables
2130 */
2131
2132static VALUE
2133match_nth(VALUE match, VALUE n)
2134{
2135 int i = match_backref_number(match, n);
2136
2137 backref_number_check(match, i);
2138
2139 rb_len_t start = RMATCH_BEG(match, i), end = RMATCH_END(match, i);
2140 if (start < 0)
2141 return Qnil;
2142
2143 return rb_str_subseq(RMATCH(match)->str, start, end - start);
2144}
2145
2146/*
2147 * :markup: markdown
2148 *
2149 * call-seq:
2150 * match_length(n) -> integer
2151 * match_length(name) -> integer
2152 *
2153 * Returns the length (in characters) of the matched substring
2154 * corresponding to the given argument.
2155 *
2156 * With non-negative integer argument `n` given,
2157 * returns the length of the matched substring
2158 * for the `n`th match:
2159 *
2160 * ```ruby
2161 * regexp = /(\d{4})-(\d{2})-(\d{2})/
2162 * match = '2026-12-25'.match(regexp)
2163 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
2164 * match.match_length(0) # => 10
2165 * match.match_length(3) # => 2
2166 * match.match_length(4) # Raises IndexError: index 4 out of matches.
2167 *
2168 * s = 'こんにちは' # Four 3-byte characters.
2169 * match = /(こん)(に)(ち)/.match(s)
2170 * # => #<MatchData "こんにち" 1:"こん" 2:"に" 3:"ち">
2171 * match.match_length(0) # => 4
2172 * match.match_length(1) # => 2
2173 * match.match_length(3) # => 1
2174 * match.match_length(4) # Raises IndexError: index 4 out of matches.
2175 * ```
2176 *
2177 *
2178 * With string or symbol argument `name` given,
2179 * returns the length of the matched substring
2180 * for the named match:
2181 *
2182 * ```ruby
2183 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
2184 * match = '2026-12-25'.match(regexp)
2185 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
2186 * match.match_length(:year) # => 4
2187 * match.match_length('day') # => 2
2188 * match.match_length(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
2189 * ```
2190 *
2191 */
2192
2193static VALUE
2194match_nth_length(VALUE match, VALUE n)
2195{
2196 int i = match_backref_number(match, n);
2197
2198 match_check(match);
2199 backref_number_check(match, i);
2200
2201 if (RMATCH_BEG(match, i) < 0)
2202 return Qnil;
2203
2204 const struct rmatch_offset *const ofs = &match_char_offsets(match)[i];
2205 return LEN2NUM(ofs->end - ofs->beg);
2206}
2207
2208void
2210{
2211 FL_SET(match, MATCH_BUSY);
2212}
2213
2214void
2215rb_match_unbusy(VALUE match)
2216{
2217 FL_UNSET(match, MATCH_BUSY);
2218}
2219
2220int
2221rb_match_count(VALUE match)
2222{
2223 if (NIL_P(match)) return -1;
2224 return RMATCH_NREGS(match);
2225}
2226
2227static VALUE
2228match_alloc_or_reuse(VALUE existing, int num_regs)
2229{
2230 /* $~ can hold a Ractor::MovedObject: Ractor#send(move: true) hollows the
2231 * MatchData out in place and the husk keeps the old RMatch body, so its capa
2232 * still reads as reusable. Reusing it would write RMatch fields into a frozen
2233 * T_OBJECT, so check the type before trusting the body. */
2234 if (!NIL_P(existing) &&
2235 RB_TYPE_P(existing, T_MATCH) &&
2236 !FL_TEST(existing, MATCH_BUSY) &&
2237 RMATCH(existing)->capa >= num_regs * 2) {
2238 match_reuse(existing);
2239 return existing;
2240 }
2241 return match_alloc_n(rb_cMatch, num_regs);
2242}
2243
2244static void
2245match_set_string(VALUE m, VALUE string, rb_len_t pos, rb_len_t len)
2246{
2247 struct RMatch *match = (struct RMatch *)m;
2248
2249 RB_OBJ_WRITE(match, &match->str, string);
2250 RB_OBJ_WRITE(match, &match->regexp, Qnil);
2251 OnigPosition beg = pos, end = pos + len;
2252 match_set_regs(m, 1, &beg, &end);
2253}
2254
2255VALUE
2256rb_backref_set_string(VALUE string, rb_len_t pos, rb_len_t len)
2257{
2258 VALUE match = match_alloc_or_reuse(rb_backref_get(), 1);
2259 match_set_string(match, string, pos, len);
2260 rb_backref_set(match);
2261 return match;
2262}
2263
2264/*
2265 * call-seq:
2266 * fixed_encoding? -> true or false
2267 *
2268 * Returns +false+ if +self+ is applicable to
2269 * a string with any ASCII-compatible encoding;
2270 * otherwise returns +true+:
2271 *
2272 * r = /a/ # => /a/
2273 * r.fixed_encoding? # => false
2274 * r.match?("\u{6666} a") # => true
2275 * r.match?("\xa1\xa2 a".force_encoding("euc-jp")) # => true
2276 * r.match?("abc".force_encoding("euc-jp")) # => true
2277 *
2278 * r = /a/u # => /a/
2279 * r.fixed_encoding? # => true
2280 * r.match?("\u{6666} a") # => true
2281 * r.match?("\xa1\xa2".force_encoding("euc-jp")) # Raises exception.
2282 * r.match?("abc".force_encoding("euc-jp")) # => true
2283 *
2284 * r = /\u{6666}/ # => /\u{6666}/
2285 * r.fixed_encoding? # => true
2286 * r.encoding # => #<Encoding:UTF-8>
2287 * r.match?("\u{6666} a") # => true
2288 * r.match?("\xa1\xa2".force_encoding("euc-jp")) # Raises exception.
2289 * r.match?("abc".force_encoding("euc-jp")) # => false
2290 *
2291 */
2292
2293static VALUE
2294rb_reg_fixed_encoding_p(VALUE re)
2295{
2296 return RBOOL(FL_TEST(re, KCODE_FIXED));
2297}
2298
2299NORETURN(static void reg_enc_error(VALUE re, VALUE str));
2300
2301static void
2302reg_enc_error(VALUE re, VALUE str)
2303{
2304 rb_raise(rb_eEncCompatError,
2305 "incompatible encoding regexp match (%s regexp with %s string)",
2306 rb_enc_inspect_name(rb_enc_get(re)),
2307 rb_enc_inspect_name(rb_enc_get(str)));
2308}
2309
2310static rb_encoding*
2311rb_reg_prepare_enc(VALUE re, VALUE str, int warn)
2312{
2313 rb_encoding *enc = 0;
2314 int cr = rb_enc_str_coderange(str);
2315
2316 if (cr == ENC_CODERANGE_BROKEN) {
2317 rb_raise(rb_eArgError,
2318 "invalid byte sequence in %s",
2319 rb_enc_name(rb_enc_get(str)));
2320 }
2321
2322 rb_reg_check(re);
2323 enc = rb_enc_get(str);
2324 if (RREGEXP_PTR(re)->enc == enc) {
2325 }
2326 else if (cr == ENC_CODERANGE_7BIT &&
2327 RREGEXP_PTR(re)->enc == rb_usascii_encoding()) {
2328 enc = RREGEXP_PTR(re)->enc;
2329 }
2330 else if (!rb_enc_asciicompat(enc)) {
2331 reg_enc_error(re, str);
2332 }
2333 else if (rb_reg_fixed_encoding_p(re)) {
2334 if ((!rb_enc_asciicompat(RREGEXP_PTR(re)->enc) ||
2335 cr != ENC_CODERANGE_7BIT)) {
2336 reg_enc_error(re, str);
2337 }
2338 enc = RREGEXP_PTR(re)->enc;
2339 }
2340 else if (warn && (RBASIC(re)->flags & REG_ENCODING_NONE) &&
2341 enc != rb_ascii8bit_encoding() &&
2342 cr != ENC_CODERANGE_7BIT) {
2343 rb_warn("historical binary regexp match /.../n against %s string",
2344 rb_enc_name(enc));
2345 }
2346 return enc;
2347}
2348
2349static regex_t *
2350reg_find_encoding(struct rb_regexp_variant *variant, rb_encoding *enc)
2351{
2352 for (; variant; variant = variant->next) {
2353 if (variant->reg.enc == enc) return &variant->reg;
2354 }
2355 return NULL;
2356}
2357
2358static regex_t *
2359reg_prepare_re(VALUE re, VALUE str, bool caller_owned)
2360{
2361 int r;
2362 OnigErrorInfo einfo;
2363 VALUE unescaped;
2364 rb_encoding *fixed_enc = 0;
2365 rb_encoding *enc = rb_reg_prepare_enc(re, str, 1);
2366
2367 regex_t *reg = RREGEXP_PTR(re);
2368 if (reg->enc == enc) return reg;
2369
2370 struct rb_regexp_variant *head = RUBY_ATOMIC_PTR_LOAD(RREGEXP(re)->variants);
2371 regex_t *cached = reg_find_encoding(head, enc);
2372 if (cached && !caller_owned) return cached;
2373
2374 VALUE src_str = RREGEXP_SRC(re);
2375 const char *pattern = RSTRING_PTR(src_str);
2376
2377 onig_errmsg_buffer err = "";
2378 unescaped = rb_reg_preprocess(
2379 pattern, pattern + RSTRING_LEN(src_str), enc,
2380 &fixed_enc, err, reg->options);
2381
2382 if (NIL_P(unescaped)) {
2383 rb_raise(rb_eArgError, "regexp preprocess failed: %s", err);
2384 }
2385
2386 // inherit the timeout settings
2387 rb_hrtime_t timelimit = reg->timelimit;
2388
2389 const char *ptr;
2390 rb_len_t len;
2391 RSTRING_GETMEM(unescaped, ptr, len);
2392
2393 struct rb_regexp_variant *variant = ALLOC(struct rb_regexp_variant);
2394 reg_onig_begin();
2395 r = onig_new_without_alloc(&variant->reg, (UChar *)ptr, (UChar *)(ptr + len),
2396 reg->options, enc, OnigDefaultSyntax, &einfo);
2397 reg_onig_end();
2398
2399 if (r) {
2400 onig_free_body(&variant->reg);
2401 SIZED_FREE(variant);
2402 reg_warn_kept();
2403 onig_error_code_to_str((UChar*)err, r, &einfo);
2404 rb_reg_raise(err, re);
2405 }
2406
2407 reg = &variant->reg;
2408 reg->timelimit = timelimit;
2409 if (reg->num_mem != RREGEXP_PTR(re)->num_mem) {
2410 rb_bug("group count mismatch in the recompiled regexp: %d != %d", reg->num_mem, RREGEXP_PTR(re)->num_mem);
2411 }
2412
2413 {
2414 /* the new pattern is only ours: free it if a warning raises */
2415 int state;
2416 rb_protect(reg_warn_kept_i, Qnil, &state);
2417 if (state) {
2418 onig_free_body(&variant->reg);
2419 SIZED_FREE(variant);
2420 rb_jump_tag(state);
2421 }
2422 }
2423
2424 if (caller_owned) {
2425 /* onig_free() releases with libc free(), so don't use ALLOC here. */
2426 reg = malloc(sizeof(regex_t));
2427 if (!reg) {
2428 onig_free_body(&variant->reg);
2429 SIZED_FREE(variant);
2430 rb_memerror();
2431 }
2432 *reg = variant->reg;
2433 SIZED_FREE(variant);
2434 RB_GC_GUARD(unescaped);
2435 return reg;
2436 }
2437
2438 /* Published variants are immutable and stay alive with re. Only the head
2439 * changes; a failed CAS may mean another Ractor compiled this encoding. */
2440 for (;;) {
2441 variant->next = head;
2442 struct rb_regexp_variant *previous = RUBY_ATOMIC_PTR_CAS(RREGEXP(re)->variants, head, variant);
2443 if (previous == head) break;
2444
2445 head = previous;
2446 cached = reg_find_encoding(head, enc);
2447 if (cached) {
2448 /* Discard our reg and use the cached version */
2449 onig_free_body(&variant->reg);
2450 SIZED_FREE(variant);
2451 reg = cached;
2452 break;
2453 }
2454 }
2455
2456 RB_GC_GUARD(unescaped);
2457 RB_GC_GUARD(src_str);
2458 RB_GC_GUARD(re);
2459 return reg;
2460}
2461
2462/* Callers of this public API free the result with onig_free() if it is not
2463 * RREGEXP_PTR(re), so return a copy and keep variants private. */
2464regex_t *
2466{
2467 return reg_prepare_re(re, str, true);
2468}
2469
2470OnigPosition
2472 OnigPosition (*match)(regex_t *reg, VALUE str, struct re_registers *regs, void *args),
2473 void *args, struct re_registers *regs)
2474{
2475 regex_t *reg = reg_prepare_re(re, str, false);
2476
2477 /* Interrupt checks in the match may run other threads: don't let them
2478 * modify str. The match always returns, as interrupts raise after it. */
2479 const char *const ptr = RSTRING_PTR(str);
2480 const rb_len_t len = RSTRING_LEN(str);
2481 VALUE lock = rb_str_try_locktmp(str);
2482 reg_onig_begin();
2483 OnigPosition result = match(reg, str, regs, args);
2484 reg_onig_end();
2485 rb_str_try_unlocktmp(str, lock);
2486
2487 RB_GC_GUARD(re);
2488 RB_GC_GUARD(str);
2489 RB_GC_GUARD(lock);
2490
2491 if (result == ONIGERR_INTERRUPTED) reg_onig_raise_interrupt();
2492 /* not locked by this: the owner of the lock may have modified str */
2493 if (lock != Qtrue && (RSTRING_PTR(str) != ptr || RSTRING_LEN(str) != len)) {
2494 rb_raise(rb_eRuntimeError, "string modified");
2495 }
2496
2497 if (result == ONIGERR_MEMORY) {
2498 /* e.g. for the match stack or the match cache table */
2499 rb_memerror();
2500 }
2501 if (result < 0) {
2502 switch (result) {
2503 case ONIG_MISMATCH:
2504 break;
2505 case ONIGERR_INTERRUPTED:
2506 reg_onig_raise_interrupt();
2507 case ONIGERR_TIMEOUT:
2508 rb_raise(rb_eRegexpTimeoutError, "regexp match timeout");
2509 default: {
2510 onig_errmsg_buffer err = "";
2511 onig_error_code_to_str((UChar*)err, (int)result);
2512 rb_reg_raise(err, re);
2513 }
2514 }
2515 }
2516
2517 return result;
2518}
2519
2521rb_reg_adjust_startpos(VALUE re, VALUE str, rb_len_t pos, int reverse)
2522{
2523 rb_len_t range;
2524 rb_encoding *enc;
2525 UChar *p, *string;
2526
2527 enc = rb_reg_prepare_enc(re, str, 0);
2528
2529 if (reverse) {
2530 range = -pos;
2531 }
2532 else {
2533 range = RSTRING_LEN(str) - pos;
2534 }
2535
2536 if (pos > 0 && ONIGENC_MBC_MAXLEN(enc) != 1 && pos < RSTRING_LEN(str)) {
2537 string = (UChar*)RSTRING_PTR(str);
2538
2539 if (range > 0) {
2540 p = onigenc_get_right_adjust_char_head(enc, string, string + pos, string + RSTRING_LEN(str));
2541 }
2542 else {
2543 p = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, string, string + pos, string + RSTRING_LEN(str));
2544 }
2545 return p - string;
2546 }
2547
2548 return pos;
2549}
2550
2552 rb_len_t pos;
2553 rb_len_t range;
2554};
2555
2556static OnigPosition
2557reg_onig_search(regex_t *reg, VALUE str, struct re_registers *regs, void *args_ptr)
2558{
2559 struct reg_onig_search_args *args = (struct reg_onig_search_args *)args_ptr;
2560 const char *ptr;
2561 rb_len_t len;
2562 RSTRING_GETMEM(str, ptr, len);
2563
2564 return onig_search(
2565 reg,
2566 (UChar *)ptr,
2567 (UChar *)(ptr + len),
2568 (UChar *)(ptr + args->pos),
2569 (UChar *)(ptr + args->range),
2570 regs,
2571 ONIG_OPTION_NONE);
2572}
2573
2574/* returns byte offset */
2575static rb_len_t
2576rb_reg_search_set_match(VALUE re, VALUE str, rb_len_t pos, int reverse, int set_backref_str, VALUE *set_match)
2577{
2578 rb_len_t len = RSTRING_LEN(str);
2579 if (pos > len || pos < 0) {
2581 return -1;
2582 }
2583
2584 struct reg_onig_search_args args = {
2585 .pos = pos,
2586 .range = reverse ? 0 : len,
2587 };
2588
2589 rb_reg_check(re);
2590
2591 /* Stack-backed regs sized to max(num_mem+1, ONIG_NREGION) so
2592 * onig_region_resize_clear takes its no-op branch. */
2593 int n = RREGEXP_PTR(re)->num_mem + 1;
2594 int cap = n < ONIG_NREGION ? ONIG_NREGION : n;
2595 VALUE regs_buf;
2596 OnigPosition *buf = ALLOCV_N(OnigPosition, regs_buf, (size_t)cap * 2);
2597 struct re_registers regs = {
2598 .allocated = cap,
2599 .num_regs = 0,
2600 .beg = buf,
2601 .end = buf + cap,
2602 };
2603
2604 OnigPosition result = rb_reg_onig_match(re, str, reg_onig_search, &args, &regs);
2605
2606 if (result == ONIG_MISMATCH) {
2607 ALLOCV_END(regs_buf);
2609 return ONIG_MISMATCH;
2610 }
2611
2612 VALUE existing = (set_match && !NIL_P(*set_match)) ? *set_match : rb_backref_get();
2613 VALUE match = match_alloc_or_reuse(existing, regs.num_regs);
2614
2615 match_set_regs(match, regs.num_regs, regs.beg, regs.end);
2616 ALLOCV_END(regs_buf);
2617
2618 if (set_backref_str) {
2619 RB_OBJ_WRITE(match, &RMATCH(match)->str, rb_str_new4(str));
2620 rb_obj_reveal(match, rb_cMatch);
2621 }
2622 else if (!RMATCH(match)->str) {
2623 /* Note that a MatchData object with RMATCH(match)->str == 0 is incomplete!
2624 * We need to hide the object from ObjectSpace.each_object.
2625 * https://bugs.ruby-lang.org/issues/19159
2626 */
2627 rb_obj_hide(match);
2628 }
2629
2630 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, re);
2631 rb_backref_set(match);
2632 if (set_match) *set_match = match;
2633
2634 return result;
2635}
2636
2638rb_reg_search0(VALUE re, VALUE str, rb_len_t pos, int reverse, int set_backref_str, VALUE *match)
2639{
2640 return rb_reg_search_set_match(re, str, pos, reverse, set_backref_str, match);
2641}
2642
2644rb_reg_search(VALUE re, VALUE str, rb_len_t pos, int reverse)
2645{
2646 return rb_reg_search_set_match(re, str, pos, reverse, 1, NULL);
2647}
2648
2649static OnigPosition
2650reg_onig_match(regex_t *reg, VALUE str, struct re_registers *regs, void *_)
2651{
2652 const char *ptr;
2653 rb_len_t len;
2654 RSTRING_GETMEM(str, ptr, len);
2655
2656 return onig_match(
2657 reg,
2658 (UChar *)ptr,
2659 (UChar *)(ptr + len),
2660 (UChar *)ptr,
2661 regs,
2662 ONIG_OPTION_NONE);
2663}
2664
2665bool
2666rb_reg_start_with_p(VALUE re, VALUE str)
2667{
2668 rb_reg_check(re);
2669
2670 int n = RREGEXP_PTR(re)->num_mem + 1;
2671 int cap = n < ONIG_NREGION ? ONIG_NREGION : n;
2672 VALUE regs_buf;
2673 OnigPosition *buf = ALLOCV_N(OnigPosition, regs_buf, (size_t)cap * 2);
2674 struct re_registers regs = {
2675 .allocated = cap,
2676 .num_regs = 0,
2677 .beg = buf,
2678 .end = buf + cap,
2679 };
2680
2681 if (rb_reg_onig_match(re, str, reg_onig_match, NULL, &regs) == ONIG_MISMATCH) {
2682 ALLOCV_END(regs_buf);
2684 return false;
2685 }
2686
2687 VALUE match = match_alloc_or_reuse(rb_backref_get(), regs.num_regs);
2688 match_set_regs(match, regs.num_regs, regs.beg, regs.end);
2689 ALLOCV_END(regs_buf);
2690
2691 RB_OBJ_WRITE(match, &RMATCH(match)->str, rb_str_new4(str));
2692 rb_obj_reveal(match, rb_cMatch);
2693 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, re);
2694 rb_backref_set(match);
2695
2696 return true;
2697}
2698
2699VALUE
2701{
2702 if (NIL_P(match)) return Qnil;
2703 match_check(match);
2704 int num_regs = RMATCH_NREGS(match);
2705 if (nth >= num_regs) {
2706 return Qnil;
2707 }
2708 if (nth < 0) {
2709 nth += num_regs;
2710 if (nth <= 0) return Qnil;
2711 }
2712 return RBOOL(RMATCH_BEG(match, nth) != -1);
2713}
2714
2715VALUE
2717{
2718 VALUE str;
2719 rb_len_t start, end, len;
2720
2721 if (NIL_P(match)) return Qnil;
2722 match_check(match);
2723 int num_regs = RMATCH_NREGS(match);
2724 if (nth >= num_regs) {
2725 return Qnil;
2726 }
2727 if (nth < 0) {
2728 nth += num_regs;
2729 if (nth <= 0) return Qnil;
2730 }
2731 start = RMATCH_BEG(match, nth);
2732 if (start == -1) return Qnil;
2733 end = RMATCH_END(match, nth);
2734 len = end - start;
2735 str = rb_str_subseq(RMATCH(match)->str, start, len);
2736 return str;
2737}
2738
2739VALUE
2741{
2742 return rb_reg_nth_match(0, match);
2743}
2744
2745
2746/*
2747 * :markup: markdown
2748 *
2749 * call-seq:
2750 * pre_match -> string
2751 *
2752 * Returns the substring of the target string that precedes the matched substring;
2753 * equivalent to [Regexp global variable][regexp global variable] <tt>$`</tt>:
2754 *
2755 * ```ruby
2756 * match = /\d+/.match('foo 123 bar 456')
2757 * # => #<MatchData "123">
2758 * match.match(0) # => "123"
2759 * match.pre_match # => "foo "
2760 * ```
2761 *
2762 * [regexp global variable]: rdoc-ref:Regexp@Global+Variables
2763 */
2764
2765VALUE
2767{
2768 VALUE str;
2769
2770 if (NIL_P(match)) return Qnil;
2771 match_check(match);
2772 if (RMATCH_BEG(match, 0) == -1) return Qnil;
2773 str = rb_str_subseq(RMATCH(match)->str, 0, RMATCH_BEG(match, 0));
2774 return str;
2775}
2776
2777
2778/*
2779 * :markup: markdown
2780 *
2781 * call-seq:
2782 * post_match -> string
2783 *
2784 * Returns the substring of the target string that follows the matched substring;
2785 * equivalent to [Regexp global variable][regexp global variable] `$'`:
2786 *
2787 * ```ruby
2788 * match = /\d+/.match('foo 123 bar 456')
2789 * # => #<MatchData "123">
2790 * match.match(0) # => "123"
2791 * match.post_match # => " bar 456"
2792 * ```
2793 *
2794 * [regexp global variable]: rdoc-ref:Regexp@Global+Variables
2795 */
2796
2797VALUE
2799{
2800 VALUE str;
2801 rb_len_t pos;
2802
2803 if (NIL_P(match)) return Qnil;
2804 match_check(match);
2805 if (RMATCH_BEG(match, 0) == -1) return Qnil;
2806 str = RMATCH(match)->str;
2807 pos = RMATCH_END(match, 0);
2808 str = rb_str_subseq(str, pos, RSTRING_LEN(str) - pos);
2809 return str;
2810}
2811
2812static int
2813match_last_index(VALUE match)
2814{
2815 int i;
2816
2817 if (NIL_P(match)) return -1;
2818 match_check(match);
2819 if (RMATCH_BEG(match, 0) == -1) return -1;
2820
2821 for (i = RMATCH_NREGS(match) - 1; RMATCH_BEG(match, i) == -1 && i > 0; i--)
2822 ;
2823 return i;
2824}
2825
2826VALUE
2828{
2829 int i = match_last_index(match);
2830 if (i <= 0) return Qnil;
2831 rb_len_t start = RMATCH_BEG(match, i);
2832 return rb_str_subseq(RMATCH(match)->str, start, RMATCH_END(match, i) - start);
2833}
2834
2835VALUE
2836rb_reg_last_defined(VALUE match)
2837{
2838 int i = match_last_index(match);
2839 if (i < 0) return Qnil;
2840 return RBOOL(i);
2841}
2842
2843static VALUE
2844last_match_getter(ID _x, VALUE *_y)
2845{
2847}
2848
2849static VALUE
2850prematch_getter(ID _x, VALUE *_y)
2851{
2853}
2854
2855static VALUE
2856postmatch_getter(ID _x, VALUE *_y)
2857{
2859}
2860
2861static VALUE
2862last_paren_match_getter(ID _x, VALUE *_y)
2863{
2865}
2866
2867static VALUE
2868match_array(VALUE match, int start)
2869{
2870 VALUE ary;
2871 VALUE target;
2872 int i;
2873
2874 match_check(match);
2875 int num_regs = RMATCH_NREGS(match);
2876 ary = rb_ary_new2(num_regs);
2877 target = RMATCH(match)->str;
2878
2879 for (i = start; i < num_regs; i++) {
2880 rb_len_t beg = RMATCH_BEG(match, i);
2881 if (beg == -1) {
2882 rb_ary_push(ary, Qnil);
2883 }
2884 else {
2885 VALUE str = rb_str_subseq(target, beg, RMATCH_END(match, i) - beg);
2886 rb_ary_push(ary, str);
2887 }
2888 }
2889 return ary;
2890}
2891
2892
2893/*
2894 * :markup: markdown
2895 *
2896 * call-seq:
2897 * to_a -> array
2898 *
2899 * Returns the array of matched substrings:
2900 *
2901 * ```ruby
2902 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
2903 * match = '2026-12-25'.match(regexp)
2904 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
2905 * match.to_a # => ["2026-12-25", "2026", "12", "25"]
2906 * ```
2907 *
2908 */
2909
2910static VALUE
2911match_to_a(VALUE match)
2912{
2913 return match_array(match, 0);
2914}
2915
2916
2917/*
2918 * :markup: markdown
2919 *
2920 * call-seq:
2921 * captures -> array
2922 *
2923 * Returns an array of the captured substrings,
2924 * including all except the entire matched substring:
2925 *
2926 * ```ruby
2927 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
2928 * match = '2026-12-25'.match(regexp)
2929 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
2930 * match.captures # => ["2026", "12", "25"]
2931 * match[1..] # => ["2026", "12", "25"] # Included in array.
2932 * match[0] # => "2026-12-25" # Not included in array.
2933 * ```
2934 *
2935 * Related: MatchData.to_a.
2936 *
2937 */
2938static VALUE
2939match_captures(VALUE match)
2940{
2941 return match_array(match, 1);
2942}
2943
2944static int
2945name_to_backref_number(const struct re_registers *regs, VALUE regexp, const char* name, const char* name_end)
2946{
2947 if (NIL_P(regexp)) return -1;
2948 return onig_name_to_backref_number(RREGEXP_PTR(regexp),
2949 (const unsigned char *)name, (const unsigned char *)name_end, regs);
2950}
2951
2952#define NAME_TO_NUMBER(regs, re, name, name_ptr, name_end) \
2953 (NIL_P(re) ? 0 : \
2954 !rb_enc_compatible(RREGEXP_SRC(re), (name)) ? 0 : \
2955 name_to_backref_number((regs), (re), (name_ptr), (name_end)))
2956
2957static int
2958match_name_to_backref_number(VALUE match, VALUE name)
2959{
2960 VALUE regexp = RMATCH(match)->regexp;
2961 if (NIL_P(regexp)) return -1;
2962
2963 int *nums;
2964 int n = onig_name_to_group_numbers(RREGEXP_PTR(regexp),
2965 (const unsigned char *)RSTRING_PTR(name),
2966 (const unsigned char *)RSTRING_END(name), &nums);
2967 if (n < 0) return n;
2968 if (n == 0) return ONIGERR_PARSER_BUG;
2969 if (n == 1) return nums[0];
2970 for (int i = n - 1; i >= 0; i--) {
2971 if (RMATCH_BEG(match, nums[i]) != ONIG_REGION_NOTPOS)
2972 return nums[i];
2973 }
2974 return nums[n - 1];
2975}
2976
2977static int
2978namev_to_backref_number(VALUE match, VALUE name)
2979{
2980 int num;
2981
2982 if (SYMBOL_P(name)) {
2983 name = rb_sym2str(name);
2984 }
2985 else if (!RB_TYPE_P(name, T_STRING)) {
2986 return -1;
2987 }
2988
2989 VALUE re = RMATCH(match)->regexp;
2990 if (NIL_P(re) || !rb_enc_compatible(RREGEXP_SRC(re), name)) {
2991 num = 0;
2992 }
2993 else {
2994 num = match_name_to_backref_number(match, name);
2995 }
2996 if (num < 1) {
2997 name_to_backref_error(name);
2998 }
2999 return num;
3000}
3001
3002static VALUE
3003match_ary_subseq(VALUE match, rb_len_t beg, rb_len_t len, VALUE result)
3004{
3005 rb_len_t olen = RMATCH_NREGS(match);
3006 rb_len_t j, end = olen < beg+len ? olen : beg+len;
3007 if (NIL_P(result)) result = rb_ary_new_capa(len);
3008 if (len == 0) return result;
3009
3010 for (j = beg; j < end; j++) {
3011 rb_ary_push(result, rb_reg_nth_match((int)j, match));
3012 }
3013 if (beg + len > j) {
3014 /* values_at passes a result that already has elements, so
3015 * adding the padding to its length can overflow. */
3016 const rb_len_t rest = beg + len - j;
3017 if (rest > RB_LEN_MAX - RARRAY_LEN(result)) {
3018 rb_raise(rb_eIndexError, "index %"PRIdLEN" too big",
3019 beg + len - 1);
3020 }
3021 rb_ary_resize(result, RARRAY_LEN(result) + rest);
3022 }
3023 return result;
3024}
3025
3026static VALUE
3027match_ary_aref(VALUE match, VALUE idx, VALUE result)
3028{
3029 rb_len_t beg, len;
3030 int num_regs = RMATCH_NREGS(match);
3031
3032 /* check if idx is Range */
3033 switch (rb_range_beg_len(idx, &beg, &len, (rb_len_t)num_regs, !NIL_P(result))) {
3034 case Qfalse:
3035 if (NIL_P(result)) return rb_reg_nth_match(NUM2INT(idx), match);
3036 rb_ary_push(result, rb_reg_nth_match(NUM2INT(idx), match));
3037 return result;
3038 case Qnil:
3039 return Qnil;
3040 default:
3041 return match_ary_subseq(match, beg, len, result);
3042 }
3043}
3044
3045/*
3046 * :markup: markdown
3047 *
3048 * call-seq:
3049 * self[n] -> string or nil
3050 * self[n, size] -> string or array
3051 * self[name] -> string or nil
3052 * self[range] -> array or nil
3053 *
3054 * With only integer argument `n` given,
3055 * returns the matched substring at offset `n`:
3056 *
3057 * ```ruby
3058 * regexp = /(\d{4})-(\d{2})-(\d{2})/
3059 * match = '2026-12-25'.match(regexp)
3060 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
3061 * match[0] # => "2026-12-25" # Entire matched string.
3062 * match[1] # => "2026" # First matched substring.
3063 * match[2] # => "12" # Second matched substring.
3064 * match[3] # => "25" # Third matched substring.
3065 * match[4] # => nil # No more matches.
3066 * match[-1] # => "25" # For negative offset, counts backwards.
3067 * ```
3068 *
3069 * With integer arguments `n` and `size` given,
3070 * returns `size` matched substrings beginning at offset `n`:
3071 *
3072 * ```ruby
3073 * regexp = /(\d{4})-(\d{2})-(\d{2})/
3074 * match = '2026-12-25'.match(regexp)
3075 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
3076 * match[0, 1] # => ["2026-12-25"]
3077 * match[0, 4] # => ["2026-12-25", "2026", "12", "25"]
3078 * match[0, 10] # => ["2026-12-25", "2026", "12", "25"]
3079 * match[-3, 2] # => ["2026", "12"]
3080 * match[0, 0] # => []
3081 * ```
3082 *
3083 * With string or symbol argument `name` given,
3084 * returns the named matched substring:
3085 *
3086 * ```ruby
3087 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3088 * match = regexp.match('2026-10-27')
3089 * # => #<MatchData "2026-10-27" year:"2026" month:"10" day:"27">
3090 * match[:year] # => "2026"
3091 * match['day'] # => "27"
3092 * match[:nosuch] # Raises IndexError : undefined group name reference: nosuch.
3093 * ```
3094 *
3095 * If multiple captures have the same name, returns matched substring for the last one.
3096 *
3097 * With [bounded range][bounded range] argument `range` given,
3098 * returns an array of matched substrings:
3099 *
3100 * ```
3101 * regexp = /(\d{4})-(\d{2})-(\d{2})/
3102 * match = '2026-12-25'.match(regexp)
3103 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
3104 * match[0..2] # => ["2026-12-25", "2026", "12"]
3105 * match[0..10] # => ["2026-12-25", "2026", "12", "25"]
3106 * match[0..-3] # => ["2026-12-25", "2026"]
3107 * match[-3..2] # => ["2026", "12"]
3108 * ```
3109 *
3110 * With [beginless range][beginless range] argument `range` given,
3111 * returns an array of matched substrings:
3112 *
3113 * ```ruby
3114 * match[..0] # => ["2026-12-25"]
3115 * match[..1] # => ["2026-12-25", "2026"]
3116 * match[..10] # => ["2026-12-25", "2026", "12", "25"]
3117 * ```
3118 *
3119 * With [endless range][endless range] argument `range` given,
3120 * returns an array of matched substrings:
3121 *
3122 * ```ruby
3123 * match[0..] # => ["2026-12-25", "2026", "12", "25"]
3124 * match[2..] # => ["12", "25"]
3125 * match[10..] # => nil
3126 * ```
3127 *
3128 * With [unbounded range][unbounded range] argument `range` given,
3129 * returns an array of all matched substrings:
3130 *
3131 * ```ruby
3132 * match[nil..nil] # => ["2026-12-25", "2026", "12", "25"]
3133 * ```
3134 *
3135 * [bounded range]: rdoc-ref:Range@Bounded+Ranges
3136 * [beginless range]: rdoc-ref:Range@Beginless+Ranges
3137 * [endless range]: rdoc-ref:Range@Endless+Ranges
3138 * [unbounded range]: rdoc-ref:Range@Unbounded+Ranges
3139 *
3140 */
3141
3142static VALUE
3143match_aref(int argc, VALUE *argv, VALUE match)
3144{
3145 VALUE idx, length;
3146
3147 match_check(match);
3148 rb_scan_args(argc, argv, "11", &idx, &length);
3149
3150 if (NIL_P(length)) {
3151 if (FIXNUM_P(idx)) {
3152 return rb_reg_nth_match(FIX2INT(idx), match);
3153 }
3154 else {
3155 int num = namev_to_backref_number(match, idx);
3156 if (num >= 0) {
3157 return rb_reg_nth_match(num, match);
3158 }
3159 else {
3160 return match_ary_aref(match, idx, Qnil);
3161 }
3162 }
3163 }
3164 else {
3165 rb_len_t beg = NUM2LEN(idx);
3166 rb_len_t len = NUM2LEN(length);
3167 rb_len_t num_regs = RMATCH_NREGS(match);
3168 if (len < 0) {
3169 return Qnil;
3170 }
3171 if (beg < 0) {
3172 beg += num_regs;
3173 if (beg < 0) return Qnil;
3174 }
3175 else if (beg > num_regs) {
3176 return Qnil;
3177 }
3178 if (beg+len > num_regs) {
3179 len = num_regs - beg;
3180 }
3181 return match_ary_subseq(match, beg, len, Qnil);
3182 }
3183}
3184
3185/*
3186 * :markup: markdown
3187 *
3188 * call-seq:
3189 * values_at(*indexes) -> array
3190 *
3191 * Returns an array of matched substrings as specified by the given `indexes`,
3192 * which may be any mixture of integers, names, and ranges.
3193 *
3194 * For each integer index `n`,
3195 * includes the `n`th matched substring:
3196 *
3197 * ```ruby
3198 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3199 * match = '2026-12-25'.match(regexp)
3200 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
3201 * match.values_at(3, 1, 2, 0) # => ["25", "2026", "12", "2026-12-25"]
3202 * ```
3203 *
3204 * For negative `n`, counts backwards in the array of matched substrings:
3205 *
3206 * ```ruby
3207 * match.values_at(3, -1) # => ["25", "25"]
3208 * ```
3209 *
3210 * For `n` out of range, returns `nil`:
3211 *
3212 * ```ruby
3213 * match.values_at(4, -4) # => [nil, nil]
3214 * ```
3215 *
3216 * For each string or symbol index `name`,
3217 * includes the matched substring for that `name`:
3218 *
3219 * ```ruby
3220 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3221 * match = '2026-12-25'.match(regexp)
3222 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
3223 * match.values_at(:day, 'year') # => ["25", "2026"]
3224 * match.values_at(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
3225 * ```
3226 *
3227 * For a Range index `range`,
3228 * returns the matched substrings for the indexes covered by that `range`:
3229 *
3230 * ```ruby
3231 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3232 * match = '2026-12-25'.match(regexp)
3233 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
3234 * match.values_at(1..2) # => ["2026", "12"]
3235 * match.values_at(1...3) # => ["2026", "12"]
3236 * ```
3237 *
3238 * For positive range value out-of-range, fills with `nil`:
3239 *
3240 * ```ruby
3241 * match.values_at(1..5) # => ["2026", "12", "25", nil, nil]
3242 * ```
3243 *
3244 * For negative range value, counts backwards in the array of matched substrings:
3245 *
3246 * ```ruby
3247 * match.values_at(-3..-1) # => ["2026", "12", "25"]
3248 * match.values_at(-5..-1) # Raises RangeError: -5..-1 out of range.
3249 * ```
3250 *
3251 * Mixed-type indexes:
3252 *
3253 * ```ruby
3254 * match.values_at(:year, 1, :month, 2, :day, 3, 0..3)
3255 * # => ["2026", "2026", "12", "12", "25", "25", "2026-12-25", "2026", "12", "25"]
3256 * ```
3257 *
3258 */
3259
3260static VALUE
3261match_values_at(int argc, VALUE *argv, VALUE match)
3262{
3263 VALUE result;
3264 int i;
3265
3266 match_check(match);
3267 result = rb_ary_new2(argc);
3268
3269 for (i=0; i<argc; i++) {
3270 if (FIXNUM_P(argv[i])) {
3271 rb_ary_push(result, rb_reg_nth_match(FIX2INT(argv[i]), match));
3272 }
3273 else {
3274 int num = namev_to_backref_number(match, argv[i]);
3275 if (num >= 0) {
3276 rb_ary_push(result, rb_reg_nth_match(num, match));
3277 }
3278 else {
3279 match_ary_aref(match, argv[i], result);
3280 }
3281 }
3282 }
3283 return result;
3284}
3285
3286
3287/*
3288 * :markup: markdown
3289 *
3290 * call-seq:
3291 * to_s -> string
3292 *
3293 * Returns the matched substring;
3294 * equivalent to #match(0):
3295 *
3296 * ```ruby
3297 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3298 * match = '2026-12-25'.match(regexp)
3299 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
3300 * match.to_s # => "2026-12-25"
3301 * ```
3302 *
3303 */
3304
3305static VALUE
3306match_to_s(VALUE match)
3307{
3308 VALUE str = rb_reg_last_match(match_check(match));
3309
3310 if (NIL_P(str)) str = rb_str_new(0,0);
3311 return str;
3312}
3313
3315 VALUE hash;
3316 VALUE match;
3317 int symbolize;
3318};
3319
3320static int
3321match_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end,
3322 int back_num, int *back_refs, OnigRegex regex, void *arg)
3323{
3324 struct named_captures_data *data = arg;
3325 VALUE hash = data->hash;
3326 VALUE match = data->match;
3327
3328 VALUE key = rb_enc_str_new((const char *)name, name_end-name, regex->enc);
3329
3330 if (data->symbolize) {
3331 key = rb_str_intern(key);
3332 }
3333
3334 VALUE value;
3335
3336 int i;
3337 int found = 0;
3338
3339 for (i = 0; i < back_num; i++) {
3340 value = rb_reg_nth_match(back_refs[i], match);
3341 if (RTEST(value)) {
3342 rb_hash_aset(hash, key, value);
3343 found = 1;
3344 }
3345 }
3346
3347 if (found == 0) {
3348 rb_hash_aset(hash, key, Qnil);
3349 }
3350
3351 return 0;
3352}
3353
3354/*
3355 * :markup: markdown
3356 *
3357 * call-seq:
3358 * named_captures(symbolize_names: false) -> hash
3359 *
3360 * Returns a hash of capture names and values:
3361 *
3362 * ```ruby
3363 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3364 * match = '2026-12-25'.match(regexp)
3365 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
3366 * match.named_captures # => {"year" => "2026", "month" => "12", "day" => "25"}
3367 * ```
3368 *
3369 * With keyword argument `symbolize_names` given as `true`,
3370 * returns hash keys as symbols:
3371 *
3372 * ```ruby
3373 * match.named_captures(symbolize_names: true)
3374 * # => {year: "2026", month: "12", day: "25"}
3375 * ```
3376 *
3377 * Returns a `nil` hash value for a name that captured nothing:
3378 *
3379 * ```ruby
3380 * regexp = /(?<year>\d{4})-(?<month>\d{2})?/
3381 * # => /(?<year>\d{4})-(?<month>\d{2})?/
3382 * match = '2026-'.match(regexp)
3383 * # => #<MatchData "2026-" year:"2026" month:nil>
3384 * match.named_captures # => {"year" => "2026", "month" => nil}
3385 * ```
3386 *
3387 */
3388
3389static VALUE
3390match_named_captures(int argc, VALUE *argv, VALUE match)
3391{
3392 VALUE hash;
3393
3394 match_check(match);
3395 if (NIL_P(RMATCH(match)->regexp))
3396 return rb_hash_new();
3397
3398 VALUE opt;
3399 int symbolize_names = 0;
3400
3401 rb_scan_args(argc, argv, "0:", &opt);
3402
3403 if (!NIL_P(opt)) {
3404 static ID keyword_ids[1];
3405
3406 VALUE symbolize_names_val;
3407
3408 if (!keyword_ids[0]) {
3409 keyword_ids[0] = rb_intern_const("symbolize_names");
3410 }
3411 rb_get_kwargs(opt, keyword_ids, 0, 1, &symbolize_names_val);
3412 if (!UNDEF_P(symbolize_names_val) && RTEST(symbolize_names_val)) {
3413 symbolize_names = 1;
3414 }
3415 }
3416
3417 hash = rb_hash_new();
3418 struct named_captures_data data = { hash, match, symbolize_names };
3419
3420 onig_foreach_name(RREGEXP_PTR(RMATCH(match)->regexp), match_named_captures_iter, &data);
3421
3422 return hash;
3423}
3424
3425/*
3426 * :markup: markdown
3427 *
3428 * call-seq:
3429 * deconstruct_keys(object) -> hash
3430 *
3431 * With an array of symbol capture names given,
3432 * returns a hash of the names and values for the given names:
3433 *
3434 * ```ruby
3435 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3436 * match = '2026-12-25'.match(regexp)
3437 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
3438 * match.deconstruct_keys([:day, :month]) # => {day: "25", month: "12"}
3439 * match.deconstruct_keys(['foo']) # Raises TypeError: wrong argument type String (expected Symbol).
3440 * ```
3441 *
3442 * Ignores symbols that are not capture names:
3443 *
3444 * ```ruby
3445 * match.deconstruct_keys([:foo]) # => {}
3446 * ```
3447 *
3448 * With `nil` given,
3449 * returns a hash of all capture names and values:
3450 *
3451 * ```ruby
3452 * match.deconstruct_keys(nil) # => {year: "2026", month: "12", day: "25"}
3453 * ```
3454 *
3455 * Returns an empty hash if no named captures were defined:
3456 *
3457 * ```ruby
3458 * regexp = /(\d{4})-(\d{2})-(\d{2})/
3459 * match = '2026-12-25'.match(regexp)
3460 * # => #<MatchData "2026-12-25" 1:"2026" 2:"12" 3:"25">
3461 * match.deconstruct_keys(nil) # => {}
3462 * ```
3463 *
3464 */
3465static VALUE
3466match_deconstruct_keys(VALUE match, VALUE keys)
3467{
3468 VALUE h;
3469 rb_len_t i;
3470
3471 match_check(match);
3472
3473 if (NIL_P(RMATCH(match)->regexp)) {
3474 return rb_hash_new();
3475 }
3476
3477 if (NIL_P(keys)) {
3478 h = rb_hash_new_capa(onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)));
3479
3480 struct named_captures_data data = { h, match, 1 };
3481
3482 onig_foreach_name(RREGEXP_PTR(RMATCH(match)->regexp), match_named_captures_iter, &data);
3483
3484 return h;
3485 }
3486
3487 Check_Type(keys, T_ARRAY);
3488
3489 if (onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)) < RARRAY_LEN(keys)) {
3490 return rb_hash_new();
3491 }
3492
3493 h = rb_hash_new_capa(RARRAY_LEN(keys));
3494
3495 for (i=0; i<RARRAY_LEN(keys); i++) {
3496 VALUE key = RARRAY_AREF(keys, i);
3497 VALUE name;
3498
3499 Check_Type(key, T_SYMBOL);
3500
3501 name = rb_sym2str(key);
3502
3503 int num = match_name_to_backref_number(match, name);
3504
3505 if (num >= 0) {
3506 rb_hash_aset(h, key, rb_reg_nth_match(num, match));
3507 }
3508 else {
3509 return h;
3510 }
3511 }
3512
3513 return h;
3514}
3515
3516/*
3517 * :markup: markdown
3518 *
3519 * call-seq:
3520 * string -> string
3521 *
3522 * Returns the target string if it was frozen;
3523 * otherwise, returns a frozen copy of the target string:
3524 *
3525 * ```ruby
3526 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3527 * match = '2026-12-25'.match(regexp)
3528 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
3529 * match.string # => "2026-12-25"
3530 * ```
3531 *
3532 */
3533
3534static VALUE
3535match_string(VALUE match)
3536{
3537 match_check(match);
3538 return RMATCH(match)->str; /* str is frozen */
3539}
3540
3542 const UChar *name;
3543 rb_len_t len;
3544};
3545
3546static int
3547match_inspect_name_iter(const OnigUChar *name, const OnigUChar *name_end,
3548 int back_num, int *back_refs, OnigRegex regex, void *arg0)
3549{
3550 struct backref_name_tag *arg = (struct backref_name_tag *)arg0;
3551 int i;
3552
3553 for (i = 0; i < back_num; i++) {
3554 arg[back_refs[i]].name = name;
3555 arg[back_refs[i]].len = name_end - name;
3556 }
3557 return 0;
3558}
3559
3560/*
3561 * :markup: markdown
3562 *
3563 * call-seq:
3564 * inspect -> string
3565 *
3566 * Returns a string representation of `self`:
3567 *
3568 * ```ruby
3569 * regexp = /(\d{4})-(\d{2})-(\d{2})/
3570 * match = '2026-12-25'.match(regexp)
3571 * match.inspect # => "#<MatchData \"2026-12-25\" 1:\"2026\" 2:\"12\" 3:\"25\">"
3572 *
3573 * match = /(ん)(に)(ち)/.match('こんにちは')
3574 * match.inspect # => "#<MatchData \"んにち\" 1:\"ん\" 2:\"に\" 3:\"ち\">"
3575 *
3576 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
3577 * match = '2026-12-25'.match(regexp)
3578 * match.inspect # => "#<MatchData \"2026-12-25\" year:\"2026\" month:\"12\" day:\"25\">"
3579 * ```
3580 *
3581 * Related: MatchData#to_s.
3582 */
3583
3584static VALUE
3585match_inspect(VALUE match)
3586{
3587 VALUE cname = rb_class_path(rb_obj_class(match));
3588 VALUE str;
3589 int i;
3590 int num_regs = RMATCH_NREGS(match);
3591 struct backref_name_tag *names;
3592 VALUE names_obj = Qnil;
3593 VALUE regexp = RMATCH(match)->regexp;
3594
3595 if (regexp == 0) {
3596 return rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)match);
3597 }
3598 else if (NIL_P(regexp)) {
3599 return rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE">",
3600 cname, rb_reg_nth_match(0, match));
3601 }
3602
3603 names = RB_ALLOCV_N(struct backref_name_tag, names_obj, num_regs);
3604 MEMZERO(names, struct backref_name_tag, num_regs);
3605
3606 onig_foreach_name(RREGEXP_PTR(regexp),
3607 match_inspect_name_iter, names);
3608
3609 str = rb_str_buf_new2("#<");
3610 rb_str_append(str, cname);
3611
3612 for (i = 0; i < num_regs; i++) {
3613 VALUE v;
3614 rb_str_buf_cat2(str, " ");
3615 if (0 < i) {
3616 if (names[i].name)
3617 rb_str_buf_cat(str, (const char *)names[i].name, names[i].len);
3618 else {
3619 rb_str_catf(str, "%d", i);
3620 }
3621 rb_str_buf_cat2(str, ":");
3622 }
3623 v = rb_reg_nth_match(i, match);
3624 if (NIL_P(v))
3625 rb_str_buf_cat2(str, "nil");
3626 else
3628 }
3629 rb_str_buf_cat2(str, ">");
3630
3631 RB_ALLOCV_END(names_obj);
3632 return str;
3633}
3634
3636
3637static int
3638read_escaped_byte(const char **pp, const char *end, onig_errmsg_buffer err)
3639{
3640 const char *p = *pp;
3641 int code;
3642 int meta_prefix = 0, ctrl_prefix = 0;
3643 size_t len;
3644
3645 if (p == end || *p++ != '\\') {
3646 errcpy(err, "too short escaped multibyte character");
3647 return -1;
3648 }
3649
3650again:
3651 if (p == end) {
3652 errcpy(err, "too short escape sequence");
3653 return -1;
3654 }
3655 switch (*p++) {
3656 case '\\': code = '\\'; break;
3657 case 'n': code = '\n'; break;
3658 case 't': code = '\t'; break;
3659 case 'r': code = '\r'; break;
3660 case 'f': code = '\f'; break;
3661 case 'v': code = '\013'; break;
3662 case 'a': code = '\007'; break;
3663 case 'e': code = '\033'; break;
3664
3665 /* \OOO */
3666 case '0': case '1': case '2': case '3':
3667 case '4': case '5': case '6': case '7':
3668 p--;
3669 code = scan_oct(p, end < p+3 ? end-p : 3, &len);
3670 p += len;
3671 break;
3672
3673 case 'x': /* \xHH */
3674 code = scan_hex(p, end < p+2 ? end-p : 2, &len);
3675 if (len < 1) {
3676 errcpy(err, "invalid hex escape");
3677 return -1;
3678 }
3679 p += len;
3680 break;
3681
3682 case 'M': /* \M-X, \M-\C-X, \M-\cX */
3683 if (meta_prefix) {
3684 errcpy(err, "duplicate meta escape");
3685 return -1;
3686 }
3687 meta_prefix = 1;
3688 if (p+1 < end && *p++ == '-' && (*p & 0x80) == 0) {
3689 if (*p == '\\') {
3690 p++;
3691 goto again;
3692 }
3693 else {
3694 code = *p++;
3695 break;
3696 }
3697 }
3698 errcpy(err, "too short meta escape");
3699 return -1;
3700
3701 case 'C': /* \C-X, \C-\M-X */
3702 if (p == end || *p++ != '-') {
3703 errcpy(err, "too short control escape");
3704 return -1;
3705 }
3706 case 'c': /* \cX, \c\M-X */
3707 if (ctrl_prefix) {
3708 errcpy(err, "duplicate control escape");
3709 return -1;
3710 }
3711 ctrl_prefix = 1;
3712 if (p < end && (*p & 0x80) == 0) {
3713 if (*p == '\\') {
3714 p++;
3715 goto again;
3716 }
3717 else {
3718 code = *p++;
3719 break;
3720 }
3721 }
3722 errcpy(err, "too short control escape");
3723 return -1;
3724
3725 default:
3726 errcpy(err, "unexpected escape sequence");
3727 return -1;
3728 }
3729 if (code < 0 || 0xff < code) {
3730 errcpy(err, "invalid escape code");
3731 return -1;
3732 }
3733
3734 if (ctrl_prefix)
3735 code &= 0x1f;
3736 if (meta_prefix)
3737 code |= 0x80;
3738
3739 *pp = p;
3740 return code;
3741}
3742
3743static int
3744unescape_escaped_nonascii(const char **pp, const char *end, rb_encoding *enc,
3745 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
3746{
3747 const char *p = *pp;
3748 int chmaxlen = rb_enc_mbmaxlen(enc);
3749 unsigned char *area = ALLOCA_N(unsigned char, chmaxlen);
3750 char *chbuf = (char *)area;
3751 int chlen = 0;
3752 int byte;
3753 int l;
3754
3755 memset(chbuf, 0, chmaxlen);
3756
3757 byte = read_escaped_byte(&p, end, err);
3758 if (byte == -1) {
3759 return -1;
3760 }
3761
3762 area[chlen++] = byte;
3763 while (chlen < chmaxlen &&
3764 MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc))) {
3765 byte = read_escaped_byte(&p, end, err);
3766 if (byte == -1) {
3767 return -1;
3768 }
3769 area[chlen++] = byte;
3770 }
3771
3772 l = rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc);
3773 if (MBCLEN_INVALID_P(l)) {
3774 errcpy(err, "invalid multibyte escape");
3775 return -1;
3776 }
3777 if (1 < chlen || (area[0] & 0x80)) {
3778 rb_str_buf_cat(buf, chbuf, chlen);
3779
3780 if (*encp == 0)
3781 *encp = enc;
3782 else if (*encp != enc) {
3783 errcpy(err, "escaped non ASCII character in UTF-8 regexp");
3784 return -1;
3785 }
3786 }
3787 else {
3788 char escbuf[5];
3789 snprintf(escbuf, sizeof(escbuf), "\\x%02X", area[0]&0xff);
3790 rb_str_buf_cat(buf, escbuf, 4);
3791 }
3792 *pp = p;
3793 return 0;
3794}
3795
3796static int
3797check_unicode_range(unsigned long code, onig_errmsg_buffer err)
3798{
3799 if ((0xd800 <= code && code <= 0xdfff) || /* Surrogates */
3800 0x10ffff < code) {
3801 errcpy(err, "invalid Unicode range");
3802 return -1;
3803 }
3804 return 0;
3805}
3806
3807static int
3808append_utf8(unsigned long uv,
3809 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
3810{
3811 if (check_unicode_range(uv, err) != 0)
3812 return -1;
3813 if (uv < 0x80) {
3814 char escbuf[5];
3815 snprintf(escbuf, sizeof(escbuf), "\\x%02X", (int)uv);
3816 rb_str_buf_cat(buf, escbuf, 4);
3817 }
3818 else {
3819 int len;
3820 char utf8buf[6];
3821 len = rb_uv_to_utf8(utf8buf, uv);
3822 rb_str_buf_cat(buf, utf8buf, len);
3823
3824 if (*encp == 0)
3825 *encp = rb_utf8_encoding();
3826 else if (*encp != rb_utf8_encoding()) {
3827 errcpy(err, "UTF-8 character in non UTF-8 regexp");
3828 return -1;
3829 }
3830 }
3831 return 0;
3832}
3833
3834static int
3835unescape_unicode_list(const char **pp, const char *end,
3836 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
3837{
3838 const char *p = *pp;
3839 int has_unicode = 0;
3840 unsigned long code;
3841 size_t len;
3842
3843 while (p < end && ISSPACE(*p)) p++;
3844
3845 while (1) {
3846 code = ruby_scan_hex(p, end-p, &len);
3847 if (len == 0)
3848 break;
3849 if (6 < len) { /* max 10FFFF */
3850 errcpy(err, "invalid Unicode range");
3851 return -1;
3852 }
3853 p += len;
3854 if (append_utf8(code, buf, encp, err) != 0)
3855 return -1;
3856 has_unicode = 1;
3857
3858 while (p < end && ISSPACE(*p)) p++;
3859 }
3860
3861 if (has_unicode == 0) {
3862 errcpy(err, "invalid Unicode list");
3863 return -1;
3864 }
3865
3866 *pp = p;
3867
3868 return 0;
3869}
3870
3871static int
3872unescape_unicode_bmp(const char **pp, const char *end,
3873 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
3874{
3875 const char *p = *pp;
3876 size_t len;
3877 unsigned long code;
3878
3879 if (end < p+4) {
3880 errcpy(err, "invalid Unicode escape");
3881 return -1;
3882 }
3883 code = ruby_scan_hex(p, 4, &len);
3884 if (len != 4) {
3885 errcpy(err, "invalid Unicode escape");
3886 return -1;
3887 }
3888 if (append_utf8(code, buf, encp, err) != 0)
3889 return -1;
3890 *pp = p + 4;
3891 return 0;
3892}
3893
3894static int
3895unescape_nonascii0(const char **pp, const char *end, rb_encoding *enc,
3896 VALUE buf, rb_encoding **encp, int *has_property,
3897 onig_errmsg_buffer err, int options, int recurse)
3898{
3899 const char *p = *pp;
3900 unsigned char c;
3901 char smallbuf[2];
3902 int in_char_class = 0;
3903 int parens = 1; /* ignored unless recurse is true */
3904 int extended_mode = options & ONIG_OPTION_EXTEND;
3905
3906begin_scan:
3907 while (p < end) {
3908 int chlen = rb_enc_precise_mbclen(p, end, enc);
3909 if (!MBCLEN_CHARFOUND_P(chlen)) {
3910 invalid_multibyte:
3911 errcpy(err, "invalid multibyte character");
3912 return -1;
3913 }
3914 chlen = MBCLEN_CHARFOUND_LEN(chlen);
3915 if (1 < chlen || (*p & 0x80)) {
3916 multibyte:
3917 rb_str_buf_cat(buf, p, chlen);
3918 p += chlen;
3919 if (*encp == 0)
3920 *encp = enc;
3921 else if (*encp != enc) {
3922 errcpy(err, "non ASCII character in UTF-8 regexp");
3923 return -1;
3924 }
3925 continue;
3926 }
3927
3928 switch (c = *p++) {
3929 case '\\':
3930 if (p == end) {
3931 errcpy(err, "too short escape sequence");
3932 return -1;
3933 }
3934 chlen = rb_enc_precise_mbclen(p, end, enc);
3935 if (!MBCLEN_CHARFOUND_P(chlen)) {
3936 goto invalid_multibyte;
3937 }
3938 if ((chlen = MBCLEN_CHARFOUND_LEN(chlen)) > 1) {
3939 /* include the previous backslash */
3940 --p;
3941 ++chlen;
3942 goto multibyte;
3943 }
3944 switch (c = *p++) {
3945 case '1': case '2': case '3':
3946 case '4': case '5': case '6': case '7': /* \O, \OO, \OOO or backref */
3947 {
3948 size_t len = end-(p-1), octlen;
3949 if (ruby_scan_oct(p-1, len < 3 ? len : 3, &octlen) <= 0177) {
3950 /* backref or 7bit octal.
3951 no need to unescape anyway.
3952 re-escaping may break backref */
3953 goto escape_asis;
3954 }
3955 }
3956 /* xxx: How about more than 199 subexpressions? */
3957
3958 case '0': /* \0, \0O, \0OO */
3959
3960 case 'x': /* \xHH */
3961 case 'c': /* \cX, \c\M-X */
3962 case 'C': /* \C-X, \C-\M-X */
3963 case 'M': /* \M-X, \M-\C-X, \M-\cX */
3964 p = p-2;
3965 if (rb_is_usascii_enc(enc)) {
3966 const char *pbeg = p;
3967 int byte = read_escaped_byte(&p, end, err);
3968 if (byte == -1) return -1;
3969 c = byte;
3970 rb_str_buf_cat(buf, pbeg, p-pbeg);
3971 }
3972 else {
3973 if (unescape_escaped_nonascii(&p, end, enc, buf, encp, err) != 0)
3974 return -1;
3975 }
3976 break;
3977
3978 case 'u':
3979 if (p == end) {
3980 errcpy(err, "too short escape sequence");
3981 return -1;
3982 }
3983 if (*p == '{') {
3984 /* \u{H HH HHH HHHH HHHHH HHHHHH ...} */
3985 p++;
3986 if (unescape_unicode_list(&p, end, buf, encp, err) != 0)
3987 return -1;
3988 if (p == end || *p++ != '}') {
3989 errcpy(err, "invalid Unicode list");
3990 return -1;
3991 }
3992 break;
3993 }
3994 else {
3995 /* \uHHHH */
3996 if (unescape_unicode_bmp(&p, end, buf, encp, err) != 0)
3997 return -1;
3998 break;
3999 }
4000
4001 case 'p': /* \p{Hiragana} */
4002 case 'P':
4003 if (!*encp) {
4004 *has_property = 1;
4005 }
4006 goto escape_asis;
4007
4008 default: /* \n, \\, \d, \9, etc. */
4009escape_asis:
4010 smallbuf[0] = '\\';
4011 smallbuf[1] = c;
4012 rb_str_buf_cat(buf, smallbuf, 2);
4013 break;
4014 }
4015 break;
4016
4017 case '#':
4018 if (extended_mode && !in_char_class) {
4019 /* consume and ignore comment in extended regexp */
4020 while ((p < end) && ((c = *p++) != '\n')) {
4021 if ((c & 0x80) && !*encp && enc == rb_utf8_encoding()) {
4022 *encp = enc;
4023 }
4024 }
4025 rb_str_buf_cat(buf, "(?#)", 4);
4026 break;
4027 }
4028 rb_str_buf_cat(buf, (char *)&c, 1);
4029 break;
4030 case '[':
4031 in_char_class++;
4032 rb_str_buf_cat(buf, (char *)&c, 1);
4033 break;
4034 case ']':
4035 if (in_char_class) {
4036 in_char_class--;
4037 }
4038 rb_str_buf_cat(buf, (char *)&c, 1);
4039 break;
4040 case ')':
4041 rb_str_buf_cat(buf, (char *)&c, 1);
4042 if (!in_char_class && recurse) {
4043 if (--parens == 0) {
4044 *pp = p;
4045 return 0;
4046 }
4047 }
4048 break;
4049 case '(':
4050 if (!in_char_class && p + 1 < end && *p == '?') {
4051 if (*(p+1) == '#') {
4052 /* (?# is comment inside any regexp, and content inside should be ignored */
4053 const char *orig_p = p;
4054 int cont = 1;
4055
4056 while (cont && (p < end)) {
4057 switch (c = *p++) {
4058 default:
4059 if (!(c & 0x80)) break;
4060 if (!*encp && enc == rb_utf8_encoding()) {
4061 *encp = enc;
4062 }
4063 --p;
4064 /* fallthrough */
4065 case '\\':
4066 chlen = rb_enc_precise_mbclen(p, end, enc);
4067 if (!MBCLEN_CHARFOUND_P(chlen)) {
4068 goto invalid_multibyte;
4069 }
4070 p += MBCLEN_CHARFOUND_LEN(chlen);
4071 break;
4072 case ')':
4073 cont = 0;
4074 break;
4075 }
4076 }
4077
4078 if (cont) {
4079 /* unterminated (?#, rewind so it is syntax error */
4080 p = orig_p;
4081 c = '(';
4082 rb_str_buf_cat(buf, (char *)&c, 1);
4083 }
4084 else {
4085 rb_str_buf_cat(buf, "(?#)", 4);
4086 }
4087 break;
4088 }
4089 else {
4090 /* potential change of extended option */
4091 int invert = 0;
4092 int local_extend = 0;
4093 const char *s;
4094
4095 if (recurse) {
4096 parens++;
4097 }
4098
4099 for (s = p+1; s < end; s++) {
4100 switch(*s) {
4101 case 'x':
4102 local_extend = invert ? -1 : 1;
4103 break;
4104 case '-':
4105 invert = 1;
4106 break;
4107 case ':':
4108 case ')':
4109 if (local_extend == 0 ||
4110 (local_extend == -1 && !extended_mode) ||
4111 (local_extend == 1 && extended_mode)) {
4112 /* no changes to extended flag */
4113 goto fallthrough;
4114 }
4115
4116 if (*s == ':') {
4117 /* change extended flag until ')' */
4118 int local_options = options;
4119 if (local_extend == 1) {
4120 local_options |= ONIG_OPTION_EXTEND;
4121 }
4122 else {
4123 local_options &= ~ONIG_OPTION_EXTEND;
4124 }
4125
4126 rb_str_buf_cat(buf, (char *)&c, 1);
4127 int ret = unescape_nonascii0(&p, end, enc, buf, encp,
4128 has_property, err,
4129 local_options, 1);
4130 if (ret < 0) return ret;
4131 goto begin_scan;
4132 }
4133 else {
4134 /* change extended flag for rest of expression */
4135 extended_mode = local_extend == 1;
4136 goto fallthrough;
4137 }
4138 case 'i':
4139 case 'm':
4140 case 'a':
4141 case 'd':
4142 case 'u':
4143 /* other option flags, ignored during scanning */
4144 break;
4145 default:
4146 /* other character, no extended flag change*/
4147 goto fallthrough;
4148 }
4149 }
4150 }
4151 }
4152 else if (!in_char_class && recurse) {
4153 parens++;
4154 }
4155 /* FALLTHROUGH */
4156 default:
4157fallthrough:
4158 rb_str_buf_cat(buf, (char *)&c, 1);
4159 break;
4160 }
4161 }
4162
4163 if (recurse) {
4164 *pp = p;
4165 }
4166 return 0;
4167}
4168
4169static int
4170unescape_nonascii(const char *p, const char *end, rb_encoding *enc,
4171 VALUE buf, rb_encoding **encp, int *has_property,
4172 onig_errmsg_buffer err, int options)
4173{
4174 return unescape_nonascii0(&p, end, enc, buf, encp, has_property,
4175 err, options, 0);
4176}
4177
4178static VALUE
4179rb_reg_preprocess(const char *p, const char *end, rb_encoding *enc,
4180 rb_encoding **fixed_enc, onig_errmsg_buffer err, int options)
4181{
4182 VALUE buf;
4183 int has_property = 0;
4184
4185 buf = rb_str_buf_new(0);
4186
4187 if (rb_enc_asciicompat(enc))
4188 *fixed_enc = 0;
4189 else {
4190 *fixed_enc = enc;
4191 rb_enc_associate(buf, enc);
4192 }
4193
4194 if (unescape_nonascii(p, end, enc, buf, fixed_enc, &has_property, err, options) != 0)
4195 return Qnil;
4196
4197 if (has_property && !*fixed_enc) {
4198 *fixed_enc = enc;
4199 }
4200
4201 if (*fixed_enc) {
4202 rb_enc_associate(buf, *fixed_enc);
4203 }
4204
4205 return buf;
4206}
4207
4208VALUE
4209rb_reg_check_preprocess(VALUE str)
4210{
4211 rb_encoding *fixed_enc = 0;
4212 onig_errmsg_buffer err = "";
4213 VALUE buf;
4214 char *p, *end;
4215 rb_encoding *enc;
4216
4217 StringValue(str);
4218 p = RSTRING_PTR(str);
4219 end = p + RSTRING_LEN(str);
4220 enc = rb_enc_get(str);
4221
4222 buf = rb_reg_preprocess(p, end, enc, &fixed_enc, err, 0);
4223 RB_GC_GUARD(str);
4224
4225 if (NIL_P(buf)) {
4226 return rb_reg_error_desc(str, 0, err);
4227 }
4228 return Qnil;
4229}
4230
4231static VALUE
4232rb_reg_preprocess_dregexp(VALUE ary, int options)
4233{
4234 rb_encoding *fixed_enc = 0;
4235 rb_encoding *regexp_enc = 0;
4236 onig_errmsg_buffer err = "";
4237 int i;
4238 VALUE result = 0;
4239 rb_encoding *ascii8bit = rb_ascii8bit_encoding();
4240
4241 if (RARRAY_LEN(ary) == 0) {
4242 rb_raise(rb_eArgError, "no arguments given");
4243 }
4244
4245 for (i = 0; i < RARRAY_LEN(ary); i++) {
4246 VALUE str = RARRAY_AREF(ary, i);
4247 VALUE buf;
4248 char *p, *end;
4249 rb_encoding *src_enc;
4250
4251 src_enc = rb_enc_get(str);
4252 if (options & ARG_ENCODING_NONE &&
4253 src_enc != ascii8bit) {
4254 if (rb_enc_str_coderange(str) != ENC_CODERANGE_7BIT)
4255 rb_raise(rb_eRegexpError, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
4256 else
4257 src_enc = ascii8bit;
4258 }
4259
4260 StringValue(str);
4261 p = RSTRING_PTR(str);
4262 end = p + RSTRING_LEN(str);
4263
4264 buf = rb_reg_preprocess(p, end, src_enc, &fixed_enc, err, options);
4265
4266 if (NIL_P(buf))
4267 rb_raise(rb_eArgError, "%s", err);
4268
4269 if (fixed_enc != 0) {
4270 if (regexp_enc != 0 && regexp_enc != fixed_enc) {
4271 rb_raise(rb_eRegexpError, "encoding mismatch in dynamic regexp : %s and %s",
4272 rb_enc_name(regexp_enc), rb_enc_name(fixed_enc));
4273 }
4274 regexp_enc = fixed_enc;
4275 }
4276
4277 if (!result)
4278 result = rb_str_new3(str);
4279 else
4280 rb_str_buf_append(result, str);
4281 }
4282 if (regexp_enc) {
4283 rb_enc_associate(result, regexp_enc);
4284 }
4285
4286 return result;
4287}
4288
4289static void
4290rb_reg_initialize_check(VALUE obj)
4291{
4292 rb_check_frozen(obj);
4293 if (FL_TEST_RAW(obj, RREGEXP_INITIALIZED)) {
4294 rb_raise(rb_eTypeError, "already initialized regexp");
4295 }
4296}
4297
4298static int
4299rb_reg_initialize(VALUE obj, const char *s, rb_len_t len, rb_encoding *enc,
4300 int options, onig_errmsg_buffer err,
4301 const char *sourcefile, int sourceline)
4302{
4303 struct RRegexp *re = RREGEXP(obj);
4304 VALUE unescaped;
4305 rb_encoding *fixed_enc = 0;
4306 rb_encoding *a_enc = rb_ascii8bit_encoding();
4307
4308 rb_reg_initialize_check(obj);
4309
4310 if (rb_enc_dummy_p(enc)) {
4311 errcpy(err, "can't make regexp with dummy encoding");
4312 return -1;
4313 }
4314
4315 unescaped = rb_reg_preprocess(s, s+len, enc, &fixed_enc, err, options);
4316 if (NIL_P(unescaped))
4317 return -1;
4318
4319 if (fixed_enc) {
4320 if ((fixed_enc != enc && (options & ARG_ENCODING_FIXED)) ||
4321 (fixed_enc != a_enc && (options & ARG_ENCODING_NONE))) {
4322 errcpy(err, "incompatible character encoding");
4323 return -1;
4324 }
4325 if (fixed_enc != a_enc) {
4326 options |= ARG_ENCODING_FIXED;
4327 enc = fixed_enc;
4328 }
4329 }
4330 else if (!(options & ARG_ENCODING_FIXED)) {
4331 enc = rb_usascii_encoding();
4332 }
4333
4334 regex_t reg;
4335 bool success = make_regexp(&reg, RSTRING_PTR(unescaped), RSTRING_LEN(unescaped), enc,
4336 options & ARG_REG_OPTION_MASK, err,
4337 sourcefile, sourceline);
4338 if (!success) {
4339 reg_warn_kept();
4340 return -1;
4341 }
4342 if (OBJ_FROZEN(obj) || FL_TEST_RAW(obj, RREGEXP_INITIALIZED)) {
4343 onig_free_body(&reg);
4344 rb_reg_initialize_check(obj);
4345 }
4346 *RREGEXP_PTR(obj) = reg;
4347
4348 rb_enc_associate((VALUE)re, enc);
4349 if ((options & ARG_ENCODING_FIXED) || fixed_enc) {
4350 re->basic.flags |= KCODE_FIXED;
4351 }
4352 if (options & ARG_ENCODING_NONE) {
4353 re->basic.flags |= REG_ENCODING_NONE;
4354 }
4355 FL_SET_RAW(obj, RREGEXP_INITIALIZED);
4356 /* after the flag, so that GC frees the pattern if a warning raises */
4357 reg_warn_kept();
4358
4359 if (RBASIC_CLASS(obj) == rb_cRegexp) {
4360 OBJ_FREEZE(obj);
4361 }
4362 RB_GC_GUARD(unescaped);
4363 return 0;
4364}
4365
4366static void
4367reg_set_source(VALUE reg, VALUE str, rb_encoding *enc)
4368{
4369 rb_encoding *regenc = rb_enc_get(reg);
4370
4371 if (regenc != enc) {
4372 VALUE dup = rb_str_dup(str);
4373 str = rb_enc_associate(dup, enc = regenc);
4374 }
4375 str = rb_fstring(str);
4376 RB_OBJ_WRITE(reg, &RREGEXP(reg)->src, str);
4377}
4378
4379static int
4380rb_reg_initialize_str(VALUE obj, VALUE str, int options, onig_errmsg_buffer err,
4381 const char *sourcefile, int sourceline)
4382{
4383 int ret;
4384 rb_encoding *str_enc = rb_enc_get(str), *enc = str_enc;
4385 if (options & ARG_ENCODING_NONE) {
4386 rb_encoding *ascii8bit = rb_ascii8bit_encoding();
4387 if (enc != ascii8bit) {
4388 if (rb_enc_str_coderange(str) != ENC_CODERANGE_7BIT) {
4389 errcpy(err, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
4390 return -1;
4391 }
4392 enc = ascii8bit;
4393 }
4394 }
4395 ret = rb_reg_initialize(obj, RSTRING_PTR(str), RSTRING_LEN(str), enc,
4396 options, err, sourcefile, sourceline);
4397 if (ret == 0) reg_set_source(obj, str, str_enc);
4398 return ret;
4399}
4400
4401VALUE
4402rb_reg_s_alloc(VALUE klass)
4403{
4404 NEWOBJ_OF(re, struct RRegexp, klass, T_REGEXP, sizeof(struct RRegexp_and_re_pattern_buffer));
4405
4406 MEMZERO(RREGEXP_PTR((VALUE)re), struct re_pattern_buffer, 1);
4407 RB_OBJ_WRITE((VALUE)re, &re->src, 0);
4408 re->variants = NULL;
4409
4410 return (VALUE)re;
4411}
4412
4413VALUE
4414rb_reg_alloc(void)
4415{
4416 return rb_reg_s_alloc(rb_cRegexp);
4417}
4418
4419VALUE
4420rb_reg_new_str(VALUE s, int options)
4421{
4422 return rb_reg_init_str(rb_reg_alloc(), s, options);
4423}
4424
4425VALUE
4426rb_reg_init_str(VALUE re, VALUE s, int options)
4427{
4428 onig_errmsg_buffer err = "";
4429
4430 if (rb_reg_initialize_str(re, s, options, err, NULL, 0) != 0) {
4431 rb_reg_raise_str(s, options, err);
4432 }
4433
4434 return re;
4435}
4436
4437static VALUE
4438rb_reg_init_str_enc(VALUE re, VALUE s, rb_encoding *enc, int options)
4439{
4440 onig_errmsg_buffer err = "";
4441
4442 if (rb_reg_initialize(re, RSTRING_PTR(s), RSTRING_LEN(s),
4443 enc, options, err, NULL, 0) != 0) {
4444 rb_reg_raise_str(s, options, err);
4445 }
4446 reg_set_source(re, s, enc);
4447
4448 return re;
4449}
4450
4451VALUE
4452rb_reg_new_from_values(rb_len_t cnt, const VALUE *elements, int opt)
4453{
4454 const VALUE ary = rb_ary_tmp_new_from_values(0, cnt, elements);
4455 VALUE val = rb_reg_new_str(rb_reg_preprocess_dregexp(ary, opt), opt);
4456 rb_ary_clear(ary);
4457 return val;
4458}
4459
4460VALUE
4461rb_enc_reg_new(const char *s, rb_len_t len, rb_encoding *enc, int options)
4462{
4463 VALUE re = rb_reg_alloc();
4464 onig_errmsg_buffer err = "";
4465
4466 if (rb_reg_initialize(re, s, len, enc, options, err, NULL, 0) != 0) {
4467 rb_enc_reg_raise(s, len, enc, options, err);
4468 }
4469 RB_OBJ_WRITE(re, &RREGEXP(re)->src, rb_fstring(rb_enc_str_new(s, len, enc)));
4470
4471 return re;
4472}
4473
4474VALUE
4475rb_reg_new(const char *s, rb_len_t len, int options)
4476{
4477 return rb_enc_reg_new(s, len, rb_ascii8bit_encoding(), options);
4478}
4479
4480VALUE
4481rb_reg_compile(VALUE str, int options, const char *sourcefile, int sourceline)
4482{
4483 VALUE re = rb_reg_alloc();
4484 onig_errmsg_buffer err = "";
4485
4486 if (!str) str = rb_str_new(0,0);
4487 if (rb_reg_initialize_str(re, str, options, err, sourcefile, sourceline) != 0) {
4488 rb_set_errinfo(rb_reg_error_desc(str, options, err));
4489 return Qnil;
4490 }
4491 return re;
4492}
4493
4494static VALUE reg_cache;
4495
4496VALUE
4498{
4499 if (rb_ractor_main_p()) {
4500 if (reg_cache && RREGEXP_SRC_LEN(reg_cache) == RSTRING_LEN(str)
4501 && ENCODING_GET(reg_cache) == ENCODING_GET(str)
4502 && memcmp(RREGEXP_SRC_PTR(reg_cache), RSTRING_PTR(str), RSTRING_LEN(str)) == 0)
4503 return reg_cache;
4504
4505 return reg_cache = rb_reg_new_str(str, 0);
4506 }
4507 else {
4508 return rb_reg_new_str(str, 0);
4509 }
4510}
4511
4512static st_index_t reg_hash(VALUE re);
4513/*
4514 * call-seq:
4515 * hash -> integer
4516 *
4517 * Returns the integer hash value for +self+.
4518 *
4519 * Related: Object#hash.
4520 *
4521 */
4522
4523VALUE
4524rb_reg_hash(VALUE re)
4525{
4526 st_index_t hashval = reg_hash(re);
4527 return ST2FIX(hashval);
4528}
4529
4530static st_index_t
4531reg_hash(VALUE re)
4532{
4533 st_index_t hashval;
4534
4535 rb_reg_check(re);
4536 hashval = RREGEXP_PTR(re)->options;
4537 hashval = rb_hash_uint(hashval, rb_memhash(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re)));
4538 return rb_hash_end(hashval);
4539}
4540
4541
4542/*
4543 * call-seq:
4544 * self == other -> true or false
4545 *
4546 * Returns whether +other+ is another \Regexp whose pattern,
4547 * flags, and encoding are the same as +self+:
4548 *
4549 * /foo/ == Regexp.new('foo') # => true
4550 * /foo/ == /foo/i # => false
4551 * /foo/ == Regexp.new('food') # => false
4552 * /foo/ == Regexp.new("abc".force_encoding("euc-jp")) # => false
4553 *
4554 */
4555
4556VALUE
4557rb_reg_equal(VALUE re1, VALUE re2)
4558{
4559 if (re1 == re2) return Qtrue;
4560 if (!RB_TYPE_P(re2, T_REGEXP)) return Qfalse;
4561 rb_reg_check(re1); rb_reg_check(re2);
4562
4563 // src is a fstring, so a pointer comparison is enough
4564 RUBY_ASSERT(FL_TEST_RAW(RREGEXP_SRC(re1), RSTRING_FSTR));
4565 RUBY_ASSERT(FL_TEST_RAW(RREGEXP_SRC(re2), RSTRING_FSTR));
4566
4567 if (FL_TEST(re1, KCODE_FIXED) != FL_TEST(re2, KCODE_FIXED)) return Qfalse;
4568 if (RREGEXP_PTR(re1)->options != RREGEXP_PTR(re2)->options) return Qfalse;
4569 if (RREGEXP_SRC_LEN(re1) != RREGEXP_SRC_LEN(re2)) return Qfalse;
4570 if (ENCODING_GET(re1) != ENCODING_GET(re2)) return Qfalse;
4571
4572 if (RREGEXP_SRC(re1) == RREGEXP_SRC(re2)) return Qtrue;
4573 if (RREGEXP_SRC_PTR(re1) == RREGEXP_SRC_PTR(re2)) return Qtrue;
4574 return RBOOL(memcmp(RREGEXP_SRC_PTR(re1), RREGEXP_SRC_PTR(re2), RREGEXP_SRC_LEN(re1)) == 0);
4575}
4576
4577/*
4578 * :markup: markdown
4579 *
4580 * call-seq:
4581 * hash -> integer
4582 *
4583 * Returns the integer hash value for `self`,
4584 * based on its target string, regexp, match, and captures.
4585 *
4586 * See also Object#hash.
4587 *
4588 */
4589
4590static VALUE
4591match_hash(VALUE match)
4592{
4593 st_index_t hashval;
4594
4595 match_check(match);
4596 hashval = rb_hash_start(rb_str_hash(RMATCH(match)->str));
4597 hashval = rb_hash_uint(hashval, reg_hash(match_regexp(match)));
4598 int num_regs = RMATCH_NREGS(match);
4599 hashval = rb_hash_uint(hashval, num_regs);
4600 hashval = rb_hash_uint(hashval, rb_memhash(RMATCH_BEG_PTR(match), num_regs * sizeof(OnigPosition)));
4601 hashval = rb_hash_uint(hashval, rb_memhash(RMATCH_END_PTR(match), num_regs * sizeof(OnigPosition)));
4602 hashval = rb_hash_end(hashval);
4603 return ST2FIX(hashval);
4604}
4605
4606/*
4607 * :markup: markdown
4608 *
4609 * call-seq:
4610 * self == object -> true or false
4611 *
4612 * Returns whether `object` is a \MatchData object
4613 * whose #string, #regexp, and #begin values are the same as those of `self`:
4614 *
4615 * ```ruby
4616 * regexp = /a/
4617 * s = 'aba'
4618 * match0 = regexp.match(s)
4619 * match1 = regexp.match(s, 2)
4620 * match0[0] # => "a"
4621 * match1[0] # => "a"
4622 * match0.begin(0) # => 0
4623 * match1.begin(0) # => 2
4624 * match0 == match0 # => true
4625 * match0 == match1 # => false
4626 * ```
4627 *
4628 */
4629
4630static VALUE
4631match_equal(VALUE match1, VALUE match2)
4632{
4633 if (match1 == match2) return Qtrue;
4634 if (!RB_TYPE_P(match2, T_MATCH)) return Qfalse;
4635 if (!RMATCH(match1)->regexp || !RMATCH(match2)->regexp) return Qfalse;
4636 if (!rb_str_equal(RMATCH(match1)->str, RMATCH(match2)->str)) return Qfalse;
4637 if (!rb_reg_equal(match_regexp(match1), match_regexp(match2))) return Qfalse;
4638 int num_regs = RMATCH_NREGS(match1);
4639 if (num_regs != RMATCH_NREGS(match2)) return Qfalse;
4640 if (memcmp(RMATCH_BEG_PTR(match1), RMATCH_BEG_PTR(match2), num_regs * sizeof(OnigPosition))) return Qfalse;
4641 if (memcmp(RMATCH_END_PTR(match1), RMATCH_END_PTR(match2), num_regs * sizeof(OnigPosition))) return Qfalse;
4642 return Qtrue;
4643}
4644
4645/*
4646 * :markup: markdown
4647 *
4648 * call-seq:
4649 * integer_at(n, radix = 10) -> integer or nil
4650 * integer_at(name, radix = 10) -> integer or nil
4651 *
4652 * Returns a captured substring converted to an integer;
4653 * the substring is interpreted as a numeric string in the given `radix`.
4654 *
4655 * With integer index `n` given,
4656 * returns the `n`th capture converted to an integer:
4657 *
4658 * ```ruby
4659 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
4660 * match = '2026-12-25'.match(regexp)
4661 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
4662 * match[0] # => "2026-12-25"
4663 * match.integer_at(0) # => 2026 # Stops interpreting at the hyphen.
4664 * match.integer_at(1) # => 2026
4665 * match.integer_at(2) # => 12
4666 * match.integer_at(3) # => 25
4667 * match.integer_at(-1) # => 25 # For negative n, counts backwards in the captures.
4668 * match.integer_at(4) # => nil
4669 * ```
4670 *
4671 * With string or symbol `name` given,
4672 * returns the named capture converted to an integer:
4673 *
4674 * ```ruby
4675 * regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
4676 * match = '2026-12-25'.match(regexp)
4677 * # => #<MatchData "2026-12-25" year:"2026" month:"12" day:"25">
4678 * match.integer_at(:year) # => 2026
4679 * match.integer_at('month') # => 12
4680 * match.integer_at(:nosuch) # Raises IndexError: undefined group name reference: nosuch.
4681 * ```
4682 *
4683 * Returns `nil` if there were no captures.
4684 *
4685 * For both forms above, the string is converted in the given `radix`:
4686 *
4687 * ```ruby
4688 * match = /\d+/.match('11')
4689 * # => #<MatchData "11">
4690 * match.integer_at(0) # => 11
4691 * match.integer_at(0, 2) # => 3
4692 * match.integer_at(0, 8) # => 9
4693 * match.integer_at(0, 16) # => 17
4694 * match.integer_at(0, 1) # Raises ArgumentError: invalid radix 1.
4695 * ```
4696 *
4697 * Related: MatchData#[], String#to_i.
4698 */
4699static VALUE
4700match_integer_at(int argc, VALUE *argv, VALUE match)
4701{
4702 match_check(match);
4703
4704 int base = 10;
4705 VALUE idx;
4706 int nth;
4707
4708 argc = rb_check_arity(argc, 1, 2);
4709 if (FIXNUM_P(idx = argv[0])) {
4710 nth = NUM2INT(idx);
4711 }
4712 else if ((nth = namev_to_backref_number(match, idx)) < 0) {
4713 name_to_backref_error(idx);
4714 }
4715
4716 if (argc > 1 && (base = NUM2INT(argv[1])) < 0) {
4717 rb_raise(rb_eArgError, "invalid radix %d", base);
4718 }
4719
4720 if (nth >= RMATCH_NREGS(match)) return Qnil;
4721 if (nth < 0 && (nth += RMATCH_NREGS(match)) <= 0) return Qnil;
4722
4723 rb_len_t start = RMATCH_BEG(match, nth), end = RMATCH_END(match, nth);
4724 if (start < 0) return Qnil;
4725 RUBY_ASSERT(start <= end, "%"PRIdLEN" > %"PRIdLEN, start, end);
4726
4727 VALUE str = RMATCH(match)->str;
4728 RUBY_ASSERT(end <= RSTRING_LEN(str), "%"PRIdLEN" > %"PRIdLEN, end, RSTRING_LEN(str));
4729
4730 char *endp;
4731 return rb_int_parse_cstr(RSTRING_PTR(str) + start, end - start, &endp, NULL,
4732 base, RB_INT_PARSE_DEFAULT);
4733}
4734
4735static VALUE
4736reg_operand(VALUE s, int check)
4737{
4738 if (SYMBOL_P(s)) {
4739 return rb_sym2str(s);
4740 }
4741 else if (RB_TYPE_P(s, T_STRING)) {
4742 return s;
4743 }
4744 else {
4745 return check ? rb_str_to_str(s) : rb_check_string_type(s);
4746 }
4747}
4748
4749static rb_len_t
4750reg_match_pos(VALUE re, VALUE *strp, rb_len_t pos, VALUE* set_match)
4751{
4752 VALUE str = *strp;
4753
4754 if (NIL_P(str)) {
4755 rb_backref_set(Qnil);
4756 return -1;
4757 }
4758 *strp = str = reg_operand(str, TRUE);
4759 if (pos != 0) {
4760 if (pos < 0) {
4761 VALUE l = rb_str_length(str);
4762 pos += NUM2INT(l);
4763 if (pos < 0) {
4764 rb_backref_set(Qnil);
4765 return pos;
4766 }
4767 }
4768 pos = rb_str_offset(str, pos);
4769 }
4770 return rb_reg_search_set_match(re, str, pos, 0, 1, set_match);
4771}
4772
4773/*
4774 * call-seq:
4775 * self =~ other -> integer or nil
4776 *
4777 * Returns the integer index (in characters) of the first match
4778 * for +self+ and +other+, or +nil+ if none;
4779 * updates {Regexp-related global variables}[rdoc-ref:Regexp@Global+Variables].
4780 *
4781 * /at/ =~ 'input data' # => 7
4782 * $~ # => #<MatchData "at">
4783 * /ax/ =~ 'input data' # => nil
4784 * $~ # => nil
4785 *
4786 * Assigns named captures to local variables of the same names
4787 * if and only if +self+:
4788 *
4789 * - Is a regexp literal;
4790 * see {Regexp Literals}[rdoc-ref:syntax/literals.rdoc@Regexp+Literals].
4791 * - Does not contain interpolations;
4792 * see {Regexp interpolation}[rdoc-ref:Regexp@Interpolation+Mode].
4793 * - Is at the left of the expression.
4794 *
4795 * Example:
4796 *
4797 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ ' x = y '
4798 * p lhs # => "x"
4799 * p rhs # => "y"
4800 *
4801 * Assigns +nil+ if not matched:
4802 *
4803 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ ' x = '
4804 * p lhs # => nil
4805 * p rhs # => nil
4806 *
4807 * Does not make local variable assignments if +self+ is not a regexp literal:
4808 *
4809 * r = /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
4810 * r =~ ' x = y '
4811 * p foo # Undefined local variable
4812 * p bar # Undefined local variable
4813 *
4814 * The assignment does not occur if the regexp is not at the left:
4815 *
4816 * ' x = y ' =~ /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
4817 * p foo, foo # Undefined local variables
4818 *
4819 * A regexp interpolation, <tt>#{}</tt>, also disables
4820 * the assignment:
4821 *
4822 * r = /(?<foo>\w+)/
4823 * /(?<foo>\w+)\s*=\s*#{r}/ =~ 'x = y'
4824 * p foo # Undefined local variable
4825 *
4826 */
4827
4828VALUE
4829rb_reg_match(VALUE re, VALUE str)
4830{
4831 rb_len_t pos = reg_match_pos(re, &str, 0, NULL);
4832 if (pos < 0) return Qnil;
4833 pos = rb_str_sublen(str, pos);
4834 return LEN2NUM(pos);
4835}
4836
4837/*
4838 * call-seq:
4839 * self === other -> true or false
4840 *
4841 * Returns whether +self+ finds a match in +other+:
4842 *
4843 * /^[a-z]*$/ === 'HELLO' # => false
4844 * /^[A-Z]*$/ === 'HELLO' # => true
4845 *
4846 * This method is called in case statements:
4847 *
4848 * s = 'HELLO'
4849 * case s
4850 * when /\A[a-z]*\z/; print "Lower case\n"
4851 * when /\A[A-Z]*\z/; print "Upper case\n"
4852 * else print "Mixed case\n"
4853 * end # => "Upper case"
4854 *
4855 */
4856
4857static VALUE
4858rb_reg_eqq(VALUE re, VALUE str)
4859{
4860 rb_len_t start;
4861
4862 str = reg_operand(str, FALSE);
4863 if (NIL_P(str)) {
4864 rb_backref_set(Qnil);
4865 return Qfalse;
4866 }
4867 start = rb_reg_search(re, str, 0, 0);
4868 return RBOOL(start >= 0);
4869}
4870
4871
4872/*
4873 * call-seq:
4874 * ~ rxp -> integer or nil
4875 *
4876 * Equivalent to <tt><i>rxp</i> =~ $_</tt>:
4877 *
4878 * $_ = "input data"
4879 * ~ /at/ # => 7
4880 *
4881 */
4882
4883VALUE
4884rb_reg_match2(VALUE re)
4885{
4886 rb_len_t start;
4887 VALUE line = rb_lastline_get();
4888
4889 if (!RB_TYPE_P(line, T_STRING)) {
4890 rb_backref_set(Qnil);
4891 return Qnil;
4892 }
4893
4894 start = rb_reg_search(re, line, 0, 0);
4895 if (start < 0) {
4896 return Qnil;
4897 }
4898 start = rb_str_sublen(line, start);
4899 return LEN2NUM(start);
4900}
4901
4902
4903/*
4904 * call-seq:
4905 * match(string, offset = 0) -> matchdata or nil
4906 * match(string, offset = 0) {|matchdata| ... } -> object
4907 *
4908 * With no block given, returns the MatchData object
4909 * that describes the match, if any, or +nil+ if none;
4910 * the search begins at the given character +offset+ in +string+:
4911 *
4912 * /abra/.match('abracadabra') # => #<MatchData "abra">
4913 * /abra/.match('abracadabra', 4) # => #<MatchData "abra">
4914 * /abra/.match('abracadabra', 8) # => nil
4915 * /abra/.match('abracadabra', 800) # => nil
4916 *
4917 * string = "\u{5d0 5d1 5e8 5d0}cadabra"
4918 * /abra/.match(string, 7) #=> #<MatchData "abra">
4919 * /abra/.match(string, 8) #=> nil
4920 * /abra/.match(string.b, 8) #=> #<MatchData "abra">
4921 *
4922 * With a block given, calls the block if and only if a match is found;
4923 * returns the block's value:
4924 *
4925 * /abra/.match('abracadabra') {|matchdata| p matchdata }
4926 * # => #<MatchData "abra">
4927 * /abra/.match('abracadabra', 4) {|matchdata| p matchdata }
4928 * # => #<MatchData "abra">
4929 * /abra/.match('abracadabra', 8) {|matchdata| p matchdata }
4930 * # => nil
4931 * /abra/.match('abracadabra', 8) {|marchdata| fail 'Cannot happen' }
4932 * # => nil
4933 *
4934 * Output (from the first two blocks above):
4935 *
4936 * #<MatchData "abra">
4937 * #<MatchData "abra">
4938 *
4939 * /(.)(.)(.)/.match("abc")[2] # => "b"
4940 * /(.)(.)/.match("abc", 1)[2] # => "c"
4941 *
4942 */
4943
4944static VALUE
4945rb_reg_match_m(int argc, VALUE *argv, VALUE re)
4946{
4947 VALUE result = Qnil, str, initpos;
4948 rb_len_t pos;
4949
4950 if (rb_scan_args(argc, argv, "11", &str, &initpos) == 2) {
4951 pos = NUM2LEN(initpos);
4952 }
4953 else {
4954 pos = 0;
4955 }
4956
4957 pos = reg_match_pos(re, &str, pos, &result);
4958 if (pos < 0) {
4959 return Qnil;
4960 }
4961 rb_match_busy(result);
4962 if (!NIL_P(result) && rb_block_given_p()) {
4963 return rb_yield(result);
4964 }
4965 return result;
4966}
4967
4968/*
4969 * call-seq:
4970 * match?(string) -> true or false
4971 * match?(string, offset = 0) -> true or false
4972 *
4973 * Returns <code>true</code> or <code>false</code> to indicate whether the
4974 * regexp is matched or not without updating $~ and other related variables.
4975 * If the second parameter is present, it specifies the position in the string
4976 * to begin the search.
4977 *
4978 * /R.../.match?("Ruby") # => true
4979 * /R.../.match?("Ruby", 1) # => false
4980 * /P.../.match?("Ruby") # => false
4981 * $& # => nil
4982 */
4983
4984static VALUE
4985rb_reg_match_m_p(int argc, VALUE *argv, VALUE re)
4986{
4987 rb_len_t pos = rb_check_arity(argc, 1, 2) > 1 ? NUM2LEN(argv[1]) : 0;
4988 return rb_reg_match_p(re, argv[0], pos);
4989}
4990
4991VALUE
4992rb_reg_match_p(VALUE re, VALUE str, rb_len_t pos)
4993{
4994 if (NIL_P(str)) return Qfalse;
4995 str = SYMBOL_P(str) ? rb_sym2str(str) : StringValue(str);
4996 if (pos) {
4997 if (pos < 0) {
4998 pos += NUM2LEN(rb_str_length(str));
4999 if (pos < 0) return Qfalse;
5000 }
5001 if (pos > 0) {
5002 rb_len_t len = 1;
5003 const char *beg = rb_str_subpos(str, pos, &len);
5004 if (!beg) return Qfalse;
5005 pos = beg - RSTRING_PTR(str);
5006 }
5007 }
5008
5009 struct reg_onig_search_args args = {
5010 .pos = pos,
5011 .range = RSTRING_LEN(str),
5012 };
5013
5014 return rb_reg_onig_match(re, str, reg_onig_search, &args, NULL) == ONIG_MISMATCH ? Qfalse : Qtrue;
5015}
5016
5017/*
5018 * Document-method: compile
5019 *
5020 * Alias for Regexp.new
5021 */
5022
5023static int
5024str_to_option(VALUE str)
5025{
5026 int flag = 0;
5027 const char *ptr;
5028 rb_len_t len;
5029 str = rb_check_string_type(str);
5030 if (NIL_P(str)) return -1;
5031 RSTRING_GETMEM(str, ptr, len);
5032 for (rb_len_t i = 0; i < len; ++i) {
5033 int f = char_to_option(ptr[i]);
5034 if (!f) {
5035 rb_raise(rb_eArgError, "unknown regexp option: %"PRIsVALUE, str);
5036 }
5037 flag |= f;
5038 }
5039 return flag;
5040}
5041
5042static void
5043set_timeout(rb_hrtime_t *hrt, VALUE timeout)
5044{
5045 double timeout_d = NIL_P(timeout) ? 0.0 : NUM2DBL(timeout);
5046 if (!NIL_P(timeout) && !(timeout_d > 0)) {
5047 rb_raise(rb_eArgError, "invalid timeout: %"PRIsVALUE, timeout);
5048 }
5049 double2hrtime(hrt, timeout_d);
5050}
5051
5052static VALUE
5053reg_copy(VALUE copy, VALUE orig)
5054{
5055 int r;
5056 rb_reg_initialize_check(copy);
5057 if ((r = onig_reg_copy_body(RREGEXP_PTR(copy), RREGEXP_PTR(orig))) != 0) {
5058 /* ONIGERR_MEMORY only */
5059 rb_raise(rb_eRegexpError, "%s", onig_error_code_to_format(r));
5060 }
5061 FL_SET_RAW(copy, RREGEXP_INITIALIZED);
5062
5063 RB_OBJ_WRITE(copy, &RREGEXP(copy)->src, RREGEXP(orig)->src);
5064 RREGEXP_PTR(copy)->timelimit = RREGEXP_PTR(orig)->timelimit;
5065 rb_enc_copy(copy, orig);
5066 FL_SET_RAW(copy, FL_TEST_RAW(orig, KCODE_FIXED|REG_ENCODING_NONE));
5067 if (RBASIC_CLASS(copy) == rb_cRegexp) {
5068 OBJ_FREEZE(copy);
5069 }
5070
5071 return copy;
5072}
5073
5074struct reg_init_args {
5075 VALUE str;
5076 VALUE timeout;
5077 rb_encoding *enc;
5078 int flags;
5079};
5080
5081static VALUE reg_extract_args(int argc, VALUE *argv, struct reg_init_args *args);
5082static VALUE reg_init_args(VALUE self, VALUE str, rb_encoding *enc, int flags);
5083
5084/*
5085 * call-seq:
5086 * Regexp.new(string, options = 0, timeout: nil) -> regexp
5087 * Regexp.new(regexp, timeout: nil) -> regexp
5088 *
5089 * With argument +string+ given, returns a new regexp with the given string
5090 * and options:
5091 *
5092 * r = Regexp.new('foo') # => /foo/
5093 * r.source # => "foo"
5094 * r.options # => 0
5095 *
5096 * Passing untrusted input as +string+ is generally not recommended;
5097 * see {Untrusted Patterns}[rdoc-ref:Regexp@Untrusted+Patterns].
5098 *
5099 * Optional argument +options+ is one of the following:
5100 *
5101 * - A String of options:
5102 *
5103 * Regexp.new('foo', 'i') # => /foo/i
5104 * Regexp.new('foo', 'im') # => /foo/im
5105 *
5106 * - The bit-wise OR of one or more of the constants
5107 * Regexp::EXTENDED, Regexp::IGNORECASE, Regexp::MULTILINE, and
5108 * Regexp::NOENCODING:
5109 *
5110 * Regexp.new('foo', Regexp::IGNORECASE) # => /foo/i
5111 * Regexp.new('foo', Regexp::EXTENDED) # => /foo/x
5112 * Regexp.new('foo', Regexp::MULTILINE) # => /foo/m
5113 * Regexp.new('foo', Regexp::NOENCODING) # => /foo/n
5114 * flags = Regexp::IGNORECASE | Regexp::EXTENDED | Regexp::MULTILINE
5115 * Regexp.new('foo', flags) # => /foo/mix
5116 *
5117 * - +nil+ or +false+, which is ignored.
5118 * - Any other truthy value, in which case the regexp will be
5119 * case-insensitive.
5120 *
5121 * If optional keyword argument +timeout+ is given,
5122 * its float value overrides the timeout interval for the class,
5123 * Regexp.timeout.
5124 * If +nil+ is passed as +timeout, it uses the timeout interval
5125 * for the class, Regexp.timeout.
5126 *
5127 * With argument +regexp+ given, returns a new regexp. The source,
5128 * options, timeout are the same as +regexp+. +options+ and +n_flag+
5129 * arguments are ineffective. The timeout can be overridden by
5130 * +timeout+ keyword.
5131 *
5132 * options = Regexp::MULTILINE
5133 * r = Regexp.new('foo', options, timeout: 1.1) # => /foo/m
5134 * r2 = Regexp.new(r) # => /foo/m
5135 * r2.timeout # => 1.1
5136 * r3 = Regexp.new(r, timeout: 3.14) # => /foo/m
5137 * r3.timeout # => 3.14
5138 *
5139 */
5140
5141static VALUE
5142rb_reg_initialize_m(int argc, VALUE *argv, VALUE self)
5143{
5144 struct reg_init_args args;
5145 VALUE re = reg_extract_args(argc, argv, &args);
5146
5147 if (NIL_P(re)) {
5148 reg_init_args(self, args.str, args.enc, args.flags);
5149 }
5150 else {
5151 reg_copy(self, re);
5152 }
5153
5154 set_timeout(&RREGEXP_PTR(self)->timelimit, args.timeout);
5155 if (RBASIC_CLASS(self) == rb_cRegexp) {
5156 OBJ_FREEZE(self);
5157 }
5158
5159 return self;
5160}
5161
5162static VALUE
5163reg_extract_args(int argc, VALUE *argv, struct reg_init_args *args)
5164{
5165 int flags = 0;
5166 rb_encoding *enc = 0;
5167 VALUE str, src, opts = Qundef, kwargs;
5168 VALUE re = Qnil;
5169
5170 rb_scan_args(argc, argv, "11:", &src, &opts, &kwargs);
5171
5172 args->timeout = Qnil;
5173 if (!NIL_P(kwargs)) {
5174 static ID keywords[1];
5175 if (!keywords[0]) {
5176 keywords[0] = rb_intern_const("timeout");
5177 }
5178 rb_get_kwargs(kwargs, keywords, 0, 1, &args->timeout);
5179 }
5180
5181 if (RB_TYPE_P(src, T_REGEXP)) {
5182 re = src;
5183
5184 if (!NIL_P(opts)) {
5185 rb_warn("flags ignored");
5186 }
5187 rb_reg_check(re);
5188 flags = rb_reg_options(re);
5189 str = RREGEXP_SRC(re);
5190 }
5191 else {
5192 if (!NIL_P(opts)) {
5193 int f;
5194 if (FIXNUM_P(opts)) flags = FIX2INT(opts);
5195 else if ((f = str_to_option(opts)) >= 0) flags = f;
5196 else if (rb_bool_expected(opts, "ignorecase", FALSE))
5197 flags = ONIG_OPTION_IGNORECASE;
5198 }
5199 str = StringValue(src);
5200 }
5201 args->str = str;
5202 args->enc = enc;
5203 args->flags = flags;
5204 return re;
5205}
5206
5207static VALUE
5208reg_init_args(VALUE self, VALUE str, rb_encoding *enc, int flags)
5209{
5210 if (enc && rb_enc_get(str) != enc)
5211 rb_reg_init_str_enc(self, str, enc, flags);
5212 else
5213 rb_reg_init_str(self, str, flags);
5214 return self;
5215}
5216
5217VALUE
5218rb_reg_quote(VALUE str)
5219{
5220 rb_encoding *enc = rb_enc_get(str);
5221 char *s, *send, *t;
5222 VALUE tmp;
5223 int c, clen;
5224 int ascii_only = rb_enc_str_asciionly_p(str);
5225
5226 s = RSTRING_PTR(str);
5227 send = s + RSTRING_LEN(str);
5228 while (s < send) {
5229 c = rb_enc_ascget(s, send, &clen, enc);
5230 if (c == -1) {
5231 s += mbclen(s, send, enc);
5232 continue;
5233 }
5234 switch (c) {
5235 case '[': case ']': case '{': case '}':
5236 case '(': case ')': case '|': case '-':
5237 case '*': case '.': case '\\':
5238 case '?': case '+': case '^': case '$':
5239 case ' ': case '#':
5240 case '\t': case '\f': case '\v': case '\n': case '\r':
5241 goto meta_found;
5242 }
5243 s += clen;
5244 }
5245 tmp = rb_str_new3(str);
5246 if (ascii_only) {
5247 rb_enc_associate(tmp, rb_usascii_encoding());
5248 }
5249 return tmp;
5250
5251 meta_found:
5252 tmp = rb_str_new(0, RSTRING_LEN(str)*2);
5253 if (ascii_only) {
5254 rb_enc_associate(tmp, rb_usascii_encoding());
5255 }
5256 else {
5257 rb_enc_copy(tmp, str);
5258 }
5259 t = RSTRING_PTR(tmp);
5260 /* copy upto metacharacter */
5261 const char *p = RSTRING_PTR(str);
5262 memcpy(t, p, s - p);
5263 t += s - p;
5264
5265 while (s < send) {
5266 c = rb_enc_ascget(s, send, &clen, enc);
5267 if (c == -1) {
5268 int n = mbclen(s, send, enc);
5269
5270 while (n--)
5271 *t++ = *s++;
5272 continue;
5273 }
5274 s += clen;
5275 switch (c) {
5276 case '[': case ']': case '{': case '}':
5277 case '(': case ')': case '|': case '-':
5278 case '*': case '.': case '\\':
5279 case '?': case '+': case '^': case '$':
5280 case '#':
5281 t += rb_enc_mbcput('\\', t, enc);
5282 break;
5283 case ' ':
5284 t += rb_enc_mbcput('\\', t, enc);
5285 t += rb_enc_mbcput(' ', t, enc);
5286 continue;
5287 case '\t':
5288 t += rb_enc_mbcput('\\', t, enc);
5289 t += rb_enc_mbcput('t', t, enc);
5290 continue;
5291 case '\n':
5292 t += rb_enc_mbcput('\\', t, enc);
5293 t += rb_enc_mbcput('n', t, enc);
5294 continue;
5295 case '\r':
5296 t += rb_enc_mbcput('\\', t, enc);
5297 t += rb_enc_mbcput('r', t, enc);
5298 continue;
5299 case '\f':
5300 t += rb_enc_mbcput('\\', t, enc);
5301 t += rb_enc_mbcput('f', t, enc);
5302 continue;
5303 case '\v':
5304 t += rb_enc_mbcput('\\', t, enc);
5305 t += rb_enc_mbcput('v', t, enc);
5306 continue;
5307 }
5308 t += rb_enc_mbcput(c, t, enc);
5309 }
5310 rb_str_resize(tmp, t - RSTRING_PTR(tmp));
5311 return tmp;
5312}
5313
5314
5315/*
5316 * call-seq:
5317 * Regexp.escape(string) -> new_string
5318 *
5319 * Returns a new string that escapes any characters
5320 * that have special meaning in a regular expression:
5321 *
5322 * s = Regexp.escape('\*?{}.') # => "\\\\\\*\\?\\{\\}\\."
5323 *
5324 * For any string +s+, this call returns a MatchData object:
5325 *
5326 * r = Regexp.new(Regexp.escape(s)) # => /\\\\\\\*\\\?\\\{\\\}\\\./
5327 * r.match(s) # => #<MatchData "\\\\\\*\\?\\{\\}\\.">
5328 *
5329 */
5330
5331static VALUE
5332rb_reg_s_quote(VALUE c, VALUE str)
5333{
5334 return rb_reg_quote(reg_operand(str, TRUE));
5335}
5336
5337int
5338rb_reg_options(VALUE re)
5339{
5340 int options;
5341
5342 rb_reg_check(re);
5343 options = RREGEXP_PTR(re)->options & ARG_REG_OPTION_MASK;
5344 if (RBASIC(re)->flags & KCODE_FIXED) options |= ARG_ENCODING_FIXED;
5345 if (RBASIC(re)->flags & REG_ENCODING_NONE) options |= ARG_ENCODING_NONE;
5346 return options;
5347}
5348
5349static VALUE
5350rb_check_regexp_type(VALUE re)
5351{
5352 return rb_check_convert_type(re, T_REGEXP, "Regexp", "to_regexp");
5353}
5354
5355/*
5356 * call-seq:
5357 * Regexp.try_convert(object) -> regexp or nil
5358 *
5359 * Returns +object+ if it is a regexp:
5360 *
5361 * Regexp.try_convert(/re/) # => /re/
5362 *
5363 * Otherwise if +object+ responds to <tt>:to_regexp</tt>,
5364 * calls <tt>object.to_regexp</tt> and returns the result.
5365 *
5366 * Returns +nil+ if +object+ does not respond to <tt>:to_regexp</tt>.
5367 *
5368 * Regexp.try_convert('re') # => nil
5369 *
5370 * Raises an exception unless <tt>object.to_regexp</tt> returns a regexp.
5371 *
5372 */
5373static VALUE
5374rb_reg_s_try_convert(VALUE dummy, VALUE re)
5375{
5376 return rb_check_regexp_type(re);
5377}
5378
5379static VALUE
5380rb_reg_s_union(VALUE self, VALUE args0)
5381{
5382 rb_len_t argc = RARRAY_LEN(args0);
5383
5384 if (argc == 0) {
5385 VALUE args[1];
5386 args[0] = rb_str_new2("(?!)");
5387 return rb_class_new_instance(1, args, rb_cRegexp);
5388 }
5389 else if (argc == 1) {
5390 VALUE arg = rb_ary_entry(args0, 0);
5391 VALUE re = rb_check_regexp_type(arg);
5392 if (!NIL_P(re))
5393 return re;
5394 else {
5395 VALUE quoted;
5396 quoted = rb_reg_s_quote(Qnil, arg);
5397 return rb_reg_new_str(quoted, 0);
5398 }
5399 }
5400 else {
5401 int i;
5402 VALUE source = rb_str_buf_new(0);
5403 rb_encoding *result_enc;
5404
5405 int has_asciionly = 0;
5406 rb_encoding *has_ascii_compat_fixed = 0;
5407 rb_encoding *has_ascii_incompat = 0;
5408
5409 for (i = 0; i < argc; i++) {
5410 volatile VALUE v;
5411 VALUE e = rb_ary_entry(args0, i);
5412
5413 if (0 < i)
5414 rb_str_buf_cat_ascii(source, "|");
5415
5416 v = rb_check_regexp_type(e);
5417 if (!NIL_P(v)) {
5418 rb_encoding *enc = rb_enc_get(v);
5419 if (!rb_enc_asciicompat(enc)) {
5420 if (!has_ascii_incompat)
5421 has_ascii_incompat = enc;
5422 else if (has_ascii_incompat != enc)
5423 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
5424 rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
5425 }
5426 else if (rb_reg_fixed_encoding_p(v)) {
5427 if (!has_ascii_compat_fixed)
5428 has_ascii_compat_fixed = enc;
5429 else if (has_ascii_compat_fixed != enc)
5430 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
5431 rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
5432 }
5433 else {
5434 has_asciionly = 1;
5435 }
5436 v = rb_reg_str_with_term(v, -1);
5437 }
5438 else {
5439 rb_encoding *enc;
5440 StringValue(e);
5441 enc = rb_enc_get(e);
5442 if (!rb_enc_asciicompat(enc)) {
5443 if (!has_ascii_incompat)
5444 has_ascii_incompat = enc;
5445 else if (has_ascii_incompat != enc)
5446 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
5447 rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
5448 }
5449 else if (rb_enc_str_asciionly_p(e)) {
5450 has_asciionly = 1;
5451 }
5452 else {
5453 if (!has_ascii_compat_fixed)
5454 has_ascii_compat_fixed = enc;
5455 else if (has_ascii_compat_fixed != enc)
5456 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
5457 rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
5458 }
5459 v = rb_reg_s_quote(Qnil, e);
5460 }
5461 if (has_ascii_incompat) {
5462 if (has_asciionly) {
5463 rb_raise(rb_eArgError, "ASCII incompatible encoding: %s",
5464 rb_enc_name(has_ascii_incompat));
5465 }
5466 if (has_ascii_compat_fixed) {
5467 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
5468 rb_enc_name(has_ascii_incompat), rb_enc_name(has_ascii_compat_fixed));
5469 }
5470 }
5471
5472 if (i == 0) {
5473 rb_enc_copy(source, v);
5474 }
5475 rb_str_append(source, v);
5476 }
5477
5478 if (has_ascii_incompat) {
5479 result_enc = has_ascii_incompat;
5480 }
5481 else if (has_ascii_compat_fixed) {
5482 result_enc = has_ascii_compat_fixed;
5483 }
5484 else {
5485 result_enc = rb_ascii8bit_encoding();
5486 }
5487
5488 rb_enc_associate(source, result_enc);
5489 return rb_class_new_instance(1, &source, rb_cRegexp);
5490 }
5491}
5492
5493/*
5494 * call-seq:
5495 * Regexp.union(*patterns) -> regexp
5496 * Regexp.union(array_of_patterns) -> regexp
5497 *
5498 * Returns a regexp that is the union of the given patterns:
5499 *
5500 * r = Regexp.union(%w[cat dog]) # => /cat|dog/
5501 * r.match('cat') # => #<MatchData "cat">
5502 * r.match('dog') # => #<MatchData "dog">
5503 * r.match('cog') # => nil
5504 *
5505 * Each string pattern is escaped so that it is matched literally:
5506 *
5507 * Regexp.union('penzance') # => /penzance/
5508 * Regexp.union('a+b*c') # => /a\+b\*c/
5509 * Regexp.union('skiing', 'sledding') # => /skiing|sledding/
5510 * Regexp.union(['skiing', 'sledding']) # => /skiing|sledding/
5511 *
5512 * For each pattern that is a regexp, it is used as is,
5513 * including its flags:
5514 *
5515 * Regexp.union(/foo/i, /bar/m, /baz/x)
5516 * # => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
5517 * Regexp.union([/foo/i, /bar/m, /baz/x])
5518 * # => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
5519 *
5520 * With no arguments, returns <tt>/(?!)/</tt>:
5521 *
5522 * Regexp.union # => /(?!)/
5523 *
5524 * If any regexp pattern contains captures, the behavior is unspecified.
5525 *
5526 */
5527static VALUE
5528rb_reg_s_union_m(VALUE self, VALUE args)
5529{
5530 VALUE v;
5531 if (RARRAY_LEN(args) == 1 &&
5532 !NIL_P(v = rb_check_array_type(rb_ary_entry(args, 0)))) {
5533 return rb_reg_s_union(self, v);
5534 }
5535 return rb_reg_s_union(self, args);
5536}
5537
5538/*
5539 * call-seq:
5540 * Regexp.linear_time?(re)
5541 * Regexp.linear_time?(string, options = 0)
5542 *
5543 * Returns +true+ if matching against <tt>re</tt> can be
5544 * done in linear time to the input string.
5545 *
5546 * Regexp.linear_time?(/re/) # => true
5547 *
5548 * Note that this is a property of the ruby interpreter, not of the argument
5549 * regular expression. Identical regexp can or cannot run in linear time
5550 * depending on your ruby binary. Neither forward nor backward compatibility
5551 * is guaranteed about the return value of this method. Our current algorithm
5552 * is (*1) but this is subject to change in the future. Alternative
5553 * implementations can also behave differently. They might always return
5554 * false for everything.
5555 *
5556 * (*1): https://doi.org/10.1109/SP40001.2021.00032
5557 *
5558 */
5559static VALUE
5560rb_reg_s_linear_time_p(int argc, VALUE *argv, VALUE self)
5561{
5562 struct reg_init_args args;
5563 VALUE re = reg_extract_args(argc, argv, &args);
5564
5565 if (NIL_P(re)) {
5566 re = reg_init_args(rb_reg_alloc(), args.str, args.enc, args.flags);
5567 }
5568
5569 return RBOOL(onig_check_linear_time(RREGEXP_PTR(re)));
5570}
5571
5572/* :nodoc: */
5573VALUE
5574rb_reg_init_copy(VALUE copy, VALUE re)
5575{
5576 if (!OBJ_INIT_COPY(copy, re)) return copy;
5577 rb_reg_check(re);
5578 return reg_copy(copy, re);
5579}
5580
5581static VALUE
5582do_regsub(VALUE str, VALUE src, VALUE regexp, int num_regs, const OnigPosition *beg, const OnigPosition *end)
5583{
5584 VALUE val = 0;
5585 char *p, *s, *e;
5586 int no, clen;
5587 rb_encoding *str_enc = rb_enc_get(str);
5588 rb_encoding *src_enc = rb_enc_get(src);
5589 int acompat = rb_enc_asciicompat(str_enc);
5590 rb_len_t n;
5591#define ASCGET(s,e,cl) (acompat ? (*(cl)=1,ISASCII((s)[0])?(s)[0]:-1) : rb_enc_ascget((s), (e), (cl), str_enc))
5592
5593 RSTRING_GETMEM(str, s, n);
5594 p = s;
5595 e = s + n;
5596
5597 while (s < e) {
5598 int c = ASCGET(s, e, &clen);
5599 char *ss;
5600
5601 if (c == -1) {
5602 s += mbclen(s, e, str_enc);
5603 continue;
5604 }
5605 ss = s;
5606 s += clen;
5607
5608 if (c != '\\' || s == e) continue;
5609
5610 if (!val) {
5611 val = rb_str_buf_new(ss-p);
5612 }
5613 rb_enc_str_buf_cat(val, p, ss-p, str_enc);
5614
5615 c = ASCGET(s, e, &clen);
5616 if (c == -1) {
5617 s += mbclen(s, e, str_enc);
5618 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
5619 p = s;
5620 continue;
5621 }
5622 s += clen;
5623
5624 p = s;
5625 switch (c) {
5626 case '1': case '2': case '3': case '4':
5627 case '5': case '6': case '7': case '8': case '9':
5628 if (!NIL_P(regexp) && onig_noname_group_capture_is_active(RREGEXP_PTR(regexp))) {
5629 no = c - '0';
5630 }
5631 else {
5632 continue;
5633 }
5634 break;
5635
5636 case 'k':
5637 if (s < e && ASCGET(s, e, &clen) == '<') {
5638 char *name, *name_end;
5639
5640 name_end = name = s + clen;
5641 while (name_end < e) {
5642 c = ASCGET(name_end, e, &clen);
5643 if (c == '>') break;
5644 name_end += c == -1 ? mbclen(name_end, e, str_enc) : clen;
5645 }
5646 if (name_end < e) {
5647 VALUE n = rb_str_subseq(str, (rb_len_t)(name - RSTRING_PTR(str)),
5648 (rb_len_t)(name_end - name));
5649 struct re_registers tmp = {
5650 .allocated = num_regs,
5651 .num_regs = num_regs,
5652 .beg = (OnigPosition *)beg,
5653 .end = (OnigPosition *)end,
5654 };
5655 if ((no = NAME_TO_NUMBER(&tmp, regexp, n, name, name_end)) < 1) {
5656 name_to_backref_error(n);
5657 }
5658 p = s = name_end + clen;
5659 break;
5660 }
5661 else {
5662 rb_raise(rb_eRuntimeError, "invalid group name reference format");
5663 }
5664 }
5665
5666 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
5667 continue;
5668
5669 case '0':
5670 case '&':
5671 no = 0;
5672 break;
5673
5674 case '`':
5675 rb_enc_str_buf_cat(val, RSTRING_PTR(src), beg[0], src_enc);
5676 continue;
5677
5678 case '\'':
5679 rb_enc_str_buf_cat(val, RSTRING_PTR(src)+end[0], RSTRING_LEN(src)-end[0], src_enc);
5680 continue;
5681
5682 case '+':
5683 no = num_regs-1;
5684 while (beg[no] == -1 && no > 0) no--;
5685 if (no == 0) continue;
5686 break;
5687
5688 case '\\':
5689 rb_enc_str_buf_cat(val, s-clen, clen, str_enc);
5690 continue;
5691
5692 default:
5693 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
5694 continue;
5695 }
5696
5697 if (no >= 0) {
5698 if (no >= num_regs) continue;
5699 if (beg[no] == -1) continue;
5700 rb_enc_str_buf_cat(val, RSTRING_PTR(src)+beg[no], end[no]-beg[no], src_enc);
5701 }
5702 }
5703
5704 if (!val) return str;
5705 if (p < e) {
5706 rb_enc_str_buf_cat(val, p, e-p, str_enc);
5707 }
5708
5709 return val;
5710#undef ASCGET
5711}
5712
5713VALUE
5714rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp)
5715{
5716 return do_regsub(str, src, regexp, regs->num_regs, regs->beg, regs->end);
5717}
5718
5719VALUE
5720rb_reg_regsub_match(VALUE str, VALUE src, VALUE match)
5721{
5722 return do_regsub(str, src, RMATCH(match)->regexp,
5723 RMATCH_NREGS(match), RMATCH_BEG_PTR(match), RMATCH_END_PTR(match));
5724}
5725
5726static VALUE
5727ignorecase_getter(ID _x, VALUE *_y)
5728{
5729 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "variable $= is no longer effective");
5730 return Qfalse;
5731}
5732
5733static void
5734ignorecase_setter(VALUE val, ID id, VALUE *_)
5735{
5736 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "variable $= is no longer effective; ignored");
5737}
5738
5739static VALUE
5740match_getter(void)
5741{
5742 VALUE match = rb_backref_get();
5743
5744 if (NIL_P(match)) return Qnil;
5745 rb_match_busy(match);
5746 return match;
5747}
5748
5749static VALUE
5750get_LAST_MATCH_INFO(ID _x, VALUE *_y)
5751{
5752 return match_getter();
5753}
5754
5755static void
5756match_setter(VALUE val, ID _x, VALUE *_y)
5757{
5758 if (!NIL_P(val)) {
5759 Check_Type(val, T_MATCH);
5760 rb_match_busy(val);
5761 }
5762 rb_backref_set(val);
5763}
5764
5765/*
5766 * call-seq:
5767 * Regexp.last_match -> matchdata or nil
5768 * Regexp.last_match(n) -> string or nil
5769 * Regexp.last_match(name) -> string or nil
5770 *
5771 * With no argument, returns the value of <tt>$~</tt>,
5772 * which is the result of the most recent pattern match
5773 * (see {Regexp global variables}[rdoc-ref:Regexp@Global+Variables]):
5774 *
5775 * /c(.)t/ =~ 'cat' # => 0
5776 * Regexp.last_match # => #<MatchData "cat" 1:"a">
5777 * /a/ =~ 'foo' # => nil
5778 * Regexp.last_match # => nil
5779 *
5780 * With non-negative integer argument +n+, returns the _n_th field in the
5781 * matchdata, if any, or nil if none:
5782 *
5783 * /c(.)t/ =~ 'cat' # => 0
5784 * Regexp.last_match(0) # => "cat"
5785 * Regexp.last_match(1) # => "a"
5786 * Regexp.last_match(2) # => nil
5787 *
5788 * With negative integer argument +n+, counts backwards from the last field:
5789 *
5790 * Regexp.last_match(-1) # => "a"
5791 *
5792 * With string or symbol argument +name+,
5793 * returns the string value for the named capture, if any:
5794 *
5795 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ 'var = val'
5796 * Regexp.last_match # => #<MatchData "var = val" lhs:"var"rhs:"val">
5797 * Regexp.last_match(:lhs) # => "var"
5798 * Regexp.last_match('rhs') # => "val"
5799 * Regexp.last_match('foo') # Raises IndexError.
5800 *
5801 */
5802
5803static VALUE
5804rb_reg_s_last_match(int argc, VALUE *argv, VALUE _)
5805{
5806 if (rb_check_arity(argc, 0, 1) == 1) {
5807 VALUE match = rb_backref_get();
5808 int n;
5809 if (NIL_P(match)) return Qnil;
5810 n = match_backref_number(match, argv[0]);
5811 return rb_reg_nth_match(n, match);
5812 }
5813 return match_getter();
5814}
5815
5816static void
5817re_warn(const char *s)
5818{
5819 rb_warn("%s", s);
5820}
5821
5822// This function is periodically called during regexp matching
5823bool
5824rb_reg_timeout_p(regex_t *reg, void *end_time_)
5825{
5826 rb_hrtime_t *end_time = (rb_hrtime_t *)end_time_;
5827
5828 if (*end_time == 0) {
5829 // This is the first time to check interrupts;
5830 // just measure the current time and determine the end time
5831 // if timeout is set.
5832 rb_hrtime_t timelimit = reg->timelimit;
5833
5834 if (!timelimit) {
5835 // no per-object timeout.
5836 timelimit = rb_reg_match_time_limit;
5837 }
5838
5839 if (timelimit) {
5840 *end_time = rb_hrtime_add(timelimit, rb_hrtime_now());
5841 }
5842 else {
5843 // no timeout is set
5844 *end_time = RB_HRTIME_MAX;
5845 }
5846 }
5847 else {
5848 if (*end_time < rb_hrtime_now()) {
5849 // Timeout has exceeded
5850 return true;
5851 }
5852 }
5853
5854 return false;
5855}
5856
5857/*
5858 * call-seq:
5859 * Regexp.timeout -> float or nil
5860 *
5861 * It returns the current default timeout interval for Regexp matching in second.
5862 * +nil+ means no default timeout configuration.
5863 */
5864
5865static VALUE
5866rb_reg_s_timeout_get(VALUE dummy)
5867{
5868 double d = hrtime2double(rb_reg_match_time_limit);
5869 if (d == 0.0) return Qnil;
5870 return DBL2NUM(d);
5871}
5872
5873/*
5874 * call-seq:
5875 * Regexp.timeout = float or nil
5876 *
5877 * It sets the default timeout interval for Regexp matching in second.
5878 * +nil+ means no default timeout configuration.
5879 * This configuration is process-global. If you want to set timeout for
5880 * each Regexp, use +timeout+ keyword for <code>Regexp.new</code>.
5881 *
5882 * Regexp.timeout = 1
5883 * /^a*b?a*$/ =~ "a" * 100000 + "x" #=> regexp match timeout (RuntimeError)
5884 */
5885
5886static VALUE
5887rb_reg_s_timeout_set(VALUE dummy, VALUE timeout)
5888{
5889 rb_ractor_ensure_main_ractor("can not access Regexp.timeout from non-main Ractors");
5890
5891 set_timeout(&rb_reg_match_time_limit, timeout);
5892
5893 return timeout;
5894}
5895
5896/*
5897 * call-seq:
5898 * rxp.timeout -> float or nil
5899 *
5900 * It returns the timeout interval for Regexp matching in second.
5901 * +nil+ means no default timeout configuration.
5902 *
5903 * This configuration is per-object. The global configuration set by
5904 * Regexp.timeout= is ignored if per-object configuration is set.
5905 *
5906 * re = Regexp.new("^a*b?a*$", timeout: 1)
5907 * re.timeout #=> 1.0
5908 * re =~ "a" * 100000 + "x" #=> regexp match timeout (RuntimeError)
5909 */
5910
5911static VALUE
5912rb_reg_timeout_get(VALUE re)
5913{
5914 rb_reg_check(re);
5915 double d = hrtime2double(RREGEXP_PTR(re)->timelimit);
5916 if (d == 0.0) return Qnil;
5917 return DBL2NUM(d);
5918}
5919
5920/*
5921 * Document-class: RegexpError
5922 *
5923 * Raised when given an invalid regexp expression.
5924 *
5925 * Regexp.new("?")
5926 *
5927 * <em>raises the exception:</em>
5928 *
5929 * RegexpError: target of repeat operator is not specified: /?/
5930 */
5931
5932/*
5933 * Document-class: Regexp
5934 *
5935 * :include: doc/_regexp.rdoc
5936 */
5937
5938void
5939Init_Regexp(void)
5940{
5941 rb_eRegexpError = rb_define_class("RegexpError", rb_eStandardError);
5942
5943 onigenc_set_default_encoding(ONIG_ENCODING_ASCII);
5944 onig_set_warn_func(re_warn);
5945 onig_set_verb_warn_func(re_warn);
5946
5947 rb_define_virtual_variable("$~", get_LAST_MATCH_INFO, match_setter);
5948 rb_define_virtual_variable("$&", last_match_getter, 0);
5949 rb_define_virtual_variable("$`", prematch_getter, 0);
5950 rb_define_virtual_variable("$'", postmatch_getter, 0);
5951 rb_define_virtual_variable("$+", last_paren_match_getter, 0);
5952
5953 rb_gvar_ractor_local("$~");
5954 rb_gvar_ractor_local("$&");
5955 rb_gvar_ractor_local("$`");
5956 rb_gvar_ractor_local("$'");
5957 rb_gvar_ractor_local("$+");
5958 rb_gvar_box_dynamic("$~");
5959 rb_gvar_box_ready("$&");
5960 rb_gvar_box_ready("$`");
5961 rb_gvar_box_ready("$'");
5962 rb_gvar_box_ready("$+");
5963
5964 rb_define_virtual_variable("$=", ignorecase_getter, ignorecase_setter);
5965
5966 rb_cRegexp = rb_define_class("Regexp", rb_cObject);
5967 rb_define_alloc_func(rb_cRegexp, rb_reg_s_alloc);
5968 rb_define_singleton_method(rb_cRegexp, "compile", rb_class_new_instance_pass_kw, -1);
5969 rb_define_singleton_method(rb_cRegexp, "quote", rb_reg_s_quote, 1);
5970 rb_define_singleton_method(rb_cRegexp, "escape", rb_reg_s_quote, 1);
5971 rb_define_singleton_method(rb_cRegexp, "union", rb_reg_s_union_m, -2);
5972 rb_define_singleton_method(rb_cRegexp, "last_match", rb_reg_s_last_match, -1);
5973 rb_define_singleton_method(rb_cRegexp, "try_convert", rb_reg_s_try_convert, 1);
5974 rb_define_singleton_method(rb_cRegexp, "linear_time?", rb_reg_s_linear_time_p, -1);
5975
5976 rb_define_method(rb_cRegexp, "initialize", rb_reg_initialize_m, -1);
5977 rb_define_method(rb_cRegexp, "initialize_copy", rb_reg_init_copy, 1);
5978 rb_define_method(rb_cRegexp, "hash", rb_reg_hash, 0);
5979 rb_define_method(rb_cRegexp, "eql?", rb_reg_equal, 1);
5980 rb_define_method(rb_cRegexp, "==", rb_reg_equal, 1);
5981 rb_define_method(rb_cRegexp, "=~", rb_reg_match, 1);
5982 rb_define_method(rb_cRegexp, "===", rb_reg_eqq, 1);
5983 rb_define_method(rb_cRegexp, "~", rb_reg_match2, 0);
5984 rb_define_method(rb_cRegexp, "match", rb_reg_match_m, -1);
5985 rb_define_method(rb_cRegexp, "match?", rb_reg_match_m_p, -1);
5986 rb_define_method(rb_cRegexp, "to_s", rb_reg_to_s, 0);
5987 rb_define_method(rb_cRegexp, "inspect", rb_reg_inspect, 0);
5988 rb_define_method(rb_cRegexp, "source", rb_reg_source, 0);
5989 rb_define_method(rb_cRegexp, "casefold?", rb_reg_casefold_p, 0);
5990 rb_define_method(rb_cRegexp, "options", rb_reg_options_m, 0);
5991 rb_define_method(rb_cRegexp, "encoding", rb_obj_encoding, 0); /* in encoding.c */
5992 rb_define_method(rb_cRegexp, "fixed_encoding?", rb_reg_fixed_encoding_p, 0);
5993 rb_define_method(rb_cRegexp, "names", rb_reg_names, 0);
5994 rb_define_method(rb_cRegexp, "named_captures", rb_reg_named_captures, 0);
5995 rb_define_method(rb_cRegexp, "timeout", rb_reg_timeout_get, 0);
5996
5997 /* Raised when regexp matching timed out. */
5998 rb_eRegexpTimeoutError = rb_define_class_under(rb_cRegexp, "TimeoutError", rb_eRegexpError);
5999 rb_define_singleton_method(rb_cRegexp, "timeout", rb_reg_s_timeout_get, 0);
6000 rb_define_singleton_method(rb_cRegexp, "timeout=", rb_reg_s_timeout_set, 1);
6001
6002 /* see Regexp.options and Regexp.new */
6003 rb_define_const(rb_cRegexp, "IGNORECASE", INT2FIX(ONIG_OPTION_IGNORECASE));
6004 /* see Regexp.options and Regexp.new */
6005 rb_define_const(rb_cRegexp, "EXTENDED", INT2FIX(ONIG_OPTION_EXTEND));
6006 /* see Regexp.options and Regexp.new */
6007 rb_define_const(rb_cRegexp, "MULTILINE", INT2FIX(ONIG_OPTION_MULTILINE));
6008 /* see Regexp.options and Regexp.new */
6009 rb_define_const(rb_cRegexp, "FIXEDENCODING", INT2FIX(ARG_ENCODING_FIXED));
6010 /* see Regexp.options and Regexp.new */
6011 rb_define_const(rb_cRegexp, "NOENCODING", INT2FIX(ARG_ENCODING_NONE));
6012
6013 rb_global_variable(&reg_cache);
6014
6015 rb_cMatch = rb_define_class("MatchData", rb_cObject);
6016 rb_define_alloc_func(rb_cMatch, match_alloc);
6017 rb_undef_method(CLASS_OF(rb_cMatch), "new");
6018 rb_undef_method(CLASS_OF(rb_cMatch), "allocate");
6019
6020 rb_define_method(rb_cMatch, "initialize_copy", rb_match_init_copy, 1);
6021 rb_define_method(rb_cMatch, "regexp", match_regexp, 0);
6022 rb_define_method(rb_cMatch, "names", match_names, 0);
6023 rb_define_method(rb_cMatch, "size", match_size, 0);
6024 rb_define_method(rb_cMatch, "length", match_size, 0);
6025 rb_define_method(rb_cMatch, "offset", match_offset, 1);
6026 rb_define_method(rb_cMatch, "byteoffset", match_byteoffset, 1);
6027 rb_define_method(rb_cMatch, "bytebegin", match_bytebegin, 1);
6028 rb_define_method(rb_cMatch, "byteend", match_byteend, 1);
6029 rb_define_method(rb_cMatch, "begin", match_begin, 1);
6030 rb_define_method(rb_cMatch, "end", match_end, 1);
6031 rb_define_method(rb_cMatch, "match", match_nth, 1);
6032 rb_define_method(rb_cMatch, "match_length", match_nth_length, 1);
6033 rb_define_method(rb_cMatch, "to_a", match_to_a, 0);
6034 rb_define_method(rb_cMatch, "[]", match_aref, -1);
6035 rb_define_method(rb_cMatch, "captures", match_captures, 0);
6036 rb_define_alias(rb_cMatch, "deconstruct", "captures");
6037 rb_define_method(rb_cMatch, "named_captures", match_named_captures, -1);
6038 rb_define_method(rb_cMatch, "deconstruct_keys", match_deconstruct_keys, 1);
6039 rb_define_method(rb_cMatch, "values_at", match_values_at, -1);
6040 rb_define_method(rb_cMatch, "pre_match", rb_reg_match_pre, 0);
6041 rb_define_method(rb_cMatch, "post_match", rb_reg_match_post, 0);
6042 rb_define_method(rb_cMatch, "to_s", match_to_s, 0);
6043 rb_define_method(rb_cMatch, "inspect", match_inspect, 0);
6044 rb_define_method(rb_cMatch, "string", match_string, 0);
6045 rb_define_method(rb_cMatch, "hash", match_hash, 0);
6046 rb_define_method(rb_cMatch, "eql?", match_equal, 1);
6047 rb_define_method(rb_cMatch, "==", match_equal, 1);
6048 rb_define_method(rb_cMatch, "integer_at", match_integer_at, -1);
6049}
Atomic operations.
#define RUBY_ATOMIC_PTR_LOAD(var)
Identical to RUBY_ATOMIC_LOAD, except it expects its arguments are void*.
Definition atomic.h:348
#define RUBY_ATOMIC_PTR_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are void*.
Definition atomic.h:375
#define ISSPACE
@old{rb_isspace}
Definition ctype.h:88
static bool rb_enc_isprint(OnigCodePoint c, rb_encoding *enc)
Identical to rb_isprint(), except it additionally takes an encoding.
Definition ctype.h:180
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3394
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3183
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
Definition coderange.h:180
struct re_pattern_buffer Regexp
Old name of re_pattern_buffer.
Definition rmatch.h:52
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:130
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1707
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:403
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define ENC_CODERANGE_CLEAN_P(cr)
Old name of RB_ENC_CODERANGE_CLEAN_P.
Definition coderange.h:183
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define LEN2NUM
Old name of RB_LEN2NUM.
Definition len_t.h:33
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition string.h:1704
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ENC_CODERANGE_UNKNOWN
Old name of RUBY_ENC_CODERANGE_UNKNOWN.
Definition coderange.h:179
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
Definition encoding.h:109
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define rb_str_new3
Old name of rb_str_new_shared.
Definition string.h:1701
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
Definition encoding.h:517
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:125
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition error.h:38
#define MBCLEN_INVALID_P(ret)
Old name of ONIGENC_MBCLEN_INVALID_P.
Definition encoding.h:518
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define MBCLEN_NEEDMORE_P(ret)
Old name of ONIGENC_MBCLEN_NEEDMORE_P.
Definition encoding.h:519
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define ENC_CODERANGE_BROKEN
Old name of RUBY_ENC_CODERANGE_BROKEN.
Definition coderange.h:182
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define scan_hex(s, l, e)
Old name of ruby_scan_hex.
Definition util.h:108
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
Definition encoding.h:516
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define T_MATCH
Old name of RUBY_T_MATCH.
Definition value_type.h:69
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:127
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:129
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define scan_oct(s, l, e)
Old name of ruby_scan_oct.
Definition util.h:85
#define NUM2LEN
Old name of RB_NUM2LEN.
Definition len_t.h:34
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:126
#define rb_str_new4
Old name of rb_str_new_frozen.
Definition string.h:1702
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define T_REGEXP
Old name of RUBY_T_REGEXP.
Definition value_type.h:77
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:679
VALUE rb_eRegexpError
RegexpError exception.
Definition re.c:67
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eEncCompatError
Encoding::CompatibilityError exception.
Definition error.c:1464
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1459
VALUE rb_obj_reveal(VALUE obj, VALUE klass)
Make a hidden object visible again.
Definition object.c:103
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:654
VALUE rb_cMatch
MatchData class.
Definition re.c:1283
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_cRegexp
Regexp class.
Definition re.c:3635
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RBIMPL_ASSERT_OR_ASSUME(...)
This is either RUBY_ASSERT or RBIMPL_ASSUME, depending on RUBY_DEBUG.
Definition assert.h:311
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
Encoding relates APIs.
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
Definition encoding.c:1638
rb_encoding * rb_ascii8bit_encoding(void)
Queries the encoding that represents ASCII-8BIT a.k.a.
Definition encoding.c:1626
rb_encoding * rb_default_internal_encoding(void)
Queries the "default internal" encoding.
Definition encoding.c:1847
static char * rb_enc_left_char_head(const char *s, const char *p, const char *e, rb_encoding *enc)
Queries the left boundary of a character.
Definition encoding.h:683
int rb_utf8_encindex(void)
Identical to rb_utf8_encoding(), except it returns the encoding's index instead of the encoding itsel...
Definition encoding.c:1644
int rb_ascii8bit_encindex(void)
Identical to rb_ascii8bit_encoding(), except it returns the encoding's index instead of the encoding ...
Definition encoding.c:1632
rb_encoding * rb_default_external_encoding(void)
Queries the "default external" encoding.
Definition encoding.c:1760
int rb_char_to_option_kcode(int c, int *option, int *kcode)
Converts a character option to its encoding.
Definition re.c:359
static int rb_enc_mbmaxlen(rb_encoding *enc)
Queries the maximum number of bytes that the passed encoding needs to represent a character.
Definition encoding.h:447
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
Definition encoding.c:1650
VALUE rb_enc_reg_new(const char *ptr, rb_len_t len, rb_encoding *enc, int opts)
Identical to rb_reg_new(), except it additionally takes an encoding.
Definition re.c:4461
rb_len_t rb_enc_strlen(const char *head, const char *tail, rb_encoding *enc)
Counts the number of characters of the passed string, according to the passed encoding.
Definition string.c:2411
rb_len_t rb_memsearch(const void *x, rb_len_t m, const void *y, rb_len_t n, rb_encoding *enc)
Looks for the passed string in the passed buffer.
Definition re.c:287
VALUE rb_str_encode(VALUE str, VALUE to, int ecflags, VALUE ecopts)
Converts the contents of the passed string from its encoding to the passed one.
Definition transcode.c:3064
void rb_memerror(void)
Triggers out-of-memory error.
Definition gc.c:6683
void rb_gc(void)
Triggers a GC process.
Definition gc.c:5704
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_resize(VALUE ary, rb_len_t len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
int rb_uv_to_utf8(char buf[6], unsigned long uv)
Encodes a Unicode codepoint into its UTF-8 representation.
Definition pack.c:1829
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1656
VALUE rb_backref_get(void)
Queries the last match, or Regexp.last_match, or the $~.
Definition vm.c:2172
void rb_backref_set(VALUE md)
Updates $~.
Definition vm.c:2178
VALUE rb_range_beg_len(VALUE range, rb_len_t *begp, rb_len_t *lenp, rb_len_t len, int err)
Deconstructs a numerical range.
Definition range.c:1949
int rb_reg_backref_number(VALUE match, VALUE backref)
Queries the index of the given named capture.
Definition re.c:1700
int rb_reg_options(VALUE re)
Queries the options of the passed regular expression.
Definition re.c:5338
VALUE rb_reg_last_match(VALUE md)
This just returns the argument, stringified.
Definition re.c:2740
void rb_match_busy(VALUE md)
Asserts that the given MatchData is "occupied".
Definition re.c:2209
VALUE rb_reg_nth_match(int n, VALUE md)
Queries the nth captured substring.
Definition re.c:2716
VALUE rb_reg_match_post(VALUE md)
The portion of the original string after the given match.
Definition re.c:2798
VALUE rb_reg_nth_defined(int n, VALUE md)
Identical to rb_reg_nth_match(), except it just returns Boolean.
Definition re.c:2700
VALUE rb_reg_match_pre(VALUE md)
The portion of the original string before the given match.
Definition re.c:2766
VALUE rb_reg_new_str(VALUE src, int opts)
Identical to rb_reg_new(), except it takes the expression in Ruby's string instead of C's.
Definition re.c:4420
VALUE rb_reg_match_last(VALUE md)
The portion of the original string that captured at the very last.
Definition re.c:2827
VALUE rb_reg_new(const char *src, rb_len_t len, int opts)
Creates a new Regular expression.
Definition re.c:4475
VALUE rb_str_subseq(VALUE str, rb_len_t beg, rb_len_t len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3300
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:967
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:970
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3995
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1706
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2057
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
Definition string.c:4364
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3959
st_index_t rb_memhash(const void *ptr, rb_len_t len)
This is a universal hash function.
Definition random.c:1720
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
Definition string.c:4503
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1714
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:9427
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
Definition string.c:1788
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:1097
void rb_thread_check_ints(void)
Checks for interrupts.
Definition thread.c:1647
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:397
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1161
int capa
Designed capacity of the buffer.
Definition io.h:11
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
rb_len_t rb_reg_search(VALUE re, VALUE str, rb_len_t pos, int dir)
Runs the passed regular expression over the passed string.
Definition re.c:2644
regex_t * rb_reg_prepare_re(VALUE re, VALUE str)
Exercises various checks and preprocesses so that the given regular expression can be applied to the ...
Definition re.c:2465
OnigPosition rb_reg_onig_match(VALUE re, VALUE str, OnigPosition(*match)(regex_t *reg, VALUE str, struct re_registers *regs, void *args), void *args, struct re_registers *regs)
Runs a regular expression match using function match.
Definition re.c:2471
VALUE rb_reg_regcomp(VALUE str)
Creates a new instance of rb_cRegexp.
Definition re.c:4497
VALUE rb_reg_quote(VALUE str)
Escapes any characters that would have special meaning in a regular expression.
Definition re.c:5218
int rb_reg_region_copy(struct re_registers *dst, const struct re_registers *src)
Duplicates a match data.
Definition re.c:1314
rb_len_t rb_reg_adjust_startpos(VALUE re, VALUE str, rb_len_t pos, int dir)
Tell us if this is a wrong idea, but it seems this function has no usage at all.
Definition re.c:2521
unsigned long ruby_scan_hex(const char *str, size_t len, size_t *ret)
Interprets the passed string a hexadecimal unsigned integer.
Definition util.c:48
unsigned long ruby_scan_oct(const char *str, size_t len, size_t *consumed)
Interprets the passed string as an octal unsigned integer.
Definition util.c:39
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define ALLOCA_N(type, n)
Definition memory.h:295
#define RB_ALLOCV_N(type, v, n)
Allocates a memory region, possibly on stack.
Definition memory.h:339
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define RB_ALLOCV_END(v)
Polite way to declare that the given array is not used any longer.
Definition memory.h:352
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:398
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RMATCH(obj)
Convenient casting macro.
Definition rmatch.h:37
#define RREGEXP(obj)
Convenient casting macro.
Definition rregexp.h:37
static struct re_pattern_buffer * RREGEXP_PTR(VALUE rexp)
Convenient getter function.
Definition rregexp.h:77
static VALUE RREGEXP_SRC(VALUE rexp)
Convenient getter function.
Definition rregexp.h:93
static rb_len_t RREGEXP_SRC_LEN(VALUE rexp)
Convenient getter function.
Definition rregexp.h:134
static char * RREGEXP_SRC_PTR(VALUE rexp)
Convenient getter function.
Definition rregexp.h:115
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Ruby object's base components.
Definition rbasic.h:69
VALUE flags
Per-object flags.
Definition rbasic.h:81
Regular expression execution context.
Definition rmatch.h:79
VALUE regexp
The expression of this match.
Definition rmatch.h:92
struct rmatch_offset * char_offset
Capture group offsets, in C array.
Definition rmatch.h:98
union RMatch::@357327212031205367147161324375004050200256000107 as
"Registers" of a match.
int char_offset_num_allocated
Number of rmatch_offset that rmatch::char_offset holds.
Definition rmatch.h:95
int num_regs
Number of capture-group registers.
Definition rmatch.h:101
int capa
Capacity of as.embed, in OnigPosition slots.
Definition rmatch.h:104
VALUE str
The target string that the match was made against.
Definition rmatch.h:87
Ruby's regular expression.
Definition rregexp.h:51
struct rb_regexp_variant * variants
Compiled variants for other encodings.
Definition rregexp.h:64
struct RBasic basic
Basic part, including flags and class.
Definition rregexp.h:54
const VALUE src
Source code of this expression.
Definition rregexp.h:57
Definition re.c:1445
Represents the region of a capture group.
Definition rmatch.h:65
rb_len_t end
End of a group.
Definition rmatch.h:67
rb_len_t beg
Beginning of a group.
Definition rmatch.h:66
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
#define RB_LEN_MAX
Maximum possible value that a rb_len_t can take.
Definition value.h:156
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376