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