Ruby 4.1.0dev (2026-04-04 revision 3b6245536cf55da9e8bfcdb03c845fe9ef931d7f)
re.c (3b6245536cf55da9e8bfcdb03c845fe9ef931d7f)
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/hash.h"
23#include "internal/imemo.h"
24#include "internal/re.h"
25#include "internal/string.h"
26#include "internal/object.h"
27#include "internal/ractor.h"
28#include "internal/variable.h"
29#include "regint.h"
30#include "ruby/encoding.h"
31#include "ruby/re.h"
32#include "ruby/util.h"
33#include "ractor_core.h"
34
35VALUE rb_eRegexpError, rb_eRegexpTimeoutError;
36
37typedef char onig_errmsg_buffer[ONIG_MAX_ERROR_MESSAGE_LEN];
38#define errcpy(err, msg) strlcpy((err), (msg), ONIG_MAX_ERROR_MESSAGE_LEN)
39
40#define BEG(no) (regs->beg[(no)])
41#define END(no) (regs->end[(no)])
42
43#if 'a' == 97 /* it's ascii */
44static const char casetable[] = {
45 '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
46 '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
47 '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
48 '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
49 /* ' ' '!' '"' '#' '$' '%' '&' ''' */
50 '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
51 /* '(' ')' '*' '+' ',' '-' '.' '/' */
52 '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
53 /* '0' '1' '2' '3' '4' '5' '6' '7' */
54 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
55 /* '8' '9' ':' ';' '<' '=' '>' '?' */
56 '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
57 /* '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' */
58 '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
59 /* 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' */
60 '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
61 /* 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' */
62 '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
63 /* 'X' 'Y' 'Z' '[' '\' ']' '^' '_' */
64 '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
65 /* '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' */
66 '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
67 /* 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' */
68 '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
69 /* 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' */
70 '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
71 /* 'x' 'y' 'z' '{' '|' '}' '~' */
72 '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
73 '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
74 '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
75 '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
76 '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
77 '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
78 '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
79 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
80 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
81 '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
82 '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
83 '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
84 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
85 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
86 '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
87 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
88 '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
89};
90#else
91# error >>> "You lose. You will need a translation table for your character set." <<<
92#endif
93
94// The process-global timeout for regexp matching
95rb_hrtime_t rb_reg_match_time_limit = 0;
96
97int
98rb_memcicmp(const void *x, const void *y, long len)
99{
100 const unsigned char *p1 = x, *p2 = y;
101 int tmp;
102
103 while (len--) {
104 if ((tmp = casetable[(unsigned)*p1++] - casetable[(unsigned)*p2++]))
105 return tmp;
106 }
107 return 0;
108}
109
110#if defined(HAVE_MEMMEM) && !defined(__APPLE__)
111static inline long
112rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n)
113{
114 const unsigned char *y;
115
116 if ((y = memmem(ys, n, xs, m)) != NULL)
117 return y - ys;
118 else
119 return -1;
120}
121#else
122static inline long
123rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n)
124{
125 const unsigned char *x = xs, *xe = xs + m;
126 const unsigned char *y = ys, *ye = ys + n;
127#define VALUE_MAX ((VALUE)~(VALUE)0)
128 VALUE hx, hy, mask = VALUE_MAX >> ((SIZEOF_VALUE - m) * CHAR_BIT);
129
130 if (m > SIZEOF_VALUE)
131 rb_bug("!!too long pattern string!!");
132
133 if (!(y = memchr(y, *x, n - m + 1)))
134 return -1;
135
136 /* Prepare hash value */
137 for (hx = *x++, hy = *y++; x < xe; ++x, ++y) {
138 hx <<= CHAR_BIT;
139 hy <<= CHAR_BIT;
140 hx |= *x;
141 hy |= *y;
142 }
143 /* Searching */
144 while (hx != hy) {
145 if (y == ye)
146 return -1;
147 hy <<= CHAR_BIT;
148 hy |= *y;
149 hy &= mask;
150 y++;
151 }
152 return y - ys - m;
153}
154#endif
155
156static inline long
157rb_memsearch_qs(const unsigned char *xs, long m, const unsigned char *ys, long n)
158{
159 const unsigned char *x = xs, *xe = xs + m;
160 const unsigned char *y = ys;
161 VALUE i, qstable[256];
162
163 /* Preprocessing */
164 for (i = 0; i < 256; ++i)
165 qstable[i] = m + 1;
166 for (; x < xe; ++x)
167 qstable[*x] = xe - x;
168 /* Searching */
169 for (; y + m <= ys + n; y += *(qstable + y[m])) {
170 if (*xs == *y && memcmp(xs, y, m) == 0)
171 return y - ys;
172 }
173 return -1;
174}
175
176static inline unsigned int
177rb_memsearch_qs_utf8_hash(const unsigned char *x)
178{
179 register const unsigned int mix = 8353;
180 register unsigned int h = *x;
181 if (h < 0xC0) {
182 return h + 256;
183 }
184 else if (h < 0xE0) {
185 h *= mix;
186 h += x[1];
187 }
188 else if (h < 0xF0) {
189 h *= mix;
190 h += x[1];
191 h *= mix;
192 h += x[2];
193 }
194 else if (h < 0xF5) {
195 h *= mix;
196 h += x[1];
197 h *= mix;
198 h += x[2];
199 h *= mix;
200 h += x[3];
201 }
202 else {
203 return h + 256;
204 }
205 return (unsigned char)h;
206}
207
208static inline long
209rb_memsearch_qs_utf8(const unsigned char *xs, long m, const unsigned char *ys, long n)
210{
211 const unsigned char *x = xs, *xe = xs + m;
212 const unsigned char *y = ys;
213 VALUE i, qstable[512];
214
215 /* Preprocessing */
216 for (i = 0; i < 512; ++i) {
217 qstable[i] = m + 1;
218 }
219 for (; x < xe; ++x) {
220 qstable[rb_memsearch_qs_utf8_hash(x)] = xe - x;
221 }
222 /* Searching */
223 for (; y + m <= ys + n; y += qstable[rb_memsearch_qs_utf8_hash(y+m)]) {
224 if (*xs == *y && memcmp(xs, y, m) == 0)
225 return y - ys;
226 }
227 return -1;
228}
229
230static inline long
231rb_memsearch_with_char_size(const unsigned char *xs, long m, const unsigned char *ys, long n, int char_size)
232{
233 const unsigned char *x = xs, x0 = *xs, *y = ys;
234
235 for (n -= m; n >= 0; n -= char_size, y += char_size) {
236 if (x0 == *y && memcmp(x+1, y+1, m-1) == 0)
237 return y - ys;
238 }
239 return -1;
240}
241
242static inline long
243rb_memsearch_wchar(const unsigned char *xs, long m, const unsigned char *ys, long n)
244{
245 return rb_memsearch_with_char_size(xs, m, ys, n, 2);
246}
247
248static inline long
249rb_memsearch_qchar(const unsigned char *xs, long m, const unsigned char *ys, long n)
250{
251 return rb_memsearch_with_char_size(xs, m, ys, n, 4);
252}
253
254long
255rb_memsearch(const void *x0, long m, const void *y0, long n, rb_encoding *enc)
256{
257 const unsigned char *x = x0, *y = y0;
258
259 if (m > n) return -1;
260 else if (m == n) {
261 return memcmp(x0, y0, m) == 0 ? 0 : -1;
262 }
263 else if (m < 1) {
264 return 0;
265 }
266 else if (m == 1) {
267 const unsigned char *ys = memchr(y, *x, n);
268
269 if (ys)
270 return ys - y;
271 else
272 return -1;
273 }
274 else if (LIKELY(rb_enc_mbminlen(enc) == 1)) {
275 if (m <= SIZEOF_VALUE) {
276 return rb_memsearch_ss(x0, m, y0, n);
277 }
278 else if (enc == rb_utf8_encoding()){
279 return rb_memsearch_qs_utf8(x0, m, y0, n);
280 }
281 }
282 else if (LIKELY(rb_enc_mbminlen(enc) == 2)) {
283 return rb_memsearch_wchar(x0, m, y0, n);
284 }
285 else if (LIKELY(rb_enc_mbminlen(enc) == 4)) {
286 return rb_memsearch_qchar(x0, m, y0, n);
287 }
288 return rb_memsearch_qs(x0, m, y0, n);
289}
290
291#define REG_ENCODING_NONE FL_USER6
292
293#define KCODE_FIXED FL_USER4
294
295static int
296char_to_option(int c)
297{
298 int val;
299
300 switch (c) {
301 case 'i':
302 val = ONIG_OPTION_IGNORECASE;
303 break;
304 case 'x':
305 val = ONIG_OPTION_EXTEND;
306 break;
307 case 'm':
308 val = ONIG_OPTION_MULTILINE;
309 break;
310 default:
311 val = 0;
312 break;
313 }
314 return val;
315}
316
317enum { OPTBUF_SIZE = 4 };
318
319static char *
320option_to_str(char str[OPTBUF_SIZE], int options)
321{
322 char *p = str;
323 if (options & ONIG_OPTION_MULTILINE) *p++ = 'm';
324 if (options & ONIG_OPTION_IGNORECASE) *p++ = 'i';
325 if (options & ONIG_OPTION_EXTEND) *p++ = 'x';
326 *p = 0;
327 return str;
328}
329
330extern int
331rb_char_to_option_kcode(int c, int *option, int *kcode)
332{
333 *option = 0;
334
335 switch (c) {
336 case 'n':
337 *kcode = rb_ascii8bit_encindex();
338 return (*option = ARG_ENCODING_NONE);
339 case 'e':
340 *kcode = ENCINDEX_EUC_JP;
341 break;
342 case 's':
343 *kcode = ENCINDEX_Windows_31J;
344 break;
345 case 'u':
346 *kcode = rb_utf8_encindex();
347 break;
348 default:
349 *kcode = -1;
350 return (*option = char_to_option(c));
351 }
352 *option = ARG_ENCODING_FIXED;
353 return 1;
354}
355
356static void
357rb_reg_check(VALUE re)
358{
359 if (!RREGEXP_PTR(re) || !RREGEXP_SRC(re) || !RREGEXP_SRC_PTR(re)) {
360 rb_raise(rb_eTypeError, "uninitialized Regexp");
361 }
362}
363
364static void
365rb_reg_expr_str(VALUE str, const char *s, long len,
366 rb_encoding *enc, rb_encoding *resenc, int term)
367{
368 const char *p, *pend;
369 int cr = ENC_CODERANGE_UNKNOWN;
370 int need_escape = 0;
371 int c, clen;
372
373 p = s; pend = p + len;
374 rb_str_coderange_scan_restartable(p, pend, enc, &cr);
375 if (rb_enc_asciicompat(enc) && ENC_CODERANGE_CLEAN_P(cr)) {
376 while (p < pend) {
377 c = rb_enc_ascget(p, pend, &clen, enc);
378 if (c == -1) {
379 if (enc == resenc) {
380 p += mbclen(p, pend, enc);
381 }
382 else {
383 need_escape = 1;
384 break;
385 }
386 }
387 else if (c != term && rb_enc_isprint(c, enc)) {
388 p += clen;
389 }
390 else {
391 need_escape = 1;
392 break;
393 }
394 }
395 }
396 else {
397 need_escape = 1;
398 }
399
400 if (!need_escape) {
401 rb_str_buf_cat(str, s, len);
402 }
403 else {
404 int unicode_p = rb_enc_unicode_p(enc);
405 p = s;
406 while (p<pend) {
407 c = rb_enc_ascget(p, pend, &clen, enc);
408 if (c == '\\' && p+clen < pend) {
409 int n = clen + mbclen(p+clen, pend, enc);
410 rb_str_buf_cat(str, p, n);
411 p += n;
412 continue;
413 }
414 else if (c == -1) {
415 clen = rb_enc_precise_mbclen(p, pend, enc);
416 if (!MBCLEN_CHARFOUND_P(clen)) {
417 c = (unsigned char)*p;
418 clen = 1;
419 goto hex;
420 }
421 if (resenc) {
422 unsigned int c = rb_enc_mbc_to_codepoint(p, pend, enc);
423 rb_str_buf_cat_escaped_char(str, c, unicode_p);
424 }
425 else {
426 clen = MBCLEN_CHARFOUND_LEN(clen);
427 rb_str_buf_cat(str, p, clen);
428 }
429 }
430 else if (c == term) {
431 char c = '\\';
432 rb_str_buf_cat(str, &c, 1);
433 rb_str_buf_cat(str, p, clen);
434 }
435 else if (rb_enc_isprint(c, enc)) {
436 rb_str_buf_cat(str, p, clen);
437 }
438 else if (!rb_enc_isspace(c, enc)) {
439 char b[8];
440
441 hex:
442 snprintf(b, sizeof(b), "\\x%02X", c);
443 rb_str_buf_cat(str, b, 4);
444 }
445 else {
446 rb_str_buf_cat(str, p, clen);
447 }
448 p += clen;
449 }
450 }
451}
452
453static VALUE
454rb_reg_desc(VALUE re)
455{
456 rb_encoding *enc = rb_enc_get(re);
457 VALUE str = rb_str_buf_new2("/");
458 rb_encoding *resenc = rb_default_internal_encoding();
459 if (resenc == NULL) resenc = rb_default_external_encoding();
460
461 if (re && rb_enc_asciicompat(enc)) {
462 rb_enc_copy(str, re);
463 }
464 else {
465 rb_enc_associate(str, rb_usascii_encoding());
466 }
467
468 VALUE src_str = RREGEXP_SRC(re);
469 rb_reg_expr_str(str, RSTRING_PTR(src_str), RSTRING_LEN(src_str), enc, resenc, '/');
470 RB_GC_GUARD(src_str);
471
472 rb_str_buf_cat2(str, "/");
473 if (re) {
474 char opts[OPTBUF_SIZE];
475 rb_reg_check(re);
476 if (*option_to_str(opts, RREGEXP_PTR(re)->options))
477 rb_str_buf_cat2(str, opts);
478 if (RBASIC(re)->flags & REG_ENCODING_NONE)
479 rb_str_buf_cat2(str, "n");
480 }
481 return str;
482}
483
484
485/*
486 * call-seq:
487 * source -> string
488 *
489 * Returns the original string of +self+:
490 *
491 * /ab+c/ix.source # => "ab+c"
492 *
493 * Regexp escape sequences are retained:
494 *
495 * /\x20\+/.source # => "\\x20\\+"
496 *
497 * Lexer escape characters are not retained:
498 *
499 * /\//.source # => "/"
500 *
501 */
502
503static VALUE
504rb_reg_source(VALUE re)
505{
506 VALUE str;
507
508 rb_reg_check(re);
509 str = rb_str_dup(RREGEXP_SRC(re));
510 return str;
511}
512
513/*
514 * call-seq:
515 * inspect -> string
516 *
517 * Returns a nicely-formatted string representation of +self+:
518 *
519 * /ab+c/ix.inspect # => "/ab+c/ix"
520 *
521 * Related: Regexp#to_s.
522 */
523
524static VALUE
525rb_reg_inspect(VALUE re)
526{
527 if (!RREGEXP_PTR(re) || !RREGEXP_SRC(re) || !RREGEXP_SRC_PTR(re)) {
528 return rb_any_to_s(re);
529 }
530 return rb_reg_desc(re);
531}
532
533static VALUE rb_reg_str_with_term(VALUE re, int term);
534
535/*
536 * call-seq:
537 * to_s -> string
538 *
539 * Returns a string showing the options and string of +self+:
540 *
541 * r0 = /ab+c/ix
542 * s0 = r0.to_s # => "(?ix-m:ab+c)"
543 *
544 * The returned string may be used as an argument to Regexp.new,
545 * or as interpolated text for a
546 * {Regexp interpolation}[rdoc-ref:Regexp@Interpolation+Mode]:
547 *
548 * r1 = Regexp.new(s0) # => /(?ix-m:ab+c)/
549 * r2 = /#{s0}/ # => /(?ix-m:ab+c)/
550 *
551 * Note that +r1+ and +r2+ are not equal to +r0+
552 * because their original strings are different:
553 *
554 * r0 == r1 # => false
555 * r0.source # => "ab+c"
556 * r1.source # => "(?ix-m:ab+c)"
557 *
558 * Related: Regexp#inspect.
559 *
560 */
561
562static VALUE
563rb_reg_to_s(VALUE re)
564{
565 return rb_reg_str_with_term(re, '/');
566}
567
568static VALUE
569rb_reg_str_with_term(VALUE re, int term)
570{
571 int options, opt;
572 const int embeddable = ONIG_OPTION_MULTILINE|ONIG_OPTION_IGNORECASE|ONIG_OPTION_EXTEND;
573 VALUE str = rb_str_buf_new2("(?");
574 char optbuf[OPTBUF_SIZE + 1]; /* for '-' */
575 rb_encoding *enc = rb_enc_get(re);
576
577 rb_reg_check(re);
578
579 rb_enc_copy(str, re);
580 options = RREGEXP_PTR(re)->options;
581 VALUE src_str = RREGEXP_SRC(re);
582 const UChar *ptr = (UChar *)RSTRING_PTR(src_str);
583 long len = RSTRING_LEN(src_str);
584 again:
585 if (len >= 4 && ptr[0] == '(' && ptr[1] == '?') {
586 int err = 1;
587 ptr += 2;
588 if ((len -= 2) > 0) {
589 do {
590 opt = char_to_option((int )*ptr);
591 if (opt != 0) {
592 options |= opt;
593 }
594 else {
595 break;
596 }
597 ++ptr;
598 } while (--len > 0);
599 }
600 if (len > 1 && *ptr == '-') {
601 ++ptr;
602 --len;
603 do {
604 opt = char_to_option((int )*ptr);
605 if (opt != 0) {
606 options &= ~opt;
607 }
608 else {
609 break;
610 }
611 ++ptr;
612 } while (--len > 0);
613 }
614 if (*ptr == ')') {
615 --len;
616 ++ptr;
617 goto again;
618 }
619 if (*ptr == ':' && ptr[len-1] == ')') {
620 Regexp *rp;
621 VALUE verbose = ruby_verbose;
623
624 ++ptr;
625 len -= 2;
626 err = onig_new(&rp, ptr, ptr + len, options,
627 enc, OnigDefaultSyntax, NULL);
628 onig_free(rp);
629 ruby_verbose = verbose;
630 }
631 if (err) {
632 options = RREGEXP_PTR(re)->options;
633 ptr = (UChar*)RREGEXP_SRC_PTR(re);
634 len = RREGEXP_SRC_LEN(re);
635 }
636 }
637
638 if (*option_to_str(optbuf, options)) rb_str_buf_cat2(str, optbuf);
639
640 if ((options & embeddable) != embeddable) {
641 optbuf[0] = '-';
642 option_to_str(optbuf + 1, ~options);
643 rb_str_buf_cat2(str, optbuf);
644 }
645
646 rb_str_buf_cat2(str, ":");
647 if (rb_enc_asciicompat(enc)) {
648 rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term);
649 rb_str_buf_cat2(str, ")");
650 }
651 else {
652 const char *s, *e;
653 char *paren;
654 ptrdiff_t n;
655 rb_str_buf_cat2(str, ")");
656 rb_enc_associate(str, rb_usascii_encoding());
657 str = rb_str_encode(str, rb_enc_from_encoding(enc), 0, Qnil);
658
659 /* backup encoded ")" to paren */
660 s = RSTRING_PTR(str);
661 e = RSTRING_END(str);
662 s = rb_enc_left_char_head(s, e-1, e, enc);
663 n = e - s;
664 paren = ALLOCA_N(char, n);
665 memcpy(paren, s, n);
666 rb_str_resize(str, RSTRING_LEN(str) - n);
667
668 rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term);
669 rb_str_buf_cat(str, paren, n);
670 }
671 rb_enc_copy(str, re);
672
673 RB_GC_GUARD(src_str);
674
675 return str;
676}
677
678NORETURN(static void rb_reg_raise(const char *err, VALUE re));
679
680static void
681rb_reg_raise(const char *err, VALUE re)
682{
683 VALUE desc = rb_reg_desc(re);
684
685 rb_raise(rb_eRegexpError, "%s: %"PRIsVALUE, err, desc);
686}
687
688static VALUE
689rb_enc_reg_error_desc(const char *s, long len, rb_encoding *enc, int options, const char *err)
690{
691 char opts[OPTBUF_SIZE + 1]; /* for '/' */
692 VALUE desc = rb_str_buf_new2(err);
693 rb_encoding *resenc = rb_default_internal_encoding();
694 if (resenc == NULL) resenc = rb_default_external_encoding();
695
696 rb_enc_associate(desc, enc);
697 rb_str_buf_cat2(desc, ": /");
698 rb_reg_expr_str(desc, s, len, enc, resenc, '/');
699 opts[0] = '/';
700 option_to_str(opts + 1, options);
701 rb_str_buf_cat2(desc, opts);
702 return rb_exc_new3(rb_eRegexpError, desc);
703}
704
705NORETURN(static void rb_enc_reg_raise(const char *s, long len, rb_encoding *enc, int options, const char *err));
706
707static void
708rb_enc_reg_raise(const char *s, long len, rb_encoding *enc, int options, const char *err)
709{
710 rb_exc_raise(rb_enc_reg_error_desc(s, len, enc, options, err));
711}
712
713static VALUE
714rb_reg_error_desc(VALUE str, int options, const char *err)
715{
716 return rb_enc_reg_error_desc(RSTRING_PTR(str), RSTRING_LEN(str),
717 rb_enc_get(str), options, err);
718}
719
720NORETURN(static void rb_reg_raise_str(VALUE str, int options, const char *err));
721
722static void
723rb_reg_raise_str(VALUE str, int options, const char *err)
724{
725 rb_exc_raise(rb_reg_error_desc(str, options, err));
726}
727
728
729/*
730 * call-seq:
731 * casefold?-> true or false
732 *
733 * Returns +true+ if the case-insensitivity flag in +self+ is set,
734 * +false+ otherwise:
735 *
736 * /a/.casefold? # => false
737 * /a/i.casefold? # => true
738 * /(?i:a)/.casefold? # => false
739 *
740 */
741
742static VALUE
743rb_reg_casefold_p(VALUE re)
744{
745 rb_reg_check(re);
746 return RBOOL(RREGEXP_PTR(re)->options & ONIG_OPTION_IGNORECASE);
747}
748
749
750/*
751 * call-seq:
752 * options -> integer
753 *
754 * Returns an integer whose bits show the options set in +self+.
755 *
756 * The option bits are:
757 *
758 * Regexp::IGNORECASE # => 1
759 * Regexp::EXTENDED # => 2
760 * Regexp::MULTILINE # => 4
761 *
762 * Examples:
763 *
764 * /foo/.options # => 0
765 * /foo/i.options # => 1
766 * /foo/x.options # => 2
767 * /foo/m.options # => 4
768 * /foo/mix.options # => 7
769 *
770 * Note that additional bits may be set in the returned integer;
771 * these are maintained internally in +self+, are ignored if passed
772 * to Regexp.new, and may be ignored by the caller:
773 *
774 * Returns the set of bits corresponding to the options used when
775 * creating this regexp (see Regexp::new for details). Note that
776 * additional bits may be set in the returned options: these are used
777 * internally by the regular expression code. These extra bits are
778 * ignored if the options are passed to Regexp::new:
779 *
780 * r = /\xa1\xa2/e # => /\xa1\xa2/
781 * r.source # => "\\xa1\\xa2"
782 * r.options # => 16
783 * Regexp.new(r.source, r.options) # => /\xa1\xa2/
784 *
785 */
786
787static VALUE
788rb_reg_options_m(VALUE re)
789{
790 int options = rb_reg_options(re);
791 return INT2NUM(options);
792}
793
794static int
795reg_names_iter(const OnigUChar *name, const OnigUChar *name_end,
796 int back_num, int *back_refs, OnigRegex regex, void *arg)
797{
798 VALUE ary = (VALUE)arg;
799 rb_ary_push(ary, rb_enc_str_new((const char *)name, name_end-name, regex->enc));
800 return 0;
801}
802
803/*
804 * call-seq:
805 * names -> array_of_names
806 *
807 * Returns an array of names of captures
808 * (see {Named Captures}[rdoc-ref:Regexp@Named+Captures]):
809 *
810 * /(?<foo>.)(?<bar>.)(?<baz>.)/.names # => ["foo", "bar", "baz"]
811 * /(?<foo>.)(?<foo>.)/.names # => ["foo"]
812 * /(.)(.)/.names # => []
813 *
814 */
815
816static VALUE
817rb_reg_names(VALUE re)
818{
819 VALUE ary;
820 rb_reg_check(re);
821 ary = rb_ary_new_capa(onig_number_of_names(RREGEXP_PTR(re)));
822 onig_foreach_name(RREGEXP_PTR(re), reg_names_iter, (void*)ary);
823 return ary;
824}
825
826static int
827reg_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end,
828 int back_num, int *back_refs, OnigRegex regex, void *arg)
829{
830 VALUE hash = (VALUE)arg;
831 VALUE ary = rb_ary_new2(back_num);
832 int i;
833
834 for (i = 0; i < back_num; i++)
835 rb_ary_store(ary, i, INT2NUM(back_refs[i]));
836
837 rb_hash_aset(hash, rb_str_new((const char*)name, name_end-name),ary);
838
839 return 0;
840}
841
842/*
843 * call-seq:
844 * named_captures -> hash
845 *
846 * Returns a hash representing named captures of +self+
847 * (see {Named Captures}[rdoc-ref:Regexp@Named+Captures]):
848 *
849 * - Each key is the name of a named capture.
850 * - Each value is an array of integer indexes for that named capture.
851 *
852 * Examples:
853 *
854 * /(?<foo>.)(?<bar>.)/.named_captures # => {"foo"=>[1], "bar"=>[2]}
855 * /(?<foo>.)(?<foo>.)/.named_captures # => {"foo"=>[1, 2]}
856 * /(.)(.)/.named_captures # => {}
857 *
858 */
859
860static VALUE
861rb_reg_named_captures(VALUE re)
862{
863 regex_t *reg = (rb_reg_check(re), RREGEXP_PTR(re));
864 VALUE hash = rb_hash_new_with_size(onig_number_of_names(reg));
865 onig_foreach_name(reg, reg_named_captures_iter, (void*)hash);
866 return hash;
867}
868
869static int
870onig_new_with_source(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
871 OnigOptionType option, OnigEncoding enc, const OnigSyntaxType* syntax,
872 OnigErrorInfo* einfo, const char *sourcefile, int sourceline)
873{
874 int r;
875
876 *reg = (regex_t* )malloc(sizeof(regex_t));
877 if (IS_NULL(*reg)) return ONIGERR_MEMORY;
878
879 r = onig_reg_init(*reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
880 if (r) goto err;
881
882 r = onig_compile_ruby(*reg, pattern, pattern_end, einfo, sourcefile, sourceline);
883 if (r) {
884 err:
885 onig_free(*reg);
886 *reg = NULL;
887 }
888 return r;
889}
890
891static Regexp*
892make_regexp(const char *s, long len, rb_encoding *enc, int flags, onig_errmsg_buffer err,
893 const char *sourcefile, int sourceline)
894{
895 Regexp *rp;
896 int r;
897 OnigErrorInfo einfo;
898
899 /* Handle escaped characters first. */
900
901 /* Build a copy of the string (in dest) with the
902 escaped characters translated, and generate the regex
903 from that.
904 */
905
906 r = onig_new_with_source(&rp, (UChar*)s, (UChar*)(s + len), flags,
907 enc, OnigDefaultSyntax, &einfo, sourcefile, sourceline);
908 if (r) {
909 onig_error_code_to_str((UChar*)err, r, &einfo);
910 return 0;
911 }
912 return rp;
913}
914
915
916/*
917 * Document-class: MatchData
918 *
919 * MatchData encapsulates the result of matching a Regexp against
920 * string. It is returned by Regexp#match and String#match, and also
921 * stored in a global variable returned by Regexp.last_match.
922 *
923 * Usage:
924 *
925 * url = 'https://docs.ruby-lang.org/en/2.5.0/MatchData.html'
926 * m = url.match(/(\d\.?)+/) # => #<MatchData "2.5.0" 1:"0">
927 * m.string # => "https://docs.ruby-lang.org/en/2.5.0/MatchData.html"
928 * m.regexp # => /(\d\.?)+/
929 * # entire matched substring:
930 * m[0] # => "2.5.0"
931 *
932 * # Working with unnamed captures
933 * m = url.match(%r{([^/]+)/([^/]+)\.html$})
934 * m.captures # => ["2.5.0", "MatchData"]
935 * m[1] # => "2.5.0"
936 * m.values_at(1, 2) # => ["2.5.0", "MatchData"]
937 *
938 * # Working with named captures
939 * m = url.match(%r{(?<version>[^/]+)/(?<module>[^/]+)\.html$})
940 * m.captures # => ["2.5.0", "MatchData"]
941 * m.named_captures # => {"version"=>"2.5.0", "module"=>"MatchData"}
942 * m[:version] # => "2.5.0"
943 * m.values_at(:version, :module)
944 * # => ["2.5.0", "MatchData"]
945 * # Numerical indexes are working, too
946 * m[1] # => "2.5.0"
947 * m.values_at(1, 2) # => ["2.5.0", "MatchData"]
948 *
949 * == Global variables equivalence
950 *
951 * Parts of last MatchData (returned by Regexp.last_match) are also
952 * aliased as global variables:
953 *
954 * * <code>$~</code> is Regexp.last_match;
955 * * <code>$&</code> is Regexp.last_match<code>[ 0 ]</code>;
956 * * <code>$1</code>, <code>$2</code>, and so on are
957 * Regexp.last_match<code>[ i ]</code> (captures by number);
958 * * <code>$`</code> is Regexp.last_match<code>.pre_match</code>;
959 * * <code>$'</code> is Regexp.last_match<code>.post_match</code>;
960 * * <code>$+</code> is Regexp.last_match<code>[ -1 ]</code> (the last capture).
961 *
962 * See also Regexp@Global+Variables.
963 */
964
966
967static VALUE
968match_alloc(VALUE klass)
969{
970 size_t alloc_size = sizeof(struct RMatch) + sizeof(rb_matchext_t);
972 NEWOBJ_OF(match, struct RMatch, klass, flags, alloc_size, 0);
973
974 match->str = Qfalse;
975 match->regexp = Qfalse;
976 memset(RMATCH_EXT(match), 0, sizeof(rb_matchext_t));
977
978 return (VALUE)match;
979}
980
981int
982rb_reg_region_copy(struct re_registers *to, const struct re_registers *from)
983{
984 onig_region_copy(to, (OnigRegion *)from);
985 if (to->allocated) return 0;
986 rb_gc();
987 onig_region_copy(to, (OnigRegion *)from);
988 if (to->allocated) return 0;
989 return ONIGERR_MEMORY;
990}
991
992typedef struct {
993 long byte_pos;
994 long char_pos;
995} pair_t;
996
997static int
998pair_byte_cmp(const void *pair1, const void *pair2)
999{
1000 long diff = ((pair_t*)pair1)->byte_pos - ((pair_t*)pair2)->byte_pos;
1001#if SIZEOF_LONG > SIZEOF_INT
1002 return diff ? diff > 0 ? 1 : -1 : 0;
1003#else
1004 return (int)diff;
1005#endif
1006}
1007
1008static void
1009update_char_offset(VALUE match)
1010{
1011 rb_matchext_t *rm = RMATCH_EXT(match);
1012 struct re_registers *regs;
1013 int i, num_regs, num_pos;
1014 long c;
1015 char *s, *p, *q;
1016 rb_encoding *enc;
1017 pair_t *pairs;
1018 VALUE pairs_obj = Qnil;
1019
1021 return;
1022
1023 regs = &rm->regs;
1024 num_regs = rm->regs.num_regs;
1025
1026 if (rm->char_offset_num_allocated < num_regs) {
1027 SIZED_REALLOC_N(rm->char_offset, struct rmatch_offset, num_regs, rm->char_offset_num_allocated);
1028 rm->char_offset_num_allocated = num_regs;
1029 }
1030
1031 enc = rb_enc_get(RMATCH(match)->str);
1032 if (rb_enc_mbmaxlen(enc) == 1) {
1033 for (i = 0; i < num_regs; i++) {
1034 rm->char_offset[i].beg = BEG(i);
1035 rm->char_offset[i].end = END(i);
1036 }
1037 return;
1038 }
1039
1040 pairs = RB_ALLOCV_N(pair_t, pairs_obj, num_regs * 2);
1041 num_pos = 0;
1042 for (i = 0; i < num_regs; i++) {
1043 if (BEG(i) < 0)
1044 continue;
1045 pairs[num_pos++].byte_pos = BEG(i);
1046 pairs[num_pos++].byte_pos = END(i);
1047 }
1048 qsort(pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1049
1050 s = p = RSTRING_PTR(RMATCH(match)->str);
1051 c = 0;
1052 for (i = 0; i < num_pos; i++) {
1053 q = s + pairs[i].byte_pos;
1054 c += rb_enc_strlen(p, q, enc);
1055 pairs[i].char_pos = c;
1056 p = q;
1057 }
1058
1059 for (i = 0; i < num_regs; i++) {
1060 pair_t key, *found;
1061 if (BEG(i) < 0) {
1062 rm->char_offset[i].beg = -1;
1063 rm->char_offset[i].end = -1;
1064 continue;
1065 }
1066
1067 key.byte_pos = BEG(i);
1068 found = bsearch(&key, pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1069 rm->char_offset[i].beg = found->char_pos;
1070
1071 key.byte_pos = END(i);
1072 found = bsearch(&key, pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1073 rm->char_offset[i].end = found->char_pos;
1074 }
1075
1076 RB_ALLOCV_END(pairs_obj);
1077}
1078
1079static VALUE
1080match_check(VALUE match)
1081{
1082 if (!RMATCH(match)->regexp) {
1083 rb_raise(rb_eTypeError, "uninitialized MatchData");
1084 }
1085 return match;
1086}
1087
1088/* :nodoc: */
1089static VALUE
1090match_init_copy(VALUE obj, VALUE orig)
1091{
1092 rb_matchext_t *rm;
1093
1094 if (!OBJ_INIT_COPY(obj, orig)) return obj;
1095
1096 RB_OBJ_WRITE(obj, &RMATCH(obj)->str, RMATCH(orig)->str);
1097 RB_OBJ_WRITE(obj, &RMATCH(obj)->regexp, RMATCH(orig)->regexp);
1098
1099 rm = RMATCH_EXT(obj);
1100 if (rb_reg_region_copy(&rm->regs, RMATCH_REGS(orig)))
1101 rb_memerror();
1102
1103 if (RMATCH_EXT(orig)->char_offset_num_allocated) {
1104 if (rm->char_offset_num_allocated < rm->regs.num_regs) {
1105 SIZED_REALLOC_N(rm->char_offset, struct rmatch_offset, rm->regs.num_regs, rm->char_offset_num_allocated);
1106 rm->char_offset_num_allocated = rm->regs.num_regs;
1107 }
1108 MEMCPY(rm->char_offset, RMATCH_EXT(orig)->char_offset,
1109 struct rmatch_offset, rm->regs.num_regs);
1110 RB_GC_GUARD(orig);
1111 }
1112
1113 return obj;
1114}
1115
1116
1117/*
1118 * call-seq:
1119 * regexp -> regexp
1120 *
1121 * Returns the regexp that produced the match:
1122 *
1123 * m = /a.*b/.match("abc") # => #<MatchData "ab">
1124 * m.regexp # => /a.*b/
1125 *
1126 */
1127
1128static VALUE
1129match_regexp(VALUE match)
1130{
1131 VALUE regexp;
1132 match_check(match);
1133 regexp = RMATCH(match)->regexp;
1134 if (NIL_P(regexp)) {
1135 VALUE str = rb_reg_nth_match(0, match);
1136 regexp = rb_reg_regcomp(rb_reg_quote(str));
1137 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, regexp);
1138 }
1139 return regexp;
1140}
1141
1142/*
1143 * call-seq:
1144 * names -> array_of_names
1145 *
1146 * Returns an array of the capture names
1147 * (see {Named Captures}[rdoc-ref:Regexp@Named+Captures]):
1148 *
1149 * m = /(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge")
1150 * # => #<MatchData "hog" foo:"h" bar:"o" baz:"g">
1151 * m.names # => ["foo", "bar", "baz"]
1152 *
1153 * m = /foo/.match('foo') # => #<MatchData "foo">
1154 * m.names # => [] # No named captures.
1155 *
1156 * Equivalent to:
1157 *
1158 * m = /(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge")
1159 * m.regexp.names # => ["foo", "bar", "baz"]
1160 *
1161 */
1162
1163static VALUE
1164match_names(VALUE match)
1165{
1166 match_check(match);
1167 if (NIL_P(RMATCH(match)->regexp))
1168 return rb_ary_new_capa(0);
1169 return rb_reg_names(RMATCH(match)->regexp);
1170}
1171
1172/*
1173 * call-seq:
1174 * size -> integer
1175 *
1176 * Returns size of the match array:
1177 *
1178 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1179 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
1180 * m.size # => 5
1181 *
1182 */
1183
1184static VALUE
1185match_size(VALUE match)
1186{
1187 match_check(match);
1188 return INT2FIX(RMATCH_REGS(match)->num_regs);
1189}
1190
1191static int name_to_backref_number(const struct re_registers *, VALUE, const char*, const char*);
1192NORETURN(static void name_to_backref_error(VALUE name));
1193
1194static void
1195name_to_backref_error(VALUE name)
1196{
1197 rb_raise(rb_eIndexError, "undefined group name reference: % "PRIsVALUE,
1198 name);
1199}
1200
1201static void
1202backref_number_check(struct re_registers *regs, int i)
1203{
1204 if (i < 0 || regs->num_regs <= i)
1205 rb_raise(rb_eIndexError, "index %d out of matches", i);
1206}
1207
1208static int
1209match_backref_number(VALUE match, VALUE backref)
1210{
1211 const char *name;
1212 int num;
1213
1214 struct re_registers *regs = RMATCH_REGS(match);
1215 VALUE regexp = RMATCH(match)->regexp;
1216
1217 match_check(match);
1218 if (SYMBOL_P(backref)) {
1219 backref = rb_sym2str(backref);
1220 }
1221 else if (!RB_TYPE_P(backref, T_STRING)) {
1222 return NUM2INT(backref);
1223 }
1224 name = StringValueCStr(backref);
1225
1226 num = name_to_backref_number(regs, regexp, name, name + RSTRING_LEN(backref));
1227
1228 if (num < 1) {
1229 name_to_backref_error(backref);
1230 }
1231
1232 return num;
1233}
1234
1235int
1237{
1238 return match_backref_number(match, backref);
1239}
1240
1241/*
1242 * call-seq:
1243 * offset(n) -> [start_offset, end_offset]
1244 * offset(name) -> [start_offset, end_offset]
1245 *
1246 * :include: doc/matchdata/offset.rdoc
1247 *
1248 */
1249
1250static VALUE
1251match_offset(VALUE match, VALUE n)
1252{
1253 int i = match_backref_number(match, n);
1254 struct re_registers *regs = RMATCH_REGS(match);
1255
1256 match_check(match);
1257 backref_number_check(regs, i);
1258
1259 if (BEG(i) < 0)
1260 return rb_assoc_new(Qnil, Qnil);
1261
1262 update_char_offset(match);
1263 return rb_assoc_new(LONG2NUM(RMATCH_EXT(match)->char_offset[i].beg),
1264 LONG2NUM(RMATCH_EXT(match)->char_offset[i].end));
1265}
1266
1267/*
1268 * call-seq:
1269 * mtch.byteoffset(n) -> array
1270 *
1271 * Returns a two-element array containing the beginning and ending byte-based offsets of
1272 * the <em>n</em>th match.
1273 * <em>n</em> can be a string or symbol to reference a named capture.
1274 *
1275 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1276 * m.byteoffset(0) #=> [1, 7]
1277 * m.byteoffset(4) #=> [6, 7]
1278 *
1279 * m = /(?<foo>.)(.)(?<bar>.)/.match("hoge")
1280 * p m.byteoffset(:foo) #=> [0, 1]
1281 * p m.byteoffset(:bar) #=> [2, 3]
1282 *
1283 */
1284
1285static VALUE
1286match_byteoffset(VALUE match, VALUE n)
1287{
1288 int i = match_backref_number(match, n);
1289 struct re_registers *regs = RMATCH_REGS(match);
1290
1291 match_check(match);
1292 backref_number_check(regs, i);
1293
1294 if (BEG(i) < 0)
1295 return rb_assoc_new(Qnil, Qnil);
1296 return rb_assoc_new(LONG2NUM(BEG(i)), LONG2NUM(END(i)));
1297}
1298
1299
1300/*
1301 * call-seq:
1302 * bytebegin(n) -> integer
1303 * bytebegin(name) -> integer
1304 *
1305 * :include: doc/matchdata/bytebegin.rdoc
1306 *
1307 */
1308
1309static VALUE
1310match_bytebegin(VALUE match, VALUE n)
1311{
1312 int i = match_backref_number(match, n);
1313 struct re_registers *regs = RMATCH_REGS(match);
1314
1315 match_check(match);
1316 backref_number_check(regs, i);
1317
1318 if (BEG(i) < 0)
1319 return Qnil;
1320 return LONG2NUM(BEG(i));
1321}
1322
1323
1324/*
1325 * call-seq:
1326 * byteend(n) -> integer
1327 * byteend(name) -> integer
1328 *
1329 * :include: doc/matchdata/byteend.rdoc
1330 *
1331 */
1332
1333static VALUE
1334match_byteend(VALUE match, VALUE n)
1335{
1336 int i = match_backref_number(match, n);
1337 struct re_registers *regs = RMATCH_REGS(match);
1338
1339 match_check(match);
1340 backref_number_check(regs, i);
1341
1342 if (BEG(i) < 0)
1343 return Qnil;
1344 return LONG2NUM(END(i));
1345}
1346
1347
1348/*
1349 * call-seq:
1350 * begin(n) -> integer
1351 * begin(name) -> integer
1352 *
1353 * :include: doc/matchdata/begin.rdoc
1354 *
1355 */
1356
1357static VALUE
1358match_begin(VALUE match, VALUE n)
1359{
1360 int i = match_backref_number(match, n);
1361 struct re_registers *regs = RMATCH_REGS(match);
1362
1363 match_check(match);
1364 backref_number_check(regs, i);
1365
1366 if (BEG(i) < 0)
1367 return Qnil;
1368
1369 update_char_offset(match);
1370 return LONG2NUM(RMATCH_EXT(match)->char_offset[i].beg);
1371}
1372
1373
1374/*
1375 * call-seq:
1376 * end(n) -> integer
1377 * end(name) -> integer
1378 *
1379 * :include: doc/matchdata/end.rdoc
1380 *
1381 */
1382
1383static VALUE
1384match_end(VALUE match, VALUE n)
1385{
1386 int i = match_backref_number(match, n);
1387 struct re_registers *regs = RMATCH_REGS(match);
1388
1389 match_check(match);
1390 backref_number_check(regs, i);
1391
1392 if (BEG(i) < 0)
1393 return Qnil;
1394
1395 update_char_offset(match);
1396 return LONG2NUM(RMATCH_EXT(match)->char_offset[i].end);
1397}
1398
1399/*
1400 * call-seq:
1401 * match(n) -> string or nil
1402 * match(name) -> string or nil
1403 *
1404 * Returns the matched substring corresponding to the given argument.
1405 *
1406 * When non-negative argument +n+ is given,
1407 * returns the matched substring for the <tt>n</tt>th match:
1408 *
1409 * m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.")
1410 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8" 5:nil>
1411 * m.match(0) # => "HX1138"
1412 * m.match(4) # => "8"
1413 * m.match(5) # => nil
1414 *
1415 * When string or symbol argument +name+ is given,
1416 * returns the matched substring for the given name:
1417 *
1418 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
1419 * # => #<MatchData "hoge" foo:"h" bar:"ge">
1420 * m.match('foo') # => "h"
1421 * m.match(:bar) # => "ge"
1422 *
1423 */
1424
1425static VALUE
1426match_nth(VALUE match, VALUE n)
1427{
1428 int i = match_backref_number(match, n);
1429 struct re_registers *regs = RMATCH_REGS(match);
1430
1431 backref_number_check(regs, i);
1432
1433 long start = BEG(i), end = END(i);
1434 if (start < 0)
1435 return Qnil;
1436
1437 return rb_str_subseq(RMATCH(match)->str, start, end - start);
1438}
1439
1440/*
1441 * call-seq:
1442 * match_length(n) -> integer or nil
1443 * match_length(name) -> integer or nil
1444 *
1445 * Returns the length (in characters) of the matched substring
1446 * corresponding to the given argument.
1447 *
1448 * When non-negative argument +n+ is given,
1449 * returns the length of the matched substring
1450 * for the <tt>n</tt>th match:
1451 *
1452 * m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.")
1453 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8" 5:nil>
1454 * m.match_length(0) # => 6
1455 * m.match_length(4) # => 1
1456 * m.match_length(5) # => nil
1457 *
1458 * When string or symbol argument +name+ is given,
1459 * returns the length of the matched substring
1460 * for the named match:
1461 *
1462 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
1463 * # => #<MatchData "hoge" foo:"h" bar:"ge">
1464 * m.match_length('foo') # => 1
1465 * m.match_length(:bar) # => 2
1466 *
1467 */
1468
1469static VALUE
1470match_nth_length(VALUE match, VALUE n)
1471{
1472 int i = match_backref_number(match, n);
1473 struct re_registers *regs = RMATCH_REGS(match);
1474
1475 match_check(match);
1476 backref_number_check(regs, i);
1477
1478 if (BEG(i) < 0)
1479 return Qnil;
1480
1481 update_char_offset(match);
1482 const struct rmatch_offset *const ofs =
1483 &RMATCH_EXT(match)->char_offset[i];
1484 return LONG2NUM(ofs->end - ofs->beg);
1485}
1486
1487#define MATCH_BUSY FL_USER2
1488
1489void
1491{
1492 FL_SET(match, MATCH_BUSY);
1493}
1494
1495void
1496rb_match_unbusy(VALUE match)
1497{
1498 FL_UNSET(match, MATCH_BUSY);
1499}
1500
1501int
1502rb_match_count(VALUE match)
1503{
1504 struct re_registers *regs;
1505 if (NIL_P(match)) return -1;
1506 regs = RMATCH_REGS(match);
1507 if (!regs) return -1;
1508 return regs->num_regs;
1509}
1510
1511static void
1512match_set_string(VALUE m, VALUE string, long pos, long len)
1513{
1514 struct RMatch *match = (struct RMatch *)m;
1515 rb_matchext_t *rmatch = RMATCH_EXT(match);
1516
1517 RB_OBJ_WRITE(match, &RMATCH(match)->str, string);
1518 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, Qnil);
1519 int err = onig_region_resize(&rmatch->regs, 1);
1520 if (err) rb_memerror();
1521 rmatch->regs.beg[0] = pos;
1522 rmatch->regs.end[0] = pos + len;
1523}
1524
1525VALUE
1526rb_backref_set_string(VALUE string, long pos, long len)
1527{
1528 VALUE match = rb_backref_get();
1529 if (NIL_P(match) || FL_TEST(match, MATCH_BUSY)) {
1530 match = match_alloc(rb_cMatch);
1531 }
1532 match_set_string(match, string, pos, len);
1533 rb_backref_set(match);
1534 return match;
1535}
1536
1537/*
1538 * call-seq:
1539 * fixed_encoding? -> true or false
1540 *
1541 * Returns +false+ if +self+ is applicable to
1542 * a string with any ASCII-compatible encoding;
1543 * otherwise returns +true+:
1544 *
1545 * r = /a/ # => /a/
1546 * r.fixed_encoding? # => false
1547 * r.match?("\u{6666} a") # => true
1548 * r.match?("\xa1\xa2 a".force_encoding("euc-jp")) # => true
1549 * r.match?("abc".force_encoding("euc-jp")) # => true
1550 *
1551 * r = /a/u # => /a/
1552 * r.fixed_encoding? # => true
1553 * r.match?("\u{6666} a") # => true
1554 * r.match?("\xa1\xa2".force_encoding("euc-jp")) # Raises exception.
1555 * r.match?("abc".force_encoding("euc-jp")) # => true
1556 *
1557 * r = /\u{6666}/ # => /\u{6666}/
1558 * r.fixed_encoding? # => true
1559 * r.encoding # => #<Encoding:UTF-8>
1560 * r.match?("\u{6666} a") # => true
1561 * r.match?("\xa1\xa2".force_encoding("euc-jp")) # Raises exception.
1562 * r.match?("abc".force_encoding("euc-jp")) # => false
1563 *
1564 */
1565
1566static VALUE
1567rb_reg_fixed_encoding_p(VALUE re)
1568{
1569 return RBOOL(FL_TEST(re, KCODE_FIXED));
1570}
1571
1572static VALUE
1573rb_reg_preprocess(const char *p, const char *end, rb_encoding *enc,
1574 rb_encoding **fixed_enc, onig_errmsg_buffer err, int options);
1575
1576NORETURN(static void reg_enc_error(VALUE re, VALUE str));
1577
1578static void
1579reg_enc_error(VALUE re, VALUE str)
1580{
1581 rb_raise(rb_eEncCompatError,
1582 "incompatible encoding regexp match (%s regexp with %s string)",
1583 rb_enc_inspect_name(rb_enc_get(re)),
1584 rb_enc_inspect_name(rb_enc_get(str)));
1585}
1586
1587static inline int
1588str_coderange(VALUE str)
1589{
1590 int cr = ENC_CODERANGE(str);
1591 if (cr == ENC_CODERANGE_UNKNOWN) {
1593 }
1594 return cr;
1595}
1596
1597static rb_encoding*
1598rb_reg_prepare_enc(VALUE re, VALUE str, int warn)
1599{
1600 rb_encoding *enc = 0;
1601 int cr = str_coderange(str);
1602
1603 if (cr == ENC_CODERANGE_BROKEN) {
1604 rb_raise(rb_eArgError,
1605 "invalid byte sequence in %s",
1606 rb_enc_name(rb_enc_get(str)));
1607 }
1608
1609 rb_reg_check(re);
1610 enc = rb_enc_get(str);
1611 if (RREGEXP_PTR(re)->enc == enc) {
1612 }
1613 else if (cr == ENC_CODERANGE_7BIT &&
1614 RREGEXP_PTR(re)->enc == rb_usascii_encoding()) {
1615 enc = RREGEXP_PTR(re)->enc;
1616 }
1617 else if (!rb_enc_asciicompat(enc)) {
1618 reg_enc_error(re, str);
1619 }
1620 else if (rb_reg_fixed_encoding_p(re)) {
1621 if ((!rb_enc_asciicompat(RREGEXP_PTR(re)->enc) ||
1622 cr != ENC_CODERANGE_7BIT)) {
1623 reg_enc_error(re, str);
1624 }
1625 enc = RREGEXP_PTR(re)->enc;
1626 }
1627 else if (warn && (RBASIC(re)->flags & REG_ENCODING_NONE) &&
1628 enc != rb_ascii8bit_encoding() &&
1629 cr != ENC_CODERANGE_7BIT) {
1630 rb_warn("historical binary regexp match /.../n against %s string",
1631 rb_enc_name(enc));
1632 }
1633 return enc;
1634}
1635
1636regex_t *
1638{
1639 int r;
1640 OnigErrorInfo einfo;
1641 VALUE unescaped;
1642 rb_encoding *fixed_enc = 0;
1643 rb_encoding *enc = rb_reg_prepare_enc(re, str, 1);
1644
1645 regex_t *reg = RREGEXP_PTR(re);
1646 if (reg->enc == enc) return reg;
1647
1648 rb_reg_check(re);
1649
1650 VALUE src_str = RREGEXP_SRC(re);
1651 const char *pattern = RSTRING_PTR(src_str);
1652
1653 onig_errmsg_buffer err = "";
1654 unescaped = rb_reg_preprocess(
1655 pattern, pattern + RSTRING_LEN(src_str), enc,
1656 &fixed_enc, err, 0);
1657
1658 if (NIL_P(unescaped)) {
1659 rb_raise(rb_eArgError, "regexp preprocess failed: %s", err);
1660 }
1661
1662 // inherit the timeout settings
1663 rb_hrtime_t timelimit = reg->timelimit;
1664
1665 const char *ptr;
1666 long len;
1667 RSTRING_GETMEM(unescaped, ptr, len);
1668
1669 /* If there are no other users of this regex, then we can directly overwrite it. */
1670 if (ruby_single_main_ractor && RREGEXP(re)->usecnt == 0) {
1671 regex_t tmp_reg;
1672 r = onig_new_without_alloc(&tmp_reg, (UChar *)ptr, (UChar *)(ptr + len),
1673 reg->options, enc,
1674 OnigDefaultSyntax, &einfo);
1675
1676 if (r) {
1677 /* There was an error so perform cleanups. */
1678 onig_free_body(&tmp_reg);
1679 }
1680 else {
1681 onig_free_body(reg);
1682 /* There are no errors so set reg to tmp_reg. */
1683 *reg = tmp_reg;
1684 }
1685 }
1686 else {
1687 r = onig_new(&reg, (UChar *)ptr, (UChar *)(ptr + len),
1688 reg->options, enc,
1689 OnigDefaultSyntax, &einfo);
1690 }
1691
1692 if (r) {
1693 onig_error_code_to_str((UChar*)err, r, &einfo);
1694 rb_reg_raise(err, re);
1695 }
1696
1697 reg->timelimit = timelimit;
1698
1699 RB_GC_GUARD(unescaped);
1700 RB_GC_GUARD(src_str);
1701 return reg;
1702}
1703
1704OnigPosition
1706 OnigPosition (*match)(regex_t *reg, VALUE str, struct re_registers *regs, void *args),
1707 void *args, struct re_registers *regs)
1708{
1709 regex_t *reg = rb_reg_prepare_re(re, str);
1710
1711 bool tmpreg = reg != RREGEXP_PTR(re);
1712 if (!tmpreg) RREGEXP(re)->usecnt++;
1713
1714 OnigPosition result = match(reg, str, regs, args);
1715
1716 if (!tmpreg) RREGEXP(re)->usecnt--;
1717 if (tmpreg) {
1718 onig_free(reg);
1719 }
1720
1721 if (result < 0) {
1722 onig_region_free(regs, 0);
1723
1724 switch (result) {
1725 case ONIG_MISMATCH:
1726 break;
1727 case ONIGERR_TIMEOUT:
1728 rb_raise(rb_eRegexpTimeoutError, "regexp match timeout");
1729 default: {
1730 onig_errmsg_buffer err = "";
1731 onig_error_code_to_str((UChar*)err, (int)result);
1732 rb_reg_raise(err, re);
1733 }
1734 }
1735 }
1736
1737 return result;
1738}
1739
1740long
1741rb_reg_adjust_startpos(VALUE re, VALUE str, long pos, int reverse)
1742{
1743 long range;
1744 rb_encoding *enc;
1745 UChar *p, *string;
1746
1747 enc = rb_reg_prepare_enc(re, str, 0);
1748
1749 if (reverse) {
1750 range = -pos;
1751 }
1752 else {
1753 range = RSTRING_LEN(str) - pos;
1754 }
1755
1756 if (pos > 0 && ONIGENC_MBC_MAXLEN(enc) != 1 && pos < RSTRING_LEN(str)) {
1757 string = (UChar*)RSTRING_PTR(str);
1758
1759 if (range > 0) {
1760 p = onigenc_get_right_adjust_char_head(enc, string, string + pos, string + RSTRING_LEN(str));
1761 }
1762 else {
1763 p = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, string, string + pos, string + RSTRING_LEN(str));
1764 }
1765 return p - string;
1766 }
1767
1768 return pos;
1769}
1770
1772 long pos;
1773 long range;
1774};
1775
1776static OnigPosition
1777reg_onig_search(regex_t *reg, VALUE str, struct re_registers *regs, void *args_ptr)
1778{
1779 struct reg_onig_search_args *args = (struct reg_onig_search_args *)args_ptr;
1780 const char *ptr;
1781 long len;
1782 RSTRING_GETMEM(str, ptr, len);
1783
1784 return onig_search(
1785 reg,
1786 (UChar *)ptr,
1787 (UChar *)(ptr + len),
1788 (UChar *)(ptr + args->pos),
1789 (UChar *)(ptr + args->range),
1790 regs,
1791 ONIG_OPTION_NONE);
1792}
1793
1794/* returns byte offset */
1795static long
1796rb_reg_search_set_match(VALUE re, VALUE str, long pos, int reverse, int set_backref_str, VALUE *set_match)
1797{
1798 long len = RSTRING_LEN(str);
1799 if (pos > len || pos < 0) {
1801 return -1;
1802 }
1803
1804 struct reg_onig_search_args args = {
1805 .pos = pos,
1806 .range = reverse ? 0 : len,
1807 };
1808 struct re_registers regs = {0};
1809
1810 OnigPosition result = rb_reg_onig_match(re, str, reg_onig_search, &args, &regs);
1811
1812 if (result == ONIG_MISMATCH) {
1814 return ONIG_MISMATCH;
1815 }
1816
1817 VALUE match = Qnil;
1818 if (set_match) {
1819 match = *set_match;
1820 }
1821
1822 if (NIL_P(match)) {
1823 match = rb_backref_get();
1824 }
1825
1826 if (!NIL_P(match) && FL_TEST(match, MATCH_BUSY)) {
1827 match = Qnil;
1828 }
1829
1830 if (NIL_P(match)) {
1831 match = match_alloc(rb_cMatch);
1832 }
1833 else {
1834 onig_region_free(&RMATCH_EXT(match)->regs, false);
1835 }
1836
1837 rb_matchext_t *rm = RMATCH_EXT(match);
1838 rm->regs = regs;
1839
1840 if (set_backref_str) {
1841 RB_OBJ_WRITE(match, &RMATCH(match)->str, rb_str_new4(str));
1842 rb_obj_reveal(match, rb_cMatch);
1843 }
1844 else {
1845 /* Note that a MatchData object with RMATCH(match)->str == 0 is incomplete!
1846 * We need to hide the object from ObjectSpace.each_object.
1847 * https://bugs.ruby-lang.org/issues/19159
1848 */
1849 rb_obj_hide(match);
1850 }
1851
1852 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, re);
1853 rb_backref_set(match);
1854 if (set_match) *set_match = match;
1855
1856 return result;
1857}
1858
1859long
1860rb_reg_search0(VALUE re, VALUE str, long pos, int reverse, int set_backref_str, VALUE *match)
1861{
1862 return rb_reg_search_set_match(re, str, pos, reverse, set_backref_str, match);
1863}
1864
1865long
1866rb_reg_search(VALUE re, VALUE str, long pos, int reverse)
1867{
1868 return rb_reg_search_set_match(re, str, pos, reverse, 1, NULL);
1869}
1870
1871static OnigPosition
1872reg_onig_match(regex_t *reg, VALUE str, struct re_registers *regs, void *_)
1873{
1874 const char *ptr;
1875 long len;
1876 RSTRING_GETMEM(str, ptr, len);
1877
1878 return onig_match(
1879 reg,
1880 (UChar *)ptr,
1881 (UChar *)(ptr + len),
1882 (UChar *)ptr,
1883 regs,
1884 ONIG_OPTION_NONE);
1885}
1886
1887bool
1888rb_reg_start_with_p(VALUE re, VALUE str)
1889{
1890 VALUE match = rb_backref_get();
1891 if (NIL_P(match) || FL_TEST(match, MATCH_BUSY)) {
1892 match = match_alloc(rb_cMatch);
1893 }
1894
1895 struct re_registers *regs = RMATCH_REGS(match);
1896
1897 if (rb_reg_onig_match(re, str, reg_onig_match, NULL, regs) == ONIG_MISMATCH) {
1899 return false;
1900 }
1901
1902 RB_OBJ_WRITE(match, &RMATCH(match)->str, rb_str_new4(str));
1903 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, re);
1904 rb_backref_set(match);
1905
1906 return true;
1907}
1908
1909VALUE
1911{
1912 struct re_registers *regs;
1913 if (NIL_P(match)) return Qnil;
1914 match_check(match);
1915 regs = RMATCH_REGS(match);
1916 if (nth >= regs->num_regs) {
1917 return Qnil;
1918 }
1919 if (nth < 0) {
1920 nth += regs->num_regs;
1921 if (nth <= 0) return Qnil;
1922 }
1923 return RBOOL(BEG(nth) != -1);
1924}
1925
1926VALUE
1928{
1929 VALUE str;
1930 long start, end, len;
1931 struct re_registers *regs;
1932
1933 if (NIL_P(match)) return Qnil;
1934 match_check(match);
1935 regs = RMATCH_REGS(match);
1936 if (nth >= regs->num_regs) {
1937 return Qnil;
1938 }
1939 if (nth < 0) {
1940 nth += regs->num_regs;
1941 if (nth <= 0) return Qnil;
1942 }
1943 start = BEG(nth);
1944 if (start == -1) return Qnil;
1945 end = END(nth);
1946 len = end - start;
1947 str = rb_str_subseq(RMATCH(match)->str, start, len);
1948 return str;
1949}
1950
1951VALUE
1953{
1954 return rb_reg_nth_match(0, match);
1955}
1956
1957
1958/*
1959 * call-seq:
1960 * pre_match -> string
1961 *
1962 * Returns the substring of the target string from its beginning
1963 * up to the first match in +self+ (that is, <tt>self[0]</tt>);
1964 * equivalent to regexp global variable <tt>$`</tt>:
1965 *
1966 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1967 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
1968 * m[0] # => "HX1138"
1969 * m.pre_match # => "T"
1970 *
1971 * Related: MatchData#post_match.
1972 *
1973 */
1974
1975VALUE
1977{
1978 VALUE str;
1979 struct re_registers *regs;
1980
1981 if (NIL_P(match)) return Qnil;
1982 match_check(match);
1983 regs = RMATCH_REGS(match);
1984 if (BEG(0) == -1) return Qnil;
1985 str = rb_str_subseq(RMATCH(match)->str, 0, BEG(0));
1986 return str;
1987}
1988
1989
1990/*
1991 * call-seq:
1992 * post_match -> str
1993 *
1994 * Returns the substring of the target string from
1995 * the end of the first match in +self+ (that is, <tt>self[0]</tt>)
1996 * to the end of the string;
1997 * equivalent to regexp global variable <tt>$'</tt>:
1998 *
1999 * m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
2000 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2001 * m[0] # => "HX1138"
2002 * m.post_match # => ": The Movie"\
2003 *
2004 * Related: MatchData.pre_match.
2005 *
2006 */
2007
2008VALUE
2010{
2011 VALUE str;
2012 long pos;
2013 struct re_registers *regs;
2014
2015 if (NIL_P(match)) return Qnil;
2016 match_check(match);
2017 regs = RMATCH_REGS(match);
2018 if (BEG(0) == -1) return Qnil;
2019 str = RMATCH(match)->str;
2020 pos = END(0);
2021 str = rb_str_subseq(str, pos, RSTRING_LEN(str) - pos);
2022 return str;
2023}
2024
2025static int
2026match_last_index(VALUE match)
2027{
2028 int i;
2029 struct re_registers *regs;
2030
2031 if (NIL_P(match)) return -1;
2032 match_check(match);
2033 regs = RMATCH_REGS(match);
2034 if (BEG(0) == -1) return -1;
2035
2036 for (i=regs->num_regs-1; BEG(i) == -1 && i > 0; i--)
2037 ;
2038 return i;
2039}
2040
2041VALUE
2043{
2044 int i = match_last_index(match);
2045 if (i <= 0) return Qnil;
2046 struct re_registers *regs = RMATCH_REGS(match);
2047 return rb_str_subseq(RMATCH(match)->str, BEG(i), END(i) - BEG(i));
2048}
2049
2050VALUE
2051rb_reg_last_defined(VALUE match)
2052{
2053 int i = match_last_index(match);
2054 if (i < 0) return Qnil;
2055 return RBOOL(i);
2056}
2057
2058static VALUE
2059last_match_getter(ID _x, VALUE *_y)
2060{
2062}
2063
2064static VALUE
2065prematch_getter(ID _x, VALUE *_y)
2066{
2068}
2069
2070static VALUE
2071postmatch_getter(ID _x, VALUE *_y)
2072{
2074}
2075
2076static VALUE
2077last_paren_match_getter(ID _x, VALUE *_y)
2078{
2080}
2081
2082static VALUE
2083match_array(VALUE match, int start)
2084{
2085 struct re_registers *regs;
2086 VALUE ary;
2087 VALUE target;
2088 int i;
2089
2090 match_check(match);
2091 regs = RMATCH_REGS(match);
2092 ary = rb_ary_new2(regs->num_regs);
2093 target = RMATCH(match)->str;
2094
2095 for (i=start; i<regs->num_regs; i++) {
2096 if (regs->beg[i] == -1) {
2097 rb_ary_push(ary, Qnil);
2098 }
2099 else {
2100 VALUE str = rb_str_subseq(target, regs->beg[i], regs->end[i]-regs->beg[i]);
2101 rb_ary_push(ary, str);
2102 }
2103 }
2104 return ary;
2105}
2106
2107
2108/*
2109 * call-seq:
2110 * to_a -> array
2111 *
2112 * Returns the array of matches:
2113 *
2114 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2115 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2116 * m.to_a # => ["HX1138", "H", "X", "113", "8"]
2117 *
2118 * Related: MatchData#captures.
2119 *
2120 */
2121
2122static VALUE
2123match_to_a(VALUE match)
2124{
2125 return match_array(match, 0);
2126}
2127
2128
2129/*
2130 * call-seq:
2131 * captures -> array
2132 *
2133 * Returns the array of captures,
2134 * which are all matches except <tt>m[0]</tt>:
2135 *
2136 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2137 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2138 * m[0] # => "HX1138"
2139 * m.captures # => ["H", "X", "113", "8"]
2140 *
2141 * Related: MatchData.to_a.
2142 *
2143 */
2144static VALUE
2145match_captures(VALUE match)
2146{
2147 return match_array(match, 1);
2148}
2149
2150static int
2151name_to_backref_number(const struct re_registers *regs, VALUE regexp, const char* name, const char* name_end)
2152{
2153 if (NIL_P(regexp)) return -1;
2154 return onig_name_to_backref_number(RREGEXP_PTR(regexp),
2155 (const unsigned char *)name, (const unsigned char *)name_end, regs);
2156}
2157
2158#define NAME_TO_NUMBER(regs, re, name, name_ptr, name_end) \
2159 (NIL_P(re) ? 0 : \
2160 !rb_enc_compatible(RREGEXP_SRC(re), (name)) ? 0 : \
2161 name_to_backref_number((regs), (re), (name_ptr), (name_end)))
2162
2163static int
2164namev_to_backref_number(const struct re_registers *regs, VALUE re, VALUE name)
2165{
2166 int num;
2167
2168 if (SYMBOL_P(name)) {
2169 name = rb_sym2str(name);
2170 }
2171 else if (!RB_TYPE_P(name, T_STRING)) {
2172 return -1;
2173 }
2174 num = NAME_TO_NUMBER(regs, re, name,
2175 RSTRING_PTR(name), RSTRING_END(name));
2176 if (num < 1) {
2177 name_to_backref_error(name);
2178 }
2179 return num;
2180}
2181
2182static VALUE
2183match_ary_subseq(VALUE match, long beg, long len, VALUE result)
2184{
2185 long olen = RMATCH_REGS(match)->num_regs;
2186 long j, end = olen < beg+len ? olen : beg+len;
2187 if (NIL_P(result)) result = rb_ary_new_capa(len);
2188 if (len == 0) return result;
2189
2190 for (j = beg; j < end; j++) {
2191 rb_ary_push(result, rb_reg_nth_match((int)j, match));
2192 }
2193 if (beg + len > j) {
2194 rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j);
2195 }
2196 return result;
2197}
2198
2199static VALUE
2200match_ary_aref(VALUE match, VALUE idx, VALUE result)
2201{
2202 long beg, len;
2203 int num_regs = RMATCH_REGS(match)->num_regs;
2204
2205 /* check if idx is Range */
2206 switch (rb_range_beg_len(idx, &beg, &len, (long)num_regs, !NIL_P(result))) {
2207 case Qfalse:
2208 if (NIL_P(result)) return rb_reg_nth_match(NUM2INT(idx), match);
2209 rb_ary_push(result, rb_reg_nth_match(NUM2INT(idx), match));
2210 return result;
2211 case Qnil:
2212 return Qnil;
2213 default:
2214 return match_ary_subseq(match, beg, len, result);
2215 }
2216}
2217
2218/*
2219 * call-seq:
2220 * self[offset] -> string or nil
2221 * self[offset, size] -> array
2222 * self[range] -> array
2223 * self[name] -> string or nil
2224 *
2225 * When arguments +offset+, +offset+ and +size+, or +range+ are given,
2226 * returns match and captures in the style of Array#[]:
2227 *
2228 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2229 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2230 * m[0] # => "HX1138"
2231 * m[1, 2] # => ["H", "X"]
2232 * m[1..3] # => ["H", "X", "113"]
2233 * m[-3, 2] # => ["X", "113"]
2234 *
2235 * When string or symbol argument +name+ is given,
2236 * returns the matched substring for the given name:
2237 *
2238 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
2239 * # => #<MatchData "hoge" foo:"h" bar:"ge">
2240 * m['foo'] # => "h"
2241 * m[:bar] # => "ge"
2242 *
2243 * If multiple captures have the same name, returns the last matched
2244 * substring.
2245 *
2246 * m = /(?<foo>.)(?<foo>.+)/.match("hoge")
2247 * # => #<MatchData "hoge" foo:"h" foo:"oge">
2248 * m[:foo] #=> "oge"
2249 *
2250 * m = /\W(?<foo>.+)|\w(?<foo>.+)|(?<foo>.+)/.match("hoge")
2251 * #<MatchData "hoge" foo:nil foo:"oge" foo:nil>
2252 * m[:foo] #=> "oge"
2253 *
2254 */
2255
2256static VALUE
2257match_aref(int argc, VALUE *argv, VALUE match)
2258{
2259 VALUE idx, length;
2260
2261 match_check(match);
2262 rb_scan_args(argc, argv, "11", &idx, &length);
2263
2264 if (NIL_P(length)) {
2265 if (FIXNUM_P(idx)) {
2266 return rb_reg_nth_match(FIX2INT(idx), match);
2267 }
2268 else {
2269 int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, idx);
2270 if (num >= 0) {
2271 return rb_reg_nth_match(num, match);
2272 }
2273 else {
2274 return match_ary_aref(match, idx, Qnil);
2275 }
2276 }
2277 }
2278 else {
2279 long beg = NUM2LONG(idx);
2280 long len = NUM2LONG(length);
2281 long num_regs = RMATCH_REGS(match)->num_regs;
2282 if (len < 0) {
2283 return Qnil;
2284 }
2285 if (beg < 0) {
2286 beg += num_regs;
2287 if (beg < 0) return Qnil;
2288 }
2289 else if (beg > num_regs) {
2290 return Qnil;
2291 }
2292 if (beg+len > num_regs) {
2293 len = num_regs - beg;
2294 }
2295 return match_ary_subseq(match, beg, len, Qnil);
2296 }
2297}
2298
2299/*
2300 * call-seq:
2301 * values_at(*indexes) -> array
2302 *
2303 * Returns match and captures at the given +indexes+,
2304 * which may include any mixture of:
2305 *
2306 * - Integers.
2307 * - Ranges.
2308 * - Names (strings and symbols).
2309 *
2310 *
2311 * Examples:
2312 *
2313 * m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
2314 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2315 * m.values_at(0, 2, -2) # => ["HX1138", "X", "113"]
2316 * m.values_at(1..2, -1) # => ["H", "X", "8"]
2317 *
2318 * m = /(?<a>\d+) *(?<op>[+\-*\/]) *(?<b>\d+)/.match("1 + 2")
2319 * # => #<MatchData "1 + 2" a:"1" op:"+" b:"2">
2320 * m.values_at(0, 1..2, :a, :b, :op)
2321 * # => ["1 + 2", "1", "+", "1", "2", "+"]
2322 *
2323 */
2324
2325static VALUE
2326match_values_at(int argc, VALUE *argv, VALUE match)
2327{
2328 VALUE result;
2329 int i;
2330
2331 match_check(match);
2332 result = rb_ary_new2(argc);
2333
2334 for (i=0; i<argc; i++) {
2335 if (FIXNUM_P(argv[i])) {
2336 rb_ary_push(result, rb_reg_nth_match(FIX2INT(argv[i]), match));
2337 }
2338 else {
2339 int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, argv[i]);
2340 if (num >= 0) {
2341 rb_ary_push(result, rb_reg_nth_match(num, match));
2342 }
2343 else {
2344 match_ary_aref(match, argv[i], result);
2345 }
2346 }
2347 }
2348 return result;
2349}
2350
2351
2352/*
2353 * call-seq:
2354 * to_s -> string
2355 *
2356 * Returns the matched string:
2357 *
2358 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2359 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2360 * m.to_s # => "HX1138"
2361 *
2362 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
2363 * # => #<MatchData "hoge" foo:"h" bar:"ge">
2364 * m.to_s # => "hoge"
2365 *
2366 * Related: MatchData.inspect.
2367 *
2368 */
2369
2370static VALUE
2371match_to_s(VALUE match)
2372{
2373 VALUE str = rb_reg_last_match(match_check(match));
2374
2375 if (NIL_P(str)) str = rb_str_new(0,0);
2376 return str;
2377}
2378
2379static int
2380match_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end,
2381 int back_num, int *back_refs, OnigRegex regex, void *arg)
2382{
2383 struct MEMO *memo = MEMO_CAST(arg);
2384 VALUE hash = memo->v1;
2385 VALUE match = memo->v2;
2386 long symbolize = memo->u3.state;
2387
2388 VALUE key = rb_enc_str_new((const char *)name, name_end-name, regex->enc);
2389
2390 if (symbolize > 0) {
2391 key = rb_str_intern(key);
2392 }
2393
2394 VALUE value;
2395
2396 int i;
2397 int found = 0;
2398
2399 for (i = 0; i < back_num; i++) {
2400 value = rb_reg_nth_match(back_refs[i], match);
2401 if (RTEST(value)) {
2402 rb_hash_aset(hash, key, value);
2403 found = 1;
2404 }
2405 }
2406
2407 if (found == 0) {
2408 rb_hash_aset(hash, key, Qnil);
2409 }
2410
2411 return 0;
2412}
2413
2414/*
2415 * call-seq:
2416 * named_captures(symbolize_names: false) -> hash
2417 *
2418 * Returns a hash of the named captures;
2419 * each key is a capture name; each value is its captured string or +nil+:
2420 *
2421 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
2422 * # => #<MatchData "hoge" foo:"h" bar:"ge">
2423 * m.named_captures # => {"foo"=>"h", "bar"=>"ge"}
2424 *
2425 * m = /(?<a>.)(?<b>.)/.match("01")
2426 * # => #<MatchData "01" a:"0" b:"1">
2427 * m.named_captures #=> {"a" => "0", "b" => "1"}
2428 *
2429 * m = /(?<a>.)(?<b>.)?/.match("0")
2430 * # => #<MatchData "0" a:"0" b:nil>
2431 * m.named_captures #=> {"a" => "0", "b" => nil}
2432 *
2433 * m = /(?<a>.)(?<a>.)/.match("01")
2434 * # => #<MatchData "01" a:"0" a:"1">
2435 * m.named_captures #=> {"a" => "1"}
2436 *
2437 * If keyword argument +symbolize_names+ is given
2438 * a true value, the keys in the resulting hash are Symbols:
2439 *
2440 * m = /(?<a>.)(?<a>.)/.match("01")
2441 * # => #<MatchData "01" a:"0" a:"1">
2442 * m.named_captures(symbolize_names: true) #=> {:a => "1"}
2443 *
2444 */
2445
2446static VALUE
2447match_named_captures(int argc, VALUE *argv, VALUE match)
2448{
2449 VALUE hash;
2450 struct MEMO *memo;
2451
2452 match_check(match);
2453 if (NIL_P(RMATCH(match)->regexp))
2454 return rb_hash_new();
2455
2456 VALUE opt;
2457 VALUE symbolize_names = 0;
2458
2459 rb_scan_args(argc, argv, "0:", &opt);
2460
2461 if (!NIL_P(opt)) {
2462 static ID keyword_ids[1];
2463
2464 VALUE symbolize_names_val;
2465
2466 if (!keyword_ids[0]) {
2467 keyword_ids[0] = rb_intern_const("symbolize_names");
2468 }
2469 rb_get_kwargs(opt, keyword_ids, 0, 1, &symbolize_names_val);
2470 if (!UNDEF_P(symbolize_names_val) && RTEST(symbolize_names_val)) {
2471 symbolize_names = 1;
2472 }
2473 }
2474
2475 hash = rb_hash_new();
2476 memo = rb_imemo_memo_new(hash, match, symbolize_names);
2477
2478 onig_foreach_name(RREGEXP(RMATCH(match)->regexp)->ptr, match_named_captures_iter, (void*)memo);
2479
2480 return hash;
2481}
2482
2483/*
2484 * call-seq:
2485 * deconstruct_keys(array_of_names) -> hash
2486 *
2487 * Returns a hash of the named captures for the given names.
2488 *
2489 * m = /(?<hours>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})/.match("18:37:22")
2490 * m.deconstruct_keys([:hours, :minutes]) # => {:hours => "18", :minutes => "37"}
2491 * m.deconstruct_keys(nil) # => {:hours => "18", :minutes => "37", :seconds => "22"}
2492 *
2493 * Returns an empty hash if no named captures were defined:
2494 *
2495 * m = /(\d{2}):(\d{2}):(\d{2})/.match("18:37:22")
2496 * m.deconstruct_keys(nil) # => {}
2497 *
2498 */
2499static VALUE
2500match_deconstruct_keys(VALUE match, VALUE keys)
2501{
2502 VALUE h;
2503 long i;
2504
2505 match_check(match);
2506
2507 if (NIL_P(RMATCH(match)->regexp)) {
2508 return rb_hash_new_with_size(0);
2509 }
2510
2511 if (NIL_P(keys)) {
2512 h = rb_hash_new_with_size(onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)));
2513
2514 struct MEMO *memo;
2515 memo = rb_imemo_memo_new(h, match, 1);
2516
2517 onig_foreach_name(RREGEXP_PTR(RMATCH(match)->regexp), match_named_captures_iter, (void*)memo);
2518
2519 return h;
2520 }
2521
2522 Check_Type(keys, T_ARRAY);
2523
2524 if (onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)) < RARRAY_LEN(keys)) {
2525 return rb_hash_new_with_size(0);
2526 }
2527
2528 h = rb_hash_new_with_size(RARRAY_LEN(keys));
2529
2530 for (i=0; i<RARRAY_LEN(keys); i++) {
2531 VALUE key = RARRAY_AREF(keys, i);
2532 VALUE name;
2533
2534 Check_Type(key, T_SYMBOL);
2535
2536 name = rb_sym2str(key);
2537
2538 int num = NAME_TO_NUMBER(RMATCH_REGS(match), RMATCH(match)->regexp, RMATCH(match)->regexp,
2539 RSTRING_PTR(name), RSTRING_END(name));
2540
2541 if (num >= 0) {
2542 rb_hash_aset(h, key, rb_reg_nth_match(num, match));
2543 }
2544 else {
2545 return h;
2546 }
2547 }
2548
2549 return h;
2550}
2551
2552/*
2553 * call-seq:
2554 * string -> string
2555 *
2556 * Returns the target string if it was frozen;
2557 * otherwise, returns a frozen copy of the target string:
2558 *
2559 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2560 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2561 * m.string # => "THX1138."
2562 *
2563 */
2564
2565static VALUE
2566match_string(VALUE match)
2567{
2568 match_check(match);
2569 return RMATCH(match)->str; /* str is frozen */
2570}
2571
2573 const UChar *name;
2574 long len;
2575};
2576
2577static int
2578match_inspect_name_iter(const OnigUChar *name, const OnigUChar *name_end,
2579 int back_num, int *back_refs, OnigRegex regex, void *arg0)
2580{
2581 struct backref_name_tag *arg = (struct backref_name_tag *)arg0;
2582 int i;
2583
2584 for (i = 0; i < back_num; i++) {
2585 arg[back_refs[i]].name = name;
2586 arg[back_refs[i]].len = name_end - name;
2587 }
2588 return 0;
2589}
2590
2591/*
2592 * call-seq:
2593 * inspect -> string
2594 *
2595 * Returns a string representation of +self+:
2596 *
2597 * m = /.$/.match("foo")
2598 * # => #<MatchData "o">
2599 * m.inspect # => "#<MatchData \"o\">"
2600 *
2601 * m = /(.)(.)(.)/.match("foo")
2602 * # => #<MatchData "foo" 1:"f" 2:"o" 3:"o">
2603 * m.inspect # => "#<MatchData \"foo\" 1:\"f\" 2:\"o\
2604 *
2605 * m = /(.)(.)?(.)/.match("fo")
2606 * # => #<MatchData "fo" 1:"f" 2:nil 3:"o">
2607 * m.inspect # => "#<MatchData \"fo\" 1:\"f\" 2:nil 3:\"o\">"
2608 *
2609 * Related: MatchData#to_s.
2610 */
2611
2612static VALUE
2613match_inspect(VALUE match)
2614{
2615 VALUE cname = rb_class_path(rb_obj_class(match));
2616 VALUE str;
2617 int i;
2618 struct re_registers *regs = RMATCH_REGS(match);
2619 int num_regs = regs->num_regs;
2620 struct backref_name_tag *names;
2621 VALUE names_obj = Qnil;
2622 VALUE regexp = RMATCH(match)->regexp;
2623
2624 if (regexp == 0) {
2625 return rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)match);
2626 }
2627 else if (NIL_P(regexp)) {
2628 return rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE">",
2629 cname, rb_reg_nth_match(0, match));
2630 }
2631
2632 names = RB_ALLOCV_N(struct backref_name_tag, names_obj, num_regs);
2633 MEMZERO(names, struct backref_name_tag, num_regs);
2634
2635 onig_foreach_name(RREGEXP_PTR(regexp),
2636 match_inspect_name_iter, names);
2637
2638 str = rb_str_buf_new2("#<");
2639 rb_str_append(str, cname);
2640
2641 for (i = 0; i < num_regs; i++) {
2642 VALUE v;
2643 rb_str_buf_cat2(str, " ");
2644 if (0 < i) {
2645 if (names[i].name)
2646 rb_str_buf_cat(str, (const char *)names[i].name, names[i].len);
2647 else {
2648 rb_str_catf(str, "%d", i);
2649 }
2650 rb_str_buf_cat2(str, ":");
2651 }
2652 v = rb_reg_nth_match(i, match);
2653 if (NIL_P(v))
2654 rb_str_buf_cat2(str, "nil");
2655 else
2657 }
2658 rb_str_buf_cat2(str, ">");
2659
2660 RB_ALLOCV_END(names_obj);
2661 return str;
2662}
2663
2665
2666static int
2667read_escaped_byte(const char **pp, const char *end, onig_errmsg_buffer err)
2668{
2669 const char *p = *pp;
2670 int code;
2671 int meta_prefix = 0, ctrl_prefix = 0;
2672 size_t len;
2673
2674 if (p == end || *p++ != '\\') {
2675 errcpy(err, "too short escaped multibyte character");
2676 return -1;
2677 }
2678
2679again:
2680 if (p == end) {
2681 errcpy(err, "too short escape sequence");
2682 return -1;
2683 }
2684 switch (*p++) {
2685 case '\\': code = '\\'; break;
2686 case 'n': code = '\n'; break;
2687 case 't': code = '\t'; break;
2688 case 'r': code = '\r'; break;
2689 case 'f': code = '\f'; break;
2690 case 'v': code = '\013'; break;
2691 case 'a': code = '\007'; break;
2692 case 'e': code = '\033'; break;
2693
2694 /* \OOO */
2695 case '0': case '1': case '2': case '3':
2696 case '4': case '5': case '6': case '7':
2697 p--;
2698 code = scan_oct(p, end < p+3 ? end-p : 3, &len);
2699 p += len;
2700 break;
2701
2702 case 'x': /* \xHH */
2703 code = scan_hex(p, end < p+2 ? end-p : 2, &len);
2704 if (len < 1) {
2705 errcpy(err, "invalid hex escape");
2706 return -1;
2707 }
2708 p += len;
2709 break;
2710
2711 case 'M': /* \M-X, \M-\C-X, \M-\cX */
2712 if (meta_prefix) {
2713 errcpy(err, "duplicate meta escape");
2714 return -1;
2715 }
2716 meta_prefix = 1;
2717 if (p+1 < end && *p++ == '-' && (*p & 0x80) == 0) {
2718 if (*p == '\\') {
2719 p++;
2720 goto again;
2721 }
2722 else {
2723 code = *p++;
2724 break;
2725 }
2726 }
2727 errcpy(err, "too short meta escape");
2728 return -1;
2729
2730 case 'C': /* \C-X, \C-\M-X */
2731 if (p == end || *p++ != '-') {
2732 errcpy(err, "too short control escape");
2733 return -1;
2734 }
2735 case 'c': /* \cX, \c\M-X */
2736 if (ctrl_prefix) {
2737 errcpy(err, "duplicate control escape");
2738 return -1;
2739 }
2740 ctrl_prefix = 1;
2741 if (p < end && (*p & 0x80) == 0) {
2742 if (*p == '\\') {
2743 p++;
2744 goto again;
2745 }
2746 else {
2747 code = *p++;
2748 break;
2749 }
2750 }
2751 errcpy(err, "too short control escape");
2752 return -1;
2753
2754 default:
2755 errcpy(err, "unexpected escape sequence");
2756 return -1;
2757 }
2758 if (code < 0 || 0xff < code) {
2759 errcpy(err, "invalid escape code");
2760 return -1;
2761 }
2762
2763 if (ctrl_prefix)
2764 code &= 0x1f;
2765 if (meta_prefix)
2766 code |= 0x80;
2767
2768 *pp = p;
2769 return code;
2770}
2771
2772static int
2773unescape_escaped_nonascii(const char **pp, const char *end, rb_encoding *enc,
2774 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
2775{
2776 const char *p = *pp;
2777 int chmaxlen = rb_enc_mbmaxlen(enc);
2778 unsigned char *area = ALLOCA_N(unsigned char, chmaxlen);
2779 char *chbuf = (char *)area;
2780 int chlen = 0;
2781 int byte;
2782 int l;
2783
2784 memset(chbuf, 0, chmaxlen);
2785
2786 byte = read_escaped_byte(&p, end, err);
2787 if (byte == -1) {
2788 return -1;
2789 }
2790
2791 area[chlen++] = byte;
2792 while (chlen < chmaxlen &&
2793 MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc))) {
2794 byte = read_escaped_byte(&p, end, err);
2795 if (byte == -1) {
2796 return -1;
2797 }
2798 area[chlen++] = byte;
2799 }
2800
2801 l = rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc);
2802 if (MBCLEN_INVALID_P(l)) {
2803 errcpy(err, "invalid multibyte escape");
2804 return -1;
2805 }
2806 if (1 < chlen || (area[0] & 0x80)) {
2807 rb_str_buf_cat(buf, chbuf, chlen);
2808
2809 if (*encp == 0)
2810 *encp = enc;
2811 else if (*encp != enc) {
2812 errcpy(err, "escaped non ASCII character in UTF-8 regexp");
2813 return -1;
2814 }
2815 }
2816 else {
2817 char escbuf[5];
2818 snprintf(escbuf, sizeof(escbuf), "\\x%02X", area[0]&0xff);
2819 rb_str_buf_cat(buf, escbuf, 4);
2820 }
2821 *pp = p;
2822 return 0;
2823}
2824
2825static int
2826check_unicode_range(unsigned long code, onig_errmsg_buffer err)
2827{
2828 if ((0xd800 <= code && code <= 0xdfff) || /* Surrogates */
2829 0x10ffff < code) {
2830 errcpy(err, "invalid Unicode range");
2831 return -1;
2832 }
2833 return 0;
2834}
2835
2836static int
2837append_utf8(unsigned long uv,
2838 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
2839{
2840 if (check_unicode_range(uv, err) != 0)
2841 return -1;
2842 if (uv < 0x80) {
2843 char escbuf[5];
2844 snprintf(escbuf, sizeof(escbuf), "\\x%02X", (int)uv);
2845 rb_str_buf_cat(buf, escbuf, 4);
2846 }
2847 else {
2848 int len;
2849 char utf8buf[6];
2850 len = rb_uv_to_utf8(utf8buf, uv);
2851 rb_str_buf_cat(buf, utf8buf, len);
2852
2853 if (*encp == 0)
2854 *encp = rb_utf8_encoding();
2855 else if (*encp != rb_utf8_encoding()) {
2856 errcpy(err, "UTF-8 character in non UTF-8 regexp");
2857 return -1;
2858 }
2859 }
2860 return 0;
2861}
2862
2863static int
2864unescape_unicode_list(const char **pp, const char *end,
2865 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
2866{
2867 const char *p = *pp;
2868 int has_unicode = 0;
2869 unsigned long code;
2870 size_t len;
2871
2872 while (p < end && ISSPACE(*p)) p++;
2873
2874 while (1) {
2875 code = ruby_scan_hex(p, end-p, &len);
2876 if (len == 0)
2877 break;
2878 if (6 < len) { /* max 10FFFF */
2879 errcpy(err, "invalid Unicode range");
2880 return -1;
2881 }
2882 p += len;
2883 if (append_utf8(code, buf, encp, err) != 0)
2884 return -1;
2885 has_unicode = 1;
2886
2887 while (p < end && ISSPACE(*p)) p++;
2888 }
2889
2890 if (has_unicode == 0) {
2891 errcpy(err, "invalid Unicode list");
2892 return -1;
2893 }
2894
2895 *pp = p;
2896
2897 return 0;
2898}
2899
2900static int
2901unescape_unicode_bmp(const char **pp, const char *end,
2902 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
2903{
2904 const char *p = *pp;
2905 size_t len;
2906 unsigned long code;
2907
2908 if (end < p+4) {
2909 errcpy(err, "invalid Unicode escape");
2910 return -1;
2911 }
2912 code = ruby_scan_hex(p, 4, &len);
2913 if (len != 4) {
2914 errcpy(err, "invalid Unicode escape");
2915 return -1;
2916 }
2917 if (append_utf8(code, buf, encp, err) != 0)
2918 return -1;
2919 *pp = p + 4;
2920 return 0;
2921}
2922
2923static int
2924unescape_nonascii0(const char **pp, const char *end, rb_encoding *enc,
2925 VALUE buf, rb_encoding **encp, int *has_property,
2926 onig_errmsg_buffer err, int options, int recurse)
2927{
2928 const char *p = *pp;
2929 unsigned char c;
2930 char smallbuf[2];
2931 int in_char_class = 0;
2932 int parens = 1; /* ignored unless recurse is true */
2933 int extended_mode = options & ONIG_OPTION_EXTEND;
2934
2935begin_scan:
2936 while (p < end) {
2937 int chlen = rb_enc_precise_mbclen(p, end, enc);
2938 if (!MBCLEN_CHARFOUND_P(chlen)) {
2939 invalid_multibyte:
2940 errcpy(err, "invalid multibyte character");
2941 return -1;
2942 }
2943 chlen = MBCLEN_CHARFOUND_LEN(chlen);
2944 if (1 < chlen || (*p & 0x80)) {
2945 multibyte:
2946 rb_str_buf_cat(buf, p, chlen);
2947 p += chlen;
2948 if (*encp == 0)
2949 *encp = enc;
2950 else if (*encp != enc) {
2951 errcpy(err, "non ASCII character in UTF-8 regexp");
2952 return -1;
2953 }
2954 continue;
2955 }
2956
2957 switch (c = *p++) {
2958 case '\\':
2959 if (p == end) {
2960 errcpy(err, "too short escape sequence");
2961 return -1;
2962 }
2963 chlen = rb_enc_precise_mbclen(p, end, enc);
2964 if (!MBCLEN_CHARFOUND_P(chlen)) {
2965 goto invalid_multibyte;
2966 }
2967 if ((chlen = MBCLEN_CHARFOUND_LEN(chlen)) > 1) {
2968 /* include the previous backslash */
2969 --p;
2970 ++chlen;
2971 goto multibyte;
2972 }
2973 switch (c = *p++) {
2974 case '1': case '2': case '3':
2975 case '4': case '5': case '6': case '7': /* \O, \OO, \OOO or backref */
2976 {
2977 size_t len = end-(p-1), octlen;
2978 if (ruby_scan_oct(p-1, len < 3 ? len : 3, &octlen) <= 0177) {
2979 /* backref or 7bit octal.
2980 no need to unescape anyway.
2981 re-escaping may break backref */
2982 goto escape_asis;
2983 }
2984 }
2985 /* xxx: How about more than 199 subexpressions? */
2986
2987 case '0': /* \0, \0O, \0OO */
2988
2989 case 'x': /* \xHH */
2990 case 'c': /* \cX, \c\M-X */
2991 case 'C': /* \C-X, \C-\M-X */
2992 case 'M': /* \M-X, \M-\C-X, \M-\cX */
2993 p = p-2;
2994 if (rb_is_usascii_enc(enc)) {
2995 const char *pbeg = p;
2996 int byte = read_escaped_byte(&p, end, err);
2997 if (byte == -1) return -1;
2998 c = byte;
2999 rb_str_buf_cat(buf, pbeg, p-pbeg);
3000 }
3001 else {
3002 if (unescape_escaped_nonascii(&p, end, enc, buf, encp, err) != 0)
3003 return -1;
3004 }
3005 break;
3006
3007 case 'u':
3008 if (p == end) {
3009 errcpy(err, "too short escape sequence");
3010 return -1;
3011 }
3012 if (*p == '{') {
3013 /* \u{H HH HHH HHHH HHHHH HHHHHH ...} */
3014 p++;
3015 if (unescape_unicode_list(&p, end, buf, encp, err) != 0)
3016 return -1;
3017 if (p == end || *p++ != '}') {
3018 errcpy(err, "invalid Unicode list");
3019 return -1;
3020 }
3021 break;
3022 }
3023 else {
3024 /* \uHHHH */
3025 if (unescape_unicode_bmp(&p, end, buf, encp, err) != 0)
3026 return -1;
3027 break;
3028 }
3029
3030 case 'p': /* \p{Hiragana} */
3031 case 'P':
3032 if (!*encp) {
3033 *has_property = 1;
3034 }
3035 goto escape_asis;
3036
3037 default: /* \n, \\, \d, \9, etc. */
3038escape_asis:
3039 smallbuf[0] = '\\';
3040 smallbuf[1] = c;
3041 rb_str_buf_cat(buf, smallbuf, 2);
3042 break;
3043 }
3044 break;
3045
3046 case '#':
3047 if (extended_mode && !in_char_class) {
3048 /* consume and ignore comment in extended regexp */
3049 while ((p < end) && ((c = *p++) != '\n')) {
3050 if ((c & 0x80) && !*encp && enc == rb_utf8_encoding()) {
3051 *encp = enc;
3052 }
3053 }
3054 break;
3055 }
3056 rb_str_buf_cat(buf, (char *)&c, 1);
3057 break;
3058 case '[':
3059 in_char_class++;
3060 rb_str_buf_cat(buf, (char *)&c, 1);
3061 break;
3062 case ']':
3063 if (in_char_class) {
3064 in_char_class--;
3065 }
3066 rb_str_buf_cat(buf, (char *)&c, 1);
3067 break;
3068 case ')':
3069 rb_str_buf_cat(buf, (char *)&c, 1);
3070 if (!in_char_class && recurse) {
3071 if (--parens == 0) {
3072 *pp = p;
3073 return 0;
3074 }
3075 }
3076 break;
3077 case '(':
3078 if (!in_char_class && p + 1 < end && *p == '?') {
3079 if (*(p+1) == '#') {
3080 /* (?# is comment inside any regexp, and content inside should be ignored */
3081 const char *orig_p = p;
3082 int cont = 1;
3083
3084 while (cont && (p < end)) {
3085 switch (c = *p++) {
3086 default:
3087 if (!(c & 0x80)) break;
3088 if (!*encp && enc == rb_utf8_encoding()) {
3089 *encp = enc;
3090 }
3091 --p;
3092 /* fallthrough */
3093 case '\\':
3094 chlen = rb_enc_precise_mbclen(p, end, enc);
3095 if (!MBCLEN_CHARFOUND_P(chlen)) {
3096 goto invalid_multibyte;
3097 }
3098 p += MBCLEN_CHARFOUND_LEN(chlen);
3099 break;
3100 case ')':
3101 cont = 0;
3102 break;
3103 }
3104 }
3105
3106 if (cont) {
3107 /* unterminated (?#, rewind so it is syntax error */
3108 p = orig_p;
3109 c = '(';
3110 rb_str_buf_cat(buf, (char *)&c, 1);
3111 }
3112 break;
3113 }
3114 else {
3115 /* potential change of extended option */
3116 int invert = 0;
3117 int local_extend = 0;
3118 const char *s;
3119
3120 if (recurse) {
3121 parens++;
3122 }
3123
3124 for (s = p+1; s < end; s++) {
3125 switch(*s) {
3126 case 'x':
3127 local_extend = invert ? -1 : 1;
3128 break;
3129 case '-':
3130 invert = 1;
3131 break;
3132 case ':':
3133 case ')':
3134 if (local_extend == 0 ||
3135 (local_extend == -1 && !extended_mode) ||
3136 (local_extend == 1 && extended_mode)) {
3137 /* no changes to extended flag */
3138 goto fallthrough;
3139 }
3140
3141 if (*s == ':') {
3142 /* change extended flag until ')' */
3143 int local_options = options;
3144 if (local_extend == 1) {
3145 local_options |= ONIG_OPTION_EXTEND;
3146 }
3147 else {
3148 local_options &= ~ONIG_OPTION_EXTEND;
3149 }
3150
3151 rb_str_buf_cat(buf, (char *)&c, 1);
3152 int ret = unescape_nonascii0(&p, end, enc, buf, encp,
3153 has_property, err,
3154 local_options, 1);
3155 if (ret < 0) return ret;
3156 goto begin_scan;
3157 }
3158 else {
3159 /* change extended flag for rest of expression */
3160 extended_mode = local_extend == 1;
3161 goto fallthrough;
3162 }
3163 case 'i':
3164 case 'm':
3165 case 'a':
3166 case 'd':
3167 case 'u':
3168 /* other option flags, ignored during scanning */
3169 break;
3170 default:
3171 /* other character, no extended flag change*/
3172 goto fallthrough;
3173 }
3174 }
3175 }
3176 }
3177 else if (!in_char_class && recurse) {
3178 parens++;
3179 }
3180 /* FALLTHROUGH */
3181 default:
3182fallthrough:
3183 rb_str_buf_cat(buf, (char *)&c, 1);
3184 break;
3185 }
3186 }
3187
3188 if (recurse) {
3189 *pp = p;
3190 }
3191 return 0;
3192}
3193
3194static int
3195unescape_nonascii(const char *p, const char *end, rb_encoding *enc,
3196 VALUE buf, rb_encoding **encp, int *has_property,
3197 onig_errmsg_buffer err, int options)
3198{
3199 return unescape_nonascii0(&p, end, enc, buf, encp, has_property,
3200 err, options, 0);
3201}
3202
3203static VALUE
3204rb_reg_preprocess(const char *p, const char *end, rb_encoding *enc,
3205 rb_encoding **fixed_enc, onig_errmsg_buffer err, int options)
3206{
3207 VALUE buf;
3208 int has_property = 0;
3209
3210 buf = rb_str_buf_new(0);
3211
3212 if (rb_enc_asciicompat(enc))
3213 *fixed_enc = 0;
3214 else {
3215 *fixed_enc = enc;
3216 rb_enc_associate(buf, enc);
3217 }
3218
3219 if (unescape_nonascii(p, end, enc, buf, fixed_enc, &has_property, err, options) != 0)
3220 return Qnil;
3221
3222 if (has_property && !*fixed_enc) {
3223 *fixed_enc = enc;
3224 }
3225
3226 if (*fixed_enc) {
3227 rb_enc_associate(buf, *fixed_enc);
3228 }
3229
3230 return buf;
3231}
3232
3233VALUE
3234rb_reg_check_preprocess(VALUE str)
3235{
3236 rb_encoding *fixed_enc = 0;
3237 onig_errmsg_buffer err = "";
3238 VALUE buf;
3239 char *p, *end;
3240 rb_encoding *enc;
3241
3242 StringValue(str);
3243 p = RSTRING_PTR(str);
3244 end = p + RSTRING_LEN(str);
3245 enc = rb_enc_get(str);
3246
3247 buf = rb_reg_preprocess(p, end, enc, &fixed_enc, err, 0);
3248 RB_GC_GUARD(str);
3249
3250 if (NIL_P(buf)) {
3251 return rb_reg_error_desc(str, 0, err);
3252 }
3253 return Qnil;
3254}
3255
3256static VALUE
3257rb_reg_preprocess_dregexp(VALUE ary, int options)
3258{
3259 rb_encoding *fixed_enc = 0;
3260 rb_encoding *regexp_enc = 0;
3261 onig_errmsg_buffer err = "";
3262 int i;
3263 VALUE result = 0;
3264 rb_encoding *ascii8bit = rb_ascii8bit_encoding();
3265
3266 if (RARRAY_LEN(ary) == 0) {
3267 rb_raise(rb_eArgError, "no arguments given");
3268 }
3269
3270 for (i = 0; i < RARRAY_LEN(ary); i++) {
3271 VALUE str = RARRAY_AREF(ary, i);
3272 VALUE buf;
3273 char *p, *end;
3274 rb_encoding *src_enc;
3275
3276 src_enc = rb_enc_get(str);
3277 if (options & ARG_ENCODING_NONE &&
3278 src_enc != ascii8bit) {
3279 if (str_coderange(str) != ENC_CODERANGE_7BIT)
3280 rb_raise(rb_eRegexpError, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
3281 else
3282 src_enc = ascii8bit;
3283 }
3284
3285 StringValue(str);
3286 p = RSTRING_PTR(str);
3287 end = p + RSTRING_LEN(str);
3288
3289 buf = rb_reg_preprocess(p, end, src_enc, &fixed_enc, err, options);
3290
3291 if (NIL_P(buf))
3292 rb_raise(rb_eArgError, "%s", err);
3293
3294 if (fixed_enc != 0) {
3295 if (regexp_enc != 0 && regexp_enc != fixed_enc) {
3296 rb_raise(rb_eRegexpError, "encoding mismatch in dynamic regexp : %s and %s",
3297 rb_enc_name(regexp_enc), rb_enc_name(fixed_enc));
3298 }
3299 regexp_enc = fixed_enc;
3300 }
3301
3302 if (!result)
3303 result = rb_str_new3(str);
3304 else
3305 rb_str_buf_append(result, str);
3306 }
3307 if (regexp_enc) {
3308 rb_enc_associate(result, regexp_enc);
3309 }
3310
3311 return result;
3312}
3313
3314static void
3315rb_reg_initialize_check(VALUE obj)
3316{
3317 rb_check_frozen(obj);
3318 if (RREGEXP_PTR(obj)) {
3319 rb_raise(rb_eTypeError, "already initialized regexp");
3320 }
3321}
3322
3323static int
3324rb_reg_initialize(VALUE obj, const char *s, long len, rb_encoding *enc,
3325 int options, onig_errmsg_buffer err,
3326 const char *sourcefile, int sourceline)
3327{
3328 struct RRegexp *re = RREGEXP(obj);
3329 VALUE unescaped;
3330 rb_encoding *fixed_enc = 0;
3331 rb_encoding *a_enc = rb_ascii8bit_encoding();
3332
3333 rb_reg_initialize_check(obj);
3334
3335 if (rb_enc_dummy_p(enc)) {
3336 errcpy(err, "can't make regexp with dummy encoding");
3337 return -1;
3338 }
3339
3340 unescaped = rb_reg_preprocess(s, s+len, enc, &fixed_enc, err, options);
3341 if (NIL_P(unescaped))
3342 return -1;
3343
3344 if (fixed_enc) {
3345 if ((fixed_enc != enc && (options & ARG_ENCODING_FIXED)) ||
3346 (fixed_enc != a_enc && (options & ARG_ENCODING_NONE))) {
3347 errcpy(err, "incompatible character encoding");
3348 return -1;
3349 }
3350 if (fixed_enc != a_enc) {
3351 options |= ARG_ENCODING_FIXED;
3352 enc = fixed_enc;
3353 }
3354 }
3355 else if (!(options & ARG_ENCODING_FIXED)) {
3356 enc = rb_usascii_encoding();
3357 }
3358
3359 rb_enc_associate((VALUE)re, enc);
3360 if ((options & ARG_ENCODING_FIXED) || fixed_enc) {
3361 re->basic.flags |= KCODE_FIXED;
3362 }
3363 if (options & ARG_ENCODING_NONE) {
3364 re->basic.flags |= REG_ENCODING_NONE;
3365 }
3366
3367 re->ptr = make_regexp(RSTRING_PTR(unescaped), RSTRING_LEN(unescaped), enc,
3368 options & ARG_REG_OPTION_MASK, err,
3369 sourcefile, sourceline);
3370 if (!re->ptr) return -1;
3371 if (RBASIC_CLASS(obj) == rb_cRegexp) {
3372 OBJ_FREEZE(obj);
3373 }
3374 RB_GC_GUARD(unescaped);
3375 return 0;
3376}
3377
3378static void
3379reg_set_source(VALUE reg, VALUE str, rb_encoding *enc)
3380{
3381 rb_encoding *regenc = rb_enc_get(reg);
3382
3383 if (regenc != enc) {
3384 VALUE dup = rb_str_dup(str);
3385 str = rb_enc_associate(dup, enc = regenc);
3386 }
3387 str = rb_fstring(str);
3388 RB_OBJ_WRITE(reg, &RREGEXP(reg)->src, str);
3389}
3390
3391static int
3392rb_reg_initialize_str(VALUE obj, VALUE str, int options, onig_errmsg_buffer err,
3393 const char *sourcefile, int sourceline)
3394{
3395 int ret;
3396 rb_encoding *str_enc = rb_enc_get(str), *enc = str_enc;
3397 if (options & ARG_ENCODING_NONE) {
3398 rb_encoding *ascii8bit = rb_ascii8bit_encoding();
3399 if (enc != ascii8bit) {
3400 if (str_coderange(str) != ENC_CODERANGE_7BIT) {
3401 errcpy(err, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
3402 return -1;
3403 }
3404 enc = ascii8bit;
3405 }
3406 }
3407 ret = rb_reg_initialize(obj, RSTRING_PTR(str), RSTRING_LEN(str), enc,
3408 options, err, sourcefile, sourceline);
3409 if (ret == 0) reg_set_source(obj, str, str_enc);
3410 return ret;
3411}
3412
3413VALUE
3414rb_reg_s_alloc(VALUE klass)
3415{
3416 NEWOBJ_OF(re, struct RRegexp, klass, T_REGEXP | (RGENGC_WB_PROTECTED_REGEXP ? FL_WB_PROTECTED : 0), sizeof(struct RRegexp), 0);
3417
3418 re->ptr = 0;
3419 RB_OBJ_WRITE(re, &re->src, 0);
3420 re->usecnt = 0;
3421
3422 return (VALUE)re;
3423}
3424
3425VALUE
3426rb_reg_alloc(void)
3427{
3428 return rb_reg_s_alloc(rb_cRegexp);
3429}
3430
3431VALUE
3432rb_reg_new_str(VALUE s, int options)
3433{
3434 return rb_reg_init_str(rb_reg_alloc(), s, options);
3435}
3436
3437VALUE
3438rb_reg_init_str(VALUE re, VALUE s, int options)
3439{
3440 onig_errmsg_buffer err = "";
3441
3442 if (rb_reg_initialize_str(re, s, options, err, NULL, 0) != 0) {
3443 rb_reg_raise_str(s, options, err);
3444 }
3445
3446 return re;
3447}
3448
3449static VALUE
3450rb_reg_init_str_enc(VALUE re, VALUE s, rb_encoding *enc, int options)
3451{
3452 onig_errmsg_buffer err = "";
3453
3454 if (rb_reg_initialize(re, RSTRING_PTR(s), RSTRING_LEN(s),
3455 enc, options, err, NULL, 0) != 0) {
3456 rb_reg_raise_str(s, options, err);
3457 }
3458 reg_set_source(re, s, enc);
3459
3460 return re;
3461}
3462
3463VALUE
3464rb_reg_new_ary(VALUE ary, int opt)
3465{
3466 return rb_reg_new_str(rb_reg_preprocess_dregexp(ary, opt), opt);
3467}
3468
3469VALUE
3470rb_enc_reg_new(const char *s, long len, rb_encoding *enc, int options)
3471{
3472 VALUE re = rb_reg_alloc();
3473 onig_errmsg_buffer err = "";
3474
3475 if (rb_reg_initialize(re, s, len, enc, options, err, NULL, 0) != 0) {
3476 rb_enc_reg_raise(s, len, enc, options, err);
3477 }
3478 RB_OBJ_WRITE(re, &RREGEXP(re)->src, rb_fstring(rb_enc_str_new(s, len, enc)));
3479
3480 return re;
3481}
3482
3483VALUE
3484rb_reg_new(const char *s, long len, int options)
3485{
3486 return rb_enc_reg_new(s, len, rb_ascii8bit_encoding(), options);
3487}
3488
3489VALUE
3490rb_reg_compile(VALUE str, int options, const char *sourcefile, int sourceline)
3491{
3492 VALUE re = rb_reg_alloc();
3493 onig_errmsg_buffer err = "";
3494
3495 if (!str) str = rb_str_new(0,0);
3496 if (rb_reg_initialize_str(re, str, options, err, sourcefile, sourceline) != 0) {
3497 rb_set_errinfo(rb_reg_error_desc(str, options, err));
3498 return Qnil;
3499 }
3500 return re;
3501}
3502
3503static VALUE reg_cache;
3504
3505VALUE
3507{
3508 if (rb_ractor_main_p()) {
3509 if (reg_cache && RREGEXP_SRC_LEN(reg_cache) == RSTRING_LEN(str)
3510 && ENCODING_GET(reg_cache) == ENCODING_GET(str)
3511 && memcmp(RREGEXP_SRC_PTR(reg_cache), RSTRING_PTR(str), RSTRING_LEN(str)) == 0)
3512 return reg_cache;
3513
3514 return reg_cache = rb_reg_new_str(str, 0);
3515 }
3516 else {
3517 return rb_reg_new_str(str, 0);
3518 }
3519}
3520
3521static st_index_t reg_hash(VALUE re);
3522/*
3523 * call-seq:
3524 * hash -> integer
3525 *
3526 * Returns the integer hash value for +self+.
3527 *
3528 * Related: Object#hash.
3529 *
3530 */
3531
3532VALUE
3533rb_reg_hash(VALUE re)
3534{
3535 st_index_t hashval = reg_hash(re);
3536 return ST2FIX(hashval);
3537}
3538
3539static st_index_t
3540reg_hash(VALUE re)
3541{
3542 st_index_t hashval;
3543
3544 rb_reg_check(re);
3545 hashval = RREGEXP_PTR(re)->options;
3546 hashval = rb_hash_uint(hashval, rb_memhash(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re)));
3547 return rb_hash_end(hashval);
3548}
3549
3550
3551/*
3552 * call-seq:
3553 * self == other -> true or false
3554 *
3555 * Returns whether +other+ is another \Regexp whose pattern,
3556 * flags, and encoding are the same as +self+:
3557 *
3558 * /foo/ == Regexp.new('foo') # => true
3559 * /foo/ == /foo/i # => false
3560 * /foo/ == Regexp.new('food') # => false
3561 * /foo/ == Regexp.new("abc".force_encoding("euc-jp")) # => false
3562 *
3563 */
3564
3565VALUE
3566rb_reg_equal(VALUE re1, VALUE re2)
3567{
3568 if (re1 == re2) return Qtrue;
3569 if (!RB_TYPE_P(re2, T_REGEXP)) return Qfalse;
3570 rb_reg_check(re1); rb_reg_check(re2);
3571 if (FL_TEST(re1, KCODE_FIXED) != FL_TEST(re2, KCODE_FIXED)) return Qfalse;
3572 if (RREGEXP_PTR(re1)->options != RREGEXP_PTR(re2)->options) return Qfalse;
3573 if (RREGEXP_SRC_LEN(re1) != RREGEXP_SRC_LEN(re2)) return Qfalse;
3574 if (ENCODING_GET(re1) != ENCODING_GET(re2)) return Qfalse;
3575 return RBOOL(memcmp(RREGEXP_SRC_PTR(re1), RREGEXP_SRC_PTR(re2), RREGEXP_SRC_LEN(re1)) == 0);
3576}
3577
3578/*
3579 * call-seq:
3580 * hash -> integer
3581 *
3582 * Returns the integer hash value for +self+,
3583 * based on the target string, regexp, match, and captures.
3584 *
3585 * See also Object#hash.
3586 *
3587 */
3588
3589static VALUE
3590match_hash(VALUE match)
3591{
3592 const struct re_registers *regs;
3593 st_index_t hashval;
3594
3595 match_check(match);
3596 hashval = rb_hash_start(rb_str_hash(RMATCH(match)->str));
3597 hashval = rb_hash_uint(hashval, reg_hash(match_regexp(match)));
3598 regs = RMATCH_REGS(match);
3599 hashval = rb_hash_uint(hashval, regs->num_regs);
3600 hashval = rb_hash_uint(hashval, rb_memhash(regs->beg, regs->num_regs * sizeof(*regs->beg)));
3601 hashval = rb_hash_uint(hashval, rb_memhash(regs->end, regs->num_regs * sizeof(*regs->end)));
3602 hashval = rb_hash_end(hashval);
3603 return ST2FIX(hashval);
3604}
3605
3606/*
3607 * call-seq:
3608 * self == other -> true or false
3609 *
3610 * Returns whether +other+ is another \MatchData object
3611 * whose target string, regexp, match, and captures
3612 * are the same as +self+.
3613 */
3614
3615static VALUE
3616match_equal(VALUE match1, VALUE match2)
3617{
3618 const struct re_registers *regs1, *regs2;
3619
3620 if (match1 == match2) return Qtrue;
3621 if (!RB_TYPE_P(match2, T_MATCH)) return Qfalse;
3622 if (!RMATCH(match1)->regexp || !RMATCH(match2)->regexp) return Qfalse;
3623 if (!rb_str_equal(RMATCH(match1)->str, RMATCH(match2)->str)) return Qfalse;
3624 if (!rb_reg_equal(match_regexp(match1), match_regexp(match2))) return Qfalse;
3625 regs1 = RMATCH_REGS(match1);
3626 regs2 = RMATCH_REGS(match2);
3627 if (regs1->num_regs != regs2->num_regs) return Qfalse;
3628 if (memcmp(regs1->beg, regs2->beg, regs1->num_regs * sizeof(*regs1->beg))) return Qfalse;
3629 if (memcmp(regs1->end, regs2->end, regs1->num_regs * sizeof(*regs1->end))) return Qfalse;
3630 return Qtrue;
3631}
3632
3633/*
3634 * call-seq:
3635 * integer_at(index, base = 10) -> integer or nil
3636 * integer_at(name, base = 10) -> integer or nil
3637 *
3638 * Converts the matched substring to integer and return the result.
3639 * +$~.integer_at(N)+ is equivalent to +$N&.to_i+.
3640 *
3641 * m = /(\d+{4})(\d+{2})(\d+{2})/.match("20260308")
3642 * # => #<MatchData "20260308" 1:"2026" 2:"03" 3:"08">
3643 * m.integer_at(0) # => 20260308
3644 * m.integer_at(1) # => 2026
3645 * m.integer_at(2) # => 3
3646 * m.integer_at(3) # => 8
3647 *
3648 * m = /(?<y>\d+{4})(?<m>\d+{2})(?<d>\d+{2})/.match("20260308")
3649 * m.integer_at("y") # => 2026
3650 * m.integer_at("m") # => 3
3651 * m.integer_at("d") # => 8
3652 *
3653 * If the substring does not match, returns +nil+.
3654 *
3655 * re = /(\d+)?/
3656 * re.match("123").integer_at(1) #=> 123
3657 * re.match("abc").integer_at(1) #=> nil
3658 *
3659 * The string is converted in decimal by default.
3660 *
3661 * /\d+/.match("011").integer_at(0) #=> 10
3662 * /\d+/.match("011").integer_at(0, 12) #=> 13
3663 * /\d+/.match("011").integer_at(0, 0) #=> 9
3664 *
3665 * See also MatchData#[], String#to_i.
3666 */
3667static VALUE
3668match_integer_at(int argc, VALUE *argv, VALUE match)
3669{
3670 const struct re_registers *regs = RMATCH_REGS(match_check(match));
3671
3672 int base = 10;
3673 VALUE idx;
3674 long nth;
3675
3676 argc = rb_check_arity(argc, 1, 2);
3677 if (FIXNUM_P(idx = argv[0])) {
3678 nth = NUM2INT(idx);
3679 }
3680 else if ((nth = namev_to_backref_number(regs, RMATCH(match)->regexp, idx)) < 0) {
3681 name_to_backref_error(idx);
3682 }
3683
3684 if (argc > 1 && (base = NUM2INT(argv[1])) < 0) {
3685 rb_raise(rb_eArgError, "invalid radix %d", base);
3686 }
3687
3688 if (nth >= regs->num_regs) return Qnil;
3689 if (nth < 0 && (nth += regs->num_regs) <= 0) return Qnil;
3690
3691 long start = BEG(nth), end = END(nth);
3692 if (start < 0) return Qnil;
3693 RUBY_ASSERT(start <= end, "%ld > %ld", start, end);
3694
3695 VALUE str = RMATCH(match)->str;
3696 RUBY_ASSERT(end <= RSTRING_LEN(str), "%ld > %ld", end, RSTRING_LEN(str));
3697
3698 char *endp;
3699 return rb_int_parse_cstr(RSTRING_PTR(str) + start, end - start, &endp, NULL,
3700 base, RB_INT_PARSE_DEFAULT);
3701}
3702
3703static VALUE
3704reg_operand(VALUE s, int check)
3705{
3706 if (SYMBOL_P(s)) {
3707 return rb_sym2str(s);
3708 }
3709 else if (RB_TYPE_P(s, T_STRING)) {
3710 return s;
3711 }
3712 else {
3713 return check ? rb_str_to_str(s) : rb_check_string_type(s);
3714 }
3715}
3716
3717static long
3718reg_match_pos(VALUE re, VALUE *strp, long pos, VALUE* set_match)
3719{
3720 VALUE str = *strp;
3721
3722 if (NIL_P(str)) {
3723 rb_backref_set(Qnil);
3724 return -1;
3725 }
3726 *strp = str = reg_operand(str, TRUE);
3727 if (pos != 0) {
3728 if (pos < 0) {
3729 VALUE l = rb_str_length(str);
3730 pos += NUM2INT(l);
3731 if (pos < 0) {
3732 return pos;
3733 }
3734 }
3735 pos = rb_str_offset(str, pos);
3736 }
3737 return rb_reg_search_set_match(re, str, pos, 0, 1, set_match);
3738}
3739
3740/*
3741 * call-seq:
3742 * self =~ other -> integer or nil
3743 *
3744 * Returns the integer index (in characters) of the first match
3745 * for +self+ and +other+, or +nil+ if none;
3746 * updates {Regexp-related global variables}[rdoc-ref:Regexp@Global+Variables].
3747 *
3748 * /at/ =~ 'input data' # => 7
3749 * $~ # => #<MatchData "at">
3750 * /ax/ =~ 'input data' # => nil
3751 * $~ # => nil
3752 *
3753 * Assigns named captures to local variables of the same names
3754 * if and only if +self+:
3755 *
3756 * - Is a regexp literal;
3757 * see {Regexp Literals}[rdoc-ref:syntax/literals.rdoc@Regexp+Literals].
3758 * - Does not contain interpolations;
3759 * see {Regexp interpolation}[rdoc-ref:Regexp@Interpolation+Mode].
3760 * - Is at the left of the expression.
3761 *
3762 * Example:
3763 *
3764 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ ' x = y '
3765 * p lhs # => "x"
3766 * p rhs # => "y"
3767 *
3768 * Assigns +nil+ if not matched:
3769 *
3770 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ ' x = '
3771 * p lhs # => nil
3772 * p rhs # => nil
3773 *
3774 * Does not make local variable assignments if +self+ is not a regexp literal:
3775 *
3776 * r = /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
3777 * r =~ ' x = y '
3778 * p foo # Undefined local variable
3779 * p bar # Undefined local variable
3780 *
3781 * The assignment does not occur if the regexp is not at the left:
3782 *
3783 * ' x = y ' =~ /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
3784 * p foo, foo # Undefined local variables
3785 *
3786 * A regexp interpolation, <tt>#{}</tt>, also disables
3787 * the assignment:
3788 *
3789 * r = /(?<foo>\w+)/
3790 * /(?<foo>\w+)\s*=\s*#{r}/ =~ 'x = y'
3791 * p foo # Undefined local variable
3792 *
3793 */
3794
3795VALUE
3796rb_reg_match(VALUE re, VALUE str)
3797{
3798 long pos = reg_match_pos(re, &str, 0, NULL);
3799 if (pos < 0) return Qnil;
3800 pos = rb_str_sublen(str, pos);
3801 return LONG2FIX(pos);
3802}
3803
3804/*
3805 * call-seq:
3806 * self === other -> true or false
3807 *
3808 * Returns whether +self+ finds a match in +other+:
3809 *
3810 * /^[a-z]*$/ === 'HELLO' # => false
3811 * /^[A-Z]*$/ === 'HELLO' # => true
3812 *
3813 * This method is called in case statements:
3814 *
3815 * s = 'HELLO'
3816 * case s
3817 * when /\A[a-z]*\z/; print "Lower case\n"
3818 * when /\A[A-Z]*\z/; print "Upper case\n"
3819 * else print "Mixed case\n"
3820 * end # => "Upper case"
3821 *
3822 */
3823
3824static VALUE
3825rb_reg_eqq(VALUE re, VALUE str)
3826{
3827 long start;
3828
3829 str = reg_operand(str, FALSE);
3830 if (NIL_P(str)) {
3831 rb_backref_set(Qnil);
3832 return Qfalse;
3833 }
3834 start = rb_reg_search(re, str, 0, 0);
3835 return RBOOL(start >= 0);
3836}
3837
3838
3839/*
3840 * call-seq:
3841 * ~ rxp -> integer or nil
3842 *
3843 * Equivalent to <tt><i>rxp</i> =~ $_</tt>:
3844 *
3845 * $_ = "input data"
3846 * ~ /at/ # => 7
3847 *
3848 */
3849
3850VALUE
3851rb_reg_match2(VALUE re)
3852{
3853 long start;
3854 VALUE line = rb_lastline_get();
3855
3856 if (!RB_TYPE_P(line, T_STRING)) {
3857 rb_backref_set(Qnil);
3858 return Qnil;
3859 }
3860
3861 start = rb_reg_search(re, line, 0, 0);
3862 if (start < 0) {
3863 return Qnil;
3864 }
3865 start = rb_str_sublen(line, start);
3866 return LONG2FIX(start);
3867}
3868
3869
3870/*
3871 * call-seq:
3872 * match(string, offset = 0) -> matchdata or nil
3873 * match(string, offset = 0) {|matchdata| ... } -> object
3874 *
3875 * With no block given, returns the MatchData object
3876 * that describes the match, if any, or +nil+ if none;
3877 * the search begins at the given character +offset+ in +string+:
3878 *
3879 * /abra/.match('abracadabra') # => #<MatchData "abra">
3880 * /abra/.match('abracadabra', 4) # => #<MatchData "abra">
3881 * /abra/.match('abracadabra', 8) # => nil
3882 * /abra/.match('abracadabra', 800) # => nil
3883 *
3884 * string = "\u{5d0 5d1 5e8 5d0}cadabra"
3885 * /abra/.match(string, 7) #=> #<MatchData "abra">
3886 * /abra/.match(string, 8) #=> nil
3887 * /abra/.match(string.b, 8) #=> #<MatchData "abra">
3888 *
3889 * With a block given, calls the block if and only if a match is found;
3890 * returns the block's value:
3891 *
3892 * /abra/.match('abracadabra') {|matchdata| p matchdata }
3893 * # => #<MatchData "abra">
3894 * /abra/.match('abracadabra', 4) {|matchdata| p matchdata }
3895 * # => #<MatchData "abra">
3896 * /abra/.match('abracadabra', 8) {|matchdata| p matchdata }
3897 * # => nil
3898 * /abra/.match('abracadabra', 8) {|marchdata| fail 'Cannot happen' }
3899 * # => nil
3900 *
3901 * Output (from the first two blocks above):
3902 *
3903 * #<MatchData "abra">
3904 * #<MatchData "abra">
3905 *
3906 * /(.)(.)(.)/.match("abc")[2] # => "b"
3907 * /(.)(.)/.match("abc", 1)[2] # => "c"
3908 *
3909 */
3910
3911static VALUE
3912rb_reg_match_m(int argc, VALUE *argv, VALUE re)
3913{
3914 VALUE result = Qnil, str, initpos;
3915 long pos;
3916
3917 if (rb_scan_args(argc, argv, "11", &str, &initpos) == 2) {
3918 pos = NUM2LONG(initpos);
3919 }
3920 else {
3921 pos = 0;
3922 }
3923
3924 pos = reg_match_pos(re, &str, pos, &result);
3925 if (pos < 0) {
3926 rb_backref_set(Qnil);
3927 return Qnil;
3928 }
3929 rb_match_busy(result);
3930 if (!NIL_P(result) && rb_block_given_p()) {
3931 return rb_yield(result);
3932 }
3933 return result;
3934}
3935
3936/*
3937 * call-seq:
3938 * match?(string) -> true or false
3939 * match?(string, offset = 0) -> true or false
3940 *
3941 * Returns <code>true</code> or <code>false</code> to indicate whether the
3942 * regexp is matched or not without updating $~ and other related variables.
3943 * If the second parameter is present, it specifies the position in the string
3944 * to begin the search.
3945 *
3946 * /R.../.match?("Ruby") # => true
3947 * /R.../.match?("Ruby", 1) # => false
3948 * /P.../.match?("Ruby") # => false
3949 * $& # => nil
3950 */
3951
3952static VALUE
3953rb_reg_match_m_p(int argc, VALUE *argv, VALUE re)
3954{
3955 long pos = rb_check_arity(argc, 1, 2) > 1 ? NUM2LONG(argv[1]) : 0;
3956 return rb_reg_match_p(re, argv[0], pos);
3957}
3958
3959VALUE
3960rb_reg_match_p(VALUE re, VALUE str, long pos)
3961{
3962 if (NIL_P(str)) return Qfalse;
3963 str = SYMBOL_P(str) ? rb_sym2str(str) : StringValue(str);
3964 if (pos) {
3965 if (pos < 0) {
3966 pos += NUM2LONG(rb_str_length(str));
3967 if (pos < 0) return Qfalse;
3968 }
3969 if (pos > 0) {
3970 long len = 1;
3971 const char *beg = rb_str_subpos(str, pos, &len);
3972 if (!beg) return Qfalse;
3973 pos = beg - RSTRING_PTR(str);
3974 }
3975 }
3976
3977 struct reg_onig_search_args args = {
3978 .pos = pos,
3979 .range = RSTRING_LEN(str),
3980 };
3981
3982 return rb_reg_onig_match(re, str, reg_onig_search, &args, NULL) == ONIG_MISMATCH ? Qfalse : Qtrue;
3983}
3984
3985/*
3986 * Document-method: compile
3987 *
3988 * Alias for Regexp.new
3989 */
3990
3991static int
3992str_to_option(VALUE str)
3993{
3994 int flag = 0;
3995 const char *ptr;
3996 long len;
3997 str = rb_check_string_type(str);
3998 if (NIL_P(str)) return -1;
3999 RSTRING_GETMEM(str, ptr, len);
4000 for (long i = 0; i < len; ++i) {
4001 int f = char_to_option(ptr[i]);
4002 if (!f) {
4003 rb_raise(rb_eArgError, "unknown regexp option: %"PRIsVALUE, str);
4004 }
4005 flag |= f;
4006 }
4007 return flag;
4008}
4009
4010static void
4011set_timeout(rb_hrtime_t *hrt, VALUE timeout)
4012{
4013 double timeout_d = NIL_P(timeout) ? 0.0 : NUM2DBL(timeout);
4014 if (!NIL_P(timeout) && timeout_d <= 0) {
4015 rb_raise(rb_eArgError, "invalid timeout: %"PRIsVALUE, timeout);
4016 }
4017 double2hrtime(hrt, timeout_d);
4018}
4019
4020static VALUE
4021reg_copy(VALUE copy, VALUE orig)
4022{
4023 int r;
4024 regex_t *re;
4025
4026 rb_reg_initialize_check(copy);
4027 if ((r = onig_reg_copy(&re, RREGEXP_PTR(orig))) != 0) {
4028 /* ONIGERR_MEMORY only */
4029 rb_raise(rb_eRegexpError, "%s", onig_error_code_to_format(r));
4030 }
4031 RREGEXP_PTR(copy) = re;
4032 RB_OBJ_WRITE(copy, &RREGEXP(copy)->src, RREGEXP(orig)->src);
4033 RREGEXP_PTR(copy)->timelimit = RREGEXP_PTR(orig)->timelimit;
4034 rb_enc_copy(copy, orig);
4035 FL_SET_RAW(copy, FL_TEST_RAW(orig, KCODE_FIXED|REG_ENCODING_NONE));
4036 if (RBASIC_CLASS(copy) == rb_cRegexp) {
4037 OBJ_FREEZE(copy);
4038 }
4039
4040 return copy;
4041}
4042
4043struct reg_init_args {
4044 VALUE str;
4045 VALUE timeout;
4046 rb_encoding *enc;
4047 int flags;
4048};
4049
4050static VALUE reg_extract_args(int argc, VALUE *argv, struct reg_init_args *args);
4051static VALUE reg_init_args(VALUE self, VALUE str, rb_encoding *enc, int flags);
4052
4053/*
4054 * call-seq:
4055 * Regexp.new(string, options = 0, timeout: nil) -> regexp
4056 * Regexp.new(regexp, timeout: nil) -> regexp
4057 *
4058 * With argument +string+ given, returns a new regexp with the given string
4059 * and options:
4060 *
4061 * r = Regexp.new('foo') # => /foo/
4062 * r.source # => "foo"
4063 * r.options # => 0
4064 *
4065 * Optional argument +options+ is one of the following:
4066 *
4067 * - A String of options:
4068 *
4069 * Regexp.new('foo', 'i') # => /foo/i
4070 * Regexp.new('foo', 'im') # => /foo/im
4071 *
4072 * - The bit-wise OR of one or more of the constants
4073 * Regexp::EXTENDED, Regexp::IGNORECASE, Regexp::MULTILINE, and
4074 * Regexp::NOENCODING:
4075 *
4076 * Regexp.new('foo', Regexp::IGNORECASE) # => /foo/i
4077 * Regexp.new('foo', Regexp::EXTENDED) # => /foo/x
4078 * Regexp.new('foo', Regexp::MULTILINE) # => /foo/m
4079 * Regexp.new('foo', Regexp::NOENCODING) # => /foo/n
4080 * flags = Regexp::IGNORECASE | Regexp::EXTENDED | Regexp::MULTILINE
4081 * Regexp.new('foo', flags) # => /foo/mix
4082 *
4083 * - +nil+ or +false+, which is ignored.
4084 * - Any other truthy value, in which case the regexp will be
4085 * case-insensitive.
4086 *
4087 * If optional keyword argument +timeout+ is given,
4088 * its float value overrides the timeout interval for the class,
4089 * Regexp.timeout.
4090 * If +nil+ is passed as +timeout, it uses the timeout interval
4091 * for the class, Regexp.timeout.
4092 *
4093 * With argument +regexp+ given, returns a new regexp. The source,
4094 * options, timeout are the same as +regexp+. +options+ and +n_flag+
4095 * arguments are ineffective. The timeout can be overridden by
4096 * +timeout+ keyword.
4097 *
4098 * options = Regexp::MULTILINE
4099 * r = Regexp.new('foo', options, timeout: 1.1) # => /foo/m
4100 * r2 = Regexp.new(r) # => /foo/m
4101 * r2.timeout # => 1.1
4102 * r3 = Regexp.new(r, timeout: 3.14) # => /foo/m
4103 * r3.timeout # => 3.14
4104 *
4105 */
4106
4107static VALUE
4108rb_reg_initialize_m(int argc, VALUE *argv, VALUE self)
4109{
4110 struct reg_init_args args;
4111 VALUE re = reg_extract_args(argc, argv, &args);
4112
4113 if (NIL_P(re)) {
4114 reg_init_args(self, args.str, args.enc, args.flags);
4115 }
4116 else {
4117 reg_copy(self, re);
4118 }
4119
4120 set_timeout(&RREGEXP_PTR(self)->timelimit, args.timeout);
4121 if (RBASIC_CLASS(self) == rb_cRegexp) {
4122 OBJ_FREEZE(self);
4123 }
4124
4125 return self;
4126}
4127
4128static VALUE
4129reg_extract_args(int argc, VALUE *argv, struct reg_init_args *args)
4130{
4131 int flags = 0;
4132 rb_encoding *enc = 0;
4133 VALUE str, src, opts = Qundef, kwargs;
4134 VALUE re = Qnil;
4135
4136 rb_scan_args(argc, argv, "11:", &src, &opts, &kwargs);
4137
4138 args->timeout = Qnil;
4139 if (!NIL_P(kwargs)) {
4140 static ID keywords[1];
4141 if (!keywords[0]) {
4142 keywords[0] = rb_intern_const("timeout");
4143 }
4144 rb_get_kwargs(kwargs, keywords, 0, 1, &args->timeout);
4145 }
4146
4147 if (RB_TYPE_P(src, T_REGEXP)) {
4148 re = src;
4149
4150 if (!NIL_P(opts)) {
4151 rb_warn("flags ignored");
4152 }
4153 rb_reg_check(re);
4154 flags = rb_reg_options(re);
4155 str = RREGEXP_SRC(re);
4156 }
4157 else {
4158 if (!NIL_P(opts)) {
4159 int f;
4160 if (FIXNUM_P(opts)) flags = FIX2INT(opts);
4161 else if ((f = str_to_option(opts)) >= 0) flags = f;
4162 else if (rb_bool_expected(opts, "ignorecase", FALSE))
4163 flags = ONIG_OPTION_IGNORECASE;
4164 }
4165 str = StringValue(src);
4166 }
4167 args->str = str;
4168 args->enc = enc;
4169 args->flags = flags;
4170 return re;
4171}
4172
4173static VALUE
4174reg_init_args(VALUE self, VALUE str, rb_encoding *enc, int flags)
4175{
4176 if (enc && rb_enc_get(str) != enc)
4177 rb_reg_init_str_enc(self, str, enc, flags);
4178 else
4179 rb_reg_init_str(self, str, flags);
4180 return self;
4181}
4182
4183VALUE
4184rb_reg_quote(VALUE str)
4185{
4186 rb_encoding *enc = rb_enc_get(str);
4187 char *s, *send, *t;
4188 VALUE tmp;
4189 int c, clen;
4190 int ascii_only = rb_enc_str_asciionly_p(str);
4191
4192 s = RSTRING_PTR(str);
4193 send = s + RSTRING_LEN(str);
4194 while (s < send) {
4195 c = rb_enc_ascget(s, send, &clen, enc);
4196 if (c == -1) {
4197 s += mbclen(s, send, enc);
4198 continue;
4199 }
4200 switch (c) {
4201 case '[': case ']': case '{': case '}':
4202 case '(': case ')': case '|': case '-':
4203 case '*': case '.': case '\\':
4204 case '?': case '+': case '^': case '$':
4205 case ' ': case '#':
4206 case '\t': case '\f': case '\v': case '\n': case '\r':
4207 goto meta_found;
4208 }
4209 s += clen;
4210 }
4211 tmp = rb_str_new3(str);
4212 if (ascii_only) {
4213 rb_enc_associate(tmp, rb_usascii_encoding());
4214 }
4215 return tmp;
4216
4217 meta_found:
4218 tmp = rb_str_new(0, RSTRING_LEN(str)*2);
4219 if (ascii_only) {
4220 rb_enc_associate(tmp, rb_usascii_encoding());
4221 }
4222 else {
4223 rb_enc_copy(tmp, str);
4224 }
4225 t = RSTRING_PTR(tmp);
4226 /* copy upto metacharacter */
4227 const char *p = RSTRING_PTR(str);
4228 memcpy(t, p, s - p);
4229 t += s - p;
4230
4231 while (s < send) {
4232 c = rb_enc_ascget(s, send, &clen, enc);
4233 if (c == -1) {
4234 int n = mbclen(s, send, enc);
4235
4236 while (n--)
4237 *t++ = *s++;
4238 continue;
4239 }
4240 s += clen;
4241 switch (c) {
4242 case '[': case ']': case '{': case '}':
4243 case '(': case ')': case '|': case '-':
4244 case '*': case '.': case '\\':
4245 case '?': case '+': case '^': case '$':
4246 case '#':
4247 t += rb_enc_mbcput('\\', t, enc);
4248 break;
4249 case ' ':
4250 t += rb_enc_mbcput('\\', t, enc);
4251 t += rb_enc_mbcput(' ', t, enc);
4252 continue;
4253 case '\t':
4254 t += rb_enc_mbcput('\\', t, enc);
4255 t += rb_enc_mbcput('t', t, enc);
4256 continue;
4257 case '\n':
4258 t += rb_enc_mbcput('\\', t, enc);
4259 t += rb_enc_mbcput('n', t, enc);
4260 continue;
4261 case '\r':
4262 t += rb_enc_mbcput('\\', t, enc);
4263 t += rb_enc_mbcput('r', t, enc);
4264 continue;
4265 case '\f':
4266 t += rb_enc_mbcput('\\', t, enc);
4267 t += rb_enc_mbcput('f', t, enc);
4268 continue;
4269 case '\v':
4270 t += rb_enc_mbcput('\\', t, enc);
4271 t += rb_enc_mbcput('v', t, enc);
4272 continue;
4273 }
4274 t += rb_enc_mbcput(c, t, enc);
4275 }
4276 rb_str_resize(tmp, t - RSTRING_PTR(tmp));
4277 return tmp;
4278}
4279
4280
4281/*
4282 * call-seq:
4283 * Regexp.escape(string) -> new_string
4284 *
4285 * Returns a new string that escapes any characters
4286 * that have special meaning in a regular expression:
4287 *
4288 * s = Regexp.escape('\*?{}.') # => "\\\\\\*\\?\\{\\}\\."
4289 *
4290 * For any string +s+, this call returns a MatchData object:
4291 *
4292 * r = Regexp.new(Regexp.escape(s)) # => /\\\\\\\*\\\?\\\{\\\}\\\./
4293 * r.match(s) # => #<MatchData "\\\\\\*\\?\\{\\}\\.">
4294 *
4295 */
4296
4297static VALUE
4298rb_reg_s_quote(VALUE c, VALUE str)
4299{
4300 return rb_reg_quote(reg_operand(str, TRUE));
4301}
4302
4303int
4304rb_reg_options(VALUE re)
4305{
4306 int options;
4307
4308 rb_reg_check(re);
4309 options = RREGEXP_PTR(re)->options & ARG_REG_OPTION_MASK;
4310 if (RBASIC(re)->flags & KCODE_FIXED) options |= ARG_ENCODING_FIXED;
4311 if (RBASIC(re)->flags & REG_ENCODING_NONE) options |= ARG_ENCODING_NONE;
4312 return options;
4313}
4314
4315static VALUE
4316rb_check_regexp_type(VALUE re)
4317{
4318 return rb_check_convert_type(re, T_REGEXP, "Regexp", "to_regexp");
4319}
4320
4321/*
4322 * call-seq:
4323 * Regexp.try_convert(object) -> regexp or nil
4324 *
4325 * Returns +object+ if it is a regexp:
4326 *
4327 * Regexp.try_convert(/re/) # => /re/
4328 *
4329 * Otherwise if +object+ responds to <tt>:to_regexp</tt>,
4330 * calls <tt>object.to_regexp</tt> and returns the result.
4331 *
4332 * Returns +nil+ if +object+ does not respond to <tt>:to_regexp</tt>.
4333 *
4334 * Regexp.try_convert('re') # => nil
4335 *
4336 * Raises an exception unless <tt>object.to_regexp</tt> returns a regexp.
4337 *
4338 */
4339static VALUE
4340rb_reg_s_try_convert(VALUE dummy, VALUE re)
4341{
4342 return rb_check_regexp_type(re);
4343}
4344
4345static VALUE
4346rb_reg_s_union(VALUE self, VALUE args0)
4347{
4348 long argc = RARRAY_LEN(args0);
4349
4350 if (argc == 0) {
4351 VALUE args[1];
4352 args[0] = rb_str_new2("(?!)");
4353 return rb_class_new_instance(1, args, rb_cRegexp);
4354 }
4355 else if (argc == 1) {
4356 VALUE arg = rb_ary_entry(args0, 0);
4357 VALUE re = rb_check_regexp_type(arg);
4358 if (!NIL_P(re))
4359 return re;
4360 else {
4361 VALUE quoted;
4362 quoted = rb_reg_s_quote(Qnil, arg);
4363 return rb_reg_new_str(quoted, 0);
4364 }
4365 }
4366 else {
4367 int i;
4368 VALUE source = rb_str_buf_new(0);
4369 rb_encoding *result_enc;
4370
4371 int has_asciionly = 0;
4372 rb_encoding *has_ascii_compat_fixed = 0;
4373 rb_encoding *has_ascii_incompat = 0;
4374
4375 for (i = 0; i < argc; i++) {
4376 volatile VALUE v;
4377 VALUE e = rb_ary_entry(args0, i);
4378
4379 if (0 < i)
4380 rb_str_buf_cat_ascii(source, "|");
4381
4382 v = rb_check_regexp_type(e);
4383 if (!NIL_P(v)) {
4384 rb_encoding *enc = rb_enc_get(v);
4385 if (!rb_enc_asciicompat(enc)) {
4386 if (!has_ascii_incompat)
4387 has_ascii_incompat = enc;
4388 else if (has_ascii_incompat != enc)
4389 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4390 rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
4391 }
4392 else if (rb_reg_fixed_encoding_p(v)) {
4393 if (!has_ascii_compat_fixed)
4394 has_ascii_compat_fixed = enc;
4395 else if (has_ascii_compat_fixed != enc)
4396 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4397 rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
4398 }
4399 else {
4400 has_asciionly = 1;
4401 }
4402 v = rb_reg_str_with_term(v, -1);
4403 }
4404 else {
4405 rb_encoding *enc;
4406 StringValue(e);
4407 enc = rb_enc_get(e);
4408 if (!rb_enc_asciicompat(enc)) {
4409 if (!has_ascii_incompat)
4410 has_ascii_incompat = enc;
4411 else if (has_ascii_incompat != enc)
4412 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4413 rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
4414 }
4415 else if (rb_enc_str_asciionly_p(e)) {
4416 has_asciionly = 1;
4417 }
4418 else {
4419 if (!has_ascii_compat_fixed)
4420 has_ascii_compat_fixed = enc;
4421 else if (has_ascii_compat_fixed != enc)
4422 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4423 rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
4424 }
4425 v = rb_reg_s_quote(Qnil, e);
4426 }
4427 if (has_ascii_incompat) {
4428 if (has_asciionly) {
4429 rb_raise(rb_eArgError, "ASCII incompatible encoding: %s",
4430 rb_enc_name(has_ascii_incompat));
4431 }
4432 if (has_ascii_compat_fixed) {
4433 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4434 rb_enc_name(has_ascii_incompat), rb_enc_name(has_ascii_compat_fixed));
4435 }
4436 }
4437
4438 if (i == 0) {
4439 rb_enc_copy(source, v);
4440 }
4441 rb_str_append(source, v);
4442 }
4443
4444 if (has_ascii_incompat) {
4445 result_enc = has_ascii_incompat;
4446 }
4447 else if (has_ascii_compat_fixed) {
4448 result_enc = has_ascii_compat_fixed;
4449 }
4450 else {
4451 result_enc = rb_ascii8bit_encoding();
4452 }
4453
4454 rb_enc_associate(source, result_enc);
4455 return rb_class_new_instance(1, &source, rb_cRegexp);
4456 }
4457}
4458
4459/*
4460 * call-seq:
4461 * Regexp.union(*patterns) -> regexp
4462 * Regexp.union(array_of_patterns) -> regexp
4463 *
4464 * Returns a new regexp that is the union of the given patterns:
4465 *
4466 * r = Regexp.union(%w[cat dog]) # => /cat|dog/
4467 * r.match('cat') # => #<MatchData "cat">
4468 * r.match('dog') # => #<MatchData "dog">
4469 * r.match('cog') # => nil
4470 *
4471 * For each pattern that is a string, <tt>Regexp.new(pattern)</tt> is used:
4472 *
4473 * Regexp.union('penzance') # => /penzance/
4474 * Regexp.union('a+b*c') # => /a\+b\*c/
4475 * Regexp.union('skiing', 'sledding') # => /skiing|sledding/
4476 * Regexp.union(['skiing', 'sledding']) # => /skiing|sledding/
4477 *
4478 * For each pattern that is a regexp, it is used as is,
4479 * including its flags:
4480 *
4481 * Regexp.union(/foo/i, /bar/m, /baz/x)
4482 * # => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
4483 * Regexp.union([/foo/i, /bar/m, /baz/x])
4484 * # => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
4485 *
4486 * With no arguments, returns <tt>/(?!)/</tt>:
4487 *
4488 * Regexp.union # => /(?!)/
4489 *
4490 * If any regexp pattern contains captures, the behavior is unspecified.
4491 *
4492 */
4493static VALUE
4494rb_reg_s_union_m(VALUE self, VALUE args)
4495{
4496 VALUE v;
4497 if (RARRAY_LEN(args) == 1 &&
4498 !NIL_P(v = rb_check_array_type(rb_ary_entry(args, 0)))) {
4499 return rb_reg_s_union(self, v);
4500 }
4501 return rb_reg_s_union(self, args);
4502}
4503
4504/*
4505 * call-seq:
4506 * Regexp.linear_time?(re)
4507 * Regexp.linear_time?(string, options = 0)
4508 *
4509 * Returns +true+ if matching against <tt>re</tt> can be
4510 * done in linear time to the input string.
4511 *
4512 * Regexp.linear_time?(/re/) # => true
4513 *
4514 * Note that this is a property of the ruby interpreter, not of the argument
4515 * regular expression. Identical regexp can or cannot run in linear time
4516 * depending on your ruby binary. Neither forward nor backward compatibility
4517 * is guaranteed about the return value of this method. Our current algorithm
4518 * is (*1) but this is subject to change in the future. Alternative
4519 * implementations can also behave differently. They might always return
4520 * false for everything.
4521 *
4522 * (*1): https://doi.org/10.1109/SP40001.2021.00032
4523 *
4524 */
4525static VALUE
4526rb_reg_s_linear_time_p(int argc, VALUE *argv, VALUE self)
4527{
4528 struct reg_init_args args;
4529 VALUE re = reg_extract_args(argc, argv, &args);
4530
4531 if (NIL_P(re)) {
4532 re = reg_init_args(rb_reg_alloc(), args.str, args.enc, args.flags);
4533 }
4534
4535 return RBOOL(onig_check_linear_time(RREGEXP_PTR(re)));
4536}
4537
4538/* :nodoc: */
4539static VALUE
4540rb_reg_init_copy(VALUE copy, VALUE re)
4541{
4542 if (!OBJ_INIT_COPY(copy, re)) return copy;
4543 rb_reg_check(re);
4544 return reg_copy(copy, re);
4545}
4546
4547VALUE
4548rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp)
4549{
4550 VALUE val = 0;
4551 char *p, *s, *e;
4552 int no, clen;
4553 rb_encoding *str_enc = rb_enc_get(str);
4554 rb_encoding *src_enc = rb_enc_get(src);
4555 int acompat = rb_enc_asciicompat(str_enc);
4556 long n;
4557#define ASCGET(s,e,cl) (acompat ? (*(cl)=1,ISASCII((s)[0])?(s)[0]:-1) : rb_enc_ascget((s), (e), (cl), str_enc))
4558
4559 RSTRING_GETMEM(str, s, n);
4560 p = s;
4561 e = s + n;
4562
4563 while (s < e) {
4564 int c = ASCGET(s, e, &clen);
4565 char *ss;
4566
4567 if (c == -1) {
4568 s += mbclen(s, e, str_enc);
4569 continue;
4570 }
4571 ss = s;
4572 s += clen;
4573
4574 if (c != '\\' || s == e) continue;
4575
4576 if (!val) {
4577 val = rb_str_buf_new(ss-p);
4578 }
4579 rb_enc_str_buf_cat(val, p, ss-p, str_enc);
4580
4581 c = ASCGET(s, e, &clen);
4582 if (c == -1) {
4583 s += mbclen(s, e, str_enc);
4584 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
4585 p = s;
4586 continue;
4587 }
4588 s += clen;
4589
4590 p = s;
4591 switch (c) {
4592 case '1': case '2': case '3': case '4':
4593 case '5': case '6': case '7': case '8': case '9':
4594 if (!NIL_P(regexp) && onig_noname_group_capture_is_active(RREGEXP_PTR(regexp))) {
4595 no = c - '0';
4596 }
4597 else {
4598 continue;
4599 }
4600 break;
4601
4602 case 'k':
4603 if (s < e && ASCGET(s, e, &clen) == '<') {
4604 char *name, *name_end;
4605
4606 name_end = name = s + clen;
4607 while (name_end < e) {
4608 c = ASCGET(name_end, e, &clen);
4609 if (c == '>') break;
4610 name_end += c == -1 ? mbclen(name_end, e, str_enc) : clen;
4611 }
4612 if (name_end < e) {
4613 VALUE n = rb_str_subseq(str, (long)(name - RSTRING_PTR(str)),
4614 (long)(name_end - name));
4615 if ((no = NAME_TO_NUMBER(regs, regexp, n, name, name_end)) < 1) {
4616 name_to_backref_error(n);
4617 }
4618 p = s = name_end + clen;
4619 break;
4620 }
4621 else {
4622 rb_raise(rb_eRuntimeError, "invalid group name reference format");
4623 }
4624 }
4625
4626 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
4627 continue;
4628
4629 case '0':
4630 case '&':
4631 no = 0;
4632 break;
4633
4634 case '`':
4635 rb_enc_str_buf_cat(val, RSTRING_PTR(src), BEG(0), src_enc);
4636 continue;
4637
4638 case '\'':
4639 rb_enc_str_buf_cat(val, RSTRING_PTR(src)+END(0), RSTRING_LEN(src)-END(0), src_enc);
4640 continue;
4641
4642 case '+':
4643 no = regs->num_regs-1;
4644 while (BEG(no) == -1 && no > 0) no--;
4645 if (no == 0) continue;
4646 break;
4647
4648 case '\\':
4649 rb_enc_str_buf_cat(val, s-clen, clen, str_enc);
4650 continue;
4651
4652 default:
4653 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
4654 continue;
4655 }
4656
4657 if (no >= 0) {
4658 if (no >= regs->num_regs) continue;
4659 if (BEG(no) == -1) continue;
4660 rb_enc_str_buf_cat(val, RSTRING_PTR(src)+BEG(no), END(no)-BEG(no), src_enc);
4661 }
4662 }
4663
4664 if (!val) return str;
4665 if (p < e) {
4666 rb_enc_str_buf_cat(val, p, e-p, str_enc);
4667 }
4668
4669 return val;
4670}
4671
4672static VALUE
4673ignorecase_getter(ID _x, VALUE *_y)
4674{
4675 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "variable $= is no longer effective");
4676 return Qfalse;
4677}
4678
4679static void
4680ignorecase_setter(VALUE val, ID id, VALUE *_)
4681{
4682 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "variable $= is no longer effective; ignored");
4683}
4684
4685static VALUE
4686match_getter(void)
4687{
4688 VALUE match = rb_backref_get();
4689
4690 if (NIL_P(match)) return Qnil;
4691 rb_match_busy(match);
4692 return match;
4693}
4694
4695static VALUE
4696get_LAST_MATCH_INFO(ID _x, VALUE *_y)
4697{
4698 return match_getter();
4699}
4700
4701static void
4702match_setter(VALUE val, ID _x, VALUE *_y)
4703{
4704 if (!NIL_P(val)) {
4705 Check_Type(val, T_MATCH);
4706 }
4707 rb_backref_set(val);
4708}
4709
4710/*
4711 * call-seq:
4712 * Regexp.last_match -> matchdata or nil
4713 * Regexp.last_match(n) -> string or nil
4714 * Regexp.last_match(name) -> string or nil
4715 *
4716 * With no argument, returns the value of <tt>$~</tt>,
4717 * which is the result of the most recent pattern match
4718 * (see {Regexp global variables}[rdoc-ref:Regexp@Global+Variables]):
4719 *
4720 * /c(.)t/ =~ 'cat' # => 0
4721 * Regexp.last_match # => #<MatchData "cat" 1:"a">
4722 * /a/ =~ 'foo' # => nil
4723 * Regexp.last_match # => nil
4724 *
4725 * With non-negative integer argument +n+, returns the _n_th field in the
4726 * matchdata, if any, or nil if none:
4727 *
4728 * /c(.)t/ =~ 'cat' # => 0
4729 * Regexp.last_match(0) # => "cat"
4730 * Regexp.last_match(1) # => "a"
4731 * Regexp.last_match(2) # => nil
4732 *
4733 * With negative integer argument +n+, counts backwards from the last field:
4734 *
4735 * Regexp.last_match(-1) # => "a"
4736 *
4737 * With string or symbol argument +name+,
4738 * returns the string value for the named capture, if any:
4739 *
4740 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ 'var = val'
4741 * Regexp.last_match # => #<MatchData "var = val" lhs:"var"rhs:"val">
4742 * Regexp.last_match(:lhs) # => "var"
4743 * Regexp.last_match('rhs') # => "val"
4744 * Regexp.last_match('foo') # Raises IndexError.
4745 *
4746 */
4747
4748static VALUE
4749rb_reg_s_last_match(int argc, VALUE *argv, VALUE _)
4750{
4751 if (rb_check_arity(argc, 0, 1) == 1) {
4752 VALUE match = rb_backref_get();
4753 int n;
4754 if (NIL_P(match)) return Qnil;
4755 n = match_backref_number(match, argv[0]);
4756 return rb_reg_nth_match(n, match);
4757 }
4758 return match_getter();
4759}
4760
4761static void
4762re_warn(const char *s)
4763{
4764 rb_warn("%s", s);
4765}
4766
4767// This function is periodically called during regexp matching
4768bool
4769rb_reg_timeout_p(regex_t *reg, void *end_time_)
4770{
4771 rb_hrtime_t *end_time = (rb_hrtime_t *)end_time_;
4772
4773 if (*end_time == 0) {
4774 // This is the first time to check interrupts;
4775 // just measure the current time and determine the end time
4776 // if timeout is set.
4777 rb_hrtime_t timelimit = reg->timelimit;
4778
4779 if (!timelimit) {
4780 // no per-object timeout.
4781 timelimit = rb_reg_match_time_limit;
4782 }
4783
4784 if (timelimit) {
4785 *end_time = rb_hrtime_add(timelimit, rb_hrtime_now());
4786 }
4787 else {
4788 // no timeout is set
4789 *end_time = RB_HRTIME_MAX;
4790 }
4791 }
4792 else {
4793 if (*end_time < rb_hrtime_now()) {
4794 // Timeout has exceeded
4795 return true;
4796 }
4797 }
4798
4799 return false;
4800}
4801
4802/*
4803 * call-seq:
4804 * Regexp.timeout -> float or nil
4805 *
4806 * It returns the current default timeout interval for Regexp matching in second.
4807 * +nil+ means no default timeout configuration.
4808 */
4809
4810static VALUE
4811rb_reg_s_timeout_get(VALUE dummy)
4812{
4813 double d = hrtime2double(rb_reg_match_time_limit);
4814 if (d == 0.0) return Qnil;
4815 return DBL2NUM(d);
4816}
4817
4818/*
4819 * call-seq:
4820 * Regexp.timeout = float or nil
4821 *
4822 * It sets the default timeout interval for Regexp matching in second.
4823 * +nil+ means no default timeout configuration.
4824 * This configuration is process-global. If you want to set timeout for
4825 * each Regexp, use +timeout+ keyword for <code>Regexp.new</code>.
4826 *
4827 * Regexp.timeout = 1
4828 * /^a*b?a*$/ =~ "a" * 100000 + "x" #=> regexp match timeout (RuntimeError)
4829 */
4830
4831static VALUE
4832rb_reg_s_timeout_set(VALUE dummy, VALUE timeout)
4833{
4834 rb_ractor_ensure_main_ractor("can not access Regexp.timeout from non-main Ractors");
4835
4836 set_timeout(&rb_reg_match_time_limit, timeout);
4837
4838 return timeout;
4839}
4840
4841/*
4842 * call-seq:
4843 * rxp.timeout -> float or nil
4844 *
4845 * It returns the timeout interval for Regexp matching in second.
4846 * +nil+ means no default timeout configuration.
4847 *
4848 * This configuration is per-object. The global configuration set by
4849 * Regexp.timeout= is ignored if per-object configuration is set.
4850 *
4851 * re = Regexp.new("^a*b?a*$", timeout: 1)
4852 * re.timeout #=> 1.0
4853 * re =~ "a" * 100000 + "x" #=> regexp match timeout (RuntimeError)
4854 */
4855
4856static VALUE
4857rb_reg_timeout_get(VALUE re)
4858{
4859 rb_reg_check(re);
4860 double d = hrtime2double(RREGEXP_PTR(re)->timelimit);
4861 if (d == 0.0) return Qnil;
4862 return DBL2NUM(d);
4863}
4864
4865/*
4866 * Document-class: RegexpError
4867 *
4868 * Raised when given an invalid regexp expression.
4869 *
4870 * Regexp.new("?")
4871 *
4872 * <em>raises the exception:</em>
4873 *
4874 * RegexpError: target of repeat operator is not specified: /?/
4875 */
4876
4877/*
4878 * Document-class: Regexp
4879 *
4880 * :include: doc/_regexp.rdoc
4881 */
4882
4883void
4884Init_Regexp(void)
4885{
4886 rb_eRegexpError = rb_define_class("RegexpError", rb_eStandardError);
4887
4888 onigenc_set_default_encoding(ONIG_ENCODING_ASCII);
4889 onig_set_warn_func(re_warn);
4890 onig_set_verb_warn_func(re_warn);
4891
4892 rb_define_virtual_variable("$~", get_LAST_MATCH_INFO, match_setter);
4893 rb_define_virtual_variable("$&", last_match_getter, 0);
4894 rb_define_virtual_variable("$`", prematch_getter, 0);
4895 rb_define_virtual_variable("$'", postmatch_getter, 0);
4896 rb_define_virtual_variable("$+", last_paren_match_getter, 0);
4897
4898 rb_gvar_ractor_local("$~");
4899 rb_gvar_ractor_local("$&");
4900 rb_gvar_ractor_local("$`");
4901 rb_gvar_ractor_local("$'");
4902 rb_gvar_ractor_local("$+");
4903
4904 rb_define_virtual_variable("$=", ignorecase_getter, ignorecase_setter);
4905
4906 rb_cRegexp = rb_define_class("Regexp", rb_cObject);
4907 rb_define_alloc_func(rb_cRegexp, rb_reg_s_alloc);
4908 rb_define_singleton_method(rb_cRegexp, "compile", rb_class_new_instance_pass_kw, -1);
4909 rb_define_singleton_method(rb_cRegexp, "quote", rb_reg_s_quote, 1);
4910 rb_define_singleton_method(rb_cRegexp, "escape", rb_reg_s_quote, 1);
4911 rb_define_singleton_method(rb_cRegexp, "union", rb_reg_s_union_m, -2);
4912 rb_define_singleton_method(rb_cRegexp, "last_match", rb_reg_s_last_match, -1);
4913 rb_define_singleton_method(rb_cRegexp, "try_convert", rb_reg_s_try_convert, 1);
4914 rb_define_singleton_method(rb_cRegexp, "linear_time?", rb_reg_s_linear_time_p, -1);
4915
4916 rb_define_method(rb_cRegexp, "initialize", rb_reg_initialize_m, -1);
4917 rb_define_method(rb_cRegexp, "initialize_copy", rb_reg_init_copy, 1);
4918 rb_define_method(rb_cRegexp, "hash", rb_reg_hash, 0);
4919 rb_define_method(rb_cRegexp, "eql?", rb_reg_equal, 1);
4920 rb_define_method(rb_cRegexp, "==", rb_reg_equal, 1);
4921 rb_define_method(rb_cRegexp, "=~", rb_reg_match, 1);
4922 rb_define_method(rb_cRegexp, "===", rb_reg_eqq, 1);
4923 rb_define_method(rb_cRegexp, "~", rb_reg_match2, 0);
4924 rb_define_method(rb_cRegexp, "match", rb_reg_match_m, -1);
4925 rb_define_method(rb_cRegexp, "match?", rb_reg_match_m_p, -1);
4926 rb_define_method(rb_cRegexp, "to_s", rb_reg_to_s, 0);
4927 rb_define_method(rb_cRegexp, "inspect", rb_reg_inspect, 0);
4928 rb_define_method(rb_cRegexp, "source", rb_reg_source, 0);
4929 rb_define_method(rb_cRegexp, "casefold?", rb_reg_casefold_p, 0);
4930 rb_define_method(rb_cRegexp, "options", rb_reg_options_m, 0);
4931 rb_define_method(rb_cRegexp, "encoding", rb_obj_encoding, 0); /* in encoding.c */
4932 rb_define_method(rb_cRegexp, "fixed_encoding?", rb_reg_fixed_encoding_p, 0);
4933 rb_define_method(rb_cRegexp, "names", rb_reg_names, 0);
4934 rb_define_method(rb_cRegexp, "named_captures", rb_reg_named_captures, 0);
4935 rb_define_method(rb_cRegexp, "timeout", rb_reg_timeout_get, 0);
4936
4937 /* Raised when regexp matching timed out. */
4938 rb_eRegexpTimeoutError = rb_define_class_under(rb_cRegexp, "TimeoutError", rb_eRegexpError);
4939 rb_define_singleton_method(rb_cRegexp, "timeout", rb_reg_s_timeout_get, 0);
4940 rb_define_singleton_method(rb_cRegexp, "timeout=", rb_reg_s_timeout_set, 1);
4941
4942 /* see Regexp.options and Regexp.new */
4943 rb_define_const(rb_cRegexp, "IGNORECASE", INT2FIX(ONIG_OPTION_IGNORECASE));
4944 /* see Regexp.options and Regexp.new */
4945 rb_define_const(rb_cRegexp, "EXTENDED", INT2FIX(ONIG_OPTION_EXTEND));
4946 /* see Regexp.options and Regexp.new */
4947 rb_define_const(rb_cRegexp, "MULTILINE", INT2FIX(ONIG_OPTION_MULTILINE));
4948 /* see Regexp.options and Regexp.new */
4949 rb_define_const(rb_cRegexp, "FIXEDENCODING", INT2FIX(ARG_ENCODING_FIXED));
4950 /* see Regexp.options and Regexp.new */
4951 rb_define_const(rb_cRegexp, "NOENCODING", INT2FIX(ARG_ENCODING_NONE));
4952
4953 rb_global_variable(&reg_cache);
4954
4955 rb_cMatch = rb_define_class("MatchData", rb_cObject);
4956 rb_define_alloc_func(rb_cMatch, match_alloc);
4957 rb_undef_method(CLASS_OF(rb_cMatch), "new");
4958 rb_undef_method(CLASS_OF(rb_cMatch), "allocate");
4959
4960 rb_define_method(rb_cMatch, "initialize_copy", match_init_copy, 1);
4961 rb_define_method(rb_cMatch, "regexp", match_regexp, 0);
4962 rb_define_method(rb_cMatch, "names", match_names, 0);
4963 rb_define_method(rb_cMatch, "size", match_size, 0);
4964 rb_define_method(rb_cMatch, "length", match_size, 0);
4965 rb_define_method(rb_cMatch, "offset", match_offset, 1);
4966 rb_define_method(rb_cMatch, "byteoffset", match_byteoffset, 1);
4967 rb_define_method(rb_cMatch, "bytebegin", match_bytebegin, 1);
4968 rb_define_method(rb_cMatch, "byteend", match_byteend, 1);
4969 rb_define_method(rb_cMatch, "begin", match_begin, 1);
4970 rb_define_method(rb_cMatch, "end", match_end, 1);
4971 rb_define_method(rb_cMatch, "match", match_nth, 1);
4972 rb_define_method(rb_cMatch, "match_length", match_nth_length, 1);
4973 rb_define_method(rb_cMatch, "to_a", match_to_a, 0);
4974 rb_define_method(rb_cMatch, "[]", match_aref, -1);
4975 rb_define_method(rb_cMatch, "captures", match_captures, 0);
4976 rb_define_alias(rb_cMatch, "deconstruct", "captures");
4977 rb_define_method(rb_cMatch, "named_captures", match_named_captures, -1);
4978 rb_define_method(rb_cMatch, "deconstruct_keys", match_deconstruct_keys, 1);
4979 rb_define_method(rb_cMatch, "values_at", match_values_at, -1);
4980 rb_define_method(rb_cMatch, "pre_match", rb_reg_match_pre, 0);
4981 rb_define_method(rb_cMatch, "post_match", rb_reg_match_post, 0);
4982 rb_define_method(rb_cMatch, "to_s", match_to_s, 0);
4983 rb_define_method(rb_cMatch, "inspect", match_inspect, 0);
4984 rb_define_method(rb_cMatch, "string", match_string, 0);
4985 rb_define_method(rb_cMatch, "hash", match_hash, 0);
4986 rb_define_method(rb_cMatch, "eql?", match_equal, 1);
4987 rb_define_method(rb_cMatch, "==", match_equal, 1);
4988 rb_define_method(rb_cMatch, "integer_at", match_integer_at, -1);
4989}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
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:3180
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2969
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
Definition coderange.h:180
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1683
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define ISSPACE
Old name of rb_isspace.
Definition ctype.h:88
#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 rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition string.h:1680
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ENC_CODERANGE(obj)
Old name of RB_ENC_CODERANGE.
Definition coderange.h:184
#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 rb_str_new3
Old name of rb_str_new_shared.
Definition string.h:1677
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
Definition encoding.h:517
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:125
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#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 MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
Definition encoding.h:516
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#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 NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#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 rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define rb_str_new4
Old name of rb_str_new_frozen.
Definition string.h:1678
#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:661
VALUE rb_eRegexpError
RegexpError exception.
Definition re.c:35
#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:1427
VALUE rb_eEncCompatError
Encoding::CompatibilityError exception.
Definition error.c:1434
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:467
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1429
VALUE rb_obj_reveal(VALUE obj, VALUE klass)
Make a hidden object visible again.
Definition object.c:104
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:640
VALUE rb_cMatch
MatchData class.
Definition re.c:965
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:95
VALUE rb_cRegexp
Regexp class.
Definition re.c:2664
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:229
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
Encoding relates APIs.
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_char_to_option_kcode(int c, int *option, int *kcode)
Converts a character option to its encoding.
Definition re.c:331
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
VALUE rb_enc_reg_new(const char *ptr, long len, rb_encoding *enc, int opts)
Identical to rb_reg_new(), except it additionally takes an encoding.
Definition re.c:3470
int rb_enc_str_coderange(VALUE str)
Scans the passed string to collect its code range.
Definition string.c:930
long rb_memsearch(const void *x, long m, const void *y, long n, rb_encoding *enc)
Looks for the passed string in the passed buffer.
Definition re.c:255
long 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:2317
long rb_str_coderange_scan_restartable(const char *str, const char *end, rb_encoding *enc, int *cr)
Scans the passed string until it finds something odd.
Definition string.c:814
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:2977
#define RGENGC_WB_PROTECTED_MATCH
This is a compile-time flag to enable/disable write barrier for struct RMatch.
Definition gc.h:512
#define RGENGC_WB_PROTECTED_REGEXP
This is a compile-time flag to enable/disable write barrier for struct RRegexp.
Definition gc.h:501
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_resize(VALUE ary, long len)
Expands or shrinks the passed array to the passed length.
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.
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
int rb_uv_to_utf8(char buf[6], unsigned long uv)
Encodes a Unicode codepoint into its UTF-8 representation.
Definition pack.c:1687
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_backref_get(void)
Queries the last match, or Regexp.last_match, or the $~.
Definition vm.c:2042
void rb_backref_set(VALUE md)
Updates $~.
Definition vm.c:2048
VALUE rb_range_beg_len(VALUE range, long *begp, long *lenp, long 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:1236
int rb_reg_options(VALUE re)
Queries the options of the passed regular expression.
Definition re.c:4304
VALUE rb_reg_last_match(VALUE md)
This just returns the argument, stringified.
Definition re.c:1952
void rb_match_busy(VALUE md)
Asserts that the given MatchData is "occupied".
Definition re.c:1490
VALUE rb_reg_nth_match(int n, VALUE md)
Queries the nth captured substring.
Definition re.c:1927
VALUE rb_reg_match_post(VALUE md)
The portion of the original string after the given match.
Definition re.c:2009
VALUE rb_reg_nth_defined(int n, VALUE md)
Identical to rb_reg_nth_match(), except it just returns Boolean.
Definition re.c:1910
VALUE rb_reg_match_pre(VALUE md)
The portion of the original string before the given match.
Definition re.c:1976
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:3432
VALUE rb_reg_match_last(VALUE md)
The portion of the original string that captured at the very last.
Definition re.c:2042
VALUE rb_reg_new(const char *src, long len, int opts)
Creates a new Regular expression.
Definition re.c:3484
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:943
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:946
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:3818
VALUE rb_str_subseq(VALUE str, long beg, long len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3171
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
Definition random.c:1791
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1682
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:1979
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
Definition string.c:4167
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:3784
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
Definition string.c:4288
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1785
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:7256
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1701
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:968
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:380
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:1024
int len
Length of the buffer.
Definition io.h:8
long rb_reg_search(VALUE re, VALUE str, long pos, int dir)
Runs the passed regular expression over the passed string.
Definition re.c:1866
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:1637
long rb_reg_adjust_startpos(VALUE re, VALUE str, long pos, int dir)
Tell us if this is a wrong idea, but it seems this function has no usage at all.
Definition re.c:1741
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:1705
VALUE rb_reg_regcomp(VALUE str)
Creates a new instance of rb_cRegexp.
Definition re.c:3506
VALUE rb_reg_quote(VALUE str)
Escapes any characters that would have special meaning in a regular expression.
Definition re.c:4184
int rb_reg_region_copy(struct re_registers *dst, const struct re_registers *src)
Duplicates a match data.
Definition re.c:982
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define ALLOCA_N(type, n)
Definition memory.h:292
#define RB_ALLOCV_N(type, v, n)
Allocates a memory region, possibly on stack.
Definition memory.h:336
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define RB_ALLOCV_END(v)
Polite way to declare that the given array is not used any longer.
Definition memory.h:349
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
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
static struct re_registers * RMATCH_REGS(VALUE match)
Queries the raw re_registers.
Definition rmatch.h:138
#define RREGEXP(obj)
Convenient casting macro.
Definition rregexp.h:37
static VALUE RREGEXP_SRC(VALUE rexp)
Convenient getter function.
Definition rregexp.h:103
#define RREGEXP_PTR(obj)
Convenient accessor macro.
Definition rregexp.h:45
static long RREGEXP_SRC_LEN(VALUE rexp)
Convenient getter function.
Definition rregexp.h:144
static char * RREGEXP_SRC_PTR(VALUE rexp)
Convenient getter function.
Definition rregexp.h:125
#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 StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#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
MEMO.
Definition imemo.h:103
VALUE flags
Per-object flags.
Definition rbasic.h:81
Regular expression execution context.
Definition rmatch.h:96
VALUE regexp
The expression of this match.
Definition rmatch.h:109
VALUE str
The target string that the match was made against.
Definition rmatch.h:104
Ruby's regular expression.
Definition rregexp.h:60
struct RBasic basic
Basic part, including flags and class.
Definition rregexp.h:63
const VALUE src
Source code of this expression.
Definition rregexp.h:74
unsigned long usecnt
Reference count.
Definition rregexp.h:90
struct re_pattern_buffer * ptr
The pattern buffer.
Definition rregexp.h:71
Definition re.c:992
Represents a match.
Definition rmatch.h:71
struct rmatch_offset * char_offset
Capture group offsets, in C array.
Definition rmatch.h:79
int char_offset_num_allocated
Number of rmatch_offset that ::rmatch::char_offset holds.
Definition rmatch.h:82
struct re_registers regs
"Registers" of a match.
Definition rmatch.h:76
Represents the region of a capture group.
Definition rmatch.h:65
long beg
Beginning of a group.
Definition rmatch.h:66
long end
End of a group.
Definition rmatch.h:67
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:433
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