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