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