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