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